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