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