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/MemoryBuffer.h"
25 #include "llvm/Support/Signals.h"
26 #include "llvm/Support/SourceMgr.h"
29 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
30 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
31 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
34 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
35 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
37 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
38 Allocator(), Symbols(Allocator), UsedNames(Allocator),
40 CompilationDir(llvm::sys::Path::GetCurrentDirectory().str()),
41 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
42 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
43 AllowTemporaryLabels(true), AutoReset(DoAutoReset) {
49 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
51 SecureLogUsed = false;
53 if (SrcMgr && SrcMgr->getNumBuffers() > 0)
54 MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
59 MCContext::~MCContext() {
64 // NOTE: The symbols are all allocated out of a bump pointer allocator,
65 // we don't need to free them here.
67 // If the stream for the .secure_log_unique directive was created free it.
68 delete (raw_ostream*)SecureLog;
71 //===----------------------------------------------------------------------===//
72 // Module Lifetime Management
73 //===----------------------------------------------------------------------===//
75 void MCContext::reset() {
82 MCGenDwarfLabelEntries.clear();
83 DwarfDebugFlags = StringRef();
84 MCLineSections.clear();
85 MCLineSectionOrder.clear();
86 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
88 // If we have the MachO uniquing map, free it.
89 delete (MachOUniqueMapTy*)MachOUniquingMap;
90 delete (ELFUniqueMapTy*)ELFUniquingMap;
91 delete (COFFUniqueMapTy*)COFFUniquingMap;
97 AllowTemporaryLabels = true;
99 GenDwarfForAssembly = false;
100 GenDwarfFileNumber = 0;
103 //===----------------------------------------------------------------------===//
104 // Symbol Manipulation
105 //===----------------------------------------------------------------------===//
107 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
108 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
110 // Do the lookup and get the entire StringMapEntry. We want access to the
111 // key if we are creating the entry.
112 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
113 MCSymbol *Sym = Entry.getValue();
118 Sym = CreateSymbol(Name);
123 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
124 // Determine whether this is an assembler temporary or normal label, if used.
125 bool isTemporary = false;
126 if (AllowTemporaryLabels)
127 isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
129 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
130 if (NameEntry->getValue()) {
131 assert(isTemporary && "Cannot rename non temporary symbols");
132 SmallString<128> NewName = Name;
134 NewName.resize(Name.size());
135 raw_svector_ostream(NewName) << NextUniqueID++;
136 NameEntry = &UsedNames.GetOrCreateValue(NewName);
137 } while (NameEntry->getValue());
139 NameEntry->setValue(true);
141 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
142 // to the copy of the string that is embedded in the UsedNames entry.
143 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
148 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
149 SmallString<128> NameSV;
150 Name.toVector(NameSV);
151 return GetOrCreateSymbol(NameSV.str());
154 MCSymbol *MCContext::CreateTempSymbol() {
155 SmallString<128> NameSV;
156 raw_svector_ostream(NameSV)
157 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
158 return CreateSymbol(NameSV);
161 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
162 MCLabel *&Label = Instances[LocalLabelVal];
164 Label = new (*this) MCLabel(0);
165 return Label->incInstance();
168 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
169 MCLabel *&Label = Instances[LocalLabelVal];
171 Label = new (*this) MCLabel(0);
172 return Label->getInstance();
175 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
176 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
177 Twine(LocalLabelVal) +
179 Twine(NextInstance(LocalLabelVal)));
181 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
183 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
184 Twine(LocalLabelVal) +
186 Twine(GetInstance(LocalLabelVal) + bORf));
189 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
190 return Symbols.lookup(Name);
193 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
194 SmallString<128> NameSV;
195 Name.toVector(NameSV);
196 return LookupSymbol(NameSV.str());
199 //===----------------------------------------------------------------------===//
200 // Section Management
201 //===----------------------------------------------------------------------===//
203 const MCSectionMachO *MCContext::
204 getMachOSection(StringRef Segment, StringRef Section,
205 unsigned TypeAndAttributes,
206 unsigned Reserved2, SectionKind Kind) {
208 // We unique sections by their segment/section pair. The returned section
209 // may not have the same flags as the requested section, if so this should be
210 // diagnosed by the client as an error.
212 // Create the map if it doesn't already exist.
213 if (MachOUniquingMap == 0)
214 MachOUniquingMap = new MachOUniqueMapTy();
215 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
217 // Form the name to look up.
218 SmallString<64> Name;
223 // Do the lookup, if we have a hit, return it.
224 const MCSectionMachO *&Entry = Map[Name.str()];
225 if (Entry) return Entry;
227 // Otherwise, return a new section.
228 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
232 const MCSectionELF *MCContext::
233 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
235 return getELFSection(Section, Type, Flags, Kind, 0, "");
238 const MCSectionELF *MCContext::
239 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
240 SectionKind Kind, unsigned EntrySize, StringRef Group) {
241 if (ELFUniquingMap == 0)
242 ELFUniquingMap = new ELFUniqueMapTy();
243 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
245 // Do the lookup, if we have a hit, return it.
246 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
247 if (Entry.getValue()) return Entry.getValue();
249 // Possibly refine the entry size first.
251 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
254 MCSymbol *GroupSym = NULL;
256 GroupSym = GetOrCreateSymbol(Group);
258 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
259 Kind, EntrySize, GroupSym);
260 Entry.setValue(Result);
264 const MCSectionELF *MCContext::CreateELFGroupSection() {
265 MCSectionELF *Result =
266 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
267 SectionKind::getReadOnly(), 4, NULL);
271 const MCSection *MCContext::getCOFFSection(StringRef Section,
272 unsigned Characteristics,
275 if (COFFUniquingMap == 0)
276 COFFUniquingMap = new COFFUniqueMapTy();
277 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
279 // Do the lookup, if we have a hit, return it.
280 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
281 if (Entry.getValue()) return Entry.getValue();
283 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
287 Entry.setValue(Result);
291 //===----------------------------------------------------------------------===//
293 //===----------------------------------------------------------------------===//
295 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
296 /// directory tables. If the file number has already been allocated it is an
297 /// error and zero is returned and the client reports the error, else the
298 /// allocated file number is returned. The file numbers may be in any order.
299 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
300 unsigned FileNumber) {
301 // TODO: a FileNumber of zero says to use the next available file number.
302 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
303 // to not be less than one. This needs to be change to be not less than zero.
305 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
306 if (FileNumber >= MCDwarfFiles.size()) {
307 MCDwarfFiles.resize(FileNumber + 1);
309 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
311 // It is an error to use see the same number more than once.
315 // Get the new MCDwarfFile slot for this FileNumber.
316 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
318 if (Directory.empty()) {
319 // Separate the directory part from the basename of the FileName.
320 StringRef tFileName = sys::path::filename(FileName);
321 if (!tFileName.empty()) {
322 Directory = sys::path::parent_path(FileName);
323 if (!Directory.empty())
324 FileName = tFileName;
328 // Find or make a entry in the MCDwarfDirs vector for this Directory.
329 // Capture directory name.
331 if (Directory.empty()) {
332 // For FileNames with no directories a DirIndex of 0 is used.
336 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
337 if (Directory == MCDwarfDirs[DirIndex])
340 if (DirIndex >= MCDwarfDirs.size()) {
341 char *Buf = static_cast<char *>(Allocate(Directory.size()));
342 memcpy(Buf, Directory.data(), Directory.size());
343 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
345 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
346 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
347 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
348 // are stored at MCDwarfFiles[FileNumber].Name .
352 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
354 char *Buf = static_cast<char *>(Allocate(FileName.size()));
355 memcpy(Buf, FileName.data(), FileName.size());
356 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
358 // return the allocated FileNumber.
362 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
363 /// currently is assigned and false otherwise.
364 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
365 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
368 return MCDwarfFiles[FileNumber] != 0;
371 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
372 // If we have a source manager and a location, use it. Otherwise just
373 // use the generic report_fatal_error().
374 if (!SrcMgr || Loc == SMLoc())
375 report_fatal_error(Msg);
377 // Use the source manager to print the message.
378 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
380 // If we reached here, we are failing ungracefully. Run the interrupt handlers
381 // to make sure any special cleanups get done, in particular that we remove
382 // files registered with RemoveFileOnSignal.
383 sys::RunInterruptHandlers();