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), NextUniqueID(0),
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(StringRef Name) {
102 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
104 MCSymbol *&Sym = Symbols[Name];
107 Sym = CreateSymbol(Name);
112 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
113 MCSymbol *&Sym = SectionSymbols[&Section];
117 StringRef Name = Section.getSectionName();
119 MCSymbol *&OldSym = Symbols[Name];
120 if (OldSym && OldSym->isUndefined()) {
125 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
126 Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
134 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName) {
135 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
136 "frameallocation_" + FuncName);
139 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
140 // Determine whether this is an assembler temporary or normal label, if used.
141 bool isTemporary = false;
142 if (AllowTemporaryLabels)
143 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
145 auto NameEntry = UsedNames.insert(std::make_pair(Name, true));
146 if (!NameEntry.second) {
147 assert(isTemporary && "Cannot rename non-temporary symbols");
148 SmallString<128> NewName = Name;
150 NewName.resize(Name.size());
151 raw_svector_ostream(NewName) << NextUniqueID++;
152 NameEntry = UsedNames.insert(std::make_pair(NewName, true));
153 } while (!NameEntry.second);
156 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
157 // to the copy of the string that is embedded in the UsedNames entry.
159 new (*this) MCSymbol(NameEntry.first->getKey(), isTemporary);
164 MCSymbol *MCContext::createTempSymbol(const Twine &Name) {
165 SmallString<128> NameSV;
166 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
167 return CreateSymbol(NameSV);
170 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
171 SmallString<128> NameSV;
172 return GetOrCreateSymbol(Name.toStringRef(NameSV));
175 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
176 SmallString<128> NameSV;
177 raw_svector_ostream(NameSV)
178 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
179 return CreateSymbol(NameSV);
182 MCSymbol *MCContext::CreateTempSymbol() {
183 SmallString<128> NameSV;
184 raw_svector_ostream(NameSV)
185 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
186 return CreateSymbol(NameSV);
189 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
190 MCLabel *&Label = Instances[LocalLabelVal];
192 Label = new (*this) MCLabel(0);
193 return Label->incInstance();
196 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
197 MCLabel *&Label = Instances[LocalLabelVal];
199 Label = new (*this) MCLabel(0);
200 return Label->getInstance();
203 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
205 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
207 Sym = CreateTempSymbol();
211 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
212 unsigned Instance = NextInstance(LocalLabelVal);
213 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
216 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
218 unsigned Instance = GetInstance(LocalLabelVal);
221 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
224 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
225 return Symbols.lookup(Name);
228 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
229 SmallString<128> NameSV;
230 Name.toVector(NameSV);
231 return LookupSymbol(NameSV.str());
234 //===----------------------------------------------------------------------===//
235 // Section Management
236 //===----------------------------------------------------------------------===//
238 const MCSectionMachO *MCContext::
239 getMachOSection(StringRef Segment, StringRef Section,
240 unsigned TypeAndAttributes,
241 unsigned Reserved2, SectionKind Kind) {
243 // We unique sections by their segment/section pair. The returned section
244 // may not have the same flags as the requested section, if so this should be
245 // diagnosed by the client as an error.
247 // Form the name to look up.
248 SmallString<64> Name;
253 // Do the lookup, if we have a hit, return it.
254 const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
255 if (Entry) return Entry;
257 // Otherwise, return a new section.
258 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
262 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
264 return getELFSection(Section, Type, Flags, 0, "");
267 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
269 if (const MCSymbol *Group = Section->getGroup())
270 GroupName = Group->getName();
272 ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
274 ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
276 StringRef CachedName = I->first.first;
277 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
280 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
281 unsigned Flags, unsigned EntrySize,
282 StringRef Group, bool Unique) {
283 // Do the lookup, if we have a hit, return it.
284 auto IterBool = ELFUniquingMap.insert(
285 std::make_pair(SectionGroupPair(Section, Group), nullptr));
286 auto &Entry = *IterBool.first;
287 if (!IterBool.second && !Unique)
290 MCSymbol *GroupSym = nullptr;
292 GroupSym = GetOrCreateSymbol(Group);
294 StringRef CachedName = Entry.first.first;
297 if (Flags & ELF::SHF_EXECINSTR)
298 Kind = SectionKind::getText();
300 Kind = SectionKind::getReadOnly();
302 MCSectionELF *Result = new (*this)
303 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, Unique);
305 Entry.second = Result;
309 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
310 unsigned Flags, unsigned EntrySize,
312 return getELFSection(Section, Type, Flags, EntrySize, Group, false);
315 const MCSectionELF *MCContext::CreateELFGroupSection() {
316 MCSectionELF *Result =
317 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
318 SectionKind::getReadOnly(), 4, nullptr, false);
322 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
323 unsigned Characteristics,
325 StringRef COMDATSymName,
327 // Do the lookup, if we have a hit, return it.
329 SectionGroupTriple T(Section, COMDATSymName, Selection);
330 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
331 auto Iter = IterBool.first;
332 if (!IterBool.second)
335 MCSymbol *COMDATSymbol = nullptr;
336 if (!COMDATSymName.empty())
337 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
339 StringRef CachedName = std::get<0>(Iter->first);
340 MCSectionCOFF *Result = new (*this)
341 MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
343 Iter->second = Result;
347 const MCSectionCOFF *
348 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
350 return getCOFFSection(Section, Characteristics, Kind, "", 0);
353 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
354 SectionGroupTriple T(Section, "", 0);
355 auto Iter = COFFUniquingMap.find(T);
356 if (Iter == COFFUniquingMap.end())
361 const MCSectionCOFF *
362 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
363 const MCSymbol *KeySym) {
364 // Return the normal section if we don't have to be associative.
368 // Make an associative section with the same name and kind as the normal
370 unsigned Characteristics =
371 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
372 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
374 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
377 //===----------------------------------------------------------------------===//
379 //===----------------------------------------------------------------------===//
381 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
382 /// directory tables. If the file number has already been allocated it is an
383 /// error and zero is returned and the client reports the error, else the
384 /// allocated file number is returned. The file numbers may be in any order.
385 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
386 unsigned FileNumber, unsigned CUID) {
387 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
388 return Table.getFile(Directory, FileName, FileNumber);
391 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
392 /// currently is assigned and false otherwise.
393 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
394 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
395 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
398 return !MCDwarfFiles[FileNumber].Name.empty();
401 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
402 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
403 /// useless debug info for them.
404 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
405 MCContext &context = MCOS.getContext();
407 auto sec = SectionStartEndSyms.begin();
408 while (sec != SectionStartEndSyms.end()) {
409 assert(sec->second.first && "Start symbol must be set by now");
410 MCOS.SwitchSection(sec->first);
411 if (MCOS.mayHaveInstructions()) {
412 MCSymbol *SectionEndSym = context.CreateTempSymbol();
413 MCOS.EmitLabel(SectionEndSym);
414 sec->second.second = SectionEndSym;
417 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
419 sec = SectionStartEndSyms.erase(to_erase);
424 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
425 // If we have a source manager and a location, use it. Otherwise just
426 // use the generic report_fatal_error().
427 if (!SrcMgr || Loc == SMLoc())
428 report_fatal_error(Msg, false);
430 // Use the source manager to print the message.
431 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
433 // If we reached here, we are failing ungracefully. Run the interrupt handlers
434 // to make sure any special cleanups get done, in particular that we remove
435 // files registered with RemoveFileOnSignal.
436 sys::RunInterruptHandlers();