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