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,
136 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
137 "$frame_escape_" + Twine(Idx));
140 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
141 // Determine whether this is an assembler temporary or normal label, if used.
142 bool isTemporary = false;
143 if (AllowTemporaryLabels)
144 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
146 auto NameEntry = UsedNames.insert(std::make_pair(Name, true));
147 if (!NameEntry.second) {
148 assert(isTemporary && "Cannot rename non-temporary symbols");
149 SmallString<128> NewName = Name;
151 NewName.resize(Name.size());
152 raw_svector_ostream(NewName) << NextUniqueID++;
153 NameEntry = UsedNames.insert(std::make_pair(NewName, true));
154 } while (!NameEntry.second);
157 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
158 // to the copy of the string that is embedded in the UsedNames entry.
160 new (*this) MCSymbol(NameEntry.first->getKey(), isTemporary);
165 MCSymbol *MCContext::createTempSymbol(const Twine &Name) {
166 SmallString<128> NameSV;
167 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
168 return CreateSymbol(NameSV);
171 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
172 SmallString<128> NameSV;
173 return GetOrCreateSymbol(Name.toStringRef(NameSV));
176 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
177 SmallString<128> NameSV;
178 raw_svector_ostream(NameSV)
179 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
180 return CreateSymbol(NameSV);
183 MCSymbol *MCContext::CreateTempSymbol() {
184 SmallString<128> NameSV;
185 raw_svector_ostream(NameSV)
186 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
187 return CreateSymbol(NameSV);
190 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
191 MCLabel *&Label = Instances[LocalLabelVal];
193 Label = new (*this) MCLabel(0);
194 return Label->incInstance();
197 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
198 MCLabel *&Label = Instances[LocalLabelVal];
200 Label = new (*this) MCLabel(0);
201 return Label->getInstance();
204 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
206 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
208 Sym = CreateTempSymbol();
212 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
213 unsigned Instance = NextInstance(LocalLabelVal);
214 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
217 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
219 unsigned Instance = GetInstance(LocalLabelVal);
222 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
225 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
226 return Symbols.lookup(Name);
229 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
230 SmallString<128> NameSV;
231 Name.toVector(NameSV);
232 return LookupSymbol(NameSV.str());
235 //===----------------------------------------------------------------------===//
236 // Section Management
237 //===----------------------------------------------------------------------===//
239 const MCSectionMachO *MCContext::
240 getMachOSection(StringRef Segment, StringRef Section,
241 unsigned TypeAndAttributes,
242 unsigned Reserved2, SectionKind Kind) {
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.str()];
256 if (Entry) return Entry;
258 // Otherwise, return a new section.
259 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
263 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
265 return getELFSection(Section, Type, Flags, 0, "");
268 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
270 if (const MCSymbol *Group = Section->getGroup())
271 GroupName = Group->getName();
273 ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
275 ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
277 StringRef CachedName = I->first.first;
278 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
281 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
282 unsigned Flags, unsigned EntrySize,
283 StringRef Group, bool Unique) {
284 // Do the lookup, if we have a hit, return it.
285 auto IterBool = ELFUniquingMap.insert(
286 std::make_pair(SectionGroupPair(Section, Group), nullptr));
287 auto &Entry = *IterBool.first;
288 if (!IterBool.second && !Unique)
291 MCSymbol *GroupSym = nullptr;
293 GroupSym = GetOrCreateSymbol(Group);
295 StringRef CachedName = Entry.first.first;
298 if (Flags & ELF::SHF_EXECINSTR)
299 Kind = SectionKind::getText();
301 Kind = SectionKind::getReadOnly();
303 MCSectionELF *Result = new (*this)
304 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, Unique);
306 Entry.second = Result;
310 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
311 unsigned Flags, unsigned EntrySize,
313 return getELFSection(Section, Type, Flags, EntrySize, Group, false);
316 const MCSectionELF *MCContext::CreateELFGroupSection() {
317 MCSectionELF *Result =
318 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
319 SectionKind::getReadOnly(), 4, nullptr, false);
323 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
324 unsigned Characteristics,
326 StringRef COMDATSymName,
328 // Do the lookup, if we have a hit, return it.
330 SectionGroupTriple T(Section, COMDATSymName, Selection);
331 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
332 auto Iter = IterBool.first;
333 if (!IterBool.second)
336 MCSymbol *COMDATSymbol = nullptr;
337 if (!COMDATSymName.empty())
338 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
340 StringRef CachedName = std::get<0>(Iter->first);
341 MCSectionCOFF *Result = new (*this)
342 MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
344 Iter->second = Result;
348 const MCSectionCOFF *
349 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
351 return getCOFFSection(Section, Characteristics, Kind, "", 0);
354 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
355 SectionGroupTriple T(Section, "", 0);
356 auto Iter = COFFUniquingMap.find(T);
357 if (Iter == COFFUniquingMap.end())
362 const MCSectionCOFF *
363 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
364 const MCSymbol *KeySym) {
365 // Return the normal section if we don't have to be associative.
369 // Make an associative section with the same name and kind as the normal
371 unsigned Characteristics =
372 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
373 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
375 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
378 //===----------------------------------------------------------------------===//
380 //===----------------------------------------------------------------------===//
382 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
383 /// directory tables. If the file number has already been allocated it is an
384 /// error and zero is returned and the client reports the error, else the
385 /// allocated file number is returned. The file numbers may be in any order.
386 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
387 unsigned FileNumber, unsigned CUID) {
388 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
389 return Table.getFile(Directory, FileName, FileNumber);
392 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
393 /// currently is assigned and false otherwise.
394 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
395 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
396 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
399 return !MCDwarfFiles[FileNumber].Name.empty();
402 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
403 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
404 /// useless debug info for them.
405 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
406 MCContext &context = MCOS.getContext();
408 auto sec = SectionStartEndSyms.begin();
409 while (sec != SectionStartEndSyms.end()) {
410 assert(sec->second.first && "Start symbol must be set by now");
411 MCOS.SwitchSection(sec->first);
412 if (MCOS.mayHaveInstructions()) {
413 MCSymbol *SectionEndSym = context.CreateTempSymbol();
414 MCOS.EmitLabel(SectionEndSym);
415 sec->second.second = SectionEndSym;
418 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
420 sec = SectionStartEndSyms.erase(to_erase);
425 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
426 // If we have a source manager and a location, use it. Otherwise just
427 // use the generic report_fatal_error().
428 if (!SrcMgr || Loc == SMLoc())
429 report_fatal_error(Msg, false);
431 // Use the source manager to print the message.
432 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
434 // If we reached here, we are failing ungracefully. Run the interrupt handlers
435 // to make sure any special cleanups get done, in particular that we remove
436 // files registered with RemoveFileOnSignal.
437 sys::RunInterruptHandlers();