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,
35 bool DoAutoInitializationFinalization ) :
36 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
37 Allocator(), Symbols(Allocator), UsedNames(Allocator),
39 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
40 AllowTemporaryLabels(true),
41 AutoInitializationFinalization(DoAutoInitializationFinalization) {
46 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
48 SecureLogUsed = false;
50 if (AutoInitializationFinalization)
54 MCContext::~MCContext() {
56 if (AutoInitializationFinalization)
59 // NOTE: The symbols are all allocated out of a bump pointer allocator,
60 // we don't need to free them here.
62 // If the stream for the .secure_log_unique directive was created free it.
63 delete (raw_ostream*)SecureLog;
66 //===----------------------------------------------------------------------===//
67 // Module Lifetime Management
68 //===----------------------------------------------------------------------===//
70 void MCContext::doInitialization() {
72 AllowTemporaryLabels = true;
74 GenDwarfForAssembly = false;
75 GenDwarfFileNumber = 0;
78 void MCContext::doFinalization() {
85 MCGenDwarfLabelEntries.clear();
86 DwarfDebugFlags = StringRef();
87 MCLineSections.clear();
88 MCLineSectionOrder.clear();
89 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
91 // If we have the MachO uniquing map, free it.
92 delete (MachOUniqueMapTy*)MachOUniquingMap;
93 delete (ELFUniqueMapTy*)ELFUniquingMap;
94 delete (COFFUniqueMapTy*)COFFUniquingMap;
100 //===----------------------------------------------------------------------===//
101 // Symbol Manipulation
102 //===----------------------------------------------------------------------===//
104 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
105 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
107 // Do the lookup and get the entire StringMapEntry. We want access to the
108 // key if we are creating the entry.
109 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
110 MCSymbol *Sym = Entry.getValue();
115 Sym = CreateSymbol(Name);
120 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
121 // Determine whether this is an assembler temporary or normal label, if used.
122 bool isTemporary = false;
123 if (AllowTemporaryLabels)
124 isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
126 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
127 if (NameEntry->getValue()) {
128 assert(isTemporary && "Cannot rename non temporary symbols");
129 SmallString<128> NewName = Name;
131 NewName.resize(Name.size());
132 raw_svector_ostream(NewName) << NextUniqueID++;
133 NameEntry = &UsedNames.GetOrCreateValue(NewName);
134 } while (NameEntry->getValue());
136 NameEntry->setValue(true);
138 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
139 // to the copy of the string that is embedded in the UsedNames entry.
140 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
145 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
146 SmallString<128> NameSV;
147 Name.toVector(NameSV);
148 return GetOrCreateSymbol(NameSV.str());
151 MCSymbol *MCContext::CreateTempSymbol() {
152 SmallString<128> NameSV;
153 raw_svector_ostream(NameSV)
154 << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
155 return CreateSymbol(NameSV);
158 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
159 MCLabel *&Label = Instances[LocalLabelVal];
161 Label = new (*this) MCLabel(0);
162 return Label->incInstance();
165 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
166 MCLabel *&Label = Instances[LocalLabelVal];
168 Label = new (*this) MCLabel(0);
169 return Label->getInstance();
172 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
173 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
174 Twine(LocalLabelVal) +
176 Twine(NextInstance(LocalLabelVal)));
178 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
180 return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
181 Twine(LocalLabelVal) +
183 Twine(GetInstance(LocalLabelVal) + bORf));
186 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
187 return Symbols.lookup(Name);
190 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
191 SmallString<128> NameSV;
192 Name.toVector(NameSV);
193 return LookupSymbol(NameSV.str());
196 //===----------------------------------------------------------------------===//
197 // Section Management
198 //===----------------------------------------------------------------------===//
200 const MCSectionMachO *MCContext::
201 getMachOSection(StringRef Segment, StringRef Section,
202 unsigned TypeAndAttributes,
203 unsigned Reserved2, SectionKind Kind) {
205 // We unique sections by their segment/section pair. The returned section
206 // may not have the same flags as the requested section, if so this should be
207 // diagnosed by the client as an error.
209 // Create the map if it doesn't already exist.
210 if (MachOUniquingMap == 0)
211 MachOUniquingMap = new MachOUniqueMapTy();
212 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
214 // Form the name to look up.
215 SmallString<64> Name;
220 // Do the lookup, if we have a hit, return it.
221 const MCSectionMachO *&Entry = Map[Name.str()];
222 if (Entry) return Entry;
224 // Otherwise, return a new section.
225 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
229 const MCSectionELF *MCContext::
230 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
232 return getELFSection(Section, Type, Flags, Kind, 0, "");
235 const MCSectionELF *MCContext::
236 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
237 SectionKind Kind, unsigned EntrySize, StringRef Group) {
238 if (ELFUniquingMap == 0)
239 ELFUniquingMap = new ELFUniqueMapTy();
240 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
242 // Do the lookup, if we have a hit, return it.
243 StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
244 if (Entry.getValue()) return Entry.getValue();
246 // Possibly refine the entry size first.
248 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
251 MCSymbol *GroupSym = NULL;
253 GroupSym = GetOrCreateSymbol(Group);
255 MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
256 Kind, EntrySize, GroupSym);
257 Entry.setValue(Result);
261 const MCSectionELF *MCContext::CreateELFGroupSection() {
262 MCSectionELF *Result =
263 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
264 SectionKind::getReadOnly(), 4, NULL);
268 const MCSection *MCContext::getCOFFSection(StringRef Section,
269 unsigned Characteristics,
272 if (COFFUniquingMap == 0)
273 COFFUniquingMap = new COFFUniqueMapTy();
274 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
276 // Do the lookup, if we have a hit, return it.
277 StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
278 if (Entry.getValue()) return Entry.getValue();
280 MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
284 Entry.setValue(Result);
288 //===----------------------------------------------------------------------===//
290 //===----------------------------------------------------------------------===//
292 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
293 /// directory tables. If the file number has already been allocated it is an
294 /// error and zero is returned and the client reports the error, else the
295 /// allocated file number is returned. The file numbers may be in any order.
296 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
297 unsigned FileNumber) {
298 // TODO: a FileNumber of zero says to use the next available file number.
299 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
300 // to not be less than one. This needs to be change to be not less than zero.
302 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
303 if (FileNumber >= MCDwarfFiles.size()) {
304 MCDwarfFiles.resize(FileNumber + 1);
306 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
308 // It is an error to use see the same number more than once.
312 // Get the new MCDwarfFile slot for this FileNumber.
313 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
315 if (Directory.empty()) {
316 // Separate the directory part from the basename of the FileName.
317 StringRef tFileName = sys::path::filename(FileName);
318 if (!tFileName.empty()) {
319 Directory = sys::path::parent_path(FileName);
320 if (!Directory.empty())
321 FileName = tFileName;
325 // Find or make a entry in the MCDwarfDirs vector for this Directory.
326 // Capture directory name.
328 if (Directory.empty()) {
329 // For FileNames with no directories a DirIndex of 0 is used.
333 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
334 if (Directory == MCDwarfDirs[DirIndex])
337 if (DirIndex >= MCDwarfDirs.size()) {
338 char *Buf = static_cast<char *>(Allocate(Directory.size()));
339 memcpy(Buf, Directory.data(), Directory.size());
340 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
342 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
343 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
344 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
345 // are stored at MCDwarfFiles[FileNumber].Name .
349 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
351 char *Buf = static_cast<char *>(Allocate(FileName.size()));
352 memcpy(Buf, FileName.data(), FileName.size());
353 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
355 // return the allocated FileNumber.
359 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
360 /// currently is assigned and false otherwise.
361 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
362 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
365 return MCDwarfFiles[FileNumber] != 0;
368 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
369 // If we have a source manager and a location, use it. Otherwise just
370 // use the generic report_fatal_error().
371 if (!SrcMgr || Loc == SMLoc())
372 report_fatal_error(Msg);
374 // Use the source manager to print the message.
375 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
377 // If we reached here, we are failing ungracefully. Run the interrupt handlers
378 // to make sure any special cleanups get done, in particular that we remove
379 // files registered with RemoveFileOnSignal.
380 sys::RunInterruptHandlers();