Teach ARM/MC/ELF about gcc compatible reloc output to get past odd linkage
[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 bool
363     IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
364                                            const MCSymbolData &DataA,
365                                            const MCFragment &FB,
366                                            bool InSet,
367                                            bool IsPCRel) const;
368
369     virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
370     virtual void WriteSection(MCAssembler &Asm,
371                       const SectionIndexMapTy &SectionIndexMap,
372                       uint32_t GroupSymbolIndex,
373                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
374                       const MCSectionELF &Section);
375
376   protected:
377     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
378                                   bool IsPCRel, bool IsRelocWithSymbol,
379                                   int64_t Addend) = 0;
380   };
381
382   //===- X86ELFObjectWriter -------------------------------------------===//
383
384   class X86ELFObjectWriter : public ELFObjectWriter {
385   public:
386     X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
387                        raw_ostream &_OS,
388                        bool IsLittleEndian);
389
390     virtual ~X86ELFObjectWriter();
391   protected:
392     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
393                                   bool IsPCRel, bool IsRelocWithSymbol,
394                                   int64_t Addend);
395   };
396
397
398   //===- ARMELFObjectWriter -------------------------------------------===//
399
400   class ARMELFObjectWriter : public ELFObjectWriter {
401   public:
402     // FIXME: MCAssembler can't yet return the Subtarget,
403     enum { DefaultEABIVersion = 0x05000000U };
404
405     ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
406                        raw_ostream &_OS,
407                        bool IsLittleEndian);
408
409     virtual ~ARMELFObjectWriter();
410
411     virtual void WriteEFlags();
412   protected:
413     virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
414                                            const MCValue &Target,
415                                            const MCFragment &F,
416                                            bool IsBSS) const;
417
418     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
419                                   bool IsPCRel, bool IsRelocWithSymbol,
420                                   int64_t Addend);
421   };
422
423   //===- MBlazeELFObjectWriter -------------------------------------------===//
424
425   class MBlazeELFObjectWriter : public ELFObjectWriter {
426   public:
427     MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
428                           raw_ostream &_OS,
429                           bool IsLittleEndian);
430
431     virtual ~MBlazeELFObjectWriter();
432   protected:
433     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
434                                   bool IsPCRel, bool IsRelocWithSymbol,
435                                   int64_t Addend);
436   };
437 }
438
439 ELFObjectWriter::~ELFObjectWriter()
440 {}
441
442 // Emit the ELF header.
443 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
444                                   unsigned NumberOfSections) {
445   // ELF Header
446   // ----------
447   //
448   // Note
449   // ----
450   // emitWord method behaves differently for ELF32 and ELF64, writing
451   // 4 bytes in the former and 8 in the latter.
452
453   Write8(0x7f); // e_ident[EI_MAG0]
454   Write8('E');  // e_ident[EI_MAG1]
455   Write8('L');  // e_ident[EI_MAG2]
456   Write8('F');  // e_ident[EI_MAG3]
457
458   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
459
460   // e_ident[EI_DATA]
461   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
462
463   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
464   // e_ident[EI_OSABI]
465   switch (TargetObjectWriter->getOSType()) {
466     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
467     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
468     default:               Write8(ELF::ELFOSABI_NONE); break;
469   }
470   Write8(0);                  // e_ident[EI_ABIVERSION]
471
472   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
473
474   Write16(ELF::ET_REL);             // e_type
475
476   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
477
478   Write32(ELF::EV_CURRENT);         // e_version
479   WriteWord(0);                    // e_entry, no entry point in .o file
480   WriteWord(0);                    // e_phoff, no program header for .o
481   WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
482             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
483
484   // e_flags = whatever the target wants
485   WriteEFlags();
486
487   // e_ehsize = ELF header size
488   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
489
490   Write16(0);                  // e_phentsize = prog header entry size
491   Write16(0);                  // e_phnum = # prog header entries = 0
492
493   // e_shentsize = Section header entry size
494   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
495
496   // e_shnum     = # of section header ents
497   if (NumberOfSections >= ELF::SHN_LORESERVE)
498     Write16(0);
499   else
500     Write16(NumberOfSections);
501
502   // e_shstrndx  = Section # of '.shstrtab'
503   if (NumberOfSections >= ELF::SHN_LORESERVE)
504     Write16(ELF::SHN_XINDEX);
505   else
506     Write16(ShstrtabIndex);
507 }
508
509 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
510                                        MCDataFragment *ShndxF,
511                                        uint64_t name,
512                                        uint8_t info, uint64_t value,
513                                        uint64_t size, uint8_t other,
514                                        uint32_t shndx,
515                                        bool Reserved) {
516   if (ShndxF) {
517     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
518       String32(*ShndxF, shndx);
519     else
520       String32(*ShndxF, 0);
521   }
522
523   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
524     uint16_t(ELF::SHN_XINDEX) : shndx;
525
526   if (is64Bit()) {
527     String32(*SymtabF, name);  // st_name
528     String8(*SymtabF, info);   // st_info
529     String8(*SymtabF, other);  // st_other
530     String16(*SymtabF, Index); // st_shndx
531     String64(*SymtabF, value); // st_value
532     String64(*SymtabF, size);  // st_size
533   } else {
534     String32(*SymtabF, name);  // st_name
535     String32(*SymtabF, value); // st_value
536     String32(*SymtabF, size);  // st_size
537     String8(*SymtabF, info);   // st_info
538     String8(*SymtabF, other);  // st_other
539     String16(*SymtabF, Index); // st_shndx
540   }
541 }
542
543 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
544   if (Data.isCommon() && Data.isExternal())
545     return Data.getCommonAlignment();
546
547   const MCSymbol &Symbol = Data.getSymbol();
548
549   if (Symbol.isAbsolute() && Symbol.isVariable()) {
550     if (const MCExpr *Value = Symbol.getVariableValue()) {
551       int64_t IntValue;
552       if (Value->EvaluateAsAbsolute(IntValue, Layout))
553         return (uint64_t)IntValue;
554     }
555   }
556
557   if (!Symbol.isInSection())
558     return 0;
559
560   if (Data.getFragment())
561     return Layout.getSymbolOffset(&Data);
562
563   return 0;
564 }
565
566 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
567                                                const MCAsmLayout &Layout) {
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
625   assert(!(Data.isCommon() && !Data.isExternal()));
626
627   const MCExpr *ESize = Data.getSize();
628   if (ESize) {
629     int64_t Res;
630     if (!ESize->EvaluateAsAbsolute(Res, Layout))
631       report_fatal_error("Size expression must be absolute.");
632     Size = Res;
633   }
634
635   // Write out the symbol table entry
636   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
637                    Size, Other, MSD.SectionIndex, IsReserved);
638 }
639
640 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
641                                        MCDataFragment *ShndxF,
642                                        const MCAssembler &Asm,
643                                        const MCAsmLayout &Layout,
644                                      const SectionIndexMapTy &SectionIndexMap) {
645   // The string table must be emitted first because we need the index
646   // into the string table for all the symbol names.
647   assert(StringTable.size() && "Missing string table");
648
649   // FIXME: Make sure the start of the symbol table is aligned.
650
651   // The first entry is the undefined symbol entry.
652   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
653
654   // Write the symbol table entries.
655   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
656   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
657     ELFSymbolData &MSD = LocalSymbolData[i];
658     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
659   }
660
661   // Write out a symbol table entry for each regular section.
662   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
663        ++i) {
664     const MCSectionELF &Section =
665       static_cast<const MCSectionELF&>(i->getSection());
666     if (Section.getType() == ELF::SHT_RELA ||
667         Section.getType() == ELF::SHT_REL ||
668         Section.getType() == ELF::SHT_STRTAB ||
669         Section.getType() == ELF::SHT_SYMTAB)
670       continue;
671     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
672                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
673     LastLocalSymbolIndex++;
674   }
675
676   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
677     ELFSymbolData &MSD = ExternalSymbolData[i];
678     MCSymbolData &Data = *MSD.SymbolData;
679     assert(((Data.getFlags() & ELF_STB_Global) ||
680             (Data.getFlags() & ELF_STB_Weak)) &&
681            "External symbol requires STB_GLOBAL or STB_WEAK flag");
682     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
683     if (GetBinding(Data) == ELF::STB_LOCAL)
684       LastLocalSymbolIndex++;
685   }
686
687   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
688     ELFSymbolData &MSD = UndefinedSymbolData[i];
689     MCSymbolData &Data = *MSD.SymbolData;
690     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
691     if (GetBinding(Data) == ELF::STB_LOCAL)
692       LastLocalSymbolIndex++;
693   }
694 }
695
696 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
697                                                const MCValue &Target,
698                                                const MCFragment &F) const {
699   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
700   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
701   const MCSymbol *Renamed = Renames.lookup(&Symbol);
702   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
703
704   if (ASymbol.isUndefined()) {
705     if (Renamed)
706       return Renamed;
707     return &ASymbol;
708   }
709
710   if (SD.isExternal()) {
711     if (Renamed)
712       return Renamed;
713     return &Symbol;
714   }
715
716   const MCSectionELF &Section =
717     static_cast<const MCSectionELF&>(ASymbol.getSection());
718   const SectionKind secKind = Section.getKind();
719
720   if (secKind.isBSS())
721     return ExplicitRelSym(Asm, Target, F, true);
722
723   if (secKind.isThreadLocal()) {
724     if (Renamed)
725       return Renamed;
726     return &Symbol;
727   }
728
729   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
730   const MCSectionELF &Sec2 =
731     static_cast<const MCSectionELF&>(F.getParent()->getSection());
732
733   if (&Sec2 != &Section &&
734       (Kind == MCSymbolRefExpr::VK_PLT ||
735        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
736        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
737     if (Renamed)
738       return Renamed;
739     return &Symbol;
740   }
741
742   if (Section.getFlags() & ELF::SHF_MERGE) {
743     if (Target.getConstant() == 0)
744       return NULL;
745     if (Renamed)
746       return Renamed;
747     return &Symbol;
748   }
749
750   return ExplicitRelSym(Asm, Target, F, false);
751 }
752
753
754 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
755                                        const MCAsmLayout &Layout,
756                                        const MCFragment *Fragment,
757                                        const MCFixup &Fixup,
758                                        MCValue Target,
759                                        uint64_t &FixedValue) {
760   int64_t Addend = 0;
761   int Index = 0;
762   int64_t Value = Target.getConstant();
763   const MCSymbol *RelocSymbol = NULL;
764
765   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
766   if (!Target.isAbsolute()) {
767     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
768     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
769     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
770
771     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
772       const MCSymbol &SymbolB = RefB->getSymbol();
773       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
774       IsPCRel = true;
775
776       // Offset of the symbol in the section
777       int64_t a = Layout.getSymbolOffset(&SDB);
778
779       // Ofeset of the relocation in the section
780       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
781       Value += b - a;
782     }
783
784     if (!RelocSymbol) {
785       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
786       MCFragment *F = SD.getFragment();
787
788       Index = F->getParent()->getOrdinal() + 1;
789
790       // Offset of the symbol in the section
791       Value += Layout.getSymbolOffset(&SD);
792     } else {
793       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
794         WeakrefUsedInReloc.insert(RelocSymbol);
795       else
796         UsedInReloc.insert(RelocSymbol);
797       Index = -1;
798     }
799     Addend = Value;
800     // Compensate for the addend on i386.
801     if (is64Bit())
802       Value = 0;
803   }
804
805   FixedValue = Value;
806   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
807                                (RelocSymbol != 0), Addend);
808   
809   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
810     Fixup.getOffset();
811
812   if (!hasRelocationAddend())
813     Addend = 0;
814   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
815   Relocations[Fragment->getParent()].push_back(ERE);
816 }
817
818
819 uint64_t
820 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
821                                              const MCSymbol *S) {
822   MCSymbolData &SD = Asm.getSymbolData(*S);
823   return SD.getIndex();
824 }
825
826 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
827                        bool Used, bool Renamed) {
828   if (Data.getFlags() & ELF_Other_Weakref)
829     return false;
830
831   if (Used)
832     return true;
833
834   if (Renamed)
835     return false;
836
837   const MCSymbol &Symbol = Data.getSymbol();
838
839   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
840     return true;
841
842   const MCSymbol &A = Symbol.AliasedSymbol();
843   if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
844     return false;
845
846   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
847     return false;
848
849   if (Symbol.isTemporary())
850     return false;
851
852   return true;
853 }
854
855 static bool isLocal(const MCSymbolData &Data, bool isSignature,
856                     bool isUsedInReloc) {
857   if (Data.isExternal())
858     return false;
859
860   const MCSymbol &Symbol = Data.getSymbol();
861   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
862
863   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
864     if (isSignature && !isUsedInReloc)
865       return true;
866
867     return false;
868   }
869
870   return true;
871 }
872
873 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
874                                       SectionIndexMapTy &SectionIndexMap) {
875   unsigned Index = 1;
876   for (MCAssembler::iterator it = Asm.begin(),
877          ie = Asm.end(); it != ie; ++it) {
878     const MCSectionELF &Section =
879       static_cast<const MCSectionELF &>(it->getSection());
880     if (Section.getType() != ELF::SHT_GROUP)
881       continue;
882     SectionIndexMap[&Section] = Index++;
883   }
884
885   for (MCAssembler::iterator it = Asm.begin(),
886          ie = Asm.end(); it != ie; ++it) {
887     const MCSectionELF &Section =
888       static_cast<const MCSectionELF &>(it->getSection());
889     if (Section.getType() == ELF::SHT_GROUP)
890       continue;
891     SectionIndexMap[&Section] = Index++;
892   }
893 }
894
895 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
896                                       const SectionIndexMapTy &SectionIndexMap,
897                                       RevGroupMapTy RevGroupMap) {
898   // FIXME: Is this the correct place to do this?
899   if (NeedsGOT) {
900     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
901     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
902     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
903     Data.setExternal(true);
904     SetBinding(Data, ELF::STB_GLOBAL);
905   }
906
907   // Build section lookup table.
908   int NumRegularSections = Asm.size();
909
910   // Index 0 is always the empty string.
911   StringMap<uint64_t> StringIndexMap;
912   StringTable += '\x00';
913
914   // Add the data for the symbols.
915   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
916          ie = Asm.symbol_end(); it != ie; ++it) {
917     const MCSymbol &Symbol = it->getSymbol();
918
919     bool Used = UsedInReloc.count(&Symbol);
920     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
921     bool isSignature = RevGroupMap.count(&Symbol);
922
923     if (!isInSymtab(Asm, *it,
924                     Used || WeakrefUsed || isSignature,
925                     Renames.count(&Symbol)))
926       continue;
927
928     ELFSymbolData MSD;
929     MSD.SymbolData = it;
930     const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
931
932     // Undefined symbols are global, but this is the first place we
933     // are able to set it.
934     bool Local = isLocal(*it, isSignature, Used);
935     if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
936       MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
937       SetBinding(*it, ELF::STB_GLOBAL);
938       SetBinding(SD, ELF::STB_GLOBAL);
939     }
940
941     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
942       SetBinding(*it, ELF::STB_WEAK);
943
944     if (it->isCommon()) {
945       assert(!Local);
946       MSD.SectionIndex = ELF::SHN_COMMON;
947     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
948       MSD.SectionIndex = ELF::SHN_ABS;
949     } else if (RefSymbol.isUndefined()) {
950       if (isSignature && !Used)
951         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
952       else
953         MSD.SectionIndex = ELF::SHN_UNDEF;
954     } else {
955       const MCSectionELF &Section =
956         static_cast<const MCSectionELF&>(RefSymbol.getSection());
957       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
958       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
959         NeedsSymtabShndx = true;
960       assert(MSD.SectionIndex && "Invalid section index!");
961     }
962
963     // The @@@ in symbol version is replaced with @ in undefined symbols and
964     // @@ in defined ones.
965     StringRef Name = Symbol.getName();
966     SmallString<32> Buf;
967
968     size_t Pos = Name.find("@@@");
969     if (Pos != StringRef::npos) {
970       Buf += Name.substr(0, Pos);
971       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
972       Buf += Name.substr(Pos + Skip);
973       Name = Buf;
974     }
975
976     uint64_t &Entry = StringIndexMap[Name];
977     if (!Entry) {
978       Entry = StringTable.size();
979       StringTable += Name;
980       StringTable += '\x00';
981     }
982     MSD.StringIndex = Entry;
983     if (MSD.SectionIndex == ELF::SHN_UNDEF)
984       UndefinedSymbolData.push_back(MSD);
985     else if (Local)
986       LocalSymbolData.push_back(MSD);
987     else
988       ExternalSymbolData.push_back(MSD);
989   }
990
991   // Symbols are required to be in lexicographic order.
992   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
993   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
994   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
995
996   // Set the symbol indices. Local symbols must come before all other
997   // symbols with non-local bindings.
998   unsigned Index = 1;
999   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1000     LocalSymbolData[i].SymbolData->setIndex(Index++);
1001
1002   Index += NumRegularSections;
1003
1004   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1005     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1006   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1007     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1008 }
1009
1010 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1011                                       const MCSectionData &SD) {
1012   if (!Relocations[&SD].empty()) {
1013     MCContext &Ctx = Asm.getContext();
1014     const MCSectionELF *RelaSection;
1015     const MCSectionELF &Section =
1016       static_cast<const MCSectionELF&>(SD.getSection());
1017
1018     const StringRef SectionName = Section.getSectionName();
1019     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1020     RelaSectionName += SectionName;
1021
1022     unsigned EntrySize;
1023     if (hasRelocationAddend())
1024       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1025     else
1026       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1027
1028     RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1029                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
1030                                     SectionKind::getReadOnly(),
1031                                     EntrySize, "");
1032
1033     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1034     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1035
1036     MCDataFragment *F = new MCDataFragment(&RelaSD);
1037
1038     WriteRelocationsFragment(Asm, F, &SD);
1039   }
1040 }
1041
1042 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1043                                        uint64_t Flags, uint64_t Address,
1044                                        uint64_t Offset, uint64_t Size,
1045                                        uint32_t Link, uint32_t Info,
1046                                        uint64_t Alignment,
1047                                        uint64_t EntrySize) {
1048   Write32(Name);        // sh_name: index into string table
1049   Write32(Type);        // sh_type
1050   WriteWord(Flags);     // sh_flags
1051   WriteWord(Address);   // sh_addr
1052   WriteWord(Offset);    // sh_offset
1053   WriteWord(Size);      // sh_size
1054   Write32(Link);        // sh_link
1055   Write32(Info);        // sh_info
1056   WriteWord(Alignment); // sh_addralign
1057   WriteWord(EntrySize); // sh_entsize
1058 }
1059
1060 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1061                                                MCDataFragment *F,
1062                                                const MCSectionData *SD) {
1063   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1064   // sort by the r_offset just like gnu as does
1065   array_pod_sort(Relocs.begin(), Relocs.end());
1066
1067   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1068     ELFRelocationEntry entry = Relocs[e - i - 1];
1069
1070     if (!entry.Index)
1071       ;
1072     else if (entry.Index < 0)
1073       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1074     else
1075       entry.Index += LocalSymbolData.size();
1076     if (is64Bit()) {
1077       String64(*F, entry.r_offset);
1078
1079       struct ELF::Elf64_Rela ERE64;
1080       ERE64.setSymbolAndType(entry.Index, entry.Type);
1081       String64(*F, ERE64.r_info);
1082
1083       if (hasRelocationAddend())
1084         String64(*F, entry.r_addend);
1085     } else {
1086       String32(*F, entry.r_offset);
1087
1088       struct ELF::Elf32_Rela ERE32;
1089       ERE32.setSymbolAndType(entry.Index, entry.Type);
1090       String32(*F, ERE32.r_info);
1091
1092       if (hasRelocationAddend())
1093         String32(*F, entry.r_addend);
1094     }
1095   }
1096 }
1097
1098 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1099                                              MCAsmLayout &Layout,
1100                                     const SectionIndexMapTy &SectionIndexMap) {
1101   MCContext &Ctx = Asm.getContext();
1102   MCDataFragment *F;
1103
1104   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1105
1106   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1107   const MCSectionELF *ShstrtabSection =
1108     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1109                       SectionKind::getReadOnly());
1110   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1111   ShstrtabSD.setAlignment(1);
1112   ShstrtabIndex = Asm.size();
1113
1114   const MCSectionELF *SymtabSection =
1115     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1116                       SectionKind::getReadOnly(),
1117                       EntrySize, "");
1118   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1119   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1120   SymbolTableIndex = Asm.size();
1121
1122   MCSectionData *SymtabShndxSD = NULL;
1123
1124   if (NeedsSymtabShndx) {
1125     const MCSectionELF *SymtabShndxSection =
1126       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1127                         SectionKind::getReadOnly(), 4, "");
1128     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1129     SymtabShndxSD->setAlignment(4);
1130   }
1131
1132   const MCSection *StrtabSection;
1133   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1134                                     SectionKind::getReadOnly());
1135   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1136   StrtabSD.setAlignment(1);
1137   StringTableIndex = Asm.size();
1138
1139   WriteRelocations(Asm, Layout);
1140
1141   // Symbol table
1142   F = new MCDataFragment(&SymtabSD);
1143   MCDataFragment *ShndxF = NULL;
1144   if (NeedsSymtabShndx) {
1145     ShndxF = new MCDataFragment(SymtabShndxSD);
1146   }
1147   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1148
1149   F = new MCDataFragment(&StrtabSD);
1150   F->getContents().append(StringTable.begin(), StringTable.end());
1151
1152   F = new MCDataFragment(&ShstrtabSD);
1153
1154   // Section header string table.
1155   //
1156   // The first entry of a string table holds a null character so skip
1157   // section 0.
1158   uint64_t Index = 1;
1159   F->getContents() += '\x00';
1160
1161   StringMap<uint64_t> SecStringMap;
1162   for (MCAssembler::const_iterator it = Asm.begin(),
1163          ie = Asm.end(); it != ie; ++it) {
1164     const MCSectionELF &Section =
1165       static_cast<const MCSectionELF&>(it->getSection());
1166     // FIXME: We could merge suffixes like in .text and .rela.text.
1167
1168     StringRef Name = Section.getSectionName();
1169     if (SecStringMap.count(Name)) {
1170       SectionStringTableIndex[&Section] =  SecStringMap[Name];
1171       continue;
1172     }
1173     // Remember the index into the string table so we can write it
1174     // into the sh_name field of the section header table.
1175     SectionStringTableIndex[&Section] = Index;
1176     SecStringMap[Name] = Index;
1177
1178     Index += Name.size() + 1;
1179     F->getContents() += Name;
1180     F->getContents() += '\x00';
1181   }
1182 }
1183
1184 bool
1185 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1186                                                       const MCSymbolData &DataA,
1187                                                       const MCFragment &FB,
1188                                                       bool InSet,
1189                                                       bool IsPCRel) const {
1190   // FIXME: This is in here just to match gnu as output. If the two ends
1191   // are in the same section, there is nothing that the linker can do to
1192   // break it.
1193   if (DataA.isExternal())
1194     return false;
1195
1196   const MCSection &SecA = DataA.getSymbol().AliasedSymbol().getSection();
1197   const MCSection &SecB = FB.getParent()->getSection();
1198   // On ELF A - B is absolute if A and B are in the same section.
1199   return &SecA == &SecB;
1200 }
1201
1202 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1203                                             MCAsmLayout &Layout,
1204                                             GroupMapTy &GroupMap,
1205                                             RevGroupMapTy &RevGroupMap) {
1206   // Create the .note.GNU-stack section if needed.
1207   MCContext &Ctx = Asm.getContext();
1208   if (Asm.getNoExecStack()) {
1209     const MCSectionELF *GnuStackSection =
1210       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1211                         SectionKind::getReadOnly());
1212     Asm.getOrCreateSectionData(*GnuStackSection);
1213   }
1214
1215   // Build the groups
1216   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1217        it != ie; ++it) {
1218     const MCSectionELF &Section =
1219       static_cast<const MCSectionELF&>(it->getSection());
1220     if (!(Section.getFlags() & ELF::SHF_GROUP))
1221       continue;
1222
1223     const MCSymbol *SignatureSymbol = Section.getGroup();
1224     Asm.getOrCreateSymbolData(*SignatureSymbol);
1225     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1226     if (!Group) {
1227       Group = Ctx.CreateELFGroupSection();
1228       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1229       Data.setAlignment(4);
1230       MCDataFragment *F = new MCDataFragment(&Data);
1231       String32(*F, ELF::GRP_COMDAT);
1232     }
1233     GroupMap[Group] = SignatureSymbol;
1234   }
1235
1236   // Add sections to the groups
1237   unsigned Index = 1;
1238   unsigned NumGroups = RevGroupMap.size();
1239   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1240        it != ie; ++it, ++Index) {
1241     const MCSectionELF &Section =
1242       static_cast<const MCSectionELF&>(it->getSection());
1243     if (!(Section.getFlags() & ELF::SHF_GROUP))
1244       continue;
1245     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1246     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1247     // FIXME: we could use the previous fragment
1248     MCDataFragment *F = new MCDataFragment(&Data);
1249     String32(*F, NumGroups + Index);
1250   }
1251 }
1252
1253 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1254                                    const SectionIndexMapTy &SectionIndexMap,
1255                                    uint32_t GroupSymbolIndex,
1256                                    uint64_t Offset, uint64_t Size,
1257                                    uint64_t Alignment,
1258                                    const MCSectionELF &Section) {
1259   uint64_t sh_link = 0;
1260   uint64_t sh_info = 0;
1261
1262   switch(Section.getType()) {
1263   case ELF::SHT_DYNAMIC:
1264     sh_link = SectionStringTableIndex[&Section];
1265     sh_info = 0;
1266     break;
1267
1268   case ELF::SHT_REL:
1269   case ELF::SHT_RELA: {
1270     const MCSectionELF *SymtabSection;
1271     const MCSectionELF *InfoSection;
1272     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1273                                                    0,
1274                                                    SectionKind::getReadOnly());
1275     sh_link = SectionIndexMap.lookup(SymtabSection);
1276     assert(sh_link && ".symtab not found");
1277
1278     // Remove ".rel" and ".rela" prefixes.
1279     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1280     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1281
1282     InfoSection = Asm.getContext().getELFSection(SectionName,
1283                                                  ELF::SHT_PROGBITS, 0,
1284                                                  SectionKind::getReadOnly());
1285     sh_info = SectionIndexMap.lookup(InfoSection);
1286     break;
1287   }
1288
1289   case ELF::SHT_SYMTAB:
1290   case ELF::SHT_DYNSYM:
1291     sh_link = StringTableIndex;
1292     sh_info = LastLocalSymbolIndex;
1293     break;
1294
1295   case ELF::SHT_SYMTAB_SHNDX:
1296     sh_link = SymbolTableIndex;
1297     break;
1298
1299   case ELF::SHT_PROGBITS:
1300   case ELF::SHT_STRTAB:
1301   case ELF::SHT_NOBITS:
1302   case ELF::SHT_NOTE:
1303   case ELF::SHT_NULL:
1304   case ELF::SHT_ARM_ATTRIBUTES:
1305   case ELF::SHT_INIT_ARRAY:
1306   case ELF::SHT_FINI_ARRAY:
1307   case ELF::SHT_PREINIT_ARRAY:
1308   case ELF::SHT_X86_64_UNWIND:
1309     // Nothing to do.
1310     break;
1311
1312   case ELF::SHT_GROUP: {
1313     sh_link = SymbolTableIndex;
1314     sh_info = GroupSymbolIndex;
1315     break;
1316   }
1317
1318   default:
1319     assert(0 && "FIXME: sh_type value not supported!");
1320     break;
1321   }
1322
1323   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1324                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1325                    Alignment, Section.getEntrySize());
1326 }
1327
1328 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1329   return SD.getOrdinal() == ~UINT32_C(0) &&
1330     !SD.getSection().isVirtualSection();
1331 }
1332
1333 static uint64_t DataSectionSize(const MCSectionData &SD) {
1334   uint64_t Ret = 0;
1335   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1336        ++i) {
1337     const MCFragment &F = *i;
1338     assert(F.getKind() == MCFragment::FT_Data);
1339     Ret += cast<MCDataFragment>(F).getContents().size();
1340   }
1341   return Ret;
1342 }
1343
1344 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1345                                    const MCSectionData &SD) {
1346   if (IsELFMetaDataSection(SD))
1347     return DataSectionSize(SD);
1348   return Layout.getSectionFileSize(&SD);
1349 }
1350
1351 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1352                                       const MCSectionData &SD) {
1353   if (IsELFMetaDataSection(SD))
1354     return DataSectionSize(SD);
1355   return Layout.getSectionAddressSize(&SD);
1356 }
1357
1358 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1359   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1360        ++i) {
1361     const MCFragment &F = *i;
1362     assert(F.getKind() == MCFragment::FT_Data);
1363     W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1364   }
1365 }
1366
1367 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1368                                   const MCAsmLayout &Layout) {
1369   GroupMapTy GroupMap;
1370   RevGroupMapTy RevGroupMap;
1371   CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1372                         RevGroupMap);
1373
1374   SectionIndexMapTy SectionIndexMap;
1375
1376   ComputeIndexMap(Asm, SectionIndexMap);
1377
1378   // Compute symbol table information.
1379   ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1380
1381   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1382                          const_cast<MCAsmLayout&>(Layout),
1383                          SectionIndexMap);
1384
1385   // Update to include the metadata sections.
1386   ComputeIndexMap(Asm, SectionIndexMap);
1387
1388   // Add 1 for the null section.
1389   unsigned NumSections = Asm.size() + 1;
1390   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1391   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1392                                     sizeof(ELF::Elf32_Ehdr);
1393   uint64_t FileOff = HeaderSize;
1394
1395   std::vector<const MCSectionELF*> Sections;
1396   Sections.resize(NumSections);
1397
1398   for (SectionIndexMapTy::const_iterator i=
1399          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1400     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1401     Sections[p.second] = p.first;
1402   }
1403
1404   for (unsigned i = 1; i < NumSections; ++i) {
1405     const MCSectionELF &Section = *Sections[i];
1406     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1407
1408     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1409
1410     // Get the size of the section in the output file (including padding).
1411     FileOff += GetSectionFileSize(Layout, SD);
1412   }
1413
1414   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1415
1416   // Write out the ELF header ...
1417   WriteHeader(FileOff - HeaderSize, NumSections);
1418
1419   FileOff = HeaderSize;
1420
1421   // ... then all of the sections ...
1422   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1423
1424   for (unsigned i = 1; i < NumSections; ++i) {
1425     const MCSectionELF &Section = *Sections[i];
1426     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1427
1428     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1429     WriteZeros(Padding);
1430     FileOff += Padding;
1431
1432     // Remember the offset into the file for this section.
1433     SectionOffsetMap[&Section] = FileOff;
1434
1435     FileOff += GetSectionFileSize(Layout, SD);
1436
1437     if (IsELFMetaDataSection(SD))
1438       WriteDataSectionData(this, SD);
1439     else
1440       Asm.WriteSectionData(&SD, Layout);
1441   }
1442
1443   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1444   WriteZeros(Padding);
1445   FileOff += Padding;
1446
1447   // ... and then the section header table.
1448   // Should we align the section header table?
1449   //
1450   // Null section first.
1451   uint64_t FirstSectionSize =
1452     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1453   uint32_t FirstSectionLink =
1454     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1455   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1456
1457   for (unsigned i = 1; i < NumSections; ++i) {
1458     const MCSectionELF &Section = *Sections[i];
1459     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1460     uint32_t GroupSymbolIndex;
1461     if (Section.getType() != ELF::SHT_GROUP)
1462       GroupSymbolIndex = 0;
1463     else
1464       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1465
1466     uint64_t Size = GetSectionAddressSize(Layout, SD);
1467
1468     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1469                  SectionOffsetMap[&Section], Size,
1470                  SD.getAlignment(), Section);
1471   }
1472 }
1473
1474 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1475                                             raw_ostream &OS,
1476                                             bool IsLittleEndian) {
1477   switch (MOTW->getEMachine()) {
1478     case ELF::EM_386:
1479     case ELF::EM_X86_64:
1480       return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1481     case ELF::EM_ARM:
1482       return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1483     case ELF::EM_MBLAZE:
1484       return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1485     default: llvm_unreachable("Unsupported architecture"); break;
1486   }
1487 }
1488
1489
1490 /// START OF SUBCLASSES for ELFObjectWriter
1491 //===- ARMELFObjectWriter -------------------------------------------===//
1492
1493 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1494                                        raw_ostream &_OS,
1495                                        bool IsLittleEndian)
1496   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1497 {}
1498
1499 ARMELFObjectWriter::~ARMELFObjectWriter()
1500 {}
1501
1502 // FIXME: get the real EABI Version from the Triple.
1503 void ARMELFObjectWriter::WriteEFlags() {
1504   Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1505 }
1506
1507 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1508 // I.e. not as an offset to a section symbol.
1509 // This code is a first-cut approximation of what ARM/gcc does.
1510
1511 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1512                                                    const MCValue &Target,
1513                                                    const MCFragment &F,
1514                                                    bool IsBSS) const {
1515   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1516   bool EmitThisSym = false;
1517
1518   if (IsBSS) {
1519     EmitThisSym = StringSwitch<bool>(Symbol.getName())
1520       .Case("_MergedGlobals", true)
1521       .Default(false);
1522   } else {
1523     EmitThisSym = StringSwitch<bool>(Symbol.getName())
1524       .Case("_MergedGlobals", true)
1525       .StartsWith(".L.str", true)
1526       .Default(false);
1527   }
1528   if (EmitThisSym)
1529     return &Symbol;
1530   if (! Symbol.isTemporary())
1531     return &Symbol;
1532   return NULL;
1533 }
1534
1535 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1536                                           const MCFixup &Fixup,
1537                                           bool IsPCRel,
1538                                           bool IsRelocWithSymbol,
1539                                           int64_t Addend) {
1540   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1541     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1542
1543   unsigned Type = 0;
1544   if (IsPCRel) {
1545     switch ((unsigned)Fixup.getKind()) {
1546     default: assert(0 && "Unimplemented");
1547     case FK_Data_4:
1548       switch (Modifier) {
1549       default: llvm_unreachable("Unsupported Modifier");
1550       case MCSymbolRefExpr::VK_None:
1551         Type = ELF::R_ARM_BASE_PREL;
1552         break;
1553       case MCSymbolRefExpr::VK_ARM_TLSGD:
1554         assert(0 && "unimplemented");
1555         break;
1556       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1557         Type = ELF::R_ARM_TLS_IE32;
1558         break;
1559       }
1560       break;
1561     case ARM::fixup_arm_uncondbranch:
1562       switch (Modifier) {
1563       case MCSymbolRefExpr::VK_ARM_PLT:
1564         Type = ELF::R_ARM_PLT32;
1565         break;
1566       default:
1567         Type = ELF::R_ARM_CALL;
1568         break;
1569       }
1570       break;
1571     case ARM::fixup_arm_condbranch:
1572       Type = ELF::R_ARM_JUMP24;
1573       break;
1574     case ARM::fixup_arm_movt_hi16:
1575     case ARM::fixup_arm_movt_hi16_pcrel:
1576       Type = ELF::R_ARM_MOVT_PREL;
1577       break;
1578     case ARM::fixup_arm_movw_lo16:
1579     case ARM::fixup_arm_movw_lo16_pcrel:
1580       Type = ELF::R_ARM_MOVW_PREL_NC;
1581       break;
1582     case ARM::fixup_t2_movt_hi16:
1583     case ARM::fixup_t2_movt_hi16_pcrel:
1584       Type = ELF::R_ARM_THM_MOVT_PREL;
1585       break;
1586     case ARM::fixup_t2_movw_lo16:
1587     case ARM::fixup_t2_movw_lo16_pcrel:
1588       Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1589       break;
1590     }
1591   } else {
1592     switch ((unsigned)Fixup.getKind()) {
1593     default: llvm_unreachable("invalid fixup kind!");
1594     case FK_Data_4:
1595       switch (Modifier) {
1596       default: llvm_unreachable("Unsupported Modifier"); break;
1597       case MCSymbolRefExpr::VK_ARM_GOT:
1598         Type = ELF::R_ARM_GOT_BREL;
1599         break;
1600       case MCSymbolRefExpr::VK_ARM_TLSGD:
1601         Type = ELF::R_ARM_TLS_GD32;
1602         break;
1603       case MCSymbolRefExpr::VK_ARM_TPOFF:
1604         Type = ELF::R_ARM_TLS_LE32;
1605         break;
1606       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1607         Type = ELF::R_ARM_TLS_IE32;
1608         break;
1609       case MCSymbolRefExpr::VK_None:
1610         Type = ELF::R_ARM_ABS32;
1611         break;
1612       case MCSymbolRefExpr::VK_ARM_GOTOFF:
1613         Type = ELF::R_ARM_GOTOFF32;
1614         break;
1615       }
1616       break;
1617     case ARM::fixup_arm_ldst_pcrel_12:
1618     case ARM::fixup_arm_pcrel_10:
1619     case ARM::fixup_arm_adr_pcrel_12:
1620     case ARM::fixup_arm_thumb_bl:
1621     case ARM::fixup_arm_thumb_cb:
1622     case ARM::fixup_arm_thumb_cp:
1623     case ARM::fixup_arm_thumb_br:
1624       assert(0 && "Unimplemented");
1625       break;
1626     case ARM::fixup_arm_uncondbranch:
1627       Type = ELF::R_ARM_CALL;
1628       break;
1629     case ARM::fixup_arm_condbranch:
1630       Type = ELF::R_ARM_JUMP24;
1631       break;
1632     case ARM::fixup_arm_movt_hi16:
1633       Type = ELF::R_ARM_MOVT_ABS;
1634       break;
1635     case ARM::fixup_arm_movw_lo16:
1636       Type = ELF::R_ARM_MOVW_ABS_NC;
1637       break;
1638     case ARM::fixup_t2_movt_hi16:
1639       Type = ELF::R_ARM_THM_MOVT_ABS;
1640       break;
1641     case ARM::fixup_t2_movw_lo16:
1642       Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1643       break;
1644     }
1645   }
1646
1647   if (RelocNeedsGOT(Modifier))
1648     NeedsGOT = true;
1649
1650   return Type;
1651 }
1652
1653 //===- MBlazeELFObjectWriter -------------------------------------------===//
1654
1655 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1656                                              raw_ostream &_OS,
1657                                              bool IsLittleEndian)
1658   : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1659 }
1660
1661 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1662 }
1663
1664 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1665                                              const MCFixup &Fixup,
1666                                              bool IsPCRel,
1667                                              bool IsRelocWithSymbol,
1668                                              int64_t Addend) {
1669   // determine the type of the relocation
1670   unsigned Type;
1671   if (IsPCRel) {
1672     switch ((unsigned)Fixup.getKind()) {
1673     default:
1674       llvm_unreachable("Unimplemented");
1675     case FK_PCRel_4:
1676       Type = ELF::R_MICROBLAZE_64_PCREL;
1677       break;
1678     case FK_PCRel_2:
1679       Type = ELF::R_MICROBLAZE_32_PCREL;
1680       break;
1681     }
1682   } else {
1683     switch ((unsigned)Fixup.getKind()) {
1684     default: llvm_unreachable("invalid fixup kind!");
1685     case FK_Data_4:
1686       Type = ((IsRelocWithSymbol || Addend !=0)
1687               ? ELF::R_MICROBLAZE_32
1688               : ELF::R_MICROBLAZE_64);
1689       break;
1690     case FK_Data_2:
1691       Type = ELF::R_MICROBLAZE_32;
1692       break;
1693     }
1694   }
1695   return Type;
1696 }
1697
1698 //===- X86ELFObjectWriter -------------------------------------------===//
1699
1700
1701 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1702                                        raw_ostream &_OS,
1703                                        bool IsLittleEndian)
1704   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1705 {}
1706
1707 X86ELFObjectWriter::~X86ELFObjectWriter()
1708 {}
1709
1710 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1711                                           const MCFixup &Fixup,
1712                                           bool IsPCRel,
1713                                           bool IsRelocWithSymbol,
1714                                           int64_t Addend) {
1715   // determine the type of the relocation
1716
1717   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1718     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1719   unsigned Type;
1720   if (is64Bit()) {
1721     if (IsPCRel) {
1722       switch ((unsigned)Fixup.getKind()) {
1723       default: llvm_unreachable("invalid fixup kind!");
1724       case FK_PCRel_8:
1725         assert(Modifier == MCSymbolRefExpr::VK_None);
1726         Type = ELF::R_X86_64_PC64;
1727         break;
1728       case X86::reloc_signed_4byte:
1729       case X86::reloc_riprel_4byte_movq_load:
1730       case FK_Data_4: // FIXME?
1731       case X86::reloc_riprel_4byte:
1732       case FK_PCRel_4:
1733         switch (Modifier) {
1734         default:
1735           llvm_unreachable("Unimplemented");
1736         case MCSymbolRefExpr::VK_None:
1737           Type = ELF::R_X86_64_PC32;
1738           break;
1739         case MCSymbolRefExpr::VK_PLT:
1740           Type = ELF::R_X86_64_PLT32;
1741           break;
1742         case MCSymbolRefExpr::VK_GOTPCREL:
1743           Type = ELF::R_X86_64_GOTPCREL;
1744           break;
1745         case MCSymbolRefExpr::VK_GOTTPOFF:
1746           Type = ELF::R_X86_64_GOTTPOFF;
1747         break;
1748         case MCSymbolRefExpr::VK_TLSGD:
1749           Type = ELF::R_X86_64_TLSGD;
1750           break;
1751         case MCSymbolRefExpr::VK_TLSLD:
1752           Type = ELF::R_X86_64_TLSLD;
1753           break;
1754         }
1755         break;
1756       case FK_PCRel_2:
1757         assert(Modifier == MCSymbolRefExpr::VK_None);
1758         Type = ELF::R_X86_64_PC16;
1759         break;
1760       }
1761     } else {
1762       switch ((unsigned)Fixup.getKind()) {
1763       default: llvm_unreachable("invalid fixup kind!");
1764       case FK_Data_8: Type = ELF::R_X86_64_64; break;
1765       case X86::reloc_signed_4byte:
1766         assert(isInt<32>(Target.getConstant()));
1767         switch (Modifier) {
1768         default:
1769           llvm_unreachable("Unimplemented");
1770         case MCSymbolRefExpr::VK_None:
1771           Type = ELF::R_X86_64_32S;
1772           break;
1773         case MCSymbolRefExpr::VK_GOT:
1774           Type = ELF::R_X86_64_GOT32;
1775           break;
1776         case MCSymbolRefExpr::VK_GOTPCREL:
1777           Type = ELF::R_X86_64_GOTPCREL;
1778           break;
1779         case MCSymbolRefExpr::VK_TPOFF:
1780           Type = ELF::R_X86_64_TPOFF32;
1781           break;
1782         case MCSymbolRefExpr::VK_DTPOFF:
1783           Type = ELF::R_X86_64_DTPOFF32;
1784           break;
1785         }
1786         break;
1787       case FK_Data_4:
1788         Type = ELF::R_X86_64_32;
1789         break;
1790       case FK_Data_2: Type = ELF::R_X86_64_16; break;
1791       case FK_PCRel_1:
1792       case FK_Data_1: Type = ELF::R_X86_64_8; break;
1793       }
1794     }
1795   } else {
1796     if (IsPCRel) {
1797       switch (Modifier) {
1798       default:
1799         llvm_unreachable("Unimplemented");
1800       case MCSymbolRefExpr::VK_None:
1801         Type = ELF::R_386_PC32;
1802         break;
1803       case MCSymbolRefExpr::VK_PLT:
1804         Type = ELF::R_386_PLT32;
1805         break;
1806       }
1807     } else {
1808       switch ((unsigned)Fixup.getKind()) {
1809       default: llvm_unreachable("invalid fixup kind!");
1810
1811       case X86::reloc_global_offset_table:
1812         Type = ELF::R_386_GOTPC;
1813         break;
1814
1815       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1816       // instead?
1817       case X86::reloc_signed_4byte:
1818       case FK_PCRel_4:
1819       case FK_Data_4:
1820         switch (Modifier) {
1821         default:
1822           llvm_unreachable("Unimplemented");
1823         case MCSymbolRefExpr::VK_None:
1824           Type = ELF::R_386_32;
1825           break;
1826         case MCSymbolRefExpr::VK_GOT:
1827           Type = ELF::R_386_GOT32;
1828           break;
1829         case MCSymbolRefExpr::VK_GOTOFF:
1830           Type = ELF::R_386_GOTOFF;
1831           break;
1832         case MCSymbolRefExpr::VK_TLSGD:
1833           Type = ELF::R_386_TLS_GD;
1834           break;
1835         case MCSymbolRefExpr::VK_TPOFF:
1836           Type = ELF::R_386_TLS_LE_32;
1837           break;
1838         case MCSymbolRefExpr::VK_INDNTPOFF:
1839           Type = ELF::R_386_TLS_IE;
1840           break;
1841         case MCSymbolRefExpr::VK_NTPOFF:
1842           Type = ELF::R_386_TLS_LE;
1843           break;
1844         case MCSymbolRefExpr::VK_GOTNTPOFF:
1845           Type = ELF::R_386_TLS_GOTIE;
1846           break;
1847         case MCSymbolRefExpr::VK_TLSLDM:
1848           Type = ELF::R_386_TLS_LDM;
1849           break;
1850         case MCSymbolRefExpr::VK_DTPOFF:
1851           Type = ELF::R_386_TLS_LDO_32;
1852           break;
1853         }
1854         break;
1855       case FK_Data_2: Type = ELF::R_386_16; break;
1856       case FK_PCRel_1:
1857       case FK_Data_1: Type = ELF::R_386_8; break;
1858       }
1859     }
1860   }
1861
1862   if (RelocNeedsGOT(Modifier))
1863     NeedsGOT = true;
1864
1865   return Type;
1866 }