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