1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeView.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFragment.h"
23 #include "llvm/MC/MCLabel.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCSectionWasm.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/MC/MCSymbolELF.h"
33 #include "llvm/MC/MCSymbolMachO.h"
34 #include "llvm/MC/MCSymbolWasm.h"
35 #include "llvm/MC/SectionKind.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/raw_ostream.h"
51 AsSecureLogFileName("as-secure-log-file-name",
52 cl::desc("As secure log file name (initialized from "
53 "AS_SECURE_LOG_FILE env variable)"),
54 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
56 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
57 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
59 : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
60 Symbols(Allocator), UsedNames(Allocator),
61 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
62 AutoReset(DoAutoReset) {
63 SecureLogFile = AsSecureLogFileName;
65 if (SrcMgr && SrcMgr->getNumBuffers())
67 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
70 MCContext::~MCContext() {
74 // NOTE: The symbols are all allocated out of a bump pointer allocator,
75 // we don't need to free them here.
78 //===----------------------------------------------------------------------===//
79 // Module Lifetime Management
80 //===----------------------------------------------------------------------===//
82 void MCContext::reset() {
83 // Call the destructors so the fragments are freed
84 COFFAllocator.DestroyAll();
85 ELFAllocator.DestroyAll();
86 MachOAllocator.DestroyAll();
88 MCSubtargetAllocator.DestroyAll();
93 CompilationDir.clear();
95 MCDwarfLineTablesCUMap.clear();
96 SectionsForRanges.clear();
97 MCGenDwarfLabelEntries.clear();
98 DwarfDebugFlags = StringRef();
99 DwarfCompileUnitID = 0;
100 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
104 MachOUniquingMap.clear();
105 ELFUniquingMap.clear();
106 COFFUniquingMap.clear();
109 AllowTemporaryLabels = true;
110 DwarfLocSeen = false;
111 GenDwarfForAssembly = false;
112 GenDwarfFileNumber = 0;
117 //===----------------------------------------------------------------------===//
118 // Symbol Manipulation
119 //===----------------------------------------------------------------------===//
121 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
122 SmallString<128> NameSV;
123 StringRef NameRef = Name.toStringRef(NameSV);
125 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
127 MCSymbol *&Sym = Symbols[NameRef];
129 Sym = createSymbol(NameRef, false, false);
134 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
136 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
137 "$frame_escape_" + Twine(Idx));
140 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
141 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
142 "$parent_frame_offset");
145 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
146 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
150 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
153 switch (MOFI->getObjectFileType()) {
154 case MCObjectFileInfo::IsCOFF:
155 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
156 case MCObjectFileInfo::IsELF:
157 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
158 case MCObjectFileInfo::IsMachO:
159 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
160 case MCObjectFileInfo::IsWasm:
161 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
164 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
168 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
170 if (CanBeUnnamed && !UseNamesOnTempLabels)
171 return createSymbolImpl(nullptr, true);
173 // Determine whether this is a user written assembler temporary or normal
175 bool IsTemporary = CanBeUnnamed;
176 if (AllowTemporaryLabels && !IsTemporary)
177 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
179 SmallString<128> NewName = Name;
180 bool AddSuffix = AlwaysAddSuffix;
181 unsigned &NextUniqueID = NextID[Name];
184 NewName.resize(Name.size());
185 raw_svector_ostream(NewName) << NextUniqueID++;
187 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
188 if (NameEntry.second || !NameEntry.first->second) {
189 // Ok, we found a name.
190 // Mark it as used for a non-section symbol.
191 NameEntry.first->second = true;
192 // Have the MCSymbol object itself refer to the copy of the string that is
193 // embedded in the UsedNames entry.
194 return createSymbolImpl(&*NameEntry.first, IsTemporary);
196 assert(IsTemporary && "Cannot rename non-temporary symbols");
199 llvm_unreachable("Infinite loop");
202 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
204 SmallString<128> NameSV;
205 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
206 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
209 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
210 SmallString<128> NameSV;
211 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
212 return createSymbol(NameSV, true, false);
215 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
216 return createTempSymbol("tmp", true, CanBeUnnamed);
219 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
220 MCLabel *&Label = Instances[LocalLabelVal];
222 Label = new (*this) MCLabel(0);
223 return Label->incInstance();
226 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
227 MCLabel *&Label = Instances[LocalLabelVal];
229 Label = new (*this) MCLabel(0);
230 return Label->getInstance();
233 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
235 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
237 Sym = createTempSymbol(false);
241 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
242 unsigned Instance = NextInstance(LocalLabelVal);
243 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
246 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
248 unsigned Instance = GetInstance(LocalLabelVal);
251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
254 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
255 SmallString<128> NameSV;
256 StringRef NameRef = Name.toStringRef(NameSV);
257 return Symbols.lookup(NameRef);
260 void MCContext::setSymbolValue(MCStreamer &Streamer,
263 auto Symbol = getOrCreateSymbol(Sym);
264 Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this));
267 //===----------------------------------------------------------------------===//
268 // Section Management
269 //===----------------------------------------------------------------------===//
271 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
272 unsigned TypeAndAttributes,
273 unsigned Reserved2, SectionKind Kind,
274 const char *BeginSymName) {
275 // We unique sections by their segment/section pair. The returned section
276 // may not have the same flags as the requested section, if so this should be
277 // diagnosed by the client as an error.
279 // Form the name to look up.
280 SmallString<64> Name;
285 // Do the lookup, if we have a hit, return it.
286 MCSectionMachO *&Entry = MachOUniquingMap[Name];
290 MCSymbol *Begin = nullptr;
292 Begin = createTempSymbol(BeginSymName, false);
294 // Otherwise, return a new section.
295 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
296 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
299 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
301 if (const MCSymbol *Group = Section->getGroup())
302 GroupName = Group->getName();
304 unsigned UniqueID = Section->getUniqueID();
305 ELFUniquingMap.erase(
306 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
307 auto I = ELFUniquingMap.insert(std::make_pair(
308 ELFSectionKey{Name, GroupName, UniqueID},
311 StringRef CachedName = I->first.SectionName;
312 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
315 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
316 unsigned Flags, SectionKind K,
318 const MCSymbolELF *Group,
320 const MCSymbolELF *Associated) {
322 MCSymbol *&Sym = Symbols[Section];
323 // A section symbol can not redefine regular symbols. There may be multiple
324 // sections with the same name, in which case the first such section wins.
325 if (Sym && Sym->isDefined() &&
326 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
327 reportError(SMLoc(), "invalid symbol redefinition");
328 if (Sym && Sym->isUndefined()) {
329 R = cast<MCSymbolELF>(Sym);
331 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
332 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
336 R->setBinding(ELF::STB_LOCAL);
337 R->setType(ELF::STT_SECTION);
339 auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
340 Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated);
342 auto *F = new MCDataFragment();
343 Ret->getFragmentList().insert(Ret->begin(), F);
350 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
351 unsigned Flags, unsigned EntrySize,
352 const MCSymbolELF *Group,
353 const MCSectionELF *RelInfoSection) {
354 StringMap<bool>::iterator I;
356 std::tie(I, Inserted) =
357 RelSecNames.insert(std::make_pair(Name.str(), true));
359 return createELFSectionImpl(
360 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
361 true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
364 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
365 const Twine &Suffix, unsigned Type,
367 unsigned EntrySize) {
368 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
371 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
372 unsigned Flags, unsigned EntrySize,
373 const Twine &Group, unsigned UniqueID,
374 const MCSymbolELF *Associated) {
375 MCSymbolELF *GroupSym = nullptr;
376 if (!Group.isTriviallyEmpty() && !Group.str().empty())
377 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
379 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
383 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
384 unsigned Flags, unsigned EntrySize,
385 const MCSymbolELF *GroupSym,
387 const MCSymbolELF *Associated) {
388 StringRef Group = "";
390 Group = GroupSym->getName();
391 // Do the lookup, if we have a hit, return it.
392 auto IterBool = ELFUniquingMap.insert(
393 std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr));
394 auto &Entry = *IterBool.first;
395 if (!IterBool.second)
398 StringRef CachedName = Entry.first.SectionName;
401 if (Flags & ELF::SHF_ARM_PURECODE)
402 Kind = SectionKind::getExecuteOnly();
403 else if (Flags & ELF::SHF_EXECINSTR)
404 Kind = SectionKind::getText();
406 Kind = SectionKind::getReadOnly();
408 MCSectionELF *Result = createELFSectionImpl(
409 CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated);
410 Entry.second = Result;
414 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
415 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
416 SectionKind::getReadOnly(), 4, Group, ~0,
420 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
421 unsigned Characteristics,
423 StringRef COMDATSymName, int Selection,
425 const char *BeginSymName) {
426 MCSymbol *COMDATSymbol = nullptr;
427 if (!COMDATSymName.empty()) {
428 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
429 COMDATSymName = COMDATSymbol->getName();
433 // Do the lookup, if we have a hit, return it.
434 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
435 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
436 auto Iter = IterBool.first;
437 if (!IterBool.second)
440 MCSymbol *Begin = nullptr;
442 Begin = createTempSymbol(BeginSymName, false);
444 StringRef CachedName = Iter->first.SectionName;
445 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
446 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
448 Iter->second = Result;
452 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
453 unsigned Characteristics,
455 const char *BeginSymName) {
456 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
460 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
461 COFFSectionKey T{Section, "", 0, GenericSectionID};
462 auto Iter = COFFUniquingMap.find(T);
463 if (Iter == COFFUniquingMap.end())
468 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
469 const MCSymbol *KeySym,
471 // Return the normal section if we don't have to be associative or unique.
472 if (!KeySym && UniqueID == GenericSectionID)
475 // If we have a key symbol, make an associative section with the same name and
476 // kind as the normal section.
477 unsigned Characteristics = Sec->getCharacteristics();
479 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
480 return getCOFFSection(Sec->getSectionName(), Characteristics,
481 Sec->getKind(), KeySym->getName(),
482 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
485 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
489 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
490 const Twine &Group, unsigned UniqueID,
491 const char *BeginSymName) {
492 MCSymbolWasm *GroupSym = nullptr;
493 if (!Group.isTriviallyEmpty() && !Group.str().empty())
494 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
496 return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
499 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
500 const MCSymbolWasm *GroupSym,
502 const char *BeginSymName) {
503 StringRef Group = "";
505 Group = GroupSym->getName();
506 // Do the lookup, if we have a hit, return it.
507 auto IterBool = WasmUniquingMap.insert(
508 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
509 auto &Entry = *IterBool.first;
510 if (!IterBool.second)
513 StringRef CachedName = Entry.first.SectionName;
515 MCSymbol *Begin = nullptr;
517 Begin = createTempSymbol(BeginSymName, false);
519 MCSectionWasm *Result = new (WasmAllocator.Allocate())
520 MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
521 Entry.second = Result;
525 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
526 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
529 //===----------------------------------------------------------------------===//
531 //===----------------------------------------------------------------------===//
533 /// getDwarfFile - takes a file name an number to place in the dwarf file and
534 /// directory tables. If the file number has already been allocated it is an
535 /// error and zero is returned and the client reports the error, else the
536 /// allocated file number is returned. The file numbers may be in any order.
537 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
538 unsigned FileNumber, unsigned CUID) {
539 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
540 return Table.getFile(Directory, FileName, FileNumber);
543 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
544 /// currently is assigned and false otherwise.
545 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
546 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
547 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
550 return !MCDwarfFiles[FileNumber].Name.empty();
553 /// Remove empty sections from SectionStartEndSyms, to avoid generating
554 /// useless debug info for them.
555 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
556 SectionsForRanges.remove_if(
557 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
560 CodeViewContext &MCContext::getCVContext() {
561 if (!CVContext.get())
562 CVContext.reset(new CodeViewContext);
563 return *CVContext.get();
566 //===----------------------------------------------------------------------===//
568 //===----------------------------------------------------------------------===//
570 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
573 // If we have a source manager use it. Otherwise, try using the inline source
575 // If that fails, use the generic report_fatal_error().
577 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
578 else if (InlineSrcMgr)
579 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
581 report_fatal_error(Msg, false);
584 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
585 reportError(Loc, Msg);
587 // If we reached here, we are failing ungracefully. Run the interrupt handlers
588 // to make sure any special cleanups get done, in particular that we remove
589 // files registered with RemoveFileOnSignal.
590 sys::RunInterruptHandlers();