ELF improvements:
[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 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "elfwriter"
32 #include "ELF.h"
33 #include "ELFWriter.h"
34 #include "ELFCodeEmitter.h"
35 #include "llvm/Constants.h"
36 #include "llvm/Module.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/DerivedTypes.h"
39 #include "llvm/CodeGen/BinaryObject.h"
40 #include "llvm/CodeGen/FileWriters.h"
41 #include "llvm/CodeGen/MachineCodeEmitter.h"
42 #include "llvm/CodeGen/ObjectCodeEmitter.h"
43 #include "llvm/CodeGen/MachineCodeEmitter.h"
44 #include "llvm/CodeGen/MachineConstantPool.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCSection.h"
47 #include "llvm/Target/TargetAsmInfo.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Target/TargetELFWriterInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Support/Mangler.h"
54 #include "llvm/Support/Streams.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58
59 using namespace llvm;
60
61 char ELFWriter::ID = 0;
62
63 /// AddELFWriter - Add the ELF writer to the function pass manager
64 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
65                                       raw_ostream &O,
66                                       TargetMachine &TM) {
67   ELFWriter *EW = new ELFWriter(O, TM);
68   PM.add(EW);
69   return EW->getObjectCodeEmitter();
70 }
71
72 //===----------------------------------------------------------------------===//
73 //                          ELFWriter Implementation
74 //===----------------------------------------------------------------------===//
75
76 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
77   : MachineFunctionPass(&ID), O(o), TM(tm),
78     OutContext(*new MCContext()),
79     TLOF(TM.getTargetLowering()->getObjFileLowering()),
80     is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
81     isLittleEndian(TM.getTargetData()->isLittleEndian()),
82     ElfHdr(isLittleEndian, is64Bit) {
83
84   TAI = TM.getTargetAsmInfo();
85   TEW = TM.getELFWriterInfo();
86
87   // Create the object code emitter object for this target.
88   ElfCE = new ELFCodeEmitter(*this);
89
90   // Inital number of sections
91   NumSections = 0;
92 }
93
94 ELFWriter::~ELFWriter() {
95   delete ElfCE;
96   delete &OutContext;
97 }
98
99 // doInitialization - Emit the file header and all of the global variables for
100 // the module to the ELF file.
101 bool ELFWriter::doInitialization(Module &M) {
102   // Initialize TargetLoweringObjectFile.
103   const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
104   
105   Mang = new Mangler(M);
106
107   // ELF Header
108   // ----------
109   // Fields e_shnum e_shstrndx are only known after all section have
110   // been emitted. They locations in the ouput buffer are recorded so
111   // to be patched up later.
112   //
113   // Note
114   // ----
115   // emitWord method behaves differently for ELF32 and ELF64, writing
116   // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
117
118   ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
119   ElfHdr.emitByte('E');  // e_ident[EI_MAG1]
120   ElfHdr.emitByte('L');  // e_ident[EI_MAG2]
121   ElfHdr.emitByte('F');  // e_ident[EI_MAG3]
122
123   ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
124   ElfHdr.emitByte(TEW->getEIData());  // e_ident[EI_DATA]
125   ElfHdr.emitByte(EV_CURRENT);        // e_ident[EI_VERSION]
126   ElfHdr.emitAlignment(16);           // e_ident[EI_NIDENT-EI_PAD]
127
128   ElfHdr.emitWord16(ET_REL);             // e_type
129   ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
130   ElfHdr.emitWord32(EV_CURRENT);         // e_version
131   ElfHdr.emitWord(0);                    // e_entry, no entry point in .o file
132   ElfHdr.emitWord(0);                    // e_phoff, no program header for .o
133   ELFHdr_e_shoff_Offset = ElfHdr.size();
134   ElfHdr.emitWord(0);                    // e_shoff = sec hdr table off in bytes
135   ElfHdr.emitWord32(TEW->getEFlags());   // e_flags = whatever the target wants
136   ElfHdr.emitWord16(TEW->getHdrSize());  // e_ehsize = ELF header size
137   ElfHdr.emitWord16(0);                  // e_phentsize = prog header entry size
138   ElfHdr.emitWord16(0);                  // e_phnum = # prog header entries = 0
139
140   // e_shentsize = Section header entry size
141   ElfHdr.emitWord16(TEW->getSHdrSize());
142
143   // e_shnum     = # of section header ents
144   ELFHdr_e_shnum_Offset = ElfHdr.size();
145   ElfHdr.emitWord16(0); // Placeholder
146
147   // e_shstrndx  = Section # of '.shstrtab'
148   ELFHdr_e_shstrndx_Offset = ElfHdr.size();
149   ElfHdr.emitWord16(0); // Placeholder
150
151   // Add the null section, which is required to be first in the file.
152   getNullSection();
153
154   // The first entry in the symtab is the null symbol and the second
155   // is a local symbol containing the module/file name
156   SymbolList.push_back(new ELFSym());
157   SymbolList.push_back(ELFSym::getFileSym());
158
159   return false;
160 }
161
162 // addGlobalSymbol - Add a global to be processed and to the global symbol 
163 // lookup, use a zero index because the table index will be determined later.
164 void ELFWriter::addGlobalSymbol(const GlobalValue *GV, 
165                                 bool AddToLookup /* = false */) {
166   PendingGlobals.insert(GV);
167   if (AddToLookup) 
168     GblSymLookup[GV] = 0;
169 }
170
171 // addExternalSymbol - Add the external to be processed and to the
172 // external symbol lookup, use a zero index because the symbol
173 // table index will be determined later
174 void ELFWriter::addExternalSymbol(const char *External) {
175   PendingExternals.insert(External);
176   ExtSymLookup[External] = 0;
177 }
178
179 // getCtorSection - Get the static constructor section
180 ELFSection &ELFWriter::getCtorSection() {
181   const MCSection *Ctor = TLOF.getStaticCtorSection();
182   return getSection(Ctor->getName(), ELFSection::SHT_PROGBITS, 
183                     getElfSectionFlags(Ctor->getKind()));
184 }
185
186 // getDtorSection - Get the static destructor section
187 ELFSection &ELFWriter::getDtorSection() {
188   const MCSection *Dtor = TLOF.getStaticDtorSection();
189   return getSection(Dtor->getName(), ELFSection::SHT_PROGBITS, 
190                     getElfSectionFlags(Dtor->getKind()));
191 }
192
193 // getTextSection - Get the text section for the specified function
194 ELFSection &ELFWriter::getTextSection(Function *F) {
195   const MCSection *Text = TLOF.SectionForGlobal(F, Mang, TM);
196   return getSection(Text->getName(), ELFSection::SHT_PROGBITS,
197                     getElfSectionFlags(Text->getKind()));
198 }
199
200 // getJumpTableSection - Get a read only section for constants when 
201 // emitting jump tables. TODO: add PIC support
202 ELFSection &ELFWriter::getJumpTableSection() {
203   const MCSection *JT = TLOF.getSectionForConstant(SectionKind::getReadOnly());
204   return getSection(JT->getName(), 
205                     ELFSection::SHT_PROGBITS,
206                     getElfSectionFlags(JT->getKind()), 
207                     TM.getTargetData()->getPointerABIAlignment());
208 }
209
210 // getConstantPoolSection - Get a constant pool section based on the machine 
211 // constant pool entry type and relocation info.
212 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
213   SectionKind Kind;
214   switch (CPE.getRelocationInfo()) {
215   default: llvm_unreachable("Unknown section kind");
216   case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
217   case 1:
218     Kind = SectionKind::getReadOnlyWithRelLocal();
219     break;
220   case 0:
221     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
222     case 4:  Kind = SectionKind::getMergeableConst4(); break;
223     case 8:  Kind = SectionKind::getMergeableConst8(); break;
224     case 16: Kind = SectionKind::getMergeableConst16(); break;
225     default: Kind = SectionKind::getMergeableConst(); break;
226     }
227   }
228
229   return getSection(TLOF.getSectionForConstant(Kind)->getName(),
230                     ELFSection::SHT_PROGBITS,
231                     getElfSectionFlags(Kind),
232                     CPE.getAlignment());
233 }
234
235 // getRelocSection - Return the relocation section of section 'S'. 'RelA' 
236 // is true if the relocation section contains entries with addends.
237 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
238   unsigned SectionHeaderTy = TEW->hasRelocationAddend() ?
239                               ELFSection::SHT_RELA : ELFSection::SHT_REL;
240   std::string RelSName(".rel");
241   if (TEW->hasRelocationAddend())
242     RelSName.append("a");
243   RelSName.append(S.getName());
244
245   return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
246 }
247
248 // getGlobalELFVisibility - Returns the ELF specific visibility type
249 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
250   switch (GV->getVisibility()) {
251   default:
252     llvm_unreachable("unknown visibility type");
253   case GlobalValue::DefaultVisibility:
254     return ELFSym::STV_DEFAULT;
255   case GlobalValue::HiddenVisibility:
256     return ELFSym::STV_HIDDEN;
257   case GlobalValue::ProtectedVisibility:
258     return ELFSym::STV_PROTECTED;
259   }
260   return 0;
261 }
262
263 // getGlobalELFBinding - Returns the ELF specific binding type
264 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
265   if (GV->hasInternalLinkage())
266     return ELFSym::STB_LOCAL;
267
268   if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
269     return ELFSym::STB_WEAK;
270
271   return ELFSym::STB_GLOBAL;
272 }
273
274 // getGlobalELFType - Returns the ELF specific type for a global
275 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
276   if (GV->isDeclaration())
277     return ELFSym::STT_NOTYPE;
278
279   if (isa<Function>(GV))
280     return ELFSym::STT_FUNC;
281
282   return ELFSym::STT_OBJECT;
283 }
284
285 // getElfSectionFlags - Get the ELF Section Header flags based
286 // on the flags defined in SectionKind.h.
287 unsigned ELFWriter::getElfSectionFlags(SectionKind Kind, bool IsAlloc) {
288   unsigned ElfSectionFlags = 0;
289   
290   if (IsAlloc)
291     ElfSectionFlags |= ELFSection::SHF_ALLOC;
292   if (Kind.isText())
293     ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
294   if (Kind.isWriteable())
295     ElfSectionFlags |= ELFSection::SHF_WRITE;
296   if (Kind.isMergeableConst() || Kind.isMergeableCString())
297     ElfSectionFlags |= ELFSection::SHF_MERGE;
298   if (Kind.isThreadLocal())
299     ElfSectionFlags |= ELFSection::SHF_TLS;
300   if (Kind.isMergeableCString())
301     ElfSectionFlags |= ELFSection::SHF_STRINGS;
302
303   return ElfSectionFlags;
304 }
305
306 // isUndefOrNull - The constant is either a null initialized value or an
307 // undefined one.
308 static bool isUndefOrNull(const Constant *CV) {
309   return (CV->isNullValue() || isa<UndefValue>(CV));
310 }
311
312 // isELFUndefSym - the symbol has no section and must be placed in
313 // the symbol table with a reference to the null section.
314 static bool isELFUndefSym(const GlobalValue *GV) {
315   // Functions which make up until this point references are an undef symbol
316   return GV->isDeclaration() || (isa<Function>(GV));
317 }
318
319 // isELFBssSym - for an undef or null value, the symbol must go to a bss
320 // section if it's not weak for linker, otherwise it's a common sym.
321 static bool isELFBssSym(const GlobalVariable *GV, SectionKind Kind) {
322   const Constant *CV = GV->getInitializer();
323
324   return (!Kind.isMergeableCString() && 
325           isUndefOrNull(CV) && 
326           !GV->isWeakForLinker());
327 }
328
329 // isELFCommonSym - for an undef or null value, the symbol must go to a
330 // common section if it's weak for linker, otherwise bss.
331 static bool isELFCommonSym(const GlobalVariable *GV) {
332   return (isUndefOrNull(GV->getInitializer()) && GV->isWeakForLinker());
333 }
334
335 // EmitGlobal - Choose the right section for global and emit it
336 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
337
338   // Check if the referenced symbol is already emitted
339   if (GblSymLookup.find(GV) != GblSymLookup.end())
340     return;
341
342   // Handle ELF Bind, Visibility and Type for the current symbol
343   unsigned SymBind = getGlobalELFBinding(GV);
344   unsigned SymType = getGlobalELFType(GV);
345
346   // All undef symbols have the same binding, type and visibily and
347   // are classified regardless of their type.
348   ELFSym *GblSym = isELFUndefSym(GV) ? ELFSym::getUndefGV(GV, SymBind)
349     : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
350
351   if (!isELFUndefSym(GV)) {
352     assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
353     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
354
355     // Handle special llvm globals
356     if (EmitSpecialLLVMGlobal(GVar))
357       return;
358
359     // Get the ELF section where this global belongs from TLOF
360     const MCSection *S = TLOF.SectionForGlobal(GV, Mang, TM);
361     SectionKind Kind = ((MCSectionELF*)S)->getKind();
362     unsigned SectionFlags = getElfSectionFlags(Kind);
363
364     // The symbol align should update the section alignment if needed
365     const TargetData *TD = TM.getTargetData();
366     unsigned Align = TD->getPreferredAlignment(GVar);
367     unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
368     GblSym->Size = Size;
369
370     if (isELFCommonSym(GVar)) {
371       GblSym->SectionIdx = ELFSection::SHN_COMMON;
372       getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
373
374       // A new linkonce section is created for each global in the
375       // common section, the default alignment is 1 and the symbol
376       // value contains its alignment.
377       GblSym->Value = Align;
378
379     } else if (isELFBssSym(GVar, Kind)) {
380       ELFSection &ES =
381         getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
382       GblSym->SectionIdx = ES.SectionIdx;
383
384       // Update the size with alignment and the next object can
385       // start in the right offset in the section
386       if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
387       ES.Align = std::max(ES.Align, Align);
388
389       // GblSym->Value should contain the virtual offset inside the section.
390       // Virtual because the BSS space is not allocated on ELF objects
391       GblSym->Value = ES.Size;
392       ES.Size += Size;
393
394     } else { // The symbol must go to some kind of data section
395       ELFSection &ES =
396         getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
397       GblSym->SectionIdx = ES.SectionIdx;
398
399       // GblSym->Value should contain the symbol offset inside the section,
400       // and all symbols should start on their required alignment boundary
401       ES.Align = std::max(ES.Align, Align);
402       ES.emitAlignment(Align);
403       GblSym->Value = ES.size();
404
405       // Emit the global to the data section 'ES'
406       EmitGlobalConstant(GVar->getInitializer(), ES);
407     }
408   }
409
410   if (GV->hasPrivateLinkage()) {
411     // For a private symbols, keep track of the index inside the
412     // private list since it will never go to the symbol table and
413     // won't be patched up later.
414     PrivateSyms.push_back(GblSym);
415     GblSymLookup[GV] = PrivateSyms.size()-1;
416   } else {
417     // Non private symbol are left with zero indices until they are patched
418     // up during the symbol table emition (where the indicies are created).
419     SymbolList.push_back(GblSym);
420     GblSymLookup[GV] = 0;
421   }
422 }
423
424 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
425                                          ELFSection &GblS) {
426
427   // Print the fields in successive locations. Pad to align if needed!
428   const TargetData *TD = TM.getTargetData();
429   unsigned Size = TD->getTypeAllocSize(CVS->getType());
430   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
431   uint64_t sizeSoFar = 0;
432   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
433     const Constant* field = CVS->getOperand(i);
434
435     // Check if padding is needed and insert one or more 0s.
436     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
437     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
438                         - cvsLayout->getElementOffset(i)) - fieldSize;
439     sizeSoFar += fieldSize + padSize;
440
441     // Now print the actual field value.
442     EmitGlobalConstant(field, GblS);
443
444     // Insert padding - this may include padding to increase the size of the
445     // current field up to the ABI size (if the struct is not packed) as well
446     // as padding to ensure that the next field starts at the right offset.
447     GblS.emitZeros(padSize);
448   }
449   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
450          "Layout of constant struct may be incorrect!");
451 }
452
453 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
454   const TargetData *TD = TM.getTargetData();
455   unsigned Size = TD->getTypeAllocSize(CV->getType());
456
457   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
458     for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
459       EmitGlobalConstant(CVA->getOperand(i), GblS);
460     return;
461   } else if (isa<ConstantAggregateZero>(CV)) {
462     GblS.emitZeros(Size);
463     return;
464   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
465     EmitGlobalConstantStruct(CVS, GblS);
466     return;
467   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
468     APInt Val = CFP->getValueAPF().bitcastToAPInt();
469     if (CFP->getType() == Type::DoubleTy)
470       GblS.emitWord64(Val.getZExtValue());
471     else if (CFP->getType() == Type::FloatTy)
472       GblS.emitWord32(Val.getZExtValue());
473     else if (CFP->getType() == Type::X86_FP80Ty) {
474       unsigned PadSize = TD->getTypeAllocSize(Type::X86_FP80Ty)-
475                          TD->getTypeStoreSize(Type::X86_FP80Ty);
476       GblS.emitWordFP80(Val.getRawData(), PadSize);
477     } else if (CFP->getType() == Type::PPC_FP128Ty)
478       llvm_unreachable("PPC_FP128Ty global emission not implemented");
479     return;
480   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
481     if (Size == 1)
482       GblS.emitByte(CI->getZExtValue());
483     else if (Size == 2) 
484       GblS.emitWord16(CI->getZExtValue());
485     else if (Size == 4)
486       GblS.emitWord32(CI->getZExtValue());
487     else 
488       EmitGlobalConstantLargeInt(CI, GblS);
489     return;
490   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
491     const VectorType *PTy = CP->getType();
492     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
493       EmitGlobalConstant(CP->getOperand(I), GblS);
494     return;
495   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
496     switch (CE->getOpcode()) {
497     case Instruction::BitCast: {
498       EmitGlobalConstant(CE->getOperand(0), GblS);
499       return;
500     }
501     case Instruction::GetElementPtr: {
502       const Constant *ptrVal = CE->getOperand(0);
503       SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
504       int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
505                                             idxVec.size());
506       EmitGlobalDataRelocation(cast<const GlobalValue>(ptrVal), 
507                                TD->getTypeAllocSize(ptrVal->getType()), 
508                                GblS, Offset);
509       return;
510     }
511     case Instruction::IntToPtr: {
512       Constant *Op = CE->getOperand(0);
513       Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
514       EmitGlobalConstant(Op, GblS);
515       return;
516     }
517     }
518     std::string msg(CE->getOpcodeName());
519     raw_string_ostream ErrorMsg(msg);
520     ErrorMsg << ": Unsupported ConstantExpr type";
521     llvm_report_error(ErrorMsg.str());
522   } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
523     // Fill the data entry with zeros or emit a relocation entry
524     if (isa<ConstantPointerNull>(CV))
525       GblS.emitZeros(Size);
526     else 
527       EmitGlobalDataRelocation(cast<const GlobalValue>(CV), 
528                                Size, GblS);
529     return;
530   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
531     // This is a constant address for a global variable or function and
532     // therefore must be referenced using a relocation entry.
533     EmitGlobalDataRelocation(GV, Size, GblS);
534     return;
535   }
536
537   std::string msg;
538   raw_string_ostream ErrorMsg(msg);
539   ErrorMsg << "Constant unimp for type: " << *CV->getType();
540   llvm_report_error(ErrorMsg.str());
541 }
542
543 void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
544                                          ELFSection &GblS, uint64_t Offset) {
545   // Create the relocation entry for the global value
546   MachineRelocation MR =
547     MachineRelocation::getGV(GblS.getCurrentPCOffset(),
548                              TEW->getAbsoluteLabelMachineRelTy(),
549                              const_cast<GlobalValue*>(GV),
550                              Offset);
551
552   // Fill the data entry with zeros
553   GblS.emitZeros(Size);
554
555   // Add the relocation entry for the current data section
556   GblS.addRelocation(MR);
557 }
558
559 void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI, 
560                                            ELFSection &S) {
561   const TargetData *TD = TM.getTargetData();
562   unsigned BitWidth = CI->getBitWidth();
563   assert(isPowerOf2_32(BitWidth) &&
564          "Non-power-of-2-sized integers not handled!");
565
566   const uint64_t *RawData = CI->getValue().getRawData();
567   uint64_t Val = 0;
568   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
569     Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
570     S.emitWord64(Val);
571   }
572 }
573
574 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
575 /// special global used by LLVM.  If so, emit it and return true, otherwise
576 /// do nothing and return false.
577 bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
578   if (GV->getName() == "llvm.used")
579     llvm_unreachable("not implemented yet");
580
581   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
582   if (GV->getSection() == "llvm.metadata" ||
583       GV->hasAvailableExternallyLinkage())
584     return true;
585   
586   if (!GV->hasAppendingLinkage()) return false;
587
588   assert(GV->hasInitializer() && "Not a special LLVM global!");
589   
590   const TargetData *TD = TM.getTargetData();
591   unsigned Align = TD->getPointerPrefAlignment();
592   if (GV->getName() == "llvm.global_ctors") {
593     ELFSection &Ctor = getCtorSection();
594     Ctor.emitAlignment(Align);
595     EmitXXStructorList(GV->getInitializer(), Ctor);
596     return true;
597   } 
598   
599   if (GV->getName() == "llvm.global_dtors") {
600     ELFSection &Dtor = getDtorSection();
601     Dtor.emitAlignment(Align);
602     EmitXXStructorList(GV->getInitializer(), Dtor);
603     return true;
604   }
605   
606   return false;
607 }
608
609 /// EmitXXStructorList - Emit the ctor or dtor list.  This just emits out the 
610 /// function pointers, ignoring the init priority.
611 void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
612   // Should be an array of '{ int, void ()* }' structs.  The first value is the
613   // init priority, which we ignore.
614   if (!isa<ConstantArray>(List)) return;
615   ConstantArray *InitList = cast<ConstantArray>(List);
616   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
617     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
618       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
619
620       if (CS->getOperand(1)->isNullValue())
621         return;  // Found a null terminator, exit printing.
622       // Emit the function pointer.
623       EmitGlobalConstant(CS->getOperand(1), Xtor);
624     }
625 }
626
627 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
628   // Nothing to do here, this is all done through the ElfCE object above.
629   return false;
630 }
631
632 /// doFinalization - Now that the module has been completely processed, emit
633 /// the ELF file to 'O'.
634 bool ELFWriter::doFinalization(Module &M) {
635   // Emit .data section placeholder
636   getDataSection();
637
638   // Emit .bss section placeholder
639   getBSSSection();
640
641   // Build and emit data, bss and "common" sections.
642   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
643        I != E; ++I)
644     EmitGlobal(I);
645
646   // Emit all pending globals
647   for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
648        I != E; ++I)
649     EmitGlobal(*I);
650
651   // Emit all pending externals
652   for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
653        I != E; ++I)
654     SymbolList.push_back(ELFSym::getExtSym(*I));
655
656   // Emit non-executable stack note
657   if (TAI->getNonexecutableStackDirective())
658     getNonExecStackSection();
659
660   // Emit a symbol for each section created until now, skip null section
661   for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
662     ELFSection &ES = *SectionList[i];
663     ELFSym *SectionSym = ELFSym::getSectionSym();
664     SectionSym->SectionIdx = ES.SectionIdx;
665     SymbolList.push_back(SectionSym);
666     ES.Sym = SymbolList.back();
667   }
668
669   // Emit string table
670   EmitStringTable(M.getModuleIdentifier());
671
672   // Emit the symbol table now, if non-empty.
673   EmitSymbolTable();
674
675   // Emit the relocation sections.
676   EmitRelocations();
677
678   // Emit the sections string table.
679   EmitSectionTableStringTable();
680
681   // Dump the sections and section table to the .o file.
682   OutputSectionsAndSectionTable();
683
684   // We are done with the abstract symbols.
685   SymbolList.clear();
686   SectionList.clear();
687   NumSections = 0;
688
689   // Release the name mangler object.
690   delete Mang; Mang = 0;
691   return false;
692 }
693
694 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
695 // using a 'Value' of known 'Size'
696 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
697                               int64_t Value, unsigned Size) {
698   if (Size == 32)
699     BO.fixWord32(Value, Offset);
700   else if (Size == 64)
701     BO.fixWord64(Value, Offset);
702   else
703     llvm_unreachable("don't know howto patch relocatable field");
704 }
705
706 /// EmitRelocations - Emit relocations
707 void ELFWriter::EmitRelocations() {
708
709   // True if the target uses the relocation entry to hold the addend,
710   // otherwise the addend is written directly to the relocatable field.
711   bool HasRelA = TEW->hasRelocationAddend();
712
713   // Create Relocation sections for each section which needs it.
714   for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
715     ELFSection &S = *SectionList[i];
716
717     // This section does not have relocations
718     if (!S.hasRelocations()) continue;
719     ELFSection &RelSec = getRelocSection(S);
720
721     // 'Link' - Section hdr idx of the associated symbol table
722     // 'Info' - Section hdr idx of the section to which the relocation applies
723     ELFSection &SymTab = getSymbolTableSection();
724     RelSec.Link = SymTab.SectionIdx;
725     RelSec.Info = S.SectionIdx;
726     RelSec.EntSize = TEW->getRelocationEntrySize();
727
728     // Get the relocations from Section
729     std::vector<MachineRelocation> Relos = S.getRelocations();
730     for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
731          MRE = Relos.end(); MRI != MRE; ++MRI) {
732       MachineRelocation &MR = *MRI;
733
734       // Relocatable field offset from the section start
735       unsigned RelOffset = MR.getMachineCodeOffset();
736
737       // Symbol index in the symbol table
738       unsigned SymIdx = 0;
739
740       // Target specific relocation field type and size
741       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
742       unsigned RelTySize = TEW->getRelocationTySize(RelType);
743       int64_t Addend = 0;
744
745       // There are several machine relocations types, and each one of
746       // them needs a different approach to retrieve the symbol table index.
747       if (MR.isGlobalValue()) {
748         const GlobalValue *G = MR.getGlobalValue();
749         int64_t GlobalOffset = MR.getConstantVal();
750         SymIdx = GblSymLookup[G];
751         if (G->hasPrivateLinkage()) {
752           // If the target uses a section offset in the relocation:
753           // SymIdx + Addend = section sym for global + section offset
754           unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
755           Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
756           SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
757         } else {
758           Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
759         }
760       } else if (MR.isExternalSymbol()) {
761         const char *ExtSym = MR.getExternalSymbol();
762         SymIdx = ExtSymLookup[ExtSym];
763         Addend = TEW->getDefaultAddendForRelTy(RelType);
764       } else {
765         // Get the symbol index for the section symbol
766         unsigned SectionIdx = MR.getConstantVal();
767         SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
768
769         // The symbol offset inside the section
770         int64_t SymOffset = (int64_t)MR.getResultPointer();
771
772         // For pc relative relocations where symbols are defined in the same
773         // section they are referenced, ignore the relocation entry and patch
774         // the relocatable field with the symbol offset directly.
775         if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
776           int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
777           RelocateField(S, RelOffset, Value, RelTySize);
778           continue;
779         }
780
781         Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
782       }
783
784       // The target without addend on the relocation symbol must be
785       // patched in the relocation place itself to contain the addend
786       // otherwise write zeros to make sure there is no garbage there
787       RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
788
789       // Get the relocation entry and emit to the relocation section
790       ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
791       EmitRelocation(RelSec, Rel, HasRelA);
792     }
793   }
794 }
795
796 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
797 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
798                                bool HasRelA) {
799   RelSec.emitWord(Rel.getOffset());
800   RelSec.emitWord(Rel.getInfo(is64Bit));
801   if (HasRelA)
802     RelSec.emitWord(Rel.getAddend());
803 }
804
805 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
806 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
807   if (is64Bit) {
808     SymbolTable.emitWord32(Sym.NameIdx);
809     SymbolTable.emitByte(Sym.Info);
810     SymbolTable.emitByte(Sym.Other);
811     SymbolTable.emitWord16(Sym.SectionIdx);
812     SymbolTable.emitWord64(Sym.Value);
813     SymbolTable.emitWord64(Sym.Size);
814   } else {
815     SymbolTable.emitWord32(Sym.NameIdx);
816     SymbolTable.emitWord32(Sym.Value);
817     SymbolTable.emitWord32(Sym.Size);
818     SymbolTable.emitByte(Sym.Info);
819     SymbolTable.emitByte(Sym.Other);
820     SymbolTable.emitWord16(Sym.SectionIdx);
821   }
822 }
823
824 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
825 /// Section Header Table
826 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
827                                   const ELFSection &SHdr) {
828   SHdrTab.emitWord32(SHdr.NameIdx);
829   SHdrTab.emitWord32(SHdr.Type);
830   if (is64Bit) {
831     SHdrTab.emitWord64(SHdr.Flags);
832     SHdrTab.emitWord(SHdr.Addr);
833     SHdrTab.emitWord(SHdr.Offset);
834     SHdrTab.emitWord64(SHdr.Size);
835     SHdrTab.emitWord32(SHdr.Link);
836     SHdrTab.emitWord32(SHdr.Info);
837     SHdrTab.emitWord64(SHdr.Align);
838     SHdrTab.emitWord64(SHdr.EntSize);
839   } else {
840     SHdrTab.emitWord32(SHdr.Flags);
841     SHdrTab.emitWord(SHdr.Addr);
842     SHdrTab.emitWord(SHdr.Offset);
843     SHdrTab.emitWord32(SHdr.Size);
844     SHdrTab.emitWord32(SHdr.Link);
845     SHdrTab.emitWord32(SHdr.Info);
846     SHdrTab.emitWord32(SHdr.Align);
847     SHdrTab.emitWord32(SHdr.EntSize);
848   }
849 }
850
851 /// EmitStringTable - If the current symbol table is non-empty, emit the string
852 /// table for it
853 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
854   if (!SymbolList.size()) return;  // Empty symbol table.
855   ELFSection &StrTab = getStringTableSection();
856
857   // Set the zero'th symbol to a null byte, as required.
858   StrTab.emitByte(0);
859
860   // Walk on the symbol list and write symbol names into the string table.
861   unsigned Index = 1;
862   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
863     ELFSym &Sym = *(*I);
864
865     std::string Name;
866     if (Sym.isGlobalValue())
867       // Use the name mangler to uniquify the LLVM symbol.
868       Name.append(Mang->getMangledName(Sym.getGlobalValue()));
869     else if (Sym.isExternalSym())
870       Name.append(Sym.getExternalSymbol());
871     else if (Sym.isFileType())
872       Name.append(ModuleName);
873
874     if (Name.empty()) {
875       Sym.NameIdx = 0;
876     } else {
877       Sym.NameIdx = Index;
878       StrTab.emitString(Name);
879
880       // Keep track of the number of bytes emitted to this section.
881       Index += Name.size()+1;
882     }
883   }
884   assert(Index == StrTab.size());
885   StrTab.Size = Index;
886 }
887
888 // SortSymbols - On the symbol table local symbols must come before
889 // all other symbols with non-local bindings. The return value is
890 // the position of the first non local symbol.
891 unsigned ELFWriter::SortSymbols() {
892   unsigned FirstNonLocalSymbol;
893   std::vector<ELFSym*> LocalSyms, OtherSyms;
894
895   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
896     if ((*I)->isLocalBind())
897       LocalSyms.push_back(*I);
898     else
899       OtherSyms.push_back(*I);
900   }
901   SymbolList.clear();
902   FirstNonLocalSymbol = LocalSyms.size();
903
904   for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
905     SymbolList.push_back(LocalSyms[i]);
906
907   for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
908     SymbolList.push_back(*I);
909
910   LocalSyms.clear();
911   OtherSyms.clear();
912
913   return FirstNonLocalSymbol;
914 }
915
916 /// EmitSymbolTable - Emit the symbol table itself.
917 void ELFWriter::EmitSymbolTable() {
918   if (!SymbolList.size()) return;  // Empty symbol table.
919
920   // Now that we have emitted the string table and know the offset into the
921   // string table of each symbol, emit the symbol table itself.
922   ELFSection &SymTab = getSymbolTableSection();
923   SymTab.Align = TEW->getPrefELFAlignment();
924
925   // Section Index of .strtab.
926   SymTab.Link = getStringTableSection().SectionIdx;
927
928   // Size of each symtab entry.
929   SymTab.EntSize = TEW->getSymTabEntrySize();
930
931   // Reorder the symbol table with local symbols first!
932   unsigned FirstNonLocalSymbol = SortSymbols();
933
934   // Emit all the symbols to the symbol table.
935   for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
936     ELFSym &Sym = *SymbolList[i];
937
938     // Emit symbol to the symbol table
939     EmitSymbol(SymTab, Sym);
940
941     // Record the symbol table index for each symbol
942     if (Sym.isGlobalValue())
943       GblSymLookup[Sym.getGlobalValue()] = i;
944     else if (Sym.isExternalSym())
945       ExtSymLookup[Sym.getExternalSymbol()] = i;
946
947     // Keep track on the symbol index into the symbol table
948     Sym.SymTabIdx = i;
949   }
950
951   // One greater than the symbol table index of the last local symbol
952   SymTab.Info = FirstNonLocalSymbol;
953   SymTab.Size = SymTab.size();
954 }
955
956 /// EmitSectionTableStringTable - This method adds and emits a section for the
957 /// ELF Section Table string table: the string table that holds all of the
958 /// section names.
959 void ELFWriter::EmitSectionTableStringTable() {
960   // First step: add the section for the string table to the list of sections:
961   ELFSection &SHStrTab = getSectionHeaderStringTableSection();
962
963   // Now that we know which section number is the .shstrtab section, update the
964   // e_shstrndx entry in the ELF header.
965   ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
966
967   // Set the NameIdx of each section in the string table and emit the bytes for
968   // the string table.
969   unsigned Index = 0;
970
971   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
972     ELFSection &S = *(*I);
973     // Set the index into the table.  Note if we have lots of entries with
974     // common suffixes, we could memoize them here if we cared.
975     S.NameIdx = Index;
976     SHStrTab.emitString(S.getName());
977
978     // Keep track of the number of bytes emitted to this section.
979     Index += S.getName().size()+1;
980   }
981
982   // Set the size of .shstrtab now that we know what it is.
983   assert(Index == SHStrTab.size());
984   SHStrTab.Size = Index;
985 }
986
987 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
988 /// and all of the sections, emit these to the ostream destination and emit the
989 /// SectionTable.
990 void ELFWriter::OutputSectionsAndSectionTable() {
991   // Pass #1: Compute the file offset for each section.
992   size_t FileOff = ElfHdr.size();   // File header first.
993
994   // Adjust alignment of all section if needed, skip the null section.
995   for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
996     ELFSection &ES = *SectionList[i];
997     if (!ES.size()) {
998       ES.Offset = FileOff;
999       continue;
1000     }
1001
1002     // Update Section size
1003     if (!ES.Size)
1004       ES.Size = ES.size();
1005
1006     // Align FileOff to whatever the alignment restrictions of the section are.
1007     if (ES.Align)
1008       FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
1009
1010     ES.Offset = FileOff;
1011     FileOff += ES.Size;
1012   }
1013
1014   // Align Section Header.
1015   unsigned TableAlign = TEW->getPrefELFAlignment();
1016   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1017
1018   // Now that we know where all of the sections will be emitted, set the e_shnum
1019   // entry in the ELF header.
1020   ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
1021
1022   // Now that we know the offset in the file of the section table, update the
1023   // e_shoff address in the ELF header.
1024   ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
1025
1026   // Now that we know all of the data in the file header, emit it and all of the
1027   // sections!
1028   O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
1029   FileOff = ElfHdr.size();
1030
1031   // Section Header Table blob
1032   BinaryObject SHdrTable(isLittleEndian, is64Bit);
1033
1034   // Emit all of sections to the file and build the section header table.
1035   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1036     ELFSection &S = *(*I);
1037     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
1038          << ", Size: " << S.Size << ", Offset: " << S.Offset
1039          << ", SectionData Size: " << S.size() << "\n";
1040
1041     // Align FileOff to whatever the alignment restrictions of the section are.
1042     if (S.size()) {
1043       if (S.Align)  {
1044         for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
1045              FileOff != NewFileOff; ++FileOff)
1046           O << (char)0xAB;
1047       }
1048       O.write((char *)&S.getData()[0], S.Size);
1049       FileOff += S.Size;
1050     }
1051
1052     EmitSectionHeader(SHdrTable, S);
1053   }
1054
1055   // Align output for the section table.
1056   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1057        FileOff != NewFileOff; ++FileOff)
1058     O << (char)0xAB;
1059
1060   // Emit the section table itself.
1061   O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
1062 }