Make EmitIntValue more efficient and more like what we do for leb128. The
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
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 ELF object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
31
32 #include "../Target/X86/X86FixupKinds.h"
33 #include "../Target/ARM/ARMFixupKinds.h"
34
35 #include <vector>
36 using namespace llvm;
37
38 static unsigned GetType(const MCSymbolData &SD) {
39   uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43          Type == ELF::STT_TLS);
44   return Type;
45 }
46
47 static unsigned GetBinding(const MCSymbolData &SD) {
48   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50          Binding == ELF::STB_WEAK);
51   return Binding;
52 }
53
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56          Binding == ELF::STB_WEAK);
57   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59 }
60
61 static unsigned GetVisibility(MCSymbolData &SD) {
62   unsigned Visibility =
63     (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66   return Visibility;
67 }
68
69
70 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
71   switch (Variant) {
72   default:
73     return false;
74   case MCSymbolRefExpr::VK_GOT:
75   case MCSymbolRefExpr::VK_PLT:
76   case MCSymbolRefExpr::VK_GOTPCREL:
77   case MCSymbolRefExpr::VK_TPOFF:
78   case MCSymbolRefExpr::VK_TLSGD:
79   case MCSymbolRefExpr::VK_GOTTPOFF:
80   case MCSymbolRefExpr::VK_INDNTPOFF:
81   case MCSymbolRefExpr::VK_NTPOFF:
82   case MCSymbolRefExpr::VK_GOTNTPOFF:
83   case MCSymbolRefExpr::VK_TLSLDM:
84   case MCSymbolRefExpr::VK_DTPOFF:
85   case MCSymbolRefExpr::VK_TLSLD:
86     return true;
87   }
88 }
89
90 namespace {
91   class ELFObjectWriter : public MCObjectWriter {
92   protected:
93     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
94       return Kind == X86::reloc_riprel_4byte ||
95         Kind == X86::reloc_riprel_4byte_movq_load;
96     }*/
97
98
99     /// ELFSymbolData - Helper struct for containing some precomputed information
100     /// on symbols.
101     struct ELFSymbolData {
102       MCSymbolData *SymbolData;
103       uint64_t StringIndex;
104       uint32_t SectionIndex;
105
106       // Support lexicographic sorting.
107       bool operator<(const ELFSymbolData &RHS) const {
108         if (GetType(*SymbolData) == ELF::STT_FILE)
109           return true;
110         if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
111           return false;
112         return SymbolData->getSymbol().getName() <
113                RHS.SymbolData->getSymbol().getName();
114       }
115     };
116
117     /// @name Relocation Data
118     /// @{
119
120     struct ELFRelocationEntry {
121       // Make these big enough for both 32-bit and 64-bit
122       uint64_t r_offset;
123       int Index;
124       unsigned Type;
125       const MCSymbol *Symbol;
126       uint64_t r_addend;
127
128       ELFRelocationEntry()
129         : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
130
131       ELFRelocationEntry(uint64_t RelocOffset, int Idx,
132                          unsigned RelType, const MCSymbol *Sym,
133                          uint64_t Addend)
134         : r_offset(RelocOffset), Index(Idx), Type(RelType),
135           Symbol(Sym), r_addend(Addend) {}
136
137       // Support lexicographic sorting.
138       bool operator<(const ELFRelocationEntry &RE) const {
139         return RE.r_offset < r_offset;
140       }
141     };
142
143     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
144     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
145     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
146
147     llvm::DenseMap<const MCSectionData*,
148                    std::vector<ELFRelocationEntry> > Relocations;
149     DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
150
151     /// @}
152     /// @name Symbol Table Data
153     /// @{
154
155     SmallString<256> StringTable;
156     std::vector<ELFSymbolData> LocalSymbolData;
157     std::vector<ELFSymbolData> ExternalSymbolData;
158     std::vector<ELFSymbolData> UndefinedSymbolData;
159
160     /// @}
161
162     bool NeedsGOT;
163
164     bool NeedsSymtabShndx;
165
166     unsigned Is64Bit : 1;
167
168     bool HasRelocationAddend;
169
170     Triple::OSType OSType;
171
172     uint16_t EMachine;
173
174     // This holds the symbol table index of the last local symbol.
175     unsigned LastLocalSymbolIndex;
176     // This holds the .strtab section index.
177     unsigned StringTableIndex;
178     // This holds the .symtab section index.
179     unsigned SymbolTableIndex;
180
181     unsigned ShstrtabIndex;
182
183
184     const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
185                                   const MCValue &Target,
186                                   const MCFragment &F) const;
187
188   public:
189     ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
190                     uint16_t _EMachine, bool _HasRelAddend,
191                     Triple::OSType _OSType)
192       : MCObjectWriter(_OS, IsLittleEndian),
193         NeedsGOT(false), NeedsSymtabShndx(false),
194         Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
195         OSType(_OSType), EMachine(_EMachine) {
196     }
197
198     virtual ~ELFObjectWriter();
199
200     void WriteWord(uint64_t W) {
201       if (Is64Bit)
202         Write64(W);
203       else
204         Write32(W);
205     }
206
207     void StringLE16(char *buf, uint16_t Value) {
208       buf[0] = char(Value >> 0);
209       buf[1] = char(Value >> 8);
210     }
211
212     void StringLE32(char *buf, uint32_t Value) {
213       StringLE16(buf, uint16_t(Value >> 0));
214       StringLE16(buf + 2, uint16_t(Value >> 16));
215     }
216
217     void StringLE64(char *buf, uint64_t Value) {
218       StringLE32(buf, uint32_t(Value >> 0));
219       StringLE32(buf + 4, uint32_t(Value >> 32));
220     }
221
222     void StringBE16(char *buf ,uint16_t Value) {
223       buf[0] = char(Value >> 8);
224       buf[1] = char(Value >> 0);
225     }
226
227     void StringBE32(char *buf, uint32_t Value) {
228       StringBE16(buf, uint16_t(Value >> 16));
229       StringBE16(buf + 2, uint16_t(Value >> 0));
230     }
231
232     void StringBE64(char *buf, uint64_t Value) {
233       StringBE32(buf, uint32_t(Value >> 32));
234       StringBE32(buf + 4, uint32_t(Value >> 0));
235     }
236
237     void String8(MCDataFragment &F, uint8_t Value) {
238       char buf[1];
239       buf[0] = Value;
240       F.getContents() += StringRef(buf, 1);
241     }
242
243     void String16(MCDataFragment &F, uint16_t Value) {
244       char buf[2];
245       if (isLittleEndian())
246         StringLE16(buf, Value);
247       else
248         StringBE16(buf, Value);
249       F.getContents() += StringRef(buf, 2);
250     }
251
252     void String32(MCDataFragment &F, uint32_t Value) {
253       char buf[4];
254       if (isLittleEndian())
255         StringLE32(buf, Value);
256       else
257         StringBE32(buf, Value);
258       F.getContents() += StringRef(buf, 4);
259     }
260
261     void String64(MCDataFragment &F, uint64_t Value) {
262       char buf[8];
263       if (isLittleEndian())
264         StringLE64(buf, Value);
265       else
266         StringBE64(buf, Value);
267       F.getContents() += StringRef(buf, 8);
268     }
269
270     virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
271
272     virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
273                           uint64_t name, uint8_t info,
274                           uint64_t value, uint64_t size,
275                           uint8_t other, uint32_t shndx,
276                           bool Reserved);
277
278     virtual void WriteSymbol(MCDataFragment *SymtabF,  MCDataFragment *ShndxF,
279                      ELFSymbolData &MSD,
280                      const MCAsmLayout &Layout);
281
282     typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
283     virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
284                           const MCAssembler &Asm,
285                           const MCAsmLayout &Layout,
286                           const SectionIndexMapTy &SectionIndexMap);
287
288     virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
289                           const MCFragment *Fragment, const MCFixup &Fixup,
290                                   MCValue Target, uint64_t &FixedValue) {
291       assert(0 && "RecordRelocation is not specific enough");
292     }
293
294     virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
295                                          const MCSymbol *S);
296
297     // Map from a group section to the signature symbol
298     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
299     // Map from a signature symbol to the group section
300     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
301
302     /// ComputeSymbolTable - Compute the symbol table data
303     ///
304     /// \param StringTable [out] - The string table data.
305     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
306     /// string table.
307     virtual void ComputeSymbolTable(MCAssembler &Asm,
308                             const SectionIndexMapTy &SectionIndexMap,
309                             RevGroupMapTy RevGroupMap);
310
311     virtual void ComputeIndexMap(MCAssembler &Asm,
312                          SectionIndexMapTy &SectionIndexMap);
313
314     virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
315                          const MCSectionData &SD);
316
317     virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
318       for (MCAssembler::const_iterator it = Asm.begin(),
319              ie = Asm.end(); it != ie; ++it) {
320         WriteRelocation(Asm, Layout, *it);
321       }
322     }
323
324     virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
325                                 const SectionIndexMapTy &SectionIndexMap);
326
327     virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
328                              GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
329
330     virtual void ExecutePostLayoutBinding(MCAssembler &Asm);
331
332     virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
333                           uint64_t Address, uint64_t Offset,
334                           uint64_t Size, uint32_t Link, uint32_t Info,
335                           uint64_t Alignment, uint64_t EntrySize);
336
337     virtual void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
338                                   const MCSectionData *SD);
339
340     virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
341                               const MCValue Target,
342                               bool IsPCRel,
343                               const MCFragment *DF) const;
344
345     virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
346     virtual void WriteSection(MCAssembler &Asm,
347                       const SectionIndexMapTy &SectionIndexMap,
348                       uint32_t GroupSymbolIndex,
349                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
350                       const MCSectionELF &Section);
351   };
352
353   //===- X86ELFObjectWriter -------------------------------------------===//
354
355   class X86ELFObjectWriter : public ELFObjectWriter {
356   public:
357     X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
358                        uint16_t _EMachine, bool _HasRelAddend,
359                        Triple::OSType _OSType);
360
361     virtual ~X86ELFObjectWriter();
362     virtual void RecordRelocation(const MCAssembler &Asm,
363                                   const MCAsmLayout &Layout,
364                                   const MCFragment *Fragment,
365                                   const MCFixup &Fixup, MCValue Target,
366                                   uint64_t &FixedValue);
367
368   private:
369     static bool isFixupKindPCRel(unsigned Kind) {
370       switch (Kind) {
371       default:
372         return false;
373       case FK_PCRel_1:
374       case FK_PCRel_2:
375       case FK_PCRel_4:
376       case X86::reloc_riprel_4byte:
377       case X86::reloc_riprel_4byte_movq_load:
378         return true;
379       }
380     }
381   };
382
383
384   //===- ARMELFObjectWriter -------------------------------------------===//
385
386   class ARMELFObjectWriter : public ELFObjectWriter {
387   public:
388     ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
389                        uint16_t _EMachine, bool _HasRelAddend,
390                        Triple::OSType _OSType);
391
392     virtual ~ARMELFObjectWriter();
393     virtual void RecordRelocation(const MCAssembler &Asm,
394                                   const MCAsmLayout &Layout,
395                                   const MCFragment *Fragment,
396                                   const MCFixup &Fixup, MCValue Target,
397                                   uint64_t &FixedValue);
398
399   protected:
400     // Fixme: pull up to ELFObjectWriter
401     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
402                           bool IsPCRel);
403   private:
404     static bool isFixupKindPCRel(unsigned Kind) {
405       switch (Kind) {
406       default:
407         return false;
408       case FK_PCRel_1:
409       case FK_PCRel_2:
410       case FK_PCRel_4:
411       case ARM::fixup_arm_ldst_pcrel_12:
412       case ARM::fixup_arm_pcrel_10:
413       case ARM::fixup_arm_branch:
414         return true;
415       }
416     }
417   };
418
419   //===- MBlazeELFObjectWriter -------------------------------------------===//
420
421   class MBlazeELFObjectWriter : public ELFObjectWriter {
422   public:
423     MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
424                           uint16_t _EMachine, bool _HasRelAddend,
425                           Triple::OSType _OSType);
426
427     virtual ~MBlazeELFObjectWriter();
428     virtual void RecordRelocation(const MCAssembler &Asm,
429                                   const MCAsmLayout &Layout,
430                                   const MCFragment *Fragment,
431                                   const MCFixup &Fixup, MCValue Target,
432                                   uint64_t &FixedValue);
433
434   private:
435     static bool isFixupKindPCRel(unsigned Kind) {
436       switch (Kind) {
437       default:
438         return false;
439       case FK_PCRel_1:
440       case FK_PCRel_2:
441       case FK_PCRel_4:
442         return true;
443       }
444     }
445   };
446 }
447
448 ELFObjectWriter::~ELFObjectWriter()
449 {}
450
451 // Emit the ELF header.
452 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
453                                   unsigned NumberOfSections) {
454   // ELF Header
455   // ----------
456   //
457   // Note
458   // ----
459   // emitWord method behaves differently for ELF32 and ELF64, writing
460   // 4 bytes in the former and 8 in the latter.
461
462   Write8(0x7f); // e_ident[EI_MAG0]
463   Write8('E');  // e_ident[EI_MAG1]
464   Write8('L');  // e_ident[EI_MAG2]
465   Write8('F');  // e_ident[EI_MAG3]
466
467   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
468
469   // e_ident[EI_DATA]
470   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
471
472   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
473   // e_ident[EI_OSABI]
474   switch (OSType) {
475     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
476     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
477     default:               Write8(ELF::ELFOSABI_NONE); break;
478   }
479   Write8(0);                  // e_ident[EI_ABIVERSION]
480
481   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
482
483   Write16(ELF::ET_REL);             // e_type
484
485   Write16(EMachine); // e_machine = target
486
487   Write32(ELF::EV_CURRENT);         // e_version
488   WriteWord(0);                    // e_entry, no entry point in .o file
489   WriteWord(0);                    // e_phoff, no program header for .o
490   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
491             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
492
493   // FIXME: Make this configurable.
494   Write32(0);   // e_flags = whatever the target wants
495
496   // e_ehsize = ELF header size
497   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
498
499   Write16(0);                  // e_phentsize = prog header entry size
500   Write16(0);                  // e_phnum = # prog header entries = 0
501
502   // e_shentsize = Section header entry size
503   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
504
505   // e_shnum     = # of section header ents
506   if (NumberOfSections >= ELF::SHN_LORESERVE)
507     Write16(0);
508   else
509     Write16(NumberOfSections);
510
511   // e_shstrndx  = Section # of '.shstrtab'
512   if (NumberOfSections >= ELF::SHN_LORESERVE)
513     Write16(ELF::SHN_XINDEX);
514   else
515     Write16(ShstrtabIndex);
516 }
517
518 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
519                                        MCDataFragment *ShndxF,
520                                        uint64_t name,
521                                        uint8_t info, uint64_t value,
522                                        uint64_t size, uint8_t other,
523                                        uint32_t shndx,
524                                        bool Reserved) {
525   if (ShndxF) {
526     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
527       String32(*ShndxF, shndx);
528     else
529       String32(*ShndxF, 0);
530   }
531
532   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
533     uint16_t(ELF::SHN_XINDEX) : shndx;
534
535   if (Is64Bit) {
536     String32(*SymtabF, name);  // st_name
537     String8(*SymtabF, info);   // st_info
538     String8(*SymtabF, other);  // st_other
539     String16(*SymtabF, Index); // st_shndx
540     String64(*SymtabF, value); // st_value
541     String64(*SymtabF, size);  // st_size
542   } else {
543     String32(*SymtabF, name);  // st_name
544     String32(*SymtabF, value); // st_value
545     String32(*SymtabF, size);  // st_size
546     String8(*SymtabF, info);   // st_info
547     String8(*SymtabF, other);  // st_other
548     String16(*SymtabF, Index); // st_shndx
549   }
550 }
551
552 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
553   if (Data.isCommon() && Data.isExternal())
554     return Data.getCommonAlignment();
555
556   const MCSymbol &Symbol = Data.getSymbol();
557   if (!Symbol.isInSection())
558     return 0;
559
560   if (MCFragment *FF = Data.getFragment())
561     return Layout.getSymbolAddress(&Data) -
562       Layout.getSectionAddress(FF->getParent());
563
564   return 0;
565 }
566
567 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
568   // The presence of symbol versions causes undefined symbols and
569   // versions declared with @@@ to be renamed.
570
571   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
572          ie = Asm.symbol_end(); it != ie; ++it) {
573     const MCSymbol &Alias = it->getSymbol();
574     const MCSymbol &Symbol = Alias.AliasedSymbol();
575     MCSymbolData &SD = Asm.getSymbolData(Symbol);
576
577     // Not an alias.
578     if (&Symbol == &Alias)
579       continue;
580
581     StringRef AliasName = Alias.getName();
582     size_t Pos = AliasName.find('@');
583     if (Pos == StringRef::npos)
584       continue;
585
586     // Aliases defined with .symvar copy the binding from the symbol they alias.
587     // This is the first place we are able to copy this information.
588     it->setExternal(SD.isExternal());
589     SetBinding(*it, GetBinding(SD));
590
591     StringRef Rest = AliasName.substr(Pos);
592     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
593       continue;
594
595     // FIXME: produce a better error message.
596     if (Symbol.isUndefined() && Rest.startswith("@@") &&
597         !Rest.startswith("@@@"))
598       report_fatal_error("A @@ version cannot be undefined");
599
600     Renames.insert(std::make_pair(&Symbol, &Alias));
601   }
602 }
603
604 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
605                                   MCDataFragment *ShndxF,
606                                   ELFSymbolData &MSD,
607                                   const MCAsmLayout &Layout) {
608   MCSymbolData &OrigData = *MSD.SymbolData;
609   MCSymbolData &Data =
610     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
611
612   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
613     Data.getSymbol().isVariable();
614
615   uint8_t Binding = GetBinding(OrigData);
616   uint8_t Visibility = GetVisibility(OrigData);
617   uint8_t Type = GetType(Data);
618
619   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
620   uint8_t Other = Visibility;
621
622   uint64_t Value = SymbolValue(Data, Layout);
623   uint64_t Size = 0;
624   const MCExpr *ESize;
625
626   assert(!(Data.isCommon() && !Data.isExternal()));
627
628   ESize = Data.getSize();
629   if (Data.getSize()) {
630     MCValue Res;
631     if (ESize->getKind() == MCExpr::Binary) {
632       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
633
634       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
635         assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
636         assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
637         Size = Res.getConstant();
638       }
639     } else if (ESize->getKind() == MCExpr::Constant) {
640       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
641     } else {
642       assert(0 && "Unsupported size expression");
643     }
644   }
645
646   // Write out the symbol table entry
647   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
648                    Size, Other, MSD.SectionIndex, IsReserved);
649 }
650
651 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
652                                        MCDataFragment *ShndxF,
653                                        const MCAssembler &Asm,
654                                        const MCAsmLayout &Layout,
655                                      const SectionIndexMapTy &SectionIndexMap) {
656   // The string table must be emitted first because we need the index
657   // into the string table for all the symbol names.
658   assert(StringTable.size() && "Missing string table");
659
660   // FIXME: Make sure the start of the symbol table is aligned.
661
662   // The first entry is the undefined symbol entry.
663   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
664
665   // Write the symbol table entries.
666   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
667   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
668     ELFSymbolData &MSD = LocalSymbolData[i];
669     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
670   }
671
672   // Write out a symbol table entry for each regular section.
673   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
674        ++i) {
675     const MCSectionELF &Section =
676       static_cast<const MCSectionELF&>(i->getSection());
677     if (Section.getType() == ELF::SHT_RELA ||
678         Section.getType() == ELF::SHT_REL ||
679         Section.getType() == ELF::SHT_STRTAB ||
680         Section.getType() == ELF::SHT_SYMTAB)
681       continue;
682     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
683                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
684     LastLocalSymbolIndex++;
685   }
686
687   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
688     ELFSymbolData &MSD = ExternalSymbolData[i];
689     MCSymbolData &Data = *MSD.SymbolData;
690     assert(((Data.getFlags() & ELF_STB_Global) ||
691             (Data.getFlags() & ELF_STB_Weak)) &&
692            "External symbol requires STB_GLOBAL or STB_WEAK flag");
693     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
694     if (GetBinding(Data) == ELF::STB_LOCAL)
695       LastLocalSymbolIndex++;
696   }
697
698   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
699     ELFSymbolData &MSD = UndefinedSymbolData[i];
700     MCSymbolData &Data = *MSD.SymbolData;
701     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
702     if (GetBinding(Data) == ELF::STB_LOCAL)
703       LastLocalSymbolIndex++;
704   }
705 }
706
707 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
708                                                const MCValue &Target,
709                                                const MCFragment &F) const {
710   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
711   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
712   const MCSymbol *Renamed = Renames.lookup(&Symbol);
713   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
714
715   if (ASymbol.isUndefined()) {
716     if (Renamed)
717       return Renamed;
718     return &ASymbol;
719   }
720
721   if (SD.isExternal()) {
722     if (Renamed)
723       return Renamed;
724     return &Symbol;
725   }
726
727   const MCSectionELF &Section =
728     static_cast<const MCSectionELF&>(ASymbol.getSection());
729   const SectionKind secKind = Section.getKind();
730
731   if (secKind.isBSS())
732     return NULL;
733
734   if (secKind.isThreadLocal()) {
735     if (Renamed)
736       return Renamed;
737     return &Symbol;
738   }
739
740   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
741   const MCSectionELF &Sec2 =
742     static_cast<const MCSectionELF&>(F.getParent()->getSection());
743
744   if (&Sec2 != &Section &&
745       (Kind == MCSymbolRefExpr::VK_PLT ||
746        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
747        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
748     if (Renamed)
749       return Renamed;
750     return &Symbol;
751   }
752
753   if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
754     if (Target.getConstant() == 0)
755       return NULL;
756     if (Renamed)
757       return Renamed;
758     return &Symbol;
759   }
760
761   return NULL;
762 }
763
764
765 uint64_t
766 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
767                                              const MCSymbol *S) {
768   MCSymbolData &SD = Asm.getSymbolData(*S);
769   return SD.getIndex();
770 }
771
772 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
773                        bool Used, bool Renamed) {
774   if (Data.getFlags() & ELF_Other_Weakref)
775     return false;
776
777   if (Used)
778     return true;
779
780   if (Renamed)
781     return false;
782
783   const MCSymbol &Symbol = Data.getSymbol();
784
785   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
786     return true;
787
788   const MCSymbol &A = Symbol.AliasedSymbol();
789   if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
790     return false;
791
792   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
793     return false;
794
795   if (Symbol.isTemporary())
796     return false;
797
798   return true;
799 }
800
801 static bool isLocal(const MCSymbolData &Data, bool isSignature,
802                     bool isUsedInReloc) {
803   if (Data.isExternal())
804     return false;
805
806   const MCSymbol &Symbol = Data.getSymbol();
807   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
808
809   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
810     if (isSignature && !isUsedInReloc)
811       return true;
812
813     return false;
814   }
815
816   return true;
817 }
818
819 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
820                                       SectionIndexMapTy &SectionIndexMap) {
821   unsigned Index = 1;
822   for (MCAssembler::iterator it = Asm.begin(),
823          ie = Asm.end(); it != ie; ++it) {
824     const MCSectionELF &Section =
825       static_cast<const MCSectionELF &>(it->getSection());
826     if (Section.getType() != ELF::SHT_GROUP)
827       continue;
828     SectionIndexMap[&Section] = Index++;
829   }
830
831   for (MCAssembler::iterator it = Asm.begin(),
832          ie = Asm.end(); it != ie; ++it) {
833     const MCSectionELF &Section =
834       static_cast<const MCSectionELF &>(it->getSection());
835     if (Section.getType() == ELF::SHT_GROUP)
836       continue;
837     SectionIndexMap[&Section] = Index++;
838   }
839 }
840
841 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
842                                       const SectionIndexMapTy &SectionIndexMap,
843                                       RevGroupMapTy RevGroupMap) {
844   // FIXME: Is this the correct place to do this?
845   if (NeedsGOT) {
846     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
847     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
848     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
849     Data.setExternal(true);
850     SetBinding(Data, ELF::STB_GLOBAL);
851   }
852
853   // Build section lookup table.
854   int NumRegularSections = Asm.size();
855
856   // Index 0 is always the empty string.
857   StringMap<uint64_t> StringIndexMap;
858   StringTable += '\x00';
859
860   // Add the data for the symbols.
861   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
862          ie = Asm.symbol_end(); it != ie; ++it) {
863     const MCSymbol &Symbol = it->getSymbol();
864
865     bool Used = UsedInReloc.count(&Symbol);
866     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
867     bool isSignature = RevGroupMap.count(&Symbol);
868
869     if (!isInSymtab(Asm, *it,
870                     Used || WeakrefUsed || isSignature,
871                     Renames.count(&Symbol)))
872       continue;
873
874     ELFSymbolData MSD;
875     MSD.SymbolData = it;
876     const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
877
878     // Undefined symbols are global, but this is the first place we
879     // are able to set it.
880     bool Local = isLocal(*it, isSignature, Used);
881     if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
882       MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
883       SetBinding(*it, ELF::STB_GLOBAL);
884       SetBinding(SD, ELF::STB_GLOBAL);
885     }
886
887     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
888       SetBinding(*it, ELF::STB_WEAK);
889
890     if (it->isCommon()) {
891       assert(!Local);
892       MSD.SectionIndex = ELF::SHN_COMMON;
893     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
894       MSD.SectionIndex = ELF::SHN_ABS;
895     } else if (RefSymbol.isUndefined()) {
896       if (isSignature && !Used)
897         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
898       else
899         MSD.SectionIndex = ELF::SHN_UNDEF;
900     } else {
901       const MCSectionELF &Section =
902         static_cast<const MCSectionELF&>(RefSymbol.getSection());
903       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
904       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
905         NeedsSymtabShndx = true;
906       assert(MSD.SectionIndex && "Invalid section index!");
907     }
908
909     // The @@@ in symbol version is replaced with @ in undefined symbols and
910     // @@ in defined ones.
911     StringRef Name = Symbol.getName();
912     SmallString<32> Buf;
913
914     size_t Pos = Name.find("@@@");
915     if (Pos != StringRef::npos) {
916       Buf += Name.substr(0, Pos);
917       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
918       Buf += Name.substr(Pos + Skip);
919       Name = Buf;
920     }
921
922     uint64_t &Entry = StringIndexMap[Name];
923     if (!Entry) {
924       Entry = StringTable.size();
925       StringTable += Name;
926       StringTable += '\x00';
927     }
928     MSD.StringIndex = Entry;
929     if (MSD.SectionIndex == ELF::SHN_UNDEF)
930       UndefinedSymbolData.push_back(MSD);
931     else if (Local)
932       LocalSymbolData.push_back(MSD);
933     else
934       ExternalSymbolData.push_back(MSD);
935   }
936
937   // Symbols are required to be in lexicographic order.
938   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
939   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
940   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
941
942   // Set the symbol indices. Local symbols must come before all other
943   // symbols with non-local bindings.
944   unsigned Index = 1;
945   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
946     LocalSymbolData[i].SymbolData->setIndex(Index++);
947
948   Index += NumRegularSections;
949
950   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
951     ExternalSymbolData[i].SymbolData->setIndex(Index++);
952   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
953     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
954 }
955
956 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
957                                       const MCSectionData &SD) {
958   if (!Relocations[&SD].empty()) {
959     MCContext &Ctx = Asm.getContext();
960     const MCSectionELF *RelaSection;
961     const MCSectionELF &Section =
962       static_cast<const MCSectionELF&>(SD.getSection());
963
964     const StringRef SectionName = Section.getSectionName();
965     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
966     RelaSectionName += SectionName;
967
968     unsigned EntrySize;
969     if (HasRelocationAddend)
970       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
971     else
972       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
973
974     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
975                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
976                                     SectionKind::getReadOnly(),
977                                     EntrySize, "");
978
979     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
980     RelaSD.setAlignment(Is64Bit ? 8 : 4);
981
982     MCDataFragment *F = new MCDataFragment(&RelaSD);
983
984     WriteRelocationsFragment(Asm, F, &SD);
985   }
986 }
987
988 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
989                                        uint64_t Flags, uint64_t Address,
990                                        uint64_t Offset, uint64_t Size,
991                                        uint32_t Link, uint32_t Info,
992                                        uint64_t Alignment,
993                                        uint64_t EntrySize) {
994   Write32(Name);        // sh_name: index into string table
995   Write32(Type);        // sh_type
996   WriteWord(Flags);     // sh_flags
997   WriteWord(Address);   // sh_addr
998   WriteWord(Offset);    // sh_offset
999   WriteWord(Size);      // sh_size
1000   Write32(Link);        // sh_link
1001   Write32(Info);        // sh_info
1002   WriteWord(Alignment); // sh_addralign
1003   WriteWord(EntrySize); // sh_entsize
1004 }
1005
1006 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1007                                                MCDataFragment *F,
1008                                                const MCSectionData *SD) {
1009   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1010   // sort by the r_offset just like gnu as does
1011   array_pod_sort(Relocs.begin(), Relocs.end());
1012
1013   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1014     ELFRelocationEntry entry = Relocs[e - i - 1];
1015
1016     if (!entry.Index)
1017       ;
1018     else if (entry.Index < 0)
1019       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1020     else
1021       entry.Index += LocalSymbolData.size();
1022     if (Is64Bit) {
1023       String64(*F, entry.r_offset);
1024
1025       struct ELF::Elf64_Rela ERE64;
1026       ERE64.setSymbolAndType(entry.Index, entry.Type);
1027       String64(*F, ERE64.r_info);
1028
1029       if (HasRelocationAddend)
1030         String64(*F, entry.r_addend);
1031     } else {
1032       String32(*F, entry.r_offset);
1033
1034       struct ELF::Elf32_Rela ERE32;
1035       ERE32.setSymbolAndType(entry.Index, entry.Type);
1036       String32(*F, ERE32.r_info);
1037
1038       if (HasRelocationAddend)
1039         String32(*F, entry.r_addend);
1040     }
1041   }
1042 }
1043
1044 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1045                                              MCAsmLayout &Layout,
1046                                     const SectionIndexMapTy &SectionIndexMap) {
1047   MCContext &Ctx = Asm.getContext();
1048   MCDataFragment *F;
1049
1050   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1051
1052   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1053   const MCSectionELF *ShstrtabSection =
1054     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1055                       SectionKind::getReadOnly());
1056   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1057   ShstrtabSD.setAlignment(1);
1058   ShstrtabIndex = Asm.size();
1059
1060   const MCSectionELF *SymtabSection =
1061     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1062                       SectionKind::getReadOnly(),
1063                       EntrySize, "");
1064   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1065   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1066   SymbolTableIndex = Asm.size();
1067
1068   MCSectionData *SymtabShndxSD = NULL;
1069
1070   if (NeedsSymtabShndx) {
1071     const MCSectionELF *SymtabShndxSection =
1072       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1073                         SectionKind::getReadOnly(), 4, "");
1074     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1075     SymtabShndxSD->setAlignment(4);
1076   }
1077
1078   const MCSection *StrtabSection;
1079   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1080                                     SectionKind::getReadOnly());
1081   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1082   StrtabSD.setAlignment(1);
1083   StringTableIndex = Asm.size();
1084
1085   WriteRelocations(Asm, Layout);
1086
1087   // Symbol table
1088   F = new MCDataFragment(&SymtabSD);
1089   MCDataFragment *ShndxF = NULL;
1090   if (NeedsSymtabShndx) {
1091     ShndxF = new MCDataFragment(SymtabShndxSD);
1092   }
1093   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1094
1095   F = new MCDataFragment(&StrtabSD);
1096   F->getContents().append(StringTable.begin(), StringTable.end());
1097
1098   F = new MCDataFragment(&ShstrtabSD);
1099
1100   // Section header string table.
1101   //
1102   // The first entry of a string table holds a null character so skip
1103   // section 0.
1104   uint64_t Index = 1;
1105   F->getContents() += '\x00';
1106
1107   StringMap<uint64_t> SecStringMap;
1108   for (MCAssembler::const_iterator it = Asm.begin(),
1109          ie = Asm.end(); it != ie; ++it) {
1110     const MCSectionELF &Section =
1111       static_cast<const MCSectionELF&>(it->getSection());
1112     // FIXME: We could merge suffixes like in .text and .rela.text.
1113
1114     StringRef Name = Section.getSectionName();
1115     if (SecStringMap.count(Name)) {
1116       SectionStringTableIndex[&Section] =  SecStringMap[Name];
1117       continue;
1118     }
1119     // Remember the index into the string table so we can write it
1120     // into the sh_name field of the section header table.
1121     SectionStringTableIndex[&Section] = Index;
1122     SecStringMap[Name] = Index;
1123
1124     Index += Name.size() + 1;
1125     F->getContents() += Name;
1126     F->getContents() += '\x00';
1127   }
1128 }
1129
1130 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1131                                            const MCValue Target,
1132                                            bool IsPCRel,
1133                                            const MCFragment *DF) const {
1134   // If this is a PCrel relocation, find the section this fixup value is
1135   // relative to.
1136   const MCSection *BaseSection = 0;
1137   if (IsPCRel) {
1138     BaseSection = &DF->getParent()->getSection();
1139     assert(BaseSection);
1140   }
1141
1142   const MCSection *SectionA = 0;
1143   const MCSymbol *SymbolA = 0;
1144   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1145     SymbolA = &A->getSymbol();
1146     SectionA = &SymbolA->AliasedSymbol().getSection();
1147   }
1148
1149   const MCSection *SectionB = 0;
1150   const MCSymbol *SymbolB = 0;
1151   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1152     SymbolB = &B->getSymbol();
1153     SectionB = &SymbolB->AliasedSymbol().getSection();
1154   }
1155
1156   if (!BaseSection)
1157     return SectionA == SectionB;
1158
1159   if (SymbolB)
1160     return false;
1161
1162   // Absolute address but PCrel instruction, so we need a relocation.
1163   if (!SymbolA)
1164     return false;
1165
1166   // FIXME: This is in here just to match gnu as output. If the two ends
1167   // are in the same section, there is nothing that the linker can do to
1168   // break it.
1169   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1170   if (DataA.isExternal())
1171     return false;
1172
1173   return BaseSection == SectionA;
1174 }
1175
1176 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1177                                           MCAsmLayout &Layout,
1178                                           GroupMapTy &GroupMap,
1179                                           RevGroupMapTy &RevGroupMap) {
1180   // Build the groups
1181   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1182        it != ie; ++it) {
1183     const MCSectionELF &Section =
1184       static_cast<const MCSectionELF&>(it->getSection());
1185     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1186       continue;
1187
1188     const MCSymbol *SignatureSymbol = Section.getGroup();
1189     Asm.getOrCreateSymbolData(*SignatureSymbol);
1190     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1191     if (!Group) {
1192       Group = Asm.getContext().CreateELFGroupSection();
1193       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1194       Data.setAlignment(4);
1195       MCDataFragment *F = new MCDataFragment(&Data);
1196       String32(*F, ELF::GRP_COMDAT);
1197     }
1198     GroupMap[Group] = SignatureSymbol;
1199   }
1200
1201   // Add sections to the groups
1202   unsigned Index = 1;
1203   unsigned NumGroups = RevGroupMap.size();
1204   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1205        it != ie; ++it, ++Index) {
1206     const MCSectionELF &Section =
1207       static_cast<const MCSectionELF&>(it->getSection());
1208     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1209       continue;
1210     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1211     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1212     // FIXME: we could use the previous fragment
1213     MCDataFragment *F = new MCDataFragment(&Data);
1214     String32(*F, NumGroups + Index);
1215   }
1216 }
1217
1218 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1219                                    const SectionIndexMapTy &SectionIndexMap,
1220                                    uint32_t GroupSymbolIndex,
1221                                    uint64_t Offset, uint64_t Size,
1222                                    uint64_t Alignment,
1223                                    const MCSectionELF &Section) {
1224   uint64_t sh_link = 0;
1225   uint64_t sh_info = 0;
1226
1227   switch(Section.getType()) {
1228   case ELF::SHT_DYNAMIC:
1229     sh_link = SectionStringTableIndex[&Section];
1230     sh_info = 0;
1231     break;
1232
1233   case ELF::SHT_REL:
1234   case ELF::SHT_RELA: {
1235     const MCSectionELF *SymtabSection;
1236     const MCSectionELF *InfoSection;
1237     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1238                                                    0,
1239                                                    SectionKind::getReadOnly());
1240     sh_link = SectionIndexMap.lookup(SymtabSection);
1241     assert(sh_link && ".symtab not found");
1242
1243     // Remove ".rel" and ".rela" prefixes.
1244     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1245     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1246
1247     InfoSection = Asm.getContext().getELFSection(SectionName,
1248                                                  ELF::SHT_PROGBITS, 0,
1249                                                  SectionKind::getReadOnly());
1250     sh_info = SectionIndexMap.lookup(InfoSection);
1251     break;
1252   }
1253
1254   case ELF::SHT_SYMTAB:
1255   case ELF::SHT_DYNSYM:
1256     sh_link = StringTableIndex;
1257     sh_info = LastLocalSymbolIndex;
1258     break;
1259
1260   case ELF::SHT_SYMTAB_SHNDX:
1261     sh_link = SymbolTableIndex;
1262     break;
1263
1264   case ELF::SHT_PROGBITS:
1265   case ELF::SHT_STRTAB:
1266   case ELF::SHT_NOBITS:
1267   case ELF::SHT_NULL:
1268   case ELF::SHT_ARM_ATTRIBUTES:
1269     // Nothing to do.
1270     break;
1271
1272   case ELF::SHT_GROUP: {
1273     sh_link = SymbolTableIndex;
1274     sh_info = GroupSymbolIndex;
1275     break;
1276   }
1277
1278   default:
1279     assert(0 && "FIXME: sh_type value not supported!");
1280     break;
1281   }
1282
1283   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1284                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1285                    Alignment, Section.getEntrySize());
1286 }
1287
1288 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1289   return SD.getAddress() == ~UINT64_C(0) &&
1290     !SD.getSection().isVirtualSection();
1291 }
1292
1293 static uint64_t DataSectionSize(const MCSectionData &SD) {
1294   uint64_t Ret = 0;
1295   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1296        ++i) {
1297     const MCFragment &F = *i;
1298     assert(F.getKind() == MCFragment::FT_Data);
1299     Ret += cast<MCDataFragment>(F).getContents().size();
1300   }
1301   return Ret;
1302 }
1303
1304 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1305                                    const MCSectionData &SD) {
1306   if (IsELFMetaDataSection(SD))
1307     return DataSectionSize(SD);
1308   return Layout.getSectionFileSize(&SD);
1309 }
1310
1311 static uint64_t GetSectionSize(const MCAsmLayout &Layout,
1312                                    const MCSectionData &SD) {
1313   if (IsELFMetaDataSection(SD))
1314     return DataSectionSize(SD);
1315   return Layout.getSectionSize(&SD);
1316 }
1317
1318 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1319   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1320        ++i) {
1321     const MCFragment &F = *i;
1322     assert(F.getKind() == MCFragment::FT_Data);
1323     W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1324   }
1325 }
1326
1327 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1328                                   const MCAsmLayout &Layout) {
1329   GroupMapTy GroupMap;
1330   RevGroupMapTy RevGroupMap;
1331   CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1332                       RevGroupMap);
1333
1334   SectionIndexMapTy SectionIndexMap;
1335
1336   ComputeIndexMap(Asm, SectionIndexMap);
1337
1338   // Compute symbol table information.
1339   ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1340
1341   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1342                          const_cast<MCAsmLayout&>(Layout),
1343                          SectionIndexMap);
1344
1345   // Update to include the metadata sections.
1346   ComputeIndexMap(Asm, SectionIndexMap);
1347
1348   // Add 1 for the null section.
1349   unsigned NumSections = Asm.size() + 1;
1350   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1351   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1352   uint64_t FileOff = HeaderSize;
1353
1354   std::vector<const MCSectionELF*> Sections;
1355   Sections.resize(NumSections);
1356
1357   for (SectionIndexMapTy::const_iterator i=
1358          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1359     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1360     Sections[p.second] = p.first;
1361   }
1362
1363   for (unsigned i = 1; i < NumSections; ++i) {
1364     const MCSectionELF &Section = *Sections[i];
1365     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1366
1367     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1368
1369     // Get the size of the section in the output file (including padding).
1370     FileOff += GetSectionFileSize(Layout, SD);
1371   }
1372
1373   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1374
1375   // Write out the ELF header ...
1376   WriteHeader(FileOff - HeaderSize, NumSections);
1377
1378   FileOff = HeaderSize;
1379
1380   // ... then all of the sections ...
1381   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1382
1383   for (unsigned i = 1; i < NumSections; ++i) {
1384     const MCSectionELF &Section = *Sections[i];
1385     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1386
1387     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1388     WriteZeros(Padding);
1389     FileOff += Padding;
1390
1391     // Remember the offset into the file for this section.
1392     SectionOffsetMap[&Section] = FileOff;
1393
1394     FileOff += GetSectionFileSize(Layout, SD);
1395
1396     if (IsELFMetaDataSection(SD))
1397       WriteDataSectionData(this, SD);
1398     else
1399       Asm.WriteSectionData(&SD, Layout, this);
1400   }
1401
1402   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1403   WriteZeros(Padding);
1404   FileOff += Padding;
1405
1406   // ... and then the section header table.
1407   // Should we align the section header table?
1408   //
1409   // Null section first.
1410   uint64_t FirstSectionSize =
1411     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1412   uint32_t FirstSectionLink =
1413     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1414   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1415
1416   for (unsigned i = 1; i < NumSections; ++i) {
1417     const MCSectionELF &Section = *Sections[i];
1418     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1419     uint32_t GroupSymbolIndex;
1420     if (Section.getType() != ELF::SHT_GROUP)
1421       GroupSymbolIndex = 0;
1422     else
1423       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1424
1425     uint64_t Size = GetSectionSize(Layout, SD);
1426
1427     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1428                  SectionOffsetMap[&Section], Size,
1429                  SD.getAlignment(), Section);
1430   }
1431 }
1432
1433 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1434                                             bool Is64Bit,
1435                                             Triple::OSType OSType,
1436                                             uint16_t EMachine,
1437                                             bool IsLittleEndian,
1438                                             bool HasRelocationAddend) {
1439   switch (EMachine) {
1440     case ELF::EM_386:
1441     case ELF::EM_X86_64:
1442       return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1443                                     HasRelocationAddend, OSType); break;
1444     case ELF::EM_ARM:
1445       return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1446                                     HasRelocationAddend, OSType); break;
1447     case ELF::EM_MBLAZE:
1448       return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1449                                        HasRelocationAddend, OSType); break;
1450     default: llvm_unreachable("Unsupported architecture"); break;
1451   }
1452 }
1453
1454
1455 /// START OF SUBCLASSES for ELFObjectWriter
1456 //===- ARMELFObjectWriter -------------------------------------------===//
1457
1458 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1459                                        bool _IsLittleEndian,
1460                                        uint16_t _EMachine, bool _HasRelocationAddend,
1461                                        Triple::OSType _OSType)
1462   : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1463                     _HasRelocationAddend, _OSType)
1464 {}
1465
1466 ARMELFObjectWriter::~ARMELFObjectWriter()
1467 {}
1468
1469 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1470                                           const MCFixup &Fixup,
1471                                           bool IsPCRel) {
1472   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1473     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1474
1475   if (IsPCRel) {
1476     switch (Modifier) {
1477     default: assert(0 && "Unimplemented Modifier");
1478     case MCSymbolRefExpr::VK_None: break;
1479     }
1480     switch ((unsigned)Fixup.getKind()) {
1481     default: assert(0 && "Unimplemented");
1482     case ARM::fixup_arm_branch: return ELF::R_ARM_CALL; break;
1483     }
1484   } else {
1485     switch ((unsigned)Fixup.getKind()) {
1486     default: llvm_unreachable("invalid fixup kind!");
1487     case ARM::fixup_arm_ldst_pcrel_12:
1488     case ARM::fixup_arm_pcrel_10:
1489     case ARM::fixup_arm_adr_pcrel_12:
1490       assert(0 && "Unimplemented"); break;
1491     case ARM::fixup_arm_branch:
1492       return ELF::R_ARM_CALL; break;
1493     case ARM::fixup_arm_movt_hi16: 
1494       return ELF::R_ARM_MOVT_ABS; break;
1495     case ARM::fixup_arm_movw_lo16:
1496       return ELF::R_ARM_MOVW_ABS_NC; break;
1497     }
1498   }
1499
1500   if (RelocNeedsGOT(Modifier))
1501     NeedsGOT = true;
1502   return -1;
1503 }
1504
1505 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1506                                           const MCAsmLayout &Layout,
1507                                           const MCFragment *Fragment,
1508                                           const MCFixup &Fixup,
1509                                           MCValue Target,
1510                                           uint64_t &FixedValue) {
1511   int64_t Addend = 0;
1512   int Index = 0;
1513   int64_t Value = Target.getConstant();
1514   const MCSymbol *RelocSymbol = NULL;
1515
1516   bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1517   if (!Target.isAbsolute()) {
1518     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1519     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1520     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1521
1522     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1523       const MCSymbol &SymbolB = RefB->getSymbol();
1524       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1525       IsPCRel = true;
1526       MCSectionData *Sec = Fragment->getParent();
1527
1528       // Offset of the symbol in the section
1529       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1530
1531       // Ofeset of the relocation in the section
1532       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1533       Value += b - a;
1534     }
1535
1536     if (!RelocSymbol) {
1537       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1538       MCFragment *F = SD.getFragment();
1539
1540       Index = F->getParent()->getOrdinal() + 1;
1541
1542       MCSectionData *FSD = F->getParent();
1543       // Offset of the symbol in the section
1544       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1545     } else {
1546       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1547         WeakrefUsedInReloc.insert(RelocSymbol);
1548       else
1549         UsedInReloc.insert(RelocSymbol);
1550       Index = -1;
1551     }
1552     Addend = Value;
1553     // Compensate for the addend on i386.
1554     if (Is64Bit)
1555       Value = 0;
1556   }
1557
1558   FixedValue = Value;
1559
1560   // determine the type of the relocation
1561   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
1562
1563   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1564     Fixup.getOffset();
1565
1566   if (!HasRelocationAddend) Addend = 0;
1567   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1568   Relocations[Fragment->getParent()].push_back(ERE);
1569 }
1570
1571 //===- MBlazeELFObjectWriter -------------------------------------------===//
1572
1573 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1574                                              bool _IsLittleEndian,
1575                                              uint16_t _EMachine,
1576                                              bool _HasRelocationAddend,
1577                                              Triple::OSType _OSType)
1578   : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1579                     _HasRelocationAddend, _OSType) {
1580 }
1581
1582 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1583 }
1584
1585 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1586                                              const MCAsmLayout &Layout,
1587                                              const MCFragment *Fragment,
1588                                              const MCFixup &Fixup,
1589                                              MCValue Target,
1590                                              uint64_t &FixedValue) {
1591   int64_t Addend = 0;
1592   int Index = 0;
1593   int64_t Value = Target.getConstant();
1594   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1595   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1596   const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1597
1598   bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1599   if (!Target.isAbsolute()) {
1600     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1601       const MCSymbol &SymbolB = RefB->getSymbol();
1602       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1603       IsPCRel = true;
1604       MCSectionData *Sec = Fragment->getParent();
1605
1606       // Offset of the symbol in the section
1607       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1608
1609       // Ofeset of the relocation in the section
1610       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1611       Value += b - a;
1612     }
1613
1614     if (!RelocSymbol) {
1615       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1616       MCFragment *F = SD.getFragment();
1617
1618       Index = F->getParent()->getOrdinal();
1619
1620       MCSectionData *FSD = F->getParent();
1621       // Offset of the symbol in the section
1622       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1623     } else {
1624       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1625         WeakrefUsedInReloc.insert(RelocSymbol);
1626       else
1627         UsedInReloc.insert(RelocSymbol);
1628       Index = -1;
1629     }
1630     Addend = Value;
1631   }
1632
1633   FixedValue = Value;
1634
1635   // determine the type of the relocation
1636   unsigned Type;
1637   if (IsPCRel) {
1638     switch ((unsigned)Fixup.getKind()) {
1639     default:
1640       llvm_unreachable("Unimplemented");
1641     case FK_PCRel_4:
1642       Type = ELF::R_MICROBLAZE_64_PCREL;
1643       break;
1644     case FK_PCRel_2:
1645       Type = ELF::R_MICROBLAZE_32_PCREL;
1646       break;
1647     }
1648   } else {
1649     switch ((unsigned)Fixup.getKind()) {
1650     default: llvm_unreachable("invalid fixup kind!");
1651     case FK_Data_4:
1652       Type = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1653                                          : ELF::R_MICROBLAZE_64;
1654       break;
1655     case FK_Data_2:
1656       Type = ELF::R_MICROBLAZE_32;
1657       break;
1658     }
1659   }
1660
1661   MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1662   if (RelocNeedsGOT(Modifier))
1663     NeedsGOT = true;
1664
1665   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1666     Fixup.getOffset();
1667
1668   if (!HasRelocationAddend) Addend = 0;
1669   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1670   Relocations[Fragment->getParent()].push_back(ERE);
1671 }
1672
1673 //===- X86ELFObjectWriter -------------------------------------------===//
1674
1675
1676 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1677                                        bool _IsLittleEndian,
1678                                        uint16_t _EMachine, bool _HasRelocationAddend,
1679                                        Triple::OSType _OSType)
1680   : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1681                     _HasRelocationAddend, _OSType)
1682 {}
1683
1684 X86ELFObjectWriter::~X86ELFObjectWriter()
1685 {}
1686
1687 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1688                                        const MCAsmLayout &Layout,
1689                                        const MCFragment *Fragment,
1690                                        const MCFixup &Fixup,
1691                                        MCValue Target,
1692                                        uint64_t &FixedValue) {
1693   int64_t Addend = 0;
1694   int Index = 0;
1695   int64_t Value = Target.getConstant();
1696   const MCSymbol *RelocSymbol = NULL;
1697
1698   bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1699   if (!Target.isAbsolute()) {
1700     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1701     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1702     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1703
1704     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1705       const MCSymbol &SymbolB = RefB->getSymbol();
1706       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1707       IsPCRel = true;
1708       MCSectionData *Sec = Fragment->getParent();
1709
1710       // Offset of the symbol in the section
1711       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1712
1713       // Ofeset of the relocation in the section
1714       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1715       Value += b - a;
1716     }
1717
1718     if (!RelocSymbol) {
1719       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1720       MCFragment *F = SD.getFragment();
1721
1722       Index = F->getParent()->getOrdinal() + 1;
1723
1724       MCSectionData *FSD = F->getParent();
1725       // Offset of the symbol in the section
1726       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1727     } else {
1728       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1729         WeakrefUsedInReloc.insert(RelocSymbol);
1730       else
1731         UsedInReloc.insert(RelocSymbol);
1732       Index = -1;
1733     }
1734     Addend = Value;
1735     // Compensate for the addend on i386.
1736     if (Is64Bit)
1737       Value = 0;
1738   }
1739
1740   FixedValue = Value;
1741
1742   // determine the type of the relocation
1743
1744   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1745     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1746   unsigned Type;
1747   if (Is64Bit) {
1748     if (IsPCRel) {
1749       switch (Modifier) {
1750       default:
1751         llvm_unreachable("Unimplemented");
1752       case MCSymbolRefExpr::VK_None:
1753         Type = ELF::R_X86_64_PC32;
1754         break;
1755       case MCSymbolRefExpr::VK_PLT:
1756         Type = ELF::R_X86_64_PLT32;
1757         break;
1758       case MCSymbolRefExpr::VK_GOTPCREL:
1759         Type = ELF::R_X86_64_GOTPCREL;
1760         break;
1761       case MCSymbolRefExpr::VK_GOTTPOFF:
1762         Type = ELF::R_X86_64_GOTTPOFF;
1763         break;
1764       case MCSymbolRefExpr::VK_TLSGD:
1765         Type = ELF::R_X86_64_TLSGD;
1766         break;
1767       case MCSymbolRefExpr::VK_TLSLD:
1768         Type = ELF::R_X86_64_TLSLD;
1769         break;
1770       }
1771     } else {
1772       switch ((unsigned)Fixup.getKind()) {
1773       default: llvm_unreachable("invalid fixup kind!");
1774       case FK_Data_8: Type = ELF::R_X86_64_64; break;
1775       case X86::reloc_signed_4byte:
1776       case FK_PCRel_4:
1777         assert(isInt<32>(Target.getConstant()));
1778         switch (Modifier) {
1779         default:
1780           llvm_unreachable("Unimplemented");
1781         case MCSymbolRefExpr::VK_None:
1782           Type = ELF::R_X86_64_32S;
1783           break;
1784         case MCSymbolRefExpr::VK_GOT:
1785           Type = ELF::R_X86_64_GOT32;
1786           break;
1787         case MCSymbolRefExpr::VK_GOTPCREL:
1788           Type = ELF::R_X86_64_GOTPCREL;
1789           break;
1790         case MCSymbolRefExpr::VK_TPOFF:
1791           Type = ELF::R_X86_64_TPOFF32;
1792           break;
1793         case MCSymbolRefExpr::VK_DTPOFF:
1794           Type = ELF::R_X86_64_DTPOFF32;
1795           break;
1796         }
1797         break;
1798       case FK_Data_4:
1799         Type = ELF::R_X86_64_32;
1800         break;
1801       case FK_Data_2: Type = ELF::R_X86_64_16; break;
1802       case FK_PCRel_1:
1803       case FK_Data_1: Type = ELF::R_X86_64_8; break;
1804       }
1805     }
1806   } else {
1807     if (IsPCRel) {
1808       switch (Modifier) {
1809       default:
1810         llvm_unreachable("Unimplemented");
1811       case MCSymbolRefExpr::VK_None:
1812         Type = ELF::R_386_PC32;
1813         break;
1814       case MCSymbolRefExpr::VK_PLT:
1815         Type = ELF::R_386_PLT32;
1816         break;
1817       }
1818     } else {
1819       switch ((unsigned)Fixup.getKind()) {
1820       default: llvm_unreachable("invalid fixup kind!");
1821
1822       case X86::reloc_global_offset_table:
1823         Type = ELF::R_386_GOTPC;
1824         break;
1825
1826       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1827       // instead?
1828       case X86::reloc_signed_4byte:
1829       case FK_PCRel_4:
1830       case FK_Data_4:
1831         switch (Modifier) {
1832         default:
1833           llvm_unreachable("Unimplemented");
1834         case MCSymbolRefExpr::VK_None:
1835           Type = ELF::R_386_32;
1836           break;
1837         case MCSymbolRefExpr::VK_GOT:
1838           Type = ELF::R_386_GOT32;
1839           break;
1840         case MCSymbolRefExpr::VK_GOTOFF:
1841           Type = ELF::R_386_GOTOFF;
1842           break;
1843         case MCSymbolRefExpr::VK_TLSGD:
1844           Type = ELF::R_386_TLS_GD;
1845           break;
1846         case MCSymbolRefExpr::VK_TPOFF:
1847           Type = ELF::R_386_TLS_LE_32;
1848           break;
1849         case MCSymbolRefExpr::VK_INDNTPOFF:
1850           Type = ELF::R_386_TLS_IE;
1851           break;
1852         case MCSymbolRefExpr::VK_NTPOFF:
1853           Type = ELF::R_386_TLS_LE;
1854           break;
1855         case MCSymbolRefExpr::VK_GOTNTPOFF:
1856           Type = ELF::R_386_TLS_GOTIE;
1857           break;
1858         case MCSymbolRefExpr::VK_TLSLDM:
1859           Type = ELF::R_386_TLS_LDM;
1860           break;
1861         case MCSymbolRefExpr::VK_DTPOFF:
1862           Type = ELF::R_386_TLS_LDO_32;
1863           break;
1864         }
1865         break;
1866       case FK_Data_2: Type = ELF::R_386_16; break;
1867       case FK_PCRel_1:
1868       case FK_Data_1: Type = ELF::R_386_8; break;
1869       }
1870     }
1871   }
1872
1873   if (RelocNeedsGOT(Modifier))
1874     NeedsGOT = true;
1875
1876
1877   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1878     Fixup.getOffset();
1879
1880   if (!HasRelocationAddend) Addend = 0;
1881   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1882   Relocations[Fragment->getParent()].push_back(ERE);
1883 }