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