Physregs may hold multiple stack slot values at the same time. Keep track
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the target-independent ELF writer.  This file writes out
11 // the ELF file in the following order:
12 //
13 //  #1. ELF Header
14 //  #2. '.text' section
15 //  #3. '.data' section
16 //  #4. '.bss' section  (conceptual position in file)
17 //  ...
18 //  #X. '.shstrtab' section
19 //  #Y. Section Table
20 //
21 // The entries in the section table are laid out as:
22 //  #0. Null entry [required]
23 //  #1. ".text" entry - the program code
24 //  #2. ".data" entry - global variables with initializers.     [ if needed ]
25 //  #3. ".bss" entry  - global variables without initializers.  [ if needed ]
26 //  ...
27 //  #N. ".shstrtab" entry - String table for the section names.
28 //
29 // NOTE: This code should eventually be extended to support 64-bit ELF (this
30 // won't be hard), but we haven't done so yet!
31 //
32 //===----------------------------------------------------------------------===//
33
34 #include "llvm/CodeGen/ELFWriter.h"
35 #include "llvm/Module.h"
36 #include "llvm/CodeGen/MachineCodeEmitter.h"
37 #include "llvm/CodeGen/MachineConstantPool.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Support/Mangler.h"
40 #include <iostream>
41 using namespace llvm;
42
43 //===----------------------------------------------------------------------===//
44 //                       ELFCodeEmitter Implementation
45 //===----------------------------------------------------------------------===//
46
47 namespace llvm {
48   /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
49   /// functions to the ELF file.
50   class ELFCodeEmitter : public MachineCodeEmitter {
51     ELFWriter &EW;
52     ELFWriter::ELFSection *ES;  // Section to write to.
53     std::vector<unsigned char> *OutBuffer;
54     size_t FnStart;
55   public:
56     ELFCodeEmitter(ELFWriter &ew) : EW(ew), OutBuffer(0) {}
57
58     void startFunction(MachineFunction &F);
59     void finishFunction(MachineFunction &F);
60
61     void emitConstantPool(MachineConstantPool *MCP) {
62       if (MCP->isEmpty()) return;
63       assert(0 && "unimp");
64     }
65     virtual void emitByte(unsigned char B) {
66       OutBuffer->push_back(B);
67     }
68     virtual void emitWordAt(unsigned W, unsigned *Ptr) {
69       assert(0 && "ni");
70     }
71     virtual void emitWord(unsigned W) {
72       assert(0 && "ni");
73     }
74     virtual uint64_t getCurrentPCValue() {
75       return OutBuffer->size();
76     }
77     virtual uint64_t getCurrentPCOffset() {
78       return OutBuffer->size()-FnStart;
79     }
80     void addRelocation(const MachineRelocation &MR) {
81       assert(0 && "relo not handled yet!");
82     }
83     virtual uint64_t getConstantPoolEntryAddress(unsigned Index) {
84       assert(0 && "CP not implementated yet!");
85       return 0;
86     }
87
88     virtual unsigned char* allocateGlobal(unsigned size, unsigned alignment) {
89       assert(0 && "Globals not implemented yet!");
90       return 0;
91     }
92
93     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
94     void startFunctionStub(unsigned StubSize) {
95       assert(0 && "JIT specific function called!");
96       abort();
97     }
98     void *finishFunctionStub(const Function *F) {
99       assert(0 && "JIT specific function called!");
100       abort();
101       return 0;
102     }
103   };
104 }
105
106 /// startFunction - This callback is invoked when a new machine function is
107 /// about to be emitted.
108 void ELFCodeEmitter::startFunction(MachineFunction &F) {
109   // Align the output buffer to the appropriate alignment.
110   unsigned Align = 16;   // FIXME: GENERICIZE!!
111   // Get the ELF Section that this function belongs in.
112   ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
113                       ELFWriter::ELFSection::SHF_EXECINSTR |
114                       ELFWriter::ELFSection::SHF_ALLOC);
115   OutBuffer = &ES->SectionData;
116
117   // Upgrade the section alignment if required.
118   if (ES->Align < Align) ES->Align = Align;
119
120   // Add padding zeros to the end of the buffer to make sure that the
121   // function will start on the correct byte alignment within the section.
122   size_t SectionOff = OutBuffer->size();
123   ELFWriter::align(*OutBuffer, Align);
124
125   FnStart = OutBuffer->size();
126 }
127
128 /// finishFunction - This callback is invoked after the function is completely
129 /// finished.
130 void ELFCodeEmitter::finishFunction(MachineFunction &F) {
131   // We now know the size of the function, add a symbol to represent it.
132   ELFWriter::ELFSym FnSym(F.getFunction());
133
134   // Figure out the binding (linkage) of the symbol.
135   switch (F.getFunction()->getLinkage()) {
136   default:
137     // appending linkage is illegal for functions.
138     assert(0 && "Unknown linkage type!");
139   case GlobalValue::ExternalLinkage:
140     FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
141     break;
142   case GlobalValue::LinkOnceLinkage:
143   case GlobalValue::WeakLinkage:
144     FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
145     break;
146   case GlobalValue::InternalLinkage:
147     FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
148     break;
149   }
150
151   ES->Size = OutBuffer->size();
152
153   FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
154   FnSym.SectionIdx = ES->SectionIdx;
155     FnSym.Value = FnStart;   // Value = Offset from start of Section.
156   FnSym.Size = OutBuffer->size()-FnStart;
157
158   // Finally, add it to the symtab.
159   EW.SymbolTable.push_back(FnSym);
160 }
161
162 //===----------------------------------------------------------------------===//
163 //                          ELFWriter Implementation
164 //===----------------------------------------------------------------------===//
165
166 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
167   e_machine = 0;  // e_machine defaults to 'No Machine'
168   e_flags = 0;    // e_flags defaults to 0, no flags.
169
170   is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;
171   isLittleEndian = TM.getTargetData().isLittleEndian();
172
173   // Create the machine code emitter object for this target.
174   MCE = new ELFCodeEmitter(*this);
175   NumSections = 0;
176 }
177
178 ELFWriter::~ELFWriter() {
179   delete MCE;
180 }
181
182 // doInitialization - Emit the file header and all of the global variables for
183 // the module to the ELF file.
184 bool ELFWriter::doInitialization(Module &M) {
185   Mang = new Mangler(M);
186
187   // Local alias to shortenify coming code.
188   std::vector<unsigned char> &FH = FileHeader;
189
190   outbyte(FH, 0x7F);                     // EI_MAG0
191   outbyte(FH, 'E');                      // EI_MAG1
192   outbyte(FH, 'L');                      // EI_MAG2
193   outbyte(FH, 'F');                      // EI_MAG3
194   outbyte(FH, is64Bit ? 2 : 1);          // EI_CLASS
195   outbyte(FH, isLittleEndian ? 1 : 2);   // EI_DATA
196   outbyte(FH, 1);                        // EI_VERSION
197   FH.resize(16);                         // EI_PAD up to 16 bytes.
198
199   // This should change for shared objects.
200   outhalf(FH, 1);                 // e_type = ET_REL
201   outhalf(FH, e_machine);         // e_machine = whatever the target wants
202   outword(FH, 1);                 // e_version = 1
203   outaddr(FH, 0);                 // e_entry = 0 -> no entry point in .o file
204   outaddr(FH, 0);                 // e_phoff = 0 -> no program header for .o
205
206   ELFHeader_e_shoff_Offset = FH.size();
207   outaddr(FH, 0);                 // e_shoff
208   outword(FH, e_flags);           // e_flags = whatever the target wants
209
210   outhalf(FH, is64Bit ? 64 : 52); // e_ehsize = ELF header size
211   outhalf(FH, 0);                 // e_phentsize = prog header entry size
212   outhalf(FH, 0);                 // e_phnum     = # prog header entries = 0
213   outhalf(FH, is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
214
215
216   ELFHeader_e_shnum_Offset = FH.size();
217   outhalf(FH, 0);                 // e_shnum     = # of section header ents
218   ELFHeader_e_shstrndx_Offset = FH.size();
219   outhalf(FH, 0);                 // e_shstrndx  = Section # of '.shstrtab'
220
221   // Add the null section, which is required to be first in the file.
222   getSection("", 0, 0);
223
224   // Start up the symbol table.  The first entry in the symtab is the null
225   // entry.
226   SymbolTable.push_back(ELFSym(0));
227
228   return false;
229 }
230
231 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
232   // If this is an external global, emit it now.  TODO: Note that it would be
233   // better to ignore the symbol here and only add it to the symbol table if
234   // referenced.
235   if (!GV->hasInitializer()) {
236     ELFSym ExternalSym(GV);
237     ExternalSym.SetBind(ELFSym::STB_GLOBAL);
238     ExternalSym.SetType(ELFSym::STT_NOTYPE);
239     ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
240     SymbolTable.push_back(ExternalSym);
241     return;
242   }
243
244   const Type *GVType = (const Type*)GV->getType();
245   unsigned Align = TM.getTargetData().getTypeAlignment(GVType);
246   unsigned Size  = TM.getTargetData().getTypeSize(GVType);
247
248   // If this global has a zero initializer, it is part of the .bss or common
249   // section.
250   if (GV->getInitializer()->isNullValue()) {
251     // If this global is part of the common block, add it now.  Variables are
252     // part of the common block if they are zero initialized and allowed to be
253     // merged with other symbols.
254     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
255       ELFSym CommonSym(GV);
256       // Value for common symbols is the alignment required.
257       CommonSym.Value = Align;
258       CommonSym.Size  = Size;
259       CommonSym.SetBind(ELFSym::STB_GLOBAL);
260       CommonSym.SetType(ELFSym::STT_OBJECT);
261       // TODO SOMEDAY: add ELF visibility.
262       CommonSym.SectionIdx = ELFSection::SHN_COMMON;
263       SymbolTable.push_back(CommonSym);
264       return;
265     }
266
267     // Otherwise, this symbol is part of the .bss section.  Emit it now.
268
269     // Handle alignment.  Ensure section is aligned at least as much as required
270     // by this symbol.
271     ELFSection &BSSSection = getBSSSection();
272     BSSSection.Align = std::max(BSSSection.Align, Align);
273
274     // Within the section, emit enough virtual padding to get us to an alignment
275     // boundary.
276     if (Align)
277       BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
278
279     ELFSym BSSSym(GV);
280     BSSSym.Value = BSSSection.Size;
281     BSSSym.Size = Size;
282     BSSSym.SetType(ELFSym::STT_OBJECT);
283
284     switch (GV->getLinkage()) {
285     default:  // weak/linkonce handled above
286       assert(0 && "Unexpected linkage type!");
287     case GlobalValue::AppendingLinkage:  // FIXME: This should be improved!
288     case GlobalValue::ExternalLinkage:
289       BSSSym.SetBind(ELFSym::STB_GLOBAL);
290       break;
291     case GlobalValue::InternalLinkage:
292       BSSSym.SetBind(ELFSym::STB_LOCAL);
293       break;
294     }
295
296     // Set the idx of the .bss section
297     BSSSym.SectionIdx = BSSSection.SectionIdx;
298     SymbolTable.push_back(BSSSym);
299
300     // Reserve space in the .bss section for this symbol.
301     BSSSection.Size += Size;
302     return;
303   }
304
305   // FIXME: handle .rodata
306   //assert(!GV->isConstant() && "unimp");
307
308   // FIXME: handle .data
309   //assert(0 && "unimp");
310 }
311
312
313 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
314   // Nothing to do here, this is all done through the MCE object above.
315   return false;
316 }
317
318 /// doFinalization - Now that the module has been completely processed, emit
319 /// the ELF file to 'O'.
320 bool ELFWriter::doFinalization(Module &M) {
321   // Okay, the ELF header and .text sections have been completed, build the
322   // .data, .bss, and "common" sections next.
323   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
324        I != E; ++I)
325     EmitGlobal(I);
326
327   // Emit the symbol table now, if non-empty.
328   EmitSymbolTable();
329
330   // FIXME: Emit the relocations now.
331
332   // Emit the string table for the sections in the ELF file we have.
333   EmitSectionTableStringTable();
334
335   // Emit the sections to the .o file, and emit the section table for the file.
336   OutputSectionsAndSectionTable();
337
338   // We are done with the abstract symbols.
339   SectionList.clear();
340   NumSections = 0;
341
342   // Release the name mangler object.
343   delete Mang; Mang = 0;
344   return false;
345 }
346
347 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
348 /// table for it and then the symbol table itself.
349 void ELFWriter::EmitSymbolTable() {
350   if (SymbolTable.size() == 1) return;  // Only the null entry.
351
352   // FIXME: compact all local symbols to the start of the symtab.
353   unsigned FirstNonLocalSymbol = 1;
354
355   ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
356   StrTab.Align = 1;
357
358   DataBuffer &StrTabBuf = StrTab.SectionData;
359
360   // Set the zero'th symbol to a null byte, as required.
361   outbyte(StrTabBuf, 0);
362   SymbolTable[0].NameIdx = 0;
363   unsigned Index = 1;
364   for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
365     // Use the name mangler to uniquify the LLVM symbol.
366     std::string Name = Mang->getValueName(SymbolTable[i].GV);
367
368     if (Name.empty()) {
369       SymbolTable[i].NameIdx = 0;
370     } else {
371       SymbolTable[i].NameIdx = Index;
372
373       // Add the name to the output buffer, including the null terminator.
374       StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
375
376       // Add a null terminator.
377       StrTabBuf.push_back(0);
378
379       // Keep track of the number of bytes emitted to this section.
380       Index += Name.size()+1;
381     }
382   }
383   assert(Index == StrTabBuf.size());
384   StrTab.Size = Index;
385
386   // Now that we have emitted the string table and know the offset into the
387   // string table of each symbol, emit the symbol table itself.
388   ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
389   SymTab.Align = is64Bit ? 8 : 4;
390   SymTab.Link = SymTab.SectionIdx;     // Section Index of .strtab.
391   SymTab.Info = FirstNonLocalSymbol;   // First non-STB_LOCAL symbol.
392   SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
393   DataBuffer &SymTabBuf = SymTab.SectionData;
394
395   if (!is64Bit) {   // 32-bit and 64-bit formats are shuffled a bit.
396     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
397       ELFSym &Sym = SymbolTable[i];
398       outword(SymTabBuf, Sym.NameIdx);
399       outaddr32(SymTabBuf, Sym.Value);
400       outword(SymTabBuf, Sym.Size);
401       outbyte(SymTabBuf, Sym.Info);
402       outbyte(SymTabBuf, Sym.Other);
403       outhalf(SymTabBuf, Sym.SectionIdx);
404     }
405   } else {
406     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
407       ELFSym &Sym = SymbolTable[i];
408       outword(SymTabBuf, Sym.NameIdx);
409       outbyte(SymTabBuf, Sym.Info);
410       outbyte(SymTabBuf, Sym.Other);
411       outhalf(SymTabBuf, Sym.SectionIdx);
412       outaddr64(SymTabBuf, Sym.Value);
413       outxword(SymTabBuf, Sym.Size);
414     }
415   }
416
417   SymTab.Size = SymTabBuf.size();
418 }
419
420 /// EmitSectionTableStringTable - This method adds and emits a section for the
421 /// ELF Section Table string table: the string table that holds all of the
422 /// section names.
423 void ELFWriter::EmitSectionTableStringTable() {
424   // First step: add the section for the string table to the list of sections:
425   ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
426
427   // Now that we know which section number is the .shstrtab section, update the
428   // e_shstrndx entry in the ELF header.
429   fixhalf(FileHeader, SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
430
431   // Set the NameIdx of each section in the string table and emit the bytes for
432   // the string table.
433   unsigned Index = 0;
434   DataBuffer &Buf = SHStrTab.SectionData;
435
436   for (std::list<ELFSection>::iterator I = SectionList.begin(),
437          E = SectionList.end(); I != E; ++I) {
438     // Set the index into the table.  Note if we have lots of entries with
439     // common suffixes, we could memoize them here if we cared.
440     I->NameIdx = Index;
441
442     // Add the name to the output buffer, including the null terminator.
443     Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
444
445     // Add a null terminator.
446     Buf.push_back(0);
447
448     // Keep track of the number of bytes emitted to this section.
449     Index += I->Name.size()+1;
450   }
451
452   // Set the size of .shstrtab now that we know what it is.
453   assert(Index == Buf.size());
454   SHStrTab.Size = Index;
455 }
456
457 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
458 /// and all of the sections, emit these to the ostream destination and emit the
459 /// SectionTable.
460 void ELFWriter::OutputSectionsAndSectionTable() {
461   // Pass #1: Compute the file offset for each section.
462   size_t FileOff = FileHeader.size();   // File header first.
463
464   // Emit all of the section data in order.
465   for (std::list<ELFSection>::iterator I = SectionList.begin(),
466          E = SectionList.end(); I != E; ++I) {
467     // Align FileOff to whatever the alignment restrictions of the section are.
468     if (I->Align)
469       FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
470     I->Offset = FileOff;
471     FileOff += I->SectionData.size();
472   }
473
474   // Align Section Header.
475   unsigned TableAlign = is64Bit ? 8 : 4;
476   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
477
478   // Now that we know where all of the sections will be emitted, set the e_shnum
479   // entry in the ELF header.
480   fixhalf(FileHeader, NumSections, ELFHeader_e_shnum_Offset);
481
482   // Now that we know the offset in the file of the section table, update the
483   // e_shoff address in the ELF header.
484   fixaddr(FileHeader, FileOff, ELFHeader_e_shoff_Offset);
485
486   // Now that we know all of the data in the file header, emit it and all of the
487   // sections!
488   O.write((char*)&FileHeader[0], FileHeader.size());
489   FileOff = FileHeader.size();
490   DataBuffer().swap(FileHeader);
491
492   DataBuffer Table;
493
494   // Emit all of the section data and build the section table itself.
495   while (!SectionList.empty()) {
496     const ELFSection &S = *SectionList.begin();
497
498     // Align FileOff to whatever the alignment restrictions of the section are.
499     if (S.Align)
500       for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
501            FileOff != NewFileOff; ++FileOff)
502         O.put((char)0xAB);
503     O.write((char*)&S.SectionData[0], S.SectionData.size());
504     FileOff += S.SectionData.size();
505
506     outword(Table, S.NameIdx);  // sh_name - Symbol table name idx
507     outword(Table, S.Type);     // sh_type - Section contents & semantics
508     outword(Table, S.Flags);    // sh_flags - Section flags.
509     outaddr(Table, S.Addr);     // sh_addr - The mem addr this section is in.
510     outaddr(Table, S.Offset);   // sh_offset - Offset from the file start.
511     outword(Table, S.Size);     // sh_size - The section size.
512     outword(Table, S.Link);     // sh_link - Section header table index link.
513     outword(Table, S.Info);     // sh_info - Auxillary information.
514     outword(Table, S.Align);    // sh_addralign - Alignment of section.
515     outword(Table, S.EntSize);  // sh_entsize - Size of entries in the section.
516
517     SectionList.pop_front();
518   }
519
520   // Align output for the section table.
521   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
522        FileOff != NewFileOff; ++FileOff)
523     O.put((char)0xAB);
524
525   // Emit the section table itself.
526   O.write((char*)&Table[0], Table.size());
527 }