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