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