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