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