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