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