Make all temporary symbols unnamed.
[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/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
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
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
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   Allocator.Reset();
86   Instances.clear();
87   CompilationDir.clear();
88   MainFileName.clear();
89   MCDwarfLineTablesCUMap.clear();
90   SectionsForRanges.clear();
91   MCGenDwarfLabelEntries.clear();
92   DwarfDebugFlags = StringRef();
93   DwarfCompileUnitID = 0;
94   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
95
96   MachOUniquingMap.clear();
97   ELFUniquingMap.clear();
98   COFFUniquingMap.clear();
99
100   NextID.clear();
101   AllowTemporaryLabels = true;
102   DwarfLocSeen = false;
103   GenDwarfForAssembly = false;
104   GenDwarfFileNumber = 0;
105 }
106
107 //===----------------------------------------------------------------------===//
108 // Symbol Manipulation
109 //===----------------------------------------------------------------------===//
110
111 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
112   SmallString<128> NameSV;
113   StringRef NameRef = Name.toStringRef(NameSV);
114
115   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
116
117   MCSymbol *&Sym = Symbols[NameRef];
118   if (!Sym)
119     Sym = createSymbol(NameRef, false);
120
121   return Sym;
122 }
123
124 MCSymbolELF *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
125   MCSymbolELF *&Sym = SectionSymbols[&Section];
126   if (Sym)
127     return Sym;
128
129   StringRef Name = Section.getSectionName();
130
131   MCSymbol *&OldSym = Symbols[Name];
132   if (OldSym && OldSym->isUndefined()) {
133     Sym = cast<MCSymbolELF>(OldSym);
134     return Sym;
135   }
136
137   auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
138   Sym = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
139
140   if (!OldSym)
141     OldSym = Sym;
142
143   return Sym;
144 }
145
146 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
147                                                  unsigned Idx) {
148   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
149                            "$frame_escape_" + Twine(Idx));
150 }
151
152 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
153   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
154                            "$parent_frame_offset");
155 }
156
157 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
158   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
159                            FuncName);
160 }
161
162 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
163                                       bool IsTemporary) {
164   if (MOFI) {
165     switch (MOFI->getObjectFileType()) {
166     case MCObjectFileInfo::IsCOFF:
167       return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
168     case MCObjectFileInfo::IsELF:
169       return new (Name, *this) MCSymbolELF(Name, IsTemporary);
170     case MCObjectFileInfo::IsMachO:
171       return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
172     }
173   }
174   return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
175                                     IsTemporary);
176 }
177
178 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix) {
179   // Determine whether this is an user writter assembler temporary or normal
180   // label, if used.
181   bool IsTemporary = false;
182   if (AllowTemporaryLabels)
183     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
184
185   if (IsTemporary && !UseNamesOnTempLabels)
186     return createSymbolImpl(nullptr, true);
187
188   SmallString<128> NewName = Name;
189   bool AddSuffix = AlwaysAddSuffix;
190   unsigned &NextUniqueID = NextID[Name];
191   for (;;) {
192     if (AddSuffix) {
193       NewName.resize(Name.size());
194       raw_svector_ostream(NewName) << NextUniqueID++;
195     }
196     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
197     if (NameEntry.second) {
198       // Ok, we found a name. Have the MCSymbol object itself refer to the copy
199       // of the string that is embedded in the UsedNames entry.
200       return createSymbolImpl(&*NameEntry.first, IsTemporary);
201     }
202     assert(IsTemporary && "Cannot rename non-temporary symbols");
203     AddSuffix = true;
204   }
205   llvm_unreachable("Infinite loop");
206 }
207
208 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
209   SmallString<128> NameSV;
210   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
211   return createSymbol(NameSV, AlwaysAddSuffix);
212 }
213
214 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
215   SmallString<128> NameSV;
216   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
217   return createSymbol(NameSV, true);
218 }
219
220 MCSymbol *MCContext::createTempSymbol() {
221   return createTempSymbol("tmp", true);
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();
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 (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
295                                             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 (*this)
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 =
368       new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
369                                GroupSym, UniqueID, Begin, Associated);
370   Entry.second = Result;
371   return Result;
372 }
373
374 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
375   MCSectionELF *Result = new (*this)
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 (*this) 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 }