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