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"
32 typedef std::pair<std::string, std::string> SectionGroupPair;
34 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
35 typedef std::map<SectionGroupPair, const MCSectionELF *> ELFUniqueMapTy;
36 typedef std::map<SectionGroupPair, const MCSectionCOFF *> COFFUniqueMapTy;
38 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
39 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
41 SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
42 Allocator(), Symbols(Allocator), UsedNames(Allocator),
44 CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
45 DwarfLocSeen(false), GenDwarfForAssembly(false), GenDwarfFileNumber(0),
46 AllowTemporaryLabels(true), DwarfCompileUnitID(0), AutoReset(DoAutoReset) {
48 error_code EC = llvm::sys::fs::current_path(CompilationDir);
50 CompilationDir.clear();
56 SecureLogFile = getenv("AS_SECURE_LOG_FILE");
58 SecureLogUsed = false;
60 if (SrcMgr && SrcMgr->getNumBuffers() > 0)
61 MainFileName = SrcMgr->getMemoryBuffer(0)->getBufferIdentifier();
66 MCContext::~MCContext() {
71 // NOTE: The symbols are all allocated out of a bump pointer allocator,
72 // we don't need to free them here.
74 // If the stream for the .secure_log_unique directive was created free it.
75 delete (raw_ostream*)SecureLog;
78 //===----------------------------------------------------------------------===//
79 // Module Lifetime Management
80 //===----------------------------------------------------------------------===//
82 void MCContext::reset() {
87 MCDwarfFilesCUMap.clear();
88 MCDwarfDirsCUMap.clear();
89 MCGenDwarfLabelEntries.clear();
90 DwarfDebugFlags = StringRef();
91 MCLineSections.clear();
92 DwarfCompileUnitID = 0;
93 MCLineTableSymbols.clear();
94 CurrentDwarfLoc = MCDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0);
96 // If we have the MachO uniquing map, free it.
97 delete (MachOUniqueMapTy*)MachOUniquingMap;
98 delete (ELFUniqueMapTy*)ELFUniquingMap;
99 delete (COFFUniqueMapTy*)COFFUniquingMap;
100 MachOUniquingMap = 0;
105 AllowTemporaryLabels = true;
106 DwarfLocSeen = false;
107 GenDwarfForAssembly = false;
108 GenDwarfFileNumber = 0;
111 //===----------------------------------------------------------------------===//
112 // Symbol Manipulation
113 //===----------------------------------------------------------------------===//
115 MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
116 assert(!Name.empty() && "Normal symbols cannot be unnamed!");
118 // Do the lookup and get the entire StringMapEntry. We want access to the
119 // key if we are creating the entry.
120 StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
121 MCSymbol *Sym = Entry.getValue();
126 Sym = CreateSymbol(Name);
131 MCSymbol *MCContext::CreateSymbol(StringRef Name) {
132 // Determine whether this is an assembler temporary or normal label, if used.
133 bool isTemporary = false;
134 if (AllowTemporaryLabels)
135 isTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
137 StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
138 if (NameEntry->getValue()) {
139 assert(isTemporary && "Cannot rename non-temporary symbols");
140 SmallString<128> NewName = Name;
142 NewName.resize(Name.size());
143 raw_svector_ostream(NewName) << NextUniqueID++;
144 NameEntry = &UsedNames.GetOrCreateValue(NewName);
145 } while (NameEntry->getValue());
147 NameEntry->setValue(true);
149 // Ok, the entry doesn't already exist. Have the MCSymbol object itself refer
150 // to the copy of the string that is embedded in the UsedNames entry.
151 MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
156 MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
157 SmallString<128> NameSV;
158 return GetOrCreateSymbol(Name.toStringRef(NameSV));
161 MCSymbol *MCContext::CreateTempSymbol() {
162 SmallString<128> NameSV;
163 raw_svector_ostream(NameSV)
164 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
165 return CreateSymbol(NameSV);
168 unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
169 MCLabel *&Label = Instances[LocalLabelVal];
171 Label = new (*this) MCLabel(0);
172 return Label->incInstance();
175 unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
176 MCLabel *&Label = Instances[LocalLabelVal];
178 Label = new (*this) MCLabel(0);
179 return Label->getInstance();
182 MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
183 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
184 Twine(LocalLabelVal) +
186 Twine(NextInstance(LocalLabelVal)));
188 MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
190 return GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
191 Twine(LocalLabelVal) +
193 Twine(GetInstance(LocalLabelVal) + bORf));
196 MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
197 return Symbols.lookup(Name);
200 MCSymbol *MCContext::LookupSymbol(const Twine &Name) const {
201 SmallString<128> NameSV;
202 Name.toVector(NameSV);
203 return LookupSymbol(NameSV.str());
206 //===----------------------------------------------------------------------===//
207 // Section Management
208 //===----------------------------------------------------------------------===//
210 const MCSectionMachO *MCContext::
211 getMachOSection(StringRef Segment, StringRef Section,
212 unsigned TypeAndAttributes,
213 unsigned Reserved2, SectionKind Kind) {
215 // We unique sections by their segment/section pair. The returned section
216 // may not have the same flags as the requested section, if so this should be
217 // diagnosed by the client as an error.
219 // Create the map if it doesn't already exist.
220 if (MachOUniquingMap == 0)
221 MachOUniquingMap = new MachOUniqueMapTy();
222 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
224 // Form the name to look up.
225 SmallString<64> Name;
230 // Do the lookup, if we have a hit, return it.
231 const MCSectionMachO *&Entry = Map[Name.str()];
232 if (Entry) return Entry;
234 // Otherwise, return a new section.
235 return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
239 const MCSectionELF *MCContext::
240 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
242 return getELFSection(Section, Type, Flags, Kind, 0, "");
245 const MCSectionELF *MCContext::
246 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
247 SectionKind Kind, unsigned EntrySize, StringRef Group) {
248 if (ELFUniquingMap == 0)
249 ELFUniquingMap = new ELFUniqueMapTy();
250 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
252 // Do the lookup, if we have a hit, return it.
253 std::pair<ELFUniqueMapTy::iterator, bool> Entry = Map.insert(
254 std::make_pair(SectionGroupPair(Section, Group), (MCSectionELF *)0));
255 if (!Entry.second) return Entry.first->second;
257 // Possibly refine the entry size first.
259 EntrySize = MCSectionELF::DetermineEntrySize(Kind);
262 MCSymbol *GroupSym = NULL;
264 GroupSym = GetOrCreateSymbol(Group);
266 MCSectionELF *Result = new (*this) MCSectionELF(
267 Entry.first->first.first, Type, Flags, Kind, EntrySize, GroupSym);
268 Entry.first->second = Result;
272 const MCSectionELF *MCContext::CreateELFGroupSection() {
273 MCSectionELF *Result =
274 new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
275 SectionKind::getReadOnly(), 4, NULL);
279 const MCSectionCOFF *
280 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
281 SectionKind Kind, StringRef COMDATSymName,
282 int Selection, const MCSectionCOFF *Assoc) {
283 if (COFFUniquingMap == 0)
284 COFFUniquingMap = new COFFUniqueMapTy();
285 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
287 // Do the lookup, if we have a hit, return it.
289 SectionGroupPair P(Section, COMDATSymName);
290 std::pair<COFFUniqueMapTy::iterator, bool> Entry =
291 Map.insert(std::make_pair(P, (MCSectionCOFF *)0));
292 COFFUniqueMapTy::iterator Iter = Entry.first;
296 const MCSymbol *COMDATSymbol = NULL;
297 if (!COMDATSymName.empty())
298 COMDATSymbol = GetOrCreateSymbol(COMDATSymName);
300 MCSectionCOFF *Result =
301 new (*this) MCSectionCOFF(Iter->first.first, Characteristics,
302 COMDATSymbol, Selection, Assoc, Kind);
304 Iter->second = Result;
308 const MCSectionCOFF *
309 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
311 return getCOFFSection(Section, Characteristics, Kind, "", 0);
314 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
315 if (COFFUniquingMap == 0)
316 COFFUniquingMap = new COFFUniqueMapTy();
317 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
319 SectionGroupPair P(Section, "");
320 COFFUniqueMapTy::iterator Iter = Map.find(P);
321 if (Iter == Map.end())
326 //===----------------------------------------------------------------------===//
328 //===----------------------------------------------------------------------===//
330 /// GetDwarfFile - takes a file name an number to place in the dwarf file and
331 /// directory tables. If the file number has already been allocated it is an
332 /// error and zero is returned and the client reports the error, else the
333 /// allocated file number is returned. The file numbers may be in any order.
334 unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
335 unsigned FileNumber, unsigned CUID) {
336 // TODO: a FileNumber of zero says to use the next available file number.
337 // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
338 // to not be less than one. This needs to be change to be not less than zero.
340 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
341 SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
342 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
343 if (FileNumber >= MCDwarfFiles.size()) {
344 MCDwarfFiles.resize(FileNumber + 1);
346 MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
348 // It is an error to use see the same number more than once.
352 // Get the new MCDwarfFile slot for this FileNumber.
353 MCDwarfFile *&File = MCDwarfFiles[FileNumber];
355 if (Directory.empty()) {
356 // Separate the directory part from the basename of the FileName.
357 StringRef tFileName = sys::path::filename(FileName);
358 if (!tFileName.empty()) {
359 Directory = sys::path::parent_path(FileName);
360 if (!Directory.empty())
361 FileName = tFileName;
365 // Find or make an entry in the MCDwarfDirs vector for this Directory.
366 // Capture directory name.
368 if (Directory.empty()) {
369 // For FileNames with no directories a DirIndex of 0 is used.
373 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
374 if (Directory == MCDwarfDirs[DirIndex])
377 if (DirIndex >= MCDwarfDirs.size()) {
378 char *Buf = static_cast<char *>(Allocate(Directory.size()));
379 memcpy(Buf, Directory.data(), Directory.size());
380 MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
382 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
383 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
384 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
385 // are stored at MCDwarfFiles[FileNumber].Name .
389 // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
391 char *Buf = static_cast<char *>(Allocate(FileName.size()));
392 memcpy(Buf, FileName.data(), FileName.size());
393 File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
395 // return the allocated FileNumber.
399 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
400 /// currently is assigned and false otherwise.
401 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
402 SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
403 if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
406 return MCDwarfFiles[FileNumber] != 0;
409 void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
410 // If we have a source manager and a location, use it. Otherwise just
411 // use the generic report_fatal_error().
412 if (!SrcMgr || Loc == SMLoc())
413 report_fatal_error(Msg);
415 // Use the source manager to print the message.
416 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
418 // If we reached here, we are failing ungracefully. Run the interrupt handlers
419 // to make sure any special cleanups get done, in particular that we remove
420 // files registered with RemoveFileOnSignal.
421 sys::RunInterruptHandlers();