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