xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/PPC64.cpp (revision 2d5d2a986ce1a93b8567dbdf3f80bc2b545d6998)
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   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
373   void writePltHeader(uint8_t *buf) const override;
374   void writePlt(uint8_t *buf, const Symbol &sym,
375                 uint64_t pltEntryAddr) const override;
376   void writeIplt(uint8_t *buf, const Symbol &sym,
377                  uint64_t pltEntryAddr) const override;
378   void relocate(uint8_t *loc, const Relocation &rel,
379                 uint64_t val) const override;
380   void writeGotHeader(uint8_t *buf) const override;
381   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
382                   uint64_t branchAddr, const Symbol &s,
383                   int64_t a) const override;
384   uint32_t getThunkSectionSpacing() const override;
385   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
386   RelExpr adjustTlsExpr(RelType type, RelExpr expr) const override;
387   RelExpr adjustGotPcExpr(RelType type, int64_t addend,
388                           const uint8_t *loc) const override;
389   void relaxGot(uint8_t *loc, const Relocation &rel,
390                 uint64_t val) const override;
391   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
392                       uint64_t val) const override;
393   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
394                       uint64_t val) const override;
395   void relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
396                       uint64_t val) const override;
397   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
398                       uint64_t val) const override;
399 
400   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
401                                         uint8_t stOther) const override;
402 };
403 } // namespace
404 
405 // Relocation masks following the #lo(value), #hi(value), #ha(value),
406 // #higher(value), #highera(value), #highest(value), and #highesta(value)
407 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
408 // document.
409 static uint16_t lo(uint64_t v) { return v; }
410 static uint16_t hi(uint64_t v) { return v >> 16; }
411 static uint64_t ha(uint64_t v) { return (v + 0x8000) >> 16; }
412 static uint16_t higher(uint64_t v) { return v >> 32; }
413 static uint16_t highera(uint64_t v) { return (v + 0x8000) >> 32; }
414 static uint16_t highest(uint64_t v) { return v >> 48; }
415 static uint16_t highesta(uint64_t v) { return (v + 0x8000) >> 48; }
416 
417 // Extracts the 'PO' field of an instruction encoding.
418 static uint8_t getPrimaryOpCode(uint32_t encoding) { return (encoding >> 26); }
419 
420 static bool isDQFormInstruction(uint32_t encoding) {
421   switch (getPrimaryOpCode(encoding)) {
422   default:
423     return false;
424   case 6: // Power10 paired loads/stores (lxvp, stxvp).
425   case 56:
426     // The only instruction with a primary opcode of 56 is `lq`.
427     return true;
428   case 61:
429     // There are both DS and DQ instruction forms with this primary opcode.
430     // Namely `lxv` and `stxv` are the DQ-forms that use it.
431     // The DS 'XO' bits being set to 01 is restricted to DQ form.
432     return (encoding & 3) == 0x1;
433   }
434 }
435 
436 static bool isDSFormInstruction(PPCLegacyInsn insn) {
437   switch (insn) {
438   default:
439     return false;
440   case PPCLegacyInsn::LWA:
441   case PPCLegacyInsn::LD:
442   case PPCLegacyInsn::LXSD:
443   case PPCLegacyInsn::LXSSP:
444   case PPCLegacyInsn::STD:
445   case PPCLegacyInsn::STXSD:
446   case PPCLegacyInsn::STXSSP:
447     return true;
448   }
449 }
450 
451 static PPCLegacyInsn getPPCLegacyInsn(uint32_t encoding) {
452   uint32_t opc = encoding & 0xfc000000;
453 
454   // If the primary opcode is shared between multiple instructions, we need to
455   // fix it up to match the actual instruction we are after.
456   if ((opc == 0xe4000000 || opc == 0xe8000000 || opc == 0xf4000000 ||
457        opc == 0xf8000000) &&
458       !isDQFormInstruction(encoding))
459     opc = encoding & 0xfc000003;
460   else if (opc == 0xf4000000)
461     opc = encoding & 0xfc000007;
462   else if (opc == 0x18000000)
463     opc = encoding & 0xfc00000f;
464 
465   // If the value is not one of the enumerators in PPCLegacyInsn, we want to
466   // return PPCLegacyInsn::NOINSN.
467   if (!checkPPCLegacyInsn(opc))
468     return PPCLegacyInsn::NOINSN;
469   return static_cast<PPCLegacyInsn>(opc);
470 }
471 
472 static PPCPrefixedInsn getPCRelativeForm(PPCLegacyInsn insn) {
473   switch (insn) {
474 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
475   case PPCLegacyInsn::Legacy:                                                  \
476     return PPCPrefixedInsn::PCRel
477 #include "PPCInsns.def"
478 #undef PCREL_OPT
479   }
480   return PPCPrefixedInsn::NOINSN;
481 }
482 
483 static LegacyToPrefixMask getInsnMask(PPCLegacyInsn insn) {
484   switch (insn) {
485 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
486   case PPCLegacyInsn::Legacy:                                                  \
487     return LegacyToPrefixMask::InsnMask
488 #include "PPCInsns.def"
489 #undef PCREL_OPT
490   }
491   return LegacyToPrefixMask::NOMASK;
492 }
493 static uint64_t getPCRelativeForm(uint32_t encoding) {
494   PPCLegacyInsn origInsn = getPPCLegacyInsn(encoding);
495   PPCPrefixedInsn pcrelInsn = getPCRelativeForm(origInsn);
496   if (pcrelInsn == PPCPrefixedInsn::NOINSN)
497     return UINT64_C(-1);
498   LegacyToPrefixMask origInsnMask = getInsnMask(origInsn);
499   uint64_t pcrelEncoding =
500       (uint64_t)pcrelInsn | (encoding & (uint64_t)origInsnMask);
501 
502   // If the mask requires moving bit 28 to bit 5, do that now.
503   if (origInsnMask == LegacyToPrefixMask::ST_STX28_TO5)
504     pcrelEncoding |= (encoding & 0x8) << 23;
505   return pcrelEncoding;
506 }
507 
508 static bool isInstructionUpdateForm(uint32_t encoding) {
509   switch (getPrimaryOpCode(encoding)) {
510   default:
511     return false;
512   case LBZU:
513   case LHAU:
514   case LHZU:
515   case LWZU:
516   case LFSU:
517   case LFDU:
518   case STBU:
519   case STHU:
520   case STWU:
521   case STFSU:
522   case STFDU:
523     return true;
524     // LWA has the same opcode as LD, and the DS bits is what differentiates
525     // between LD/LDU/LWA
526   case LD:
527   case STD:
528     return (encoding & 3) == 1;
529   }
530 }
531 
532 // Compute the total displacement between the prefixed instruction that gets
533 // to the start of the data and the load/store instruction that has the offset
534 // into the data structure.
535 // For example:
536 // paddi 3, 0, 1000, 1
537 // lwz 3, 20(3)
538 // Should add up to 1020 for total displacement.
539 static int64_t getTotalDisp(uint64_t prefixedInsn, uint32_t accessInsn) {
540   int64_t disp34 = llvm::SignExtend64(
541       ((prefixedInsn & 0x3ffff00000000) >> 16) | (prefixedInsn & 0xffff), 34);
542   int32_t disp16 = llvm::SignExtend32(accessInsn & 0xffff, 16);
543   // For DS and DQ form instructions, we need to mask out the XO bits.
544   if (isDQFormInstruction(accessInsn))
545     disp16 &= ~0xf;
546   else if (isDSFormInstruction(getPPCLegacyInsn(accessInsn)))
547     disp16 &= ~0x3;
548   return disp34 + disp16;
549 }
550 
551 // There are a number of places when we either want to read or write an
552 // instruction when handling a half16 relocation type. On big-endian the buffer
553 // pointer is pointing into the middle of the word we want to extract, and on
554 // little-endian it is pointing to the start of the word. These 2 helpers are to
555 // simplify reading and writing in that context.
556 static void writeFromHalf16(uint8_t *loc, uint32_t insn) {
557   write32(config->isLE ? loc : loc - 2, insn);
558 }
559 
560 static uint32_t readFromHalf16(const uint8_t *loc) {
561   return read32(config->isLE ? loc : loc - 2);
562 }
563 
564 static uint64_t readPrefixedInstruction(const uint8_t *loc) {
565   uint64_t fullInstr = read64(loc);
566   return config->isLE ? (fullInstr << 32 | fullInstr >> 32) : fullInstr;
567 }
568 
569 PPC64::PPC64() {
570   copyRel = R_PPC64_COPY;
571   gotRel = R_PPC64_GLOB_DAT;
572   noneRel = R_PPC64_NONE;
573   pltRel = R_PPC64_JMP_SLOT;
574   relativeRel = R_PPC64_RELATIVE;
575   iRelativeRel = R_PPC64_IRELATIVE;
576   symbolicRel = R_PPC64_ADDR64;
577   pltHeaderSize = 60;
578   pltEntrySize = 4;
579   ipltEntrySize = 16; // PPC64PltCallStub::size
580   gotBaseSymInGotPlt = false;
581   gotHeaderEntriesNum = 1;
582   gotPltHeaderEntriesNum = 2;
583   needsThunks = true;
584 
585   tlsModuleIndexRel = R_PPC64_DTPMOD64;
586   tlsOffsetRel = R_PPC64_DTPREL64;
587 
588   tlsGotRel = R_PPC64_TPREL64;
589 
590   needsMoreStackNonSplit = false;
591 
592   // We need 64K pages (at least under glibc/Linux, the loader won't
593   // set different permissions on a finer granularity than that).
594   defaultMaxPageSize = 65536;
595 
596   // The PPC64 ELF ABI v1 spec, says:
597   //
598   //   It is normally desirable to put segments with different characteristics
599   //   in separate 256 Mbyte portions of the address space, to give the
600   //   operating system full paging flexibility in the 64-bit address space.
601   //
602   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
603   // use 0x10000000 as the starting address.
604   defaultImageBase = 0x10000000;
605 
606   write32(trapInstr.data(), 0x7fe00008);
607 }
608 
609 int PPC64::getTlsGdRelaxSkip(RelType type) const {
610   // A __tls_get_addr call instruction is marked with 2 relocations:
611   //
612   //   R_PPC64_TLSGD / R_PPC64_TLSLD: marker relocation
613   //   R_PPC64_REL24: __tls_get_addr
614   //
615   // After the relaxation we no longer call __tls_get_addr and should skip both
616   // relocations to not create a false dependence on __tls_get_addr being
617   // defined.
618   if (type == R_PPC64_TLSGD || type == R_PPC64_TLSLD)
619     return 2;
620   return 1;
621 }
622 
623 static uint32_t getEFlags(InputFile *file) {
624   if (config->ekind == ELF64BEKind)
625     return cast<ObjFile<ELF64BE>>(file)->getObj().getHeader().e_flags;
626   return cast<ObjFile<ELF64LE>>(file)->getObj().getHeader().e_flags;
627 }
628 
629 // This file implements v2 ABI. This function makes sure that all
630 // object files have v2 or an unspecified version as an ABI version.
631 uint32_t PPC64::calcEFlags() const {
632   for (InputFile *f : objectFiles) {
633     uint32_t flag = getEFlags(f);
634     if (flag == 1)
635       error(toString(f) + ": ABI version 1 is not supported");
636     else if (flag > 2)
637       error(toString(f) + ": unrecognized e_flags: " + Twine(flag));
638   }
639   return 2;
640 }
641 
642 void PPC64::relaxGot(uint8_t *loc, const Relocation &rel, uint64_t val) const {
643   switch (rel.type) {
644   case R_PPC64_TOC16_HA:
645     // Convert "addis reg, 2, .LC0@toc@h" to "addis reg, 2, var@toc@h" or "nop".
646     relocate(loc, rel, val);
647     break;
648   case R_PPC64_TOC16_LO_DS: {
649     // Convert "ld reg, .LC0@toc@l(reg)" to "addi reg, reg, var@toc@l" or
650     // "addi reg, 2, var@toc".
651     uint32_t insn = readFromHalf16(loc);
652     if (getPrimaryOpCode(insn) != LD)
653       error("expected a 'ld' for got-indirect to toc-relative relaxing");
654     writeFromHalf16(loc, (insn & 0x03ffffff) | 0x38000000);
655     relocateNoSym(loc, R_PPC64_TOC16_LO, val);
656     break;
657   }
658   case R_PPC64_GOT_PCREL34: {
659     // Clear the first 8 bits of the prefix and the first 6 bits of the
660     // instruction (the primary opcode).
661     uint64_t insn = readPrefixedInstruction(loc);
662     if ((insn & 0xfc000000) != 0xe4000000)
663       error("expected a 'pld' for got-indirect to pc-relative relaxing");
664     insn &= ~0xff000000fc000000;
665 
666     // Replace the cleared bits with the values for PADDI (0x600000038000000);
667     insn |= 0x600000038000000;
668     writePrefixedInstruction(loc, insn);
669     relocate(loc, rel, val);
670     break;
671   }
672   case R_PPC64_PCREL_OPT: {
673     // We can only relax this if the R_PPC64_GOT_PCREL34 at this offset can
674     // be relaxed. The eligibility for the relaxation needs to be determined
675     // on that relocation since this one does not relocate a symbol.
676     uint64_t insn = readPrefixedInstruction(loc);
677     uint32_t accessInsn = read32(loc + rel.addend);
678     uint64_t pcRelInsn = getPCRelativeForm(accessInsn);
679 
680     // This error is not necessary for correctness but is emitted for now
681     // to ensure we don't miss these opportunities in real code. It can be
682     // removed at a later date.
683     if (pcRelInsn == UINT64_C(-1)) {
684       errorOrWarn(
685           "unrecognized instruction for R_PPC64_PCREL_OPT relaxation: 0x" +
686           Twine::utohexstr(accessInsn));
687       break;
688     }
689 
690     int64_t totalDisp = getTotalDisp(insn, accessInsn);
691     if (!isInt<34>(totalDisp))
692       break; // Displacement doesn't fit.
693     // Convert the PADDI to the prefixed version of accessInsn and convert
694     // accessInsn to a nop.
695     writePrefixedInstruction(loc, pcRelInsn |
696                                       ((totalDisp & 0x3ffff0000) << 16) |
697                                       (totalDisp & 0xffff));
698     write32(loc + rel.addend, NOP); // nop accessInsn.
699     break;
700   }
701   default:
702     llvm_unreachable("unexpected relocation type");
703   }
704 }
705 
706 void PPC64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
707                            uint64_t val) const {
708   // Reference: 3.7.4.2 of the 64-bit ELF V2 abi supplement.
709   // The general dynamic code sequence for a global `x` will look like:
710   // Instruction                    Relocation                Symbol
711   // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
712   // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
713   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
714   //                                R_PPC64_REL24               __tls_get_addr
715   // nop                            None                       None
716 
717   // Relaxing to local exec entails converting:
718   // addis r3, r2, x@got@tlsgd@ha    into      nop
719   // addi  r3, r3, x@got@tlsgd@l     into      addis r3, r13, x@tprel@ha
720   // bl __tls_get_addr(x@tlsgd)      into      nop
721   // nop                             into      addi r3, r3, x@tprel@l
722 
723   switch (rel.type) {
724   case R_PPC64_GOT_TLSGD16_HA:
725     writeFromHalf16(loc, NOP);
726     break;
727   case R_PPC64_GOT_TLSGD16:
728   case R_PPC64_GOT_TLSGD16_LO:
729     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13
730     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
731     break;
732   case R_PPC64_GOT_TLSGD_PCREL34:
733     // Relax from paddi r3, 0, x@got@tlsgd@pcrel, 1 to
734     //            paddi r3, r13, x@tprel, 0
735     writePrefixedInstruction(loc, 0x06000000386d0000);
736     relocateNoSym(loc, R_PPC64_TPREL34, val);
737     break;
738   case R_PPC64_TLSGD: {
739     // PC Relative Relaxation:
740     // Relax from bl __tls_get_addr@notoc(x@tlsgd) to
741     //            nop
742     // TOC Relaxation:
743     // Relax from bl __tls_get_addr(x@tlsgd)
744     //            nop
745     // to
746     //            nop
747     //            addi r3, r3, x@tprel@l
748     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
749     if (locAsInt % 4 == 0) {
750       write32(loc, NOP);            // nop
751       write32(loc + 4, 0x38630000); // addi r3, r3
752       // Since we are relocating a half16 type relocation and Loc + 4 points to
753       // the start of an instruction we need to advance the buffer by an extra
754       // 2 bytes on BE.
755       relocateNoSym(loc + 4 + (config->ekind == ELF64BEKind ? 2 : 0),
756                     R_PPC64_TPREL16_LO, val);
757     } else if (locAsInt % 4 == 1) {
758       write32(loc - 1, NOP);
759     } else {
760       errorOrWarn("R_PPC64_TLSGD has unexpected byte alignment");
761     }
762     break;
763   }
764   default:
765     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
766   }
767 }
768 
769 void PPC64::relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
770                            uint64_t val) const {
771   // Reference: 3.7.4.3 of the 64-bit ELF V2 abi supplement.
772   // The local dynamic code sequence for a global `x` will look like:
773   // Instruction                    Relocation                Symbol
774   // addis r3, r2, x@got@tlsld@ha   R_PPC64_GOT_TLSLD16_HA      x
775   // addi  r3, r3, x@got@tlsld@l    R_PPC64_GOT_TLSLD16_LO      x
776   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSLD               x
777   //                                R_PPC64_REL24               __tls_get_addr
778   // nop                            None                       None
779 
780   // Relaxing to local exec entails converting:
781   // addis r3, r2, x@got@tlsld@ha   into      nop
782   // addi  r3, r3, x@got@tlsld@l    into      addis r3, r13, 0
783   // bl __tls_get_addr(x@tlsgd)     into      nop
784   // nop                            into      addi r3, r3, 4096
785 
786   switch (rel.type) {
787   case R_PPC64_GOT_TLSLD16_HA:
788     writeFromHalf16(loc, NOP);
789     break;
790   case R_PPC64_GOT_TLSLD16_LO:
791     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13, 0
792     break;
793   case R_PPC64_GOT_TLSLD_PCREL34:
794     // Relax from paddi r3, 0, x1@got@tlsld@pcrel, 1 to
795     //            paddi r3, r13, 0x1000, 0
796     writePrefixedInstruction(loc, 0x06000000386d1000);
797     break;
798   case R_PPC64_TLSLD: {
799     // PC Relative Relaxation:
800     // Relax from bl __tls_get_addr@notoc(x@tlsld)
801     // to
802     //            nop
803     // TOC Relaxation:
804     // Relax from bl __tls_get_addr(x@tlsld)
805     //            nop
806     // to
807     //            nop
808     //            addi r3, r3, 4096
809     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
810     if (locAsInt % 4 == 0) {
811       write32(loc, NOP);
812       write32(loc + 4, 0x38631000); // addi r3, r3, 4096
813     } else if (locAsInt % 4 == 1) {
814       write32(loc - 1, NOP);
815     } else {
816       errorOrWarn("R_PPC64_TLSLD has unexpected byte alignment");
817     }
818     break;
819   }
820   case R_PPC64_DTPREL16:
821   case R_PPC64_DTPREL16_HA:
822   case R_PPC64_DTPREL16_HI:
823   case R_PPC64_DTPREL16_DS:
824   case R_PPC64_DTPREL16_LO:
825   case R_PPC64_DTPREL16_LO_DS:
826   case R_PPC64_DTPREL34:
827     relocate(loc, rel, val);
828     break;
829   default:
830     llvm_unreachable("unsupported relocation for TLS LD to LE relaxation");
831   }
832 }
833 
834 unsigned elf::getPPCDFormOp(unsigned secondaryOp) {
835   switch (secondaryOp) {
836   case LBZX:
837     return LBZ;
838   case LHZX:
839     return LHZ;
840   case LWZX:
841     return LWZ;
842   case LDX:
843     return LD;
844   case STBX:
845     return STB;
846   case STHX:
847     return STH;
848   case STWX:
849     return STW;
850   case STDX:
851     return STD;
852   case ADD:
853     return ADDI;
854   default:
855     return 0;
856   }
857 }
858 
859 void PPC64::relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
860                            uint64_t val) const {
861   // The initial exec code sequence for a global `x` will look like:
862   // Instruction                    Relocation                Symbol
863   // addis r9, r2, x@got@tprel@ha   R_PPC64_GOT_TPREL16_HA      x
864   // ld    r9, x@got@tprel@l(r9)    R_PPC64_GOT_TPREL16_LO_DS   x
865   // add r9, r9, x@tls              R_PPC64_TLS                 x
866 
867   // Relaxing to local exec entails converting:
868   // addis r9, r2, x@got@tprel@ha       into        nop
869   // ld r9, x@got@tprel@l(r9)           into        addis r9, r13, x@tprel@ha
870   // add r9, r9, x@tls                  into        addi r9, r9, x@tprel@l
871 
872   // x@tls R_PPC64_TLS is a relocation which does not compute anything,
873   // it is replaced with r13 (thread pointer).
874 
875   // The add instruction in the initial exec sequence has multiple variations
876   // that need to be handled. If we are building an address it will use an add
877   // instruction, if we are accessing memory it will use any of the X-form
878   // indexed load or store instructions.
879 
880   unsigned offset = (config->ekind == ELF64BEKind) ? 2 : 0;
881   switch (rel.type) {
882   case R_PPC64_GOT_TPREL16_HA:
883     write32(loc - offset, NOP);
884     break;
885   case R_PPC64_GOT_TPREL16_LO_DS:
886   case R_PPC64_GOT_TPREL16_DS: {
887     uint32_t regNo = read32(loc - offset) & 0x03E00000; // bits 6-10
888     write32(loc - offset, 0x3C0D0000 | regNo);          // addis RegNo, r13
889     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
890     break;
891   }
892   case R_PPC64_GOT_TPREL_PCREL34: {
893     const uint64_t pldRT = readPrefixedInstruction(loc) & 0x0000000003e00000;
894     // paddi RT(from pld), r13, symbol@tprel, 0
895     writePrefixedInstruction(loc, 0x06000000380d0000 | pldRT);
896     relocateNoSym(loc, R_PPC64_TPREL34, val);
897     break;
898   }
899   case R_PPC64_TLS: {
900     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
901     if (locAsInt % 4 == 0) {
902       uint32_t primaryOp = getPrimaryOpCode(read32(loc));
903       if (primaryOp != 31)
904         error("unrecognized instruction for IE to LE R_PPC64_TLS");
905       uint32_t secondaryOp = (read32(loc) & 0x000007FE) >> 1; // bits 21-30
906       uint32_t dFormOp = getPPCDFormOp(secondaryOp);
907       if (dFormOp == 0)
908         error("unrecognized instruction for IE to LE R_PPC64_TLS");
909       write32(loc, ((dFormOp << 26) | (read32(loc) & 0x03FFFFFF)));
910       relocateNoSym(loc + offset, R_PPC64_TPREL16_LO, val);
911     } else if (locAsInt % 4 == 1) {
912       // If the offset is not 4 byte aligned then we have a PCRel type reloc.
913       // This version of the relocation is offset by one byte from the
914       // instruction it references.
915       uint32_t tlsInstr = read32(loc - 1);
916       uint32_t primaryOp = getPrimaryOpCode(tlsInstr);
917       if (primaryOp != 31)
918         errorOrWarn("unrecognized instruction for IE to LE R_PPC64_TLS");
919       uint32_t secondaryOp = (tlsInstr & 0x000007FE) >> 1; // bits 21-30
920       // The add is a special case and should be turned into a nop. The paddi
921       // that comes before it will already have computed the address of the
922       // symbol.
923       if (secondaryOp == 266) {
924         // Check if the add uses the same result register as the input register.
925         uint32_t rt = (tlsInstr & 0x03E00000) >> 21; // bits 6-10
926         uint32_t ra = (tlsInstr & 0x001F0000) >> 16; // bits 11-15
927         if (ra == rt) {
928           write32(loc - 1, NOP);
929         } else {
930           // mr rt, ra
931           write32(loc - 1, 0x7C000378 | (rt << 16) | (ra << 21) | (ra << 11));
932         }
933       } else {
934         uint32_t dFormOp = getPPCDFormOp(secondaryOp);
935         if (dFormOp == 0)
936           errorOrWarn("unrecognized instruction for IE to LE R_PPC64_TLS");
937         write32(loc - 1, ((dFormOp << 26) | (tlsInstr & 0x03FF0000)));
938       }
939     } else {
940       errorOrWarn("R_PPC64_TLS must be either 4 byte aligned or one byte "
941                   "offset from 4 byte aligned");
942     }
943     break;
944   }
945   default:
946     llvm_unreachable("unknown relocation for IE to LE");
947     break;
948   }
949 }
950 
951 RelExpr PPC64::getRelExpr(RelType type, const Symbol &s,
952                           const uint8_t *loc) const {
953   switch (type) {
954   case R_PPC64_NONE:
955     return R_NONE;
956   case R_PPC64_ADDR16:
957   case R_PPC64_ADDR16_DS:
958   case R_PPC64_ADDR16_HA:
959   case R_PPC64_ADDR16_HI:
960   case R_PPC64_ADDR16_HIGH:
961   case R_PPC64_ADDR16_HIGHER:
962   case R_PPC64_ADDR16_HIGHERA:
963   case R_PPC64_ADDR16_HIGHEST:
964   case R_PPC64_ADDR16_HIGHESTA:
965   case R_PPC64_ADDR16_LO:
966   case R_PPC64_ADDR16_LO_DS:
967   case R_PPC64_ADDR32:
968   case R_PPC64_ADDR64:
969     return R_ABS;
970   case R_PPC64_GOT16:
971   case R_PPC64_GOT16_DS:
972   case R_PPC64_GOT16_HA:
973   case R_PPC64_GOT16_HI:
974   case R_PPC64_GOT16_LO:
975   case R_PPC64_GOT16_LO_DS:
976     return R_GOT_OFF;
977   case R_PPC64_TOC16:
978   case R_PPC64_TOC16_DS:
979   case R_PPC64_TOC16_HI:
980   case R_PPC64_TOC16_LO:
981     return R_GOTREL;
982   case R_PPC64_GOT_PCREL34:
983   case R_PPC64_GOT_TPREL_PCREL34:
984   case R_PPC64_PCREL_OPT:
985     return R_GOT_PC;
986   case R_PPC64_TOC16_HA:
987   case R_PPC64_TOC16_LO_DS:
988     return config->tocOptimize ? R_PPC64_RELAX_TOC : R_GOTREL;
989   case R_PPC64_TOC:
990     return R_PPC64_TOCBASE;
991   case R_PPC64_REL14:
992   case R_PPC64_REL24:
993     return R_PPC64_CALL_PLT;
994   case R_PPC64_REL24_NOTOC:
995     return R_PLT_PC;
996   case R_PPC64_REL16_LO:
997   case R_PPC64_REL16_HA:
998   case R_PPC64_REL16_HI:
999   case R_PPC64_REL32:
1000   case R_PPC64_REL64:
1001   case R_PPC64_PCREL34:
1002     return R_PC;
1003   case R_PPC64_GOT_TLSGD16:
1004   case R_PPC64_GOT_TLSGD16_HA:
1005   case R_PPC64_GOT_TLSGD16_HI:
1006   case R_PPC64_GOT_TLSGD16_LO:
1007     return R_TLSGD_GOT;
1008   case R_PPC64_GOT_TLSGD_PCREL34:
1009     return R_TLSGD_PC;
1010   case R_PPC64_GOT_TLSLD16:
1011   case R_PPC64_GOT_TLSLD16_HA:
1012   case R_PPC64_GOT_TLSLD16_HI:
1013   case R_PPC64_GOT_TLSLD16_LO:
1014     return R_TLSLD_GOT;
1015   case R_PPC64_GOT_TLSLD_PCREL34:
1016     return R_TLSLD_PC;
1017   case R_PPC64_GOT_TPREL16_HA:
1018   case R_PPC64_GOT_TPREL16_LO_DS:
1019   case R_PPC64_GOT_TPREL16_DS:
1020   case R_PPC64_GOT_TPREL16_HI:
1021     return R_GOT_OFF;
1022   case R_PPC64_GOT_DTPREL16_HA:
1023   case R_PPC64_GOT_DTPREL16_LO_DS:
1024   case R_PPC64_GOT_DTPREL16_DS:
1025   case R_PPC64_GOT_DTPREL16_HI:
1026     return R_TLSLD_GOT_OFF;
1027   case R_PPC64_TPREL16:
1028   case R_PPC64_TPREL16_HA:
1029   case R_PPC64_TPREL16_LO:
1030   case R_PPC64_TPREL16_HI:
1031   case R_PPC64_TPREL16_DS:
1032   case R_PPC64_TPREL16_LO_DS:
1033   case R_PPC64_TPREL16_HIGHER:
1034   case R_PPC64_TPREL16_HIGHERA:
1035   case R_PPC64_TPREL16_HIGHEST:
1036   case R_PPC64_TPREL16_HIGHESTA:
1037   case R_PPC64_TPREL34:
1038     return R_TPREL;
1039   case R_PPC64_DTPREL16:
1040   case R_PPC64_DTPREL16_DS:
1041   case R_PPC64_DTPREL16_HA:
1042   case R_PPC64_DTPREL16_HI:
1043   case R_PPC64_DTPREL16_HIGHER:
1044   case R_PPC64_DTPREL16_HIGHERA:
1045   case R_PPC64_DTPREL16_HIGHEST:
1046   case R_PPC64_DTPREL16_HIGHESTA:
1047   case R_PPC64_DTPREL16_LO:
1048   case R_PPC64_DTPREL16_LO_DS:
1049   case R_PPC64_DTPREL64:
1050   case R_PPC64_DTPREL34:
1051     return R_DTPREL;
1052   case R_PPC64_TLSGD:
1053     return R_TLSDESC_CALL;
1054   case R_PPC64_TLSLD:
1055     return R_TLSLD_HINT;
1056   case R_PPC64_TLS:
1057     return R_TLSIE_HINT;
1058   default:
1059     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
1060           ") against symbol " + toString(s));
1061     return R_NONE;
1062   }
1063 }
1064 
1065 RelType PPC64::getDynRel(RelType type) const {
1066   if (type == R_PPC64_ADDR64 || type == R_PPC64_TOC)
1067     return R_PPC64_ADDR64;
1068   return R_PPC64_NONE;
1069 }
1070 
1071 int64_t PPC64::getImplicitAddend(const uint8_t *buf, RelType type) const {
1072   switch (type) {
1073   case R_PPC64_NONE:
1074     return 0;
1075   case R_PPC64_REL32:
1076     return SignExtend64<32>(read32(buf));
1077   case R_PPC64_ADDR64:
1078   case R_PPC64_REL64:
1079     return read64(buf);
1080   default:
1081     internalLinkerError(getErrorLocation(buf),
1082                         "cannot read addend for relocation " + toString(type));
1083     return 0;
1084   }
1085 }
1086 
1087 void PPC64::writeGotHeader(uint8_t *buf) const {
1088   write64(buf, getPPC64TocBase());
1089 }
1090 
1091 void PPC64::writePltHeader(uint8_t *buf) const {
1092   // The generic resolver stub goes first.
1093   write32(buf +  0, 0x7c0802a6); // mflr r0
1094   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
1095   write32(buf +  8, 0x7d6802a6); // mflr r11
1096   write32(buf + 12, 0x7c0803a6); // mtlr r0
1097   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
1098   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
1099   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
1100   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
1101   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
1102   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
1103   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
1104   write32(buf + 44, 0x7d8903a6); // mtctr   r12
1105   write32(buf + 48, 0x4e800420); // bctr
1106 
1107   // The 'bcl' instruction will set the link register to the address of the
1108   // following instruction ('mflr r11'). Here we store the offset from that
1109   // instruction  to the first entry in the GotPlt section.
1110   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
1111   write64(buf + 52, gotPltOffset);
1112 }
1113 
1114 void PPC64::writePlt(uint8_t *buf, const Symbol &sym,
1115                      uint64_t /*pltEntryAddr*/) const {
1116   int32_t offset = pltHeaderSize + sym.pltIndex * pltEntrySize;
1117   // bl __glink_PLTresolve
1118   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
1119 }
1120 
1121 void PPC64::writeIplt(uint8_t *buf, const Symbol &sym,
1122                       uint64_t /*pltEntryAddr*/) const {
1123   writePPC64LoadAndBranch(buf, sym.getGotPltVA() - getPPC64TocBase());
1124 }
1125 
1126 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
1127   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
1128   uint64_t tocBiasedVal = val - ppc64TocOffset;
1129   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
1130   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
1131 
1132   switch (type) {
1133   // TOC biased relocation.
1134   case R_PPC64_GOT16:
1135   case R_PPC64_GOT_TLSGD16:
1136   case R_PPC64_GOT_TLSLD16:
1137   case R_PPC64_TOC16:
1138     return {R_PPC64_ADDR16, tocBiasedVal};
1139   case R_PPC64_GOT16_DS:
1140   case R_PPC64_TOC16_DS:
1141   case R_PPC64_GOT_TPREL16_DS:
1142   case R_PPC64_GOT_DTPREL16_DS:
1143     return {R_PPC64_ADDR16_DS, tocBiasedVal};
1144   case R_PPC64_GOT16_HA:
1145   case R_PPC64_GOT_TLSGD16_HA:
1146   case R_PPC64_GOT_TLSLD16_HA:
1147   case R_PPC64_GOT_TPREL16_HA:
1148   case R_PPC64_GOT_DTPREL16_HA:
1149   case R_PPC64_TOC16_HA:
1150     return {R_PPC64_ADDR16_HA, tocBiasedVal};
1151   case R_PPC64_GOT16_HI:
1152   case R_PPC64_GOT_TLSGD16_HI:
1153   case R_PPC64_GOT_TLSLD16_HI:
1154   case R_PPC64_GOT_TPREL16_HI:
1155   case R_PPC64_GOT_DTPREL16_HI:
1156   case R_PPC64_TOC16_HI:
1157     return {R_PPC64_ADDR16_HI, tocBiasedVal};
1158   case R_PPC64_GOT16_LO:
1159   case R_PPC64_GOT_TLSGD16_LO:
1160   case R_PPC64_GOT_TLSLD16_LO:
1161   case R_PPC64_TOC16_LO:
1162     return {R_PPC64_ADDR16_LO, tocBiasedVal};
1163   case R_PPC64_GOT16_LO_DS:
1164   case R_PPC64_TOC16_LO_DS:
1165   case R_PPC64_GOT_TPREL16_LO_DS:
1166   case R_PPC64_GOT_DTPREL16_LO_DS:
1167     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
1168 
1169   // Dynamic Thread pointer biased relocation types.
1170   case R_PPC64_DTPREL16:
1171     return {R_PPC64_ADDR16, dtpBiasedVal};
1172   case R_PPC64_DTPREL16_DS:
1173     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
1174   case R_PPC64_DTPREL16_HA:
1175     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
1176   case R_PPC64_DTPREL16_HI:
1177     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
1178   case R_PPC64_DTPREL16_HIGHER:
1179     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
1180   case R_PPC64_DTPREL16_HIGHERA:
1181     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
1182   case R_PPC64_DTPREL16_HIGHEST:
1183     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
1184   case R_PPC64_DTPREL16_HIGHESTA:
1185     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
1186   case R_PPC64_DTPREL16_LO:
1187     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
1188   case R_PPC64_DTPREL16_LO_DS:
1189     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
1190   case R_PPC64_DTPREL64:
1191     return {R_PPC64_ADDR64, dtpBiasedVal};
1192 
1193   default:
1194     return {type, val};
1195   }
1196 }
1197 
1198 static bool isTocOptType(RelType type) {
1199   switch (type) {
1200   case R_PPC64_GOT16_HA:
1201   case R_PPC64_GOT16_LO_DS:
1202   case R_PPC64_TOC16_HA:
1203   case R_PPC64_TOC16_LO_DS:
1204   case R_PPC64_TOC16_LO:
1205     return true;
1206   default:
1207     return false;
1208   }
1209 }
1210 
1211 void PPC64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
1212   RelType type = rel.type;
1213   bool shouldTocOptimize =  isTocOptType(type);
1214   // For dynamic thread pointer relative, toc-relative, and got-indirect
1215   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
1216   std::tie(type, val) = toAddr16Rel(type, val);
1217 
1218   switch (type) {
1219   case R_PPC64_ADDR14: {
1220     checkAlignment(loc, val, 4, rel);
1221     // Preserve the AA/LK bits in the branch instruction
1222     uint8_t aalk = loc[3];
1223     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
1224     break;
1225   }
1226   case R_PPC64_ADDR16:
1227     checkIntUInt(loc, val, 16, rel);
1228     write16(loc, val);
1229     break;
1230   case R_PPC64_ADDR32:
1231     checkIntUInt(loc, val, 32, rel);
1232     write32(loc, val);
1233     break;
1234   case R_PPC64_ADDR16_DS:
1235   case R_PPC64_TPREL16_DS: {
1236     checkInt(loc, val, 16, rel);
1237     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1238     // DS-form instructions only use bits 30-31.
1239     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
1240     checkAlignment(loc, lo(val), mask + 1, rel);
1241     write16(loc, (read16(loc) & mask) | lo(val));
1242   } break;
1243   case R_PPC64_ADDR16_HA:
1244   case R_PPC64_REL16_HA:
1245   case R_PPC64_TPREL16_HA:
1246     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
1247       writeFromHalf16(loc, NOP);
1248     else {
1249       checkInt(loc, val + 0x8000, 32, rel);
1250       write16(loc, ha(val));
1251     }
1252     break;
1253   case R_PPC64_ADDR16_HI:
1254   case R_PPC64_REL16_HI:
1255   case R_PPC64_TPREL16_HI:
1256     checkInt(loc, val, 32, rel);
1257     write16(loc, hi(val));
1258     break;
1259   case R_PPC64_ADDR16_HIGH:
1260     write16(loc, hi(val));
1261     break;
1262   case R_PPC64_ADDR16_HIGHER:
1263   case R_PPC64_TPREL16_HIGHER:
1264     write16(loc, higher(val));
1265     break;
1266   case R_PPC64_ADDR16_HIGHERA:
1267   case R_PPC64_TPREL16_HIGHERA:
1268     write16(loc, highera(val));
1269     break;
1270   case R_PPC64_ADDR16_HIGHEST:
1271   case R_PPC64_TPREL16_HIGHEST:
1272     write16(loc, highest(val));
1273     break;
1274   case R_PPC64_ADDR16_HIGHESTA:
1275   case R_PPC64_TPREL16_HIGHESTA:
1276     write16(loc, highesta(val));
1277     break;
1278   case R_PPC64_ADDR16_LO:
1279   case R_PPC64_REL16_LO:
1280   case R_PPC64_TPREL16_LO:
1281     // When the high-adjusted part of a toc relocation evaluates to 0, it is
1282     // changed into a nop. The lo part then needs to be updated to use the
1283     // toc-pointer register r2, as the base register.
1284     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1285       uint32_t insn = readFromHalf16(loc);
1286       if (isInstructionUpdateForm(insn))
1287         error(getErrorLocation(loc) +
1288               "can't toc-optimize an update instruction: 0x" +
1289               utohexstr(insn));
1290       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
1291     } else {
1292       write16(loc, lo(val));
1293     }
1294     break;
1295   case R_PPC64_ADDR16_LO_DS:
1296   case R_PPC64_TPREL16_LO_DS: {
1297     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1298     // DS-form instructions only use bits 30-31.
1299     uint32_t insn = readFromHalf16(loc);
1300     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
1301     checkAlignment(loc, lo(val), mask + 1, rel);
1302     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1303       // When the high-adjusted part of a toc relocation evaluates to 0, it is
1304       // changed into a nop. The lo part then needs to be updated to use the toc
1305       // pointer register r2, as the base register.
1306       if (isInstructionUpdateForm(insn))
1307         error(getErrorLocation(loc) +
1308               "Can't toc-optimize an update instruction: 0x" +
1309               Twine::utohexstr(insn));
1310       insn &= 0xffe00000 | mask;
1311       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
1312     } else {
1313       write16(loc, (read16(loc) & mask) | lo(val));
1314     }
1315   } break;
1316   case R_PPC64_TPREL16:
1317     checkInt(loc, val, 16, rel);
1318     write16(loc, val);
1319     break;
1320   case R_PPC64_REL32:
1321     checkInt(loc, val, 32, rel);
1322     write32(loc, val);
1323     break;
1324   case R_PPC64_ADDR64:
1325   case R_PPC64_REL64:
1326   case R_PPC64_TOC:
1327     write64(loc, val);
1328     break;
1329   case R_PPC64_REL14: {
1330     uint32_t mask = 0x0000FFFC;
1331     checkInt(loc, val, 16, rel);
1332     checkAlignment(loc, val, 4, rel);
1333     write32(loc, (read32(loc) & ~mask) | (val & mask));
1334     break;
1335   }
1336   case R_PPC64_REL24:
1337   case R_PPC64_REL24_NOTOC: {
1338     uint32_t mask = 0x03FFFFFC;
1339     checkInt(loc, val, 26, rel);
1340     checkAlignment(loc, val, 4, rel);
1341     write32(loc, (read32(loc) & ~mask) | (val & mask));
1342     break;
1343   }
1344   case R_PPC64_DTPREL64:
1345     write64(loc, val - dynamicThreadPointerOffset);
1346     break;
1347   case R_PPC64_DTPREL34:
1348     // The Dynamic Thread Vector actually points 0x8000 bytes past the start
1349     // of the TLS block. Therefore, in the case of R_PPC64_DTPREL34 we first
1350     // need to subtract that value then fallthrough to the general case.
1351     val -= dynamicThreadPointerOffset;
1352     LLVM_FALLTHROUGH;
1353   case R_PPC64_PCREL34:
1354   case R_PPC64_GOT_PCREL34:
1355   case R_PPC64_GOT_TLSGD_PCREL34:
1356   case R_PPC64_GOT_TLSLD_PCREL34:
1357   case R_PPC64_GOT_TPREL_PCREL34:
1358   case R_PPC64_TPREL34: {
1359     const uint64_t si0Mask = 0x00000003ffff0000;
1360     const uint64_t si1Mask = 0x000000000000ffff;
1361     const uint64_t fullMask = 0x0003ffff0000ffff;
1362     checkInt(loc, val, 34, rel);
1363 
1364     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1365     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1366                              (val & si1Mask));
1367     break;
1368   }
1369   // If we encounter a PCREL_OPT relocation that we won't optimize.
1370   case R_PPC64_PCREL_OPT:
1371     break;
1372   default:
1373     llvm_unreachable("unknown relocation");
1374   }
1375 }
1376 
1377 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
1378                        uint64_t branchAddr, const Symbol &s, int64_t a) const {
1379   if (type != R_PPC64_REL14 && type != R_PPC64_REL24 &&
1380       type != R_PPC64_REL24_NOTOC)
1381     return false;
1382 
1383   // If a function is in the Plt it needs to be called with a call-stub.
1384   if (s.isInPlt())
1385     return true;
1386 
1387   // This check looks at the st_other bits of the callee with relocation
1388   // R_PPC64_REL14 or R_PPC64_REL24. If the value is 1, then the callee
1389   // clobbers the TOC and we need an R2 save stub.
1390   if (type != R_PPC64_REL24_NOTOC && (s.stOther >> 5) == 1)
1391     return true;
1392 
1393   if (type == R_PPC64_REL24_NOTOC && (s.stOther >> 5) > 1)
1394     return true;
1395 
1396   // If a symbol is a weak undefined and we are compiling an executable
1397   // it doesn't need a range-extending thunk since it can't be called.
1398   if (s.isUndefWeak() && !config->shared)
1399     return false;
1400 
1401   // If the offset exceeds the range of the branch type then it will need
1402   // a range-extending thunk.
1403   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
1404   return !inBranchRange(type, branchAddr,
1405                         s.getVA(a) +
1406                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
1407 }
1408 
1409 uint32_t PPC64::getThunkSectionSpacing() const {
1410   // See comment in Arch/ARM.cpp for a more detailed explanation of
1411   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
1412   // R_PPC64_REL24, which is used by unconditional branch instructions.
1413   // 0x2000000 = (1 << 24-1) * 4
1414   return 0x2000000;
1415 }
1416 
1417 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
1418   int64_t offset = dst - src;
1419   if (type == R_PPC64_REL14)
1420     return isInt<16>(offset);
1421   if (type == R_PPC64_REL24 || type == R_PPC64_REL24_NOTOC)
1422     return isInt<26>(offset);
1423   llvm_unreachable("unsupported relocation type used in branch");
1424 }
1425 
1426 RelExpr PPC64::adjustTlsExpr(RelType type, RelExpr expr) const {
1427   if (type != R_PPC64_GOT_TLSGD_PCREL34 && expr == R_RELAX_TLS_GD_TO_IE)
1428     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
1429   if (expr == R_RELAX_TLS_LD_TO_LE)
1430     return R_RELAX_TLS_LD_TO_LE_ABS;
1431   return expr;
1432 }
1433 
1434 RelExpr PPC64::adjustGotPcExpr(RelType type, int64_t addend,
1435                                const uint8_t *loc) const {
1436   if ((type == R_PPC64_GOT_PCREL34 || type == R_PPC64_PCREL_OPT) &&
1437       config->pcRelOptimize) {
1438     // It only makes sense to optimize pld since paddi means that the address
1439     // of the object in the GOT is required rather than the object itself.
1440     if ((readPrefixedInstruction(loc) & 0xfc000000) == 0xe4000000)
1441       return R_PPC64_RELAX_GOT_PC;
1442   }
1443   return R_GOT_PC;
1444 }
1445 
1446 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
1447 // The general dynamic code sequence for a global `x` uses 4 instructions.
1448 // Instruction                    Relocation                Symbol
1449 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
1450 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
1451 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
1452 //                                R_PPC64_REL24               __tls_get_addr
1453 // nop                            None                       None
1454 //
1455 // Relaxing to initial-exec entails:
1456 // 1) Convert the addis/addi pair that builds the address of the tls_index
1457 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
1458 // 2) Convert the call to __tls_get_addr to a nop.
1459 // 3) Convert the nop following the call to an add of the loaded offset to the
1460 //    thread pointer.
1461 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
1462 // used as the relaxation hint for both steps 2 and 3.
1463 void PPC64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
1464                            uint64_t val) const {
1465   switch (rel.type) {
1466   case R_PPC64_GOT_TLSGD16_HA:
1467     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
1468     //                      addis rT, r2, sym@got@tprel@ha.
1469     relocateNoSym(loc, R_PPC64_GOT_TPREL16_HA, val);
1470     return;
1471   case R_PPC64_GOT_TLSGD16:
1472   case R_PPC64_GOT_TLSGD16_LO: {
1473     // Relax from addi  r3, rA, sym@got@tlsgd@l to
1474     //            ld r3, sym@got@tprel@l(rA)
1475     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
1476     writeFromHalf16(loc, 0xe8600000 | ra);
1477     relocateNoSym(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
1478     return;
1479   }
1480   case R_PPC64_GOT_TLSGD_PCREL34: {
1481     // Relax from paddi r3, 0, sym@got@tlsgd@pcrel, 1 to
1482     //            pld r3, sym@got@tprel@pcrel
1483     writePrefixedInstruction(loc, 0x04100000e4600000);
1484     relocateNoSym(loc, R_PPC64_GOT_TPREL_PCREL34, val);
1485     return;
1486   }
1487   case R_PPC64_TLSGD: {
1488     // PC Relative Relaxation:
1489     // Relax from bl __tls_get_addr@notoc(x@tlsgd) to
1490     //            nop
1491     // TOC Relaxation:
1492     // Relax from bl __tls_get_addr(x@tlsgd)
1493     //            nop
1494     // to
1495     //            nop
1496     //            add r3, r3, r13
1497     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
1498     if (locAsInt % 4 == 0) {
1499       write32(loc, NOP);            // bl __tls_get_addr(sym@tlsgd) --> nop
1500       write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
1501     } else if (locAsInt % 4 == 1) {
1502       // bl __tls_get_addr(sym@tlsgd) --> add r3, r3, r13
1503       write32(loc - 1, 0x7c636a14);
1504     } else {
1505       errorOrWarn("R_PPC64_TLSGD has unexpected byte alignment");
1506     }
1507     return;
1508   }
1509   default:
1510     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
1511   }
1512 }
1513 
1514 // The prologue for a split-stack function is expected to look roughly
1515 // like this:
1516 //    .Lglobal_entry_point:
1517 //      # TOC pointer initialization.
1518 //      ...
1519 //    .Llocal_entry_point:
1520 //      # load the __private_ss member of the threads tcbhead.
1521 //      ld r0,-0x7000-64(r13)
1522 //      # subtract the functions stack size from the stack pointer.
1523 //      addis r12, r1, ha(-stack-frame size)
1524 //      addi  r12, r12, l(-stack-frame size)
1525 //      # compare needed to actual and branch to allocate_more_stack if more
1526 //      # space is needed, otherwise fallthrough to 'normal' function body.
1527 //      cmpld cr7,r12,r0
1528 //      blt- cr7, .Lallocate_more_stack
1529 //
1530 // -) The allocate_more_stack block might be placed after the split-stack
1531 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1532 //    instead.
1533 // -) If either the addis or addi is not needed due to the stack size being
1534 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1535 //    but there will always be 2 instructions the linker can overwrite for the
1536 //    adjusted stack size.
1537 //
1538 // The linkers job here is to increase the stack size used in the addis/addi
1539 // pair by split-stack-size-adjust.
1540 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1541 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1542 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1543                                              uint8_t stOther) const {
1544   // If the caller has a global entry point adjust the buffer past it. The start
1545   // of the split-stack prologue will be at the local entry point.
1546   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1547 
1548   // At the very least we expect to see a load of some split-stack data from the
1549   // tcb, and 2 instructions that calculate the ending stack address this
1550   // function will require. If there is not enough room for at least 3
1551   // instructions it can't be a split-stack prologue.
1552   if (loc + 12 >= end)
1553     return false;
1554 
1555   // First instruction must be `ld r0, -0x7000-64(r13)`
1556   if (read32(loc) != 0xe80d8fc0)
1557     return false;
1558 
1559   int16_t hiImm = 0;
1560   int16_t loImm = 0;
1561   // First instruction can be either an addis if the frame size is larger then
1562   // 32K, or an addi if the size is less then 32K.
1563   int32_t firstInstr = read32(loc + 4);
1564   if (getPrimaryOpCode(firstInstr) == 15) {
1565     hiImm = firstInstr & 0xFFFF;
1566   } else if (getPrimaryOpCode(firstInstr) == 14) {
1567     loImm = firstInstr & 0xFFFF;
1568   } else {
1569     return false;
1570   }
1571 
1572   // Second instruction is either an addi or a nop. If the first instruction was
1573   // an addi then LoImm is set and the second instruction must be a nop.
1574   uint32_t secondInstr = read32(loc + 8);
1575   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1576     loImm = secondInstr & 0xFFFF;
1577   } else if (secondInstr != NOP) {
1578     return false;
1579   }
1580 
1581   // The register operands of the first instruction should be the stack-pointer
1582   // (r1) as the input (RA) and r12 as the output (RT). If the second
1583   // instruction is not a nop, then it should use r12 as both input and output.
1584   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1585                              uint8_t expectedRA) {
1586     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1587            ((instr & 0x1F0000) >> 16 == expectedRA);
1588   };
1589   if (!checkRegOperands(firstInstr, 12, 1))
1590     return false;
1591   if (secondInstr != NOP && !checkRegOperands(secondInstr, 12, 12))
1592     return false;
1593 
1594   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1595   // Check that the adjusted size doesn't overflow what we can represent with 2
1596   // instructions.
1597   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1598     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1599     return false;
1600   }
1601 
1602   int32_t adjustedStackFrameSize =
1603       stackFrameSize - config->splitStackAdjustSize;
1604 
1605   loImm = adjustedStackFrameSize & 0xFFFF;
1606   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1607   if (hiImm) {
1608     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1609     // If the low immediate is zero the second instruction will be a nop.
1610     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : NOP;
1611     write32(loc + 8, secondInstr);
1612   } else {
1613     // addi r12, r1, imm
1614     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1615     write32(loc + 8, NOP);
1616   }
1617 
1618   return true;
1619 }
1620 
1621 TargetInfo *elf::getPPC64TargetInfo() {
1622   static PPC64 target;
1623   return &target;
1624 }
1625