xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCContext.cpp (revision d9a42747950146bf03cda7f6e25d219253f8a57a)
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 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
472                                               unsigned Flags, SectionKind K,
473                                               unsigned EntrySize,
474                                               const MCSymbolELF *Group,
475                                               bool Comdat, unsigned UniqueID,
476                                               const MCSymbolELF *LinkedToSym) {
477   MCSymbolELF *R;
478   MCSymbol *&Sym = Symbols[Section];
479   // A section symbol can not redefine regular symbols. There may be multiple
480   // sections with the same name, in which case the first such section wins.
481   if (Sym && Sym->isDefined() &&
482       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
483     reportError(SMLoc(), "invalid symbol redefinition");
484   if (Sym && Sym->isUndefined()) {
485     R = cast<MCSymbolELF>(Sym);
486   } else {
487     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
488     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
489     if (!Sym)
490       Sym = R;
491   }
492   R->setBinding(ELF::STB_LOCAL);
493   R->setType(ELF::STT_SECTION);
494 
495   auto *Ret = new (ELFAllocator.Allocate())
496       MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
497                    R, LinkedToSym);
498 
499   auto *F = new MCDataFragment();
500   Ret->getFragmentList().insert(Ret->begin(), F);
501   F->setParent(Ret);
502   R->setFragment(F);
503 
504   return Ret;
505 }
506 
507 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
508                                              unsigned Flags, unsigned EntrySize,
509                                              const MCSymbolELF *Group,
510                                              const MCSectionELF *RelInfoSection) {
511   StringMap<bool>::iterator I;
512   bool Inserted;
513   std::tie(I, Inserted) =
514       RelSecNames.insert(std::make_pair(Name.str(), true));
515 
516   return createELFSectionImpl(
517       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
518       true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
519 }
520 
521 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
522                                             const Twine &Suffix, unsigned Type,
523                                             unsigned Flags,
524                                             unsigned EntrySize) {
525   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
526                        /*IsComdat=*/true);
527 }
528 
529 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
530                                        unsigned Flags, unsigned EntrySize,
531                                        const Twine &Group, bool IsComdat,
532                                        unsigned UniqueID,
533                                        const MCSymbolELF *LinkedToSym) {
534   MCSymbolELF *GroupSym = nullptr;
535   if (!Group.isTriviallyEmpty() && !Group.str().empty())
536     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
537 
538   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
539                        UniqueID, LinkedToSym);
540 }
541 
542 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
543                                        unsigned Flags, unsigned EntrySize,
544                                        const MCSymbolELF *GroupSym,
545                                        bool IsComdat, unsigned UniqueID,
546                                        const MCSymbolELF *LinkedToSym) {
547   StringRef Group = "";
548   if (GroupSym)
549     Group = GroupSym->getName();
550   assert(!(LinkedToSym && LinkedToSym->getName().empty()));
551   // Do the lookup, if we have a hit, return it.
552   auto IterBool = ELFUniquingMap.insert(std::make_pair(
553       ELFSectionKey{Section.str(), Group,
554                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
555       nullptr));
556   auto &Entry = *IterBool.first;
557   if (!IterBool.second)
558     return Entry.second;
559 
560   StringRef CachedName = Entry.first.SectionName;
561 
562   SectionKind Kind;
563   if (Flags & ELF::SHF_ARM_PURECODE)
564     Kind = SectionKind::getExecuteOnly();
565   else if (Flags & ELF::SHF_EXECINSTR)
566     Kind = SectionKind::getText();
567   else
568     Kind = SectionKind::getReadOnly();
569 
570   MCSectionELF *Result =
571       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
572                            IsComdat, UniqueID, LinkedToSym);
573   Entry.second = Result;
574 
575   recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
576                                 Result->getUniqueID(), Result->getEntrySize());
577 
578   return Result;
579 }
580 
581 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
582                                                bool IsComdat) {
583   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
584                               SectionKind::getReadOnly(), 4, Group, IsComdat,
585                               MCSection::NonUniqueID, nullptr);
586 }
587 
588 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
589                                               unsigned Flags, unsigned UniqueID,
590                                               unsigned EntrySize) {
591   bool IsMergeable = Flags & ELF::SHF_MERGE;
592   if (UniqueID == GenericSectionID)
593     ELFSeenGenericMergeableSections.insert(SectionName);
594 
595   // For mergeable sections or non-mergeable sections with a generic mergeable
596   // section name we enter their Unique ID into the ELFEntrySizeMap so that
597   // compatible globals can be assigned to the same section.
598   if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
599     ELFEntrySizeMap.insert(std::make_pair(
600         ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
601   }
602 }
603 
604 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
605   return SectionName.startswith(".rodata.str") ||
606          SectionName.startswith(".rodata.cst");
607 }
608 
609 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
610   return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
611          ELFSeenGenericMergeableSections.count(SectionName);
612 }
613 
614 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
615                                                        unsigned Flags,
616                                                        unsigned EntrySize) {
617   auto I = ELFEntrySizeMap.find(
618       MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
619   return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
620 }
621 
622 MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind,
623                                          MCSection *Parent,
624                                          const MCExpr *SubsectionId) {
625   // Do the lookup. If we don't have a hit, return a new section.
626   auto &GOFFSection = GOFFUniquingMap[Section.str()];
627   if (!GOFFSection)
628     GOFFSection = new (GOFFAllocator.Allocate())
629         MCSectionGOFF(Section, Kind, Parent, SubsectionId);
630 
631   return GOFFSection;
632 }
633 
634 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
635                                          unsigned Characteristics,
636                                          SectionKind Kind,
637                                          StringRef COMDATSymName, int Selection,
638                                          unsigned UniqueID,
639                                          const char *BeginSymName) {
640   MCSymbol *COMDATSymbol = nullptr;
641   if (!COMDATSymName.empty()) {
642     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
643     COMDATSymName = COMDATSymbol->getName();
644   }
645 
646 
647   // Do the lookup, if we have a hit, return it.
648   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
649   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
650   auto Iter = IterBool.first;
651   if (!IterBool.second)
652     return Iter->second;
653 
654   MCSymbol *Begin = nullptr;
655   if (BeginSymName)
656     Begin = createTempSymbol(BeginSymName, false);
657 
658   StringRef CachedName = Iter->first.SectionName;
659   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
660       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
661 
662   Iter->second = Result;
663   return Result;
664 }
665 
666 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
667                                          unsigned Characteristics,
668                                          SectionKind Kind,
669                                          const char *BeginSymName) {
670   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
671                         BeginSymName);
672 }
673 
674 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
675                                                     const MCSymbol *KeySym,
676                                                     unsigned UniqueID) {
677   // Return the normal section if we don't have to be associative or unique.
678   if (!KeySym && UniqueID == GenericSectionID)
679     return Sec;
680 
681   // If we have a key symbol, make an associative section with the same name and
682   // kind as the normal section.
683   unsigned Characteristics = Sec->getCharacteristics();
684   if (KeySym) {
685     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
686     return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
687                           KeySym->getName(),
688                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
689   }
690 
691   return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
692                         UniqueID);
693 }
694 
695 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
696                                          unsigned Flags, const Twine &Group,
697                                          unsigned UniqueID,
698                                          const char *BeginSymName) {
699   MCSymbolWasm *GroupSym = nullptr;
700   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
701     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
702     GroupSym->setComdat(true);
703   }
704 
705   return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
706 }
707 
708 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
709                                          unsigned Flags,
710                                          const MCSymbolWasm *GroupSym,
711                                          unsigned UniqueID,
712                                          const char *BeginSymName) {
713   StringRef Group = "";
714   if (GroupSym)
715     Group = GroupSym->getName();
716   // Do the lookup, if we have a hit, return it.
717   auto IterBool = WasmUniquingMap.insert(
718       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
719   auto &Entry = *IterBool.first;
720   if (!IterBool.second)
721     return Entry.second;
722 
723   StringRef CachedName = Entry.first.SectionName;
724 
725   MCSymbol *Begin = createSymbol(CachedName, true, false);
726   Symbols[Begin->getName()] = Begin;
727   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
728 
729   MCSectionWasm *Result = new (WasmAllocator.Allocate())
730       MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
731   Entry.second = Result;
732 
733   auto *F = new MCDataFragment();
734   Result->getFragmentList().insert(Result->begin(), F);
735   F->setParent(Result);
736   Begin->setFragment(F);
737 
738   return Result;
739 }
740 
741 bool MCContext::hasXCOFFSection(StringRef Section,
742                                 XCOFF::CsectProperties CsectProp) const {
743   return XCOFFUniquingMap.count(
744              XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
745 }
746 
747 MCSectionXCOFF *MCContext::getXCOFFSection(
748     StringRef Section, SectionKind Kind,
749     Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
750     const char *BeginSymName,
751     Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
752   bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
753   assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
754 
755   // Do the lookup. If we have a hit, return it.
756   auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
757       IsDwarfSec
758           ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.value())
759           : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
760       nullptr));
761   auto &Entry = *IterBool.first;
762   if (!IterBool.second) {
763     MCSectionXCOFF *ExistedEntry = Entry.second;
764     if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
765       report_fatal_error("section's multiply symbols policy does not match");
766 
767     return ExistedEntry;
768   }
769 
770   // Otherwise, return a new section.
771   StringRef CachedName = Entry.first.SectionName;
772   MCSymbolXCOFF *QualName = nullptr;
773   // Debug section don't have storage class attribute.
774   if (IsDwarfSec)
775     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
776   else
777     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
778         CachedName + "[" +
779         XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
780 
781   MCSymbol *Begin = nullptr;
782   if (BeginSymName)
783     Begin = createTempSymbol(BeginSymName, false);
784 
785   // QualName->getUnqualifiedName() and CachedName are the same except when
786   // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
787   MCSectionXCOFF *Result = nullptr;
788   if (IsDwarfSec)
789     Result = new (XCOFFAllocator.Allocate())
790         MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
791                        DwarfSectionSubtypeFlags.value(), Begin, CachedName,
792                        MultiSymbolsAllowed);
793   else
794     Result = new (XCOFFAllocator.Allocate())
795         MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
796                        CsectProp->Type, Kind, QualName, Begin, CachedName,
797                        MultiSymbolsAllowed);
798 
799   Entry.second = Result;
800 
801   auto *F = new MCDataFragment();
802   Result->getFragmentList().insert(Result->begin(), F);
803   F->setParent(Result);
804 
805   if (Begin)
806     Begin->setFragment(F);
807 
808   return Result;
809 }
810 
811 MCSectionSPIRV *MCContext::getSPIRVSection() {
812   MCSymbol *Begin = nullptr;
813   MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate())
814       MCSectionSPIRV(SectionKind::getText(), Begin);
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 MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section,
827                                                        SectionKind K) {
828   // Do the lookup, if we have a hit, return it.
829   auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
830   if (!ItInsertedPair.second)
831     return ItInsertedPair.first->second;
832 
833   auto MapIt = ItInsertedPair.first;
834   // Grab the name from the StringMap. Since the Section is going to keep a
835   // copy of this StringRef we need to make sure the underlying string stays
836   // alive as long as we need it.
837   StringRef Name = MapIt->first();
838   MapIt->second =
839       new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
840 
841   // The first fragment will store the header
842   auto *F = new MCDataFragment();
843   MapIt->second->getFragmentList().insert(MapIt->second->begin(), F);
844   F->setParent(MapIt->second);
845 
846   return MapIt->second;
847 }
848 
849 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
850   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
851 }
852 
853 void MCContext::addDebugPrefixMapEntry(const std::string &From,
854                                        const std::string &To) {
855   DebugPrefixMap.insert(std::make_pair(From, To));
856 }
857 
858 void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) {
859   for (const auto &V : DebugPrefixMap)
860     if (llvm::sys::path::replace_path_prefix(Path, V.first, V.second))
861       break;
862 }
863 
864 void MCContext::RemapDebugPaths() {
865   const auto &DebugPrefixMap = this->DebugPrefixMap;
866   if (DebugPrefixMap.empty())
867     return;
868 
869   // Remap compilation directory.
870   remapDebugPath(CompilationDir);
871 
872   // Remap MCDwarfDirs and RootFile.Name in all compilation units.
873   SmallString<256> P;
874   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
875     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
876       P = Dir;
877       remapDebugPath(P);
878       Dir = std::string(P);
879     }
880 
881     // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
882     // DW_AT_decl_file for DWARF v5 generated for assembly source.
883     P = CUIDTablePair.second.getRootFile().Name;
884     remapDebugPath(P);
885     CUIDTablePair.second.getRootFile().Name = std::string(P);
886   }
887 }
888 
889 //===----------------------------------------------------------------------===//
890 // Dwarf Management
891 //===----------------------------------------------------------------------===//
892 
893 EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const {
894   if (!TargetOptions)
895     return EmitDwarfUnwindType::Default;
896   return TargetOptions->EmitDwarfUnwind;
897 }
898 
899 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
900   // MCDwarf needs the root file as well as the compilation directory.
901   // If we find a '.file 0' directive that will supersede these values.
902   Optional<MD5::MD5Result> Cksum;
903   if (getDwarfVersion() >= 5) {
904     MD5 Hash;
905     MD5::MD5Result Sum;
906     Hash.update(Buffer);
907     Hash.final(Sum);
908     Cksum = Sum;
909   }
910   // Canonicalize the root filename. It cannot be empty, and should not
911   // repeat the compilation dir.
912   // The MCContext ctor initializes MainFileName to the name associated with
913   // the SrcMgr's main file ID, which might be the same as InputFileName (and
914   // possibly include directory components).
915   // Or, MainFileName might have been overridden by a -main-file-name option,
916   // which is supposed to be just a base filename with no directory component.
917   // So, if the InputFileName and MainFileName are not equal, assume
918   // MainFileName is a substitute basename and replace the last component.
919   SmallString<1024> FileNameBuf = InputFileName;
920   if (FileNameBuf.empty() || FileNameBuf == "-")
921     FileNameBuf = "<stdin>";
922   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
923     llvm::sys::path::remove_filename(FileNameBuf);
924     llvm::sys::path::append(FileNameBuf, getMainFileName());
925   }
926   StringRef FileName = FileNameBuf;
927   if (FileName.consume_front(getCompilationDir()))
928     if (llvm::sys::path::is_separator(FileName.front()))
929       FileName = FileName.drop_front();
930   assert(!FileName.empty());
931   setMCLineTableRootFile(
932       /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
933 }
934 
935 /// getDwarfFile - takes a file name and number to place in the dwarf file and
936 /// directory tables.  If the file number has already been allocated it is an
937 /// error and zero is returned and the client reports the error, else the
938 /// allocated file number is returned.  The file numbers may be in any order.
939 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
940                                            StringRef FileName,
941                                            unsigned FileNumber,
942                                            Optional<MD5::MD5Result> Checksum,
943                                            Optional<StringRef> Source,
944                                            unsigned CUID) {
945   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
946   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
947                           FileNumber);
948 }
949 
950 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
951 /// currently is assigned and false otherwise.
952 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
953   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
954   if (FileNumber == 0)
955     return getDwarfVersion() >= 5;
956   if (FileNumber >= LineTable.getMCDwarfFiles().size())
957     return false;
958 
959   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
960 }
961 
962 /// Remove empty sections from SectionsForRanges, to avoid generating
963 /// useless debug info for them.
964 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
965   SectionsForRanges.remove_if(
966       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
967 }
968 
969 CodeViewContext &MCContext::getCVContext() {
970   if (!CVContext)
971     CVContext.reset(new CodeViewContext);
972   return *CVContext;
973 }
974 
975 //===----------------------------------------------------------------------===//
976 // Error Reporting
977 //===----------------------------------------------------------------------===//
978 
979 void MCContext::diagnose(const SMDiagnostic &SMD) {
980   assert(DiagHandler && "MCContext::DiagHandler is not set");
981   bool UseInlineSrcMgr = false;
982   const SourceMgr *SMP = nullptr;
983   if (SrcMgr) {
984     SMP = SrcMgr;
985   } else if (InlineSrcMgr) {
986     SMP = InlineSrcMgr.get();
987     UseInlineSrcMgr = true;
988   } else
989     llvm_unreachable("Either SourceMgr should be available");
990   DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
991 }
992 
993 void MCContext::reportCommon(
994     SMLoc Loc,
995     std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
996   // * MCContext::SrcMgr is null when the MC layer emits machine code for input
997   //   other than assembly file, say, for .c/.cpp/.ll/.bc.
998   // * MCContext::InlineSrcMgr is null when the inline asm is not used.
999   // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1000   //   and MCContext::InlineSrcMgr are null.
1001   SourceMgr SM;
1002   const SourceMgr *SMP = &SM;
1003   bool UseInlineSrcMgr = false;
1004 
1005   // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1006   //        For MC-only execution, only SrcMgr is used;
1007   //        For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1008   //        inline asm in the IR.
1009   if (Loc.isValid()) {
1010     if (SrcMgr) {
1011       SMP = SrcMgr;
1012     } else if (InlineSrcMgr) {
1013       SMP = InlineSrcMgr.get();
1014       UseInlineSrcMgr = true;
1015     } else
1016       llvm_unreachable("Either SourceMgr should be available");
1017   }
1018 
1019   SMDiagnostic D;
1020   GetMessage(D, SMP);
1021   DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1022 }
1023 
1024 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
1025   HadError = true;
1026   reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1027     D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1028   });
1029 }
1030 
1031 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
1032   if (TargetOptions && TargetOptions->MCNoWarn)
1033     return;
1034   if (TargetOptions && TargetOptions->MCFatalWarnings) {
1035     reportError(Loc, Msg);
1036   } else {
1037     reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1038       D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1039     });
1040   }
1041 }
1042