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