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