Support standard DWARF TLS opcode; Darwin and PS4 use it.
[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), NextUniqueID(0),
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   NextUniqueID = 0;
91   AllowTemporaryLabels = true;
92   DwarfLocSeen = false;
93   GenDwarfForAssembly = false;
94   GenDwarfFileNumber = 0;
95 }
96
97 //===----------------------------------------------------------------------===//
98 // Symbol Manipulation
99 //===----------------------------------------------------------------------===//
100
101 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
102   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
103
104   MCSymbol *&Sym = Symbols[Name];
105
106   if (!Sym)
107     Sym = CreateSymbol(Name);
108
109   return Sym;
110 }
111
112 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
113   MCSymbol *&Sym = SectionSymbols[&Section];
114   if (Sym)
115     return Sym;
116
117   StringRef Name = Section.getSectionName();
118
119   MCSymbol *&OldSym = Symbols[Name];
120   if (OldSym && OldSym->isUndefined()) {
121     Sym = OldSym;
122     return OldSym;
123   }
124
125   auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
126   Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
127
128   if (!OldSym)
129     OldSym = Sym;
130
131   return Sym;
132 }
133
134 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName) {
135   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
136                            "frameallocation_" + FuncName);
137 }
138
139 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
140   // Determine whether this is an assembler temporary or normal label, if used.
141   bool isTemporary = false;
142   if (AllowTemporaryLabels)
143     isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
144
145   auto NameEntry = UsedNames.insert(std::make_pair(Name, true));
146   if (!NameEntry.second) {
147     assert(isTemporary && "Cannot rename non-temporary symbols");
148     SmallString<128> NewName = Name;
149     do {
150       NewName.resize(Name.size());
151       raw_svector_ostream(NewName) << NextUniqueID++;
152       NameEntry = UsedNames.insert(std::make_pair(NewName, true));
153     } while (!NameEntry.second);
154   }
155
156   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
157   // to the copy of the string that is embedded in the UsedNames entry.
158   MCSymbol *Result =
159       new (*this) MCSymbol(NameEntry.first->getKey(), isTemporary);
160
161   return Result;
162 }
163
164 MCSymbol *MCContext::createTempSymbol(const Twine &Name) {
165   SmallString<128> NameSV;
166   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
167   return CreateSymbol(NameSV);
168 }
169
170 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
171   SmallString<128> NameSV;
172   return GetOrCreateSymbol(Name.toStringRef(NameSV));
173 }
174
175 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
176   SmallString<128> NameSV;
177   raw_svector_ostream(NameSV)
178     << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
179   return CreateSymbol(NameSV);
180 }
181
182 MCSymbol *MCContext::CreateTempSymbol() {
183   SmallString<128> NameSV;
184   raw_svector_ostream(NameSV)
185     << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
186   return CreateSymbol(NameSV);
187 }
188
189 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
190   MCLabel *&Label = Instances[LocalLabelVal];
191   if (!Label)
192     Label = new (*this) MCLabel(0);
193   return Label->incInstance();
194 }
195
196 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
197   MCLabel *&Label = Instances[LocalLabelVal];
198   if (!Label)
199     Label = new (*this) MCLabel(0);
200   return Label->getInstance();
201 }
202
203 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
204                                                        unsigned Instance) {
205   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
206   if (!Sym)
207     Sym = CreateTempSymbol();
208   return Sym;
209 }
210
211 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
212   unsigned Instance = NextInstance(LocalLabelVal);
213   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
214 }
215
216 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
217                                                bool Before) {
218   unsigned Instance = GetInstance(LocalLabelVal);
219   if (!Before)
220     ++Instance;
221   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
222 }
223
224 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
225   return Symbols.lookup(Name);
226 }
227
228 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
229   SmallString<128> NameSV;
230   Name.toVector(NameSV);
231   return LookupSymbol(NameSV.str());
232 }
233
234 //===----------------------------------------------------------------------===//
235 // Section Management
236 //===----------------------------------------------------------------------===//
237
238 const MCSectionMachO *MCContext::
239 getMachOSection(StringRef Segment, StringRef Section,
240                 unsigned TypeAndAttributes,
241                 unsigned Reserved2, SectionKind Kind) {
242
243   // We unique sections by their segment/section pair.  The returned section
244   // may not have the same flags as the requested section, if so this should be
245   // diagnosed by the client as an error.
246
247   // Form the name to look up.
248   SmallString<64> Name;
249   Name += Segment;
250   Name.push_back(',');
251   Name += Section;
252
253   // Do the lookup, if we have a hit, return it.
254   const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
255   if (Entry) return Entry;
256
257   // Otherwise, return a new section.
258   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
259                                             Reserved2, Kind);
260 }
261
262 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
263                                              unsigned Flags) {
264   return getELFSection(Section, Type, Flags, 0, "");
265 }
266
267 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
268   StringRef GroupName;
269   if (const MCSymbol *Group = Section->getGroup())
270     GroupName = Group->getName();
271
272   ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
273   auto I =
274       ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
275                                            Section)).first;
276   StringRef CachedName = I->first.first;
277   const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
278 }
279
280 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
281                                              unsigned Flags, unsigned EntrySize,
282                                              StringRef Group, bool Unique) {
283   // Do the lookup, if we have a hit, return it.
284   auto IterBool = ELFUniquingMap.insert(
285       std::make_pair(SectionGroupPair(Section, Group), nullptr));
286   auto &Entry = *IterBool.first;
287   if (!IterBool.second && !Unique)
288     return Entry.second;
289
290   MCSymbol *GroupSym = nullptr;
291   if (!Group.empty())
292     GroupSym = GetOrCreateSymbol(Group);
293
294   StringRef CachedName = Entry.first.first;
295
296   SectionKind Kind;
297   if (Flags & ELF::SHF_EXECINSTR)
298     Kind = SectionKind::getText();
299   else
300     Kind = SectionKind::getReadOnly();
301
302   MCSectionELF *Result = new (*this)
303       MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym, Unique);
304   if (!Unique)
305     Entry.second = Result;
306   return Result;
307 }
308
309 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
310                                              unsigned Flags, unsigned EntrySize,
311                                              StringRef Group) {
312   return getELFSection(Section, Type, Flags, EntrySize, Group, false);
313 }
314
315 const MCSectionELF *MCContext::CreateELFGroupSection() {
316   MCSectionELF *Result =
317       new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
318                                SectionKind::getReadOnly(), 4, nullptr, false);
319   return Result;
320 }
321
322 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
323                                                unsigned Characteristics,
324                                                SectionKind Kind,
325                                                StringRef COMDATSymName,
326                                                int Selection) {
327   // Do the lookup, if we have a hit, return it.
328
329   SectionGroupTriple T(Section, COMDATSymName, Selection);
330   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
331   auto Iter = IterBool.first;
332   if (!IterBool.second)
333     return Iter->second;
334
335   MCSymbol *COMDATSymbol = nullptr;
336   if (!COMDATSymName.empty())
337     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
338
339   StringRef CachedName = std::get<0>(Iter->first);
340   MCSectionCOFF *Result = new (*this)
341       MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
342
343   Iter->second = Result;
344   return Result;
345 }
346
347 const MCSectionCOFF *
348 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
349                           SectionKind Kind) {
350   return getCOFFSection(Section, Characteristics, Kind, "", 0);
351 }
352
353 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
354   SectionGroupTriple T(Section, "", 0);
355   auto Iter = COFFUniquingMap.find(T);
356   if (Iter == COFFUniquingMap.end())
357     return nullptr;
358   return Iter->second;
359 }
360
361 const MCSectionCOFF *
362 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
363                                      const MCSymbol *KeySym) {
364   // Return the normal section if we don't have to be associative.
365   if (!KeySym)
366     return Sec;
367
368   // Make an associative section with the same name and kind as the normal
369   // section.
370   unsigned Characteristics =
371       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
372   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
373                         KeySym->getName(),
374                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
375 }
376
377 //===----------------------------------------------------------------------===//
378 // Dwarf Management
379 //===----------------------------------------------------------------------===//
380
381 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
382 /// directory tables.  If the file number has already been allocated it is an
383 /// error and zero is returned and the client reports the error, else the
384 /// allocated file number is returned.  The file numbers may be in any order.
385 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
386                                  unsigned FileNumber, unsigned CUID) {
387   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
388   return Table.getFile(Directory, FileName, FileNumber);
389 }
390
391 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
392 /// currently is assigned and false otherwise.
393 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
394   const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
395   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
396     return false;
397
398   return !MCDwarfFiles[FileNumber].Name.empty();
399 }
400
401 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
402 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
403 /// useless debug info for them.
404 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
405   MCContext &context = MCOS.getContext();
406
407   auto sec = SectionStartEndSyms.begin();
408   while (sec != SectionStartEndSyms.end()) {
409     assert(sec->second.first && "Start symbol must be set by now");
410     MCOS.SwitchSection(sec->first);
411     if (MCOS.mayHaveInstructions()) {
412       MCSymbol *SectionEndSym = context.CreateTempSymbol();
413       MCOS.EmitLabel(SectionEndSym);
414       sec->second.second = SectionEndSym;
415       ++sec;
416     } else {
417       MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
418         to_erase = sec;
419       sec = SectionStartEndSyms.erase(to_erase);
420     }
421   }
422 }
423
424 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
425   // If we have a source manager and a location, use it. Otherwise just
426   // use the generic report_fatal_error().
427   if (!SrcMgr || Loc == SMLoc())
428     report_fatal_error(Msg, false);
429
430   // Use the source manager to print the message.
431   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
432
433   // If we reached here, we are failing ungracefully. Run the interrupt handlers
434   // to make sure any special cleanups get done, in particular that we remove
435   // files registered with RemoveFileOnSignal.
436   sys::RunInterruptHandlers();
437   exit(1);
438 }