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