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);
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) {
169 // Determine whether this is an assembler temporary or normal label, if used.
170 bool IsTemporary = false;
171 if (AllowTemporaryLabels)
172 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
174 if (IsTemporary && AlwaysAddSuffix && !UseNamesOnTempLabels)
175 return createSymbolImpl(nullptr, true);
177 SmallString<128> NewName = Name;
178 bool AddSuffix = AlwaysAddSuffix;
179 unsigned &NextUniqueID = NextID[Name];
182 NewName.resize(Name.size());
183 raw_svector_ostream(NewName) << NextUniqueID++;
185 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
186 if (NameEntry.second) {
187 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
188 // of the string that is embedded in the UsedNames entry.
189 return createSymbolImpl(&*NameEntry.first, IsTemporary);
191 assert(IsTemporary && "Cannot rename non-temporary symbols");
194 llvm_unreachable("Infinite loop");
197 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
198 SmallString<128> NameSV;
199 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
200 return CreateSymbol(NameSV, AlwaysAddSuffix);
203 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
204 SmallString<128> NameSV;
205 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
206 return CreateSymbol(NameSV, true);
209 MCSymbol *MCContext::createTempSymbol() {
210 return createTempSymbol("tmp", true);
213 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
214 MCLabel *&Label = Instances[LocalLabelVal];
216 Label = new (*this) MCLabel(0);
217 return Label->incInstance();
220 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
221 MCLabel *&Label = Instances[LocalLabelVal];
223 Label = new (*this) MCLabel(0);
224 return Label->getInstance();
227 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
229 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
231 Sym = createTempSymbol();
235 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
236 unsigned Instance = NextInstance(LocalLabelVal);
237 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
240 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
242 unsigned Instance = GetInstance(LocalLabelVal);
245 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
248 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
249 SmallString<128> NameSV;
250 StringRef NameRef = Name.toStringRef(NameSV);
251 return Symbols.lookup(NameRef);
254 //===----------------------------------------------------------------------===//
255 // Section Management
256 //===----------------------------------------------------------------------===//
258 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
259 unsigned TypeAndAttributes,
260 unsigned Reserved2, SectionKind Kind,
261 const char *BeginSymName) {
263 // We unique sections by their segment/section pair. The returned section
264 // may not have the same flags as the requested section, if so this should be
265 // diagnosed by the client as an error.
267 // Form the name to look up.
268 SmallString<64> Name;
273 // Do the lookup, if we have a hit, return it.
274 MCSectionMachO *&Entry = MachOUniquingMap[Name];
278 MCSymbol *Begin = nullptr;
280 Begin = createTempSymbol(BeginSymName, false);
282 // Otherwise, return a new section.
283 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
284 Reserved2, Kind, Begin);
287 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
289 if (const MCSymbol *Group = Section->getGroup())
290 GroupName = Group->getName();
292 unsigned UniqueID = Section->getUniqueID();
293 ELFUniquingMap.erase(
294 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
295 auto I = ELFUniquingMap.insert(std::make_pair(
296 ELFSectionKey{Name, GroupName, UniqueID},
299 StringRef CachedName = I->first.SectionName;
300 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
303 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
304 unsigned Flags, unsigned EntrySize,
305 const MCSymbol *Group,
306 const MCSectionELF *Associated) {
307 StringMap<bool>::iterator I;
309 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
312 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
313 EntrySize, Group, true, nullptr, Associated);
316 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
317 unsigned Flags, unsigned EntrySize,
318 StringRef Group, unsigned UniqueID,
319 const char *BeginSymName) {
320 MCSymbol *GroupSym = nullptr;
322 GroupSym = getOrCreateSymbol(Group);
324 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
325 BeginSymName, nullptr);
328 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
329 unsigned Flags, unsigned EntrySize,
330 const MCSymbol *GroupSym,
332 const char *BeginSymName,
333 const MCSectionELF *Associated) {
334 StringRef Group = "";
336 Group = GroupSym->getName();
337 // Do the lookup, if we have a hit, return it.
338 auto IterBool = ELFUniquingMap.insert(
339 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
340 auto &Entry = *IterBool.first;
341 if (!IterBool.second)
344 StringRef CachedName = Entry.first.SectionName;
347 if (Flags & ELF::SHF_EXECINSTR)
348 Kind = SectionKind::getText();
350 Kind = SectionKind::getReadOnly();
352 MCSymbol *Begin = nullptr;
354 Begin = createTempSymbol(BeginSymName, false);
356 MCSectionELF *Result =
357 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
358 GroupSym, UniqueID, Begin, Associated);
359 Entry.second = Result;
363 MCSectionELF *MCContext::createELFGroupSection(const MCSymbol *Group) {
364 MCSectionELF *Result = new (*this)
365 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
366 Group, ~0, nullptr, nullptr);
370 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
371 unsigned Characteristics,
373 StringRef COMDATSymName, int Selection,
374 const char *BeginSymName) {
375 MCSymbol *COMDATSymbol = nullptr;
376 if (!COMDATSymName.empty()) {
377 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
378 COMDATSymName = COMDATSymbol->getName();
381 // Do the lookup, if we have a hit, return it.
382 COFFSectionKey T{Section, COMDATSymName, Selection};
383 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
384 auto Iter = IterBool.first;
385 if (!IterBool.second)
388 MCSymbol *Begin = nullptr;
390 Begin = createTempSymbol(BeginSymName, false);
392 StringRef CachedName = Iter->first.SectionName;
393 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
394 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
396 Iter->second = Result;
400 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
401 unsigned Characteristics,
403 const char *BeginSymName) {
404 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
407 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
408 COFFSectionKey T{Section, "", 0};
409 auto Iter = COFFUniquingMap.find(T);
410 if (Iter == COFFUniquingMap.end())
415 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
416 const MCSymbol *KeySym) {
417 // Return the normal section if we don't have to be associative.
421 // Make an associative section with the same name and kind as the normal
423 unsigned Characteristics =
424 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
425 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
427 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
430 //===----------------------------------------------------------------------===//
432 //===----------------------------------------------------------------------===//
434 /// getDwarfFile - takes a file name an number to place in the dwarf file and
435 /// directory tables. If the file number has already been allocated it is an
436 /// error and zero is returned and the client reports the error, else the
437 /// allocated file number is returned. The file numbers may be in any order.
438 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
439 unsigned FileNumber, unsigned CUID) {
440 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
441 return Table.getFile(Directory, FileName, FileNumber);
444 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
445 /// currently is assigned and false otherwise.
446 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
447 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
448 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
451 return !MCDwarfFiles[FileNumber].Name.empty();
454 /// Remove empty sections from SectionStartEndSyms, to avoid generating
455 /// useless debug info for them.
456 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
457 SectionsForRanges.remove_if(
458 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
461 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
462 // If we have a source manager and a location, use it. Otherwise just
463 // use the generic report_fatal_error().
464 if (!SrcMgr || Loc == SMLoc())
465 report_fatal_error(Msg, false);
467 // Use the source manager to print the message.
468 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
470 // If we reached here, we are failing ungracefully. Run the interrupt handlers
471 // to make sure any special cleanups get done, in particular that we remove
472 // files registered with RemoveFileOnSignal.
473 sys::RunInterruptHandlers();