1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
28 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
29 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
30 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
33 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
34 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
36 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
37 Allocator(), Symbols(Allocator), UsedNames(Allocator),
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) {
48 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
50 SecureLogUsed = false;
53 MCContext::~MCContext() {
58 // NOTE: The symbols are all allocated out of a bump pointer allocator,
59 // we don't need to free them here.
61 // If the stream for the .secure_log_unique directive was created free it.
62 delete (raw_ostream*)SecureLog;
65 //===----------------------------------------------------------------------===//
66 // Module Lifetime Management
67 //===----------------------------------------------------------------------===//
69 void MCContext::reset() {
76 MCGenDwarfLabelEntries.clear();
77 DwarfDebugFlags = StringRef();
78 MCLineSections.clear();
79 MCLineSectionOrder.clear();
80 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
82 // If we have the MachO uniquing map, free it.
83 delete (MachOUniqueMapTy*)MachOUniquingMap;
84 delete (ELFUniqueMapTy*)ELFUniquingMap;
85 delete (COFFUniqueMapTy*)COFFUniquingMap;
91 AllowTemporaryLabels = true;
93 GenDwarfForAssembly = false;
94 GenDwarfFileNumber = 0;
97 //===----------------------------------------------------------------------===//
98 // Symbol Manipulation
99 //===----------------------------------------------------------------------===//
101 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
102 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
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();
112 Sym = CreateSymbol(Name);
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());
123 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
124 if (NameEntry->getValue()) {
125 assert(isTemporary && "Cannot rename non temporary symbols");
126 SmallString<128> NewName = Name;
128 NewName.resize(Name.size());
129 raw_svector_ostream(NewName) << NextUniqueID++;
130 NameEntry = &UsedNames.GetOrCreateValue(NewName);
131 } while (NameEntry->getValue());
133 NameEntry->setValue(true);
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);
142 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
143 SmallString<128> NameSV;
144 Name.toVector(NameSV);
145 return GetOrCreateSymbol(NameSV.str());
148 MCSymbol *MCContext::CreateTempSymbol() {
149 SmallString<128> NameSV;
150 raw_svector_ostream(NameSV)
151 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
152 return CreateSymbol(NameSV);
155 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
156 MCLabel *&Label = Instances[LocalLabelVal];
158 Label = new (*this) MCLabel(0);
159 return Label->incInstance();
162 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
163 MCLabel *&Label = Instances[LocalLabelVal];
165 Label = new (*this) MCLabel(0);
166 return Label->getInstance();
169 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
170 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
171 Twine(LocalLabelVal) +
173 Twine(NextInstance(LocalLabelVal)));
175 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
177 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
178 Twine(LocalLabelVal) +
180 Twine(GetInstance(LocalLabelVal) + bORf));
183 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
184 return Symbols.lookup(Name);
187 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
188 SmallString<128> NameSV;
189 Name.toVector(NameSV);
190 return LookupSymbol(NameSV.str());
193 //===----------------------------------------------------------------------===//
194 // Section Management
195 //===----------------------------------------------------------------------===//
197 const MCSectionMachO *MCContext::
198 getMachOSection(StringRef Segment, StringRef Section,
199 unsigned TypeAndAttributes,
200 unsigned Reserved2, SectionKind Kind) {
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.
206 // Create the map if it doesn't already exist.
207 if (MachOUniquingMap == 0)
208 MachOUniquingMap = new MachOUniqueMapTy();
209 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
211 // Form the name to look up.
212 SmallString<64> Name;
217 // Do the lookup, if we have a hit, return it.
218 const MCSectionMachO *&Entry = Map[Name.str()];
219 if (Entry) return Entry;
221 // Otherwise, return a new section.
222 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
226 const MCSectionELF *MCContext::
227 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
229 return getELFSection(Section, Type, Flags, Kind, 0, "");
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;
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();
243 // Possibly refine the entry size first.
245 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
248 MCSymbol *GroupSym = NULL;
250 GroupSym = GetOrCreateSymbol(Group);
252 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
253 Kind, EntrySize, GroupSym);
254 Entry.setValue(Result);
258 const MCSectionELF *MCContext::CreateELFGroupSection() {
259 MCSectionELF *Result =
260 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
261 SectionKind::getReadOnly(), 4, NULL);
265 const MCSection *MCContext::getCOFFSection(StringRef Section,
266 unsigned Characteristics,
269 if (COFFUniquingMap == 0)
270 COFFUniquingMap = new COFFUniqueMapTy();
271 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
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();
277 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
281 Entry.setValue(Result);
285 //===----------------------------------------------------------------------===//
287 //===----------------------------------------------------------------------===//
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.
299 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
300 if (FileNumber >= MCDwarfFiles.size()) {
301 MCDwarfFiles.resize(FileNumber + 1);
303 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
305 // It is an error to use see the same number more than once.
309 // Get the new MCDwarfFile slot for this FileNumber.
310 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
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;
322 // Find or make a entry in the MCDwarfDirs vector for this Directory.
323 // Capture directory name.
325 if (Directory.empty()) {
326 // For FileNames with no directories a DirIndex of 0 is used.
330 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
331 if (Directory == MCDwarfDirs[DirIndex])
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()));
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 .
346 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
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);
352 // return the allocated FileNumber.
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())
362 return MCDwarfFiles[FileNumber] != 0;
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);
371 // Use the source manager to print the message.
372 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
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();