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/BinaryFormat/XCOFF.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"
25 #include "llvm/MC/MCObjectFileInfo.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"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/raw_ostream.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 
60 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
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 = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
72                                    ->getBufferIdentifier());
73 }
74 
75 MCContext::~MCContext() {
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 
87 void MCContext::reset() {
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   ELFEntrySizeMap.clear();
118   ELFSeenGenericMergeableSections.clear();
119 
120   NextID.clear();
121   AllowTemporaryLabels = true;
122   DwarfLocSeen = false;
123   GenDwarfForAssembly = false;
124   GenDwarfFileNumber = 0;
125 
126   HadError = false;
127 }
128 
129 //===----------------------------------------------------------------------===//
130 // Symbol Manipulation
131 //===----------------------------------------------------------------------===//
132 
133 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
134   SmallString<128> NameSV;
135   StringRef NameRef = Name.toStringRef(NameSV);
136 
137   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
138 
139   MCSymbol *&Sym = Symbols[NameRef];
140   if (!Sym)
141     Sym = createSymbol(NameRef, false, false);
142 
143   return Sym;
144 }
145 
146 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
147                                                  unsigned Idx) {
148   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
149                            "$frame_escape_" + Twine(Idx));
150 }
151 
152 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
153   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
154                            "$parent_frame_offset");
155 }
156 
157 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
158   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
159                            FuncName);
160 }
161 
162 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
163                                       bool IsTemporary) {
164   static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
165                 "MCSymbol classes must be trivially destructible");
166   static_assert(std::is_trivially_destructible<MCSymbolELF>(),
167                 "MCSymbol classes must be trivially destructible");
168   static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
169                 "MCSymbol classes must be trivially destructible");
170   static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
171                 "MCSymbol classes must be trivially destructible");
172   static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
173                 "MCSymbol classes must be trivially destructible");
174   if (MOFI) {
175     switch (MOFI->getObjectFileType()) {
176     case MCObjectFileInfo::IsCOFF:
177       return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
178     case MCObjectFileInfo::IsELF:
179       return new (Name, *this) MCSymbolELF(Name, IsTemporary);
180     case MCObjectFileInfo::IsMachO:
181       return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
182     case MCObjectFileInfo::IsWasm:
183       return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
184     case MCObjectFileInfo::IsXCOFF:
185       return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
186     }
187   }
188   return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
189                                     IsTemporary);
190 }
191 
192 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
193                                   bool CanBeUnnamed) {
194   if (CanBeUnnamed && !UseNamesOnTempLabels)
195     return createSymbolImpl(nullptr, true);
196 
197   // Determine whether this is a user written assembler temporary or normal
198   // label, if used.
199   bool IsTemporary = CanBeUnnamed;
200   if (AllowTemporaryLabels && !IsTemporary)
201     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
202 
203   SmallString<128> NewName = Name;
204   bool AddSuffix = AlwaysAddSuffix;
205   unsigned &NextUniqueID = NextID[Name];
206   while (true) {
207     if (AddSuffix) {
208       NewName.resize(Name.size());
209       raw_svector_ostream(NewName) << NextUniqueID++;
210     }
211     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
212     if (NameEntry.second || !NameEntry.first->second) {
213       // Ok, we found a name.
214       // Mark it as used for a non-section symbol.
215       NameEntry.first->second = true;
216       // Have the MCSymbol object itself refer to the copy of the string that is
217       // embedded in the UsedNames entry.
218       return createSymbolImpl(&*NameEntry.first, IsTemporary);
219     }
220     assert(IsTemporary && "Cannot rename non-temporary symbols");
221     AddSuffix = true;
222   }
223   llvm_unreachable("Infinite loop");
224 }
225 
226 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
227                                       bool CanBeUnnamed) {
228   SmallString<128> NameSV;
229   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
230   return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
231 }
232 
233 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
234   SmallString<128> NameSV;
235   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
236   return createSymbol(NameSV, true, false);
237 }
238 
239 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
240   return createTempSymbol("tmp", true, CanBeUnnamed);
241 }
242 
243 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
244   MCLabel *&Label = Instances[LocalLabelVal];
245   if (!Label)
246     Label = new (*this) MCLabel(0);
247   return Label->incInstance();
248 }
249 
250 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
251   MCLabel *&Label = Instances[LocalLabelVal];
252   if (!Label)
253     Label = new (*this) MCLabel(0);
254   return Label->getInstance();
255 }
256 
257 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
258                                                        unsigned Instance) {
259   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
260   if (!Sym)
261     Sym = createTempSymbol(false);
262   return Sym;
263 }
264 
265 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
266   unsigned Instance = NextInstance(LocalLabelVal);
267   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
268 }
269 
270 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
271                                                bool Before) {
272   unsigned Instance = GetInstance(LocalLabelVal);
273   if (!Before)
274     ++Instance;
275   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
276 }
277 
278 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
279   SmallString<128> NameSV;
280   StringRef NameRef = Name.toStringRef(NameSV);
281   return Symbols.lookup(NameRef);
282 }
283 
284 void MCContext::setSymbolValue(MCStreamer &Streamer,
285                               StringRef Sym,
286                               uint64_t Val) {
287   auto Symbol = getOrCreateSymbol(Sym);
288   Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
289 }
290 
291 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
292   InlineAsmUsedLabelNames[Sym->getName()] = Sym;
293 }
294 
295 //===----------------------------------------------------------------------===//
296 // Section Management
297 //===----------------------------------------------------------------------===//
298 
299 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
300                                            unsigned TypeAndAttributes,
301                                            unsigned Reserved2, SectionKind Kind,
302                                            const char *BeginSymName) {
303   // We unique sections by their segment/section pair.  The returned section
304   // may not have the same flags as the requested section, if so this should be
305   // diagnosed by the client as an error.
306 
307   // Form the name to look up.
308   assert(Section.size() <= 16 && "section name is too long");
309   assert(!memchr(Section.data(), '\0', Section.size()) &&
310          "section name cannot contain NUL");
311 
312   // Do the lookup, if we have a hit, return it.
313   auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
314   if (!R.second)
315     return R.first->second;
316 
317   MCSymbol *Begin = nullptr;
318   if (BeginSymName)
319     Begin = createTempSymbol(BeginSymName, false);
320 
321   // Otherwise, return a new section.
322   StringRef Name = R.first->first();
323   R.first->second = new (MachOAllocator.Allocate())
324       MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
325                      TypeAndAttributes, Reserved2, Kind, Begin);
326   return R.first->second;
327 }
328 
329 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
330   StringRef GroupName;
331   if (const MCSymbol *Group = Section->getGroup())
332     GroupName = Group->getName();
333 
334   // This function is only used by .debug*, which should not have the
335   // SHF_LINK_ORDER flag.
336   unsigned UniqueID = Section->getUniqueID();
337   ELFUniquingMap.erase(
338       ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
339   auto I = ELFUniquingMap
340                .insert(std::make_pair(
341                    ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
342                .first;
343   StringRef CachedName = I->first.SectionName;
344   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
345 }
346 
347 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
348                                               unsigned Flags, SectionKind K,
349                                               unsigned EntrySize,
350                                               const MCSymbolELF *Group,
351                                               unsigned UniqueID,
352                                               const MCSymbolELF *LinkedToSym) {
353   MCSymbolELF *R;
354   MCSymbol *&Sym = Symbols[Section];
355   // A section symbol can not redefine regular symbols. There may be multiple
356   // sections with the same name, in which case the first such section wins.
357   if (Sym && Sym->isDefined() &&
358       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
359     reportError(SMLoc(), "invalid symbol redefinition");
360   if (Sym && Sym->isUndefined()) {
361     R = cast<MCSymbolELF>(Sym);
362   } else {
363     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
364     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
365     if (!Sym)
366       Sym = R;
367   }
368   R->setBinding(ELF::STB_LOCAL);
369   R->setType(ELF::STT_SECTION);
370 
371   auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
372       Section, Type, Flags, K, EntrySize, Group, UniqueID, R, LinkedToSym);
373 
374   auto *F = new MCDataFragment();
375   Ret->getFragmentList().insert(Ret->begin(), F);
376   F->setParent(Ret);
377   R->setFragment(F);
378 
379   return Ret;
380 }
381 
382 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
383                                              unsigned Flags, unsigned EntrySize,
384                                              const MCSymbolELF *Group,
385                                              const MCSectionELF *RelInfoSection) {
386   StringMap<bool>::iterator I;
387   bool Inserted;
388   std::tie(I, Inserted) =
389       RelSecNames.insert(std::make_pair(Name.str(), true));
390 
391   return createELFSectionImpl(
392       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
393       true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
394 }
395 
396 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
397                                             const Twine &Suffix, unsigned Type,
398                                             unsigned Flags,
399                                             unsigned EntrySize) {
400   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
401 }
402 
403 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
404                                        unsigned Flags, unsigned EntrySize,
405                                        const Twine &Group, unsigned UniqueID,
406                                        const MCSymbolELF *LinkedToSym) {
407   MCSymbolELF *GroupSym = nullptr;
408   if (!Group.isTriviallyEmpty() && !Group.str().empty())
409     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
410 
411   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
412                        LinkedToSym);
413 }
414 
415 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
416                                        unsigned Flags, unsigned EntrySize,
417                                        const MCSymbolELF *GroupSym,
418                                        unsigned UniqueID,
419                                        const MCSymbolELF *LinkedToSym) {
420   StringRef Group = "";
421   if (GroupSym)
422     Group = GroupSym->getName();
423   assert(!(LinkedToSym && LinkedToSym->getName().empty()));
424   // Do the lookup, if we have a hit, return it.
425   auto IterBool = ELFUniquingMap.insert(std::make_pair(
426       ELFSectionKey{Section.str(), Group,
427                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
428       nullptr));
429   auto &Entry = *IterBool.first;
430   if (!IterBool.second)
431     return Entry.second;
432 
433   StringRef CachedName = Entry.first.SectionName;
434 
435   SectionKind Kind;
436   if (Flags & ELF::SHF_ARM_PURECODE)
437     Kind = SectionKind::getExecuteOnly();
438   else if (Flags & ELF::SHF_EXECINSTR)
439     Kind = SectionKind::getText();
440   else
441     Kind = SectionKind::getReadOnly();
442 
443   MCSectionELF *Result =
444       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
445                            UniqueID, LinkedToSym);
446   Entry.second = Result;
447 
448   recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
449                                 Result->getUniqueID(), Result->getEntrySize());
450 
451   return Result;
452 }
453 
454 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
455   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
456                               SectionKind::getReadOnly(), 4, Group,
457                               MCSection::NonUniqueID, nullptr);
458 }
459 
460 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
461                                               unsigned Flags, unsigned UniqueID,
462                                               unsigned EntrySize) {
463   bool IsMergeable = Flags & ELF::SHF_MERGE;
464   if (IsMergeable && (UniqueID == GenericSectionID))
465     ELFSeenGenericMergeableSections.insert(SectionName);
466 
467   // For mergeable sections or non-mergeable sections with a generic mergeable
468   // section name we enter their Unique ID into the ELFEntrySizeMap so that
469   // compatible globals can be assigned to the same section.
470   if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
471     ELFEntrySizeMap.insert(std::make_pair(
472         ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
473   }
474 }
475 
476 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
477   return SectionName.startswith(".rodata.str") ||
478          SectionName.startswith(".rodata.cst");
479 }
480 
481 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
482   return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
483          ELFSeenGenericMergeableSections.count(SectionName);
484 }
485 
486 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
487                                                        unsigned Flags,
488                                                        unsigned EntrySize) {
489   auto I = ELFEntrySizeMap.find(
490       MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
491   return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
492 }
493 
494 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
495                                          unsigned Characteristics,
496                                          SectionKind Kind,
497                                          StringRef COMDATSymName, int Selection,
498                                          unsigned UniqueID,
499                                          const char *BeginSymName) {
500   MCSymbol *COMDATSymbol = nullptr;
501   if (!COMDATSymName.empty()) {
502     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
503     COMDATSymName = COMDATSymbol->getName();
504   }
505 
506 
507   // Do the lookup, if we have a hit, return it.
508   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
509   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
510   auto Iter = IterBool.first;
511   if (!IterBool.second)
512     return Iter->second;
513 
514   MCSymbol *Begin = nullptr;
515   if (BeginSymName)
516     Begin = createTempSymbol(BeginSymName, false);
517 
518   StringRef CachedName = Iter->first.SectionName;
519   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
520       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
521 
522   Iter->second = Result;
523   return Result;
524 }
525 
526 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
527                                          unsigned Characteristics,
528                                          SectionKind Kind,
529                                          const char *BeginSymName) {
530   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
531                         BeginSymName);
532 }
533 
534 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
535                                                     const MCSymbol *KeySym,
536                                                     unsigned UniqueID) {
537   // Return the normal section if we don't have to be associative or unique.
538   if (!KeySym && UniqueID == GenericSectionID)
539     return Sec;
540 
541   // If we have a key symbol, make an associative section with the same name and
542   // kind as the normal section.
543   unsigned Characteristics = Sec->getCharacteristics();
544   if (KeySym) {
545     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
546     return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
547                           KeySym->getName(),
548                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
549   }
550 
551   return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
552                         UniqueID);
553 }
554 
555 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
556                                          const Twine &Group, unsigned UniqueID,
557                                          const char *BeginSymName) {
558   MCSymbolWasm *GroupSym = nullptr;
559   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
560     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
561     GroupSym->setComdat(true);
562   }
563 
564   return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
565 }
566 
567 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
568                                          const MCSymbolWasm *GroupSym,
569                                          unsigned UniqueID,
570                                          const char *BeginSymName) {
571   StringRef Group = "";
572   if (GroupSym)
573     Group = GroupSym->getName();
574   // Do the lookup, if we have a hit, return it.
575   auto IterBool = WasmUniquingMap.insert(
576       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
577   auto &Entry = *IterBool.first;
578   if (!IterBool.second)
579     return Entry.second;
580 
581   StringRef CachedName = Entry.first.SectionName;
582 
583   MCSymbol *Begin = createSymbol(CachedName, false, false);
584   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
585 
586   MCSectionWasm *Result = new (WasmAllocator.Allocate())
587       MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
588   Entry.second = Result;
589 
590   auto *F = new MCDataFragment();
591   Result->getFragmentList().insert(Result->begin(), F);
592   F->setParent(Result);
593   Begin->setFragment(F);
594 
595   return Result;
596 }
597 
598 MCSectionXCOFF *MCContext::getXCOFFSection(StringRef Section,
599                                            XCOFF::StorageMappingClass SMC,
600                                            XCOFF::SymbolType Type,
601                                            XCOFF::StorageClass SC,
602                                            SectionKind Kind,
603                                            const char *BeginSymName) {
604   // Do the lookup. If we have a hit, return it.
605   auto IterBool = XCOFFUniquingMap.insert(
606       std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr));
607   auto &Entry = *IterBool.first;
608   if (!IterBool.second)
609     return Entry.second;
610 
611   // Otherwise, return a new section.
612   StringRef CachedName = Entry.first.SectionName;
613   MCSymbol *QualName = getOrCreateSymbol(
614       CachedName + "[" + XCOFF::getMappingClassString(SMC) + "]");
615 
616   MCSymbol *Begin = nullptr;
617   if (BeginSymName)
618     Begin = createTempSymbol(BeginSymName, false);
619 
620   MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
621       CachedName, SMC, Type, SC, Kind, cast<MCSymbolXCOFF>(QualName), Begin);
622   Entry.second = Result;
623 
624   auto *F = new MCDataFragment();
625   Result->getFragmentList().insert(Result->begin(), F);
626   F->setParent(Result);
627 
628   if (Begin)
629     Begin->setFragment(F);
630 
631   return Result;
632 }
633 
634 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
635   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
636 }
637 
638 void MCContext::addDebugPrefixMapEntry(const std::string &From,
639                                        const std::string &To) {
640   DebugPrefixMap.insert(std::make_pair(From, To));
641 }
642 
643 void MCContext::RemapDebugPaths() {
644   const auto &DebugPrefixMap = this->DebugPrefixMap;
645   const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
646     for (const auto &Entry : DebugPrefixMap)
647       if (StringRef(Path).startswith(Entry.first)) {
648         std::string RemappedPath =
649             (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
650         Path.swap(RemappedPath);
651       }
652   };
653 
654   // Remap compilation directory.
655   std::string CompDir = std::string(CompilationDir.str());
656   RemapDebugPath(CompDir);
657   CompilationDir = CompDir;
658 
659   // Remap MCDwarfDirs in all compilation units.
660   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
661     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
662       RemapDebugPath(Dir);
663 }
664 
665 //===----------------------------------------------------------------------===//
666 // Dwarf Management
667 //===----------------------------------------------------------------------===//
668 
669 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
670   // MCDwarf needs the root file as well as the compilation directory.
671   // If we find a '.file 0' directive that will supersede these values.
672   Optional<MD5::MD5Result> Cksum;
673   if (getDwarfVersion() >= 5) {
674     MD5 Hash;
675     MD5::MD5Result Sum;
676     Hash.update(Buffer);
677     Hash.final(Sum);
678     Cksum = Sum;
679   }
680   // Canonicalize the root filename. It cannot be empty, and should not
681   // repeat the compilation dir.
682   // The MCContext ctor initializes MainFileName to the name associated with
683   // the SrcMgr's main file ID, which might be the same as InputFileName (and
684   // possibly include directory components).
685   // Or, MainFileName might have been overridden by a -main-file-name option,
686   // which is supposed to be just a base filename with no directory component.
687   // So, if the InputFileName and MainFileName are not equal, assume
688   // MainFileName is a substitute basename and replace the last component.
689   SmallString<1024> FileNameBuf = InputFileName;
690   if (FileNameBuf.empty() || FileNameBuf == "-")
691     FileNameBuf = "<stdin>";
692   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
693     llvm::sys::path::remove_filename(FileNameBuf);
694     llvm::sys::path::append(FileNameBuf, getMainFileName());
695   }
696   StringRef FileName = FileNameBuf;
697   if (FileName.consume_front(getCompilationDir()))
698     if (llvm::sys::path::is_separator(FileName.front()))
699       FileName = FileName.drop_front();
700   assert(!FileName.empty());
701   setMCLineTableRootFile(
702       /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
703 }
704 
705 /// getDwarfFile - takes a file name and number to place in the dwarf file and
706 /// directory tables.  If the file number has already been allocated it is an
707 /// error and zero is returned and the client reports the error, else the
708 /// allocated file number is returned.  The file numbers may be in any order.
709 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
710                                            StringRef FileName,
711                                            unsigned FileNumber,
712                                            Optional<MD5::MD5Result> Checksum,
713                                            Optional<StringRef> Source,
714                                            unsigned CUID) {
715   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
716   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
717                           FileNumber);
718 }
719 
720 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
721 /// currently is assigned and false otherwise.
722 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
723   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
724   if (FileNumber == 0)
725     return getDwarfVersion() >= 5;
726   if (FileNumber >= LineTable.getMCDwarfFiles().size())
727     return false;
728 
729   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
730 }
731 
732 /// Remove empty sections from SectionsForRanges, to avoid generating
733 /// useless debug info for them.
734 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
735   SectionsForRanges.remove_if(
736       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
737 }
738 
739 CodeViewContext &MCContext::getCVContext() {
740   if (!CVContext.get())
741     CVContext.reset(new CodeViewContext);
742   return *CVContext.get();
743 }
744 
745 //===----------------------------------------------------------------------===//
746 // Error Reporting
747 //===----------------------------------------------------------------------===//
748 
749 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
750   HadError = true;
751 
752   // If we have a source manager use it. Otherwise, try using the inline source
753   // manager.
754   // If that fails, use the generic report_fatal_error().
755   if (SrcMgr)
756     SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
757   else if (InlineSrcMgr)
758     InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
759   else
760     report_fatal_error(Msg, false);
761 }
762 
763 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
764   if (TargetOptions && TargetOptions->MCNoWarn)
765     return;
766   if (TargetOptions && TargetOptions->MCFatalWarnings)
767     reportError(Loc, Msg);
768   else {
769     // If we have a source manager use it. Otherwise, try using the inline
770     // source manager.
771     if (SrcMgr)
772       SrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
773     else if (InlineSrcMgr)
774       InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
775   }
776 }
777 
778 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
779   reportError(Loc, Msg);
780 
781   // If we reached here, we are failing ungracefully. Run the interrupt handlers
782   // to make sure any special cleanups get done, in particular that we remove
783   // files registered with RemoveFileOnSignal.
784   sys::RunInterruptHandlers();
785   exit(1);
786 }
787