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