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->getObjectFileType()) {
166 case MCObjectFileInfo::IsCOFF:
167 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
168 case MCObjectFileInfo::IsELF:
169 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
170 case MCObjectFileInfo::IsMachO:
171 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
174 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
178 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
180 if (IsTemporary && !UseNamesOnTempLabels)
181 return createSymbolImpl(nullptr, true);
183 // Determine whether this is an user writter assembler temporary or normal
186 if (AllowTemporaryLabels)
187 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
189 SmallString<128> NewName = Name;
190 bool AddSuffix = AlwaysAddSuffix;
191 unsigned &NextUniqueID = NextID[Name];
194 NewName.resize(Name.size());
195 raw_svector_ostream(NewName) << NextUniqueID++;
197 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
198 if (NameEntry.second) {
199 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
200 // of the string that is embedded in the UsedNames entry.
201 return createSymbolImpl(&*NameEntry.first, IsTemporary);
203 assert(IsTemporary && "Cannot rename non-temporary symbols");
206 llvm_unreachable("Infinite loop");
209 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
210 SmallString<128> NameSV;
211 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
212 return createSymbol(NameSV, AlwaysAddSuffix, true);
215 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
216 SmallString<128> NameSV;
217 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
218 return createSymbol(NameSV, true, false);
221 MCSymbol *MCContext::createTempSymbol() {
222 return createTempSymbol("tmp", true);
225 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
226 MCLabel *&Label = Instances[LocalLabelVal];
228 Label = new (*this) MCLabel(0);
229 return Label->incInstance();
232 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
233 MCLabel *&Label = Instances[LocalLabelVal];
235 Label = new (*this) MCLabel(0);
236 return Label->getInstance();
239 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
241 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
243 Sym = createTempSymbol();
247 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
248 unsigned Instance = NextInstance(LocalLabelVal);
249 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
252 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
254 unsigned Instance = GetInstance(LocalLabelVal);
257 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
260 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
261 SmallString<128> NameSV;
262 StringRef NameRef = Name.toStringRef(NameSV);
263 return Symbols.lookup(NameRef);
266 //===----------------------------------------------------------------------===//
267 // Section Management
268 //===----------------------------------------------------------------------===//
270 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
271 unsigned TypeAndAttributes,
272 unsigned Reserved2, SectionKind Kind,
273 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 (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
296 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::createELFRelSection(StringRef Name, unsigned Type,
316 unsigned Flags, unsigned EntrySize,
317 const MCSymbolELF *Group,
318 const MCSectionELF *Associated) {
319 StringMap<bool>::iterator I;
321 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
324 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
325 EntrySize, Group, true, nullptr, Associated);
328 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
329 unsigned Flags, unsigned EntrySize,
330 StringRef Group, unsigned UniqueID,
331 const char *BeginSymName) {
332 MCSymbolELF *GroupSym = nullptr;
334 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
336 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
337 BeginSymName, nullptr);
340 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
341 unsigned Flags, unsigned EntrySize,
342 const MCSymbolELF *GroupSym,
344 const char *BeginSymName,
345 const MCSectionELF *Associated) {
346 StringRef Group = "";
348 Group = GroupSym->getName();
349 // Do the lookup, if we have a hit, return it.
350 auto IterBool = ELFUniquingMap.insert(
351 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
352 auto &Entry = *IterBool.first;
353 if (!IterBool.second)
356 StringRef CachedName = Entry.first.SectionName;
359 if (Flags & ELF::SHF_EXECINSTR)
360 Kind = SectionKind::getText();
362 Kind = SectionKind::getReadOnly();
364 MCSymbol *Begin = nullptr;
366 Begin = createTempSymbol(BeginSymName, false);
368 MCSectionELF *Result =
369 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
370 GroupSym, UniqueID, Begin, Associated);
371 Entry.second = Result;
375 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
376 MCSectionELF *Result = new (*this)
377 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
378 Group, ~0, nullptr, nullptr);
382 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
383 unsigned Characteristics,
385 StringRef COMDATSymName, int Selection,
386 const char *BeginSymName) {
387 MCSymbol *COMDATSymbol = nullptr;
388 if (!COMDATSymName.empty()) {
389 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
390 COMDATSymName = COMDATSymbol->getName();
393 // Do the lookup, if we have a hit, return it.
394 COFFSectionKey T{Section, COMDATSymName, Selection};
395 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
396 auto Iter = IterBool.first;
397 if (!IterBool.second)
400 MCSymbol *Begin = nullptr;
402 Begin = createTempSymbol(BeginSymName, false);
404 StringRef CachedName = Iter->first.SectionName;
405 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
406 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
408 Iter->second = Result;
412 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
413 unsigned Characteristics,
415 const char *BeginSymName) {
416 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
419 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
420 COFFSectionKey T{Section, "", 0};
421 auto Iter = COFFUniquingMap.find(T);
422 if (Iter == COFFUniquingMap.end())
427 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
428 const MCSymbol *KeySym) {
429 // Return the normal section if we don't have to be associative.
433 // Make an associative section with the same name and kind as the normal
435 unsigned Characteristics =
436 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
437 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
439 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
442 //===----------------------------------------------------------------------===//
444 //===----------------------------------------------------------------------===//
446 /// getDwarfFile - takes a file name an number to place in the dwarf file and
447 /// directory tables. If the file number has already been allocated it is an
448 /// error and zero is returned and the client reports the error, else the
449 /// allocated file number is returned. The file numbers may be in any order.
450 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
451 unsigned FileNumber, unsigned CUID) {
452 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
453 return Table.getFile(Directory, FileName, FileNumber);
456 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
457 /// currently is assigned and false otherwise.
458 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
459 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
460 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
463 return !MCDwarfFiles[FileNumber].Name.empty();
466 /// Remove empty sections from SectionStartEndSyms, to avoid generating
467 /// useless debug info for them.
468 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
469 SectionsForRanges.remove_if(
470 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
473 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
474 // If we have a source manager and a location, use it. Otherwise just
475 // use the generic report_fatal_error().
476 if (!SrcMgr || Loc == SMLoc())
477 report_fatal_error(Msg, false);
479 // Use the source manager to print the message.
480 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
482 // If we reached here, we are failing ungracefully. Run the interrupt handlers
483 // to make sure any special cleanups get done, in particular that we remove
484 // files registered with RemoveFileOnSignal.
485 sys::RunInterruptHandlers();