MCDwarf: Refactor line table handling into a single data structure
[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 typedef std::pair<std::string, std::string> SectionGroupPair;
33
34 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
35 typedef std::map<SectionGroupPair, const MCSectionELF *> ELFUniqueMapTy;
36 typedef std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniqueMapTy;
37
38 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
39                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
40                      bool DoAutoReset) :
41   SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
42   Allocator(), Symbols(Allocator), UsedNames(Allocator),
43   NextUniqueID(0),
44   CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
45   DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
46   AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
47
48   error_code EC = llvm::sys::fs::current_path(CompilationDir);
49   if (EC)
50     CompilationDir.clear();
51
52   MachOUniquingMap = 0;
53   ELFUniquingMap = 0;
54   COFFUniquingMap = 0;
55
56   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
57   SecureLog = 0;
58   SecureLogUsed = false;
59
60   if (SrcMgr && SrcMgr->getNumBuffers() > 0)
61     MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
62   else
63     MainFileName = "";
64 }
65
66 MCContext::~MCContext() {
67
68   if (AutoReset)
69     reset();
70
71   // NOTE: The symbols are all allocated out of a bump pointer allocator,
72   // we don't need to free them here.
73
74   // If the stream for the .secure_log_unique directive was created free it.
75   delete (raw_ostream*)SecureLog;
76 }
77
78 //===----------------------------------------------------------------------===//
79 // Module Lifetime Management
80 //===----------------------------------------------------------------------===//
81
82 void MCContext::reset() {
83   UsedNames.clear();
84   Symbols.clear();
85   Allocator.Reset();
86   Instances.clear();
87   MCDwarfFileTablesCUMap.clear();
88   MCGenDwarfLabelEntries.clear();
89   DwarfDebugFlags = StringRef();
90   DwarfCompileUnitID = 0;
91   CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
92
93   // If we have the MachO uniquing map, free it.
94   delete (MachOUniqueMapTy*)MachOUniquingMap;
95   delete (ELFUniqueMapTy*)ELFUniquingMap;
96   delete (COFFUniqueMapTy*)COFFUniquingMap;
97   MachOUniquingMap = 0;
98   ELFUniquingMap = 0;
99   COFFUniquingMap = 0;
100
101   NextUniqueID = 0;
102   AllowTemporaryLabels = true;
103   DwarfLocSeen = false;
104   GenDwarfForAssembly = false;
105   GenDwarfFileNumber = 0;
106 }
107
108 //===----------------------------------------------------------------------===//
109 // Symbol Manipulation
110 //===----------------------------------------------------------------------===//
111
112 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
113   assert(!Name.empty() && "Normal symbols cannot be unnamed!");
114
115   // Do the lookup and get the entire StringMapEntry.  We want access to the
116   // key if we are creating the entry.
117   StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
118   MCSymbol *Sym = Entry.getValue();
119
120   if (Sym)
121     return Sym;
122
123   Sym = CreateSymbol(Name);
124   Entry.setValue(Sym);
125   return Sym;
126 }
127
128 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
129   // Determine whether this is an assembler temporary or normal label, if used.
130   bool isTemporary = false;
131   if (AllowTemporaryLabels)
132     isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
133
134   StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
135   if (NameEntry->getValue()) {
136     assert(isTemporary && "Cannot rename non-temporary symbols");
137     SmallString<128> NewName = Name;
138     do {
139       NewName.resize(Name.size());
140       raw_svector_ostream(NewName) << NextUniqueID++;
141       NameEntry = &UsedNames.GetOrCreateValue(NewName);
142     } while (NameEntry->getValue());
143   }
144   NameEntry->setValue(true);
145
146   // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
147   // to the copy of the string that is embedded in the UsedNames entry.
148   MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
149
150   return Result;
151 }
152
153 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
154   SmallString<128> NameSV;
155   return GetOrCreateSymbol(Name.toStringRef(NameSV));
156 }
157
158 MCSymbol *MCContext::CreateTempSymbol() {
159   SmallString<128> NameSV;
160   raw_svector_ostream(NameSV)
161     << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
162   return CreateSymbol(NameSV);
163 }
164
165 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
166   MCLabel *&Label = Instances[LocalLabelVal];
167   if (!Label)
168     Label = new (*this) MCLabel(0);
169   return Label->incInstance();
170 }
171
172 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
173   MCLabel *&Label = Instances[LocalLabelVal];
174   if (!Label)
175     Label = new (*this) MCLabel(0);
176   return Label->getInstance();
177 }
178
179 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
180   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
181                            Twine(LocalLabelVal) +
182                            "\2" +
183                            Twine(NextInstance(LocalLabelVal)));
184 }
185 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
186                                                int bORf) {
187   return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
188                            Twine(LocalLabelVal) +
189                            "\2" +
190                            Twine(GetInstance(LocalLabelVal) + bORf));
191 }
192
193 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
194   return Symbols.lookup(Name);
195 }
196
197 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
198   SmallString<128> NameSV;
199   Name.toVector(NameSV);
200   return LookupSymbol(NameSV.str());
201 }
202
203 //===----------------------------------------------------------------------===//
204 // Section Management
205 //===----------------------------------------------------------------------===//
206
207 const MCSectionMachO *MCContext::
208 getMachOSection(StringRef Segment, StringRef Section,
209                 unsigned TypeAndAttributes,
210                 unsigned Reserved2, SectionKind Kind) {
211
212   // We unique sections by their segment/section pair.  The returned section
213   // may not have the same flags as the requested section, if so this should be
214   // diagnosed by the client as an error.
215
216   // Create the map if it doesn't already exist.
217   if (MachOUniquingMap == 0)
218     MachOUniquingMap = new MachOUniqueMapTy();
219   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
220
221   // Form the name to look up.
222   SmallString<64> Name;
223   Name += Segment;
224   Name.push_back(',');
225   Name += Section;
226
227   // Do the lookup, if we have a hit, return it.
228   const MCSectionMachO *&Entry = Map[Name.str()];
229   if (Entry) return Entry;
230
231   // Otherwise, return a new section.
232   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
233                                             Reserved2, Kind);
234 }
235
236 const MCSectionELF *MCContext::
237 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
238               SectionKind Kind) {
239   return getELFSection(Section, Type, Flags, Kind, 0, "");
240 }
241
242 const MCSectionELF *MCContext::
243 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
244               SectionKind Kind, unsigned EntrySize, StringRef Group) {
245   if (ELFUniquingMap == 0)
246     ELFUniquingMap = new ELFUniqueMapTy();
247   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
248
249   // Do the lookup, if we have a hit, return it.
250   std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert(
251       std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0));
252   if (!Entry.second) return Entry.first->second;
253
254   // Possibly refine the entry size first.
255   if (!EntrySize) {
256     EntrySize = MCSectionELF::DetermineEntrySize(Kind);
257   }
258
259   MCSymbol *GroupSym = NULL;
260   if (!Group.empty())
261     GroupSym = GetOrCreateSymbol(Group);
262
263   MCSectionELF *Result = new (*this) MCSectionELF(
264       Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym);
265   Entry.first->second = Result;
266   return Result;
267 }
268
269 const MCSectionELF *MCContext::CreateELFGroupSection() {
270   MCSectionELF *Result =
271     new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
272                              SectionKind::getReadOnly(), 4, NULL);
273   return Result;
274 }
275
276 const MCSectionCOFF *
277 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
278                           SectionKind Kind, StringRef COMDATSymName,
279                           int Selection, const MCSectionCOFF *Assoc) {
280   if (COFFUniquingMap == 0)
281     COFFUniquingMap = new COFFUniqueMapTy();
282   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
283
284   // Do the lookup, if we have a hit, return it.
285
286   SectionGroupPair P(Section, COMDATSymName);
287   std::pair<COFFUniqueMapTy::iterator, bool> Entry =
288       Map.insert(std::make_pair(P, (MCSectionCOFF *)0));
289   COFFUniqueMapTy::iterator Iter = Entry.first;
290   if (!Entry.second)
291     return Iter->second;
292
293   const MCSymbol *COMDATSymbol = NULL;
294   if (!COMDATSymName.empty())
295     COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
296
297   MCSectionCOFF *Result =
298       new (*this) MCSectionCOFF(Iter->first.first, Characteristics,
299                                 COMDATSymbol, Selection, Assoc, Kind);
300
301   Iter->second = Result;
302   return Result;
303 }
304
305 const MCSectionCOFF *
306 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
307                           SectionKind Kind) {
308   return getCOFFSection(Section, Characteristics, Kind, "", 0);
309 }
310
311 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
312   if (COFFUniquingMap == 0)
313     COFFUniquingMap = new COFFUniqueMapTy();
314   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
315
316   SectionGroupPair P(Section, "");
317   COFFUniqueMapTy::iterator Iter = Map.find(P);
318   if (Iter == Map.end())
319     return 0;
320   return Iter->second;
321 }
322
323 //===----------------------------------------------------------------------===//
324 // Dwarf Management
325 //===----------------------------------------------------------------------===//
326
327 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
328 /// directory tables.  If the file number has already been allocated it is an
329 /// error and zero is returned and the client reports the error, else the
330 /// allocated file number is returned.  The file numbers may be in any order.
331 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
332                                  unsigned FileNumber, unsigned CUID) {
333   // TODO: a FileNumber of zero says to use the next available file number.
334   // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
335   // to not be less than one.  This needs to be change to be not less than zero.
336
337   MCDwarfFileTable &Table = MCDwarfFileTablesCUMap[CUID];
338   SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = Table.getMCDwarfFiles();
339   SmallVectorImpl<StringRef>& MCDwarfDirs = Table.getMCDwarfDirs();
340   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
341   if (FileNumber >= MCDwarfFiles.size()) {
342     MCDwarfFiles.resize(FileNumber + 1);
343   } else {
344     MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
345     if (ExistingFile)
346       // It is an error to use see the same number more than once.
347       return 0;
348   }
349
350   // Get the new MCDwarfFile slot for this FileNumber.
351   MCDwarfFile *&File = MCDwarfFiles[FileNumber];
352
353   if (Directory.empty()) {
354     // Separate the directory part from the basename of the FileName.
355     StringRef tFileName = sys::path::filename(FileName);
356     if (!tFileName.empty()) {
357       Directory = sys::path::parent_path(FileName);
358       if (!Directory.empty())
359         FileName = tFileName;
360     }
361   }
362
363   // Find or make an entry in the MCDwarfDirs vector for this Directory.
364   // Capture directory name.
365   unsigned DirIndex;
366   if (Directory.empty()) {
367     // For FileNames with no directories a DirIndex of 0 is used.
368     DirIndex = 0;
369   } else {
370     DirIndex = 0;
371     for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
372       if (Directory == MCDwarfDirs[DirIndex])
373         break;
374     }
375     if (DirIndex >= MCDwarfDirs.size()) {
376       char *Buf = static_cast<char *>(Allocate(Directory.size()));
377       memcpy(Buf, Directory.data(), Directory.size());
378       MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
379     }
380     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
381     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
382     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
383     // are stored at MCDwarfFiles[FileNumber].Name .
384     DirIndex++;
385   }
386
387   // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
388   // vector.
389   char *Buf = static_cast<char *>(Allocate(FileName.size()));
390   memcpy(Buf, FileName.data(), FileName.size());
391   File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
392
393   // return the allocated FileNumber.
394   return FileNumber;
395 }
396
397 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
398 /// currently is assigned and false otherwise.
399 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
400   const SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = getMCDwarfFiles(CUID);
401   if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
402     return false;
403
404   return MCDwarfFiles[FileNumber] != 0;
405 }
406
407 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
408   // If we have a source manager and a location, use it. Otherwise just
409   // use the generic report_fatal_error().
410   if (!SrcMgr || Loc == SMLoc())
411     report_fatal_error(Msg);
412
413   // Use the source manager to print the message.
414   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
415
416   // If we reached here, we are failing ungracefully. Run the interrupt handlers
417   // to make sure any special cleanups get done, in particular that we remove
418   // files registered with RemoveFileOnSignal.
419   sys::RunInterruptHandlers();
420   exit(1);
421 }