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/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/SourceMgr.h"
30 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
31 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
32 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
35 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
36 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
38 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
39 Allocator(), Symbols(Allocator), UsedNames(Allocator),
41 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
42 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
43 AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
45 error_code EC = llvm::sys::fs::current_path(CompilationDir);
46 assert(!EC && "Could not determine the current directory");
52 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
54 SecureLogUsed = false;
56 if (SrcMgr && SrcMgr->getNumBuffers() > 0)
57 MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
62 MCContext::~MCContext() {
67 // NOTE: The symbols are all allocated out of a bump pointer allocator,
68 // we don't need to free them here.
70 // If the stream for the .secure_log_unique directive was created free it.
71 delete (raw_ostream*)SecureLog;
74 //===----------------------------------------------------------------------===//
75 // Module Lifetime Management
76 //===----------------------------------------------------------------------===//
78 void MCContext::reset() {
83 MCDwarfFilesCUMap.clear();
84 MCDwarfDirsCUMap.clear();
85 MCGenDwarfLabelEntries.clear();
86 DwarfDebugFlags = StringRef();
87 MCLineSections.clear();
88 MCLineSectionOrder.clear();
89 DwarfCompileUnitID = 0;
90 MCLineTableSymbols.clear();
91 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
93 // If we have the MachO uniquing map, free it.
94 delete (MachOUniqueMapTy*)MachOUniquingMap;
95 delete (ELFUniqueMapTy*)ELFUniquingMap;
96 delete (COFFUniqueMapTy*)COFFUniquingMap;
102 AllowTemporaryLabels = true;
103 DwarfLocSeen = false;
104 GenDwarfForAssembly = false;
105 GenDwarfFileNumber = 0;
108 //===----------------------------------------------------------------------===//
109 // Symbol Manipulation
110 //===----------------------------------------------------------------------===//
112 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
113 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
115 // Do the lookup and get the entire StringMapEntry. We want access to the
116 // key if we are creating the entry.
117 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
118 MCSymbol *Sym = Entry.getValue();
123 Sym = CreateSymbol(Name);
128 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
129 // Determine whether this is an assembler temporary or normal label, if used.
130 bool isTemporary = false;
131 if (AllowTemporaryLabels)
132 isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
134 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
135 if (NameEntry->getValue()) {
136 assert(isTemporary && "Cannot rename non temporary symbols");
137 SmallString<128> NewName = Name;
139 NewName.resize(Name.size());
140 raw_svector_ostream(NewName) << NextUniqueID++;
141 NameEntry = &UsedNames.GetOrCreateValue(NewName);
142 } while (NameEntry->getValue());
144 NameEntry->setValue(true);
146 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
147 // to the copy of the string that is embedded in the UsedNames entry.
148 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
153 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
154 SmallString<128> NameSV;
155 Name.toVector(NameSV);
156 return GetOrCreateSymbol(NameSV.str());
159 MCSymbol *MCContext::CreateTempSymbol() {
160 SmallString<128> NameSV;
161 raw_svector_ostream(NameSV)
162 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
163 return CreateSymbol(NameSV);
166 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
167 MCLabel *&Label = Instances[LocalLabelVal];
169 Label = new (*this) MCLabel(0);
170 return Label->incInstance();
173 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
174 MCLabel *&Label = Instances[LocalLabelVal];
176 Label = new (*this) MCLabel(0);
177 return Label->getInstance();
180 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
181 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
182 Twine(LocalLabelVal) +
184 Twine(NextInstance(LocalLabelVal)));
186 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
188 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
189 Twine(LocalLabelVal) +
191 Twine(GetInstance(LocalLabelVal) + bORf));
194 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
195 return Symbols.lookup(Name);
198 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
199 SmallString<128> NameSV;
200 Name.toVector(NameSV);
201 return LookupSymbol(NameSV.str());
204 //===----------------------------------------------------------------------===//
205 // Section Management
206 //===----------------------------------------------------------------------===//
208 const MCSectionMachO *MCContext::
209 getMachOSection(StringRef Segment, StringRef Section,
210 unsigned TypeAndAttributes,
211 unsigned Reserved2, SectionKind Kind) {
213 // We unique sections by their segment/section pair. The returned section
214 // may not have the same flags as the requested section, if so this should be
215 // diagnosed by the client as an error.
217 // Create the map if it doesn't already exist.
218 if (MachOUniquingMap == 0)
219 MachOUniquingMap = new MachOUniqueMapTy();
220 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
222 // Form the name to look up.
223 SmallString<64> Name;
228 // Do the lookup, if we have a hit, return it.
229 const MCSectionMachO *&Entry = Map[Name.str()];
230 if (Entry) return Entry;
232 // Otherwise, return a new section.
233 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
237 const MCSectionELF *MCContext::
238 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
240 return getELFSection(Section, Type, Flags, Kind, 0, "");
243 const MCSectionELF *MCContext::
244 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
245 SectionKind Kind, unsigned EntrySize, StringRef Group) {
246 if (ELFUniquingMap == 0)
247 ELFUniquingMap = new ELFUniqueMapTy();
248 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
250 // Do the lookup, if we have a hit, return it.
251 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
252 if (Entry.getValue()) return Entry.getValue();
254 // Possibly refine the entry size first.
256 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
259 MCSymbol *GroupSym = NULL;
261 GroupSym = GetOrCreateSymbol(Group);
263 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
264 Kind, EntrySize, GroupSym);
265 Entry.setValue(Result);
269 const MCSectionELF *MCContext::CreateELFGroupSection() {
270 MCSectionELF *Result =
271 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
272 SectionKind::getReadOnly(), 4, NULL);
276 const MCSection *MCContext::getCOFFSection(StringRef Section,
277 unsigned Characteristics,
280 if (COFFUniquingMap == 0)
281 COFFUniquingMap = new COFFUniqueMapTy();
282 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
284 // Do the lookup, if we have a hit, return it.
285 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
286 if (Entry.getValue()) return Entry.getValue();
288 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
292 Entry.setValue(Result);
296 //===----------------------------------------------------------------------===//
298 //===----------------------------------------------------------------------===//
300 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
301 /// directory tables. If the file number has already been allocated it is an
302 /// error and zero is returned and the client reports the error, else the
303 /// allocated file number is returned. The file numbers may be in any order.
304 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
305 unsigned FileNumber, unsigned CUID) {
306 // TODO: a FileNumber of zero says to use the next available file number.
307 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
308 // to not be less than one. This needs to be change to be not less than zero.
310 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
311 SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
312 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
313 if (FileNumber >= MCDwarfFiles.size()) {
314 MCDwarfFiles.resize(FileNumber + 1);
316 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
318 // It is an error to use see the same number more than once.
322 // Get the new MCDwarfFile slot for this FileNumber.
323 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
325 if (Directory.empty()) {
326 // Separate the directory part from the basename of the FileName.
327 StringRef tFileName = sys::path::filename(FileName);
328 if (!tFileName.empty()) {
329 Directory = sys::path::parent_path(FileName);
330 if (!Directory.empty())
331 FileName = tFileName;
335 // Find or make a entry in the MCDwarfDirs vector for this Directory.
336 // Capture directory name.
338 if (Directory.empty()) {
339 // For FileNames with no directories a DirIndex of 0 is used.
343 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
344 if (Directory == MCDwarfDirs[DirIndex])
347 if (DirIndex >= MCDwarfDirs.size()) {
348 char *Buf = static_cast<char *>(Allocate(Directory.size()));
349 memcpy(Buf, Directory.data(), Directory.size());
350 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
352 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
353 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
354 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
355 // are stored at MCDwarfFiles[FileNumber].Name .
359 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
361 char *Buf = static_cast<char *>(Allocate(FileName.size()));
362 memcpy(Buf, FileName.data(), FileName.size());
363 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
365 // return the allocated FileNumber.
369 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
370 /// currently is assigned and false otherwise.
371 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
372 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
373 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
376 return MCDwarfFiles[FileNumber] != 0;
379 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
380 // If we have a source manager and a location, use it. Otherwise just
381 // use the generic report_fatal_error().
382 if (!SrcMgr || Loc == SMLoc())
383 report_fatal_error(Msg);
385 // Use the source manager to print the message.
386 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
388 // If we reached here, we are failing ungracefully. Run the interrupt handlers
389 // to make sure any special cleanups get done, in particular that we remove
390 // files registered with RemoveFileOnSignal.
391 sys::RunInterruptHandlers();