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/MCSymbol.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/SourceMgr.h"
32 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
33 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
35 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
36 Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
37 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
38 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
39 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
40 AutoReset(DoAutoReset) {
42 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
44 CompilationDir.clear();
46 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
48 SecureLogUsed = false;
50 if (SrcMgr && SrcMgr->getNumBuffers())
52 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
55 MCContext::~MCContext() {
60 // NOTE: The symbols are all allocated out of a bump pointer allocator,
61 // we don't need to free them here.
63 // If the stream for the .secure_log_unique directive was created free it.
64 delete (raw_ostream*)SecureLog;
67 //===----------------------------------------------------------------------===//
68 // Module Lifetime Management
69 //===----------------------------------------------------------------------===//
71 void MCContext::reset() {
76 MCDwarfLineTablesCUMap.clear();
77 MCGenDwarfLabelEntries.clear();
78 DwarfDebugFlags = StringRef();
79 DwarfCompileUnitID = 0;
80 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
82 MachOUniquingMap.clear();
83 ELFUniquingMap.clear();
84 COFFUniquingMap.clear();
87 AllowTemporaryLabels = true;
89 GenDwarfForAssembly = false;
90 GenDwarfFileNumber = 0;
93 //===----------------------------------------------------------------------===//
94 // Symbol Manipulation
95 //===----------------------------------------------------------------------===//
97 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
98 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
100 // Do the lookup and get the entire StringMapEntry. We want access to the
101 // key if we are creating the entry.
102 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
103 MCSymbol *Sym = Entry.getValue();
108 Sym = CreateSymbol(Name);
113 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
114 // Determine whether this is an assembler temporary or normal label, if used.
115 bool isTemporary = false;
116 if (AllowTemporaryLabels)
117 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
119 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
120 if (NameEntry->getValue()) {
121 assert(isTemporary && "Cannot rename non-temporary symbols");
122 SmallString<128> NewName = Name;
124 NewName.resize(Name.size());
125 raw_svector_ostream(NewName) << NextUniqueID++;
126 NameEntry = &UsedNames.GetOrCreateValue(NewName);
127 } while (NameEntry->getValue());
129 NameEntry->setValue(true);
131 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
132 // to the copy of the string that is embedded in the UsedNames entry.
133 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
138 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
139 SmallString<128> NameSV;
140 return GetOrCreateSymbol(Name.toStringRef(NameSV));
143 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
144 SmallString<128> NameSV;
145 raw_svector_ostream(NameSV)
146 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
147 return CreateSymbol(NameSV);
150 MCSymbol *MCContext::CreateTempSymbol() {
151 SmallString<128> NameSV;
152 raw_svector_ostream(NameSV)
153 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
154 return CreateSymbol(NameSV);
157 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
158 MCLabel *&Label = Instances[LocalLabelVal];
160 Label = new (*this) MCLabel(0);
161 return Label->incInstance();
164 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
165 MCLabel *&Label = Instances[LocalLabelVal];
167 Label = new (*this) MCLabel(0);
168 return Label->getInstance();
171 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
173 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
175 Sym = CreateTempSymbol();
179 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
180 unsigned Instance = NextInstance(LocalLabelVal);
181 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
184 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
186 unsigned Instance = GetInstance(LocalLabelVal);
189 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
192 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
193 return Symbols.lookup(Name);
196 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
197 SmallString<128> NameSV;
198 Name.toVector(NameSV);
199 return LookupSymbol(NameSV.str());
202 //===----------------------------------------------------------------------===//
203 // Section Management
204 //===----------------------------------------------------------------------===//
206 const MCSectionMachO *MCContext::
207 getMachOSection(StringRef Segment, StringRef Section,
208 unsigned TypeAndAttributes,
209 unsigned Reserved2, SectionKind Kind) {
211 // We unique sections by their segment/section pair. The returned section
212 // may not have the same flags as the requested section, if so this should be
213 // diagnosed by the client as an error.
215 // Form the name to look up.
216 SmallString<64> Name;
221 // Do the lookup, if we have a hit, return it.
222 const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
223 if (Entry) return Entry;
225 // Otherwise, return a new section.
226 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
230 const MCSectionELF *MCContext::
231 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
233 return getELFSection(Section, Type, Flags, Kind, 0, "");
236 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
238 if (const MCSymbol *Group = Section->getGroup())
239 GroupName = Group->getName();
241 ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
243 ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
245 StringRef CachedName = I->first.first;
246 const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
249 const MCSectionELF *MCContext::
250 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
251 SectionKind Kind, unsigned EntrySize, StringRef Group) {
252 // Do the lookup, if we have a hit, return it.
253 auto IterBool = ELFUniquingMap.insert(
254 std::make_pair(SectionGroupPair(Section, Group), nullptr));
255 auto &Entry = *IterBool.first;
256 if (!IterBool.second) return Entry.second;
258 // Possibly refine the entry size first.
260 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
263 MCSymbol *GroupSym = nullptr;
265 GroupSym = GetOrCreateSymbol(Group);
267 StringRef CachedName = Entry.first.first;
268 MCSectionELF *Result = new (*this)
269 MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym);
270 Entry.second = Result;
274 const MCSectionELF *MCContext::CreateELFGroupSection() {
275 MCSectionELF *Result =
276 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
277 SectionKind::getReadOnly(), 4, nullptr);
281 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
282 unsigned Characteristics,
284 StringRef COMDATSymName,
286 // Do the lookup, if we have a hit, return it.
288 SectionGroupTriple T(Section, COMDATSymName, Selection);
289 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
290 auto Iter = IterBool.first;
291 if (!IterBool.second)
294 MCSymbol *COMDATSymbol = nullptr;
295 if (!COMDATSymName.empty())
296 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
298 StringRef CachedName = std::get<0>(Iter->first);
299 MCSectionCOFF *Result = new (*this)
300 MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
302 Iter->second = Result;
306 const MCSectionCOFF *
307 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
309 return getCOFFSection(Section, Characteristics, Kind, "", 0);
312 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
313 SectionGroupTriple T(Section, "", 0);
314 auto Iter = COFFUniquingMap.find(T);
315 if (Iter == COFFUniquingMap.end())
320 const MCSectionCOFF *
321 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
322 const MCSymbol *KeySym) {
323 // Return the normal section if we don't have to be associative.
327 // Make an associative section with the same name and kind as the normal
329 unsigned Characteristics =
330 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
331 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
333 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
336 //===----------------------------------------------------------------------===//
338 //===----------------------------------------------------------------------===//
340 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
341 /// directory tables. If the file number has already been allocated it is an
342 /// error and zero is returned and the client reports the error, else the
343 /// allocated file number is returned. The file numbers may be in any order.
344 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
345 unsigned FileNumber, unsigned CUID) {
346 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
347 return Table.getFile(Directory, FileName, FileNumber);
350 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
351 /// currently is assigned and false otherwise.
352 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
353 const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
354 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
357 return !MCDwarfFiles[FileNumber].Name.empty();
360 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
361 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
362 /// useless debug info for them.
363 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
364 MCContext &context = MCOS.getContext();
366 auto sec = SectionStartEndSyms.begin();
367 while (sec != SectionStartEndSyms.end()) {
368 assert(sec->second.first && "Start symbol must be set by now");
369 MCOS.SwitchSection(sec->first);
370 if (MCOS.mayHaveInstructions()) {
371 MCSymbol *SectionEndSym = context.CreateTempSymbol();
372 MCOS.EmitLabel(SectionEndSym);
373 sec->second.second = SectionEndSym;
376 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
378 sec = SectionStartEndSyms.erase(to_erase);
383 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
384 // If we have a source manager and a location, use it. Otherwise just
385 // use the generic report_fatal_error().
386 if (!SrcMgr || Loc == SMLoc())
387 report_fatal_error(Msg, false);
389 // Use the source manager to print the message.
390 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
392 // If we reached here, we are failing ungracefully. Run the interrupt handlers
393 // to make sure any special cleanups get done, in particular that we remove
394 // files registered with RemoveFileOnSignal.
395 sys::RunInterruptHandlers();