LLVM  10.0.0
MCContext.cpp
Go to the documentation of this file.
1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/MC/MCContext.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/BinaryFormat/ELF.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCCodeView.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFragment.h"
24 #include "llvm/MC/MCLabel.h"
26 #include "llvm/MC/MCSectionCOFF.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCSectionWasm.h"
30 #include "llvm/MC/MCSectionXCOFF.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCSymbolCOFF.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCSymbolMachO.h"
36 #include "llvm/MC/MCSymbolWasm.h"
37 #include "llvm/MC/MCSymbolXCOFF.h"
38 #include "llvm/MC/SectionKind.h"
39 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
47 #include <cassert>
48 #include <cstdlib>
49 #include <tuple>
50 #include <utility>
51 
52 using namespace llvm;
53 
54 static cl::opt<char*>
55 AsSecureLogFileName("as-secure-log-file-name",
56  cl::desc("As secure log file name (initialized from "
57  "AS_SECURE_LOG_FILE env variable)"),
58  cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
59 
61  const MCObjectFileInfo *mofi, const SourceMgr *mgr,
62  MCTargetOptions const *TargetOpts, bool DoAutoReset)
63  : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
64  Symbols(Allocator), UsedNames(Allocator),
65  InlineAsmUsedLabelNames(Allocator),
66  CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
67  AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
68  SecureLogFile = AsSecureLogFileName;
69 
70  if (SrcMgr && SrcMgr->getNumBuffers())
71  MainFileName =
72  SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
73 }
74 
76  if (AutoReset)
77  reset();
78 
79  // NOTE: The symbols are all allocated out of a bump pointer allocator,
80  // we don't need to free them here.
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // Module Lifetime Management
85 //===----------------------------------------------------------------------===//
86 
88  // Call the destructors so the fragments are freed
89  COFFAllocator.DestroyAll();
90  ELFAllocator.DestroyAll();
91  MachOAllocator.DestroyAll();
92  XCOFFAllocator.DestroyAll();
93 
94  MCSubtargetAllocator.DestroyAll();
95  InlineAsmUsedLabelNames.clear();
96  UsedNames.clear();
97  Symbols.clear();
98  Allocator.Reset();
99  Instances.clear();
100  CompilationDir.clear();
101  MainFileName.clear();
102  MCDwarfLineTablesCUMap.clear();
103  SectionsForRanges.clear();
104  MCGenDwarfLabelEntries.clear();
105  DwarfDebugFlags = StringRef();
106  DwarfCompileUnitID = 0;
107  CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
108 
109  CVContext.reset();
110 
111  MachOUniquingMap.clear();
112  ELFUniquingMap.clear();
113  COFFUniquingMap.clear();
114  WasmUniquingMap.clear();
115  XCOFFUniquingMap.clear();
116 
117  NextID.clear();
118  AllowTemporaryLabels = true;
119  DwarfLocSeen = false;
120  GenDwarfForAssembly = false;
121  GenDwarfFileNumber = 0;
122 
123  HadError = false;
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // Symbol Manipulation
128 //===----------------------------------------------------------------------===//
129 
131  SmallString<128> NameSV;
132  StringRef NameRef = Name.toStringRef(NameSV);
133 
134  assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
135 
136  MCSymbol *&Sym = Symbols[NameRef];
137  if (!Sym)
138  Sym = createSymbol(NameRef, false, false);
139 
140  return Sym;
141 }
142 
144  unsigned Idx) {
145  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
146  "$frame_escape_" + Twine(Idx));
147 }
148 
150  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
151  "$parent_frame_offset");
152 }
153 
155  return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
156  FuncName);
157 }
158 
159 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
160  bool IsTemporary) {
161  if (MOFI) {
162  switch (MOFI->getObjectFileType()) {
164  return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
166  return new (Name, *this) MCSymbolELF(Name, IsTemporary);
168  return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
170  return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
172  return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
173  }
174  }
175  return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
176  IsTemporary);
177 }
178 
179 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
180  bool CanBeUnnamed) {
181  if (CanBeUnnamed && !UseNamesOnTempLabels)
182  return createSymbolImpl(nullptr, true);
183 
184  // Determine whether this is a user written assembler temporary or normal
185  // label, if used.
186  bool IsTemporary = CanBeUnnamed;
187  if (AllowTemporaryLabels && !IsTemporary)
188  IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
189 
190  SmallString<128> NewName = Name;
191  bool AddSuffix = AlwaysAddSuffix;
192  unsigned &NextUniqueID = NextID[Name];
193  while (true) {
194  if (AddSuffix) {
195  NewName.resize(Name.size());
196  raw_svector_ostream(NewName) << NextUniqueID++;
197  }
198  auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
199  if (NameEntry.second || !NameEntry.first->second) {
200  // Ok, we found a name.
201  // Mark it as used for a non-section symbol.
202  NameEntry.first->second = true;
203  // Have the MCSymbol object itself refer to the copy of the string that is
204  // embedded in the UsedNames entry.
205  return createSymbolImpl(&*NameEntry.first, IsTemporary);
206  }
207  assert(IsTemporary && "Cannot rename non-temporary symbols");
208  AddSuffix = true;
209  }
210  llvm_unreachable("Infinite loop");
211 }
212 
213 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
214  bool CanBeUnnamed) {
215  SmallString<128> NameSV;
216  raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
217  return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
218 }
219 
221  SmallString<128> NameSV;
222  raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
223  return createSymbol(NameSV, true, false);
224 }
225 
227  return createTempSymbol("tmp", true, CanBeUnnamed);
228 }
229 
230 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
231  MCLabel *&Label = Instances[LocalLabelVal];
232  if (!Label)
233  Label = new (*this) MCLabel(0);
234  return Label->incInstance();
235 }
236 
237 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
238  MCLabel *&Label = Instances[LocalLabelVal];
239  if (!Label)
240  Label = new (*this) MCLabel(0);
241  return Label->getInstance();
242 }
243 
244 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
245  unsigned Instance) {
246  MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
247  if (!Sym)
248  Sym = createTempSymbol(false);
249  return Sym;
250 }
251 
253  unsigned Instance = NextInstance(LocalLabelVal);
254  return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
255 }
256 
258  bool Before) {
259  unsigned Instance = GetInstance(LocalLabelVal);
260  if (!Before)
261  ++Instance;
262  return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
263 }
264 
266  SmallString<128> NameSV;
267  StringRef NameRef = Name.toStringRef(NameSV);
268  return Symbols.lookup(NameRef);
269 }
270 
272  StringRef Sym,
273  uint64_t Val) {
274  auto Symbol = getOrCreateSymbol(Sym);
275  Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this));
276 }
277 
279  InlineAsmUsedLabelNames[Sym->getName()] = Sym;
280 }
281 
282 //===----------------------------------------------------------------------===//
283 // Section Management
284 //===----------------------------------------------------------------------===//
285 
287  unsigned TypeAndAttributes,
288  unsigned Reserved2, SectionKind Kind,
289  const char *BeginSymName) {
290  // We unique sections by their segment/section pair. The returned section
291  // may not have the same flags as the requested section, if so this should be
292  // diagnosed by the client as an error.
293 
294  // Form the name to look up.
296  Name += Segment;
297  Name.push_back(',');
298  Name += Section;
299 
300  // Do the lookup, if we have a hit, return it.
301  MCSectionMachO *&Entry = MachOUniquingMap[Name];
302  if (Entry)
303  return Entry;
304 
305  MCSymbol *Begin = nullptr;
306  if (BeginSymName)
307  Begin = createTempSymbol(BeginSymName, false);
308 
309  // Otherwise, return a new section.
310  return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
311  Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
312 }
313 
315  StringRef GroupName;
316  if (const MCSymbol *Group = Section->getGroup())
317  GroupName = Group->getName();
318 
319  unsigned UniqueID = Section->getUniqueID();
320  ELFUniquingMap.erase(
321  ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
322  auto I = ELFUniquingMap.insert(std::make_pair(
323  ELFSectionKey{Name, GroupName, UniqueID},
324  Section))
325  .first;
326  StringRef CachedName = I->first.SectionName;
327  const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
328 }
329 
330 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
331  unsigned Flags, SectionKind K,
332  unsigned EntrySize,
333  const MCSymbolELF *Group,
334  unsigned UniqueID,
335  const MCSymbolELF *Associated) {
336  MCSymbolELF *R;
337  MCSymbol *&Sym = Symbols[Section];
338  // A section symbol can not redefine regular symbols. There may be multiple
339  // sections with the same name, in which case the first such section wins.
340  if (Sym && Sym->isDefined() &&
341  (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
342  reportError(SMLoc(), "invalid symbol redefinition");
343  if (Sym && Sym->isUndefined()) {
344  R = cast<MCSymbolELF>(Sym);
345  } else {
346  auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
347  R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
348  if (!Sym)
349  Sym = R;
350  }
353 
354  auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
355  Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated);
356 
357  auto *F = new MCDataFragment();
358  Ret->getFragmentList().insert(Ret->begin(), F);
359  F->setParent(Ret);
360  R->setFragment(F);
361 
362  return Ret;
363 }
364 
366  unsigned Flags, unsigned EntrySize,
367  const MCSymbolELF *Group,
368  const MCSectionELF *RelInfoSection) {
370  bool Inserted;
371  std::tie(I, Inserted) =
372  RelSecNames.insert(std::make_pair(Name.str(), true));
373 
374  return createELFSectionImpl(
375  I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
376  true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
377 }
378 
380  const Twine &Suffix, unsigned Type,
381  unsigned Flags,
382  unsigned EntrySize) {
383  return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
384 }
385 
386 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
387  unsigned Flags, unsigned EntrySize,
388  const Twine &Group, unsigned UniqueID,
389  const MCSymbolELF *Associated) {
390  MCSymbolELF *GroupSym = nullptr;
391  if (!Group.isTriviallyEmpty() && !Group.str().empty())
392  GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
393 
394  return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
395  Associated);
396 }
397 
398 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
399  unsigned Flags, unsigned EntrySize,
400  const MCSymbolELF *GroupSym,
401  unsigned UniqueID,
402  const MCSymbolELF *Associated) {
403  StringRef Group = "";
404  if (GroupSym)
405  Group = GroupSym->getName();
406  // Do the lookup, if we have a hit, return it.
407  auto IterBool = ELFUniquingMap.insert(
408  std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr));
409  auto &Entry = *IterBool.first;
410  if (!IterBool.second)
411  return Entry.second;
412 
413  StringRef CachedName = Entry.first.SectionName;
414 
416  if (Flags & ELF::SHF_ARM_PURECODE)
418  else if (Flags & ELF::SHF_EXECINSTR)
419  Kind = SectionKind::getText();
420  else
421  Kind = SectionKind::getReadOnly();
422 
423  MCSectionELF *Result = createELFSectionImpl(
424  CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated);
425  Entry.second = Result;
426  return Result;
427 }
428 
430  return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
431  SectionKind::getReadOnly(), 4, Group, ~0,
432  nullptr);
433 }
434 
436  unsigned Characteristics,
438  StringRef COMDATSymName, int Selection,
439  unsigned UniqueID,
440  const char *BeginSymName) {
441  MCSymbol *COMDATSymbol = nullptr;
442  if (!COMDATSymName.empty()) {
443  COMDATSymbol = getOrCreateSymbol(COMDATSymName);
444  COMDATSymName = COMDATSymbol->getName();
445  }
446 
447 
448  // Do the lookup, if we have a hit, return it.
449  COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
450  auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
451  auto Iter = IterBool.first;
452  if (!IterBool.second)
453  return Iter->second;
454 
455  MCSymbol *Begin = nullptr;
456  if (BeginSymName)
457  Begin = createTempSymbol(BeginSymName, false);
458 
459  StringRef CachedName = Iter->first.SectionName;
460  MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
461  CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
462 
463  Iter->second = Result;
464  return Result;
465 }
466 
468  unsigned Characteristics,
470  const char *BeginSymName) {
471  return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
472  BeginSymName);
473 }
474 
476  const MCSymbol *KeySym,
477  unsigned UniqueID) {
478  // Return the normal section if we don't have to be associative or unique.
479  if (!KeySym && UniqueID == GenericSectionID)
480  return Sec;
481 
482  // If we have a key symbol, make an associative section with the same name and
483  // kind as the normal section.
484  unsigned Characteristics = Sec->getCharacteristics();
485  if (KeySym) {
486  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
488  Sec->getKind(), KeySym->getName(),
490  }
491 
492  return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
493  "", 0, UniqueID);
494 }
495 
497  const Twine &Group, unsigned UniqueID,
498  const char *BeginSymName) {
499  MCSymbolWasm *GroupSym = nullptr;
500  if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
501  GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
502  GroupSym->setComdat(true);
503  }
504 
505  return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
506 }
507 
509  const MCSymbolWasm *GroupSym,
510  unsigned UniqueID,
511  const char *BeginSymName) {
512  StringRef Group = "";
513  if (GroupSym)
514  Group = GroupSym->getName();
515  // Do the lookup, if we have a hit, return it.
516  auto IterBool = WasmUniquingMap.insert(
517  std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
518  auto &Entry = *IterBool.first;
519  if (!IterBool.second)
520  return Entry.second;
521 
522  StringRef CachedName = Entry.first.SectionName;
523 
524  MCSymbol *Begin = createSymbol(CachedName, false, false);
525  cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
526 
527  MCSectionWasm *Result = new (WasmAllocator.Allocate())
528  MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
529  Entry.second = Result;
530 
531  auto *F = new MCDataFragment();
532  Result->getFragmentList().insert(Result->begin(), F);
533  F->setParent(Result);
534  Begin->setFragment(F);
535 
536  return Result;
537 }
538 
541  XCOFF::SymbolType Type,
544  const char *BeginSymName) {
545  // Do the lookup. If we have a hit, return it.
546  auto IterBool = XCOFFUniquingMap.insert(
547  std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr));
548  auto &Entry = *IterBool.first;
549  if (!IterBool.second)
550  return Entry.second;
551 
552  // Otherwise, return a new section.
553  StringRef CachedName = Entry.first.SectionName;
554  MCSymbol *QualName = getOrCreateSymbol(
555  CachedName + "[" + XCOFF::getMappingClassString(SMC) + "]");
556 
557  MCSymbol *Begin = nullptr;
558  if (BeginSymName)
559  Begin = createTempSymbol(BeginSymName, false);
560 
561  MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
562  CachedName, SMC, Type, SC, Kind, cast<MCSymbolXCOFF>(QualName), Begin);
563  Entry.second = Result;
564 
565  auto *F = new MCDataFragment();
566  Result->getFragmentList().insert(Result->begin(), F);
567  F->setParent(Result);
568 
569  if (Begin)
570  Begin->setFragment(F);
571 
572  return Result;
573 }
574 
576  return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
577 }
578 
579 void MCContext::addDebugPrefixMapEntry(const std::string &From,
580  const std::string &To) {
581  DebugPrefixMap.insert(std::make_pair(From, To));
582 }
583 
585  const auto &DebugPrefixMap = this->DebugPrefixMap;
586  const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
587  for (const auto &Entry : DebugPrefixMap)
588  if (StringRef(Path).startswith(Entry.first)) {
589  std::string RemappedPath =
590  (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
591  Path.swap(RemappedPath);
592  }
593  };
594 
595  // Remap compilation directory.
596  std::string CompDir = CompilationDir.str();
597  RemapDebugPath(CompDir);
598  CompilationDir = CompDir;
599 
600  // Remap MCDwarfDirs in all compilation units.
601  for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
602  for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
603  RemapDebugPath(Dir);
604 }
605 
606 //===----------------------------------------------------------------------===//
607 // Dwarf Management
608 //===----------------------------------------------------------------------===//
609 
611  // MCDwarf needs the root file as well as the compilation directory.
612  // If we find a '.file 0' directive that will supersede these values.
614  if (getDwarfVersion() >= 5) {
615  MD5 Hash;
616  MD5::MD5Result Sum;
617  Hash.update(Buffer);
618  Hash.final(Sum);
619  Cksum = Sum;
620  }
621  // Canonicalize the root filename. It cannot be empty, and should not
622  // repeat the compilation dir.
623  // The MCContext ctor initializes MainFileName to the name associated with
624  // the SrcMgr's main file ID, which might be the same as InputFileName (and
625  // possibly include directory components).
626  // Or, MainFileName might have been overridden by a -main-file-name option,
627  // which is supposed to be just a base filename with no directory component.
628  // So, if the InputFileName and MainFileName are not equal, assume
629  // MainFileName is a substitute basename and replace the last component.
630  SmallString<1024> FileNameBuf = InputFileName;
631  if (FileNameBuf.empty() || FileNameBuf == "-")
632  FileNameBuf = "<stdin>";
633  if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
636  }
637  StringRef FileName = FileNameBuf;
638  if (FileName.consume_front(getCompilationDir()))
639  if (llvm::sys::path::is_separator(FileName.front()))
640  FileName = FileName.drop_front();
641  assert(!FileName.empty());
643  /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
644 }
645 
646 /// getDwarfFile - takes a file name and number to place in the dwarf file and
647 /// directory tables. If the file number has already been allocated it is an
648 /// error and zero is returned and the client reports the error, else the
649 /// allocated file number is returned. The file numbers may be in any order.
651  StringRef FileName,
652  unsigned FileNumber,
653  Optional<MD5::MD5Result> Checksum,
655  unsigned CUID) {
656  MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
657  return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
658  FileNumber);
659 }
660 
661 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
662 /// currently is assigned and false otherwise.
663 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
664  const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
665  if (FileNumber == 0)
666  return getDwarfVersion() >= 5;
667  if (FileNumber >= LineTable.getMCDwarfFiles().size())
668  return false;
669 
670  return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
671 }
672 
673 /// Remove empty sections from SectionsForRanges, to avoid generating
674 /// useless debug info for them.
676  SectionsForRanges.remove_if(
677  [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
678 }
679 
681  if (!CVContext.get())
682  CVContext.reset(new CodeViewContext);
683  return *CVContext.get();
684 }
685 
686 //===----------------------------------------------------------------------===//
687 // Error Reporting
688 //===----------------------------------------------------------------------===//
689 
690 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
691  HadError = true;
692 
693  // If we have a source manager use it. Otherwise, try using the inline source
694  // manager.
695  // If that fails, use the generic report_fatal_error().
696  if (SrcMgr)
697  SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
698  else if (InlineSrcMgr)
699  InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
700  else
701  report_fatal_error(Msg, false);
702 }
703 
704 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
705  if (TargetOptions && TargetOptions->MCNoWarn)
706  return;
707  if (TargetOptions && TargetOptions->MCFatalWarnings)
708  reportError(Loc, Msg);
709  else {
710  // If we have a source manager use it. Otherwise, try using the inline
711  // source manager.
712  if (SrcMgr)
713  SrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
714  else if (InlineSrcMgr)
715  InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
716  }
717 }
718 
719 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
720  reportError(Loc, Msg);
721 
722  // If we reached here, we are failing ungracefully. Run the interrupt handlers
723  // to make sure any special cleanups get done, in particular that we remove
724  // files registered with RemoveFileOnSignal.
726  exit(1);
727 }
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:39
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:616
MCSymbol * getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before)
Create and return a directional local symbol for numbered label (used for "1b" or 1f" references)...
Definition: MCContext.cpp:257
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:474
SectionKind getKind() const
Definition: MCSection.h:111
This represents a section on a Mach-O system (used by Mac OS X).
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:239
MCSymbol * lookupSymbol(const Twine &Name) const
Get the symbol for Name, or null.
Definition: MCContext.cpp:265
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:158
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
unsigned getNumBuffers() const
Definition: SourceMgr.h:137
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:277
StringRef getLinkerPrivateGlobalPrefix() const
Definition: MCAsmInfo.h:522
void push_back(const T &Elt)
Definition: SmallVector.h:211
MCSymbol * getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen...
Definition: MCContext.cpp:143
void reset()
reset - return object to right after construction state to prepare to process a new module ...
Definition: MCContext.cpp:87
SourceMgr SrcMgr
Definition: Error.cpp:23
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition: Twine.h:400
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:455
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:671
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K)
Definition: MCContext.h:487
MCSymbol * createDirectionalLocalSymbol(unsigned LocalLabelVal)
Create the definition of a directional local symbol for numbered label (used for "1:" definitions)...
Definition: MCContext.cpp:252
MCSymbol * getOrCreateParentFrameOffsetSymbol(StringRef FuncName)
Definition: MCContext.cpp:149
void setGenDwarfRootFile(StringRef FileName, StringRef Buffer)
Specifies information about the "root file" for assembler clients (e.g., llvm-mc).
Definition: MCContext.cpp:610
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:543
F(f)
uint16_t getDwarfVersion() const
Definition: MCContext.h:660
StringRef getPrivateGlobalPrefix() const
Definition: MCAsmInfo.h:515
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:435
MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=GenericSectionID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym...
Definition: MCContext.cpp:475
This represents a section on Windows.
Definition: MCSectionCOFF.h:26
void setComdat(bool isComdat)
Definition: MCSymbolWasm.h:72
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
Definition: SourceMgr.cpp:242
#define DWARF2_FLAG_IS_STMT
Definition: MCDwarf.h:82
MCSymbol * createLinkerPrivateTempSymbol()
Create and return a new linker temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:220
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
Definition: Allocator.h:195
void renameELFSection(MCSectionELF *Section, StringRef Name)
Definition: MCContext.cpp:314
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:642
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition: MD5.cpp:189
void finalizeDwarfSections(MCStreamer &MCOS)
Remove empty sections from SectionsForRanges, to avoid generating useless debug info for them...
Definition: MCContext.cpp:675
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
Definition: MCSymbol.h:245
void setFragment(MCFragment *F) const
Mark the symbol as defined in the fragment F.
Definition: MCSymbol.h:266
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
MCDwarfLineTable & getMCDwarfLineTable(unsigned CUID)
Definition: MCContext.h:558
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value)
Emit an assignment of Value to Symbol.
Definition: MCStreamer.cpp:970
static cl::opt< char * > AsSecureLogFileName("as-secure-log-file-name", cl::desc("As secure log file name (initialized from " "AS_SECURE_LOG_FILE env variable)"), cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden)
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
Expected< unsigned > getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, Optional< MD5::MD5Result > Checksum, Optional< StringRef > Source, unsigned CUID)
Creates an entry in the dwarf file and directory tables.
Definition: MCContext.cpp:650
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:132
StorageClass
Definition: XCOFF.h:77
MCSectionXCOFF * getXCOFFSection(StringRef Section, XCOFF::StorageMappingClass MappingClass, XCOFF::SymbolType CSectType, XCOFF::StorageClass StorageClass, SectionKind K, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:539
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:286
void RemapDebugPaths()
Definition: MCContext.cpp:584
Instances of this class represent the information from a dwarf .loc directive.
Definition: MCDwarf.h:70
unsigned getCharacteristics() const
Definition: MCSectionCOFF.h:70
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false)
Definition: MCExpr.cpp:169
LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:719
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI, const MCObjectFileInfo *MOFI, const SourceMgr *Mgr=nullptr, MCTargetOptions const *TargetOpts=nullptr, bool DoAutoReset=true)
Definition: MCContext.cpp:60
unsigned getMainFileID() const
Definition: SourceMgr.h:141
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
unsigned getUniqueID() const
Definition: MCSectionELF.h:84
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
const SmallVectorImpl< MCDwarfFile > & getMCDwarfFiles() const
Definition: MCDwarf.h:362
Streaming machine code generation interface.
Definition: MCStreamer.h:197
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:226
unsigned const MachineRegisterInfo * MRI
const MCSymbolELF * getGroup() const
Definition: MCSectionELF.h:75
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
StorageMappingClass
Storage Mapping Class definitions.
Definition: XCOFF.h:29
This represents a section on wasm.
Definition: MCSectionWasm.h:27
void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
virtual bool mayHaveInstructions(MCSection &Sec) const
Definition: MCStreamer.h:1032
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:690
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
Definition: MCContext.cpp:379
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: StringMap.h:369
Environment getObjectFileType() const
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
StringRef getMappingClassString(XCOFF::StorageMappingClass SMC)
Definition: XCOFF.cpp:13
StringRef getSectionName() const
Definition: MCSectionCOFF.h:69
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID=0)
isValidDwarfFileNumber - takes a dwarf file number and returns true if it currently is assigned and f...
Definition: MCContext.cpp:663
void setType(unsigned Type) const
Definition: MCSymbolELF.cpp:92
StringRef getCompilationDir() const
Get the compilation directory for DW_AT_comp_dir The compilation directory should be set with setComp...
Definition: MCContext.h:527
MCSectionELF * createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *RelInfoSection)
Definition: MCContext.cpp:365
void registerInlineAsmLabel(MCSymbol *Sym)
registerInlineAsmLabel - Records that the name is a label referenced in inline assembly.
Definition: MCContext.cpp:278
unsigned incInstance()
Increment the current instance of this Directional Local Label.
Definition: MCLabel.h:40
Basic Register Allocator
BlockVerifier::State From
MCSymbol * getOrCreateLSDASymbol(StringRef FuncName)
Definition: MCContext.cpp:154
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:250
void setBinding(unsigned Binding) const
Definition: MCSymbolELF.cpp:41
CHAIN = SC CHAIN, Imm128 - System call.
MCSymbol * getBeginSymbol()
Definition: MCSection.h:115
void reportWarning(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:704
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:393
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:242
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:241
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:260
void setSymbolValue(MCStreamer &Streamer, StringRef Sym, uint64_t Val)
Set value for a symbol.
Definition: MCContext.cpp:271
iterator insert(iterator where, pointer New)
Definition: ilist.h:226
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:130
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
unsigned getInstance() const
Get the current instance of this Directional Local Label.
Definition: MCLabel.h:37
void addDebugPrefixMapEntry(const std::string &From, const std::string &To)
Add an entry to the debug prefix map.
Definition: MCContext.cpp:579
#define I(x, y, z)
Definition: MD5.cpp:58
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:325
Generic base class for all target subtargets.
Definition: MD5.h:41
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
const std::string & getMainFileName() const
Get the main file name for use in error messages and debug info.
Definition: MCContext.h:541
MCSectionELF * createELFGroupSection(const MCSymbolELF *Group)
Definition: MCContext.cpp:429
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:196
CodeViewContext & getCVContext()
Definition: MCContext.cpp:680
Fragment for data and encoded instructions.
Definition: MCFragment.h:229
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:407
Instances of this class represent a label name in the MC file, and MCLabel are created and uniqued by...
Definition: MCLabel.h:23
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM_NODISCARD char front() const
front - Get the first character in the string.
Definition: StringRef.h:155
void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir, StringRef Filename, Optional< MD5::MD5Result > Checksum, Optional< StringRef > Source)
Specifies the "root" file and directory of the compilation unit.
Definition: MCContext.h:584
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:424
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
Expected< unsigned > tryGetFile(StringRef &Directory, StringRef &FileName, Optional< MD5::MD5Result > Checksum, Optional< StringRef > Source, uint16_t DwarfVersion, unsigned FileNumber=0)
Definition: MCDwarf.cpp:537
Represents a location in source code.
Definition: SMLoc.h:23
MCSection::FragmentListType & getFragmentList()
Definition: MCSection.h:152
static SectionKind getReadOnly()
Definition: SectionKind.h:181
StringRef getSectionName() const
Definition: MCSectionELF.h:70
iterator begin()
Definition: MCSection.h:165
static SectionKind getExecuteOnly()
Definition: SectionKind.h:180
static SectionKind getText()
Definition: SectionKind.h:179
void resize(size_type N)
Definition: SmallVector.h:344
MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
Definition: MCContext.cpp:575
Holds state from .cv_file and .cv_loc directives for later emission.
Definition: MCCodeView.h:137