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