Avoid unnecessary section switching. NFC.
[oota-llvm.git] / lib / MC / MCContext.cpp
1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/ELF.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include <map>
30
31 using namespace llvm;
32
33 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
34                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
35                      bool DoAutoReset)
36     : SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi), Allocator(),
37       Symbols(Allocator), UsedNames(Allocator),
38       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0), DwarfLocSeen(false),
39       GenDwarfForAssembly(false), GenDwarfFileNumber(0), DwarfVersion(4),
40       AllowTemporaryLabels(true), DwarfCompileUnitID(0),
41       AutoReset(DoAutoReset) {
42
43   std::error_code EC = llvm::sys::fs::current_path(CompilationDir);
44   if (EC)
45     CompilationDir.clear();
46
47   SecureLogFile = getenv("AS_SECURE_LOG_FILE");
48   SecureLog = nullptr;
49   SecureLogUsed = false;
50
51   if (SrcMgr && SrcMgr->getNumBuffers())
52     MainFileName =
53         SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
54 }
55
56 MCContext::~MCContext() {
57
58   if (AutoReset)
59     reset();
60
61   // NOTE: The symbols are all allocated out of a bump pointer allocator,
62   // we don't need to free them here.
63
64   // If the stream for the .secure_log_unique directive was created free it.
65   delete (raw_ostream *)SecureLog;
66 }
67
68 //===----------------------------------------------------------------------===//
69 // Module Lifetime Management
70 //===----------------------------------------------------------------------===//
71
72 void MCContext::reset() {
73   UsedNames.clear();
74   Symbols.clear();
75   Allocator.Reset();
76   Instances.clear();
77   CompilationDir.clear();
78   MainFileName.clear();
79   MCDwarfLineTablesCUMap.clear();
80   SectionsForRanges.clear();
81   MCGenDwarfLabelEntries.clear();
82   DwarfDebugFlags = StringRef();
83   DwarfCompileUnitID = 0;
84   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
85
86   MachOUniquingMap.clear();
87   ELFUniquingMap.clear();
88   COFFUniquingMap.clear();
89
90   NextID.clear();
91   AllowTemporaryLabels = true;
92   DwarfLocSeen = false;
93   GenDwarfForAssembly = false;
94   GenDwarfFileNumber = 0;
95 }
96
97 //===----------------------------------------------------------------------===//
98 // Symbol Manipulation
99 //===----------------------------------------------------------------------===//
100
101 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
102   SmallString<128> NameSV;
103   StringRef NameRef = Name.toStringRef(NameSV);
104
105   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
106
107   MCSymbol *&Sym = Symbols[NameRef];
108   if (!Sym)
109     Sym = CreateSymbol(NameRef, false);
110
111   return Sym;
112 }
113
114 MCSymbol *MCContext::getOrCreateSectionSymbol(const MCSectionELF &Section) {
115   MCSymbol *&Sym = SectionSymbols[&Section];
116   if (Sym)
117     return Sym;
118
119   StringRef Name = Section.getSectionName();
120
121   MCSymbol *&OldSym = Symbols[Name];
122   if (OldSym && OldSym->isUndefined()) {
123     Sym = OldSym;
124     return OldSym;
125   }
126
127   auto NameIter = UsedNames.insert(std::make_pair(Name, true)).first;
128   Sym = new (*this) MCSymbol(NameIter->getKey(), /*isTemporary*/ false);
129
130   if (!OldSym)
131     OldSym = Sym;
132
133   return Sym;
134 }
135
136 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
137                                                  unsigned Idx) {
138   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
139                            "$frame_escape_" + Twine(Idx));
140 }
141
142 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
143   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
144                            "$parent_frame_offset");
145 }
146
147 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
148   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
149                            FuncName);
150 }
151
152 MCSymbol *MCContext::CreateSymbol(StringRef Name, bool AlwaysAddSuffix) {
153   // Determine whether this is an assembler temporary or normal label, if used.
154   bool IsTemporary = false;
155   if (AllowTemporaryLabels)
156     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
157
158   if (IsTemporary && AlwaysAddSuffix && !UseNamesOnTempLabels)
159     return new (*this) MCSymbol("", true);
160
161   SmallString<128> NewName = Name;
162   bool AddSuffix = AlwaysAddSuffix;
163   unsigned &NextUniqueID = NextID[Name];
164   for (;;) {
165     if (AddSuffix) {
166       NewName.resize(Name.size());
167       raw_svector_ostream(NewName) << NextUniqueID++;
168     }
169     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
170     if (NameEntry.second) {
171       // Ok, we found a name. Have the MCSymbol object itself refer to the copy
172       // of the string that is embedded in the UsedNames entry.
173       MCSymbol *Result =
174           new (*this) MCSymbol(NameEntry.first->getKey(), IsTemporary);
175       return Result;
176     }
177     assert(IsTemporary && "Cannot rename non-temporary symbols");
178     AddSuffix = true;
179   }
180   llvm_unreachable("Infinite loop");
181 }
182
183 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
184   SmallString<128> NameSV;
185   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
186   return CreateSymbol(NameSV, AlwaysAddSuffix);
187 }
188
189 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
190   SmallString<128> NameSV;
191   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
192   return CreateSymbol(NameSV, true);
193 }
194
195 MCSymbol *MCContext::createTempSymbol() {
196   return createTempSymbol("tmp", true);
197 }
198
199 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
200   MCLabel *&Label = Instances[LocalLabelVal];
201   if (!Label)
202     Label = new (*this) MCLabel(0);
203   return Label->incInstance();
204 }
205
206 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
207   MCLabel *&Label = Instances[LocalLabelVal];
208   if (!Label)
209     Label = new (*this) MCLabel(0);
210   return Label->getInstance();
211 }
212
213 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
214                                                        unsigned Instance) {
215   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
216   if (!Sym)
217     Sym = createTempSymbol();
218   return Sym;
219 }
220
221 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
222   unsigned Instance = NextInstance(LocalLabelVal);
223   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
224 }
225
226 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
227                                                bool Before) {
228   unsigned Instance = GetInstance(LocalLabelVal);
229   if (!Before)
230     ++Instance;
231   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
232 }
233
234 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
235   SmallString<128> NameSV;
236   StringRef NameRef = Name.toStringRef(NameSV);
237   return Symbols.lookup(NameRef);
238 }
239
240 //===----------------------------------------------------------------------===//
241 // Section Management
242 //===----------------------------------------------------------------------===//
243
244 const MCSectionMachO *
245 MCContext::getMachOSection(StringRef Segment, StringRef Section,
246                            unsigned TypeAndAttributes, unsigned Reserved2,
247                            SectionKind Kind, const char *BeginSymName) {
248
249   // We unique sections by their segment/section pair.  The returned section
250   // may not have the same flags as the requested section, if so this should be
251   // diagnosed by the client as an error.
252
253   // Form the name to look up.
254   SmallString<64> Name;
255   Name += Segment;
256   Name.push_back(',');
257   Name += Section;
258
259   // Do the lookup, if we have a hit, return it.
260   const MCSectionMachO *&Entry = MachOUniquingMap[Name];
261   if (Entry)
262     return Entry;
263
264   MCSymbol *Begin = nullptr;
265   if (BeginSymName)
266     Begin = createTempSymbol(BeginSymName, false);
267
268   // Otherwise, return a new section.
269   return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
270                                             Reserved2, Kind, Begin);
271 }
272
273 void MCContext::renameELFSection(const MCSectionELF *Section, StringRef Name) {
274   StringRef GroupName;
275   if (const MCSymbol *Group = Section->getGroup())
276     GroupName = Group->getName();
277
278   unsigned UniqueID = Section->getUniqueID();
279   ELFUniquingMap.erase(
280       ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
281   auto I = ELFUniquingMap.insert(std::make_pair(
282                                      ELFSectionKey{Name, GroupName, UniqueID},
283                                      Section))
284                .first;
285   StringRef CachedName = I->first.SectionName;
286   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
287 }
288
289 const MCSectionELF *
290 MCContext::createELFRelSection(StringRef Name, unsigned Type, unsigned Flags,
291                                unsigned EntrySize, const MCSymbol *Group,
292                                const MCSectionELF *Associated) {
293   StringMap<bool>::iterator I;
294   bool Inserted;
295   std::tie(I, Inserted) = ELFRelSecNames.insert(std::make_pair(Name, true));
296
297   return new (*this)
298       MCSectionELF(I->getKey(), Type, Flags, SectionKind::getReadOnly(),
299                    EntrySize, Group, true, nullptr, Associated);
300 }
301
302 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
303                                              unsigned Flags, unsigned EntrySize,
304                                              StringRef Group, unsigned UniqueID,
305                                              const char *BeginSymName) {
306   MCSymbol *GroupSym = nullptr;
307   if (!Group.empty())
308     GroupSym = getOrCreateSymbol(Group);
309
310   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
311                        BeginSymName, nullptr);
312 }
313
314 const MCSectionELF *MCContext::getELFSection(StringRef Section, unsigned Type,
315                                              unsigned Flags, unsigned EntrySize,
316                                              const MCSymbol *GroupSym,
317                                              unsigned UniqueID,
318                                              const char *BeginSymName,
319                                              const MCSectionELF *Associated) {
320   StringRef Group = "";
321   if (GroupSym)
322     Group = GroupSym->getName();
323   // Do the lookup, if we have a hit, return it.
324   auto IterBool = ELFUniquingMap.insert(
325       std::make_pair(ELFSectionKey{Section, Group, UniqueID}, nullptr));
326   auto &Entry = *IterBool.first;
327   if (!IterBool.second)
328     return Entry.second;
329
330   StringRef CachedName = Entry.first.SectionName;
331
332   SectionKind Kind;
333   if (Flags & ELF::SHF_EXECINSTR)
334     Kind = SectionKind::getText();
335   else
336     Kind = SectionKind::getReadOnly();
337
338   MCSymbol *Begin = nullptr;
339   if (BeginSymName)
340     Begin = createTempSymbol(BeginSymName, false);
341
342   MCSectionELF *Result =
343       new (*this) MCSectionELF(CachedName, Type, Flags, Kind, EntrySize,
344                                GroupSym, UniqueID, Begin, Associated);
345   Entry.second = Result;
346   return Result;
347 }
348
349 const MCSectionELF *MCContext::createELFGroupSection(const MCSymbol *Group) {
350   MCSectionELF *Result = new (*this)
351       MCSectionELF(".group", ELF::SHT_GROUP, 0, SectionKind::getReadOnly(), 4,
352                    Group, ~0, nullptr, nullptr);
353   return Result;
354 }
355
356 const MCSectionCOFF *
357 MCContext::getCOFFSection(StringRef Section, unsigned Characteristics,
358                           SectionKind Kind, StringRef COMDATSymName,
359                           int Selection, const char *BeginSymName) {
360   MCSymbol *COMDATSymbol = nullptr;
361   if (!COMDATSymName.empty()) {
362     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
363     COMDATSymName = COMDATSymbol->getName();
364   }
365
366   // Do the lookup, if we have a hit, return it.
367   COFFSectionKey T{Section, COMDATSymName, Selection};
368   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
369   auto Iter = IterBool.first;
370   if (!IterBool.second)
371     return Iter->second;
372
373   MCSymbol *Begin = nullptr;
374   if (BeginSymName)
375     Begin = createTempSymbol(BeginSymName, false);
376
377   StringRef CachedName = Iter->first.SectionName;
378   MCSectionCOFF *Result = new (*this) MCSectionCOFF(
379       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
380
381   Iter->second = Result;
382   return Result;
383 }
384
385 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
386                                                unsigned Characteristics,
387                                                SectionKind Kind,
388                                                const char *BeginSymName) {
389   return getCOFFSection(Section, Characteristics, Kind, "", 0, BeginSymName);
390 }
391
392 const MCSectionCOFF *MCContext::getCOFFSection(StringRef Section) {
393   COFFSectionKey T{Section, "", 0};
394   auto Iter = COFFUniquingMap.find(T);
395   if (Iter == COFFUniquingMap.end())
396     return nullptr;
397   return Iter->second;
398 }
399
400 const MCSectionCOFF *
401 MCContext::getAssociativeCOFFSection(const MCSectionCOFF *Sec,
402                                      const MCSymbol *KeySym) {
403   // Return the normal section if we don't have to be associative.
404   if (!KeySym)
405     return Sec;
406
407   // Make an associative section with the same name and kind as the normal
408   // section.
409   unsigned Characteristics =
410       Sec->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
411   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
412                         KeySym->getName(),
413                         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
414 }
415
416 //===----------------------------------------------------------------------===//
417 // Dwarf Management
418 //===----------------------------------------------------------------------===//
419
420 /// getDwarfFile - takes a file name an number to place in the dwarf file and
421 /// directory tables.  If the file number has already been allocated it is an
422 /// error and zero is returned and the client reports the error, else the
423 /// allocated file number is returned.  The file numbers may be in any order.
424 unsigned MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
425                                  unsigned FileNumber, unsigned CUID) {
426   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
427   return Table.getFile(Directory, FileName, FileNumber);
428 }
429
430 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
431 /// currently is assigned and false otherwise.
432 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
433   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = getMCDwarfFiles(CUID);
434   if (FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
435     return false;
436
437   return !MCDwarfFiles[FileNumber].Name.empty();
438 }
439
440 /// Remove empty sections from SectionStartEndSyms, to avoid generating
441 /// useless debug info for them.
442 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
443   std::vector<const MCSection *> Keep;
444   for (const MCSection *Sec : SectionsForRanges) {
445     if (MCOS.mayHaveInstructions(*Sec))
446       Keep.push_back(Sec);
447   }
448   SectionsForRanges.clear();
449   SectionsForRanges.insert(Keep.begin(), Keep.end());
450 }
451
452 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) const {
453   // If we have a source manager and a location, use it. Otherwise just
454   // use the generic report_fatal_error().
455   if (!SrcMgr || Loc == SMLoc())
456     report_fatal_error(Msg, false);
457
458   // Use the source manager to print the message.
459   SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
460
461   // If we reached here, we are failing ungracefully. Run the interrupt handlers
462   // to make sure any special cleanups get done, in particular that we remove
463   // files registered with RemoveFileOnSignal.
464   sys::RunInterruptHandlers();
465   exit(1);
466 }