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/MCSymbolELF.h"
24 #include "llvm/Support/ELF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/SourceMgr.h"
34 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
35 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
37 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
38 Symbols(Allocator), UsedNames(Allocator),
39 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
40 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
41 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
42 AutoReset(DoAutoReset) {
44 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
46 CompilationDir.clear();
48 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
50 SecureLogUsed = false;
52 if (SrcMgr && SrcMgr->getNumBuffers())
54 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
57 MCContext::~MCContext() {
61 // NOTE: The symbols are all allocated out of a bump pointer allocator,
62 // we don't need to free them here.
64 // If the stream for the .secure_log_unique directive was created free it.
65 delete (raw_ostream *)SecureLog;
68 //===----------------------------------------------------------------------===//
69 // Module Lifetime Management
70 //===----------------------------------------------------------------------===//
72 void MCContext::reset() {
73 // Call the destructors so the fragments are freed
74 for (auto &I : ELFUniquingMap)
75 I.second->~MCSectionELF();
76 for (auto &I : COFFUniquingMap)
77 I.second->~MCSectionCOFF();
78 for (auto &I : MachOUniquingMap)
79 I.second->~MCSectionMachO();
85 CompilationDir.clear();
87 MCDwarfLineTablesCUMap.clear();
88 SectionsForRanges.clear();
89 MCGenDwarfLabelEntries.clear();
90 DwarfDebugFlags = StringRef();
91 DwarfCompileUnitID = 0;
92 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
94 MachOUniquingMap.clear();
95 ELFUniquingMap.clear();
96 COFFUniquingMap.clear();
99 AllowTemporaryLabels = true;
100 DwarfLocSeen = false;
101 GenDwarfForAssembly = false;
102 GenDwarfFileNumber = 0;
105 //===----------------------------------------------------------------------===//
106 // Symbol Manipulation
107 //===----------------------------------------------------------------------===//
109 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
110 SmallString<128> NameSV;
111 StringRef NameRef = Name.toStringRef(NameSV);
113 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
115 MCSymbol *&Sym = Symbols[NameRef];
117 Sym = createSymbol(NameRef, false, false);
122 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
123 MCSymbolELF *&Sym = SectionSymbols[&Section];
127 StringRef Name = Section.getSectionName();
129 MCSymbol *&OldSym = Symbols[Name];
130 if (OldSym && OldSym->isUndefined()) {
131 Sym = cast<MCSymbolELF>(OldSym);
135 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
136 Sym = new (*this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
144 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
146 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
147 "$frame_escape_" + Twine(Idx));
150 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
151 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
152 "$parent_frame_offset");
155 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
156 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
160 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
162 bool IsELF = MOFI && MOFI->getObjectFileType() == MCObjectFileInfo::IsELF;
164 return new (*this) MCSymbolELF(Name, IsTemporary);
165 return new (*this) MCSymbol(false, Name, IsTemporary);
168 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
170 if (IsTemporary && !UseNamesOnTempLabels)
171 return createSymbolImpl(nullptr, true);
173 // Determine whether this is an user writter assembler temporary or normal
176 if (AllowTemporaryLabels)
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) {
189 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
190 // of the string that is embedded in the UsedNames entry.
191 return createSymbolImpl(&*NameEntry.first, IsTemporary);
193 assert(IsTemporary && "Cannot rename non-temporary symbols");
196 llvm_unreachable("Infinite loop");
199 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
200 SmallString<128> NameSV;
201 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
202 return createSymbol(NameSV, AlwaysAddSuffix, true);
205 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
206 SmallString<128> NameSV;
207 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
208 return createSymbol(NameSV, true, false);
211 MCSymbol *MCContext::createTempSymbol() {
212 return createTempSymbol("tmp", true);
215 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
216 MCLabel *&Label = Instances[LocalLabelVal];
218 Label = new (*this) MCLabel(0);
219 return Label->incInstance();
222 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
223 MCLabel *&Label = Instances[LocalLabelVal];
225 Label = new (*this) MCLabel(0);
226 return Label->getInstance();
229 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
231 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
233 Sym = createTempSymbol();
237 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
238 unsigned Instance = NextInstance(LocalLabelVal);
239 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
242 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
244 unsigned Instance = GetInstance(LocalLabelVal);
247 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
250 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
251 SmallString<128> NameSV;
252 StringRef NameRef = Name.toStringRef(NameSV);
253 return Symbols.lookup(NameRef);
256 //===----------------------------------------------------------------------===//
257 // Section Management
258 //===----------------------------------------------------------------------===//
260 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
261 unsigned TypeAndAttributes,
262 unsigned Reserved2, SectionKind Kind,
263 const char *BeginSymName) {
265 // We unique sections by their segment/section pair. The returned section
266 // may not have the same flags as the requested section, if so this should be
267 // diagnosed by the client as an error.
269 // Form the name to look up.
270 SmallString<64> Name;
275 // Do the lookup, if we have a hit, return it.
276 MCSectionMachO *&Entry = MachOUniquingMap[Name];
280 MCSymbol *Begin = nullptr;
282 Begin = createTempSymbol(BeginSymName, false);
284 // Otherwise, return a new section.
285 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
286 Reserved2, Kind, Begin);
289 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
291 if (const MCSymbol *Group = Section->getGroup())
292 GroupName = Group->getName();
294 unsigned UniqueID = Section->getUniqueID();
295 ELFUniquingMap.erase(
296 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
297 auto I = ELFUniquingMap.insert(std::make_pair(
298 ELFSectionKey{Name, GroupName, UniqueID},
301 StringRef CachedName = I->first.SectionName;
302 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
305 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
306 unsigned Flags, unsigned EntrySize,
307 const MCSymbolELF *Group,
308 const MCSectionELF *Associated) {
309 StringMap<bool>::iterator I;
311 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
314 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
315 EntrySize, Group, true, nullptr, Associated);
318 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
319 unsigned Flags, unsigned EntrySize,
320 StringRef Group, unsigned UniqueID,
321 const char *BeginSymName) {
322 MCSymbolELF *GroupSym = nullptr;
324 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
326 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
327 BeginSymName, nullptr);
330 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
331 unsigned Flags, unsigned EntrySize,
332 const MCSymbolELF *GroupSym,
334 const char *BeginSymName,
335 const MCSectionELF *Associated) {
336 StringRef Group = "";
338 Group = GroupSym->getName();
339 // Do the lookup, if we have a hit, return it.
340 auto IterBool = ELFUniquingMap.insert(
341 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
342 auto &Entry = *IterBool.first;
343 if (!IterBool.second)
346 StringRef CachedName = Entry.first.SectionName;
349 if (Flags & ELF::SHF_EXECINSTR)
350 Kind = SectionKind::getText();
352 Kind = SectionKind::getReadOnly();
354 MCSymbol *Begin = nullptr;
356 Begin = createTempSymbol(BeginSymName, false);
358 MCSectionELF *Result =
359 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
360 GroupSym, UniqueID, Begin, Associated);
361 Entry.second = Result;
365 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
366 MCSectionELF *Result = new (*this)
367 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
368 Group, ~0, nullptr, nullptr);
372 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
373 unsigned Characteristics,
375 StringRef COMDATSymName, int Selection,
376 const char *BeginSymName) {
377 MCSymbol *COMDATSymbol = nullptr;
378 if (!COMDATSymName.empty()) {
379 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
380 COMDATSymName = COMDATSymbol->getName();
383 // Do the lookup, if we have a hit, return it.
384 COFFSectionKey T{Section, COMDATSymName, Selection};
385 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
386 auto Iter = IterBool.first;
387 if (!IterBool.second)
390 MCSymbol *Begin = nullptr;
392 Begin = createTempSymbol(BeginSymName, false);
394 StringRef CachedName = Iter->first.SectionName;
395 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
396 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
398 Iter->second = Result;
402 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
403 unsigned Characteristics,
405 const char *BeginSymName) {
406 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
409 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
410 COFFSectionKey T{Section, "", 0};
411 auto Iter = COFFUniquingMap.find(T);
412 if (Iter == COFFUniquingMap.end())
417 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
418 const MCSymbol *KeySym) {
419 // Return the normal section if we don't have to be associative.
423 // Make an associative section with the same name and kind as the normal
425 unsigned Characteristics =
426 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
427 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
429 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
432 //===----------------------------------------------------------------------===//
434 //===----------------------------------------------------------------------===//
436 /// getDwarfFile - takes a file name an number to place in the dwarf file and
437 /// directory tables. If the file number has already been allocated it is an
438 /// error and zero is returned and the client reports the error, else the
439 /// allocated file number is returned. The file numbers may be in any order.
440 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
441 unsigned FileNumber, unsigned CUID) {
442 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
443 return Table.getFile(Directory, FileName, FileNumber);
446 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
447 /// currently is assigned and false otherwise.
448 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
449 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
450 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
453 return !MCDwarfFiles[FileNumber].Name.empty();
456 /// Remove empty sections from SectionStartEndSyms, to avoid generating
457 /// useless debug info for them.
458 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
459 SectionsForRanges.remove_if(
460 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
463 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
464 // If we have a source manager and a location, use it. Otherwise just
465 // use the generic report_fatal_error().
466 if (!SrcMgr || Loc == SMLoc())
467 report_fatal_error(Msg, false);
469 // Use the source manager to print the message.
470 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
472 // If we reached here, we are failing ungracefully. Run the interrupt handlers
473 // to make sure any special cleanups get done, in particular that we remove
474 // files registered with RemoveFileOnSignal.
475 sys::RunInterruptHandlers();