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