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