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/MCAsmInfo.h"
14 #include "llvm/MC/MCDwarf.h"
15 #include "llvm/MC/MCLabel.h"
16 #include "llvm/MC/MCObjectFileInfo.h"
17 #include "llvm/MC/MCRegisterInfo.h"
18 #include "llvm/MC/MCSectionCOFF.h"
19 #include "llvm/MC/MCSectionELF.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/ELF.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/SourceMgr.h"
33 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
34 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
36 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
37 Symbols(Allocator), UsedNames(Allocator),
38 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
39 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
40 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
41 AutoReset(DoAutoReset) {
43 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
45 CompilationDir.clear();
47 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
49 SecureLogUsed = false;
51 if (SrcMgr && SrcMgr->getNumBuffers())
53 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
56 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() {
77 CompilationDir.clear();
79 MCDwarfLineTablesCUMap.clear();
80 SectionStartEndSyms.clear();
81 MCGenDwarfLabelEntries.clear();
82 DwarfDebugFlags = StringRef();
83 DwarfCompileUnitID = 0;
84 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
86 MachOUniquingMap.clear();
87 ELFUniquingMap.clear();
88 COFFUniquingMap.clear();
91 AllowTemporaryLabels = true;
93 GenDwarfForAssembly = false;
94 GenDwarfFileNumber = 0;
97 //===----------------------------------------------------------------------===//
98 // Symbol Manipulation
99 //===----------------------------------------------------------------------===//
101 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
102 SmallString<128> NameSV;
103 StringRef NameRef = Name.toStringRef(NameSV);
105 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
107 MCSymbol *&Sym = Symbols[NameRef];
109 Sym = CreateSymbol(NameRef, false);
114 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
115 MCSymbol *&Sym = SectionSymbols[&Section];
119 StringRef Name = Section.getSectionName();
121 MCSymbol *&OldSym = Symbols[Name];
122 if (OldSym && OldSym->isUndefined()) {
127 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
128 Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
136 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
138 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
139 "$frame_escape_" + Twine(Idx));
142 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
143 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
144 "$parent_frame_offset");
147 MCSymbol *MCContext::CreateSymbol(StringRef Name, bool AlwaysAddSuffix) {
148 // Determine whether this is an assembler temporary or normal label, if used.
149 bool IsTemporary = false;
150 if (AllowTemporaryLabels)
151 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
153 if (IsTemporary && AlwaysAddSuffix && !UseNamesOnTempLabels)
154 return new (*this) MCSymbol("", true);
156 SmallString<128> NewName = Name;
157 bool AddSuffix = AlwaysAddSuffix;
158 unsigned &NextUniqueID = NextID[Name];
161 NewName.resize(Name.size());
162 raw_svector_ostream(NewName) << NextUniqueID++;
164 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
165 if (NameEntry.second) {
166 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
167 // of the string that is embedded in the UsedNames entry.
169 new (*this) MCSymbol(NameEntry.first->getKey(), IsTemporary);
172 assert(IsTemporary && "Cannot rename non-temporary symbols");
175 llvm_unreachable("Infinite loop");
178 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
179 SmallString<128> NameSV;
180 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
181 return CreateSymbol(NameSV, AlwaysAddSuffix);
184 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
185 SmallString<128> NameSV;
186 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
187 return CreateSymbol(NameSV, true);
190 MCSymbol *MCContext::createTempSymbol() {
191 return createTempSymbol("tmp", true);
194 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
195 MCLabel *&Label = Instances[LocalLabelVal];
197 Label = new (*this) MCLabel(0);
198 return Label->incInstance();
201 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
202 MCLabel *&Label = Instances[LocalLabelVal];
204 Label = new (*this) MCLabel(0);
205 return Label->getInstance();
208 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
210 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
212 Sym = createTempSymbol();
216 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
217 unsigned Instance = NextInstance(LocalLabelVal);
218 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
221 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
223 unsigned Instance = GetInstance(LocalLabelVal);
226 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
229 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
230 SmallString<128> NameSV;
231 StringRef NameRef = Name.toStringRef(NameSV);
232 return Symbols.lookup(NameRef);
235 //===----------------------------------------------------------------------===//
236 // Section Management
237 //===----------------------------------------------------------------------===//
239 const MCSectionMachO *
240 MCContext::getMachOSection(StringRef Segment, StringRef Section,
241 unsigned TypeAndAttributes, unsigned Reserved2,
242 SectionKind Kind, const char *BeginSymName) {
244 // We unique sections by their segment/section pair. The returned section
245 // may not have the same flags as the requested section, if so this should be
246 // diagnosed by the client as an error.
248 // Form the name to look up.
249 SmallString<64> Name;
254 // Do the lookup, if we have a hit, return it.
255 const MCSectionMachO *&Entry = MachOUniquingMap[Name];
259 MCSymbol *Begin = nullptr;
261 Begin = createTempSymbol(BeginSymName, false);
263 // Otherwise, return a new section.
264 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
265 Reserved2, Kind, Begin);
268 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
270 if (const MCSymbol *Group = Section->getGroup())
271 GroupName = Group->getName();
273 unsigned UniqueID = Section->getUniqueID();
274 ELFUniquingMap.erase(
275 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
276 auto I = ELFUniquingMap.insert(std::make_pair(
277 ELFSectionKey{Name, GroupName, UniqueID},
280 StringRef CachedName = I->first.SectionName;
281 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
285 MCContext::createELFRelSection(StringRef Name, unsigned Type, unsigned Flags,
286 unsigned EntrySize, const MCSymbol *Group,
287 const MCSectionELF *Associated) {
288 StringMap<bool>::iterator I;
290 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
293 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
294 EntrySize, Group, true, nullptr, Associated);
297 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
298 unsigned Flags, unsigned EntrySize,
299 StringRef Group, unsigned UniqueID,
300 const char *BeginSymName) {
301 MCSymbol *GroupSym = nullptr;
303 GroupSym = getOrCreateSymbol(Group);
305 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
306 BeginSymName, nullptr);
309 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
310 unsigned Flags, unsigned EntrySize,
311 const MCSymbol *GroupSym,
313 const char *BeginSymName,
314 const MCSectionELF *Associated) {
315 StringRef Group = "";
317 Group = GroupSym->getName();
318 // Do the lookup, if we have a hit, return it.
319 auto IterBool = ELFUniquingMap.insert(
320 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
321 auto &Entry = *IterBool.first;
322 if (!IterBool.second)
325 StringRef CachedName = Entry.first.SectionName;
328 if (Flags & ELF::SHF_EXECINSTR)
329 Kind = SectionKind::getText();
331 Kind = SectionKind::getReadOnly();
333 MCSymbol *Begin = nullptr;
335 Begin = createTempSymbol(BeginSymName, false);
337 MCSectionELF *Result =
338 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
339 GroupSym, UniqueID, Begin, Associated);
340 Entry.second = Result;
344 const MCSectionELF *MCContext::createELFGroupSection(const MCSymbol *Group) {
345 MCSectionELF *Result = new (*this)
346 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
347 Group, ~0, nullptr, nullptr);
351 const MCSectionCOFF *
352 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
353 SectionKind Kind, StringRef COMDATSymName,
354 int Selection, const char *BeginSymName) {
355 MCSymbol *COMDATSymbol = nullptr;
356 if (!COMDATSymName.empty()) {
357 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
358 COMDATSymName = COMDATSymbol->getName();
361 // Do the lookup, if we have a hit, return it.
362 COFFSectionKey T{Section, COMDATSymName, Selection};
363 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
364 auto Iter = IterBool.first;
365 if (!IterBool.second)
368 MCSymbol *Begin = nullptr;
370 Begin = createTempSymbol(BeginSymName, false);
372 StringRef CachedName = Iter->first.SectionName;
373 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
374 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
376 Iter->second = Result;
380 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
381 unsigned Characteristics,
383 const char *BeginSymName) {
384 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
387 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
388 COFFSectionKey T{Section, "", 0};
389 auto Iter = COFFUniquingMap.find(T);
390 if (Iter == COFFUniquingMap.end())
395 const MCSectionCOFF *
396 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
397 const MCSymbol *KeySym) {
398 // Return the normal section if we don't have to be associative.
402 // Make an associative section with the same name and kind as the normal
404 unsigned Characteristics =
405 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
406 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
408 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
411 //===----------------------------------------------------------------------===//
413 //===----------------------------------------------------------------------===//
415 /// getDwarfFile - takes a file name an number to place in the dwarf file and
416 /// directory tables. If the file number has already been allocated it is an
417 /// error and zero is returned and the client reports the error, else the
418 /// allocated file number is returned. The file numbers may be in any order.
419 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
420 unsigned FileNumber, unsigned CUID) {
421 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
422 return Table.getFile(Directory, FileName, FileNumber);
425 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
426 /// currently is assigned and false otherwise.
427 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
428 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
429 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
432 return !MCDwarfFiles[FileNumber].Name.empty();
435 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
436 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
437 /// useless debug info for them.
438 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
439 MCContext &context = MCOS.getContext();
441 auto sec = SectionStartEndSyms.begin();
442 while (sec != SectionStartEndSyms.end()) {
443 assert(sec->second.first && "Start symbol must be set by now");
444 MCOS.SwitchSection(sec->first);
445 if (MCOS.mayHaveInstructions()) {
446 MCSymbol *SectionEndSym = context.createTempSymbol();
447 MCOS.EmitLabel(SectionEndSym);
448 sec->second.second = SectionEndSym;
451 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *>>::iterator
453 sec = SectionStartEndSyms.erase(to_erase);
458 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
459 // If we have a source manager and a location, use it. Otherwise just
460 // use the generic report_fatal_error().
461 if (!SrcMgr || Loc == SMLoc())
462 report_fatal_error(Msg, false);
464 // Use the source manager to print the message.
465 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
467 // If we reached here, we are failing ungracefully. Run the interrupt handlers
468 // to make sure any special cleanups get done, in particular that we remove
469 // files registered with RemoveFileOnSignal.
470 sys::RunInterruptHandlers();