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/DenseMapInfo.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/BinaryFormat/COFF.h"
18 #include "llvm/BinaryFormat/ELF.h"
19 #include "llvm/BinaryFormat/Wasm.h"
20 #include "llvm/BinaryFormat/XCOFF.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCCodeView.h"
23 #include "llvm/MC/MCDwarf.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFragment.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCLabel.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSectionGOFF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCSectionSPIRV.h"
33 #include "llvm/MC/MCSectionWasm.h"
34 #include "llvm/MC/MCSectionXCOFF.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCSymbolCOFF.h"
39 #include "llvm/MC/MCSymbolELF.h"
40 #include "llvm/MC/MCSymbolGOFF.h"
41 #include "llvm/MC/MCSymbolMachO.h"
42 #include "llvm/MC/MCSymbolWasm.h"
43 #include "llvm/MC/MCSymbolXCOFF.h"
44 #include "llvm/MC/MCTargetOptions.h"
45 #include "llvm/MC/SectionKind.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/SMLoc.h"
52 #include "llvm/Support/SourceMgr.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <cassert>
55 #include <cstdlib>
56 #include <tuple>
57 #include <utility>
58 
59 using namespace llvm;
60 
61 static cl::opt<char*>
62 AsSecureLogFileName("as-secure-log-file-name",
63         cl::desc("As secure log file name (initialized from "
64                  "AS_SECURE_LOG_FILE env variable)"),
65         cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
66 
67 static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
68                                std::vector<const MDNode *> &) {
69   SMD.print(nullptr, errs());
70 }
71 
72 MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
73                      const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
74                      const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
75                      bool DoAutoReset, StringRef Swift5ReflSegmentName)
76     : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
77       SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
78       MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator), UsedNames(Allocator),
79       InlineAsmUsedLabelNames(Allocator),
80       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
81       AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
82   SecureLogFile = AsSecureLogFileName;
83 
84   if (SrcMgr && SrcMgr->getNumBuffers())
85     MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
86                                    ->getBufferIdentifier());
87 
88   switch (TheTriple.getObjectFormat()) {
89   case Triple::MachO:
90     Env = IsMachO;
91     break;
92   case Triple::COFF:
93     if (!TheTriple.isOSWindows())
94       report_fatal_error(
95           "Cannot initialize MC for non-Windows COFF object files.");
96 
97     Env = IsCOFF;
98     break;
99   case Triple::ELF:
100     Env = IsELF;
101     break;
102   case Triple::Wasm:
103     Env = IsWasm;
104     break;
105   case Triple::XCOFF:
106     Env = IsXCOFF;
107     break;
108   case Triple::GOFF:
109     Env = IsGOFF;
110     break;
111   case Triple::DXContainer:
112     Env = IsDXContainer;
113     break;
114   case Triple::SPIRV:
115     Env = IsSPIRV;
116     break;
117   case Triple::UnknownObjectFormat:
118     report_fatal_error("Cannot initialize MC for unknown object file format.");
119     break;
120   }
121 }
122 
123 MCContext::~MCContext() {
124   if (AutoReset)
125     reset();
126 
127   // NOTE: The symbols are all allocated out of a bump pointer allocator,
128   // we don't need to free them here.
129 }
130 
131 void MCContext::initInlineSourceManager() {
132   if (!InlineSrcMgr)
133     InlineSrcMgr.reset(new SourceMgr());
134 }
135 
136 //===----------------------------------------------------------------------===//
137 // Module Lifetime Management
138 //===----------------------------------------------------------------------===//
139 
140 void MCContext::reset() {
141   SrcMgr = nullptr;
142   InlineSrcMgr.reset();
143   LocInfos.clear();
144   DiagHandler = defaultDiagHandler;
145 
146   // Call the destructors so the fragments are freed
147   COFFAllocator.DestroyAll();
148   ELFAllocator.DestroyAll();
149   GOFFAllocator.DestroyAll();
150   MachOAllocator.DestroyAll();
151   WasmAllocator.DestroyAll();
152   XCOFFAllocator.DestroyAll();
153   MCInstAllocator.DestroyAll();
154   SPIRVAllocator.DestroyAll();
155 
156   MCSubtargetAllocator.DestroyAll();
157   InlineAsmUsedLabelNames.clear();
158   UsedNames.clear();
159   Symbols.clear();
160   Allocator.Reset();
161   Instances.clear();
162   CompilationDir.clear();
163   MainFileName.clear();
164   MCDwarfLineTablesCUMap.clear();
165   SectionsForRanges.clear();
166   MCGenDwarfLabelEntries.clear();
167   DwarfDebugFlags = StringRef();
168   DwarfCompileUnitID = 0;
169   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
170 
171   CVContext.reset();
172 
173   MachOUniquingMap.clear();
174   ELFUniquingMap.clear();
175   GOFFUniquingMap.clear();
176   COFFUniquingMap.clear();
177   WasmUniquingMap.clear();
178   XCOFFUniquingMap.clear();
179 
180   ELFEntrySizeMap.clear();
181   ELFSeenGenericMergeableSections.clear();
182 
183   NextID.clear();
184   AllowTemporaryLabels = true;
185   DwarfLocSeen = false;
186   GenDwarfForAssembly = false;
187   GenDwarfFileNumber = 0;
188 
189   HadError = false;
190 }
191 
192 //===----------------------------------------------------------------------===//
193 // MCInst Management
194 //===----------------------------------------------------------------------===//
195 
196 MCInst *MCContext::createMCInst() {
197   return new (MCInstAllocator.Allocate()) MCInst;
198 }
199 
200 //===----------------------------------------------------------------------===//
201 // Symbol Manipulation
202 //===----------------------------------------------------------------------===//
203 
204 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
205   SmallString<128> NameSV;
206   StringRef NameRef = Name.toStringRef(NameSV);
207 
208   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
209 
210   MCSymbol *&Sym = Symbols[NameRef];
211   if (!Sym)
212     Sym = createSymbol(NameRef, false, false);
213 
214   return Sym;
215 }
216 
217 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
218                                                  unsigned Idx) {
219   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
220                            "$frame_escape_" + Twine(Idx));
221 }
222 
223 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
224   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
225                            "$parent_frame_offset");
226 }
227 
228 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
229   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
230                            FuncName);
231 }
232 
233 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
234                                       bool IsTemporary) {
235   static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
236                 "MCSymbol classes must be trivially destructible");
237   static_assert(std::is_trivially_destructible<MCSymbolELF>(),
238                 "MCSymbol classes must be trivially destructible");
239   static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
240                 "MCSymbol classes must be trivially destructible");
241   static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
242                 "MCSymbol classes must be trivially destructible");
243   static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
244                 "MCSymbol classes must be trivially destructible");
245 
246   switch (getObjectFileType()) {
247   case MCContext::IsCOFF:
248     return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
249   case MCContext::IsELF:
250     return new (Name, *this) MCSymbolELF(Name, IsTemporary);
251   case MCContext::IsGOFF:
252     return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
253   case MCContext::IsMachO:
254     return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
255   case MCContext::IsWasm:
256     return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
257   case MCContext::IsXCOFF:
258     return createXCOFFSymbolImpl(Name, IsTemporary);
259   case MCContext::IsDXContainer:
260     break;
261   case MCContext::IsSPIRV:
262     return new (Name, *this)
263         MCSymbol(MCSymbol::SymbolKindUnset, Name, IsTemporary);
264   }
265   return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
266                                     IsTemporary);
267 }
268 
269 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
270                                   bool CanBeUnnamed) {
271   if (CanBeUnnamed && !UseNamesOnTempLabels)
272     return createSymbolImpl(nullptr, true);
273 
274   // Determine whether this is a user written assembler temporary or normal
275   // label, if used.
276   bool IsTemporary = CanBeUnnamed;
277   if (AllowTemporaryLabels && !IsTemporary)
278     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
279 
280   SmallString<128> NewName = Name;
281   bool AddSuffix = AlwaysAddSuffix;
282   unsigned &NextUniqueID = NextID[Name];
283   while (true) {
284     if (AddSuffix) {
285       NewName.resize(Name.size());
286       raw_svector_ostream(NewName) << NextUniqueID++;
287     }
288     auto NameEntry = UsedNames.insert(std::make_pair(NewName.str(), true));
289     if (NameEntry.second || !NameEntry.first->second) {
290       // Ok, we found a name.
291       // Mark it as used for a non-section symbol.
292       NameEntry.first->second = true;
293       // Have the MCSymbol object itself refer to the copy of the string that is
294       // embedded in the UsedNames entry.
295       return createSymbolImpl(&*NameEntry.first, IsTemporary);
296     }
297     assert(IsTemporary && "Cannot rename non-temporary symbols");
298     AddSuffix = true;
299   }
300   llvm_unreachable("Infinite loop");
301 }
302 
303 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
304   SmallString<128> NameSV;
305   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
306   return createSymbol(NameSV, AlwaysAddSuffix, true);
307 }
308 
309 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
310   SmallString<128> NameSV;
311   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
312   return createSymbol(NameSV, true, false);
313 }
314 
315 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
316   SmallString<128> NameSV;
317   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
318   return createSymbol(NameSV, true, false);
319 }
320 
321 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
322 
323 MCSymbol *MCContext::createNamedTempSymbol() {
324   return createNamedTempSymbol("tmp");
325 }
326 
327 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
328   MCLabel *&Label = Instances[LocalLabelVal];
329   if (!Label)
330     Label = new (*this) MCLabel(0);
331   return Label->incInstance();
332 }
333 
334 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
335   MCLabel *&Label = Instances[LocalLabelVal];
336   if (!Label)
337     Label = new (*this) MCLabel(0);
338   return Label->getInstance();
339 }
340 
341 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
342                                                        unsigned Instance) {
343   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
344   if (!Sym)
345     Sym = createNamedTempSymbol();
346   return Sym;
347 }
348 
349 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
350   unsigned Instance = NextInstance(LocalLabelVal);
351   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
352 }
353 
354 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
355                                                bool Before) {
356   unsigned Instance = GetInstance(LocalLabelVal);
357   if (!Before)
358     ++Instance;
359   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
360 }
361 
362 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
363   SmallString<128> NameSV;
364   StringRef NameRef = Name.toStringRef(NameSV);
365   return Symbols.lookup(NameRef);
366 }
367 
368 void MCContext::setSymbolValue(MCStreamer &Streamer,
369                               StringRef Sym,
370                               uint64_t Val) {
371   auto Symbol = getOrCreateSymbol(Sym);
372   Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
373 }
374 
375 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
376   InlineAsmUsedLabelNames[Sym->getName()] = Sym;
377 }
378 
379 MCSymbolXCOFF *
380 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
381                                  bool IsTemporary) {
382   if (!Name)
383     return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
384 
385   StringRef OriginalName = Name->first();
386   if (OriginalName.startswith("._Renamed..") ||
387       OriginalName.startswith("_Renamed.."))
388     reportError(SMLoc(), "invalid symbol name from source");
389 
390   if (MAI->isValidUnquotedName(OriginalName))
391     return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
392 
393   // Now we have a name that contains invalid character(s) for XCOFF symbol.
394   // Let's replace with something valid, but save the original name so that
395   // we could still use the original name in the symbol table.
396   SmallString<128> InvalidName(OriginalName);
397 
398   // If it's an entry point symbol, we will keep the '.'
399   // in front for the convention purpose. Otherwise, add "_Renamed.."
400   // as prefix to signal this is an renamed symbol.
401   const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
402   SmallString<128> ValidName =
403       StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
404 
405   // Append the hex values of '_' and invalid characters with "_Renamed..";
406   // at the same time replace invalid characters with '_'.
407   for (size_t I = 0; I < InvalidName.size(); ++I) {
408     if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
409       raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
410       InvalidName[I] = '_';
411     }
412   }
413 
414   // Skip entry point symbol's '.' as we already have a '.' in front of
415   // "_Renamed".
416   if (IsEntryPoint)
417     ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
418   else
419     ValidName.append(InvalidName);
420 
421   auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
422   assert((NameEntry.second || !NameEntry.first->second) &&
423          "This name is used somewhere else.");
424   // Mark the name as used for a non-section symbol.
425   NameEntry.first->second = true;
426   // Have the MCSymbol object itself refer to the copy of the string
427   // that is embedded in the UsedNames entry.
428   MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
429       MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
430   XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
431   return XSym;
432 }
433 
434 //===----------------------------------------------------------------------===//
435 // Section Management
436 //===----------------------------------------------------------------------===//
437 
438 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
439                                            unsigned TypeAndAttributes,
440                                            unsigned Reserved2, SectionKind Kind,
441                                            const char *BeginSymName) {
442   // We unique sections by their segment/section pair.  The returned section
443   // may not have the same flags as the requested section, if so this should be
444   // diagnosed by the client as an error.
445 
446   // Form the name to look up.
447   assert(Section.size() <= 16 && "section name is too long");
448   assert(!memchr(Section.data(), '\0', Section.size()) &&
449          "section name cannot contain NUL");
450 
451   // Do the lookup, if we have a hit, return it.
452   auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
453   if (!R.second)
454     return R.first->second;
455 
456   MCSymbol *Begin = nullptr;
457   if (BeginSymName)
458     Begin = createTempSymbol(BeginSymName, false);
459 
460   // Otherwise, return a new section.
461   StringRef Name = R.first->first();
462   R.first->second = new (MachOAllocator.Allocate())
463       MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
464                      TypeAndAttributes, Reserved2, Kind, Begin);
465   return R.first->second;
466 }
467 
468 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
469   StringRef GroupName;
470   if (const MCSymbol *Group = Section->getGroup())
471     GroupName = Group->getName();
472 
473   // This function is only used by .debug*, which should not have the
474   // SHF_LINK_ORDER flag.
475   unsigned UniqueID = Section->getUniqueID();
476   ELFUniquingMap.erase(
477       ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
478   auto I = ELFUniquingMap
479                .insert(std::make_pair(
480                    ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
481                .first;
482   StringRef CachedName = I->first.SectionName;
483   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
484 }
485 
486 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
487                                               unsigned Flags, SectionKind K,
488                                               unsigned EntrySize,
489                                               const MCSymbolELF *Group,
490                                               bool Comdat, unsigned UniqueID,
491                                               const MCSymbolELF *LinkedToSym) {
492   MCSymbolELF *R;
493   MCSymbol *&Sym = Symbols[Section];
494   // A section symbol can not redefine regular symbols. There may be multiple
495   // sections with the same name, in which case the first such section wins.
496   if (Sym && Sym->isDefined() &&
497       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
498     reportError(SMLoc(), "invalid symbol redefinition");
499   if (Sym && Sym->isUndefined()) {
500     R = cast<MCSymbolELF>(Sym);
501   } else {
502     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
503     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
504     if (!Sym)
505       Sym = R;
506   }
507   R->setBinding(ELF::STB_LOCAL);
508   R->setType(ELF::STT_SECTION);
509 
510   auto *Ret = new (ELFAllocator.Allocate())
511       MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
512                    R, LinkedToSym);
513 
514   auto *F = new MCDataFragment();
515   Ret->getFragmentList().insert(Ret->begin(), F);
516   F->setParent(Ret);
517   R->setFragment(F);
518 
519   return Ret;
520 }
521 
522 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
523                                              unsigned Flags, unsigned EntrySize,
524                                              const MCSymbolELF *Group,
525                                              const MCSectionELF *RelInfoSection) {
526   StringMap<bool>::iterator I;
527   bool Inserted;
528   std::tie(I, Inserted) =
529       RelSecNames.insert(std::make_pair(Name.str(), true));
530 
531   return createELFSectionImpl(
532       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
533       true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
534 }
535 
536 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
537                                             const Twine &Suffix, unsigned Type,
538                                             unsigned Flags,
539                                             unsigned EntrySize) {
540   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
541                        /*IsComdat=*/true);
542 }
543 
544 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
545                                        unsigned Flags, unsigned EntrySize,
546                                        const Twine &Group, bool IsComdat,
547                                        unsigned UniqueID,
548                                        const MCSymbolELF *LinkedToSym) {
549   MCSymbolELF *GroupSym = nullptr;
550   if (!Group.isTriviallyEmpty() && !Group.str().empty())
551     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
552 
553   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
554                        UniqueID, LinkedToSym);
555 }
556 
557 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
558                                        unsigned Flags, unsigned EntrySize,
559                                        const MCSymbolELF *GroupSym,
560                                        bool IsComdat, unsigned UniqueID,
561                                        const MCSymbolELF *LinkedToSym) {
562   StringRef Group = "";
563   if (GroupSym)
564     Group = GroupSym->getName();
565   assert(!(LinkedToSym && LinkedToSym->getName().empty()));
566   // Do the lookup, if we have a hit, return it.
567   auto IterBool = ELFUniquingMap.insert(std::make_pair(
568       ELFSectionKey{Section.str(), Group,
569                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
570       nullptr));
571   auto &Entry = *IterBool.first;
572   if (!IterBool.second)
573     return Entry.second;
574 
575   StringRef CachedName = Entry.first.SectionName;
576 
577   SectionKind Kind;
578   if (Flags & ELF::SHF_ARM_PURECODE)
579     Kind = SectionKind::getExecuteOnly();
580   else if (Flags & ELF::SHF_EXECINSTR)
581     Kind = SectionKind::getText();
582   else
583     Kind = SectionKind::getReadOnly();
584 
585   MCSectionELF *Result =
586       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
587                            IsComdat, UniqueID, LinkedToSym);
588   Entry.second = Result;
589 
590   recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
591                                 Result->getUniqueID(), Result->getEntrySize());
592 
593   return Result;
594 }
595 
596 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
597                                                bool IsComdat) {
598   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
599                               SectionKind::getReadOnly(), 4, Group, IsComdat,
600                               MCSection::NonUniqueID, nullptr);
601 }
602 
603 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
604                                               unsigned Flags, unsigned UniqueID,
605                                               unsigned EntrySize) {
606   bool IsMergeable = Flags & ELF::SHF_MERGE;
607   if (UniqueID == GenericSectionID)
608     ELFSeenGenericMergeableSections.insert(SectionName);
609 
610   // For mergeable sections or non-mergeable sections with a generic mergeable
611   // section name we enter their Unique ID into the ELFEntrySizeMap so that
612   // compatible globals can be assigned to the same section.
613   if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
614     ELFEntrySizeMap.insert(std::make_pair(
615         ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
616   }
617 }
618 
619 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
620   return SectionName.startswith(".rodata.str") ||
621          SectionName.startswith(".rodata.cst");
622 }
623 
624 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
625   return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
626          ELFSeenGenericMergeableSections.count(SectionName);
627 }
628 
629 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
630                                                        unsigned Flags,
631                                                        unsigned EntrySize) {
632   auto I = ELFEntrySizeMap.find(
633       MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
634   return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
635 }
636 
637 MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind,
638                                          MCSection *Parent,
639                                          const MCExpr *SubsectionId) {
640   // Do the lookup. If we don't have a hit, return a new section.
641   auto &GOFFSection = GOFFUniquingMap[Section.str()];
642   if (!GOFFSection)
643     GOFFSection = new (GOFFAllocator.Allocate())
644         MCSectionGOFF(Section, Kind, Parent, SubsectionId);
645 
646   return GOFFSection;
647 }
648 
649 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
650                                          unsigned Characteristics,
651                                          SectionKind Kind,
652                                          StringRef COMDATSymName, int Selection,
653                                          unsigned UniqueID,
654                                          const char *BeginSymName) {
655   MCSymbol *COMDATSymbol = nullptr;
656   if (!COMDATSymName.empty()) {
657     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
658     COMDATSymName = COMDATSymbol->getName();
659   }
660 
661 
662   // Do the lookup, if we have a hit, return it.
663   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
664   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
665   auto Iter = IterBool.first;
666   if (!IterBool.second)
667     return Iter->second;
668 
669   MCSymbol *Begin = nullptr;
670   if (BeginSymName)
671     Begin = createTempSymbol(BeginSymName, false);
672 
673   StringRef CachedName = Iter->first.SectionName;
674   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
675       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
676 
677   Iter->second = Result;
678   return Result;
679 }
680 
681 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
682                                          unsigned Characteristics,
683                                          SectionKind Kind,
684                                          const char *BeginSymName) {
685   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
686                         BeginSymName);
687 }
688 
689 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
690                                                     const MCSymbol *KeySym,
691                                                     unsigned UniqueID) {
692   // Return the normal section if we don't have to be associative or unique.
693   if (!KeySym && UniqueID == GenericSectionID)
694     return Sec;
695 
696   // If we have a key symbol, make an associative section with the same name and
697   // kind as the normal section.
698   unsigned Characteristics = Sec->getCharacteristics();
699   if (KeySym) {
700     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
701     return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
702                           KeySym->getName(),
703                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
704   }
705 
706   return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
707                         UniqueID);
708 }
709 
710 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
711                                          unsigned Flags, const Twine &Group,
712                                          unsigned UniqueID,
713                                          const char *BeginSymName) {
714   MCSymbolWasm *GroupSym = nullptr;
715   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
716     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
717     GroupSym->setComdat(true);
718   }
719 
720   return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
721 }
722 
723 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
724                                          unsigned Flags,
725                                          const MCSymbolWasm *GroupSym,
726                                          unsigned UniqueID,
727                                          const char *BeginSymName) {
728   StringRef Group = "";
729   if (GroupSym)
730     Group = GroupSym->getName();
731   // Do the lookup, if we have a hit, return it.
732   auto IterBool = WasmUniquingMap.insert(
733       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
734   auto &Entry = *IterBool.first;
735   if (!IterBool.second)
736     return Entry.second;
737 
738   StringRef CachedName = Entry.first.SectionName;
739 
740   MCSymbol *Begin = createSymbol(CachedName, true, false);
741   Symbols[Begin->getName()] = Begin;
742   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
743 
744   MCSectionWasm *Result = new (WasmAllocator.Allocate())
745       MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
746   Entry.second = Result;
747 
748   auto *F = new MCDataFragment();
749   Result->getFragmentList().insert(Result->begin(), F);
750   F->setParent(Result);
751   Begin->setFragment(F);
752 
753   return Result;
754 }
755 
756 bool MCContext::hasXCOFFSection(StringRef Section,
757                                 XCOFF::CsectProperties CsectProp) const {
758   return XCOFFUniquingMap.count(
759              XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
760 }
761 
762 MCSectionXCOFF *MCContext::getXCOFFSection(
763     StringRef Section, SectionKind Kind,
764     Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
765     const char *BeginSymName,
766     Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
767   bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
768   assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
769 
770   // Do the lookup. If we have a hit, return it.
771   auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
772       IsDwarfSec
773           ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
774           : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
775       nullptr));
776   auto &Entry = *IterBool.first;
777   if (!IterBool.second) {
778     MCSectionXCOFF *ExistedEntry = Entry.second;
779     if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
780       report_fatal_error("section's multiply symbols policy does not match");
781 
782     return ExistedEntry;
783   }
784 
785   // Otherwise, return a new section.
786   StringRef CachedName = Entry.first.SectionName;
787   MCSymbolXCOFF *QualName = nullptr;
788   // Debug section don't have storage class attribute.
789   if (IsDwarfSec)
790     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
791   else
792     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
793         CachedName + "[" +
794         XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
795 
796   MCSymbol *Begin = nullptr;
797   if (BeginSymName)
798     Begin = createTempSymbol(BeginSymName, false);
799 
800   // QualName->getUnqualifiedName() and CachedName are the same except when
801   // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
802   MCSectionXCOFF *Result = nullptr;
803   if (IsDwarfSec)
804     Result = new (XCOFFAllocator.Allocate())
805         MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
806                        DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
807                        MultiSymbolsAllowed);
808   else
809     Result = new (XCOFFAllocator.Allocate())
810         MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
811                        CsectProp->Type, Kind, QualName, Begin, CachedName,
812                        MultiSymbolsAllowed);
813 
814   Entry.second = Result;
815 
816   auto *F = new MCDataFragment();
817   Result->getFragmentList().insert(Result->begin(), F);
818   F->setParent(Result);
819 
820   if (Begin)
821     Begin->setFragment(F);
822 
823   return Result;
824 }
825 
826 MCSectionSPIRV *MCContext::getSPIRVSection() {
827   MCSymbol *Begin = nullptr;
828   MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate())
829       MCSectionSPIRV(SectionKind::getText(), Begin);
830 
831   auto *F = new MCDataFragment();
832   Result->getFragmentList().insert(Result->begin(), F);
833   F->setParent(Result);
834 
835   if (Begin)
836     Begin->setFragment(F);
837 
838   return Result;
839 }
840 
841 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
842   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
843 }
844 
845 void MCContext::addDebugPrefixMapEntry(const std::string &From,
846                                        const std::string &To) {
847   DebugPrefixMap.insert(std::make_pair(From, To));
848 }
849 
850 void MCContext::RemapDebugPaths() {
851   const auto &DebugPrefixMap = this->DebugPrefixMap;
852   if (DebugPrefixMap.empty())
853     return;
854 
855   const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
856     SmallString<256> P(Path);
857     for (const auto &Entry : DebugPrefixMap) {
858       if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) {
859         Path = P.str().str();
860         break;
861       }
862     }
863   };
864 
865   // Remap compilation directory.
866   std::string CompDir = std::string(CompilationDir.str());
867   RemapDebugPath(CompDir);
868   CompilationDir = CompDir;
869 
870   // Remap MCDwarfDirs in all compilation units.
871   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
872     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
873       RemapDebugPath(Dir);
874 }
875 
876 //===----------------------------------------------------------------------===//
877 // Dwarf Management
878 //===----------------------------------------------------------------------===//
879 
880 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
881   // MCDwarf needs the root file as well as the compilation directory.
882   // If we find a '.file 0' directive that will supersede these values.
883   Optional<MD5::MD5Result> Cksum;
884   if (getDwarfVersion() >= 5) {
885     MD5 Hash;
886     MD5::MD5Result Sum;
887     Hash.update(Buffer);
888     Hash.final(Sum);
889     Cksum = Sum;
890   }
891   // Canonicalize the root filename. It cannot be empty, and should not
892   // repeat the compilation dir.
893   // The MCContext ctor initializes MainFileName to the name associated with
894   // the SrcMgr's main file ID, which might be the same as InputFileName (and
895   // possibly include directory components).
896   // Or, MainFileName might have been overridden by a -main-file-name option,
897   // which is supposed to be just a base filename with no directory component.
898   // So, if the InputFileName and MainFileName are not equal, assume
899   // MainFileName is a substitute basename and replace the last component.
900   SmallString<1024> FileNameBuf = InputFileName;
901   if (FileNameBuf.empty() || FileNameBuf == "-")
902     FileNameBuf = "<stdin>";
903   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
904     llvm::sys::path::remove_filename(FileNameBuf);
905     llvm::sys::path::append(FileNameBuf, getMainFileName());
906   }
907   StringRef FileName = FileNameBuf;
908   if (FileName.consume_front(getCompilationDir()))
909     if (llvm::sys::path::is_separator(FileName.front()))
910       FileName = FileName.drop_front();
911   assert(!FileName.empty());
912   setMCLineTableRootFile(
913       /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
914 }
915 
916 /// getDwarfFile - takes a file name and number to place in the dwarf file and
917 /// directory tables.  If the file number has already been allocated it is an
918 /// error and zero is returned and the client reports the error, else the
919 /// allocated file number is returned.  The file numbers may be in any order.
920 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
921                                            StringRef FileName,
922                                            unsigned FileNumber,
923                                            Optional<MD5::MD5Result> Checksum,
924                                            Optional<StringRef> Source,
925                                            unsigned CUID) {
926   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
927   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
928                           FileNumber);
929 }
930 
931 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
932 /// currently is assigned and false otherwise.
933 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
934   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
935   if (FileNumber == 0)
936     return getDwarfVersion() >= 5;
937   if (FileNumber >= LineTable.getMCDwarfFiles().size())
938     return false;
939 
940   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
941 }
942 
943 /// Remove empty sections from SectionsForRanges, to avoid generating
944 /// useless debug info for them.
945 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
946   SectionsForRanges.remove_if(
947       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
948 }
949 
950 CodeViewContext &MCContext::getCVContext() {
951   if (!CVContext)
952     CVContext.reset(new CodeViewContext);
953   return *CVContext;
954 }
955 
956 //===----------------------------------------------------------------------===//
957 // Error Reporting
958 //===----------------------------------------------------------------------===//
959 
960 void MCContext::diagnose(const SMDiagnostic &SMD) {
961   assert(DiagHandler && "MCContext::DiagHandler is not set");
962   bool UseInlineSrcMgr = false;
963   const SourceMgr *SMP = nullptr;
964   if (SrcMgr) {
965     SMP = SrcMgr;
966   } else if (InlineSrcMgr) {
967     SMP = InlineSrcMgr.get();
968     UseInlineSrcMgr = true;
969   } else
970     llvm_unreachable("Either SourceMgr should be available");
971   DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
972 }
973 
974 void MCContext::reportCommon(
975     SMLoc Loc,
976     std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
977   // * MCContext::SrcMgr is null when the MC layer emits machine code for input
978   //   other than assembly file, say, for .c/.cpp/.ll/.bc.
979   // * MCContext::InlineSrcMgr is null when the inline asm is not used.
980   // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
981   //   and MCContext::InlineSrcMgr are null.
982   SourceMgr SM;
983   const SourceMgr *SMP = &SM;
984   bool UseInlineSrcMgr = false;
985 
986   // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
987   //        For MC-only execution, only SrcMgr is used;
988   //        For non MC-only execution, InlineSrcMgr is only ctor'd if there is
989   //        inline asm in the IR.
990   if (Loc.isValid()) {
991     if (SrcMgr) {
992       SMP = SrcMgr;
993     } else if (InlineSrcMgr) {
994       SMP = InlineSrcMgr.get();
995       UseInlineSrcMgr = true;
996     } else
997       llvm_unreachable("Either SourceMgr should be available");
998   }
999 
1000   SMDiagnostic D;
1001   GetMessage(D, SMP);
1002   DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1003 }
1004 
1005 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
1006   HadError = true;
1007   reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1008     D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1009   });
1010 }
1011 
1012 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
1013   if (TargetOptions && TargetOptions->MCNoWarn)
1014     return;
1015   if (TargetOptions && TargetOptions->MCFatalWarnings) {
1016     reportError(Loc, Msg);
1017   } else {
1018     reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1019       D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1020     });
1021   }
1022 }
1023