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