Introduce a string_ostream string builder facilty
[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/MCSymbol.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include <map>
29
30 using namespace llvm;
31
32 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
33                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
34                      bool DoAutoReset)
35     : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
36       Symbols(Allocator), UsedNames(Allocator), NextUniqueID(0),
37       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
38       GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
39       AllowTemporaryLabels(true), DwarfCompileUnitID(0),
40       AutoReset(DoAutoReset) {
41
42   std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
43   if (EC)
44     CompilationDir.clear();
45
46   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
47   SecureLog = nullptr;
48   SecureLogUsed = false;
49
50   if (SrcMgr && SrcMgr->getNumBuffers() > 0)
51     MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
52 }
53
54 MCContext::~MCContext() {
55
56   if (AutoReset)
57     reset();
58
59   // NOTE: The symbols are all allocated out of a bump pointer allocator,
60   // we don't need to free them here.
61
62   // If the stream for the .secure_log_unique directive was created free it.
63   delete (raw_ostream*)SecureLog;
64 }
65
66 //===----------------------------------------------------------------------===//
67 // Module Lifetime Management
68 //===----------------------------------------------------------------------===//
69
70 void MCContext::reset() {
71   UsedNames.clear();
72   Symbols.clear();
73   Allocator.Reset();
74   Instances.clear();
75   MCDwarfLineTablesCUMap.clear();
76   MCGenDwarfLabelEntries.clear();
77   DwarfDebugFlags = StringRef();
78   DwarfCompileUnitID = 0;
79   CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
80
81   MachOUniquingMap.clear();
82   ELFUniquingMap.clear();
83   COFFUniquingMap.clear();
84
85   NextUniqueID = 0;
86   AllowTemporaryLabels = true;
87   DwarfLocSeen = false;
88   GenDwarfForAssembly = false;
89   GenDwarfFileNumber = 0;
90 }
91
92 //===----------------------------------------------------------------------===//
93 // Symbol Manipulation
94 //===----------------------------------------------------------------------===//
95
96 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
97   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
98
99   // Do the lookup and get the entire StringMapEntry.  We want access to the
100   // key if we are creating the entry.
101   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
102   MCSymbol *Sym = Entry.getValue();
103
104   if (Sym)
105     return Sym;
106
107   Sym = CreateSymbol(Name);
108   Entry.setValue(Sym);
109   return Sym;
110 }
111
112 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
113   // Determine whether this is an assembler temporary or normal label, if used.
114   bool isTemporary = false;
115   if (AllowTemporaryLabels)
116     isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
117
118   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
119   if (NameEntry->getValue()) {
120     assert(isTemporary && "Cannot rename non-temporary symbols");
121     SmallString<128> NewName = Name;
122     do {
123       NewName.resize(Name.size());
124       raw_svector_ostream(NewName) << NextUniqueID++;
125       NameEntry = &UsedNames.GetOrCreateValue(NewName);
126     } while (NameEntry->getValue());
127   }
128   NameEntry->setValue(true);
129
130   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
131   // to the copy of the string that is embedded in the UsedNames entry.
132   MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
133
134   return Result;
135 }
136
137 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
138   SmallString<128> NameSV;
139   return GetOrCreateSymbol(Name.toStringRef(NameSV));
140 }
141
142 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
143   small_string_ostream<128> NameSV;
144   NameSV << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
145   return CreateSymbol(NameSV.str());
146 }
147
148 MCSymbol *MCContext::CreateTempSymbol() {
149   small_string_ostream<128> NameSV;
150   NameSV << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
151   return CreateSymbol(NameSV.str());
152 }
153
154 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
155   MCLabel *&Label = Instances[LocalLabelVal];
156   if (!Label)
157     Label = new (*this) MCLabel(0);
158   return Label->incInstance();
159 }
160
161 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
162   MCLabel *&Label = Instances[LocalLabelVal];
163   if (!Label)
164     Label = new (*this) MCLabel(0);
165   return Label->getInstance();
166 }
167
168 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
169                                                        unsigned Instance) {
170   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
171   if (!Sym)
172     Sym = CreateTempSymbol();
173   return Sym;
174 }
175
176 MCSymbol *MCContext::CreateDirectionalLocalSymbol(unsigned LocalLabelVal) {
177   unsigned Instance = NextInstance(LocalLabelVal);
178   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
179 }
180
181 MCSymbol *MCContext::GetDirectionalLocalSymbol(unsigned LocalLabelVal,
182                                                bool Before) {
183   unsigned Instance = GetInstance(LocalLabelVal);
184   if (!Before)
185     ++Instance;
186   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
187 }
188
189 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
190   return Symbols.lookup(Name);
191 }
192
193 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
194   SmallString<128> NameSV;
195   Name.toVector(NameSV);
196   return LookupSymbol(NameSV.str());
197 }
198
199 //===----------------------------------------------------------------------===//
200 // Section Management
201 //===----------------------------------------------------------------------===//
202
203 const MCSectionMachO *MCContext::
204 getMachOSection(StringRef Segment, StringRef Section,
205                 unsigned TypeAndAttributes,
206                 unsigned Reserved2, SectionKind Kind) {
207
208   // We unique sections by their segment/section pair.  The returned section
209   // may not have the same flags as the requested section, if so this should be
210   // diagnosed by the client as an error.
211
212   // Form the name to look up.
213   SmallString<64> Name;
214   Name += Segment;
215   Name.push_back(',');
216   Name += Section;
217
218   // Do the lookup, if we have a hit, return it.
219   const MCSectionMachO *&Entry = MachOUniquingMap[Name.str()];
220   if (Entry) return Entry;
221
222   // Otherwise, return a new section.
223   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
224                                             Reserved2, Kind);
225 }
226
227 const MCSectionELF *MCContext::
228 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
229               SectionKind Kind) {
230   return getELFSection(Section, Type, Flags, Kind, 0, "");
231 }
232
233 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
234   StringRef GroupName;
235   if (const MCSymbol *Group = Section->getGroup())
236     GroupName = Group->getName();
237
238   ELFUniquingMap.erase(SectionGroupPair(Section->getSectionName(), GroupName));
239   auto I =
240       ELFUniquingMap.insert(std::make_pair(SectionGroupPair(Name, GroupName),
241                                            Section)).first;
242   StringRef CachedName = I->first.first;
243   const_cast<MCSectionELF*>(Section)->setSectionName(CachedName);
244 }
245
246 const MCSectionELF *MCContext::
247 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
248               SectionKind Kind, unsigned EntrySize, StringRef Group) {
249   // Do the lookup, if we have a hit, return it.
250   auto IterBool = ELFUniquingMap.insert(
251       std::make_pair(SectionGroupPair(Section, Group), nullptr));
252   auto &Entry = *IterBool.first;
253   if (!IterBool.second) return Entry.second;
254
255   // Possibly refine the entry size first.
256   if (!EntrySize) {
257     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
258   }
259
260   MCSymbol *GroupSym = nullptr;
261   if (!Group.empty())
262     GroupSym = GetOrCreateSymbol(Group);
263
264   StringRef CachedName = Entry.first.first;
265   MCSectionELF *Result = new (*this)
266       MCSectionELF(CachedName, Type, Flags, Kind, EntrySize, GroupSym);
267   Entry.second = Result;
268   return Result;
269 }
270
271 const MCSectionELF *MCContext::CreateELFGroupSection() {
272   MCSectionELF *Result =
273     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
274                              SectionKind::getReadOnly(), 4, nullptr);
275   return Result;
276 }
277
278 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
279                                                unsigned Characteristics,
280                                                SectionKind Kind,
281                                                StringRef COMDATSymName,
282                                                int Selection) {
283   // Do the lookup, if we have a hit, return it.
284
285   SectionGroupPair P(Section, COMDATSymName);
286   auto IterBool = COFFUniquingMap.insert(std::make_pair(P, nullptr));
287   auto Iter = IterBool.first;
288   if (!IterBool.second)
289     return Iter->second;
290
291   const MCSymbol *COMDATSymbol = nullptr;
292   if (!COMDATSymName.empty())
293     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
294
295   StringRef CachedName = Iter->first.first;
296   MCSectionCOFF *Result = new (*this)
297       MCSectionCOFF(CachedName, Characteristics, COMDATSymbol, Selection, Kind);
298
299   Iter->second = Result;
300   return Result;
301 }
302
303 const MCSectionCOFF *
304 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
305                           SectionKind Kind) {
306   return getCOFFSection(Section, Characteristics, Kind, "", 0);
307 }
308
309 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
310   SectionGroupPair P(Section, "");
311   auto Iter = COFFUniquingMap.find(P);
312   if (Iter == COFFUniquingMap.end())
313     return nullptr;
314   return Iter->second;
315 }
316
317 //===----------------------------------------------------------------------===//
318 // Dwarf Management
319 //===----------------------------------------------------------------------===//
320
321 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
322 /// directory tables.  If the file number has already been allocated it is an
323 /// error and zero is returned and the client reports the error, else the
324 /// allocated file number is returned.  The file numbers may be in any order.
325 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
326                                  unsigned FileNumber, unsigned CUID) {
327   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
328   return Table.getFile(Directory, FileName, FileNumber);
329 }
330
331 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
332 /// currently is assigned and false otherwise.
333 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
334   const SmallVectorImpl<MCDwarfFile>& MCDwarfFiles = getMCDwarfFiles(CUID);
335   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
336     return false;
337
338   return !MCDwarfFiles[FileNumber].Name.empty();
339 }
340
341 /// finalizeDwarfSections - Emit end symbols for each non-empty code section.
342 /// Also remove empty sections from SectionStartEndSyms, to avoid generating
343 /// useless debug info for them.
344 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
345   MCContext &context = MCOS.getContext();
346
347   auto sec = SectionStartEndSyms.begin();
348   while (sec != SectionStartEndSyms.end()) {
349     assert(sec->second.first && "Start symbol must be set by now");
350     MCOS.SwitchSection(sec->first);
351     if (MCOS.mayHaveInstructions()) {
352       MCSymbol *SectionEndSym = context.CreateTempSymbol();
353       MCOS.EmitLabel(SectionEndSym);
354       sec->second.second = SectionEndSym;
355       ++sec;
356     } else {
357       MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> >::iterator
358         to_erase = sec;
359       sec = SectionStartEndSyms.erase(to_erase);
360     }
361   }
362 }
363
364 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) const {
365   // If we have a source manager and a location, use it. Otherwise just
366   // use the generic report_fatal_error().
367   if (!SrcMgr || Loc == SMLoc())
368     report_fatal_error(Msg, false);
369
370   // Use the source manager to print the message.
371   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
372
373   // If we reached here, we are failing ungracefully. Run the interrupt handlers
374   // to make sure any special cleanups get done, in particular that we remove
375   // files registered with RemoveFileOnSignal.
376   sys::RunInterruptHandlers();
377   exit(1);
378 }