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/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCLabel.h"
17 #include "llvm/MC/MCObjectFileInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCSectionCOFF.h"
20 #include "llvm/MC/MCSectionELF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbolCOFF.h"
24 #include "llvm/MC/MCSymbolELF.h"
25 #include "llvm/MC/MCSymbolMachO.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
36 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
37 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
39 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
40 Symbols(Allocator), UsedNames(Allocator),
41 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
42 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
43 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
44 AutoReset(DoAutoReset) {
46 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
48 CompilationDir.clear();
50 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
52 SecureLogUsed = false;
54 if (SrcMgr && SrcMgr->getNumBuffers())
56 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
59 MCContext::~MCContext() {
63 // NOTE: The symbols are all allocated out of a bump pointer allocator,
64 // we don't need to free them here.
66 // If the stream for the .secure_log_unique directive was created free it.
67 delete (raw_ostream *)SecureLog;
70 //===----------------------------------------------------------------------===//
71 // Module Lifetime Management
72 //===----------------------------------------------------------------------===//
74 void MCContext::reset() {
75 // Call the destructors so the fragments are freed
76 for (auto &I : ELFUniquingMap)
77 I.second->~MCSectionELF();
78 for (auto &I : COFFUniquingMap)
79 I.second->~MCSectionCOFF();
80 for (auto &I : MachOUniquingMap)
81 I.second->~MCSectionMachO();
87 CompilationDir.clear();
89 MCDwarfLineTablesCUMap.clear();
90 SectionsForRanges.clear();
91 MCGenDwarfLabelEntries.clear();
92 DwarfDebugFlags = StringRef();
93 DwarfCompileUnitID = 0;
94 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
96 MachOUniquingMap.clear();
97 ELFUniquingMap.clear();
98 COFFUniquingMap.clear();
101 AllowTemporaryLabels = true;
102 DwarfLocSeen = false;
103 GenDwarfForAssembly = false;
104 GenDwarfFileNumber = 0;
107 //===----------------------------------------------------------------------===//
108 // Symbol Manipulation
109 //===----------------------------------------------------------------------===//
111 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
112 SmallString<128> NameSV;
113 StringRef NameRef = Name.toStringRef(NameSV);
115 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
117 MCSymbol *&Sym = Symbols[NameRef];
119 Sym = createSymbol(NameRef, false, false);
124 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
125 MCSymbolELF *&Sym = SectionSymbols[&Section];
129 StringRef Name = Section.getSectionName();
131 MCSymbol *&OldSym = Symbols[Name];
132 if (OldSym && OldSym->isUndefined()) {
133 Sym = cast<MCSymbolELF>(OldSym);
137 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
138 Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
146 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
148 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
149 "$frame_escape_" + Twine(Idx));
152 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
153 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
154 "$parent_frame_offset");
157 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
158 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
162 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
165 switch (MOFI->getTargetTriple().getObjectFormat()) {
167 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
169 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
171 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
172 case Triple::UnknownObjectFormat:
176 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
180 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
182 if (CanBeUnnamed && !UseNamesOnTempLabels)
183 return createSymbolImpl(nullptr, true);
185 // Determine whether this is an user writter assembler temporary or normal
187 bool IsTemporary = CanBeUnnamed;
188 if (AllowTemporaryLabels && !IsTemporary)
189 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
191 SmallString<128> NewName = Name;
192 bool AddSuffix = AlwaysAddSuffix;
193 unsigned &NextUniqueID = NextID[Name];
196 NewName.resize(Name.size());
197 raw_svector_ostream(NewName) << NextUniqueID++;
199 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
200 if (NameEntry.second) {
201 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
202 // of the string that is embedded in the UsedNames entry.
203 return createSymbolImpl(&*NameEntry.first, IsTemporary);
205 assert(IsTemporary && "Cannot rename non-temporary symbols");
208 llvm_unreachable("Infinite loop");
211 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
213 SmallString<128> NameSV;
214 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
215 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
218 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
219 SmallString<128> NameSV;
220 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
221 return createSymbol(NameSV, true, false);
224 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
225 return createTempSymbol("tmp", true, CanBeUnnamed);
228 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
229 MCLabel *&Label = Instances[LocalLabelVal];
231 Label = new (*this) MCLabel(0);
232 return Label->incInstance();
235 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
236 MCLabel *&Label = Instances[LocalLabelVal];
238 Label = new (*this) MCLabel(0);
239 return Label->getInstance();
242 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
244 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
246 Sym = createTempSymbol(false);
250 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
251 unsigned Instance = NextInstance(LocalLabelVal);
252 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
255 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
257 unsigned Instance = GetInstance(LocalLabelVal);
260 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
263 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
264 SmallString<128> NameSV;
265 StringRef NameRef = Name.toStringRef(NameSV);
266 return Symbols.lookup(NameRef);
269 //===----------------------------------------------------------------------===//
270 // Section Management
271 //===----------------------------------------------------------------------===//
273 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
274 unsigned TypeAndAttributes,
275 unsigned Reserved2, SectionKind Kind,
276 const char *BeginSymName) {
278 // We unique sections by their segment/section pair. The returned section
279 // may not have the same flags as the requested section, if so this should be
280 // diagnosed by the client as an error.
282 // Form the name to look up.
283 SmallString<64> Name;
288 // Do the lookup, if we have a hit, return it.
289 MCSectionMachO *&Entry = MachOUniquingMap[Name];
293 MCSymbol *Begin = nullptr;
295 Begin = createTempSymbol(BeginSymName, false);
297 // Otherwise, return a new section.
298 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
299 Reserved2, Kind, Begin);
302 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
304 if (const MCSymbol *Group = Section->getGroup())
305 GroupName = Group->getName();
307 unsigned UniqueID = Section->getUniqueID();
308 ELFUniquingMap.erase(
309 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
310 auto I = ELFUniquingMap.insert(std::make_pair(
311 ELFSectionKey{Name, GroupName, UniqueID},
314 StringRef CachedName = I->first.SectionName;
315 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
318 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
319 unsigned Flags, unsigned EntrySize,
320 const MCSymbolELF *Group,
321 const MCSectionELF *Associated) {
322 StringMap<bool>::iterator I;
324 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
327 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
328 EntrySize, Group, true, nullptr, Associated);
331 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
332 unsigned Flags, unsigned EntrySize,
333 StringRef Group, unsigned UniqueID,
334 const char *BeginSymName) {
335 MCSymbolELF *GroupSym = nullptr;
337 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
339 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
340 BeginSymName, nullptr);
343 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
344 unsigned Flags, unsigned EntrySize,
345 const MCSymbolELF *GroupSym,
347 const char *BeginSymName,
348 const MCSectionELF *Associated) {
349 StringRef Group = "";
351 Group = GroupSym->getName();
352 // Do the lookup, if we have a hit, return it.
353 auto IterBool = ELFUniquingMap.insert(
354 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
355 auto &Entry = *IterBool.first;
356 if (!IterBool.second)
359 StringRef CachedName = Entry.first.SectionName;
362 if (Flags & ELF::SHF_EXECINSTR)
363 Kind = SectionKind::getText();
365 Kind = SectionKind::getReadOnly();
367 MCSymbol *Begin = nullptr;
369 Begin = createTempSymbol(BeginSymName, false);
371 MCSectionELF *Result =
372 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
373 GroupSym, UniqueID, Begin, Associated);
374 Entry.second = Result;
378 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
379 MCSectionELF *Result = new (*this)
380 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
381 Group, ~0, nullptr, nullptr);
385 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
386 unsigned Characteristics,
388 StringRef COMDATSymName, int Selection,
389 const char *BeginSymName) {
390 MCSymbol *COMDATSymbol = nullptr;
391 if (!COMDATSymName.empty()) {
392 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
393 COMDATSymName = COMDATSymbol->getName();
396 // Do the lookup, if we have a hit, return it.
397 COFFSectionKey T{Section, COMDATSymName, Selection};
398 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
399 auto Iter = IterBool.first;
400 if (!IterBool.second)
403 MCSymbol *Begin = nullptr;
405 Begin = createTempSymbol(BeginSymName, false);
407 StringRef CachedName = Iter->first.SectionName;
408 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
409 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
411 Iter->second = Result;
415 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
416 unsigned Characteristics,
418 const char *BeginSymName) {
419 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
422 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
423 COFFSectionKey T{Section, "", 0};
424 auto Iter = COFFUniquingMap.find(T);
425 if (Iter == COFFUniquingMap.end())
430 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
431 const MCSymbol *KeySym) {
432 // Return the normal section if we don't have to be associative.
436 // Make an associative section with the same name and kind as the normal
438 unsigned Characteristics =
439 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
440 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
442 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
445 //===----------------------------------------------------------------------===//
447 //===----------------------------------------------------------------------===//
449 /// getDwarfFile - takes a file name an number to place in the dwarf file and
450 /// directory tables. If the file number has already been allocated it is an
451 /// error and zero is returned and the client reports the error, else the
452 /// allocated file number is returned. The file numbers may be in any order.
453 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
454 unsigned FileNumber, unsigned CUID) {
455 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
456 return Table.getFile(Directory, FileName, FileNumber);
459 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
460 /// currently is assigned and false otherwise.
461 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
462 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
463 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
466 return !MCDwarfFiles[FileNumber].Name.empty();
469 /// Remove empty sections from SectionStartEndSyms, to avoid generating
470 /// useless debug info for them.
471 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
472 SectionsForRanges.remove_if(
473 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
476 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
477 // If we have a source manager and a location, use it. Otherwise just
478 // use the generic report_fatal_error().
479 if (!SrcMgr || Loc == SMLoc())
480 report_fatal_error(Msg, false);
482 // Use the source manager to print the message.
483 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
485 // If we reached here, we are failing ungracefully. Run the interrupt handlers
486 // to make sure any special cleanups get done, in particular that we remove
487 // files registered with RemoveFileOnSignal.
488 sys::RunInterruptHandlers();