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