1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmInfo.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCLabel.h"
17 #include "llvm/MC/MCObjectFileInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCSectionCOFF.h"
20 #include "llvm/MC/MCSectionELF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbolCOFF.h"
24 #include "llvm/MC/MCSymbolELF.h"
25 #include "llvm/MC/MCSymbolMachO.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include <map>
33
34 using namespace llvm;
35
MCContext(const MCAsmInfo * mai,const MCRegisterInfo * mri,const MCObjectFileInfo * mofi,const SourceMgr * mgr,bool DoAutoReset)36 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
37 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
38 bool DoAutoReset)
39 : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
40 Symbols(Allocator), UsedNames(Allocator),
41 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
42 GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
43 AllowTemporaryLabels(true), DwarfCompileUnitID(0),
44 AutoReset(DoAutoReset) {
45
46 std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
47 if (EC)
48 CompilationDir.clear();
49
50 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
51 SecureLog = nullptr;
52 SecureLogUsed = false;
53
54 if (SrcMgr && SrcMgr->getNumBuffers())
55 MainFileName =
56 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
57 }
58
~MCContext()59 MCContext::~MCContext() {
60 if (AutoReset)
61 reset();
62
63 // NOTE: The symbols are all allocated out of a bump pointer allocator,
64 // we don't need to free them here.
65
66 // If the stream for the .secure_log_unique directive was created free it.
67 delete (raw_ostream *)SecureLog;
68 }
69
70 //===----------------------------------------------------------------------===//
71 // Module Lifetime Management
72 //===----------------------------------------------------------------------===//
73
reset()74 void MCContext::reset() {
75 // Call the destructors so the fragments are freed
76 for (auto &I : ELFUniquingMap)
77 I.second->~MCSectionELF();
78 for (auto &I : COFFUniquingMap)
79 I.second->~MCSectionCOFF();
80 for (auto &I : MachOUniquingMap)
81 I.second->~MCSectionMachO();
82
83 UsedNames.clear();
84 Symbols.clear();
85 SectionSymbols.clear();
86 Allocator.Reset();
87 Instances.clear();
88 CompilationDir.clear();
89 MainFileName.clear();
90 MCDwarfLineTablesCUMap.clear();
91 SectionsForRanges.clear();
92 MCGenDwarfLabelEntries.clear();
93 DwarfDebugFlags = StringRef();
94 DwarfCompileUnitID = 0;
95 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
96
97 MachOUniquingMap.clear();
98 ELFUniquingMap.clear();
99 COFFUniquingMap.clear();
100
101 NextID.clear();
102 AllowTemporaryLabels = true;
103 DwarfLocSeen = false;
104 GenDwarfForAssembly = false;
105 GenDwarfFileNumber = 0;
106 }
107
108 //===----------------------------------------------------------------------===//
109 // Symbol Manipulation
110 //===----------------------------------------------------------------------===//
111
getOrCreateSymbol(const Twine & Name)112 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
113 SmallString<128> NameSV;
114 StringRef NameRef = Name.toStringRef(NameSV);
115
116 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
117
118 MCSymbol *&Sym = Symbols[NameRef];
119 if (!Sym)
120 Sym = createSymbol(NameRef, false, false);
121
122 return Sym;
123 }
124
getOrCreateSectionSymbol(const MCSectionELF & Section)125 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
126 MCSymbolELF *&Sym = SectionSymbols[&Section];
127 if (Sym)
128 return Sym;
129
130 StringRef Name = Section.getSectionName();
131
132 MCSymbol *&OldSym = Symbols[Name];
133 if (OldSym && OldSym->isUndefined()) {
134 Sym = cast<MCSymbolELF>(OldSym);
135 return Sym;
136 }
137
138 auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
139 Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
140
141 if (!OldSym)
142 OldSym = Sym;
143
144 return Sym;
145 }
146
getOrCreateFrameAllocSymbol(StringRef FuncName,unsigned Idx)147 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
148 unsigned Idx) {
149 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
150 "$frame_escape_" + Twine(Idx));
151 }
152
getOrCreateParentFrameOffsetSymbol(StringRef FuncName)153 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
154 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
155 "$parent_frame_offset");
156 }
157
getOrCreateLSDASymbol(StringRef FuncName)158 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
159 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
160 FuncName);
161 }
162
createSymbolImpl(const StringMapEntry<bool> * Name,bool IsTemporary)163 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
164 bool IsTemporary) {
165 if (MOFI) {
166 switch (MOFI->getObjectFileType()) {
167 case MCObjectFileInfo::IsCOFF:
168 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
169 case MCObjectFileInfo::IsELF:
170 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
171 case MCObjectFileInfo::IsMachO:
172 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
173 }
174 }
175 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
176 IsTemporary);
177 }
178
createSymbol(StringRef Name,bool AlwaysAddSuffix,bool CanBeUnnamed)179 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
180 bool CanBeUnnamed) {
181 if (CanBeUnnamed && !UseNamesOnTempLabels)
182 return createSymbolImpl(nullptr, true);
183
184 // Determine whether this is an user writter assembler temporary or normal
185 // label, if used.
186 bool IsTemporary = CanBeUnnamed;
187 if (AllowTemporaryLabels && !IsTemporary)
188 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
189
190 SmallString<128> NewName = Name;
191 bool AddSuffix = AlwaysAddSuffix;
192 unsigned &NextUniqueID = NextID[Name];
193 for (;;) {
194 if (AddSuffix) {
195 NewName.resize(Name.size());
196 raw_svector_ostream(NewName) << NextUniqueID++;
197 }
198 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
199 if (NameEntry.second) {
200 // Ok, we found a name. Have the MCSymbol object itself refer to the copy
201 // of the string that is embedded in the UsedNames entry.
202 return createSymbolImpl(&*NameEntry.first, IsTemporary);
203 }
204 assert(IsTemporary && "Cannot rename non-temporary symbols");
205 AddSuffix = true;
206 }
207 llvm_unreachable("Infinite loop");
208 }
209
createTempSymbol(const Twine & Name,bool AlwaysAddSuffix,bool CanBeUnnamed)210 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
211 bool CanBeUnnamed) {
212 SmallString<128> NameSV;
213 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
214 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
215 }
216
createLinkerPrivateTempSymbol()217 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
218 SmallString<128> NameSV;
219 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
220 return createSymbol(NameSV, true, false);
221 }
222
createTempSymbol(bool CanBeUnnamed)223 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
224 return createTempSymbol("tmp", true, CanBeUnnamed);
225 }
226
NextInstance(unsigned LocalLabelVal)227 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
228 MCLabel *&Label = Instances[LocalLabelVal];
229 if (!Label)
230 Label = new (*this) MCLabel(0);
231 return Label->incInstance();
232 }
233
GetInstance(unsigned LocalLabelVal)234 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
235 MCLabel *&Label = Instances[LocalLabelVal];
236 if (!Label)
237 Label = new (*this) MCLabel(0);
238 return Label->getInstance();
239 }
240
getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,unsigned Instance)241 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
242 unsigned Instance) {
243 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
244 if (!Sym)
245 Sym = createTempSymbol(false);
246 return Sym;
247 }
248
createDirectionalLocalSymbol(unsigned LocalLabelVal)249 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
250 unsigned Instance = NextInstance(LocalLabelVal);
251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
252 }
253
getDirectionalLocalSymbol(unsigned LocalLabelVal,bool Before)254 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
255 bool Before) {
256 unsigned Instance = GetInstance(LocalLabelVal);
257 if (!Before)
258 ++Instance;
259 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
260 }
261
lookupSymbol(const Twine & Name) const262 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
263 SmallString<128> NameSV;
264 StringRef NameRef = Name.toStringRef(NameSV);
265 return Symbols.lookup(NameRef);
266 }
267
268 //===----------------------------------------------------------------------===//
269 // Section Management
270 //===----------------------------------------------------------------------===//
271
getMachOSection(StringRef Segment,StringRef Section,unsigned TypeAndAttributes,unsigned Reserved2,SectionKind Kind,const char * BeginSymName)272 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
273 unsigned TypeAndAttributes,
274 unsigned Reserved2, SectionKind Kind,
275 const char *BeginSymName) {
276
277 // We unique sections by their segment/section pair. The returned section
278 // may not have the same flags as the requested section, if so this should be
279 // diagnosed by the client as an error.
280
281 // Form the name to look up.
282 SmallString<64> Name;
283 Name += Segment;
284 Name.push_back(',');
285 Name += Section;
286
287 // Do the lookup, if we have a hit, return it.
288 MCSectionMachO *&Entry = MachOUniquingMap[Name];
289 if (Entry)
290 return Entry;
291
292 MCSymbol *Begin = nullptr;
293 if (BeginSymName)
294 Begin = createTempSymbol(BeginSymName, false);
295
296 // Otherwise, return a new section.
297 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
298 Reserved2, Kind, Begin);
299 }
300
renameELFSection(MCSectionELF * Section,StringRef Name)301 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
302 StringRef GroupName;
303 if (const MCSymbol *Group = Section->getGroup())
304 GroupName = Group->getName();
305
306 unsigned UniqueID = Section->getUniqueID();
307 ELFUniquingMap.erase(
308 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
309 auto I = ELFUniquingMap.insert(std::make_pair(
310 ELFSectionKey{Name, GroupName, UniqueID},
311 Section))
312 .first;
313 StringRef CachedName = I->first.SectionName;
314 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
315 }
316
createELFRelSection(StringRef Name,unsigned Type,unsigned Flags,unsigned EntrySize,const MCSymbolELF * Group,const MCSectionELF * Associated)317 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
318 unsigned Flags, unsigned EntrySize,
319 const MCSymbolELF *Group,
320 const MCSectionELF *Associated) {
321 StringMap<bool>::iterator I;
322 bool Inserted;
323 std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
324
325 return new (*this)
326 MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
327 EntrySize, Group, true, nullptr, Associated);
328 }
329
getELFSection(StringRef Section,unsigned Type,unsigned Flags,unsigned EntrySize,StringRef Group,unsigned UniqueID,const char * BeginSymName)330 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
331 unsigned Flags, unsigned EntrySize,
332 StringRef Group, unsigned UniqueID,
333 const char *BeginSymName) {
334 MCSymbolELF *GroupSym = nullptr;
335 if (!Group.empty())
336 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
337
338 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
339 BeginSymName, nullptr);
340 }
341
getELFSection(StringRef Section,unsigned Type,unsigned Flags,unsigned EntrySize,const MCSymbolELF * GroupSym,unsigned UniqueID,const char * BeginSymName,const MCSectionELF * Associated)342 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
343 unsigned Flags, unsigned EntrySize,
344 const MCSymbolELF *GroupSym,
345 unsigned UniqueID,
346 const char *BeginSymName,
347 const MCSectionELF *Associated) {
348 StringRef Group = "";
349 if (GroupSym)
350 Group = GroupSym->getName();
351 // Do the lookup, if we have a hit, return it.
352 auto IterBool = ELFUniquingMap.insert(
353 std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
354 auto &Entry = *IterBool.first;
355 if (!IterBool.second)
356 return Entry.second;
357
358 StringRef CachedName = Entry.first.SectionName;
359
360 SectionKind Kind;
361 if (Flags & ELF::SHF_EXECINSTR)
362 Kind = SectionKind::getText();
363 else
364 Kind = SectionKind::getReadOnly();
365
366 MCSymbol *Begin = nullptr;
367 if (BeginSymName)
368 Begin = createTempSymbol(BeginSymName, false);
369
370 MCSectionELF *Result =
371 new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
372 GroupSym, UniqueID, Begin, Associated);
373 Entry.second = Result;
374 return Result;
375 }
376
createELFGroupSection(const MCSymbolELF * Group)377 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
378 MCSectionELF *Result = new (*this)
379 MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
380 Group, ~0, nullptr, nullptr);
381 return Result;
382 }
383
getCOFFSection(StringRef Section,unsigned Characteristics,SectionKind Kind,StringRef COMDATSymName,int Selection,const char * BeginSymName)384 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
385 unsigned Characteristics,
386 SectionKind Kind,
387 StringRef COMDATSymName, int Selection,
388 const char *BeginSymName) {
389 MCSymbol *COMDATSymbol = nullptr;
390 if (!COMDATSymName.empty()) {
391 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
392 COMDATSymName = COMDATSymbol->getName();
393 }
394
395 // Do the lookup, if we have a hit, return it.
396 COFFSectionKey T{Section, COMDATSymName, Selection};
397 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
398 auto Iter = IterBool.first;
399 if (!IterBool.second)
400 return Iter->second;
401
402 MCSymbol *Begin = nullptr;
403 if (BeginSymName)
404 Begin = createTempSymbol(BeginSymName, false);
405
406 StringRef CachedName = Iter->first.SectionName;
407 MCSectionCOFF *Result = new (*this) MCSectionCOFF(
408 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
409
410 Iter->second = Result;
411 return Result;
412 }
413
getCOFFSection(StringRef Section,unsigned Characteristics,SectionKind Kind,const char * BeginSymName)414 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
415 unsigned Characteristics,
416 SectionKind Kind,
417 const char *BeginSymName) {
418 return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
419 }
420
getCOFFSection(StringRef Section)421 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
422 COFFSectionKey T{Section, "", 0};
423 auto Iter = COFFUniquingMap.find(T);
424 if (Iter == COFFUniquingMap.end())
425 return nullptr;
426 return Iter->second;
427 }
428
getAssociativeCOFFSection(MCSectionCOFF * Sec,const MCSymbol * KeySym)429 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
430 const MCSymbol *KeySym) {
431 // Return the normal section if we don't have to be associative.
432 if (!KeySym)
433 return Sec;
434
435 // Make an associative section with the same name and kind as the normal
436 // section.
437 unsigned Characteristics =
438 Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
439 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
440 KeySym->getName(),
441 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
442 }
443
444 //===----------------------------------------------------------------------===//
445 // Dwarf Management
446 //===----------------------------------------------------------------------===//
447
448 /// getDwarfFile - takes a file name an number to place in the dwarf file and
449 /// directory tables. If the file number has already been allocated it is an
450 /// error and zero is returned and the client reports the error, else the
451 /// allocated file number is returned. The file numbers may be in any order.
getDwarfFile(StringRef Directory,StringRef FileName,unsigned FileNumber,unsigned CUID)452 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
453 unsigned FileNumber, unsigned CUID) {
454 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
455 return Table.getFile(Directory, FileName, FileNumber);
456 }
457
458 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
459 /// currently is assigned and false otherwise.
isValidDwarfFileNumber(unsigned FileNumber,unsigned CUID)460 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
461 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
462 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
463 return false;
464
465 return !MCDwarfFiles[FileNumber].Name.empty();
466 }
467
468 /// Remove empty sections from SectionStartEndSyms, to avoid generating
469 /// useless debug info for them.
finalizeDwarfSections(MCStreamer & MCOS)470 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
471 SectionsForRanges.remove_if(
472 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
473 }
474
reportFatalError(SMLoc Loc,const Twine & Msg) const475 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
476 // If we have a source manager and a location, use it. Otherwise just
477 // use the generic report_fatal_error().
478 if (!SrcMgr || Loc == SMLoc())
479 report_fatal_error(Msg, false);
480
481 // Use the source manager to print the message.
482 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
483
484 // If we reached here, we are failing ungracefully. Run the interrupt handlers
485 // to make sure any special cleanups get done, in particular that we remove
486 // files registered with RemoveFileOnSignal.
487 sys::RunInterruptHandlers();
488 exit(1);
489 }
490