Recommit r310809 with a fix for the spill problem
[llvm-core.git] / lib / MC / MCContext.cpp
blobe7bd045c7574ce975222b516b5e89733c0fcbc41
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 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeView.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFragment.h"
23 #include "llvm/MC/MCLabel.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCSectionWasm.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/MC/MCSymbolELF.h"
33 #include "llvm/MC/MCSymbolMachO.h"
34 #include "llvm/MC/MCSymbolWasm.h"
35 #include "llvm/MC/SectionKind.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <cstdlib>
45 #include <tuple>
46 #include <utility>
48 using namespace llvm;
50 static cl::opt<char*>
51 AsSecureLogFileName("as-secure-log-file-name",
52 cl::desc("As secure log file name (initialized from "
53 "AS_SECURE_LOG_FILE env variable)"),
54 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
56 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
57 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
58 bool DoAutoReset)
59 : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
60 Symbols(Allocator), UsedNames(Allocator),
61 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
62 AutoReset(DoAutoReset) {
63 SecureLogFile = AsSecureLogFileName;
65 if (SrcMgr && SrcMgr->getNumBuffers())
66 MainFileName =
67 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
70 MCContext::~MCContext() {
71 if (AutoReset)
72 reset();
74 // NOTE: The symbols are all allocated out of a bump pointer allocator,
75 // we don't need to free them here.
78 //===----------------------------------------------------------------------===//
79 // Module Lifetime Management
80 //===----------------------------------------------------------------------===//
82 void MCContext::reset() {
83 // Call the destructors so the fragments are freed
84 COFFAllocator.DestroyAll();
85 ELFAllocator.DestroyAll();
86 MachOAllocator.DestroyAll();
88 MCSubtargetAllocator.DestroyAll();
89 UsedNames.clear();
90 Symbols.clear();
91 Allocator.Reset();
92 Instances.clear();
93 CompilationDir.clear();
94 MainFileName.clear();
95 MCDwarfLineTablesCUMap.clear();
96 SectionsForRanges.clear();
97 MCGenDwarfLabelEntries.clear();
98 DwarfDebugFlags = StringRef();
99 DwarfCompileUnitID = 0;
100 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
102 CVContext.reset();
104 MachOUniquingMap.clear();
105 ELFUniquingMap.clear();
106 COFFUniquingMap.clear();
108 NextID.clear();
109 AllowTemporaryLabels = true;
110 DwarfLocSeen = false;
111 GenDwarfForAssembly = false;
112 GenDwarfFileNumber = 0;
114 HadError = false;
117 //===----------------------------------------------------------------------===//
118 // Symbol Manipulation
119 //===----------------------------------------------------------------------===//
121 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
122 SmallString<128> NameSV;
123 StringRef NameRef = Name.toStringRef(NameSV);
125 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
127 MCSymbol *&Sym = Symbols[NameRef];
128 if (!Sym)
129 Sym = createSymbol(NameRef, false, false);
131 return Sym;
134 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
135 unsigned Idx) {
136 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
137 "$frame_escape_" + Twine(Idx));
140 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
141 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
142 "$parent_frame_offset");
145 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
146 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
147 FuncName);
150 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
151 bool IsTemporary) {
152 if (MOFI) {
153 switch (MOFI->getObjectFileType()) {
154 case MCObjectFileInfo::IsCOFF:
155 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
156 case MCObjectFileInfo::IsELF:
157 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
158 case MCObjectFileInfo::IsMachO:
159 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
160 case MCObjectFileInfo::IsWasm:
161 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
164 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
165 IsTemporary);
168 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
169 bool CanBeUnnamed) {
170 if (CanBeUnnamed && !UseNamesOnTempLabels)
171 return createSymbolImpl(nullptr, true);
173 // Determine whether this is a user written assembler temporary or normal
174 // label, if used.
175 bool IsTemporary = CanBeUnnamed;
176 if (AllowTemporaryLabels && !IsTemporary)
177 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
179 SmallString<128> NewName = Name;
180 bool AddSuffix = AlwaysAddSuffix;
181 unsigned &NextUniqueID = NextID[Name];
182 while (true) {
183 if (AddSuffix) {
184 NewName.resize(Name.size());
185 raw_svector_ostream(NewName) << NextUniqueID++;
187 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
188 if (NameEntry.second || !NameEntry.first->second) {
189 // Ok, we found a name.
190 // Mark it as used for a non-section symbol.
191 NameEntry.first->second = true;
192 // Have the MCSymbol object itself refer to the copy of the string that is
193 // embedded in the UsedNames entry.
194 return createSymbolImpl(&*NameEntry.first, IsTemporary);
196 assert(IsTemporary && "Cannot rename non-temporary symbols");
197 AddSuffix = true;
199 llvm_unreachable("Infinite loop");
202 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
203 bool CanBeUnnamed) {
204 SmallString<128> NameSV;
205 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
206 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
209 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
210 SmallString<128> NameSV;
211 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
212 return createSymbol(NameSV, true, false);
215 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
216 return createTempSymbol("tmp", true, CanBeUnnamed);
219 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
220 MCLabel *&Label = Instances[LocalLabelVal];
221 if (!Label)
222 Label = new (*this) MCLabel(0);
223 return Label->incInstance();
226 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
227 MCLabel *&Label = Instances[LocalLabelVal];
228 if (!Label)
229 Label = new (*this) MCLabel(0);
230 return Label->getInstance();
233 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
234 unsigned Instance) {
235 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
236 if (!Sym)
237 Sym = createTempSymbol(false);
238 return Sym;
241 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
242 unsigned Instance = NextInstance(LocalLabelVal);
243 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
246 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
247 bool Before) {
248 unsigned Instance = GetInstance(LocalLabelVal);
249 if (!Before)
250 ++Instance;
251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
254 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
255 SmallString<128> NameSV;
256 StringRef NameRef = Name.toStringRef(NameSV);
257 return Symbols.lookup(NameRef);
260 void MCContext::setSymbolValue(MCStreamer &Streamer,
261 StringRef Sym,
262 uint64_t Val) {
263 auto Symbol = getOrCreateSymbol(Sym);
264 Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this));
267 //===----------------------------------------------------------------------===//
268 // Section Management
269 //===----------------------------------------------------------------------===//
271 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
272 unsigned TypeAndAttributes,
273 unsigned Reserved2, SectionKind Kind,
274 const char *BeginSymName) {
275 // We unique sections by their segment/section pair. The returned section
276 // may not have the same flags as the requested section, if so this should be
277 // diagnosed by the client as an error.
279 // Form the name to look up.
280 SmallString<64> Name;
281 Name += Segment;
282 Name.push_back(',');
283 Name += Section;
285 // Do the lookup, if we have a hit, return it.
286 MCSectionMachO *&Entry = MachOUniquingMap[Name];
287 if (Entry)
288 return Entry;
290 MCSymbol *Begin = nullptr;
291 if (BeginSymName)
292 Begin = createTempSymbol(BeginSymName, false);
294 // Otherwise, return a new section.
295 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
296 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
299 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
300 StringRef GroupName;
301 if (const MCSymbol *Group = Section->getGroup())
302 GroupName = Group->getName();
304 unsigned UniqueID = Section->getUniqueID();
305 ELFUniquingMap.erase(
306 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
307 auto I = ELFUniquingMap.insert(std::make_pair(
308 ELFSectionKey{Name, GroupName, UniqueID},
309 Section))
310 .first;
311 StringRef CachedName = I->first.SectionName;
312 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
315 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
316 unsigned Flags, SectionKind K,
317 unsigned EntrySize,
318 const MCSymbolELF *Group,
319 unsigned UniqueID,
320 const MCSymbolELF *Associated) {
321 MCSymbolELF *R;
322 MCSymbol *&Sym = Symbols[Section];
323 // A section symbol can not redefine regular symbols. There may be multiple
324 // sections with the same name, in which case the first such section wins.
325 if (Sym && Sym->isDefined() &&
326 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
327 reportError(SMLoc(), "invalid symbol redefinition");
328 if (Sym && Sym->isUndefined()) {
329 R = cast<MCSymbolELF>(Sym);
330 } else {
331 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
332 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
333 if (!Sym)
334 Sym = R;
336 R->setBinding(ELF::STB_LOCAL);
337 R->setType(ELF::STT_SECTION);
339 auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
340 Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated);
342 auto *F = new MCDataFragment();
343 Ret->getFragmentList().insert(Ret->begin(), F);
344 F->setParent(Ret);
345 R->setFragment(F);
347 return Ret;
350 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
351 unsigned Flags, unsigned EntrySize,
352 const MCSymbolELF *Group,
353 const MCSectionELF *RelInfoSection) {
354 StringMap<bool>::iterator I;
355 bool Inserted;
356 std::tie(I, Inserted) =
357 RelSecNames.insert(std::make_pair(Name.str(), true));
359 return createELFSectionImpl(
360 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
361 true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
364 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
365 const Twine &Suffix, unsigned Type,
366 unsigned Flags,
367 unsigned EntrySize) {
368 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
371 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
372 unsigned Flags, unsigned EntrySize,
373 const Twine &Group, unsigned UniqueID,
374 const MCSymbolELF *Associated) {
375 MCSymbolELF *GroupSym = nullptr;
376 if (!Group.isTriviallyEmpty() && !Group.str().empty())
377 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
379 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
380 Associated);
383 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
384 unsigned Flags, unsigned EntrySize,
385 const MCSymbolELF *GroupSym,
386 unsigned UniqueID,
387 const MCSymbolELF *Associated) {
388 StringRef Group = "";
389 if (GroupSym)
390 Group = GroupSym->getName();
391 // Do the lookup, if we have a hit, return it.
392 auto IterBool = ELFUniquingMap.insert(
393 std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr));
394 auto &Entry = *IterBool.first;
395 if (!IterBool.second)
396 return Entry.second;
398 StringRef CachedName = Entry.first.SectionName;
400 SectionKind Kind;
401 if (Flags & ELF::SHF_ARM_PURECODE)
402 Kind = SectionKind::getExecuteOnly();
403 else if (Flags & ELF::SHF_EXECINSTR)
404 Kind = SectionKind::getText();
405 else
406 Kind = SectionKind::getReadOnly();
408 MCSectionELF *Result = createELFSectionImpl(
409 CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated);
410 Entry.second = Result;
411 return Result;
414 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
415 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
416 SectionKind::getReadOnly(), 4, Group, ~0,
417 nullptr);
420 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
421 unsigned Characteristics,
422 SectionKind Kind,
423 StringRef COMDATSymName, int Selection,
424 unsigned UniqueID,
425 const char *BeginSymName) {
426 MCSymbol *COMDATSymbol = nullptr;
427 if (!COMDATSymName.empty()) {
428 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
429 COMDATSymName = COMDATSymbol->getName();
433 // Do the lookup, if we have a hit, return it.
434 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
435 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
436 auto Iter = IterBool.first;
437 if (!IterBool.second)
438 return Iter->second;
440 MCSymbol *Begin = nullptr;
441 if (BeginSymName)
442 Begin = createTempSymbol(BeginSymName, false);
444 StringRef CachedName = Iter->first.SectionName;
445 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
446 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
448 Iter->second = Result;
449 return Result;
452 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
453 unsigned Characteristics,
454 SectionKind Kind,
455 const char *BeginSymName) {
456 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
457 BeginSymName);
460 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
461 COFFSectionKey T{Section, "", 0, GenericSectionID};
462 auto Iter = COFFUniquingMap.find(T);
463 if (Iter == COFFUniquingMap.end())
464 return nullptr;
465 return Iter->second;
468 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
469 const MCSymbol *KeySym,
470 unsigned UniqueID) {
471 // Return the normal section if we don't have to be associative or unique.
472 if (!KeySym && UniqueID == GenericSectionID)
473 return Sec;
475 // If we have a key symbol, make an associative section with the same name and
476 // kind as the normal section.
477 unsigned Characteristics = Sec->getCharacteristics();
478 if (KeySym) {
479 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
480 return getCOFFSection(Sec->getSectionName(), Characteristics,
481 Sec->getKind(), KeySym->getName(),
482 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
485 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
486 "", 0, UniqueID);
489 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, unsigned Type,
490 const Twine &Group, unsigned UniqueID,
491 const char *BeginSymName) {
492 MCSymbolWasm *GroupSym = nullptr;
493 if (!Group.isTriviallyEmpty() && !Group.str().empty())
494 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
496 return getWasmSection(Section, Type, GroupSym, UniqueID, BeginSymName);
499 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, unsigned Type,
500 const MCSymbolWasm *GroupSym,
501 unsigned UniqueID,
502 const char *BeginSymName) {
503 StringRef Group = "";
504 if (GroupSym)
505 Group = GroupSym->getName();
506 // Do the lookup, if we have a hit, return it.
507 auto IterBool = WasmUniquingMap.insert(
508 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
509 auto &Entry = *IterBool.first;
510 if (!IterBool.second)
511 return Entry.second;
513 StringRef CachedName = Entry.first.SectionName;
515 SectionKind Kind = SectionKind::getText();
517 MCSymbol *Begin = nullptr;
518 if (BeginSymName)
519 Begin = createTempSymbol(BeginSymName, false);
521 MCSectionWasm *Result = new (WasmAllocator.Allocate())
522 MCSectionWasm(CachedName, Type, Kind, GroupSym, UniqueID, Begin);
523 Entry.second = Result;
524 return Result;
527 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
528 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
531 //===----------------------------------------------------------------------===//
532 // Dwarf Management
533 //===----------------------------------------------------------------------===//
535 /// getDwarfFile - takes a file name an number to place in the dwarf file and
536 /// directory tables. If the file number has already been allocated it is an
537 /// error and zero is returned and the client reports the error, else the
538 /// allocated file number is returned. The file numbers may be in any order.
539 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
540 unsigned FileNumber, unsigned CUID) {
541 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
542 return Table.getFile(Directory, FileName, FileNumber);
545 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
546 /// currently is assigned and false otherwise.
547 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
548 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
549 if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
550 return false;
552 return !MCDwarfFiles[FileNumber].Name.empty();
555 /// Remove empty sections from SectionStartEndSyms, to avoid generating
556 /// useless debug info for them.
557 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
558 SectionsForRanges.remove_if(
559 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
562 CodeViewContext &MCContext::getCVContext() {
563 if (!CVContext.get())
564 CVContext.reset(new CodeViewContext);
565 return *CVContext.get();
568 //===----------------------------------------------------------------------===//
569 // Error Reporting
570 //===----------------------------------------------------------------------===//
572 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
573 HadError = true;
575 // If we have a source manager use it. Otherwise, try using the inline source
576 // manager.
577 // If that fails, use the generic report_fatal_error().
578 if (SrcMgr)
579 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
580 else if (InlineSrcMgr)
581 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
582 else
583 report_fatal_error(Msg, false);
586 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
587 reportError(Loc, Msg);
589 // If we reached here, we are failing ungracefully. Run the interrupt handlers
590 // to make sure any special cleanups get done, in particular that we remove
591 // files registered with RemoveFileOnSignal.
592 sys::RunInterruptHandlers();
593 exit(1);