b8bfa7d2a0f1a02973210bf284d1d8ba5187f3bd
[oota-llvm.git] / lib / CodeGen / ELFWriter.h
1 //===-- ELFWriter.h - Target-independent ELF writer support -----*- C++ -*-===//
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 // This file defines the ELFWriter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef ELFWRITER_H
15 #define ELFWRITER_H
16
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include <map>
20
21 namespace llvm {
22   class BinaryObject;
23   class Constant;
24   class ConstantStruct;
25   class ELFCodeEmitter;
26   class ELFRelocation;
27   class ELFSection;
28   struct ELFSym;
29   class GlobalVariable;
30   class Mangler;
31   class MachineCodeEmitter;
32   class MachineConstantPoolEntry;
33   class ObjectCodeEmitter;
34   class TargetAsmInfo;
35   class TargetELFWriterInfo;
36   class raw_ostream;
37   class SectionKind;
38
39   typedef std::vector<ELFSym*>::iterator ELFSymIter;
40   typedef std::vector<ELFSection*>::iterator ELFSectionIter;
41   typedef SetVector<const GlobalValue*>::const_iterator PendingGblsIter;
42   typedef SetVector<const char *>::const_iterator PendingExtsIter;
43
44   /// ELFWriter - This class implements the common target-independent code for
45   /// writing ELF files.  Targets should derive a class from this to
46   /// parameterize the output format.
47   ///
48   class ELFWriter : public MachineFunctionPass {
49     friend class ELFCodeEmitter;
50   public:
51     static char ID;
52
53     /// Return the ELFCodeEmitter as an instance of ObjectCodeEmitter
54     ObjectCodeEmitter *getObjectCodeEmitter() {
55       return reinterpret_cast<ObjectCodeEmitter*>(ElfCE);
56     }
57
58     ELFWriter(raw_ostream &O, TargetMachine &TM);
59     ~ELFWriter();
60
61   protected:
62     /// Output stream to send the resultant object file to.
63     raw_ostream &O;
64
65     /// Target machine description.
66     TargetMachine &TM;
67
68     /// Target Elf Writer description.
69     const TargetELFWriterInfo *TEW;
70
71     /// Mang - The object used to perform name mangling for this module.
72     Mangler *Mang;
73
74     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
75     /// code for functions to the .o file.
76     ELFCodeEmitter *ElfCE;
77
78     /// TAI - Target Asm Info, provide information about section names for
79     /// globals and other target specific stuff.
80     const TargetAsmInfo *TAI;
81
82     //===------------------------------------------------------------------===//
83     // Properties inferred automatically from the target machine.
84     //===------------------------------------------------------------------===//
85
86     /// is64Bit/isLittleEndian - This information is inferred from the target
87     /// machine directly, indicating whether to emit a 32- or 64-bit ELF file.
88     bool is64Bit, isLittleEndian;
89
90     /// doInitialization - Emit the file header and all of the global variables
91     /// for the module to the ELF file.
92     bool doInitialization(Module &M);
93     bool runOnMachineFunction(MachineFunction &MF);
94
95     /// doFinalization - Now that the module has been completely processed, emit
96     /// the ELF file to 'O'.
97     bool doFinalization(Module &M);
98
99   private:
100     /// Blob containing the Elf header
101     BinaryObject ElfHdr;
102
103     /// SectionList - This is the list of sections that we have emitted to the
104     /// file. Once the file has been completely built, the section header table
105     /// is constructed from this info.
106     std::vector<ELFSection*> SectionList;
107     unsigned NumSections;   // Always = SectionList.size()
108
109     /// SectionLookup - This is a mapping from section name to section number in
110     /// the SectionList. Used to quickly gather the Section Index from TAI names
111     std::map<std::string, ELFSection*> SectionLookup;
112
113     /// PendingGlobals - Globals not processed as symbols yet.
114     SetVector<const GlobalValue*> PendingGlobals;
115
116     /// GblSymLookup - This is a mapping from global value to a symbol index
117     /// in the symbol table or private symbols list. This is useful since reloc
118     /// symbol references must be quickly mapped to their indices on the lists.
119     std::map<const GlobalValue*, uint32_t> GblSymLookup;
120
121     /// PendingExternals - Externals not processed as symbols yet.
122     SetVector<const char *> PendingExternals;
123
124     /// ExtSymLookup - This is a mapping from externals to a symbol index
125     /// in the symbol table list. This is useful since reloc symbol references
126     /// must be quickly mapped to their symbol table indices.
127     std::map<const char *, uint32_t> ExtSymLookup;
128
129     /// SymbolList - This is the list of symbols emitted to the symbol table.
130     /// When the SymbolList is finally built, local symbols must be placed in
131     /// the beginning while non-locals at the end.
132     std::vector<ELFSym*> SymbolList;
133
134     /// PrivateSyms - Record private symbols, every symbol here must never be
135     /// present in the SymbolList.
136     std::vector<ELFSym*> PrivateSyms;
137
138     // Remove tab from section name prefix. This is necessary becase TAI
139     // sometimes return a section name prefixed with elf unused chars. This is
140     // a little bit dirty. FIXME: find a better approach, maybe add more
141     // methods to TAI to get the clean name?
142     void fixNameForSection(std::string &Name) {
143       size_t Pos = Name.find("\t");
144       if (Pos != std::string::npos)
145         Name.erase(Pos, 1);
146
147       Pos = Name.find(".section ");
148       if (Pos != std::string::npos)
149         Name.erase(Pos, 9);
150
151       Pos = Name.find("\n");
152       if (Pos != std::string::npos)
153         Name.erase(Pos, 1);
154     }
155
156     /// getSection - Return the section with the specified name, creating a new
157     /// section if one does not already exist.
158     ELFSection &getSection(const std::string &Name, unsigned Type,
159                            unsigned Flags = 0, unsigned Align = 0) {
160       std::string SName(Name);
161       fixNameForSection(SName);
162
163       ELFSection *&SN = SectionLookup[SName];
164       if (SN) return *SN;
165
166       SectionList.push_back(new ELFSection(SName, isLittleEndian, is64Bit));
167       SN = SectionList.back();
168       SN->SectionIdx = NumSections++;
169       SN->Type = Type;
170       SN->Flags = Flags;
171       SN->Link = ELFSection::SHN_UNDEF;
172       SN->Align = Align;
173       return *SN;
174     }
175
176     /// TODO: support mangled names here to emit the right .text section
177     /// for c++ object files.
178     ELFSection &getTextSection() {
179       return getSection(".text", ELFSection::SHT_PROGBITS,
180                         ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC);
181     }
182
183     ELFSection &getNonExecStackSection() {
184       return getSection(".note.GNU-stack", ELFSection::SHT_PROGBITS, 0, 1);
185     }
186
187     ELFSection &getSymbolTableSection() {
188       return getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
189     }
190
191     ELFSection &getStringTableSection() {
192       return getSection(".strtab", ELFSection::SHT_STRTAB, 0, 1);
193     }
194
195     ELFSection &getSectionHeaderStringTableSection() {
196       return getSection(".shstrtab", ELFSection::SHT_STRTAB, 0, 1);
197     }
198
199     ELFSection &getDataSection() {
200       return getSection(".data", ELFSection::SHT_PROGBITS,
201                         ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 4);
202     }
203
204     ELFSection &getBSSSection() {
205       return getSection(".bss", ELFSection::SHT_NOBITS,
206                         ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 4);
207     }
208
209     ELFSection &getNullSection() {
210       return getSection("", ELFSection::SHT_NULL, 0);
211     }
212
213     ELFSection &getJumpTableSection();
214     ELFSection &getConstantPoolSection(MachineConstantPoolEntry &CPE);
215     ELFSection &getRelocSection(ELFSection &S);
216
217     // Helpers for obtaining ELF specific info.
218     unsigned getGlobalELFBinding(const GlobalValue *GV);
219     unsigned getGlobalELFType(const GlobalValue *GV);
220     unsigned getGlobalELFVisibility(const GlobalValue *GV);
221     unsigned getElfSectionFlags(SectionKind Kind);
222
223     // addGlobalSymbol - Add a global to be processed and to the
224     // global symbol lookup, use a zero index for non private symbols
225     // because the table index will be determined later.
226     void addGlobalSymbol(const GlobalValue *GV);
227
228     // addExternalSymbol - Add the external to be processed and to the
229     // external symbol lookup, use a zero index because the symbol
230     // table index will be determined later
231     void addExternalSymbol(const char *External);
232
233     // As we complete the ELF file, we need to update fields in the ELF header
234     // (e.g. the location of the section table).  These members keep track of
235     // the offset in ELFHeader of these various pieces to update and other
236     // locations in the file.
237     unsigned ELFHdr_e_shoff_Offset;     // e_shoff    in ELF header.
238     unsigned ELFHdr_e_shstrndx_Offset;  // e_shstrndx in ELF header.
239     unsigned ELFHdr_e_shnum_Offset;     // e_shnum    in ELF header.
240
241   private:
242     void EmitGlobal(const GlobalValue *GV);
243     void EmitGlobalConstant(const Constant *C, ELFSection &GblS);
244     void EmitGlobalConstantStruct(const ConstantStruct *CVS,
245                                   ELFSection &GblS);
246     ELFSection &getGlobalSymELFSection(const GlobalVariable *GV, ELFSym &Sym);
247     void EmitRelocations();
248     void EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel, bool HasRelA);
249     void EmitSectionHeader(BinaryObject &SHdrTab, const ELFSection &SHdr);
250     void EmitSectionTableStringTable();
251     void EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym);
252     void EmitSymbolTable();
253     void EmitStringTable(const std::string &ModuleName);
254     void OutputSectionsAndSectionTable();
255     void RelocateField(BinaryObject &BO, uint32_t Offset, int64_t Value,
256                        unsigned Size);
257     unsigned SortSymbols();
258   };
259 }
260
261 #endif