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