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), DwarfCompileUnitID(0), 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 DwarfCompileUnitID = 0;
87 MCLineTableSymbols.clear();
88 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
90 // If we have the MachO uniquing map, free it.
91 delete (MachOUniqueMapTy*)MachOUniquingMap;
92 delete (ELFUniqueMapTy*)ELFUniquingMap;
93 delete (COFFUniqueMapTy*)COFFUniquingMap;
99 AllowTemporaryLabels = true;
100 DwarfLocSeen = false;
101 GenDwarfForAssembly = false;
102 GenDwarfFileNumber = 0;
105 //===----------------------------------------------------------------------===//
106 // Symbol Manipulation
107 //===----------------------------------------------------------------------===//
109 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
110 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
112 // Do the lookup and get the entire StringMapEntry. We want access to the
113 // key if we are creating the entry.
114 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
115 MCSymbol *Sym = Entry.getValue();
120 Sym = CreateSymbol(Name);
125 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
126 // Determine whether this is an assembler temporary or normal label, if used.
127 bool isTemporary = false;
128 if (AllowTemporaryLabels)
129 isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
131 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
132 if (NameEntry->getValue()) {
133 assert(isTemporary && "Cannot rename non temporary symbols");
134 SmallString<128> NewName = Name;
136 NewName.resize(Name.size());
137 raw_svector_ostream(NewName) << NextUniqueID++;
138 NameEntry = &UsedNames.GetOrCreateValue(NewName);
139 } while (NameEntry->getValue());
141 NameEntry->setValue(true);
143 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
144 // to the copy of the string that is embedded in the UsedNames entry.
145 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
150 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
151 SmallString<128> NameSV;
152 Name.toVector(NameSV);
153 return GetOrCreateSymbol(NameSV.str());
156 MCSymbol *MCContext::CreateTempSymbol() {
157 SmallString<128> NameSV;
158 raw_svector_ostream(NameSV)
159 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
160 return CreateSymbol(NameSV);
163 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
164 MCLabel *&Label = Instances[LocalLabelVal];
166 Label = new (*this) MCLabel(0);
167 return Label->incInstance();
170 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
171 MCLabel *&Label = Instances[LocalLabelVal];
173 Label = new (*this) MCLabel(0);
174 return Label->getInstance();
177 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
178 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
179 Twine(LocalLabelVal) +
181 Twine(NextInstance(LocalLabelVal)));
183 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
185 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
186 Twine(LocalLabelVal) +
188 Twine(GetInstance(LocalLabelVal) + bORf));
191 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
192 return Symbols.lookup(Name);
195 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
196 SmallString<128> NameSV;
197 Name.toVector(NameSV);
198 return LookupSymbol(NameSV.str());
201 //===----------------------------------------------------------------------===//
202 // Section Management
203 //===----------------------------------------------------------------------===//
205 const MCSectionMachO *MCContext::
206 getMachOSection(StringRef Segment, StringRef Section,
207 unsigned TypeAndAttributes,
208 unsigned Reserved2, SectionKind Kind) {
210 // We unique sections by their segment/section pair. The returned section
211 // may not have the same flags as the requested section, if so this should be
212 // diagnosed by the client as an error.
214 // Create the map if it doesn't already exist.
215 if (MachOUniquingMap == 0)
216 MachOUniquingMap = new MachOUniqueMapTy();
217 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
219 // Form the name to look up.
220 SmallString<64> Name;
225 // Do the lookup, if we have a hit, return it.
226 const MCSectionMachO *&Entry = Map[Name.str()];
227 if (Entry) return Entry;
229 // Otherwise, return a new section.
230 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
234 const MCSectionELF *MCContext::
235 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
237 return getELFSection(Section, Type, Flags, Kind, 0, "");
240 const MCSectionELF *MCContext::
241 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
242 SectionKind Kind, unsigned EntrySize, StringRef Group) {
243 if (ELFUniquingMap == 0)
244 ELFUniquingMap = new ELFUniqueMapTy();
245 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
247 // Do the lookup, if we have a hit, return it.
248 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
249 if (Entry.getValue()) return Entry.getValue();
251 // Possibly refine the entry size first.
253 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
256 MCSymbol *GroupSym = NULL;
258 GroupSym = GetOrCreateSymbol(Group);
260 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
261 Kind, EntrySize, GroupSym);
262 Entry.setValue(Result);
266 const MCSectionELF *MCContext::CreateELFGroupSection() {
267 MCSectionELF *Result =
268 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
269 SectionKind::getReadOnly(), 4, NULL);
273 const MCSection *MCContext::getCOFFSection(StringRef Section,
274 unsigned Characteristics,
277 if (COFFUniquingMap == 0)
278 COFFUniquingMap = new COFFUniqueMapTy();
279 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
281 // Do the lookup, if we have a hit, return it.
282 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
283 if (Entry.getValue()) return Entry.getValue();
285 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
289 Entry.setValue(Result);
293 //===----------------------------------------------------------------------===//
295 //===----------------------------------------------------------------------===//
297 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
298 /// directory tables. If the file number has already been allocated it is an
299 /// error and zero is returned and the client reports the error, else the
300 /// allocated file number is returned. The file numbers may be in any order.
301 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
302 unsigned FileNumber) {
303 // TODO: a FileNumber of zero says to use the next available file number.
304 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
305 // to not be less than one. This needs to be change to be not less than zero.
307 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
308 if (FileNumber >= MCDwarfFiles.size()) {
309 MCDwarfFiles.resize(FileNumber + 1);
311 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
313 // It is an error to use see the same number more than once.
317 // Get the new MCDwarfFile slot for this FileNumber.
318 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
320 if (Directory.empty()) {
321 // Separate the directory part from the basename of the FileName.
322 StringRef tFileName = sys::path::filename(FileName);
323 if (!tFileName.empty()) {
324 Directory = sys::path::parent_path(FileName);
325 if (!Directory.empty())
326 FileName = tFileName;
330 // Find or make a entry in the MCDwarfDirs vector for this Directory.
331 // Capture directory name.
333 if (Directory.empty()) {
334 // For FileNames with no directories a DirIndex of 0 is used.
338 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
339 if (Directory == MCDwarfDirs[DirIndex])
342 if (DirIndex >= MCDwarfDirs.size()) {
343 char *Buf = static_cast<char *>(Allocate(Directory.size()));
344 memcpy(Buf, Directory.data(), Directory.size());
345 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
347 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
348 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
349 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
350 // are stored at MCDwarfFiles[FileNumber].Name .
354 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
356 char *Buf = static_cast<char *>(Allocate(FileName.size()));
357 memcpy(Buf, FileName.data(), FileName.size());
358 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
360 // return the allocated FileNumber.
364 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
365 /// currently is assigned and false otherwise.
366 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
367 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
370 return MCDwarfFiles[FileNumber] != 0;
373 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
374 // If we have a source manager and a location, use it. Otherwise just
375 // use the generic report_fatal_error().
376 if (!SrcMgr || Loc == SMLoc())
377 report_fatal_error(Msg);
379 // Use the source manager to print the message.
380 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
382 // If we reached here, we are failing ungracefully. Run the interrupt handlers
383 // to make sure any special cleanups get done, in particular that we remove
384 // files registered with RemoveFileOnSignal.
385 sys::RunInterruptHandlers();