Allocate space for MCSymbol::Name only if required.
[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, 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                                   bool IsTemporary) {
180   if (IsTemporary && !UseNamesOnTempLabels)
181     return createSymbolImpl(nullptr, true);
182
183   // Determine whether this is an user writter assembler temporary or normal
184   // label, if used.
185   IsTemporary = false;
186   if (AllowTemporaryLabels)
187     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
188
189   SmallString<128> NewName = Name;
190   bool AddSuffix = AlwaysAddSuffix;
191   unsigned &NextUniqueID = NextID[Name];
192   for (;;) {
193     if (AddSuffix) {
194       NewName.resize(Name.size());
195       raw_svector_ostream(NewName) << NextUniqueID++;
196     }
197     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
198     if (NameEntry.second) {
199       // Ok, we found a name. Have the MCSymbol object itself refer to the copy
200       // of the string that is embedded in the UsedNames entry.
201       return createSymbolImpl(&*NameEntry.first, IsTemporary);
202     }
203     assert(IsTemporary && "Cannot rename non-temporary symbols");
204     AddSuffix = true;
205   }
206   llvm_unreachable("Infinite loop");
207 }
208
209 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
210   SmallString<128> NameSV;
211   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
212   return createSymbol(NameSV, AlwaysAddSuffix, true);
213 }
214
215 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
216   SmallString<128> NameSV;
217   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
218   return createSymbol(NameSV, true, false);
219 }
220
221 MCSymbol *MCContext::createTempSymbol() {
222   return createTempSymbol("tmp", true);
223 }
224
225 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
226   MCLabel *&Label = Instances[LocalLabelVal];
227   if (!Label)
228     Label = new (*this) MCLabel(0);
229   return Label->incInstance();
230 }
231
232 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
233   MCLabel *&Label = Instances[LocalLabelVal];
234   if (!Label)
235     Label = new (*this) MCLabel(0);
236   return Label->getInstance();
237 }
238
239 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
240                                                        unsigned Instance) {
241   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
242   if (!Sym)
243     Sym = createTempSymbol();
244   return Sym;
245 }
246
247 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
248   unsigned Instance = NextInstance(LocalLabelVal);
249   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
250 }
251
252 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
253                                                bool Before) {
254   unsigned Instance = GetInstance(LocalLabelVal);
255   if (!Before)
256     ++Instance;
257   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
258 }
259
260 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
261   SmallString<128> NameSV;
262   StringRef NameRef = Name.toStringRef(NameSV);
263   return Symbols.lookup(NameRef);
264 }
265
266 //===----------------------------------------------------------------------===//
267 // Section Management
268 //===----------------------------------------------------------------------===//
269
270 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
271                                            unsigned TypeAndAttributes,
272                                            unsigned Reserved2, SectionKind Kind,
273                                            const char *BeginSymName) {
274
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.
278
279   // Form the name to look up.
280   SmallString<64> Name;
281   Name += Segment;
282   Name.push_back(',');
283   Name += Section;
284
285   // Do the lookup, if we have a hit, return it.
286   MCSectionMachO *&Entry = MachOUniquingMap[Name];
287   if (Entry)
288     return Entry;
289
290   MCSymbol *Begin = nullptr;
291   if (BeginSymName)
292     Begin = createTempSymbol(BeginSymName, false);
293
294   // Otherwise, return a new section.
295   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
296                                             Reserved2, Kind, Begin);
297 }
298
299 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
300   StringRef GroupName;
301   if (const MCSymbol *Group = Section->getGroup())
302     GroupName = Group->getName();
303
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);
313 }
314
315 MCSectionELF *MCContext::createELFRelSection(StringRef Name, unsigned Type,
316                                              unsigned Flags, unsigned EntrySize,
317                                              const MCSymbolELF *Group,
318                                              const MCSectionELF *Associated) {
319   StringMap<bool>::iterator I;
320   bool Inserted;
321   std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
322
323   return new (*this)
324       MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
325                    EntrySize, Group, true, nullptr, Associated);
326 }
327
328 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
329                                        unsigned Flags, unsigned EntrySize,
330                                        StringRef Group, unsigned UniqueID,
331                                        const char *BeginSymName) {
332   MCSymbolELF *GroupSym = nullptr;
333   if (!Group.empty())
334     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
335
336   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
337                        BeginSymName, nullptr);
338 }
339
340 MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
341                                        unsigned Flags, unsigned EntrySize,
342                                        const MCSymbolELF *GroupSym,
343                                        unsigned UniqueID,
344                                        const char *BeginSymName,
345                                        const MCSectionELF *Associated) {
346   StringRef Group = "";
347   if (GroupSym)
348     Group = GroupSym->getName();
349   // Do the lookup, if we have a hit, return it.
350   auto IterBool = ELFUniquingMap.insert(
351       std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
352   auto &Entry = *IterBool.first;
353   if (!IterBool.second)
354     return Entry.second;
355
356   StringRef CachedName = Entry.first.SectionName;
357
358   SectionKind Kind;
359   if (Flags & ELF::SHF_EXECINSTR)
360     Kind = SectionKind::getText();
361   else
362     Kind = SectionKind::getReadOnly();
363
364   MCSymbol *Begin = nullptr;
365   if (BeginSymName)
366     Begin = createTempSymbol(BeginSymName, false);
367
368   MCSectionELF *Result =
369       new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
370                                GroupSym, UniqueID, Begin, Associated);
371   Entry.second = Result;
372   return Result;
373 }
374
375 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
376   MCSectionELF *Result = new (*this)
377       MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
378                    Group, ~0, nullptr, nullptr);
379   return Result;
380 }
381
382 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
383                                          unsigned Characteristics,
384                                          SectionKind Kind,
385                                          StringRef COMDATSymName, int Selection,
386                                          const char *BeginSymName) {
387   MCSymbol *COMDATSymbol = nullptr;
388   if (!COMDATSymName.empty()) {
389     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
390     COMDATSymName = COMDATSymbol->getName();
391   }
392
393   // Do the lookup, if we have a hit, return it.
394   COFFSectionKey T{Section, COMDATSymName, Selection};
395   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
396   auto Iter = IterBool.first;
397   if (!IterBool.second)
398     return Iter->second;
399
400   MCSymbol *Begin = nullptr;
401   if (BeginSymName)
402     Begin = createTempSymbol(BeginSymName, false);
403
404   StringRef CachedName = Iter->first.SectionName;
405   MCSectionCOFF *Result = new (*this) MCSectionCOFF(
406       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
407
408   Iter->second = Result;
409   return Result;
410 }
411
412 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
413                                          unsigned Characteristics,
414                                          SectionKind Kind,
415                                          const char *BeginSymName) {
416   return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
417 }
418
419 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
420   COFFSectionKey T{Section, "", 0};
421   auto Iter = COFFUniquingMap.find(T);
422   if (Iter == COFFUniquingMap.end())
423     return nullptr;
424   return Iter->second;
425 }
426
427 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
428                                                     const MCSymbol *KeySym) {
429   // Return the normal section if we don't have to be associative.
430   if (!KeySym)
431     return Sec;
432
433   // Make an associative section with the same name and kind as the normal
434   // section.
435   unsigned Characteristics =
436       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
437   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
438                         KeySym->getName(),
439                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
440 }
441
442 //===----------------------------------------------------------------------===//
443 // Dwarf Management
444 //===----------------------------------------------------------------------===//
445
446 /// getDwarfFile - takes a file name an number to place in the dwarf file and
447 /// directory tables.  If the file number has already been allocated it is an
448 /// error and zero is returned and the client reports the error, else the
449 /// allocated file number is returned.  The file numbers may be in any order.
450 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
451                                  unsigned FileNumber, unsigned CUID) {
452   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
453   return Table.getFile(Directory, FileName, FileNumber);
454 }
455
456 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
457 /// currently is assigned and false otherwise.
458 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
459   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
460   if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
461     return false;
462
463   return !MCDwarfFiles[FileNumber].Name.empty();
464 }
465
466 /// Remove empty sections from SectionStartEndSyms, to avoid generating
467 /// useless debug info for them.
468 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
469   SectionsForRanges.remove_if(
470       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
471 }
472
473 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
474   // If we have a source manager and a location, use it. Otherwise just
475   // use the generic report_fatal_error().
476   if (!SrcMgr || Loc == SMLoc())
477     report_fatal_error(Msg, false);
478
479   // Use the source manager to print the message.
480   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
481
482   // If we reached here, we are failing ungracefully. Run the interrupt handlers
483   // to make sure any special cleanups get done, in particular that we remove
484   // files registered with RemoveFileOnSignal.
485   sys::RunInterruptHandlers();
486   exit(1);
487 }