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