xref: /llvm-project-15.0.7/lld/ELF/Arch/PPC64.cpp (revision 291bfff5)
1 //===- PPC64.cpp ----------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolTable.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "Thunks.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/Memory.h"
16 #include "llvm/Support/Endian.h"
17 
18 using namespace llvm;
19 using namespace llvm::object;
20 using namespace llvm::support::endian;
21 using namespace llvm::ELF;
22 using namespace lld;
23 using namespace lld::elf;
24 
25 constexpr uint64_t ppc64TocOffset = 0x8000;
26 constexpr uint64_t dynamicThreadPointerOffset = 0x8000;
27 
28 // The instruction encoding of bits 21-30 from the ISA for the Xform and Dform
29 // instructions that can be used as part of the initial exec TLS sequence.
30 enum XFormOpcd {
31   LBZX = 87,
32   LHZX = 279,
33   LWZX = 23,
34   LDX = 21,
35   STBX = 215,
36   STHX = 407,
37   STWX = 151,
38   STDX = 149,
39   ADD = 266,
40 };
41 
42 enum DFormOpcd {
43   LBZ = 34,
44   LBZU = 35,
45   LHZ = 40,
46   LHZU = 41,
47   LHAU = 43,
48   LWZ = 32,
49   LWZU = 33,
50   LFSU = 49,
51   LD = 58,
52   LFDU = 51,
53   STB = 38,
54   STBU = 39,
55   STH = 44,
56   STHU = 45,
57   STW = 36,
58   STWU = 37,
59   STFSU = 53,
60   STFDU = 55,
61   STD = 62,
62   ADDI = 14
63 };
64 
65 constexpr uint32_t NOP = 0x60000000;
66 
67 enum class PPCLegacyInsn : uint32_t {
68   NOINSN = 0,
69   // Loads.
70   LBZ = 0x88000000,
71   LHZ = 0xa0000000,
72   LWZ = 0x80000000,
73   LHA = 0xa8000000,
74   LWA = 0xe8000002,
75   LD = 0xe8000000,
76   LFS = 0xC0000000,
77   LXSSP = 0xe4000003,
78   LFD = 0xc8000000,
79   LXSD = 0xe4000002,
80   LXV = 0xf4000001,
81   LXVP = 0x18000000,
82 
83   // Stores.
84   STB = 0x98000000,
85   STH = 0xb0000000,
86   STW = 0x90000000,
87   STD = 0xf8000000,
88   STFS = 0xd0000000,
89   STXSSP = 0xf4000003,
90   STFD = 0xd8000000,
91   STXSD = 0xf4000002,
92   STXV = 0xf4000005,
93   STXVP = 0x18000001
94 };
95 enum class PPCPrefixedInsn : uint64_t {
96   NOINSN = 0,
97   PREFIX_MLS = 0x0610000000000000,
98   PREFIX_8LS = 0x0410000000000000,
99 
100   // Loads.
101   PLBZ = PREFIX_MLS,
102   PLHZ = PREFIX_MLS,
103   PLWZ = PREFIX_MLS,
104   PLHA = PREFIX_MLS,
105   PLWA = PREFIX_8LS | 0xa4000000,
106   PLD = PREFIX_8LS | 0xe4000000,
107   PLFS = PREFIX_MLS,
108   PLXSSP = PREFIX_8LS | 0xac000000,
109   PLFD = PREFIX_MLS,
110   PLXSD = PREFIX_8LS | 0xa8000000,
111   PLXV = PREFIX_8LS | 0xc8000000,
112   PLXVP = PREFIX_8LS | 0xe8000000,
113 
114   // Stores.
115   PSTB = PREFIX_MLS,
116   PSTH = PREFIX_MLS,
117   PSTW = PREFIX_MLS,
118   PSTD = PREFIX_8LS | 0xf4000000,
119   PSTFS = PREFIX_MLS,
120   PSTXSSP = PREFIX_8LS | 0xbc000000,
121   PSTFD = PREFIX_MLS,
122   PSTXSD = PREFIX_8LS | 0xb8000000,
123   PSTXV = PREFIX_8LS | 0xd8000000,
124   PSTXVP = PREFIX_8LS | 0xf8000000
125 };
126 static bool checkPPCLegacyInsn(uint32_t encoding) {
127   PPCLegacyInsn insn = static_cast<PPCLegacyInsn>(encoding);
128   if (insn == PPCLegacyInsn::NOINSN)
129     return false;
130 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
131   if (insn == PPCLegacyInsn::Legacy)                                           \
132     return true;
133 #include "PPCInsns.def"
134 #undef PCREL_OPT
135   return false;
136 }
137 
138 // Masks to apply to legacy instructions when converting them to prefixed,
139 // pc-relative versions. For the most part, the primary opcode is shared
140 // between the legacy instruction and the suffix of its prefixed version.
141 // However, there are some instances where that isn't the case (DS-Form and
142 // DQ-form instructions).
143 enum class LegacyToPrefixMask : uint64_t {
144   NOMASK = 0x0,
145   OPC_AND_RST = 0xffe00000, // Primary opc (0-5) and R[ST] (6-10).
146   ONLY_RST = 0x3e00000,     // [RS]T (6-10).
147   ST_STX28_TO5 =
148       0x8000000003e00000, // S/T (6-10) - The [S/T]X bit moves from 28 to 5.
149 };
150 
151 uint64_t elf::getPPC64TocBase() {
152   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
153   // TOC starts where the first of these sections starts. We always create a
154   // .got when we see a relocation that uses it, so for us the start is always
155   // the .got.
156   uint64_t tocVA = in.got->getVA();
157 
158   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
159   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
160   // code (crt1.o) assumes that you can get from the TOC base to the
161   // start of the .toc section with only a single (signed) 16-bit relocation.
162   return tocVA + ppc64TocOffset;
163 }
164 
165 unsigned elf::getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther) {
166   // The offset is encoded into the 3 most significant bits of the st_other
167   // field, with some special values described in section 3.4.1 of the ABI:
168   // 0   --> Zero offset between the GEP and LEP, and the function does NOT use
169   //         the TOC pointer (r2). r2 will hold the same value on returning from
170   //         the function as it did on entering the function.
171   // 1   --> Zero offset between the GEP and LEP, and r2 should be treated as a
172   //         caller-saved register for all callers.
173   // 2-6 --> The  binary logarithm of the offset eg:
174   //         2 --> 2^2 = 4 bytes -->  1 instruction.
175   //         6 --> 2^6 = 64 bytes --> 16 instructions.
176   // 7   --> Reserved.
177   uint8_t gepToLep = (stOther >> 5) & 7;
178   if (gepToLep < 2)
179     return 0;
180 
181   // The value encoded in the st_other bits is the
182   // log-base-2(offset).
183   if (gepToLep < 7)
184     return 1 << gepToLep;
185 
186   error("reserved value of 7 in the 3 most-significant-bits of st_other");
187   return 0;
188 }
189 
190 bool elf::isPPC64SmallCodeModelTocReloc(RelType type) {
191   // The only small code model relocations that access the .toc section.
192   return type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS;
193 }
194 
195 void elf::writePrefixedInstruction(uint8_t *loc, uint64_t insn) {
196   insn = config->isLE ? insn << 32 | insn >> 32 : insn;
197   write64(loc, insn);
198 }
199 
200 static bool addOptional(StringRef name, uint64_t value,
201                         std::vector<Defined *> &defined) {
202   Symbol *sym = symtab->find(name);
203   if (!sym || sym->isDefined())
204     return false;
205   sym->resolve(Defined{/*file=*/nullptr, saver.save(name), STB_GLOBAL,
206                        STV_HIDDEN, STT_FUNC, value,
207                        /*size=*/0, /*section=*/nullptr});
208   defined.push_back(cast<Defined>(sym));
209   return true;
210 }
211 
212 // If from is 14, write ${prefix}14: firstInsn; ${prefix}15:
213 // firstInsn+0x200008; ...; ${prefix}31: firstInsn+(31-14)*0x200008; $tail
214 // The labels are defined only if they exist in the symbol table.
215 static void writeSequence(MutableArrayRef<uint32_t> buf, const char *prefix,
216                           int from, uint32_t firstInsn,
217                           ArrayRef<uint32_t> tail) {
218   std::vector<Defined *> defined;
219   char name[16];
220   int first;
221   uint32_t *ptr = buf.data();
222   for (int r = from; r < 32; ++r) {
223     format("%s%d", prefix, r).snprint(name, sizeof(name));
224     if (addOptional(name, 4 * (r - from), defined) && defined.size() == 1)
225       first = r - from;
226     write32(ptr++, firstInsn + 0x200008 * (r - from));
227   }
228   for (uint32_t insn : tail)
229     write32(ptr++, insn);
230   assert(ptr == &*buf.end());
231 
232   if (defined.empty())
233     return;
234   // The full section content has the extent of [begin, end). We drop unused
235   // instructions and write [first,end).
236   auto *sec = make<InputSection>(
237       nullptr, SHF_ALLOC, SHT_PROGBITS, 4,
238       makeArrayRef(reinterpret_cast<uint8_t *>(buf.data() + first),
239                    4 * (buf.size() - first)),
240       ".text");
241   inputSections.push_back(sec);
242   for (Defined *sym : defined) {
243     sym->section = sec;
244     sym->value -= 4 * first;
245   }
246 }
247 
248 // Implements some save and restore functions as described by ELF V2 ABI to be
249 // compatible with GCC. With GCC -Os, when the number of call-saved registers
250 // exceeds a certain threshold, GCC generates _savegpr0_* _restgpr0_* calls and
251 // expects the linker to define them. See
252 // https://sourceware.org/pipermail/binutils/2002-February/017444.html and
253 // https://sourceware.org/pipermail/binutils/2004-August/036765.html . This is
254 // weird because libgcc.a would be the natural place. The linker generation
255 // approach has the advantage that the linker can generate multiple copies to
256 // avoid long branch thunks. However, we don't consider the advantage
257 // significant enough to complicate our trunk implementation, so we take the
258 // simple approach and synthesize .text sections providing the implementation.
259 void elf::addPPC64SaveRestore() {
260   static uint32_t savegpr0[20], restgpr0[21], savegpr1[19], restgpr1[19];
261   constexpr uint32_t blr = 0x4e800020, mtlr_0 = 0x7c0803a6;
262 
263   // _restgpr0_14: ld 14, -144(1); _restgpr0_15: ld 15, -136(1); ...
264   // Tail: ld 0, 16(1); mtlr 0; blr
265   writeSequence(restgpr0, "_restgpr0_", 14, 0xe9c1ff70,
266                 {0xe8010010, mtlr_0, blr});
267   // _restgpr1_14: ld 14, -144(12); _restgpr1_15: ld 15, -136(12); ...
268   // Tail: blr
269   writeSequence(restgpr1, "_restgpr1_", 14, 0xe9ccff70, {blr});
270   // _savegpr0_14: std 14, -144(1); _savegpr0_15: std 15, -136(1); ...
271   // Tail: std 0, 16(1); blr
272   writeSequence(savegpr0, "_savegpr0_", 14, 0xf9c1ff70, {0xf8010010, blr});
273   // _savegpr1_14: std 14, -144(12); _savegpr1_15: std 15, -136(12); ...
274   // Tail: blr
275   writeSequence(savegpr1, "_savegpr1_", 14, 0xf9ccff70, {blr});
276 }
277 
278 // Find the R_PPC64_ADDR64 in .rela.toc with matching offset.
279 template <typename ELFT>
280 static std::pair<Defined *, int64_t>
281 getRelaTocSymAndAddend(InputSectionBase *tocSec, uint64_t offset) {
282   if (tocSec->numRelocations == 0)
283     return {};
284 
285   // .rela.toc contains exclusively R_PPC64_ADDR64 relocations sorted by
286   // r_offset: 0, 8, 16, etc. For a given Offset, Offset / 8 gives us the
287   // relocation index in most cases.
288   //
289   // In rare cases a TOC entry may store a constant that doesn't need an
290   // R_PPC64_ADDR64, the corresponding r_offset is therefore missing. Offset / 8
291   // points to a relocation with larger r_offset. Do a linear probe then.
292   // Constants are extremely uncommon in .toc and the extra number of array
293   // accesses can be seen as a small constant.
294   ArrayRef<typename ELFT::Rela> relas = tocSec->template relas<ELFT>();
295   uint64_t index = std::min<uint64_t>(offset / 8, relas.size() - 1);
296   for (;;) {
297     if (relas[index].r_offset == offset) {
298       Symbol &sym = tocSec->getFile<ELFT>()->getRelocTargetSym(relas[index]);
299       return {dyn_cast<Defined>(&sym), getAddend<ELFT>(relas[index])};
300     }
301     if (relas[index].r_offset < offset || index == 0)
302       break;
303     --index;
304   }
305   return {};
306 }
307 
308 // When accessing a symbol defined in another translation unit, compilers
309 // reserve a .toc entry, allocate a local label and generate toc-indirect
310 // instructions:
311 //
312 //   addis 3, 2, .LC0@toc@ha  # R_PPC64_TOC16_HA
313 //   ld    3, .LC0@toc@l(3)   # R_PPC64_TOC16_LO_DS, load the address from a .toc entry
314 //   ld/lwa 3, 0(3)           # load the value from the address
315 //
316 //   .section .toc,"aw",@progbits
317 //   .LC0: .tc var[TC],var
318 //
319 // If var is defined, non-preemptable and addressable with a 32-bit signed
320 // offset from the toc base, the address of var can be computed by adding an
321 // offset to the toc base, saving a load.
322 //
323 //   addis 3,2,var@toc@ha     # this may be relaxed to a nop,
324 //   addi  3,3,var@toc@l      # then this becomes addi 3,2,var@toc
325 //   ld/lwa 3, 0(3)           # load the value from the address
326 //
327 // Returns true if the relaxation is performed.
328 bool elf::tryRelaxPPC64TocIndirection(const Relocation &rel, uint8_t *bufLoc) {
329   assert(config->tocOptimize);
330   if (rel.addend < 0)
331     return false;
332 
333   // If the symbol is not the .toc section, this isn't a toc-indirection.
334   Defined *defSym = dyn_cast<Defined>(rel.sym);
335   if (!defSym || !defSym->isSection() || defSym->section->name != ".toc")
336     return false;
337 
338   Defined *d;
339   int64_t addend;
340   auto *tocISB = cast<InputSectionBase>(defSym->section);
341   std::tie(d, addend) =
342       config->isLE ? getRelaTocSymAndAddend<ELF64LE>(tocISB, rel.addend)
343                    : getRelaTocSymAndAddend<ELF64BE>(tocISB, rel.addend);
344 
345   // Only non-preemptable defined symbols can be relaxed.
346   if (!d || d->isPreemptible)
347     return false;
348 
349   // R_PPC64_ADDR64 should have created a canonical PLT for the non-preemptable
350   // ifunc and changed its type to STT_FUNC.
351   assert(!d->isGnuIFunc());
352 
353   // Two instructions can materialize a 32-bit signed offset from the toc base.
354   uint64_t tocRelative = d->getVA(addend) - getPPC64TocBase();
355   if (!isInt<32>(tocRelative))
356     return false;
357 
358   // Add PPC64TocOffset that will be subtracted by PPC64::relocate().
359   target->relaxGot(bufLoc, rel, tocRelative + ppc64TocOffset);
360   return true;
361 }
362 
363 namespace {
364 class PPC64 final : public TargetInfo {
365 public:
366   PPC64();
367   int getTlsGdRelaxSkip(RelType type) const override;
368   uint32_t calcEFlags() const override;
369   RelExpr getRelExpr(RelType type, const Symbol &s,
370                      const uint8_t *loc) const override;
371   RelType getDynRel(RelType type) const override;
372   void writePltHeader(uint8_t *buf) const override;
373   void writePlt(uint8_t *buf, const Symbol &sym,
374                 uint64_t pltEntryAddr) const override;
375   void writeIplt(uint8_t *buf, const Symbol &sym,
376                  uint64_t pltEntryAddr) const override;
377   void relocate(uint8_t *loc, const Relocation &rel,
378                 uint64_t val) const override;
379   void writeGotHeader(uint8_t *buf) const override;
380   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
381                   uint64_t branchAddr, const Symbol &s,
382                   int64_t a) const override;
383   uint32_t getThunkSectionSpacing() const override;
384   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
385   RelExpr adjustRelaxExpr(RelType type, const uint8_t *data,
386                           RelExpr expr) const override;
387   void relaxGot(uint8_t *loc, const Relocation &rel,
388                 uint64_t val) const override;
389   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
390                       uint64_t val) const override;
391   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
392                       uint64_t val) const override;
393   void relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
394                       uint64_t val) const override;
395   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
396                       uint64_t val) const override;
397 
398   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
399                                         uint8_t stOther) const override;
400 };
401 } // namespace
402 
403 // Relocation masks following the #lo(value), #hi(value), #ha(value),
404 // #higher(value), #highera(value), #highest(value), and #highesta(value)
405 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
406 // document.
407 static uint16_t lo(uint64_t v) { return v; }
408 static uint16_t hi(uint64_t v) { return v >> 16; }
409 static uint16_t ha(uint64_t v) { return (v + 0x8000) >> 16; }
410 static uint16_t higher(uint64_t v) { return v >> 32; }
411 static uint16_t highera(uint64_t v) { return (v + 0x8000) >> 32; }
412 static uint16_t highest(uint64_t v) { return v >> 48; }
413 static uint16_t highesta(uint64_t v) { return (v + 0x8000) >> 48; }
414 
415 // Extracts the 'PO' field of an instruction encoding.
416 static uint8_t getPrimaryOpCode(uint32_t encoding) { return (encoding >> 26); }
417 
418 static bool isDQFormInstruction(uint32_t encoding) {
419   switch (getPrimaryOpCode(encoding)) {
420   default:
421     return false;
422   case 6: // Power10 paired loads/stores (lxvp, stxvp).
423   case 56:
424     // The only instruction with a primary opcode of 56 is `lq`.
425     return true;
426   case 61:
427     // There are both DS and DQ instruction forms with this primary opcode.
428     // Namely `lxv` and `stxv` are the DQ-forms that use it.
429     // The DS 'XO' bits being set to 01 is restricted to DQ form.
430     return (encoding & 3) == 0x1;
431   }
432 }
433 
434 static bool isDSFormInstruction(PPCLegacyInsn insn) {
435   switch (insn) {
436   default:
437     return false;
438   case PPCLegacyInsn::LWA:
439   case PPCLegacyInsn::LD:
440   case PPCLegacyInsn::LXSD:
441   case PPCLegacyInsn::LXSSP:
442   case PPCLegacyInsn::STD:
443   case PPCLegacyInsn::STXSD:
444   case PPCLegacyInsn::STXSSP:
445     return true;
446   }
447 }
448 
449 static PPCLegacyInsn getPPCLegacyInsn(uint32_t encoding) {
450   uint32_t opc = encoding & 0xfc000000;
451 
452   // If the primary opcode is shared between multiple instructions, we need to
453   // fix it up to match the actual instruction we are after.
454   if ((opc == 0xe4000000 || opc == 0xe8000000 || opc == 0xf4000000 ||
455        opc == 0xf8000000) &&
456       !isDQFormInstruction(encoding))
457     opc = encoding & 0xfc000003;
458   else if (opc == 0xf4000000)
459     opc = encoding & 0xfc000007;
460   else if (opc == 0x18000000)
461     opc = encoding & 0xfc00000f;
462 
463   // If the value is not one of the enumerators in PPCLegacyInsn, we want to
464   // return PPCLegacyInsn::NOINSN.
465   if (!checkPPCLegacyInsn(opc))
466     return PPCLegacyInsn::NOINSN;
467   return static_cast<PPCLegacyInsn>(opc);
468 }
469 
470 static PPCPrefixedInsn getPCRelativeForm(PPCLegacyInsn insn) {
471   switch (insn) {
472 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
473   case PPCLegacyInsn::Legacy:                                                  \
474     return PPCPrefixedInsn::PCRel
475 #include "PPCInsns.def"
476 #undef PCREL_OPT
477   }
478   return PPCPrefixedInsn::NOINSN;
479 }
480 
481 static LegacyToPrefixMask getInsnMask(PPCLegacyInsn insn) {
482   switch (insn) {
483 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
484   case PPCLegacyInsn::Legacy:                                                  \
485     return LegacyToPrefixMask::InsnMask
486 #include "PPCInsns.def"
487 #undef PCREL_OPT
488   }
489   return LegacyToPrefixMask::NOMASK;
490 }
491 static uint64_t getPCRelativeForm(uint32_t encoding) {
492   PPCLegacyInsn origInsn = getPPCLegacyInsn(encoding);
493   PPCPrefixedInsn pcrelInsn = getPCRelativeForm(origInsn);
494   if (pcrelInsn == PPCPrefixedInsn::NOINSN)
495     return UINT64_C(-1);
496   LegacyToPrefixMask origInsnMask = getInsnMask(origInsn);
497   uint64_t pcrelEncoding =
498       (uint64_t)pcrelInsn | (encoding & (uint64_t)origInsnMask);
499 
500   // If the mask requires moving bit 28 to bit 5, do that now.
501   if (origInsnMask == LegacyToPrefixMask::ST_STX28_TO5)
502     pcrelEncoding |= (encoding & 0x8) << 23;
503   return pcrelEncoding;
504 }
505 
506 static bool isInstructionUpdateForm(uint32_t encoding) {
507   switch (getPrimaryOpCode(encoding)) {
508   default:
509     return false;
510   case LBZU:
511   case LHAU:
512   case LHZU:
513   case LWZU:
514   case LFSU:
515   case LFDU:
516   case STBU:
517   case STHU:
518   case STWU:
519   case STFSU:
520   case STFDU:
521     return true;
522     // LWA has the same opcode as LD, and the DS bits is what differentiates
523     // between LD/LDU/LWA
524   case LD:
525   case STD:
526     return (encoding & 3) == 1;
527   }
528 }
529 
530 // Compute the total displacement between the prefixed instruction that gets
531 // to the start of the data and the load/store instruction that has the offset
532 // into the data structure.
533 // For example:
534 // paddi 3, 0, 1000, 1
535 // lwz 3, 20(3)
536 // Should add up to 1020 for total displacement.
537 static int64_t getTotalDisp(uint64_t prefixedInsn, uint32_t accessInsn) {
538   int64_t disp34 = llvm::SignExtend64(
539       ((prefixedInsn & 0x3ffff00000000) >> 16) | (prefixedInsn & 0xffff), 34);
540   int32_t disp16 = llvm::SignExtend32(accessInsn & 0xffff, 16);
541   // For DS and DQ form instructions, we need to mask out the XO bits.
542   if (isDQFormInstruction(accessInsn))
543     disp16 &= ~0xf;
544   else if (isDSFormInstruction(getPPCLegacyInsn(accessInsn)))
545     disp16 &= ~0x3;
546   return disp34 + disp16;
547 }
548 
549 // There are a number of places when we either want to read or write an
550 // instruction when handling a half16 relocation type. On big-endian the buffer
551 // pointer is pointing into the middle of the word we want to extract, and on
552 // little-endian it is pointing to the start of the word. These 2 helpers are to
553 // simplify reading and writing in that context.
554 static void writeFromHalf16(uint8_t *loc, uint32_t insn) {
555   write32(config->isLE ? loc : loc - 2, insn);
556 }
557 
558 static uint32_t readFromHalf16(const uint8_t *loc) {
559   return read32(config->isLE ? loc : loc - 2);
560 }
561 
562 static uint64_t readPrefixedInstruction(const uint8_t *loc) {
563   uint64_t fullInstr = read64(loc);
564   return config->isLE ? (fullInstr << 32 | fullInstr >> 32) : fullInstr;
565 }
566 
567 PPC64::PPC64() {
568   copyRel = R_PPC64_COPY;
569   gotRel = R_PPC64_GLOB_DAT;
570   noneRel = R_PPC64_NONE;
571   pltRel = R_PPC64_JMP_SLOT;
572   relativeRel = R_PPC64_RELATIVE;
573   iRelativeRel = R_PPC64_IRELATIVE;
574   symbolicRel = R_PPC64_ADDR64;
575   pltHeaderSize = 60;
576   pltEntrySize = 4;
577   ipltEntrySize = 16; // PPC64PltCallStub::size
578   gotBaseSymInGotPlt = false;
579   gotHeaderEntriesNum = 1;
580   gotPltHeaderEntriesNum = 2;
581   needsThunks = true;
582 
583   tlsModuleIndexRel = R_PPC64_DTPMOD64;
584   tlsOffsetRel = R_PPC64_DTPREL64;
585 
586   tlsGotRel = R_PPC64_TPREL64;
587 
588   needsMoreStackNonSplit = false;
589 
590   // We need 64K pages (at least under glibc/Linux, the loader won't
591   // set different permissions on a finer granularity than that).
592   defaultMaxPageSize = 65536;
593 
594   // The PPC64 ELF ABI v1 spec, says:
595   //
596   //   It is normally desirable to put segments with different characteristics
597   //   in separate 256 Mbyte portions of the address space, to give the
598   //   operating system full paging flexibility in the 64-bit address space.
599   //
600   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
601   // use 0x10000000 as the starting address.
602   defaultImageBase = 0x10000000;
603 
604   write32(trapInstr.data(), 0x7fe00008);
605 }
606 
607 int PPC64::getTlsGdRelaxSkip(RelType type) const {
608   // A __tls_get_addr call instruction is marked with 2 relocations:
609   //
610   //   R_PPC64_TLSGD / R_PPC64_TLSLD: marker relocation
611   //   R_PPC64_REL24: __tls_get_addr
612   //
613   // After the relaxation we no longer call __tls_get_addr and should skip both
614   // relocations to not create a false dependence on __tls_get_addr being
615   // defined.
616   if (type == R_PPC64_TLSGD || type == R_PPC64_TLSLD)
617     return 2;
618   return 1;
619 }
620 
621 static uint32_t getEFlags(InputFile *file) {
622   if (config->ekind == ELF64BEKind)
623     return cast<ObjFile<ELF64BE>>(file)->getObj().getHeader().e_flags;
624   return cast<ObjFile<ELF64LE>>(file)->getObj().getHeader().e_flags;
625 }
626 
627 // This file implements v2 ABI. This function makes sure that all
628 // object files have v2 or an unspecified version as an ABI version.
629 uint32_t PPC64::calcEFlags() const {
630   for (InputFile *f : objectFiles) {
631     uint32_t flag = getEFlags(f);
632     if (flag == 1)
633       error(toString(f) + ": ABI version 1 is not supported");
634     else if (flag > 2)
635       error(toString(f) + ": unrecognized e_flags: " + Twine(flag));
636   }
637   return 2;
638 }
639 
640 void PPC64::relaxGot(uint8_t *loc, const Relocation &rel, uint64_t val) const {
641   switch (rel.type) {
642   case R_PPC64_TOC16_HA:
643     // Convert "addis reg, 2, .LC0@toc@h" to "addis reg, 2, var@toc@h" or "nop".
644     relocate(loc, rel, val);
645     break;
646   case R_PPC64_TOC16_LO_DS: {
647     // Convert "ld reg, .LC0@toc@l(reg)" to "addi reg, reg, var@toc@l" or
648     // "addi reg, 2, var@toc".
649     uint32_t insn = readFromHalf16(loc);
650     if (getPrimaryOpCode(insn) != LD)
651       error("expected a 'ld' for got-indirect to toc-relative relaxing");
652     writeFromHalf16(loc, (insn & 0x03ffffff) | 0x38000000);
653     relocateNoSym(loc, R_PPC64_TOC16_LO, val);
654     break;
655   }
656   case R_PPC64_GOT_PCREL34: {
657     // Clear the first 8 bits of the prefix and the first 6 bits of the
658     // instruction (the primary opcode).
659     uint64_t insn = readPrefixedInstruction(loc);
660     if ((insn & 0xfc000000) != 0xe4000000)
661       error("expected a 'pld' for got-indirect to pc-relative relaxing");
662     insn &= ~0xff000000fc000000;
663 
664     // Replace the cleared bits with the values for PADDI (0x600000038000000);
665     insn |= 0x600000038000000;
666     writePrefixedInstruction(loc, insn);
667     relocate(loc, rel, val);
668     break;
669   }
670   case R_PPC64_PCREL_OPT: {
671     // We can only relax this if the R_PPC64_GOT_PCREL34 at this offset can
672     // be relaxed. The eligibility for the relaxation needs to be determined
673     // on that relocation since this one does not relocate a symbol.
674     uint64_t insn = readPrefixedInstruction(loc);
675     uint32_t accessInsn = read32(loc + rel.addend);
676     uint64_t pcRelInsn = getPCRelativeForm(accessInsn);
677 
678     // This error is not necessary for correctness but is emitted for now
679     // to ensure we don't miss these opportunities in real code. It can be
680     // removed at a later date.
681     if (pcRelInsn == UINT64_C(-1)) {
682       errorOrWarn(
683           "unrecognized instruction for R_PPC64_PCREL_OPT relaxation: 0x" +
684           Twine::utohexstr(accessInsn));
685       break;
686     }
687 
688     int64_t totalDisp = getTotalDisp(insn, accessInsn);
689     if (!isInt<34>(totalDisp))
690       break; // Displacement doesn't fit.
691     // Convert the PADDI to the prefixed version of accessInsn and convert
692     // accessInsn to a nop.
693     writePrefixedInstruction(loc, pcRelInsn |
694                                       ((totalDisp & 0x3ffff0000) << 16) |
695                                       (totalDisp & 0xffff));
696     write32(loc + rel.addend, NOP); // nop accessInsn.
697     break;
698   }
699   default:
700     llvm_unreachable("unexpected relocation type");
701   }
702 }
703 
704 void PPC64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
705                            uint64_t val) const {
706   // Reference: 3.7.4.2 of the 64-bit ELF V2 abi supplement.
707   // The general dynamic code sequence for a global `x` will look like:
708   // Instruction                    Relocation                Symbol
709   // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
710   // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
711   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
712   //                                R_PPC64_REL24               __tls_get_addr
713   // nop                            None                       None
714 
715   // Relaxing to local exec entails converting:
716   // addis r3, r2, x@got@tlsgd@ha    into      nop
717   // addi  r3, r3, x@got@tlsgd@l     into      addis r3, r13, x@tprel@ha
718   // bl __tls_get_addr(x@tlsgd)      into      nop
719   // nop                             into      addi r3, r3, x@tprel@l
720 
721   switch (rel.type) {
722   case R_PPC64_GOT_TLSGD16_HA:
723     writeFromHalf16(loc, NOP);
724     break;
725   case R_PPC64_GOT_TLSGD16:
726   case R_PPC64_GOT_TLSGD16_LO:
727     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13
728     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
729     break;
730   case R_PPC64_TLSGD:
731     write32(loc, NOP);
732     write32(loc + 4, 0x38630000); // addi r3, r3
733     // Since we are relocating a half16 type relocation and Loc + 4 points to
734     // the start of an instruction we need to advance the buffer by an extra
735     // 2 bytes on BE.
736     relocateNoSym(loc + 4 + (config->ekind == ELF64BEKind ? 2 : 0),
737                   R_PPC64_TPREL16_LO, val);
738     break;
739   default:
740     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
741   }
742 }
743 
744 void PPC64::relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
745                            uint64_t val) const {
746   // Reference: 3.7.4.3 of the 64-bit ELF V2 abi supplement.
747   // The local dynamic code sequence for a global `x` will look like:
748   // Instruction                    Relocation                Symbol
749   // addis r3, r2, x@got@tlsld@ha   R_PPC64_GOT_TLSLD16_HA      x
750   // addi  r3, r3, x@got@tlsld@l    R_PPC64_GOT_TLSLD16_LO      x
751   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSLD               x
752   //                                R_PPC64_REL24               __tls_get_addr
753   // nop                            None                       None
754 
755   // Relaxing to local exec entails converting:
756   // addis r3, r2, x@got@tlsld@ha   into      nop
757   // addi  r3, r3, x@got@tlsld@l    into      addis r3, r13, 0
758   // bl __tls_get_addr(x@tlsgd)     into      nop
759   // nop                            into      addi r3, r3, 4096
760 
761   switch (rel.type) {
762   case R_PPC64_GOT_TLSLD16_HA:
763     writeFromHalf16(loc, NOP);
764     break;
765   case R_PPC64_GOT_TLSLD16_LO:
766     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13, 0
767     break;
768   case R_PPC64_TLSLD:
769     write32(loc, NOP);
770     write32(loc + 4, 0x38631000); // addi r3, r3, 4096
771     break;
772   case R_PPC64_DTPREL16:
773   case R_PPC64_DTPREL16_HA:
774   case R_PPC64_DTPREL16_HI:
775   case R_PPC64_DTPREL16_DS:
776   case R_PPC64_DTPREL16_LO:
777   case R_PPC64_DTPREL16_LO_DS:
778     relocate(loc, rel, val);
779     break;
780   default:
781     llvm_unreachable("unsupported relocation for TLS LD to LE relaxation");
782   }
783 }
784 
785 unsigned elf::getPPCDFormOp(unsigned secondaryOp) {
786   switch (secondaryOp) {
787   case LBZX:
788     return LBZ;
789   case LHZX:
790     return LHZ;
791   case LWZX:
792     return LWZ;
793   case LDX:
794     return LD;
795   case STBX:
796     return STB;
797   case STHX:
798     return STH;
799   case STWX:
800     return STW;
801   case STDX:
802     return STD;
803   case ADD:
804     return ADDI;
805   default:
806     return 0;
807   }
808 }
809 
810 void PPC64::relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
811                            uint64_t val) const {
812   // The initial exec code sequence for a global `x` will look like:
813   // Instruction                    Relocation                Symbol
814   // addis r9, r2, x@got@tprel@ha   R_PPC64_GOT_TPREL16_HA      x
815   // ld    r9, x@got@tprel@l(r9)    R_PPC64_GOT_TPREL16_LO_DS   x
816   // add r9, r9, x@tls              R_PPC64_TLS                 x
817 
818   // Relaxing to local exec entails converting:
819   // addis r9, r2, x@got@tprel@ha       into        nop
820   // ld r9, x@got@tprel@l(r9)           into        addis r9, r13, x@tprel@ha
821   // add r9, r9, x@tls                  into        addi r9, r9, x@tprel@l
822 
823   // x@tls R_PPC64_TLS is a relocation which does not compute anything,
824   // it is replaced with r13 (thread pointer).
825 
826   // The add instruction in the initial exec sequence has multiple variations
827   // that need to be handled. If we are building an address it will use an add
828   // instruction, if we are accessing memory it will use any of the X-form
829   // indexed load or store instructions.
830 
831   unsigned offset = (config->ekind == ELF64BEKind) ? 2 : 0;
832   switch (rel.type) {
833   case R_PPC64_GOT_TPREL16_HA:
834     write32(loc - offset, NOP);
835     break;
836   case R_PPC64_GOT_TPREL16_LO_DS:
837   case R_PPC64_GOT_TPREL16_DS: {
838     uint32_t regNo = read32(loc - offset) & 0x03E00000; // bits 6-10
839     write32(loc - offset, 0x3C0D0000 | regNo);          // addis RegNo, r13
840     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
841     break;
842   }
843   case R_PPC64_TLS: {
844     uint32_t primaryOp = getPrimaryOpCode(read32(loc));
845     if (primaryOp != 31)
846       error("unrecognized instruction for IE to LE R_PPC64_TLS");
847     uint32_t secondaryOp = (read32(loc) & 0x000007FE) >> 1; // bits 21-30
848     uint32_t dFormOp = getPPCDFormOp(secondaryOp);
849     if (dFormOp == 0)
850       error("unrecognized instruction for IE to LE R_PPC64_TLS");
851     write32(loc, ((dFormOp << 26) | (read32(loc) & 0x03FFFFFF)));
852     relocateNoSym(loc + offset, R_PPC64_TPREL16_LO, val);
853     break;
854   }
855   default:
856     llvm_unreachable("unknown relocation for IE to LE");
857     break;
858   }
859 }
860 
861 RelExpr PPC64::getRelExpr(RelType type, const Symbol &s,
862                           const uint8_t *loc) const {
863   switch (type) {
864   case R_PPC64_NONE:
865     return R_NONE;
866   case R_PPC64_ADDR16:
867   case R_PPC64_ADDR16_DS:
868   case R_PPC64_ADDR16_HA:
869   case R_PPC64_ADDR16_HI:
870   case R_PPC64_ADDR16_HIGHER:
871   case R_PPC64_ADDR16_HIGHERA:
872   case R_PPC64_ADDR16_HIGHEST:
873   case R_PPC64_ADDR16_HIGHESTA:
874   case R_PPC64_ADDR16_LO:
875   case R_PPC64_ADDR16_LO_DS:
876   case R_PPC64_ADDR32:
877   case R_PPC64_ADDR64:
878     return R_ABS;
879   case R_PPC64_GOT16:
880   case R_PPC64_GOT16_DS:
881   case R_PPC64_GOT16_HA:
882   case R_PPC64_GOT16_HI:
883   case R_PPC64_GOT16_LO:
884   case R_PPC64_GOT16_LO_DS:
885     return R_GOT_OFF;
886   case R_PPC64_TOC16:
887   case R_PPC64_TOC16_DS:
888   case R_PPC64_TOC16_HI:
889   case R_PPC64_TOC16_LO:
890     return R_GOTREL;
891   case R_PPC64_GOT_PCREL34:
892   case R_PPC64_PCREL_OPT:
893     return R_GOT_PC;
894   case R_PPC64_TOC16_HA:
895   case R_PPC64_TOC16_LO_DS:
896     return config->tocOptimize ? R_PPC64_RELAX_TOC : R_GOTREL;
897   case R_PPC64_TOC:
898     return R_PPC64_TOCBASE;
899   case R_PPC64_REL14:
900   case R_PPC64_REL24:
901     return R_PPC64_CALL_PLT;
902   case R_PPC64_REL24_NOTOC:
903     return R_PLT_PC;
904   case R_PPC64_REL16_LO:
905   case R_PPC64_REL16_HA:
906   case R_PPC64_REL16_HI:
907   case R_PPC64_REL32:
908   case R_PPC64_REL64:
909   case R_PPC64_PCREL34:
910     return R_PC;
911   case R_PPC64_GOT_TLSGD16:
912   case R_PPC64_GOT_TLSGD16_HA:
913   case R_PPC64_GOT_TLSGD16_HI:
914   case R_PPC64_GOT_TLSGD16_LO:
915     return R_TLSGD_GOT;
916   case R_PPC64_GOT_TLSLD16:
917   case R_PPC64_GOT_TLSLD16_HA:
918   case R_PPC64_GOT_TLSLD16_HI:
919   case R_PPC64_GOT_TLSLD16_LO:
920     return R_TLSLD_GOT;
921   case R_PPC64_GOT_TPREL16_HA:
922   case R_PPC64_GOT_TPREL16_LO_DS:
923   case R_PPC64_GOT_TPREL16_DS:
924   case R_PPC64_GOT_TPREL16_HI:
925     return R_GOT_OFF;
926   case R_PPC64_GOT_DTPREL16_HA:
927   case R_PPC64_GOT_DTPREL16_LO_DS:
928   case R_PPC64_GOT_DTPREL16_DS:
929   case R_PPC64_GOT_DTPREL16_HI:
930     return R_TLSLD_GOT_OFF;
931   case R_PPC64_TPREL16:
932   case R_PPC64_TPREL16_HA:
933   case R_PPC64_TPREL16_LO:
934   case R_PPC64_TPREL16_HI:
935   case R_PPC64_TPREL16_DS:
936   case R_PPC64_TPREL16_LO_DS:
937   case R_PPC64_TPREL16_HIGHER:
938   case R_PPC64_TPREL16_HIGHERA:
939   case R_PPC64_TPREL16_HIGHEST:
940   case R_PPC64_TPREL16_HIGHESTA:
941   case R_PPC64_TPREL34:
942     return R_TLS;
943   case R_PPC64_DTPREL16:
944   case R_PPC64_DTPREL16_DS:
945   case R_PPC64_DTPREL16_HA:
946   case R_PPC64_DTPREL16_HI:
947   case R_PPC64_DTPREL16_HIGHER:
948   case R_PPC64_DTPREL16_HIGHERA:
949   case R_PPC64_DTPREL16_HIGHEST:
950   case R_PPC64_DTPREL16_HIGHESTA:
951   case R_PPC64_DTPREL16_LO:
952   case R_PPC64_DTPREL16_LO_DS:
953   case R_PPC64_DTPREL64:
954     return R_DTPREL;
955   case R_PPC64_TLSGD:
956     return R_TLSDESC_CALL;
957   case R_PPC64_TLSLD:
958     return R_TLSLD_HINT;
959   case R_PPC64_TLS:
960     return R_TLSIE_HINT;
961   default:
962     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
963           ") against symbol " + toString(s));
964     return R_NONE;
965   }
966 }
967 
968 RelType PPC64::getDynRel(RelType type) const {
969   if (type == R_PPC64_ADDR64 || type == R_PPC64_TOC)
970     return R_PPC64_ADDR64;
971   return R_PPC64_NONE;
972 }
973 
974 void PPC64::writeGotHeader(uint8_t *buf) const {
975   write64(buf, getPPC64TocBase());
976 }
977 
978 void PPC64::writePltHeader(uint8_t *buf) const {
979   // The generic resolver stub goes first.
980   write32(buf +  0, 0x7c0802a6); // mflr r0
981   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
982   write32(buf +  8, 0x7d6802a6); // mflr r11
983   write32(buf + 12, 0x7c0803a6); // mtlr r0
984   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
985   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
986   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
987   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
988   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
989   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
990   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
991   write32(buf + 44, 0x7d8903a6); // mtctr   r12
992   write32(buf + 48, 0x4e800420); // bctr
993 
994   // The 'bcl' instruction will set the link register to the address of the
995   // following instruction ('mflr r11'). Here we store the offset from that
996   // instruction  to the first entry in the GotPlt section.
997   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
998   write64(buf + 52, gotPltOffset);
999 }
1000 
1001 void PPC64::writePlt(uint8_t *buf, const Symbol &sym,
1002                      uint64_t /*pltEntryAddr*/) const {
1003   int32_t offset = pltHeaderSize + sym.pltIndex * pltEntrySize;
1004   // bl __glink_PLTresolve
1005   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
1006 }
1007 
1008 void PPC64::writeIplt(uint8_t *buf, const Symbol &sym,
1009                       uint64_t /*pltEntryAddr*/) const {
1010   writePPC64LoadAndBranch(buf, sym.getGotPltVA() - getPPC64TocBase());
1011 }
1012 
1013 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
1014   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
1015   uint64_t tocBiasedVal = val - ppc64TocOffset;
1016   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
1017   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
1018 
1019   switch (type) {
1020   // TOC biased relocation.
1021   case R_PPC64_GOT16:
1022   case R_PPC64_GOT_TLSGD16:
1023   case R_PPC64_GOT_TLSLD16:
1024   case R_PPC64_TOC16:
1025     return {R_PPC64_ADDR16, tocBiasedVal};
1026   case R_PPC64_GOT16_DS:
1027   case R_PPC64_TOC16_DS:
1028   case R_PPC64_GOT_TPREL16_DS:
1029   case R_PPC64_GOT_DTPREL16_DS:
1030     return {R_PPC64_ADDR16_DS, tocBiasedVal};
1031   case R_PPC64_GOT16_HA:
1032   case R_PPC64_GOT_TLSGD16_HA:
1033   case R_PPC64_GOT_TLSLD16_HA:
1034   case R_PPC64_GOT_TPREL16_HA:
1035   case R_PPC64_GOT_DTPREL16_HA:
1036   case R_PPC64_TOC16_HA:
1037     return {R_PPC64_ADDR16_HA, tocBiasedVal};
1038   case R_PPC64_GOT16_HI:
1039   case R_PPC64_GOT_TLSGD16_HI:
1040   case R_PPC64_GOT_TLSLD16_HI:
1041   case R_PPC64_GOT_TPREL16_HI:
1042   case R_PPC64_GOT_DTPREL16_HI:
1043   case R_PPC64_TOC16_HI:
1044     return {R_PPC64_ADDR16_HI, tocBiasedVal};
1045   case R_PPC64_GOT16_LO:
1046   case R_PPC64_GOT_TLSGD16_LO:
1047   case R_PPC64_GOT_TLSLD16_LO:
1048   case R_PPC64_TOC16_LO:
1049     return {R_PPC64_ADDR16_LO, tocBiasedVal};
1050   case R_PPC64_GOT16_LO_DS:
1051   case R_PPC64_TOC16_LO_DS:
1052   case R_PPC64_GOT_TPREL16_LO_DS:
1053   case R_PPC64_GOT_DTPREL16_LO_DS:
1054     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
1055 
1056   // Dynamic Thread pointer biased relocation types.
1057   case R_PPC64_DTPREL16:
1058     return {R_PPC64_ADDR16, dtpBiasedVal};
1059   case R_PPC64_DTPREL16_DS:
1060     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
1061   case R_PPC64_DTPREL16_HA:
1062     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
1063   case R_PPC64_DTPREL16_HI:
1064     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
1065   case R_PPC64_DTPREL16_HIGHER:
1066     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
1067   case R_PPC64_DTPREL16_HIGHERA:
1068     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
1069   case R_PPC64_DTPREL16_HIGHEST:
1070     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
1071   case R_PPC64_DTPREL16_HIGHESTA:
1072     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
1073   case R_PPC64_DTPREL16_LO:
1074     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
1075   case R_PPC64_DTPREL16_LO_DS:
1076     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
1077   case R_PPC64_DTPREL64:
1078     return {R_PPC64_ADDR64, dtpBiasedVal};
1079 
1080   default:
1081     return {type, val};
1082   }
1083 }
1084 
1085 static bool isTocOptType(RelType type) {
1086   switch (type) {
1087   case R_PPC64_GOT16_HA:
1088   case R_PPC64_GOT16_LO_DS:
1089   case R_PPC64_TOC16_HA:
1090   case R_PPC64_TOC16_LO_DS:
1091   case R_PPC64_TOC16_LO:
1092     return true;
1093   default:
1094     return false;
1095   }
1096 }
1097 
1098 void PPC64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
1099   RelType type = rel.type;
1100   bool shouldTocOptimize =  isTocOptType(type);
1101   // For dynamic thread pointer relative, toc-relative, and got-indirect
1102   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
1103   std::tie(type, val) = toAddr16Rel(type, val);
1104 
1105   switch (type) {
1106   case R_PPC64_ADDR14: {
1107     checkAlignment(loc, val, 4, rel);
1108     // Preserve the AA/LK bits in the branch instruction
1109     uint8_t aalk = loc[3];
1110     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
1111     break;
1112   }
1113   case R_PPC64_ADDR16:
1114     checkIntUInt(loc, val, 16, rel);
1115     write16(loc, val);
1116     break;
1117   case R_PPC64_ADDR32:
1118     checkIntUInt(loc, val, 32, rel);
1119     write32(loc, val);
1120     break;
1121   case R_PPC64_ADDR16_DS:
1122   case R_PPC64_TPREL16_DS: {
1123     checkInt(loc, val, 16, rel);
1124     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1125     // DS-form instructions only use bits 30-31.
1126     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
1127     checkAlignment(loc, lo(val), mask + 1, rel);
1128     write16(loc, (read16(loc) & mask) | lo(val));
1129   } break;
1130   case R_PPC64_ADDR16_HA:
1131   case R_PPC64_REL16_HA:
1132   case R_PPC64_TPREL16_HA:
1133     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
1134       writeFromHalf16(loc, NOP);
1135     else
1136       write16(loc, ha(val));
1137     break;
1138   case R_PPC64_ADDR16_HI:
1139   case R_PPC64_REL16_HI:
1140   case R_PPC64_TPREL16_HI:
1141     write16(loc, hi(val));
1142     break;
1143   case R_PPC64_ADDR16_HIGHER:
1144   case R_PPC64_TPREL16_HIGHER:
1145     write16(loc, higher(val));
1146     break;
1147   case R_PPC64_ADDR16_HIGHERA:
1148   case R_PPC64_TPREL16_HIGHERA:
1149     write16(loc, highera(val));
1150     break;
1151   case R_PPC64_ADDR16_HIGHEST:
1152   case R_PPC64_TPREL16_HIGHEST:
1153     write16(loc, highest(val));
1154     break;
1155   case R_PPC64_ADDR16_HIGHESTA:
1156   case R_PPC64_TPREL16_HIGHESTA:
1157     write16(loc, highesta(val));
1158     break;
1159   case R_PPC64_ADDR16_LO:
1160   case R_PPC64_REL16_LO:
1161   case R_PPC64_TPREL16_LO:
1162     // When the high-adjusted part of a toc relocation evaluates to 0, it is
1163     // changed into a nop. The lo part then needs to be updated to use the
1164     // toc-pointer register r2, as the base register.
1165     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1166       uint32_t insn = readFromHalf16(loc);
1167       if (isInstructionUpdateForm(insn))
1168         error(getErrorLocation(loc) +
1169               "can't toc-optimize an update instruction: 0x" +
1170               utohexstr(insn));
1171       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
1172     } else {
1173       write16(loc, lo(val));
1174     }
1175     break;
1176   case R_PPC64_ADDR16_LO_DS:
1177   case R_PPC64_TPREL16_LO_DS: {
1178     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1179     // DS-form instructions only use bits 30-31.
1180     uint32_t insn = readFromHalf16(loc);
1181     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
1182     checkAlignment(loc, lo(val), mask + 1, rel);
1183     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1184       // When the high-adjusted part of a toc relocation evaluates to 0, it is
1185       // changed into a nop. The lo part then needs to be updated to use the toc
1186       // pointer register r2, as the base register.
1187       if (isInstructionUpdateForm(insn))
1188         error(getErrorLocation(loc) +
1189               "Can't toc-optimize an update instruction: 0x" +
1190               Twine::utohexstr(insn));
1191       insn &= 0xffe00000 | mask;
1192       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
1193     } else {
1194       write16(loc, (read16(loc) & mask) | lo(val));
1195     }
1196   } break;
1197   case R_PPC64_TPREL16:
1198     checkInt(loc, val, 16, rel);
1199     write16(loc, val);
1200     break;
1201   case R_PPC64_REL32:
1202     checkInt(loc, val, 32, rel);
1203     write32(loc, val);
1204     break;
1205   case R_PPC64_ADDR64:
1206   case R_PPC64_REL64:
1207   case R_PPC64_TOC:
1208     write64(loc, val);
1209     break;
1210   case R_PPC64_REL14: {
1211     uint32_t mask = 0x0000FFFC;
1212     checkInt(loc, val, 16, rel);
1213     checkAlignment(loc, val, 4, rel);
1214     write32(loc, (read32(loc) & ~mask) | (val & mask));
1215     break;
1216   }
1217   case R_PPC64_REL24:
1218   case R_PPC64_REL24_NOTOC: {
1219     uint32_t mask = 0x03FFFFFC;
1220     checkInt(loc, val, 26, rel);
1221     checkAlignment(loc, val, 4, rel);
1222     write32(loc, (read32(loc) & ~mask) | (val & mask));
1223     break;
1224   }
1225   case R_PPC64_DTPREL64:
1226     write64(loc, val - dynamicThreadPointerOffset);
1227     break;
1228   case R_PPC64_PCREL34: {
1229     const uint64_t si0Mask = 0x00000003ffff0000;
1230     const uint64_t si1Mask = 0x000000000000ffff;
1231     const uint64_t fullMask = 0x0003ffff0000ffff;
1232     checkInt(loc, val, 34, rel);
1233 
1234     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1235     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1236                              (val & si1Mask));
1237     break;
1238   }
1239   case R_PPC64_GOT_PCREL34:
1240   case R_PPC64_TPREL34: {
1241     const uint64_t si0Mask = 0x00000003ffff0000;
1242     const uint64_t si1Mask = 0x000000000000ffff;
1243     const uint64_t fullMask = 0x0003ffff0000ffff;
1244     checkInt(loc, val, 34, rel);
1245 
1246     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1247     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1248                              (val & si1Mask));
1249     break;
1250   }
1251   // If we encounter a PCREL_OPT relocation that we won't optimize.
1252   case R_PPC64_PCREL_OPT:
1253     break;
1254   default:
1255     llvm_unreachable("unknown relocation");
1256   }
1257 }
1258 
1259 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
1260                        uint64_t branchAddr, const Symbol &s, int64_t a) const {
1261   if (type != R_PPC64_REL14 && type != R_PPC64_REL24 &&
1262       type != R_PPC64_REL24_NOTOC)
1263     return false;
1264 
1265   // If a function is in the Plt it needs to be called with a call-stub.
1266   if (s.isInPlt())
1267     return true;
1268 
1269   // This check looks at the st_other bits of the callee with relocation
1270   // R_PPC64_REL14 or R_PPC64_REL24. If the value is 1, then the callee
1271   // clobbers the TOC and we need an R2 save stub.
1272   if (type != R_PPC64_REL24_NOTOC && (s.stOther >> 5) == 1)
1273     return true;
1274 
1275   if (type == R_PPC64_REL24_NOTOC && (s.stOther >> 5) > 1)
1276     return true;
1277 
1278   // If a symbol is a weak undefined and we are compiling an executable
1279   // it doesn't need a range-extending thunk since it can't be called.
1280   if (s.isUndefWeak() && !config->shared)
1281     return false;
1282 
1283   // If the offset exceeds the range of the branch type then it will need
1284   // a range-extending thunk.
1285   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
1286   return !inBranchRange(type, branchAddr,
1287                         s.getVA(a) +
1288                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
1289 }
1290 
1291 uint32_t PPC64::getThunkSectionSpacing() const {
1292   // See comment in Arch/ARM.cpp for a more detailed explanation of
1293   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
1294   // R_PPC64_REL24, which is used by unconditional branch instructions.
1295   // 0x2000000 = (1 << 24-1) * 4
1296   return 0x2000000;
1297 }
1298 
1299 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
1300   int64_t offset = dst - src;
1301   if (type == R_PPC64_REL14)
1302     return isInt<16>(offset);
1303   if (type == R_PPC64_REL24 || type == R_PPC64_REL24_NOTOC)
1304     return isInt<26>(offset);
1305   llvm_unreachable("unsupported relocation type used in branch");
1306 }
1307 
1308 RelExpr PPC64::adjustRelaxExpr(RelType type, const uint8_t *data,
1309                                RelExpr expr) const {
1310   if ((type == R_PPC64_GOT_PCREL34 || type == R_PPC64_PCREL_OPT) &&
1311       config->pcRelOptimize) {
1312     // It only makes sense to optimize pld since paddi means that the address
1313     // of the object in the GOT is required rather than the object itself.
1314     assert(data && "Expecting an instruction encoding here");
1315     if ((readPrefixedInstruction(data) & 0xfc000000) == 0xe4000000)
1316       return R_PPC64_RELAX_GOT_PC;
1317   }
1318   if (expr == R_RELAX_TLS_GD_TO_IE)
1319     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
1320   if (expr == R_RELAX_TLS_LD_TO_LE)
1321     return R_RELAX_TLS_LD_TO_LE_ABS;
1322   return expr;
1323 }
1324 
1325 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
1326 // The general dynamic code sequence for a global `x` uses 4 instructions.
1327 // Instruction                    Relocation                Symbol
1328 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
1329 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
1330 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
1331 //                                R_PPC64_REL24               __tls_get_addr
1332 // nop                            None                       None
1333 //
1334 // Relaxing to initial-exec entails:
1335 // 1) Convert the addis/addi pair that builds the address of the tls_index
1336 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
1337 // 2) Convert the call to __tls_get_addr to a nop.
1338 // 3) Convert the nop following the call to an add of the loaded offset to the
1339 //    thread pointer.
1340 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
1341 // used as the relaxation hint for both steps 2 and 3.
1342 void PPC64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
1343                            uint64_t val) const {
1344   switch (rel.type) {
1345   case R_PPC64_GOT_TLSGD16_HA:
1346     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
1347     //                      addis rT, r2, sym@got@tprel@ha.
1348     relocateNoSym(loc, R_PPC64_GOT_TPREL16_HA, val);
1349     return;
1350   case R_PPC64_GOT_TLSGD16:
1351   case R_PPC64_GOT_TLSGD16_LO: {
1352     // Relax from addi  r3, rA, sym@got@tlsgd@l to
1353     //            ld r3, sym@got@tprel@l(rA)
1354     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
1355     writeFromHalf16(loc, 0xe8600000 | ra);
1356     relocateNoSym(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
1357     return;
1358   }
1359   case R_PPC64_TLSGD:
1360     write32(loc, NOP);            // bl __tls_get_addr(sym@tlsgd) --> nop
1361     write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
1362     return;
1363   default:
1364     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
1365   }
1366 }
1367 
1368 // The prologue for a split-stack function is expected to look roughly
1369 // like this:
1370 //    .Lglobal_entry_point:
1371 //      # TOC pointer initialization.
1372 //      ...
1373 //    .Llocal_entry_point:
1374 //      # load the __private_ss member of the threads tcbhead.
1375 //      ld r0,-0x7000-64(r13)
1376 //      # subtract the functions stack size from the stack pointer.
1377 //      addis r12, r1, ha(-stack-frame size)
1378 //      addi  r12, r12, l(-stack-frame size)
1379 //      # compare needed to actual and branch to allocate_more_stack if more
1380 //      # space is needed, otherwise fallthrough to 'normal' function body.
1381 //      cmpld cr7,r12,r0
1382 //      blt- cr7, .Lallocate_more_stack
1383 //
1384 // -) The allocate_more_stack block might be placed after the split-stack
1385 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1386 //    instead.
1387 // -) If either the addis or addi is not needed due to the stack size being
1388 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1389 //    but there will always be 2 instructions the linker can overwrite for the
1390 //    adjusted stack size.
1391 //
1392 // The linkers job here is to increase the stack size used in the addis/addi
1393 // pair by split-stack-size-adjust.
1394 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1395 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1396 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1397                                              uint8_t stOther) const {
1398   // If the caller has a global entry point adjust the buffer past it. The start
1399   // of the split-stack prologue will be at the local entry point.
1400   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1401 
1402   // At the very least we expect to see a load of some split-stack data from the
1403   // tcb, and 2 instructions that calculate the ending stack address this
1404   // function will require. If there is not enough room for at least 3
1405   // instructions it can't be a split-stack prologue.
1406   if (loc + 12 >= end)
1407     return false;
1408 
1409   // First instruction must be `ld r0, -0x7000-64(r13)`
1410   if (read32(loc) != 0xe80d8fc0)
1411     return false;
1412 
1413   int16_t hiImm = 0;
1414   int16_t loImm = 0;
1415   // First instruction can be either an addis if the frame size is larger then
1416   // 32K, or an addi if the size is less then 32K.
1417   int32_t firstInstr = read32(loc + 4);
1418   if (getPrimaryOpCode(firstInstr) == 15) {
1419     hiImm = firstInstr & 0xFFFF;
1420   } else if (getPrimaryOpCode(firstInstr) == 14) {
1421     loImm = firstInstr & 0xFFFF;
1422   } else {
1423     return false;
1424   }
1425 
1426   // Second instruction is either an addi or a nop. If the first instruction was
1427   // an addi then LoImm is set and the second instruction must be a nop.
1428   uint32_t secondInstr = read32(loc + 8);
1429   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1430     loImm = secondInstr & 0xFFFF;
1431   } else if (secondInstr != NOP) {
1432     return false;
1433   }
1434 
1435   // The register operands of the first instruction should be the stack-pointer
1436   // (r1) as the input (RA) and r12 as the output (RT). If the second
1437   // instruction is not a nop, then it should use r12 as both input and output.
1438   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1439                              uint8_t expectedRA) {
1440     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1441            ((instr & 0x1F0000) >> 16 == expectedRA);
1442   };
1443   if (!checkRegOperands(firstInstr, 12, 1))
1444     return false;
1445   if (secondInstr != NOP && !checkRegOperands(secondInstr, 12, 12))
1446     return false;
1447 
1448   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1449   // Check that the adjusted size doesn't overflow what we can represent with 2
1450   // instructions.
1451   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1452     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1453     return false;
1454   }
1455 
1456   int32_t adjustedStackFrameSize =
1457       stackFrameSize - config->splitStackAdjustSize;
1458 
1459   loImm = adjustedStackFrameSize & 0xFFFF;
1460   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1461   if (hiImm) {
1462     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1463     // If the low immediate is zero the second instruction will be a nop.
1464     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : NOP;
1465     write32(loc + 8, secondInstr);
1466   } else {
1467     // addi r12, r1, imm
1468     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1469     write32(loc + 8, NOP);
1470   }
1471 
1472   return true;
1473 }
1474 
1475 TargetInfo *elf::getPPC64TargetInfo() {
1476   static PPC64 target;
1477   return &target;
1478 }
1479