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