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