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 SmallString<128> NewName = Name;
154 bool AddSuffix = AlwaysAddSuffix;
155 unsigned &NextUniqueID = NextID[Name];
158 NewName.resize(Name.size());
159 raw_svector_ostream(NewName) << NextUniqueID++;
161 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
162 if (NameEntry.second) {
163 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
164 // of the string that is embedded in the UsedNames entry.
166 new (*this) MCSymbol(NameEntry.first->getKey(), IsTemporary);
169 assert(IsTemporary && "Cannot rename non-temporary symbols");
172 llvm_unreachable("Infinite loop");
175 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
176 SmallString<128> NameSV;
177 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
178 return CreateSymbol(NameSV, AlwaysAddSuffix);
181 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
182 SmallString<128> NameSV;
183 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
184 return CreateSymbol(NameSV, true);
187 MCSymbol *MCContext::CreateTempSymbol() {
188 return createTempSymbol("tmp", true);
191 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
192 MCLabel *&Label = Instances[LocalLabelVal];
194 Label = new (*this) MCLabel(0);
195 return Label->incInstance();
198 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
199 MCLabel *&Label = Instances[LocalLabelVal];
201 Label = new (*this) MCLabel(0);
202 return Label->getInstance();
205 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
207 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
209 Sym = CreateTempSymbol();
213 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
214 unsigned Instance = NextInstance(LocalLabelVal);
215 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
218 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
220 unsigned Instance = GetInstance(LocalLabelVal);
223 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
226 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
227 SmallString<128> NameSV;
228 StringRef NameRef = Name.toStringRef(NameSV);
229 return Symbols.lookup(NameRef);
232 //===----------------------------------------------------------------------===//
233 // Section Management
234 //===----------------------------------------------------------------------===//
236 const MCSectionMachO *
237 MCContext::getMachOSection(StringRef Segment, StringRef Section,
238 unsigned TypeAndAttributes, unsigned Reserved2,
239 SectionKind Kind, const char *BeginSymName) {
241 // We unique sections by their segment/section pair. The returned section
242 // may not have the same flags as the requested section, if so this should be
243 // diagnosed by the client as an error.
245 // Form the name to look up.
246 SmallString<64> Name;
251 // Do the lookup, if we have a hit, return it.
252 const MCSectionMachO *&Entry = MachOUniquingMap[Name];
256 MCSymbol *Begin = nullptr;
258 Begin = createTempSymbol(BeginSymName, false);
260 // Otherwise, return a new section.
261 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
262 Reserved2, Kind, Begin);
265 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
267 if (const MCSymbol *Group = Section->getGroup())
268 GroupName = Group->getName();
270 unsigned UniqueID = Section->getUniqueID();
271 ELFUniquingMap.erase(
272 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
273 auto I = ELFUniquingMap.insert(std::make_pair(
274 ELFSectionKey{Name, GroupName, UniqueID},
276 StringRef CachedName = I->first.SectionName;
277 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
281 MCContext::createELFRelSection(StringRef Name, unsigned Type, unsigned Flags,
282 unsigned EntrySize, const MCSymbol *Group,
283 const MCSectionELF *Associated) {
284 StringMap<bool>::iterator I;
286 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
289 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
290 EntrySize, Group, true, nullptr, Associated);
293 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
294 unsigned Flags, unsigned EntrySize,
295 StringRef Group, unsigned UniqueID,
296 const char *BeginSymName) {
297 MCSymbol *GroupSym = nullptr;
298 if (!Group.empty()) {
299 GroupSym = GetOrCreateSymbol(Group);
300 Group = GroupSym->getName();
303 // Do the lookup, if we have a hit, return it.
304 auto IterBool = ELFUniquingMap.insert(
305 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
306 auto &Entry = *IterBool.first;
307 if (!IterBool.second)
310 StringRef CachedName = Entry.first.SectionName;
313 if (Flags & ELF::SHF_EXECINSTR)
314 Kind = SectionKind::getText();
316 Kind = SectionKind::getReadOnly();
318 MCSymbol *Begin = nullptr;
320 Begin = createTempSymbol(BeginSymName, false);
322 MCSectionELF *Result =
323 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
324 GroupSym, UniqueID, Begin, nullptr);
325 Entry.second = Result;
329 const MCSectionELF *MCContext::CreateELFGroupSection() {
330 MCSectionELF *Result = new (*this)
331 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
332 nullptr, ~0, nullptr, nullptr);
336 const MCSectionCOFF *
337 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
338 SectionKind Kind, StringRef COMDATSymName,
339 int Selection, const char *BeginSymName) {
340 MCSymbol *COMDATSymbol = nullptr;
341 if (!COMDATSymName.empty()) {
342 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
343 COMDATSymName = COMDATSymbol->getName();
346 // Do the lookup, if we have a hit, return it.
347 COFFSectionKey T{Section, COMDATSymName, Selection};
348 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
349 auto Iter = IterBool.first;
350 if (!IterBool.second)
353 MCSymbol *Begin = nullptr;
355 Begin = createTempSymbol(BeginSymName, false);
357 StringRef CachedName = Iter->first.SectionName;
358 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
359 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
361 Iter->second = Result;
365 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
366 unsigned Characteristics,
368 const char *BeginSymName) {
369 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
372 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
373 COFFSectionKey T{Section, "", 0};
374 auto Iter = COFFUniquingMap.find(T);
375 if (Iter == COFFUniquingMap.end())
380 const MCSectionCOFF *
381 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
382 const MCSymbol *KeySym) {
383 // Return the normal section if we don't have to be associative.
387 // Make an associative section with the same name and kind as the normal
389 unsigned Characteristics =
390 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
391 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
393 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
396 //===----------------------------------------------------------------------===//
398 //===----------------------------------------------------------------------===//
400 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
401 /// directory tables. If the file number has already been allocated it is an
402 /// error and zero is returned and the client reports the error, else the
403 /// allocated file number is returned. The file numbers may be in any order.
404 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
405 unsigned FileNumber, unsigned CUID) {
406 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
407 return Table.getFile(Directory, FileName, FileNumber);
410 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
411 /// currently is assigned and false otherwise.
412 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
413 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
414 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
417 return !MCDwarfFiles[FileNumber].Name.empty();
420 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
421 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
422 /// useless debug info for them.
423 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
424 MCContext &context = MCOS.getContext();
426 auto sec = SectionStartEndSyms.begin();
427 while (sec != SectionStartEndSyms.end()) {
428 assert(sec->second.first && "Start symbol must be set by now");
429 MCOS.SwitchSection(sec->first);
430 if (MCOS.mayHaveInstructions()) {
431 MCSymbol *SectionEndSym = context.CreateTempSymbol();
432 MCOS.EmitLabel(SectionEndSym);
433 sec->second.second = SectionEndSym;
436 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
438 sec = SectionStartEndSyms.erase(to_erase);
443 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
444 // If we have a source manager and a location, use it. Otherwise just
445 // use the generic report_fatal_error().
446 if (!SrcMgr || Loc == SMLoc())
447 report_fatal_error(Msg, false);
449 // Use the source manager to print the message.
450 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
452 // If we reached here, we are failing ungracefully. Run the interrupt handlers
453 // to make sure any special cleanups get done, in particular that we remove
454 // files registered with RemoveFileOnSignal.
455 sys::RunInterruptHandlers();