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