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