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/MC/MCAsmInfo.h"
12#include "llvm/MC/MCObjectFileInfo.h"
13#include "llvm/MC/MCRegisterInfo.h"
14#include "llvm/MC/MCSectionMachO.h"
15#include "llvm/MC/MCSectionELF.h"
16#include "llvm/MC/MCSectionCOFF.h"
17#include "llvm/MC/MCSymbol.h"
18#include "llvm/MC/MCLabel.h"
19#include "llvm/MC/MCDwarf.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Support/ELF.h"
23using namespace llvm;
24
25typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
26typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
27typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
28
29
30MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
31                     const MCObjectFileInfo *mofi) :
32  MAI(mai), MRI(mri), MOFI(mofi),
33  Allocator(), Symbols(Allocator), UsedNames(Allocator),
34  NextUniqueID(0),
35  CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
36  AllowTemporaryLabels(true) {
37  MachOUniquingMap = 0;
38  ELFUniquingMap = 0;
39  COFFUniquingMap = 0;
40
41  SecureLogFile = getenv("AS_SECURE_LOG_FILE");
42  SecureLog = 0;
43  SecureLogUsed = false;
44
45  DwarfLocSeen = false;
46}
47
48MCContext::~MCContext() {
49  // NOTE: The symbols are all allocated out of a bump pointer allocator,
50  // we don't need to free them here.
51
52  // If we have the MachO uniquing map, free it.
53  delete (MachOUniqueMapTy*)MachOUniquingMap;
54  delete (ELFUniqueMapTy*)ELFUniquingMap;
55  delete (COFFUniqueMapTy*)COFFUniquingMap;
56
57  // If the stream for the .secure_log_unique directive was created free it.
58  delete (raw_ostream*)SecureLog;
59}
60
61//===----------------------------------------------------------------------===//
62// Symbol Manipulation
63//===----------------------------------------------------------------------===//
64
65MCSymbol *MCContext::GetOrCreateSymbol(StringRef Name) {
66  assert(!Name.empty() && "Normal symbols cannot be unnamed!");
67
68  // Do the lookup and get the entire StringMapEntry.  We want access to the
69  // key if we are creating the entry.
70  StringMapEntry<MCSymbol*> &Entry = Symbols.GetOrCreateValue(Name);
71  MCSymbol *Sym = Entry.getValue();
72
73  if (Sym)
74    return Sym;
75
76  Sym = CreateSymbol(Name);
77  Entry.setValue(Sym);
78  return Sym;
79}
80
81MCSymbol *MCContext::CreateSymbol(StringRef Name) {
82  // Determine whether this is an assembler temporary or normal label, if used.
83  bool isTemporary = false;
84  if (AllowTemporaryLabels)
85    isTemporary = Name.startswith(MAI.getPrivateGlobalPrefix());
86
87  StringMapEntry<bool> *NameEntry = &UsedNames.GetOrCreateValue(Name);
88  if (NameEntry->getValue()) {
89    assert(isTemporary && "Cannot rename non temporary symbols");
90    SmallString<128> NewName = Name;
91    do {
92      NewName.resize(Name.size());
93      raw_svector_ostream(NewName) << NextUniqueID++;
94      NameEntry = &UsedNames.GetOrCreateValue(NewName);
95    } while (NameEntry->getValue());
96  }
97  NameEntry->setValue(true);
98
99  // Ok, the entry doesn't already exist.  Have the MCSymbol object itself refer
100  // to the copy of the string that is embedded in the UsedNames entry.
101  MCSymbol *Result = new (*this) MCSymbol(NameEntry->getKey(), isTemporary);
102
103  return Result;
104}
105
106MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
107  SmallString<128> NameSV;
108  Name.toVector(NameSV);
109  return GetOrCreateSymbol(NameSV.str());
110}
111
112MCSymbol *MCContext::CreateTempSymbol() {
113  SmallString<128> NameSV;
114  raw_svector_ostream(NameSV)
115    << MAI.getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
116  return CreateSymbol(NameSV);
117}
118
119unsigned MCContext::NextInstance(int64_t LocalLabelVal) {
120  MCLabel *&Label = Instances[LocalLabelVal];
121  if (!Label)
122    Label = new (*this) MCLabel(0);
123  return Label->incInstance();
124}
125
126unsigned MCContext::GetInstance(int64_t LocalLabelVal) {
127  MCLabel *&Label = Instances[LocalLabelVal];
128  if (!Label)
129    Label = new (*this) MCLabel(0);
130  return Label->getInstance();
131}
132
133MCSymbol *MCContext::CreateDirectionalLocalSymbol(int64_t LocalLabelVal) {
134  return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
135                           Twine(LocalLabelVal) +
136                           "\2" +
137                           Twine(NextInstance(LocalLabelVal)));
138}
139MCSymbol *MCContext::GetDirectionalLocalSymbol(int64_t LocalLabelVal,
140                                               int bORf) {
141  return GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix()) +
142                           Twine(LocalLabelVal) +
143                           "\2" +
144                           Twine(GetInstance(LocalLabelVal) + bORf));
145}
146
147MCSymbol *MCContext::LookupSymbol(StringRef Name) const {
148  return Symbols.lookup(Name);
149}
150
151//===----------------------------------------------------------------------===//
152// Section Management
153//===----------------------------------------------------------------------===//
154
155const MCSectionMachO *MCContext::
156getMachOSection(StringRef Segment, StringRef Section,
157                unsigned TypeAndAttributes,
158                unsigned Reserved2, SectionKind Kind) {
159
160  // We unique sections by their segment/section pair.  The returned section
161  // may not have the same flags as the requested section, if so this should be
162  // diagnosed by the client as an error.
163
164  // Create the map if it doesn't already exist.
165  if (MachOUniquingMap == 0)
166    MachOUniquingMap = new MachOUniqueMapTy();
167  MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)MachOUniquingMap;
168
169  // Form the name to look up.
170  SmallString<64> Name;
171  Name += Segment;
172  Name.push_back(',');
173  Name += Section;
174
175  // Do the lookup, if we have a hit, return it.
176  const MCSectionMachO *&Entry = Map[Name.str()];
177  if (Entry) return Entry;
178
179  // Otherwise, return a new section.
180  return Entry = new (*this) MCSectionMachO(Segment, Section, TypeAndAttributes,
181                                            Reserved2, Kind);
182}
183
184const MCSectionELF *MCContext::
185getELFSection(StringRef Section, unsigned Type, unsigned Flags,
186              SectionKind Kind) {
187  return getELFSection(Section, Type, Flags, Kind, 0, "");
188}
189
190const MCSectionELF *MCContext::
191getELFSection(StringRef Section, unsigned Type, unsigned Flags,
192              SectionKind Kind, unsigned EntrySize, StringRef Group) {
193  if (ELFUniquingMap == 0)
194    ELFUniquingMap = new ELFUniqueMapTy();
195  ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)ELFUniquingMap;
196
197  // Do the lookup, if we have a hit, return it.
198  StringMapEntry<const MCSectionELF*> &Entry = Map.GetOrCreateValue(Section);
199  if (Entry.getValue()) return Entry.getValue();
200
201  // Possibly refine the entry size first.
202  if (!EntrySize) {
203    EntrySize = MCSectionELF::DetermineEntrySize(Kind);
204  }
205
206  MCSymbol *GroupSym = NULL;
207  if (!Group.empty())
208    GroupSym = GetOrCreateSymbol(Group);
209
210  MCSectionELF *Result = new (*this) MCSectionELF(Entry.getKey(), Type, Flags,
211                                                  Kind, EntrySize, GroupSym);
212  Entry.setValue(Result);
213  return Result;
214}
215
216const MCSectionELF *MCContext::CreateELFGroupSection() {
217  MCSectionELF *Result =
218    new (*this) MCSectionELF(".group", ELF::SHT_GROUP, 0,
219                             SectionKind::getReadOnly(), 4, NULL);
220  return Result;
221}
222
223const MCSection *MCContext::getCOFFSection(StringRef Section,
224                                           unsigned Characteristics,
225                                           int Selection,
226                                           SectionKind Kind) {
227  if (COFFUniquingMap == 0)
228    COFFUniquingMap = new COFFUniqueMapTy();
229  COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)COFFUniquingMap;
230
231  // Do the lookup, if we have a hit, return it.
232  StringMapEntry<const MCSectionCOFF*> &Entry = Map.GetOrCreateValue(Section);
233  if (Entry.getValue()) return Entry.getValue();
234
235  MCSectionCOFF *Result = new (*this) MCSectionCOFF(Entry.getKey(),
236                                                    Characteristics,
237                                                    Selection, Kind);
238
239  Entry.setValue(Result);
240  return Result;
241}
242
243//===----------------------------------------------------------------------===//
244// Dwarf Management
245//===----------------------------------------------------------------------===//
246
247/// GetDwarfFile - takes a file name an number to place in the dwarf file and
248/// directory tables.  If the file number has already been allocated it is an
249/// error and zero is returned and the client reports the error, else the
250/// allocated file number is returned.  The file numbers may be in any order.
251unsigned MCContext::GetDwarfFile(StringRef FileName, unsigned FileNumber) {
252  // TODO: a FileNumber of zero says to use the next available file number.
253  // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
254  // to not be less than one.  This needs to be change to be not less than zero.
255
256  // Make space for this FileNumber in the MCDwarfFiles vector if needed.
257  if (FileNumber >= MCDwarfFiles.size()) {
258    MCDwarfFiles.resize(FileNumber + 1);
259  } else {
260    MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
261    if (ExistingFile)
262      // It is an error to use see the same number more than once.
263      return 0;
264  }
265
266  // Get the new MCDwarfFile slot for this FileNumber.
267  MCDwarfFile *&File = MCDwarfFiles[FileNumber];
268
269  // Separate the directory part from the basename of the FileName.
270  std::pair<StringRef, StringRef> Slash = FileName.rsplit('/');
271
272  // Find or make a entry in the MCDwarfDirs vector for this Directory.
273  StringRef Name;
274  unsigned DirIndex;
275  // Capture directory name.
276  if (Slash.second.empty()) {
277    Name = Slash.first;
278    DirIndex = 0; // For FileNames with no directories a DirIndex of 0 is used.
279  } else {
280    StringRef Directory = Slash.first;
281    Name = Slash.second;
282    DirIndex = 0;
283    for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
284      if (Directory == MCDwarfDirs[DirIndex])
285        break;
286    }
287    if (DirIndex >= MCDwarfDirs.size()) {
288      char *Buf = static_cast<char *>(Allocate(Directory.size()));
289      memcpy(Buf, Directory.data(), Directory.size());
290      MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
291    }
292    // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
293    // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
294    // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames are
295    // stored at MCDwarfFiles[FileNumber].Name .
296    DirIndex++;
297  }
298
299  // Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
300  // vector.
301  char *Buf = static_cast<char *>(Allocate(Name.size()));
302  memcpy(Buf, Name.data(), Name.size());
303  File = new (*this) MCDwarfFile(StringRef(Buf, Name.size()), DirIndex);
304
305  // return the allocated FileNumber.
306  return FileNumber;
307}
308
309/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
310/// currently is assigned and false otherwise.
311bool MCContext::isValidDwarfFileNumber(unsigned FileNumber) {
312  if(FileNumber == 0 || FileNumber >= MCDwarfFiles.size())
313    return false;
314
315  return MCDwarfFiles[FileNumber] != 0;
316}
317