]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Target.cpp
Merge lld trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Target.cpp
1 //===- Target.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Machine-specific things, such as applying relocations, creation of
11 // GOT or PLT entries, etc., are handled in this file.
12 //
13 // Refer the ELF spec for the single letter variables, S, A or P, used
14 // in this file.
15 //
16 // Some functions defined in this file has "relaxTls" as part of their names.
17 // They do peephole optimization for TLS variables by rewriting instructions.
18 // They are not part of the ABI but optional optimization, so you can skip
19 // them if you are not interested in how TLS variables are optimized.
20 // See the following paper for the details.
21 //
22 //   Ulrich Drepper, ELF Handling For Thread-Local Storage
23 //   http://www.akkadia.org/drepper/tls.pdf
24 //
25 //===----------------------------------------------------------------------===//
26
27 #include "Target.h"
28 #include "Error.h"
29 #include "InputFiles.h"
30 #include "Memory.h"
31 #include "OutputSections.h"
32 #include "SymbolTable.h"
33 #include "Symbols.h"
34 #include "SyntheticSections.h"
35 #include "Thunks.h"
36 #include "Writer.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Object/ELF.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/Endian.h"
41
42 using namespace llvm;
43 using namespace llvm::object;
44 using namespace llvm::support::endian;
45 using namespace llvm::ELF;
46
47 std::string lld::toString(uint32_t Type) {
48   StringRef S = getELFRelocationTypeName(elf::Config->EMachine, Type);
49   if (S == "Unknown")
50     return ("Unknown (" + Twine(Type) + ")").str();
51   return S;
52 }
53
54 namespace lld {
55 namespace elf {
56
57 TargetInfo *Target;
58
59 static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }
60 static void or32be(uint8_t *P, int32_t V) { write32be(P, read32be(P) | V); }
61
62 template <class ELFT> static std::string getErrorLoc(const uint8_t *Loc) {
63   for (InputSectionBase *D : InputSections) {
64     auto *IS = dyn_cast_or_null<InputSection>(D);
65     if (!IS || !IS->OutSec)
66       continue;
67
68     uint8_t *ISLoc = cast<OutputSection>(IS->OutSec)->Loc + IS->OutSecOff;
69     if (ISLoc <= Loc && Loc < ISLoc + IS->getSize())
70       return IS->template getLocation<ELFT>(Loc - ISLoc) + ": ";
71   }
72   return "";
73 }
74
75 static std::string getErrorLocation(const uint8_t *Loc) {
76   switch (Config->EKind) {
77   case ELF32LEKind:
78     return getErrorLoc<ELF32LE>(Loc);
79   case ELF32BEKind:
80     return getErrorLoc<ELF32BE>(Loc);
81   case ELF64LEKind:
82     return getErrorLoc<ELF64LE>(Loc);
83   case ELF64BEKind:
84     return getErrorLoc<ELF64BE>(Loc);
85   default:
86     llvm_unreachable("unknown ELF type");
87   }
88 }
89
90 template <unsigned N>
91 static void checkInt(uint8_t *Loc, int64_t V, uint32_t Type) {
92   if (!isInt<N>(V))
93     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
94           " out of range");
95 }
96
97 template <unsigned N>
98 static void checkUInt(uint8_t *Loc, uint64_t V, uint32_t Type) {
99   if (!isUInt<N>(V))
100     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
101           " out of range");
102 }
103
104 template <unsigned N>
105 static void checkIntUInt(uint8_t *Loc, uint64_t V, uint32_t Type) {
106   if (!isInt<N>(V) && !isUInt<N>(V))
107     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
108           " out of range");
109 }
110
111 template <unsigned N>
112 static void checkAlignment(uint8_t *Loc, uint64_t V, uint32_t Type) {
113   if ((V & (N - 1)) != 0)
114     error(getErrorLocation(Loc) + "improper alignment for relocation " +
115           toString(Type));
116 }
117
118 namespace {
119 class X86TargetInfo final : public TargetInfo {
120 public:
121   X86TargetInfo();
122   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
123                      const uint8_t *Loc) const override;
124   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
125   void writeGotPltHeader(uint8_t *Buf) const override;
126   uint32_t getDynRel(uint32_t Type) const override;
127   bool isTlsLocalDynamicRel(uint32_t Type) const override;
128   bool isTlsInitialExecRel(uint32_t Type) const override;
129   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
130   void writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const override;
131   void writePltHeader(uint8_t *Buf) const override;
132   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
133                 int32_t Index, unsigned RelOff) const override;
134   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
135
136   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
137                           RelExpr Expr) const override;
138   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
139   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
140   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
141   void relaxTlsLdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
142 };
143
144 template <class ELFT> class X86_64TargetInfo final : public TargetInfo {
145 public:
146   X86_64TargetInfo();
147   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
148                      const uint8_t *Loc) const override;
149   bool isPicRel(uint32_t Type) const override;
150   bool isTlsLocalDynamicRel(uint32_t Type) const override;
151   bool isTlsInitialExecRel(uint32_t Type) const override;
152   void writeGotPltHeader(uint8_t *Buf) const override;
153   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
154   void writePltHeader(uint8_t *Buf) const override;
155   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
156                 int32_t Index, unsigned RelOff) const override;
157   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
158
159   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
160                           RelExpr Expr) const override;
161   void relaxGot(uint8_t *Loc, uint64_t Val) const override;
162   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
163   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
164   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
165   void relaxTlsLdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
166
167 private:
168   void relaxGotNoPic(uint8_t *Loc, uint64_t Val, uint8_t Op,
169                      uint8_t ModRm) const;
170 };
171
172 class PPCTargetInfo final : public TargetInfo {
173 public:
174   PPCTargetInfo();
175   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
176   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
177                      const uint8_t *Loc) const override;
178 };
179
180 class PPC64TargetInfo final : public TargetInfo {
181 public:
182   PPC64TargetInfo();
183   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
184                      const uint8_t *Loc) const override;
185   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
186                 int32_t Index, unsigned RelOff) const override;
187   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
188 };
189
190 class AArch64TargetInfo final : public TargetInfo {
191 public:
192   AArch64TargetInfo();
193   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
194                      const uint8_t *Loc) const override;
195   bool isPicRel(uint32_t Type) const override;
196   bool isTlsInitialExecRel(uint32_t Type) const override;
197   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
198   void writePltHeader(uint8_t *Buf) const override;
199   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
200                 int32_t Index, unsigned RelOff) const override;
201   bool usesOnlyLowPageBits(uint32_t Type) const override;
202   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
203   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
204                           RelExpr Expr) const override;
205   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
206   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
207   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
208 };
209
210 class AMDGPUTargetInfo final : public TargetInfo {
211 public:
212   AMDGPUTargetInfo();
213   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
214   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
215                      const uint8_t *Loc) const override;
216 };
217
218 class ARMTargetInfo final : public TargetInfo {
219 public:
220   ARMTargetInfo();
221   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
222                      const uint8_t *Loc) const override;
223   bool isPicRel(uint32_t Type) const override;
224   uint32_t getDynRel(uint32_t Type) const override;
225   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
226   bool isTlsLocalDynamicRel(uint32_t Type) const override;
227   bool isTlsInitialExecRel(uint32_t Type) const override;
228   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
229   void writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const override;
230   void writePltHeader(uint8_t *Buf) const override;
231   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
232                 int32_t Index, unsigned RelOff) const override;
233   void addPltSymbols(InputSectionBase *IS, uint64_t Off) const override;
234   void addPltHeaderSymbols(InputSectionBase *ISD) const override;
235   bool needsThunk(RelExpr Expr, uint32_t RelocType, const InputFile *File,
236                   const SymbolBody &S) const override;
237   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
238 };
239
240 template <class ELFT> class MipsTargetInfo final : public TargetInfo {
241 public:
242   MipsTargetInfo();
243   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
244                      const uint8_t *Loc) const override;
245   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
246   bool isPicRel(uint32_t Type) const override;
247   uint32_t getDynRel(uint32_t Type) const override;
248   bool isTlsLocalDynamicRel(uint32_t Type) const override;
249   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
250   void writePltHeader(uint8_t *Buf) const override;
251   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
252                 int32_t Index, unsigned RelOff) const override;
253   bool needsThunk(RelExpr Expr, uint32_t RelocType, const InputFile *File,
254                   const SymbolBody &S) const override;
255   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
256   bool usesOnlyLowPageBits(uint32_t Type) const override;
257 };
258 } // anonymous namespace
259
260 TargetInfo *createTarget() {
261   switch (Config->EMachine) {
262   case EM_386:
263   case EM_IAMCU:
264     return make<X86TargetInfo>();
265   case EM_AARCH64:
266     return make<AArch64TargetInfo>();
267   case EM_AMDGPU:
268     return make<AMDGPUTargetInfo>();
269   case EM_ARM:
270     return make<ARMTargetInfo>();
271   case EM_MIPS:
272     switch (Config->EKind) {
273     case ELF32LEKind:
274       return make<MipsTargetInfo<ELF32LE>>();
275     case ELF32BEKind:
276       return make<MipsTargetInfo<ELF32BE>>();
277     case ELF64LEKind:
278       return make<MipsTargetInfo<ELF64LE>>();
279     case ELF64BEKind:
280       return make<MipsTargetInfo<ELF64BE>>();
281     default:
282       fatal("unsupported MIPS target");
283     }
284   case EM_PPC:
285     return make<PPCTargetInfo>();
286   case EM_PPC64:
287     return make<PPC64TargetInfo>();
288   case EM_X86_64:
289     if (Config->EKind == ELF32LEKind)
290       return make<X86_64TargetInfo<ELF32LE>>();
291     return make<X86_64TargetInfo<ELF64LE>>();
292   }
293   fatal("unknown target machine");
294 }
295
296 TargetInfo::~TargetInfo() {}
297
298 int64_t TargetInfo::getImplicitAddend(const uint8_t *Buf, uint32_t Type) const {
299   return 0;
300 }
301
302 bool TargetInfo::usesOnlyLowPageBits(uint32_t Type) const { return false; }
303
304 bool TargetInfo::needsThunk(RelExpr Expr, uint32_t RelocType,
305                             const InputFile *File, const SymbolBody &S) const {
306   return false;
307 }
308
309 bool TargetInfo::isTlsInitialExecRel(uint32_t Type) const { return false; }
310
311 bool TargetInfo::isTlsLocalDynamicRel(uint32_t Type) const { return false; }
312
313 void TargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
314   writeGotPlt(Buf, S);
315 }
316
317 RelExpr TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
318                                     RelExpr Expr) const {
319   return Expr;
320 }
321
322 void TargetInfo::relaxGot(uint8_t *Loc, uint64_t Val) const {
323   llvm_unreachable("Should not have claimed to be relaxable");
324 }
325
326 void TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
327                                 uint64_t Val) const {
328   llvm_unreachable("Should not have claimed to be relaxable");
329 }
330
331 void TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
332                                 uint64_t Val) const {
333   llvm_unreachable("Should not have claimed to be relaxable");
334 }
335
336 void TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
337                                 uint64_t Val) const {
338   llvm_unreachable("Should not have claimed to be relaxable");
339 }
340
341 void TargetInfo::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
342                                 uint64_t Val) const {
343   llvm_unreachable("Should not have claimed to be relaxable");
344 }
345
346 X86TargetInfo::X86TargetInfo() {
347   CopyRel = R_386_COPY;
348   GotRel = R_386_GLOB_DAT;
349   PltRel = R_386_JUMP_SLOT;
350   IRelativeRel = R_386_IRELATIVE;
351   RelativeRel = R_386_RELATIVE;
352   TlsGotRel = R_386_TLS_TPOFF;
353   TlsModuleIndexRel = R_386_TLS_DTPMOD32;
354   TlsOffsetRel = R_386_TLS_DTPOFF32;
355   GotEntrySize = 4;
356   GotPltEntrySize = 4;
357   PltEntrySize = 16;
358   PltHeaderSize = 16;
359   TlsGdRelaxSkip = 2;
360   // 0xCC is the "int3" (call debug exception handler) instruction.
361   TrapInstr = 0xcccccccc;
362 }
363
364 RelExpr X86TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
365                                   const uint8_t *Loc) const {
366   switch (Type) {
367   case R_386_8:
368   case R_386_16:
369   case R_386_32:
370   case R_386_TLS_LDO_32:
371     return R_ABS;
372   case R_386_TLS_GD:
373     return R_TLSGD;
374   case R_386_TLS_LDM:
375     return R_TLSLD;
376   case R_386_PLT32:
377     return R_PLT_PC;
378   case R_386_PC8:
379   case R_386_PC16:
380   case R_386_PC32:
381     return R_PC;
382   case R_386_GOTPC:
383     return R_GOTONLY_PC_FROM_END;
384   case R_386_TLS_IE:
385     return R_GOT;
386   case R_386_GOT32:
387   case R_386_GOT32X:
388     // These relocations can be calculated in two different ways.
389     // Usual calculation is G + A - GOT what means an offset in GOT table
390     // (R_GOT_FROM_END). When instruction pointed by relocation has no base
391     // register, then relocations can be used when PIC code is disabled. In that
392     // case calculation is G + A, it resolves to an address of entry in GOT
393     // (R_GOT) and not an offset.
394     //
395     // To check that instruction has no base register we scan ModR/M byte.
396     // See "Table 2-2. 32-Bit Addressing Forms with the ModR/M Byte"
397     // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
398     //  64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
399     if ((Loc[-1] & 0xc7) != 0x5)
400       return R_GOT_FROM_END;
401     if (Config->Pic)
402       error(toString(S.File) + ": relocation " + toString(Type) + " against '" +
403             S.getName() +
404             "' without base register can not be used when PIC enabled");
405     return R_GOT;
406   case R_386_TLS_GOTIE:
407     return R_GOT_FROM_END;
408   case R_386_GOTOFF:
409     return R_GOTREL_FROM_END;
410   case R_386_TLS_LE:
411     return R_TLS;
412   case R_386_TLS_LE_32:
413     return R_NEG_TLS;
414   case R_386_NONE:
415     return R_NONE;
416   default:
417     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
418     return R_HINT;
419   }
420 }
421
422 RelExpr X86TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
423                                        RelExpr Expr) const {
424   switch (Expr) {
425   default:
426     return Expr;
427   case R_RELAX_TLS_GD_TO_IE:
428     return R_RELAX_TLS_GD_TO_IE_END;
429   case R_RELAX_TLS_GD_TO_LE:
430     return R_RELAX_TLS_GD_TO_LE_NEG;
431   }
432 }
433
434 void X86TargetInfo::writeGotPltHeader(uint8_t *Buf) const {
435   write32le(Buf, In<ELF32LE>::Dynamic->getVA());
436 }
437
438 void X86TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &S) const {
439   // Entries in .got.plt initially points back to the corresponding
440   // PLT entries with a fixed offset to skip the first instruction.
441   write32le(Buf, S.getPltVA() + 6);
442 }
443
444 void X86TargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
445   // An x86 entry is the address of the ifunc resolver function.
446   write32le(Buf, S.getVA());
447 }
448
449 uint32_t X86TargetInfo::getDynRel(uint32_t Type) const {
450   if (Type == R_386_TLS_LE)
451     return R_386_TLS_TPOFF;
452   if (Type == R_386_TLS_LE_32)
453     return R_386_TLS_TPOFF32;
454   return Type;
455 }
456
457 bool X86TargetInfo::isTlsLocalDynamicRel(uint32_t Type) const {
458   return Type == R_386_TLS_LDO_32 || Type == R_386_TLS_LDM;
459 }
460
461 bool X86TargetInfo::isTlsInitialExecRel(uint32_t Type) const {
462   return Type == R_386_TLS_IE || Type == R_386_TLS_GOTIE;
463 }
464
465 void X86TargetInfo::writePltHeader(uint8_t *Buf) const {
466   if (Config->Pic) {
467     const uint8_t V[] = {
468         0xff, 0xb3, 0x04, 0x00, 0x00, 0x00, // pushl GOTPLT+4(%ebx)
469         0xff, 0xa3, 0x08, 0x00, 0x00, 0x00, // jmp *GOTPLT+8(%ebx)
470         0x90, 0x90, 0x90, 0x90              // nop
471     };
472     memcpy(Buf, V, sizeof(V));
473
474     uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize();
475     uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA() - Ebx;
476     write32le(Buf + 2, GotPlt + 4);
477     write32le(Buf + 8, GotPlt + 8);
478     return;
479   }
480
481   const uint8_t PltData[] = {
482       0xff, 0x35, 0x00, 0x00, 0x00, 0x00, // pushl (GOTPLT+4)
483       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *(GOTPLT+8)
484       0x90, 0x90, 0x90, 0x90              // nop
485   };
486   memcpy(Buf, PltData, sizeof(PltData));
487   uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA();
488   write32le(Buf + 2, GotPlt + 4);
489   write32le(Buf + 8, GotPlt + 8);
490 }
491
492 void X86TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
493                              uint64_t PltEntryAddr, int32_t Index,
494                              unsigned RelOff) const {
495   const uint8_t Inst[] = {
496       0xff, 0x00, 0x00, 0x00, 0x00, 0x00, // jmp *foo_in_GOT|*foo@GOT(%ebx)
497       0x68, 0x00, 0x00, 0x00, 0x00,       // pushl $reloc_offset
498       0xe9, 0x00, 0x00, 0x00, 0x00        // jmp .PLT0@PC
499   };
500   memcpy(Buf, Inst, sizeof(Inst));
501
502   if (Config->Pic) {
503     // jmp *foo@GOT(%ebx)
504     uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize();
505     Buf[1] = 0xa3;
506     write32le(Buf + 2, GotPltEntryAddr - Ebx);
507   } else {
508     // jmp *foo_in_GOT
509     Buf[1] = 0x25;
510     write32le(Buf + 2, GotPltEntryAddr);
511   }
512
513   write32le(Buf + 7, RelOff);
514   write32le(Buf + 12, -Index * PltEntrySize - PltHeaderSize - 16);
515 }
516
517 int64_t X86TargetInfo::getImplicitAddend(const uint8_t *Buf,
518                                          uint32_t Type) const {
519   switch (Type) {
520   default:
521     return 0;
522   case R_386_8:
523   case R_386_PC8:
524     return SignExtend64<8>(*Buf);
525   case R_386_16:
526   case R_386_PC16:
527     return SignExtend64<16>(read16le(Buf));
528   case R_386_32:
529   case R_386_GOT32:
530   case R_386_GOT32X:
531   case R_386_GOTOFF:
532   case R_386_GOTPC:
533   case R_386_PC32:
534   case R_386_PLT32:
535   case R_386_TLS_LE:
536     return SignExtend64<32>(read32le(Buf));
537   }
538 }
539
540 void X86TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
541                                 uint64_t Val) const {
542   // R_386_{PC,}{8,16} are not part of the i386 psABI, but they are
543   // being used for some 16-bit programs such as boot loaders, so
544   // we want to support them.
545   switch (Type) {
546   case R_386_8:
547     checkUInt<8>(Loc, Val, Type);
548     *Loc = Val;
549     break;
550   case R_386_PC8:
551     checkInt<8>(Loc, Val, Type);
552     *Loc = Val;
553     break;
554   case R_386_16:
555     checkUInt<16>(Loc, Val, Type);
556     write16le(Loc, Val);
557     break;
558   case R_386_PC16:
559     checkInt<16>(Loc, Val, Type);
560     write16le(Loc, Val);
561     break;
562   default:
563     checkInt<32>(Loc, Val, Type);
564     write32le(Loc, Val);
565   }
566 }
567
568 void X86TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
569                                    uint64_t Val) const {
570   // Convert
571   //   leal x@tlsgd(, %ebx, 1),
572   //   call __tls_get_addr@plt
573   // to
574   //   movl %gs:0,%eax
575   //   subl $x@ntpoff,%eax
576   const uint8_t Inst[] = {
577       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0, %eax
578       0x81, 0xe8, 0x00, 0x00, 0x00, 0x00  // subl 0(%ebx), %eax
579   };
580   memcpy(Loc - 3, Inst, sizeof(Inst));
581   write32le(Loc + 5, Val);
582 }
583
584 void X86TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
585                                    uint64_t Val) const {
586   // Convert
587   //   leal x@tlsgd(, %ebx, 1),
588   //   call __tls_get_addr@plt
589   // to
590   //   movl %gs:0, %eax
591   //   addl x@gotntpoff(%ebx), %eax
592   const uint8_t Inst[] = {
593       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0, %eax
594       0x03, 0x83, 0x00, 0x00, 0x00, 0x00  // addl 0(%ebx), %eax
595   };
596   memcpy(Loc - 3, Inst, sizeof(Inst));
597   write32le(Loc + 5, Val);
598 }
599
600 // In some conditions, relocations can be optimized to avoid using GOT.
601 // This function does that for Initial Exec to Local Exec case.
602 void X86TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
603                                    uint64_t Val) const {
604   // Ulrich's document section 6.2 says that @gotntpoff can
605   // be used with MOVL or ADDL instructions.
606   // @indntpoff is similar to @gotntpoff, but for use in
607   // position dependent code.
608   uint8_t Reg = (Loc[-1] >> 3) & 7;
609
610   if (Type == R_386_TLS_IE) {
611     if (Loc[-1] == 0xa1) {
612       // "movl foo@indntpoff,%eax" -> "movl $foo,%eax"
613       // This case is different from the generic case below because
614       // this is a 5 byte instruction while below is 6 bytes.
615       Loc[-1] = 0xb8;
616     } else if (Loc[-2] == 0x8b) {
617       // "movl foo@indntpoff,%reg" -> "movl $foo,%reg"
618       Loc[-2] = 0xc7;
619       Loc[-1] = 0xc0 | Reg;
620     } else {
621       // "addl foo@indntpoff,%reg" -> "addl $foo,%reg"
622       Loc[-2] = 0x81;
623       Loc[-1] = 0xc0 | Reg;
624     }
625   } else {
626     assert(Type == R_386_TLS_GOTIE);
627     if (Loc[-2] == 0x8b) {
628       // "movl foo@gottpoff(%rip),%reg" -> "movl $foo,%reg"
629       Loc[-2] = 0xc7;
630       Loc[-1] = 0xc0 | Reg;
631     } else {
632       // "addl foo@gotntpoff(%rip),%reg" -> "leal foo(%reg),%reg"
633       Loc[-2] = 0x8d;
634       Loc[-1] = 0x80 | (Reg << 3) | Reg;
635     }
636   }
637   write32le(Loc, Val);
638 }
639
640 void X86TargetInfo::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
641                                    uint64_t Val) const {
642   if (Type == R_386_TLS_LDO_32) {
643     write32le(Loc, Val);
644     return;
645   }
646
647   // Convert
648   //   leal foo(%reg),%eax
649   //   call ___tls_get_addr
650   // to
651   //   movl %gs:0,%eax
652   //   nop
653   //   leal 0(%esi,1),%esi
654   const uint8_t Inst[] = {
655       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0,%eax
656       0x90,                               // nop
657       0x8d, 0x74, 0x26, 0x00              // leal 0(%esi,1),%esi
658   };
659   memcpy(Loc - 2, Inst, sizeof(Inst));
660 }
661
662 template <class ELFT> X86_64TargetInfo<ELFT>::X86_64TargetInfo() {
663   CopyRel = R_X86_64_COPY;
664   GotRel = R_X86_64_GLOB_DAT;
665   PltRel = R_X86_64_JUMP_SLOT;
666   RelativeRel = R_X86_64_RELATIVE;
667   IRelativeRel = R_X86_64_IRELATIVE;
668   TlsGotRel = R_X86_64_TPOFF64;
669   TlsModuleIndexRel = R_X86_64_DTPMOD64;
670   TlsOffsetRel = R_X86_64_DTPOFF64;
671   GotEntrySize = 8;
672   GotPltEntrySize = 8;
673   PltEntrySize = 16;
674   PltHeaderSize = 16;
675   TlsGdRelaxSkip = 2;
676   // Align to the large page size (known as a superpage or huge page).
677   // FreeBSD automatically promotes large, superpage-aligned allocations.
678   DefaultImageBase = 0x200000;
679   // 0xCC is the "int3" (call debug exception handler) instruction.
680   TrapInstr = 0xcccccccc;
681 }
682
683 template <class ELFT>
684 RelExpr X86_64TargetInfo<ELFT>::getRelExpr(uint32_t Type, const SymbolBody &S,
685                                            const uint8_t *Loc) const {
686   switch (Type) {
687   case R_X86_64_8:
688   case R_X86_64_16:
689   case R_X86_64_32:
690   case R_X86_64_32S:
691   case R_X86_64_64:
692   case R_X86_64_DTPOFF32:
693   case R_X86_64_DTPOFF64:
694     return R_ABS;
695   case R_X86_64_TPOFF32:
696     return R_TLS;
697   case R_X86_64_TLSLD:
698     return R_TLSLD_PC;
699   case R_X86_64_TLSGD:
700     return R_TLSGD_PC;
701   case R_X86_64_SIZE32:
702   case R_X86_64_SIZE64:
703     return R_SIZE;
704   case R_X86_64_PLT32:
705     return R_PLT_PC;
706   case R_X86_64_PC32:
707   case R_X86_64_PC64:
708     return R_PC;
709   case R_X86_64_GOT32:
710   case R_X86_64_GOT64:
711     return R_GOT_FROM_END;
712   case R_X86_64_GOTPCREL:
713   case R_X86_64_GOTPCRELX:
714   case R_X86_64_REX_GOTPCRELX:
715   case R_X86_64_GOTTPOFF:
716     return R_GOT_PC;
717   case R_X86_64_NONE:
718     return R_NONE;
719   default:
720     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
721     return R_HINT;
722   }
723 }
724
725 template <class ELFT>
726 void X86_64TargetInfo<ELFT>::writeGotPltHeader(uint8_t *Buf) const {
727   // The first entry holds the value of _DYNAMIC. It is not clear why that is
728   // required, but it is documented in the psabi and the glibc dynamic linker
729   // seems to use it (note that this is relevant for linking ld.so, not any
730   // other program).
731   write64le(Buf, In<ELFT>::Dynamic->getVA());
732 }
733
734 template <class ELFT>
735 void X86_64TargetInfo<ELFT>::writeGotPlt(uint8_t *Buf,
736                                          const SymbolBody &S) const {
737   // See comments in X86TargetInfo::writeGotPlt.
738   write32le(Buf, S.getPltVA() + 6);
739 }
740
741 template <class ELFT>
742 void X86_64TargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const {
743   const uint8_t PltData[] = {
744       0xff, 0x35, 0x00, 0x00, 0x00, 0x00, // pushq GOTPLT+8(%rip)
745       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *GOTPLT+16(%rip)
746       0x0f, 0x1f, 0x40, 0x00              // nop
747   };
748   memcpy(Buf, PltData, sizeof(PltData));
749   uint64_t GotPlt = In<ELFT>::GotPlt->getVA();
750   uint64_t Plt = In<ELFT>::Plt->getVA();
751   write32le(Buf + 2, GotPlt - Plt + 2); // GOTPLT+8
752   write32le(Buf + 8, GotPlt - Plt + 4); // GOTPLT+16
753 }
754
755 template <class ELFT>
756 void X86_64TargetInfo<ELFT>::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
757                                       uint64_t PltEntryAddr, int32_t Index,
758                                       unsigned RelOff) const {
759   const uint8_t Inst[] = {
760       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmpq *got(%rip)
761       0x68, 0x00, 0x00, 0x00, 0x00,       // pushq <relocation index>
762       0xe9, 0x00, 0x00, 0x00, 0x00        // jmpq plt[0]
763   };
764   memcpy(Buf, Inst, sizeof(Inst));
765
766   write32le(Buf + 2, GotPltEntryAddr - PltEntryAddr - 6);
767   write32le(Buf + 7, Index);
768   write32le(Buf + 12, -Index * PltEntrySize - PltHeaderSize - 16);
769 }
770
771 template <class ELFT>
772 bool X86_64TargetInfo<ELFT>::isPicRel(uint32_t Type) const {
773   return Type != R_X86_64_PC32 && Type != R_X86_64_32;
774 }
775
776 template <class ELFT>
777 bool X86_64TargetInfo<ELFT>::isTlsInitialExecRel(uint32_t Type) const {
778   return Type == R_X86_64_GOTTPOFF;
779 }
780
781 template <class ELFT>
782 bool X86_64TargetInfo<ELFT>::isTlsLocalDynamicRel(uint32_t Type) const {
783   return Type == R_X86_64_DTPOFF32 || Type == R_X86_64_DTPOFF64 ||
784          Type == R_X86_64_TLSLD;
785 }
786
787 template <class ELFT>
788 void X86_64TargetInfo<ELFT>::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
789                                             uint64_t Val) const {
790   // Convert
791   //   .byte 0x66
792   //   leaq x@tlsgd(%rip), %rdi
793   //   .word 0x6666
794   //   rex64
795   //   call __tls_get_addr@plt
796   // to
797   //   mov %fs:0x0,%rax
798   //   lea x@tpoff,%rax
799   const uint8_t Inst[] = {
800       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0x0,%rax
801       0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00              // lea x@tpoff,%rax
802   };
803   memcpy(Loc - 4, Inst, sizeof(Inst));
804
805   // The original code used a pc relative relocation and so we have to
806   // compensate for the -4 in had in the addend.
807   write32le(Loc + 8, Val + 4);
808 }
809
810 template <class ELFT>
811 void X86_64TargetInfo<ELFT>::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
812                                             uint64_t Val) const {
813   // Convert
814   //   .byte 0x66
815   //   leaq x@tlsgd(%rip), %rdi
816   //   .word 0x6666
817   //   rex64
818   //   call __tls_get_addr@plt
819   // to
820   //   mov %fs:0x0,%rax
821   //   addq x@tpoff,%rax
822   const uint8_t Inst[] = {
823       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0x0,%rax
824       0x48, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00              // addq x@tpoff,%rax
825   };
826   memcpy(Loc - 4, Inst, sizeof(Inst));
827
828   // Both code sequences are PC relatives, but since we are moving the constant
829   // forward by 8 bytes we have to subtract the value by 8.
830   write32le(Loc + 8, Val - 8);
831 }
832
833 // In some conditions, R_X86_64_GOTTPOFF relocation can be optimized to
834 // R_X86_64_TPOFF32 so that it does not use GOT.
835 template <class ELFT>
836 void X86_64TargetInfo<ELFT>::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
837                                             uint64_t Val) const {
838   uint8_t *Inst = Loc - 3;
839   uint8_t Reg = Loc[-1] >> 3;
840   uint8_t *RegSlot = Loc - 1;
841
842   // Note that ADD with RSP or R12 is converted to ADD instead of LEA
843   // because LEA with these registers needs 4 bytes to encode and thus
844   // wouldn't fit the space.
845
846   if (memcmp(Inst, "\x48\x03\x25", 3) == 0) {
847     // "addq foo@gottpoff(%rip),%rsp" -> "addq $foo,%rsp"
848     memcpy(Inst, "\x48\x81\xc4", 3);
849   } else if (memcmp(Inst, "\x4c\x03\x25", 3) == 0) {
850     // "addq foo@gottpoff(%rip),%r12" -> "addq $foo,%r12"
851     memcpy(Inst, "\x49\x81\xc4", 3);
852   } else if (memcmp(Inst, "\x4c\x03", 2) == 0) {
853     // "addq foo@gottpoff(%rip),%r[8-15]" -> "leaq foo(%r[8-15]),%r[8-15]"
854     memcpy(Inst, "\x4d\x8d", 2);
855     *RegSlot = 0x80 | (Reg << 3) | Reg;
856   } else if (memcmp(Inst, "\x48\x03", 2) == 0) {
857     // "addq foo@gottpoff(%rip),%reg -> "leaq foo(%reg),%reg"
858     memcpy(Inst, "\x48\x8d", 2);
859     *RegSlot = 0x80 | (Reg << 3) | Reg;
860   } else if (memcmp(Inst, "\x4c\x8b", 2) == 0) {
861     // "movq foo@gottpoff(%rip),%r[8-15]" -> "movq $foo,%r[8-15]"
862     memcpy(Inst, "\x49\xc7", 2);
863     *RegSlot = 0xc0 | Reg;
864   } else if (memcmp(Inst, "\x48\x8b", 2) == 0) {
865     // "movq foo@gottpoff(%rip),%reg" -> "movq $foo,%reg"
866     memcpy(Inst, "\x48\xc7", 2);
867     *RegSlot = 0xc0 | Reg;
868   } else {
869     error(getErrorLocation(Loc - 3) +
870           "R_X86_64_GOTTPOFF must be used in MOVQ or ADDQ instructions only");
871   }
872
873   // The original code used a PC relative relocation.
874   // Need to compensate for the -4 it had in the addend.
875   write32le(Loc, Val + 4);
876 }
877
878 template <class ELFT>
879 void X86_64TargetInfo<ELFT>::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
880                                             uint64_t Val) const {
881   // Convert
882   //   leaq bar@tlsld(%rip), %rdi
883   //   callq __tls_get_addr@PLT
884   //   leaq bar@dtpoff(%rax), %rcx
885   // to
886   //   .word 0x6666
887   //   .byte 0x66
888   //   mov %fs:0,%rax
889   //   leaq bar@tpoff(%rax), %rcx
890   if (Type == R_X86_64_DTPOFF64) {
891     write64le(Loc, Val);
892     return;
893   }
894   if (Type == R_X86_64_DTPOFF32) {
895     write32le(Loc, Val);
896     return;
897   }
898
899   const uint8_t Inst[] = {
900       0x66, 0x66,                                          // .word 0x6666
901       0x66,                                                // .byte 0x66
902       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00 // mov %fs:0,%rax
903   };
904   memcpy(Loc - 3, Inst, sizeof(Inst));
905 }
906
907 template <class ELFT>
908 void X86_64TargetInfo<ELFT>::relocateOne(uint8_t *Loc, uint32_t Type,
909                                          uint64_t Val) const {
910   switch (Type) {
911   case R_X86_64_8:
912     checkUInt<8>(Loc, Val, Type);
913     *Loc = Val;
914     break;
915   case R_X86_64_16:
916     checkUInt<16>(Loc, Val, Type);
917     write16le(Loc, Val);
918     break;
919   case R_X86_64_32:
920     checkUInt<32>(Loc, Val, Type);
921     write32le(Loc, Val);
922     break;
923   case R_X86_64_32S:
924   case R_X86_64_TPOFF32:
925   case R_X86_64_GOT32:
926   case R_X86_64_GOTPCREL:
927   case R_X86_64_GOTPCRELX:
928   case R_X86_64_REX_GOTPCRELX:
929   case R_X86_64_PC32:
930   case R_X86_64_GOTTPOFF:
931   case R_X86_64_PLT32:
932   case R_X86_64_TLSGD:
933   case R_X86_64_TLSLD:
934   case R_X86_64_DTPOFF32:
935   case R_X86_64_SIZE32:
936     checkInt<32>(Loc, Val, Type);
937     write32le(Loc, Val);
938     break;
939   case R_X86_64_64:
940   case R_X86_64_DTPOFF64:
941   case R_X86_64_GLOB_DAT:
942   case R_X86_64_PC64:
943   case R_X86_64_SIZE64:
944   case R_X86_64_GOT64:
945     write64le(Loc, Val);
946     break;
947   default:
948     llvm_unreachable("unexpected relocation");
949   }
950 }
951
952 template <class ELFT>
953 RelExpr X86_64TargetInfo<ELFT>::adjustRelaxExpr(uint32_t Type,
954                                                 const uint8_t *Data,
955                                                 RelExpr RelExpr) const {
956   if (Type != R_X86_64_GOTPCRELX && Type != R_X86_64_REX_GOTPCRELX)
957     return RelExpr;
958   const uint8_t Op = Data[-2];
959   const uint8_t ModRm = Data[-1];
960
961   // FIXME: When PIC is disabled and foo is defined locally in the
962   // lower 32 bit address space, memory operand in mov can be converted into
963   // immediate operand. Otherwise, mov must be changed to lea. We support only
964   // latter relaxation at this moment.
965   if (Op == 0x8b)
966     return R_RELAX_GOT_PC;
967
968   // Relax call and jmp.
969   if (Op == 0xff && (ModRm == 0x15 || ModRm == 0x25))
970     return R_RELAX_GOT_PC;
971
972   // Relaxation of test, adc, add, and, cmp, or, sbb, sub, xor.
973   // If PIC then no relaxation is available.
974   // We also don't relax test/binop instructions without REX byte,
975   // they are 32bit operations and not common to have.
976   assert(Type == R_X86_64_REX_GOTPCRELX);
977   return Config->Pic ? RelExpr : R_RELAX_GOT_PC_NOPIC;
978 }
979
980 // A subset of relaxations can only be applied for no-PIC. This method
981 // handles such relaxations. Instructions encoding information was taken from:
982 // "Intel 64 and IA-32 Architectures Software Developer's Manual V2"
983 // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
984 //    64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
985 template <class ELFT>
986 void X86_64TargetInfo<ELFT>::relaxGotNoPic(uint8_t *Loc, uint64_t Val,
987                                            uint8_t Op, uint8_t ModRm) const {
988   const uint8_t Rex = Loc[-3];
989   // Convert "test %reg, foo@GOTPCREL(%rip)" to "test $foo, %reg".
990   if (Op == 0x85) {
991     // See "TEST-Logical Compare" (4-428 Vol. 2B),
992     // TEST r/m64, r64 uses "full" ModR / M byte (no opcode extension).
993
994     // ModR/M byte has form XX YYY ZZZ, where
995     // YYY is MODRM.reg(register 2), ZZZ is MODRM.rm(register 1).
996     // XX has different meanings:
997     // 00: The operand's memory address is in reg1.
998     // 01: The operand's memory address is reg1 + a byte-sized displacement.
999     // 10: The operand's memory address is reg1 + a word-sized displacement.
1000     // 11: The operand is reg1 itself.
1001     // If an instruction requires only one operand, the unused reg2 field
1002     // holds extra opcode bits rather than a register code
1003     // 0xC0 == 11 000 000 binary.
1004     // 0x38 == 00 111 000 binary.
1005     // We transfer reg2 to reg1 here as operand.
1006     // See "2.1.3 ModR/M and SIB Bytes" (Vol. 2A 2-3).
1007     Loc[-1] = 0xc0 | (ModRm & 0x38) >> 3; // ModR/M byte.
1008
1009     // Change opcode from TEST r/m64, r64 to TEST r/m64, imm32
1010     // See "TEST-Logical Compare" (4-428 Vol. 2B).
1011     Loc[-2] = 0xf7;
1012
1013     // Move R bit to the B bit in REX byte.
1014     // REX byte is encoded as 0100WRXB, where
1015     // 0100 is 4bit fixed pattern.
1016     // REX.W When 1, a 64-bit operand size is used. Otherwise, when 0, the
1017     //   default operand size is used (which is 32-bit for most but not all
1018     //   instructions).
1019     // REX.R This 1-bit value is an extension to the MODRM.reg field.
1020     // REX.X This 1-bit value is an extension to the SIB.index field.
1021     // REX.B This 1-bit value is an extension to the MODRM.rm field or the
1022     // SIB.base field.
1023     // See "2.2.1.2 More on REX Prefix Fields " (2-8 Vol. 2A).
1024     Loc[-3] = (Rex & ~0x4) | (Rex & 0x4) >> 2;
1025     write32le(Loc, Val);
1026     return;
1027   }
1028
1029   // If we are here then we need to relax the adc, add, and, cmp, or, sbb, sub
1030   // or xor operations.
1031
1032   // Convert "binop foo@GOTPCREL(%rip), %reg" to "binop $foo, %reg".
1033   // Logic is close to one for test instruction above, but we also
1034   // write opcode extension here, see below for details.
1035   Loc[-1] = 0xc0 | (ModRm & 0x38) >> 3 | (Op & 0x3c); // ModR/M byte.
1036
1037   // Primary opcode is 0x81, opcode extension is one of:
1038   // 000b = ADD, 001b is OR, 010b is ADC, 011b is SBB,
1039   // 100b is AND, 101b is SUB, 110b is XOR, 111b is CMP.
1040   // This value was wrote to MODRM.reg in a line above.
1041   // See "3.2 INSTRUCTIONS (A-M)" (Vol. 2A 3-15),
1042   // "INSTRUCTION SET REFERENCE, N-Z" (Vol. 2B 4-1) for
1043   // descriptions about each operation.
1044   Loc[-2] = 0x81;
1045   Loc[-3] = (Rex & ~0x4) | (Rex & 0x4) >> 2;
1046   write32le(Loc, Val);
1047 }
1048
1049 template <class ELFT>
1050 void X86_64TargetInfo<ELFT>::relaxGot(uint8_t *Loc, uint64_t Val) const {
1051   const uint8_t Op = Loc[-2];
1052   const uint8_t ModRm = Loc[-1];
1053
1054   // Convert "mov foo@GOTPCREL(%rip),%reg" to "lea foo(%rip),%reg".
1055   if (Op == 0x8b) {
1056     Loc[-2] = 0x8d;
1057     write32le(Loc, Val);
1058     return;
1059   }
1060
1061   if (Op != 0xff) {
1062     // We are relaxing a rip relative to an absolute, so compensate
1063     // for the old -4 addend.
1064     assert(!Config->Pic);
1065     relaxGotNoPic(Loc, Val + 4, Op, ModRm);
1066     return;
1067   }
1068
1069   // Convert call/jmp instructions.
1070   if (ModRm == 0x15) {
1071     // ABI says we can convert "call *foo@GOTPCREL(%rip)" to "nop; call foo".
1072     // Instead we convert to "addr32 call foo" where addr32 is an instruction
1073     // prefix. That makes result expression to be a single instruction.
1074     Loc[-2] = 0x67; // addr32 prefix
1075     Loc[-1] = 0xe8; // call
1076     write32le(Loc, Val);
1077     return;
1078   }
1079
1080   // Convert "jmp *foo@GOTPCREL(%rip)" to "jmp foo; nop".
1081   // jmp doesn't return, so it is fine to use nop here, it is just a stub.
1082   assert(ModRm == 0x25);
1083   Loc[-2] = 0xe9; // jmp
1084   Loc[3] = 0x90;  // nop
1085   write32le(Loc - 1, Val + 1);
1086 }
1087
1088 // Relocation masks following the #lo(value), #hi(value), #ha(value),
1089 // #higher(value), #highera(value), #highest(value), and #highesta(value)
1090 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
1091 // document.
1092 static uint16_t applyPPCLo(uint64_t V) { return V; }
1093 static uint16_t applyPPCHi(uint64_t V) { return V >> 16; }
1094 static uint16_t applyPPCHa(uint64_t V) { return (V + 0x8000) >> 16; }
1095 static uint16_t applyPPCHigher(uint64_t V) { return V >> 32; }
1096 static uint16_t applyPPCHighera(uint64_t V) { return (V + 0x8000) >> 32; }
1097 static uint16_t applyPPCHighest(uint64_t V) { return V >> 48; }
1098 static uint16_t applyPPCHighesta(uint64_t V) { return (V + 0x8000) >> 48; }
1099
1100 PPCTargetInfo::PPCTargetInfo() {}
1101
1102 void PPCTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1103                                 uint64_t Val) const {
1104   switch (Type) {
1105   case R_PPC_ADDR16_HA:
1106     write16be(Loc, applyPPCHa(Val));
1107     break;
1108   case R_PPC_ADDR16_LO:
1109     write16be(Loc, applyPPCLo(Val));
1110     break;
1111   case R_PPC_ADDR32:
1112   case R_PPC_REL32:
1113     write32be(Loc, Val);
1114     break;
1115   case R_PPC_REL24:
1116     or32be(Loc, Val & 0x3FFFFFC);
1117     break;
1118   default:
1119     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1120   }
1121 }
1122
1123 RelExpr PPCTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1124                                   const uint8_t *Loc) const {
1125   switch (Type) {
1126   case R_PPC_REL24:
1127   case R_PPC_REL32:
1128     return R_PC;
1129   default:
1130     return R_ABS;
1131   }
1132 }
1133
1134 PPC64TargetInfo::PPC64TargetInfo() {
1135   PltRel = GotRel = R_PPC64_GLOB_DAT;
1136   RelativeRel = R_PPC64_RELATIVE;
1137   GotEntrySize = 8;
1138   GotPltEntrySize = 8;
1139   PltEntrySize = 32;
1140   PltHeaderSize = 0;
1141
1142   // We need 64K pages (at least under glibc/Linux, the loader won't
1143   // set different permissions on a finer granularity than that).
1144   DefaultMaxPageSize = 65536;
1145
1146   // The PPC64 ELF ABI v1 spec, says:
1147   //
1148   //   It is normally desirable to put segments with different characteristics
1149   //   in separate 256 Mbyte portions of the address space, to give the
1150   //   operating system full paging flexibility in the 64-bit address space.
1151   //
1152   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
1153   // use 0x10000000 as the starting address.
1154   DefaultImageBase = 0x10000000;
1155 }
1156
1157 static uint64_t PPC64TocOffset = 0x8000;
1158
1159 uint64_t getPPC64TocBase() {
1160   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
1161   // TOC starts where the first of these sections starts. We always create a
1162   // .got when we see a relocation that uses it, so for us the start is always
1163   // the .got.
1164   uint64_t TocVA = In<ELF64BE>::Got->getVA();
1165
1166   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
1167   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
1168   // code (crt1.o) assumes that you can get from the TOC base to the
1169   // start of the .toc section with only a single (signed) 16-bit relocation.
1170   return TocVA + PPC64TocOffset;
1171 }
1172
1173 RelExpr PPC64TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1174                                     const uint8_t *Loc) const {
1175   switch (Type) {
1176   default:
1177     return R_ABS;
1178   case R_PPC64_TOC16:
1179   case R_PPC64_TOC16_DS:
1180   case R_PPC64_TOC16_HA:
1181   case R_PPC64_TOC16_HI:
1182   case R_PPC64_TOC16_LO:
1183   case R_PPC64_TOC16_LO_DS:
1184     return R_GOTREL;
1185   case R_PPC64_TOC:
1186     return R_PPC_TOC;
1187   case R_PPC64_REL24:
1188     return R_PPC_PLT_OPD;
1189   }
1190 }
1191
1192 void PPC64TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1193                                uint64_t PltEntryAddr, int32_t Index,
1194                                unsigned RelOff) const {
1195   uint64_t Off = GotPltEntryAddr - getPPC64TocBase();
1196
1197   // FIXME: What we should do, in theory, is get the offset of the function
1198   // descriptor in the .opd section, and use that as the offset from %r2 (the
1199   // TOC-base pointer). Instead, we have the GOT-entry offset, and that will
1200   // be a pointer to the function descriptor in the .opd section. Using
1201   // this scheme is simpler, but requires an extra indirection per PLT dispatch.
1202
1203   write32be(Buf, 0xf8410028);                       // std %r2, 40(%r1)
1204   write32be(Buf + 4, 0x3d620000 | applyPPCHa(Off)); // addis %r11, %r2, X@ha
1205   write32be(Buf + 8, 0xe98b0000 | applyPPCLo(Off)); // ld %r12, X@l(%r11)
1206   write32be(Buf + 12, 0xe96c0000);                  // ld %r11,0(%r12)
1207   write32be(Buf + 16, 0x7d6903a6);                  // mtctr %r11
1208   write32be(Buf + 20, 0xe84c0008);                  // ld %r2,8(%r12)
1209   write32be(Buf + 24, 0xe96c0010);                  // ld %r11,16(%r12)
1210   write32be(Buf + 28, 0x4e800420);                  // bctr
1211 }
1212
1213 static std::pair<uint32_t, uint64_t> toAddr16Rel(uint32_t Type, uint64_t Val) {
1214   uint64_t V = Val - PPC64TocOffset;
1215   switch (Type) {
1216   case R_PPC64_TOC16:
1217     return {R_PPC64_ADDR16, V};
1218   case R_PPC64_TOC16_DS:
1219     return {R_PPC64_ADDR16_DS, V};
1220   case R_PPC64_TOC16_HA:
1221     return {R_PPC64_ADDR16_HA, V};
1222   case R_PPC64_TOC16_HI:
1223     return {R_PPC64_ADDR16_HI, V};
1224   case R_PPC64_TOC16_LO:
1225     return {R_PPC64_ADDR16_LO, V};
1226   case R_PPC64_TOC16_LO_DS:
1227     return {R_PPC64_ADDR16_LO_DS, V};
1228   default:
1229     return {Type, Val};
1230   }
1231 }
1232
1233 void PPC64TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1234                                   uint64_t Val) const {
1235   // For a TOC-relative relocation, proceed in terms of the corresponding
1236   // ADDR16 relocation type.
1237   std::tie(Type, Val) = toAddr16Rel(Type, Val);
1238
1239   switch (Type) {
1240   case R_PPC64_ADDR14: {
1241     checkAlignment<4>(Loc, Val, Type);
1242     // Preserve the AA/LK bits in the branch instruction
1243     uint8_t AALK = Loc[3];
1244     write16be(Loc + 2, (AALK & 3) | (Val & 0xfffc));
1245     break;
1246   }
1247   case R_PPC64_ADDR16:
1248     checkInt<16>(Loc, Val, Type);
1249     write16be(Loc, Val);
1250     break;
1251   case R_PPC64_ADDR16_DS:
1252     checkInt<16>(Loc, Val, Type);
1253     write16be(Loc, (read16be(Loc) & 3) | (Val & ~3));
1254     break;
1255   case R_PPC64_ADDR16_HA:
1256   case R_PPC64_REL16_HA:
1257     write16be(Loc, applyPPCHa(Val));
1258     break;
1259   case R_PPC64_ADDR16_HI:
1260   case R_PPC64_REL16_HI:
1261     write16be(Loc, applyPPCHi(Val));
1262     break;
1263   case R_PPC64_ADDR16_HIGHER:
1264     write16be(Loc, applyPPCHigher(Val));
1265     break;
1266   case R_PPC64_ADDR16_HIGHERA:
1267     write16be(Loc, applyPPCHighera(Val));
1268     break;
1269   case R_PPC64_ADDR16_HIGHEST:
1270     write16be(Loc, applyPPCHighest(Val));
1271     break;
1272   case R_PPC64_ADDR16_HIGHESTA:
1273     write16be(Loc, applyPPCHighesta(Val));
1274     break;
1275   case R_PPC64_ADDR16_LO:
1276     write16be(Loc, applyPPCLo(Val));
1277     break;
1278   case R_PPC64_ADDR16_LO_DS:
1279   case R_PPC64_REL16_LO:
1280     write16be(Loc, (read16be(Loc) & 3) | (applyPPCLo(Val) & ~3));
1281     break;
1282   case R_PPC64_ADDR32:
1283   case R_PPC64_REL32:
1284     checkInt<32>(Loc, Val, Type);
1285     write32be(Loc, Val);
1286     break;
1287   case R_PPC64_ADDR64:
1288   case R_PPC64_REL64:
1289   case R_PPC64_TOC:
1290     write64be(Loc, Val);
1291     break;
1292   case R_PPC64_REL24: {
1293     uint32_t Mask = 0x03FFFFFC;
1294     checkInt<24>(Loc, Val, Type);
1295     write32be(Loc, (read32be(Loc) & ~Mask) | (Val & Mask));
1296     break;
1297   }
1298   default:
1299     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1300   }
1301 }
1302
1303 AArch64TargetInfo::AArch64TargetInfo() {
1304   CopyRel = R_AARCH64_COPY;
1305   RelativeRel = R_AARCH64_RELATIVE;
1306   IRelativeRel = R_AARCH64_IRELATIVE;
1307   GotRel = R_AARCH64_GLOB_DAT;
1308   PltRel = R_AARCH64_JUMP_SLOT;
1309   TlsDescRel = R_AARCH64_TLSDESC;
1310   TlsGotRel = R_AARCH64_TLS_TPREL64;
1311   GotEntrySize = 8;
1312   GotPltEntrySize = 8;
1313   PltEntrySize = 16;
1314   PltHeaderSize = 32;
1315   DefaultMaxPageSize = 65536;
1316
1317   // It doesn't seem to be documented anywhere, but tls on aarch64 uses variant
1318   // 1 of the tls structures and the tcb size is 16.
1319   TcbSize = 16;
1320 }
1321
1322 RelExpr AArch64TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1323                                       const uint8_t *Loc) const {
1324   switch (Type) {
1325   default:
1326     return R_ABS;
1327   case R_AARCH64_TLSDESC_ADR_PAGE21:
1328     return R_TLSDESC_PAGE;
1329   case R_AARCH64_TLSDESC_LD64_LO12_NC:
1330   case R_AARCH64_TLSDESC_ADD_LO12_NC:
1331     return R_TLSDESC;
1332   case R_AARCH64_TLSDESC_CALL:
1333     return R_TLSDESC_CALL;
1334   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
1335   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1336     return R_TLS;
1337   case R_AARCH64_CALL26:
1338   case R_AARCH64_CONDBR19:
1339   case R_AARCH64_JUMP26:
1340   case R_AARCH64_TSTBR14:
1341     return R_PLT_PC;
1342   case R_AARCH64_PREL16:
1343   case R_AARCH64_PREL32:
1344   case R_AARCH64_PREL64:
1345   case R_AARCH64_ADR_PREL_LO21:
1346     return R_PC;
1347   case R_AARCH64_ADR_PREL_PG_HI21:
1348     return R_PAGE_PC;
1349   case R_AARCH64_LD64_GOT_LO12_NC:
1350   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1351     return R_GOT;
1352   case R_AARCH64_ADR_GOT_PAGE:
1353   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1354     return R_GOT_PAGE_PC;
1355   case R_AARCH64_NONE:
1356     return R_NONE;
1357   }
1358 }
1359
1360 RelExpr AArch64TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
1361                                            RelExpr Expr) const {
1362   if (Expr == R_RELAX_TLS_GD_TO_IE) {
1363     if (Type == R_AARCH64_TLSDESC_ADR_PAGE21)
1364       return R_RELAX_TLS_GD_TO_IE_PAGE_PC;
1365     return R_RELAX_TLS_GD_TO_IE_ABS;
1366   }
1367   return Expr;
1368 }
1369
1370 bool AArch64TargetInfo::usesOnlyLowPageBits(uint32_t Type) const {
1371   switch (Type) {
1372   default:
1373     return false;
1374   case R_AARCH64_ADD_ABS_LO12_NC:
1375   case R_AARCH64_LD64_GOT_LO12_NC:
1376   case R_AARCH64_LDST128_ABS_LO12_NC:
1377   case R_AARCH64_LDST16_ABS_LO12_NC:
1378   case R_AARCH64_LDST32_ABS_LO12_NC:
1379   case R_AARCH64_LDST64_ABS_LO12_NC:
1380   case R_AARCH64_LDST8_ABS_LO12_NC:
1381   case R_AARCH64_TLSDESC_ADD_LO12_NC:
1382   case R_AARCH64_TLSDESC_LD64_LO12_NC:
1383   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1384     return true;
1385   }
1386 }
1387
1388 bool AArch64TargetInfo::isTlsInitialExecRel(uint32_t Type) const {
1389   return Type == R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 ||
1390          Type == R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC;
1391 }
1392
1393 bool AArch64TargetInfo::isPicRel(uint32_t Type) const {
1394   return Type == R_AARCH64_ABS32 || Type == R_AARCH64_ABS64;
1395 }
1396
1397 void AArch64TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
1398   write64le(Buf, In<ELF64LE>::Plt->getVA());
1399 }
1400
1401 // Page(Expr) is the page address of the expression Expr, defined
1402 // as (Expr & ~0xFFF). (This applies even if the machine page size
1403 // supported by the platform has a different value.)
1404 uint64_t getAArch64Page(uint64_t Expr) {
1405   return Expr & (~static_cast<uint64_t>(0xFFF));
1406 }
1407
1408 void AArch64TargetInfo::writePltHeader(uint8_t *Buf) const {
1409   const uint8_t PltData[] = {
1410       0xf0, 0x7b, 0xbf, 0xa9, // stp    x16, x30, [sp,#-16]!
1411       0x10, 0x00, 0x00, 0x90, // adrp   x16, Page(&(.plt.got[2]))
1412       0x11, 0x02, 0x40, 0xf9, // ldr    x17, [x16, Offset(&(.plt.got[2]))]
1413       0x10, 0x02, 0x00, 0x91, // add    x16, x16, Offset(&(.plt.got[2]))
1414       0x20, 0x02, 0x1f, 0xd6, // br     x17
1415       0x1f, 0x20, 0x03, 0xd5, // nop
1416       0x1f, 0x20, 0x03, 0xd5, // nop
1417       0x1f, 0x20, 0x03, 0xd5  // nop
1418   };
1419   memcpy(Buf, PltData, sizeof(PltData));
1420
1421   uint64_t Got = In<ELF64LE>::GotPlt->getVA();
1422   uint64_t Plt = In<ELF64LE>::Plt->getVA();
1423   relocateOne(Buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
1424               getAArch64Page(Got + 16) - getAArch64Page(Plt + 4));
1425   relocateOne(Buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, Got + 16);
1426   relocateOne(Buf + 12, R_AARCH64_ADD_ABS_LO12_NC, Got + 16);
1427 }
1428
1429 void AArch64TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1430                                  uint64_t PltEntryAddr, int32_t Index,
1431                                  unsigned RelOff) const {
1432   const uint8_t Inst[] = {
1433       0x10, 0x00, 0x00, 0x90, // adrp x16, Page(&(.plt.got[n]))
1434       0x11, 0x02, 0x40, 0xf9, // ldr  x17, [x16, Offset(&(.plt.got[n]))]
1435       0x10, 0x02, 0x00, 0x91, // add  x16, x16, Offset(&(.plt.got[n]))
1436       0x20, 0x02, 0x1f, 0xd6  // br   x17
1437   };
1438   memcpy(Buf, Inst, sizeof(Inst));
1439
1440   relocateOne(Buf, R_AARCH64_ADR_PREL_PG_HI21,
1441               getAArch64Page(GotPltEntryAddr) - getAArch64Page(PltEntryAddr));
1442   relocateOne(Buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, GotPltEntryAddr);
1443   relocateOne(Buf + 8, R_AARCH64_ADD_ABS_LO12_NC, GotPltEntryAddr);
1444 }
1445
1446 static void write32AArch64Addr(uint8_t *L, uint64_t Imm) {
1447   uint32_t ImmLo = (Imm & 0x3) << 29;
1448   uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
1449   uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
1450   write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
1451 }
1452
1453 // Return the bits [Start, End] from Val shifted Start bits.
1454 // For instance, getBits(0xF0, 4, 8) returns 0xF.
1455 static uint64_t getBits(uint64_t Val, int Start, int End) {
1456   uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
1457   return (Val >> Start) & Mask;
1458 }
1459
1460 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
1461 static void or32AArch64Imm(uint8_t *L, uint64_t Imm) {
1462   or32le(L, (Imm & 0xFFF) << 10);
1463 }
1464
1465 void AArch64TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1466                                     uint64_t Val) const {
1467   switch (Type) {
1468   case R_AARCH64_ABS16:
1469   case R_AARCH64_PREL16:
1470     checkIntUInt<16>(Loc, Val, Type);
1471     write16le(Loc, Val);
1472     break;
1473   case R_AARCH64_ABS32:
1474   case R_AARCH64_PREL32:
1475     checkIntUInt<32>(Loc, Val, Type);
1476     write32le(Loc, Val);
1477     break;
1478   case R_AARCH64_ABS64:
1479   case R_AARCH64_GLOB_DAT:
1480   case R_AARCH64_PREL64:
1481     write64le(Loc, Val);
1482     break;
1483   case R_AARCH64_ADD_ABS_LO12_NC:
1484     or32AArch64Imm(Loc, Val);
1485     break;
1486   case R_AARCH64_ADR_GOT_PAGE:
1487   case R_AARCH64_ADR_PREL_PG_HI21:
1488   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1489   case R_AARCH64_TLSDESC_ADR_PAGE21:
1490     checkInt<33>(Loc, Val, Type);
1491     write32AArch64Addr(Loc, Val >> 12);
1492     break;
1493   case R_AARCH64_ADR_PREL_LO21:
1494     checkInt<21>(Loc, Val, Type);
1495     write32AArch64Addr(Loc, Val);
1496     break;
1497   case R_AARCH64_CALL26:
1498   case R_AARCH64_JUMP26:
1499     checkInt<28>(Loc, Val, Type);
1500     or32le(Loc, (Val & 0x0FFFFFFC) >> 2);
1501     break;
1502   case R_AARCH64_CONDBR19:
1503     checkInt<21>(Loc, Val, Type);
1504     or32le(Loc, (Val & 0x1FFFFC) << 3);
1505     break;
1506   case R_AARCH64_LD64_GOT_LO12_NC:
1507   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1508   case R_AARCH64_TLSDESC_LD64_LO12_NC:
1509     checkAlignment<8>(Loc, Val, Type);
1510     or32le(Loc, (Val & 0xFF8) << 7);
1511     break;
1512   case R_AARCH64_LDST8_ABS_LO12_NC:
1513     or32AArch64Imm(Loc, getBits(Val, 0, 11));
1514     break;
1515   case R_AARCH64_LDST16_ABS_LO12_NC:
1516     or32AArch64Imm(Loc, getBits(Val, 1, 11));
1517     break;
1518   case R_AARCH64_LDST32_ABS_LO12_NC:
1519     or32AArch64Imm(Loc, getBits(Val, 2, 11));
1520     break;
1521   case R_AARCH64_LDST64_ABS_LO12_NC:
1522     or32AArch64Imm(Loc, getBits(Val, 3, 11));
1523     break;
1524   case R_AARCH64_LDST128_ABS_LO12_NC:
1525     or32AArch64Imm(Loc, getBits(Val, 4, 11));
1526     break;
1527   case R_AARCH64_MOVW_UABS_G0_NC:
1528     or32le(Loc, (Val & 0xFFFF) << 5);
1529     break;
1530   case R_AARCH64_MOVW_UABS_G1_NC:
1531     or32le(Loc, (Val & 0xFFFF0000) >> 11);
1532     break;
1533   case R_AARCH64_MOVW_UABS_G2_NC:
1534     or32le(Loc, (Val & 0xFFFF00000000) >> 27);
1535     break;
1536   case R_AARCH64_MOVW_UABS_G3:
1537     or32le(Loc, (Val & 0xFFFF000000000000) >> 43);
1538     break;
1539   case R_AARCH64_TSTBR14:
1540     checkInt<16>(Loc, Val, Type);
1541     or32le(Loc, (Val & 0xFFFC) << 3);
1542     break;
1543   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
1544     checkInt<24>(Loc, Val, Type);
1545     or32AArch64Imm(Loc, Val >> 12);
1546     break;
1547   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1548   case R_AARCH64_TLSDESC_ADD_LO12_NC:
1549     or32AArch64Imm(Loc, Val);
1550     break;
1551   default:
1552     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1553   }
1554 }
1555
1556 void AArch64TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
1557                                        uint64_t Val) const {
1558   // TLSDESC Global-Dynamic relocation are in the form:
1559   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
1560   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12_NC]
1561   //   add     x0, x0, :tlsdesc_los:v     [_AARCH64_TLSDESC_ADD_LO12_NC]
1562   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
1563   //   blr     x1
1564   // And it can optimized to:
1565   //   movz    x0, #0x0, lsl #16
1566   //   movk    x0, #0x10
1567   //   nop
1568   //   nop
1569   checkUInt<32>(Loc, Val, Type);
1570
1571   switch (Type) {
1572   case R_AARCH64_TLSDESC_ADD_LO12_NC:
1573   case R_AARCH64_TLSDESC_CALL:
1574     write32le(Loc, 0xd503201f); // nop
1575     return;
1576   case R_AARCH64_TLSDESC_ADR_PAGE21:
1577     write32le(Loc, 0xd2a00000 | (((Val >> 16) & 0xffff) << 5)); // movz
1578     return;
1579   case R_AARCH64_TLSDESC_LD64_LO12_NC:
1580     write32le(Loc, 0xf2800000 | ((Val & 0xffff) << 5)); // movk
1581     return;
1582   default:
1583     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
1584   }
1585 }
1586
1587 void AArch64TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
1588                                        uint64_t Val) const {
1589   // TLSDESC Global-Dynamic relocation are in the form:
1590   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
1591   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12_NC]
1592   //   add     x0, x0, :tlsdesc_los:v     [_AARCH64_TLSDESC_ADD_LO12_NC]
1593   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
1594   //   blr     x1
1595   // And it can optimized to:
1596   //   adrp    x0, :gottprel:v
1597   //   ldr     x0, [x0, :gottprel_lo12:v]
1598   //   nop
1599   //   nop
1600
1601   switch (Type) {
1602   case R_AARCH64_TLSDESC_ADD_LO12_NC:
1603   case R_AARCH64_TLSDESC_CALL:
1604     write32le(Loc, 0xd503201f); // nop
1605     break;
1606   case R_AARCH64_TLSDESC_ADR_PAGE21:
1607     write32le(Loc, 0x90000000); // adrp
1608     relocateOne(Loc, R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21, Val);
1609     break;
1610   case R_AARCH64_TLSDESC_LD64_LO12_NC:
1611     write32le(Loc, 0xf9400000); // ldr
1612     relocateOne(Loc, R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC, Val);
1613     break;
1614   default:
1615     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
1616   }
1617 }
1618
1619 void AArch64TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
1620                                        uint64_t Val) const {
1621   checkUInt<32>(Loc, Val, Type);
1622
1623   if (Type == R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21) {
1624     // Generate MOVZ.
1625     uint32_t RegNo = read32le(Loc) & 0x1f;
1626     write32le(Loc, (0xd2a00000 | RegNo) | (((Val >> 16) & 0xffff) << 5));
1627     return;
1628   }
1629   if (Type == R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC) {
1630     // Generate MOVK.
1631     uint32_t RegNo = read32le(Loc) & 0x1f;
1632     write32le(Loc, (0xf2800000 | RegNo) | ((Val & 0xffff) << 5));
1633     return;
1634   }
1635   llvm_unreachable("invalid relocation for TLS IE to LE relaxation");
1636 }
1637
1638 AMDGPUTargetInfo::AMDGPUTargetInfo() {
1639   RelativeRel = R_AMDGPU_REL64;
1640   GotRel = R_AMDGPU_ABS64;
1641   GotEntrySize = 8;
1642 }
1643
1644 void AMDGPUTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1645                                    uint64_t Val) const {
1646   switch (Type) {
1647   case R_AMDGPU_ABS32:
1648   case R_AMDGPU_GOTPCREL:
1649   case R_AMDGPU_GOTPCREL32_LO:
1650   case R_AMDGPU_REL32:
1651   case R_AMDGPU_REL32_LO:
1652     write32le(Loc, Val);
1653     break;
1654   case R_AMDGPU_ABS64:
1655     write64le(Loc, Val);
1656     break;
1657   case R_AMDGPU_GOTPCREL32_HI:
1658   case R_AMDGPU_REL32_HI:
1659     write32le(Loc, Val >> 32);
1660     break;
1661   default:
1662     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1663   }
1664 }
1665
1666 RelExpr AMDGPUTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1667                                      const uint8_t *Loc) const {
1668   switch (Type) {
1669   case R_AMDGPU_ABS32:
1670   case R_AMDGPU_ABS64:
1671     return R_ABS;
1672   case R_AMDGPU_REL32:
1673   case R_AMDGPU_REL32_LO:
1674   case R_AMDGPU_REL32_HI:
1675     return R_PC;
1676   case R_AMDGPU_GOTPCREL:
1677   case R_AMDGPU_GOTPCREL32_LO:
1678   case R_AMDGPU_GOTPCREL32_HI:
1679     return R_GOT_PC;
1680   default:
1681     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
1682     return R_HINT;
1683   }
1684 }
1685
1686 ARMTargetInfo::ARMTargetInfo() {
1687   CopyRel = R_ARM_COPY;
1688   RelativeRel = R_ARM_RELATIVE;
1689   IRelativeRel = R_ARM_IRELATIVE;
1690   GotRel = R_ARM_GLOB_DAT;
1691   PltRel = R_ARM_JUMP_SLOT;
1692   TlsGotRel = R_ARM_TLS_TPOFF32;
1693   TlsModuleIndexRel = R_ARM_TLS_DTPMOD32;
1694   TlsOffsetRel = R_ARM_TLS_DTPOFF32;
1695   GotEntrySize = 4;
1696   GotPltEntrySize = 4;
1697   PltEntrySize = 16;
1698   PltHeaderSize = 20;
1699   // ARM uses Variant 1 TLS
1700   TcbSize = 8;
1701   NeedsThunks = true;
1702 }
1703
1704 RelExpr ARMTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1705                                   const uint8_t *Loc) const {
1706   switch (Type) {
1707   default:
1708     return R_ABS;
1709   case R_ARM_THM_JUMP11:
1710     return R_PC;
1711   case R_ARM_CALL:
1712   case R_ARM_JUMP24:
1713   case R_ARM_PC24:
1714   case R_ARM_PLT32:
1715   case R_ARM_PREL31:
1716   case R_ARM_THM_JUMP19:
1717   case R_ARM_THM_JUMP24:
1718   case R_ARM_THM_CALL:
1719     return R_PLT_PC;
1720   case R_ARM_GOTOFF32:
1721     // (S + A) - GOT_ORG
1722     return R_GOTREL;
1723   case R_ARM_GOT_BREL:
1724     // GOT(S) + A - GOT_ORG
1725     return R_GOT_OFF;
1726   case R_ARM_GOT_PREL:
1727   case R_ARM_TLS_IE32:
1728     // GOT(S) + A - P
1729     return R_GOT_PC;
1730   case R_ARM_TARGET1:
1731     return Config->Target1Rel ? R_PC : R_ABS;
1732   case R_ARM_TARGET2:
1733     if (Config->Target2 == Target2Policy::Rel)
1734       return R_PC;
1735     if (Config->Target2 == Target2Policy::Abs)
1736       return R_ABS;
1737     return R_GOT_PC;
1738   case R_ARM_TLS_GD32:
1739     return R_TLSGD_PC;
1740   case R_ARM_TLS_LDM32:
1741     return R_TLSLD_PC;
1742   case R_ARM_BASE_PREL:
1743     // B(S) + A - P
1744     // FIXME: currently B(S) assumed to be .got, this may not hold for all
1745     // platforms.
1746     return R_GOTONLY_PC;
1747   case R_ARM_MOVW_PREL_NC:
1748   case R_ARM_MOVT_PREL:
1749   case R_ARM_REL32:
1750   case R_ARM_THM_MOVW_PREL_NC:
1751   case R_ARM_THM_MOVT_PREL:
1752     return R_PC;
1753   case R_ARM_NONE:
1754     return R_NONE;
1755   case R_ARM_TLS_LE32:
1756     return R_TLS;
1757   }
1758 }
1759
1760 bool ARMTargetInfo::isPicRel(uint32_t Type) const {
1761   return (Type == R_ARM_TARGET1 && !Config->Target1Rel) ||
1762          (Type == R_ARM_ABS32);
1763 }
1764
1765 uint32_t ARMTargetInfo::getDynRel(uint32_t Type) const {
1766   if (Type == R_ARM_TARGET1 && !Config->Target1Rel)
1767     return R_ARM_ABS32;
1768   if (Type == R_ARM_ABS32)
1769     return Type;
1770   // Keep it going with a dummy value so that we can find more reloc errors.
1771   return R_ARM_ABS32;
1772 }
1773
1774 void ARMTargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
1775   write32le(Buf, In<ELF32LE>::Plt->getVA());
1776 }
1777
1778 void ARMTargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
1779   // An ARM entry is the address of the ifunc resolver function.
1780   write32le(Buf, S.getVA());
1781 }
1782
1783 void ARMTargetInfo::writePltHeader(uint8_t *Buf) const {
1784   const uint8_t PltData[] = {
1785       0x04, 0xe0, 0x2d, 0xe5, //     str lr, [sp,#-4]!
1786       0x04, 0xe0, 0x9f, 0xe5, //     ldr lr, L2
1787       0x0e, 0xe0, 0x8f, 0xe0, // L1: add lr, pc, lr
1788       0x08, 0xf0, 0xbe, 0xe5, //     ldr pc, [lr, #8]
1789       0x00, 0x00, 0x00, 0x00, // L2: .word   &(.got.plt) - L1 - 8
1790   };
1791   memcpy(Buf, PltData, sizeof(PltData));
1792   uint64_t GotPlt = In<ELF32LE>::GotPlt->getVA();
1793   uint64_t L1 = In<ELF32LE>::Plt->getVA() + 8;
1794   write32le(Buf + 16, GotPlt - L1 - 8);
1795 }
1796
1797 void ARMTargetInfo::addPltHeaderSymbols(InputSectionBase *ISD) const {
1798   auto *IS = cast<InputSection>(ISD);
1799   addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, 0, 0, IS);
1800   addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, 16, 0, IS);
1801 }
1802
1803 void ARMTargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1804                              uint64_t PltEntryAddr, int32_t Index,
1805                              unsigned RelOff) const {
1806   // FIXME: Using simple code sequence with simple relocations.
1807   // There is a more optimal sequence but it requires support for the group
1808   // relocations. See ELF for the ARM Architecture Appendix A.3
1809   const uint8_t PltData[] = {
1810       0x04, 0xc0, 0x9f, 0xe5, //     ldr ip, L2
1811       0x0f, 0xc0, 0x8c, 0xe0, // L1: add ip, ip, pc
1812       0x00, 0xf0, 0x9c, 0xe5, //     ldr pc, [ip]
1813       0x00, 0x00, 0x00, 0x00, // L2: .word   Offset(&(.plt.got) - L1 - 8
1814   };
1815   memcpy(Buf, PltData, sizeof(PltData));
1816   uint64_t L1 = PltEntryAddr + 4;
1817   write32le(Buf + 12, GotPltEntryAddr - L1 - 8);
1818 }
1819
1820 void ARMTargetInfo::addPltSymbols(InputSectionBase *ISD, uint64_t Off) const {
1821   auto *IS = cast<InputSection>(ISD);
1822   addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, Off, 0, IS);
1823   addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, Off + 12, 0, IS);
1824 }
1825
1826 bool ARMTargetInfo::needsThunk(RelExpr Expr, uint32_t RelocType,
1827                                const InputFile *File,
1828                                const SymbolBody &S) const {
1829   // If S is an undefined weak symbol in an executable we don't need a Thunk.
1830   // In a DSO calls to undefined symbols, including weak ones get PLT entries
1831   // which may need a thunk.
1832   if (S.isUndefined() && !S.isLocal() && S.symbol()->isWeak() &&
1833       !Config->Shared)
1834     return false;
1835   // A state change from ARM to Thumb and vice versa must go through an
1836   // interworking thunk if the relocation type is not R_ARM_CALL or
1837   // R_ARM_THM_CALL.
1838   switch (RelocType) {
1839   case R_ARM_PC24:
1840   case R_ARM_PLT32:
1841   case R_ARM_JUMP24:
1842     // Source is ARM, all PLT entries are ARM so no interworking required.
1843     // Otherwise we need to interwork if Symbol has bit 0 set (Thumb).
1844     if (Expr == R_PC && ((S.getVA() & 1) == 1))
1845       return true;
1846     break;
1847   case R_ARM_THM_JUMP19:
1848   case R_ARM_THM_JUMP24:
1849     // Source is Thumb, all PLT entries are ARM so interworking is required.
1850     // Otherwise we need to interwork if Symbol has bit 0 clear (ARM).
1851     if (Expr == R_PLT_PC || ((S.getVA() & 1) == 0))
1852       return true;
1853     break;
1854   }
1855   return false;
1856 }
1857
1858 void ARMTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1859                                 uint64_t Val) const {
1860   switch (Type) {
1861   case R_ARM_ABS32:
1862   case R_ARM_BASE_PREL:
1863   case R_ARM_GLOB_DAT:
1864   case R_ARM_GOTOFF32:
1865   case R_ARM_GOT_BREL:
1866   case R_ARM_GOT_PREL:
1867   case R_ARM_REL32:
1868   case R_ARM_RELATIVE:
1869   case R_ARM_TARGET1:
1870   case R_ARM_TARGET2:
1871   case R_ARM_TLS_GD32:
1872   case R_ARM_TLS_IE32:
1873   case R_ARM_TLS_LDM32:
1874   case R_ARM_TLS_LDO32:
1875   case R_ARM_TLS_LE32:
1876   case R_ARM_TLS_TPOFF32:
1877   case R_ARM_TLS_DTPOFF32:
1878     write32le(Loc, Val);
1879     break;
1880   case R_ARM_TLS_DTPMOD32:
1881     write32le(Loc, 1);
1882     break;
1883   case R_ARM_PREL31:
1884     checkInt<31>(Loc, Val, Type);
1885     write32le(Loc, (read32le(Loc) & 0x80000000) | (Val & ~0x80000000));
1886     break;
1887   case R_ARM_CALL:
1888     // R_ARM_CALL is used for BL and BLX instructions, depending on the
1889     // value of bit 0 of Val, we must select a BL or BLX instruction
1890     if (Val & 1) {
1891       // If bit 0 of Val is 1 the target is Thumb, we must select a BLX.
1892       // The BLX encoding is 0xfa:H:imm24 where Val = imm24:H:'1'
1893       checkInt<26>(Loc, Val, Type);
1894       write32le(Loc, 0xfa000000 |                    // opcode
1895                          ((Val & 2) << 23) |         // H
1896                          ((Val >> 2) & 0x00ffffff)); // imm24
1897       break;
1898     }
1899     if ((read32le(Loc) & 0xfe000000) == 0xfa000000)
1900       // BLX (always unconditional) instruction to an ARM Target, select an
1901       // unconditional BL.
1902       write32le(Loc, 0xeb000000 | (read32le(Loc) & 0x00ffffff));
1903   // fall through as BL encoding is shared with B
1904   case R_ARM_JUMP24:
1905   case R_ARM_PC24:
1906   case R_ARM_PLT32:
1907     checkInt<26>(Loc, Val, Type);
1908     write32le(Loc, (read32le(Loc) & ~0x00ffffff) | ((Val >> 2) & 0x00ffffff));
1909     break;
1910   case R_ARM_THM_JUMP11:
1911     checkInt<12>(Loc, Val, Type);
1912     write16le(Loc, (read32le(Loc) & 0xf800) | ((Val >> 1) & 0x07ff));
1913     break;
1914   case R_ARM_THM_JUMP19:
1915     // Encoding T3: Val = S:J2:J1:imm6:imm11:0
1916     checkInt<21>(Loc, Val, Type);
1917     write16le(Loc,
1918               (read16le(Loc) & 0xfbc0) |   // opcode cond
1919                   ((Val >> 10) & 0x0400) | // S
1920                   ((Val >> 12) & 0x003f)); // imm6
1921     write16le(Loc + 2,
1922               0x8000 |                    // opcode
1923                   ((Val >> 8) & 0x0800) | // J2
1924                   ((Val >> 5) & 0x2000) | // J1
1925                   ((Val >> 1) & 0x07ff)); // imm11
1926     break;
1927   case R_ARM_THM_CALL:
1928     // R_ARM_THM_CALL is used for BL and BLX instructions, depending on the
1929     // value of bit 0 of Val, we must select a BL or BLX instruction
1930     if ((Val & 1) == 0) {
1931       // Ensure BLX destination is 4-byte aligned. As BLX instruction may
1932       // only be two byte aligned. This must be done before overflow check
1933       Val = alignTo(Val, 4);
1934     }
1935     // Bit 12 is 0 for BLX, 1 for BL
1936     write16le(Loc + 2, (read16le(Loc + 2) & ~0x1000) | (Val & 1) << 12);
1937   // Fall through as rest of encoding is the same as B.W
1938   case R_ARM_THM_JUMP24:
1939     // Encoding B  T4, BL T1, BLX T2: Val = S:I1:I2:imm10:imm11:0
1940     // FIXME: Use of I1 and I2 require v6T2ops
1941     checkInt<25>(Loc, Val, Type);
1942     write16le(Loc,
1943               0xf000 |                     // opcode
1944                   ((Val >> 14) & 0x0400) | // S
1945                   ((Val >> 12) & 0x03ff)); // imm10
1946     write16le(Loc + 2,
1947               (read16le(Loc + 2) & 0xd000) |                  // opcode
1948                   (((~(Val >> 10)) ^ (Val >> 11)) & 0x2000) | // J1
1949                   (((~(Val >> 11)) ^ (Val >> 13)) & 0x0800) | // J2
1950                   ((Val >> 1) & 0x07ff));                     // imm11
1951     break;
1952   case R_ARM_MOVW_ABS_NC:
1953   case R_ARM_MOVW_PREL_NC:
1954     write32le(Loc, (read32le(Loc) & ~0x000f0fff) | ((Val & 0xf000) << 4) |
1955                        (Val & 0x0fff));
1956     break;
1957   case R_ARM_MOVT_ABS:
1958   case R_ARM_MOVT_PREL:
1959     checkInt<32>(Loc, Val, Type);
1960     write32le(Loc, (read32le(Loc) & ~0x000f0fff) |
1961                        (((Val >> 16) & 0xf000) << 4) | ((Val >> 16) & 0xfff));
1962     break;
1963   case R_ARM_THM_MOVT_ABS:
1964   case R_ARM_THM_MOVT_PREL:
1965     // Encoding T1: A = imm4:i:imm3:imm8
1966     checkInt<32>(Loc, Val, Type);
1967     write16le(Loc,
1968               0xf2c0 |                     // opcode
1969                   ((Val >> 17) & 0x0400) | // i
1970                   ((Val >> 28) & 0x000f)); // imm4
1971     write16le(Loc + 2,
1972               (read16le(Loc + 2) & 0x8f00) | // opcode
1973                   ((Val >> 12) & 0x7000) |   // imm3
1974                   ((Val >> 16) & 0x00ff));   // imm8
1975     break;
1976   case R_ARM_THM_MOVW_ABS_NC:
1977   case R_ARM_THM_MOVW_PREL_NC:
1978     // Encoding T3: A = imm4:i:imm3:imm8
1979     write16le(Loc,
1980               0xf240 |                     // opcode
1981                   ((Val >> 1) & 0x0400) |  // i
1982                   ((Val >> 12) & 0x000f)); // imm4
1983     write16le(Loc + 2,
1984               (read16le(Loc + 2) & 0x8f00) | // opcode
1985                   ((Val << 4) & 0x7000) |    // imm3
1986                   (Val & 0x00ff));           // imm8
1987     break;
1988   default:
1989     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1990   }
1991 }
1992
1993 int64_t ARMTargetInfo::getImplicitAddend(const uint8_t *Buf,
1994                                          uint32_t Type) const {
1995   switch (Type) {
1996   default:
1997     return 0;
1998   case R_ARM_ABS32:
1999   case R_ARM_BASE_PREL:
2000   case R_ARM_GOTOFF32:
2001   case R_ARM_GOT_BREL:
2002   case R_ARM_GOT_PREL:
2003   case R_ARM_REL32:
2004   case R_ARM_TARGET1:
2005   case R_ARM_TARGET2:
2006   case R_ARM_TLS_GD32:
2007   case R_ARM_TLS_LDM32:
2008   case R_ARM_TLS_LDO32:
2009   case R_ARM_TLS_IE32:
2010   case R_ARM_TLS_LE32:
2011     return SignExtend64<32>(read32le(Buf));
2012   case R_ARM_PREL31:
2013     return SignExtend64<31>(read32le(Buf));
2014   case R_ARM_CALL:
2015   case R_ARM_JUMP24:
2016   case R_ARM_PC24:
2017   case R_ARM_PLT32:
2018     return SignExtend64<26>(read32le(Buf) << 2);
2019   case R_ARM_THM_JUMP11:
2020     return SignExtend64<12>(read16le(Buf) << 1);
2021   case R_ARM_THM_JUMP19: {
2022     // Encoding T3: A = S:J2:J1:imm10:imm6:0
2023     uint16_t Hi = read16le(Buf);
2024     uint16_t Lo = read16le(Buf + 2);
2025     return SignExtend64<20>(((Hi & 0x0400) << 10) | // S
2026                             ((Lo & 0x0800) << 8) |  // J2
2027                             ((Lo & 0x2000) << 5) |  // J1
2028                             ((Hi & 0x003f) << 12) | // imm6
2029                             ((Lo & 0x07ff) << 1));  // imm11:0
2030   }
2031   case R_ARM_THM_CALL:
2032   case R_ARM_THM_JUMP24: {
2033     // Encoding B T4, BL T1, BLX T2: A = S:I1:I2:imm10:imm11:0
2034     // I1 = NOT(J1 EOR S), I2 = NOT(J2 EOR S)
2035     // FIXME: I1 and I2 require v6T2ops
2036     uint16_t Hi = read16le(Buf);
2037     uint16_t Lo = read16le(Buf + 2);
2038     return SignExtend64<24>(((Hi & 0x0400) << 14) |                    // S
2039                             (~((Lo ^ (Hi << 3)) << 10) & 0x00800000) | // I1
2040                             (~((Lo ^ (Hi << 1)) << 11) & 0x00400000) | // I2
2041                             ((Hi & 0x003ff) << 12) |                   // imm0
2042                             ((Lo & 0x007ff) << 1)); // imm11:0
2043   }
2044   // ELF for the ARM Architecture 4.6.1.1 the implicit addend for MOVW and
2045   // MOVT is in the range -32768 <= A < 32768
2046   case R_ARM_MOVW_ABS_NC:
2047   case R_ARM_MOVT_ABS:
2048   case R_ARM_MOVW_PREL_NC:
2049   case R_ARM_MOVT_PREL: {
2050     uint64_t Val = read32le(Buf) & 0x000f0fff;
2051     return SignExtend64<16>(((Val & 0x000f0000) >> 4) | (Val & 0x00fff));
2052   }
2053   case R_ARM_THM_MOVW_ABS_NC:
2054   case R_ARM_THM_MOVT_ABS:
2055   case R_ARM_THM_MOVW_PREL_NC:
2056   case R_ARM_THM_MOVT_PREL: {
2057     // Encoding T3: A = imm4:i:imm3:imm8
2058     uint16_t Hi = read16le(Buf);
2059     uint16_t Lo = read16le(Buf + 2);
2060     return SignExtend64<16>(((Hi & 0x000f) << 12) | // imm4
2061                             ((Hi & 0x0400) << 1) |  // i
2062                             ((Lo & 0x7000) >> 4) |  // imm3
2063                             (Lo & 0x00ff));         // imm8
2064   }
2065   }
2066 }
2067
2068 bool ARMTargetInfo::isTlsLocalDynamicRel(uint32_t Type) const {
2069   return Type == R_ARM_TLS_LDO32 || Type == R_ARM_TLS_LDM32;
2070 }
2071
2072 bool ARMTargetInfo::isTlsInitialExecRel(uint32_t Type) const {
2073   return Type == R_ARM_TLS_IE32;
2074 }
2075
2076 template <class ELFT> MipsTargetInfo<ELFT>::MipsTargetInfo() {
2077   GotPltHeaderEntriesNum = 2;
2078   DefaultMaxPageSize = 65536;
2079   GotEntrySize = sizeof(typename ELFT::uint);
2080   GotPltEntrySize = sizeof(typename ELFT::uint);
2081   PltEntrySize = 16;
2082   PltHeaderSize = 32;
2083   CopyRel = R_MIPS_COPY;
2084   PltRel = R_MIPS_JUMP_SLOT;
2085   NeedsThunks = true;
2086   if (ELFT::Is64Bits) {
2087     RelativeRel = (R_MIPS_64 << 8) | R_MIPS_REL32;
2088     TlsGotRel = R_MIPS_TLS_TPREL64;
2089     TlsModuleIndexRel = R_MIPS_TLS_DTPMOD64;
2090     TlsOffsetRel = R_MIPS_TLS_DTPREL64;
2091   } else {
2092     RelativeRel = R_MIPS_REL32;
2093     TlsGotRel = R_MIPS_TLS_TPREL32;
2094     TlsModuleIndexRel = R_MIPS_TLS_DTPMOD32;
2095     TlsOffsetRel = R_MIPS_TLS_DTPREL32;
2096   }
2097 }
2098
2099 template <class ELFT>
2100 RelExpr MipsTargetInfo<ELFT>::getRelExpr(uint32_t Type, const SymbolBody &S,
2101                                          const uint8_t *Loc) const {
2102   // See comment in the calculateMipsRelChain.
2103   if (ELFT::Is64Bits || Config->MipsN32Abi)
2104     Type &= 0xff;
2105   switch (Type) {
2106   default:
2107     return R_ABS;
2108   case R_MIPS_JALR:
2109     return R_HINT;
2110   case R_MIPS_GPREL16:
2111   case R_MIPS_GPREL32:
2112     return R_MIPS_GOTREL;
2113   case R_MIPS_26:
2114     return R_PLT;
2115   case R_MIPS_HI16:
2116   case R_MIPS_LO16:
2117     // R_MIPS_HI16/R_MIPS_LO16 relocations against _gp_disp calculate
2118     // offset between start of function and 'gp' value which by default
2119     // equal to the start of .got section. In that case we consider these
2120     // relocations as relative.
2121     if (&S == ElfSym::MipsGpDisp)
2122       return R_MIPS_GOT_GP_PC;
2123     if (&S == ElfSym::MipsLocalGp)
2124       return R_MIPS_GOT_GP;
2125     // fallthrough
2126   case R_MIPS_GOT_OFST:
2127     return R_ABS;
2128   case R_MIPS_PC32:
2129   case R_MIPS_PC16:
2130   case R_MIPS_PC19_S2:
2131   case R_MIPS_PC21_S2:
2132   case R_MIPS_PC26_S2:
2133   case R_MIPS_PCHI16:
2134   case R_MIPS_PCLO16:
2135     return R_PC;
2136   case R_MIPS_GOT16:
2137     if (S.isLocal())
2138       return R_MIPS_GOT_LOCAL_PAGE;
2139   // fallthrough
2140   case R_MIPS_CALL16:
2141   case R_MIPS_GOT_DISP:
2142   case R_MIPS_TLS_GOTTPREL:
2143     return R_MIPS_GOT_OFF;
2144   case R_MIPS_CALL_HI16:
2145   case R_MIPS_CALL_LO16:
2146   case R_MIPS_GOT_HI16:
2147   case R_MIPS_GOT_LO16:
2148     return R_MIPS_GOT_OFF32;
2149   case R_MIPS_GOT_PAGE:
2150     return R_MIPS_GOT_LOCAL_PAGE;
2151   case R_MIPS_TLS_GD:
2152     return R_MIPS_TLSGD;
2153   case R_MIPS_TLS_LDM:
2154     return R_MIPS_TLSLD;
2155   }
2156 }
2157
2158 template <class ELFT> bool MipsTargetInfo<ELFT>::isPicRel(uint32_t Type) const {
2159   return Type == R_MIPS_32 || Type == R_MIPS_64;
2160 }
2161
2162 template <class ELFT>
2163 uint32_t MipsTargetInfo<ELFT>::getDynRel(uint32_t Type) const {
2164   return RelativeRel;
2165 }
2166
2167 template <class ELFT>
2168 bool MipsTargetInfo<ELFT>::isTlsLocalDynamicRel(uint32_t Type) const {
2169   return Type == R_MIPS_TLS_LDM;
2170 }
2171
2172 template <class ELFT>
2173 void MipsTargetInfo<ELFT>::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
2174   write32<ELFT::TargetEndianness>(Buf, In<ELFT>::Plt->getVA());
2175 }
2176
2177 template <endianness E, uint8_t BSIZE, uint8_t SHIFT>
2178 static int64_t getPcRelocAddend(const uint8_t *Loc) {
2179   uint32_t Instr = read32<E>(Loc);
2180   uint32_t Mask = 0xffffffff >> (32 - BSIZE);
2181   return SignExtend64<BSIZE + SHIFT>((Instr & Mask) << SHIFT);
2182 }
2183
2184 template <endianness E, uint8_t BSIZE, uint8_t SHIFT>
2185 static void applyMipsPcReloc(uint8_t *Loc, uint32_t Type, uint64_t V) {
2186   uint32_t Mask = 0xffffffff >> (32 - BSIZE);
2187   uint32_t Instr = read32<E>(Loc);
2188   if (SHIFT > 0)
2189     checkAlignment<(1 << SHIFT)>(Loc, V, Type);
2190   checkInt<BSIZE + SHIFT>(Loc, V, Type);
2191   write32<E>(Loc, (Instr & ~Mask) | ((V >> SHIFT) & Mask));
2192 }
2193
2194 template <endianness E> static void writeMipsHi16(uint8_t *Loc, uint64_t V) {
2195   uint32_t Instr = read32<E>(Loc);
2196   uint16_t Res = ((V + 0x8000) >> 16) & 0xffff;
2197   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2198 }
2199
2200 template <endianness E> static void writeMipsHigher(uint8_t *Loc, uint64_t V) {
2201   uint32_t Instr = read32<E>(Loc);
2202   uint16_t Res = ((V + 0x80008000) >> 32) & 0xffff;
2203   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2204 }
2205
2206 template <endianness E> static void writeMipsHighest(uint8_t *Loc, uint64_t V) {
2207   uint32_t Instr = read32<E>(Loc);
2208   uint16_t Res = ((V + 0x800080008000) >> 48) & 0xffff;
2209   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2210 }
2211
2212 template <endianness E> static void writeMipsLo16(uint8_t *Loc, uint64_t V) {
2213   uint32_t Instr = read32<E>(Loc);
2214   write32<E>(Loc, (Instr & 0xffff0000) | (V & 0xffff));
2215 }
2216
2217 template <class ELFT> static bool isMipsR6() {
2218   const auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
2219   uint32_t Arch = FirstObj.getObj().getHeader()->e_flags & EF_MIPS_ARCH;
2220   return Arch == EF_MIPS_ARCH_32R6 || Arch == EF_MIPS_ARCH_64R6;
2221 }
2222
2223 template <class ELFT>
2224 void MipsTargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const {
2225   const endianness E = ELFT::TargetEndianness;
2226   if (Config->MipsN32Abi) {
2227     write32<E>(Buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
2228     write32<E>(Buf + 4, 0x8dd90000);  // lw    $25, %lo(&GOTPLT[0])($14)
2229     write32<E>(Buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
2230     write32<E>(Buf + 12, 0x030ec023); // subu  $24, $24, $14
2231   } else {
2232     write32<E>(Buf, 0x3c1c0000);      // lui   $28, %hi(&GOTPLT[0])
2233     write32<E>(Buf + 4, 0x8f990000);  // lw    $25, %lo(&GOTPLT[0])($28)
2234     write32<E>(Buf + 8, 0x279c0000);  // addiu $28, $28, %lo(&GOTPLT[0])
2235     write32<E>(Buf + 12, 0x031cc023); // subu  $24, $24, $28
2236   }
2237
2238   write32<E>(Buf + 16, 0x03e07825); // move  $15, $31
2239   write32<E>(Buf + 20, 0x0018c082); // srl   $24, $24, 2
2240   write32<E>(Buf + 24, 0x0320f809); // jalr  $25
2241   write32<E>(Buf + 28, 0x2718fffe); // subu  $24, $24, 2
2242
2243   uint64_t GotPlt = In<ELFT>::GotPlt->getVA();
2244   writeMipsHi16<E>(Buf, GotPlt);
2245   writeMipsLo16<E>(Buf + 4, GotPlt);
2246   writeMipsLo16<E>(Buf + 8, GotPlt);
2247 }
2248
2249 template <class ELFT>
2250 void MipsTargetInfo<ELFT>::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
2251                                     uint64_t PltEntryAddr, int32_t Index,
2252                                     unsigned RelOff) const {
2253   const endianness E = ELFT::TargetEndianness;
2254   write32<E>(Buf, 0x3c0f0000);     // lui   $15, %hi(.got.plt entry)
2255   write32<E>(Buf + 4, 0x8df90000); // l[wd] $25, %lo(.got.plt entry)($15)
2256                                    // jr    $25
2257   write32<E>(Buf + 8, isMipsR6<ELFT>() ? 0x03200009 : 0x03200008);
2258   write32<E>(Buf + 12, 0x25f80000); // addiu $24, $15, %lo(.got.plt entry)
2259   writeMipsHi16<E>(Buf, GotPltEntryAddr);
2260   writeMipsLo16<E>(Buf + 4, GotPltEntryAddr);
2261   writeMipsLo16<E>(Buf + 12, GotPltEntryAddr);
2262 }
2263
2264 template <class ELFT>
2265 bool MipsTargetInfo<ELFT>::needsThunk(RelExpr Expr, uint32_t Type,
2266                                       const InputFile *File,
2267                                       const SymbolBody &S) const {
2268   // Any MIPS PIC code function is invoked with its address in register $t9.
2269   // So if we have a branch instruction from non-PIC code to the PIC one
2270   // we cannot make the jump directly and need to create a small stubs
2271   // to save the target function address.
2272   // See page 3-38 ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2273   if (Type != R_MIPS_26)
2274     return false;
2275   auto *F = dyn_cast_or_null<ELFFileBase<ELFT>>(File);
2276   if (!F)
2277     return false;
2278   // If current file has PIC code, LA25 stub is not required.
2279   if (F->getObj().getHeader()->e_flags & EF_MIPS_PIC)
2280     return false;
2281   auto *D = dyn_cast<DefinedRegular>(&S);
2282   // LA25 is required if target file has PIC code
2283   // or target symbol is a PIC symbol.
2284   return D && D->isMipsPIC<ELFT>();
2285 }
2286
2287 template <class ELFT>
2288 int64_t MipsTargetInfo<ELFT>::getImplicitAddend(const uint8_t *Buf,
2289                                                 uint32_t Type) const {
2290   const endianness E = ELFT::TargetEndianness;
2291   switch (Type) {
2292   default:
2293     return 0;
2294   case R_MIPS_32:
2295   case R_MIPS_GPREL32:
2296   case R_MIPS_TLS_DTPREL32:
2297   case R_MIPS_TLS_TPREL32:
2298     return SignExtend64<32>(read32<E>(Buf));
2299   case R_MIPS_26:
2300     // FIXME (simon): If the relocation target symbol is not a PLT entry
2301     // we should use another expression for calculation:
2302     // ((A << 2) | (P & 0xf0000000)) >> 2
2303     return SignExtend64<28>((read32<E>(Buf) & 0x3ffffff) << 2);
2304   case R_MIPS_GPREL16:
2305   case R_MIPS_LO16:
2306   case R_MIPS_PCLO16:
2307   case R_MIPS_TLS_DTPREL_HI16:
2308   case R_MIPS_TLS_DTPREL_LO16:
2309   case R_MIPS_TLS_TPREL_HI16:
2310   case R_MIPS_TLS_TPREL_LO16:
2311     return SignExtend64<16>(read32<E>(Buf));
2312   case R_MIPS_PC16:
2313     return getPcRelocAddend<E, 16, 2>(Buf);
2314   case R_MIPS_PC19_S2:
2315     return getPcRelocAddend<E, 19, 2>(Buf);
2316   case R_MIPS_PC21_S2:
2317     return getPcRelocAddend<E, 21, 2>(Buf);
2318   case R_MIPS_PC26_S2:
2319     return getPcRelocAddend<E, 26, 2>(Buf);
2320   case R_MIPS_PC32:
2321     return getPcRelocAddend<E, 32, 0>(Buf);
2322   }
2323 }
2324
2325 static std::pair<uint32_t, uint64_t>
2326 calculateMipsRelChain(uint8_t *Loc, uint32_t Type, uint64_t Val) {
2327   // MIPS N64 ABI packs multiple relocations into the single relocation
2328   // record. In general, all up to three relocations can have arbitrary
2329   // types. In fact, Clang and GCC uses only a few combinations. For now,
2330   // we support two of them. That is allow to pass at least all LLVM
2331   // test suite cases.
2332   // <any relocation> / R_MIPS_SUB / R_MIPS_HI16 | R_MIPS_LO16
2333   // <any relocation> / R_MIPS_64 / R_MIPS_NONE
2334   // The first relocation is a 'real' relocation which is calculated
2335   // using the corresponding symbol's value. The second and the third
2336   // relocations used to modify result of the first one: extend it to
2337   // 64-bit, extract high or low part etc. For details, see part 2.9 Relocation
2338   // at the https://dmz-portal.mips.com/mw/images/8/82/007-4658-001.pdf
2339   uint32_t Type2 = (Type >> 8) & 0xff;
2340   uint32_t Type3 = (Type >> 16) & 0xff;
2341   if (Type2 == R_MIPS_NONE && Type3 == R_MIPS_NONE)
2342     return std::make_pair(Type, Val);
2343   if (Type2 == R_MIPS_64 && Type3 == R_MIPS_NONE)
2344     return std::make_pair(Type2, Val);
2345   if (Type2 == R_MIPS_SUB && (Type3 == R_MIPS_HI16 || Type3 == R_MIPS_LO16))
2346     return std::make_pair(Type3, -Val);
2347   error(getErrorLocation(Loc) + "unsupported relocations combination " +
2348         Twine(Type));
2349   return std::make_pair(Type & 0xff, Val);
2350 }
2351
2352 template <class ELFT>
2353 void MipsTargetInfo<ELFT>::relocateOne(uint8_t *Loc, uint32_t Type,
2354                                        uint64_t Val) const {
2355   const endianness E = ELFT::TargetEndianness;
2356   // Thread pointer and DRP offsets from the start of TLS data area.
2357   // https://www.linux-mips.org/wiki/NPTL
2358   if (Type == R_MIPS_TLS_DTPREL_HI16 || Type == R_MIPS_TLS_DTPREL_LO16 ||
2359       Type == R_MIPS_TLS_DTPREL32 || Type == R_MIPS_TLS_DTPREL64)
2360     Val -= 0x8000;
2361   else if (Type == R_MIPS_TLS_TPREL_HI16 || Type == R_MIPS_TLS_TPREL_LO16 ||
2362            Type == R_MIPS_TLS_TPREL32 || Type == R_MIPS_TLS_TPREL64)
2363     Val -= 0x7000;
2364   if (ELFT::Is64Bits || Config->MipsN32Abi)
2365     std::tie(Type, Val) = calculateMipsRelChain(Loc, Type, Val);
2366   switch (Type) {
2367   case R_MIPS_32:
2368   case R_MIPS_GPREL32:
2369   case R_MIPS_TLS_DTPREL32:
2370   case R_MIPS_TLS_TPREL32:
2371     write32<E>(Loc, Val);
2372     break;
2373   case R_MIPS_64:
2374   case R_MIPS_TLS_DTPREL64:
2375   case R_MIPS_TLS_TPREL64:
2376     write64<E>(Loc, Val);
2377     break;
2378   case R_MIPS_26:
2379     write32<E>(Loc, (read32<E>(Loc) & ~0x3ffffff) | ((Val >> 2) & 0x3ffffff));
2380     break;
2381   case R_MIPS_GOT16:
2382     // The R_MIPS_GOT16 relocation's value in "relocatable" linking mode
2383     // is updated addend (not a GOT index). In that case write high 16 bits
2384     // to store a correct addend value.
2385     if (Config->Relocatable)
2386       writeMipsHi16<E>(Loc, Val);
2387     else {
2388       checkInt<16>(Loc, Val, Type);
2389       writeMipsLo16<E>(Loc, Val);
2390     }
2391     break;
2392   case R_MIPS_GOT_DISP:
2393   case R_MIPS_GOT_PAGE:
2394   case R_MIPS_GPREL16:
2395   case R_MIPS_TLS_GD:
2396   case R_MIPS_TLS_LDM:
2397     checkInt<16>(Loc, Val, Type);
2398   // fallthrough
2399   case R_MIPS_CALL16:
2400   case R_MIPS_CALL_LO16:
2401   case R_MIPS_GOT_LO16:
2402   case R_MIPS_GOT_OFST:
2403   case R_MIPS_LO16:
2404   case R_MIPS_PCLO16:
2405   case R_MIPS_TLS_DTPREL_LO16:
2406   case R_MIPS_TLS_GOTTPREL:
2407   case R_MIPS_TLS_TPREL_LO16:
2408     writeMipsLo16<E>(Loc, Val);
2409     break;
2410   case R_MIPS_CALL_HI16:
2411   case R_MIPS_GOT_HI16:
2412   case R_MIPS_HI16:
2413   case R_MIPS_PCHI16:
2414   case R_MIPS_TLS_DTPREL_HI16:
2415   case R_MIPS_TLS_TPREL_HI16:
2416     writeMipsHi16<E>(Loc, Val);
2417     break;
2418   case R_MIPS_HIGHER:
2419     writeMipsHigher<E>(Loc, Val);
2420     break;
2421   case R_MIPS_HIGHEST:
2422     writeMipsHighest<E>(Loc, Val);
2423     break;
2424   case R_MIPS_JALR:
2425     // Ignore this optimization relocation for now
2426     break;
2427   case R_MIPS_PC16:
2428     applyMipsPcReloc<E, 16, 2>(Loc, Type, Val);
2429     break;
2430   case R_MIPS_PC19_S2:
2431     applyMipsPcReloc<E, 19, 2>(Loc, Type, Val);
2432     break;
2433   case R_MIPS_PC21_S2:
2434     applyMipsPcReloc<E, 21, 2>(Loc, Type, Val);
2435     break;
2436   case R_MIPS_PC26_S2:
2437     applyMipsPcReloc<E, 26, 2>(Loc, Type, Val);
2438     break;
2439   case R_MIPS_PC32:
2440     applyMipsPcReloc<E, 32, 0>(Loc, Type, Val);
2441     break;
2442   default:
2443     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
2444   }
2445 }
2446
2447 template <class ELFT>
2448 bool MipsTargetInfo<ELFT>::usesOnlyLowPageBits(uint32_t Type) const {
2449   return Type == R_MIPS_LO16 || Type == R_MIPS_GOT_OFST;
2450 }
2451 }
2452 }