1 //===- ARM64.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 "Arch/ARM64Common.h" 10 #include "InputFiles.h" 11 #include "Symbols.h" 12 #include "SyntheticSections.h" 13 #include "Target.h" 14 15 #include "lld/Common/ErrorHandler.h" 16 #include "mach-o/compact_unwind_encoding.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/BinaryFormat/MachO.h" 20 #include "llvm/Support/Endian.h" 21 #include "llvm/Support/MathExtras.h" 22 23 using namespace llvm; 24 using namespace llvm::MachO; 25 using namespace llvm::support::endian; 26 using namespace lld; 27 using namespace lld::macho; 28 29 namespace { 30 31 struct ARM64 : ARM64Common { 32 ARM64(); 33 void writeStub(uint8_t *buf, const Symbol &) const override; 34 void writeStubHelperHeader(uint8_t *buf) const override; 35 void writeStubHelperEntry(uint8_t *buf, const Symbol &, 36 uint64_t entryAddr) const override; 37 const RelocAttrs &getRelocAttrs(uint8_t type) const override; 38 void populateThunk(InputSection *thunk, Symbol *funcSym) override; 39 void applyOptimizationHints(uint8_t *, const ConcatInputSection *, 40 ArrayRef<uint64_t>) const override; 41 }; 42 43 } // namespace 44 45 // Random notes on reloc types: 46 // ADDEND always pairs with BRANCH26, PAGE21, or PAGEOFF12 47 // POINTER_TO_GOT: ld64 supports a 4-byte pc-relative form as well as an 8-byte 48 // absolute version of this relocation. The semantics of the absolute relocation 49 // are weird -- it results in the value of the GOT slot being written, instead 50 // of the address. Let's not support it unless we find a real-world use case. 51 52 const RelocAttrs &ARM64::getRelocAttrs(uint8_t type) const { 53 static const std::array<RelocAttrs, 11> relocAttrsArray{{ 54 #define B(x) RelocAttrBits::x 55 {"UNSIGNED", 56 B(UNSIGNED) | B(ABSOLUTE) | B(EXTERN) | B(LOCAL) | B(BYTE4) | B(BYTE8)}, 57 {"SUBTRACTOR", B(SUBTRAHEND) | B(EXTERN) | B(BYTE4) | B(BYTE8)}, 58 {"BRANCH26", B(PCREL) | B(EXTERN) | B(BRANCH) | B(BYTE4)}, 59 {"PAGE21", B(PCREL) | B(EXTERN) | B(BYTE4)}, 60 {"PAGEOFF12", B(ABSOLUTE) | B(EXTERN) | B(BYTE4)}, 61 {"GOT_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(GOT) | B(BYTE4)}, 62 {"GOT_LOAD_PAGEOFF12", 63 B(ABSOLUTE) | B(EXTERN) | B(GOT) | B(LOAD) | B(BYTE4)}, 64 {"POINTER_TO_GOT", B(PCREL) | B(EXTERN) | B(GOT) | B(POINTER) | B(BYTE4)}, 65 {"TLVP_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(TLV) | B(BYTE4)}, 66 {"TLVP_LOAD_PAGEOFF12", 67 B(ABSOLUTE) | B(EXTERN) | B(TLV) | B(LOAD) | B(BYTE4)}, 68 {"ADDEND", B(ADDEND)}, 69 #undef B 70 }}; 71 assert(type < relocAttrsArray.size() && "invalid relocation type"); 72 if (type >= relocAttrsArray.size()) 73 return invalidRelocAttrs; 74 return relocAttrsArray[type]; 75 } 76 77 static constexpr uint32_t stubCode[] = { 78 0x90000010, // 00: adrp x16, __la_symbol_ptr@page 79 0xf9400210, // 04: ldr x16, [x16, __la_symbol_ptr@pageoff] 80 0xd61f0200, // 08: br x16 81 }; 82 83 void ARM64::writeStub(uint8_t *buf8, const Symbol &sym) const { 84 ::writeStub<LP64>(buf8, stubCode, sym); 85 } 86 87 static constexpr uint32_t stubHelperHeaderCode[] = { 88 0x90000011, // 00: adrp x17, _dyld_private@page 89 0x91000231, // 04: add x17, x17, _dyld_private@pageoff 90 0xa9bf47f0, // 08: stp x16/x17, [sp, #-16]! 91 0x90000010, // 0c: adrp x16, dyld_stub_binder@page 92 0xf9400210, // 10: ldr x16, [x16, dyld_stub_binder@pageoff] 93 0xd61f0200, // 14: br x16 94 }; 95 96 void ARM64::writeStubHelperHeader(uint8_t *buf8) const { 97 ::writeStubHelperHeader<LP64>(buf8, stubHelperHeaderCode); 98 } 99 100 static constexpr uint32_t stubHelperEntryCode[] = { 101 0x18000050, // 00: ldr w16, l0 102 0x14000000, // 04: b stubHelperHeader 103 0x00000000, // 08: l0: .long 0 104 }; 105 106 void ARM64::writeStubHelperEntry(uint8_t *buf8, const Symbol &sym, 107 uint64_t entryVA) const { 108 ::writeStubHelperEntry(buf8, stubHelperEntryCode, sym, entryVA); 109 } 110 111 // A thunk is the relaxed variation of stubCode. We don't need the 112 // extra indirection through a lazy pointer because the target address 113 // is known at link time. 114 static constexpr uint32_t thunkCode[] = { 115 0x90000010, // 00: adrp x16, <thunk.ptr>@page 116 0x91000210, // 04: add x16, [x16,<thunk.ptr>@pageoff] 117 0xd61f0200, // 08: br x16 118 }; 119 120 void ARM64::populateThunk(InputSection *thunk, Symbol *funcSym) { 121 thunk->align = 4; 122 thunk->data = {reinterpret_cast<const uint8_t *>(thunkCode), 123 sizeof(thunkCode)}; 124 thunk->relocs.push_back({/*type=*/ARM64_RELOC_PAGEOFF12, 125 /*pcrel=*/false, /*length=*/2, 126 /*offset=*/4, /*addend=*/0, 127 /*referent=*/funcSym}); 128 thunk->relocs.push_back({/*type=*/ARM64_RELOC_PAGE21, 129 /*pcrel=*/true, /*length=*/2, 130 /*offset=*/0, /*addend=*/0, 131 /*referent=*/funcSym}); 132 } 133 134 ARM64::ARM64() : ARM64Common(LP64()) { 135 cpuType = CPU_TYPE_ARM64; 136 cpuSubtype = CPU_SUBTYPE_ARM64_ALL; 137 138 stubSize = sizeof(stubCode); 139 thunkSize = sizeof(thunkCode); 140 141 // Branch immediate is two's complement 26 bits, which is implicitly 142 // multiplied by 4 (since all functions are 4-aligned: The branch range 143 // is -4*(2**(26-1))..4*(2**(26-1) - 1). 144 backwardBranchRange = 128 * 1024 * 1024; 145 forwardBranchRange = backwardBranchRange - 4; 146 147 modeDwarfEncoding = UNWIND_ARM64_MODE_DWARF; 148 subtractorRelocType = ARM64_RELOC_SUBTRACTOR; 149 unsignedRelocType = ARM64_RELOC_UNSIGNED; 150 151 stubHelperHeaderSize = sizeof(stubHelperHeaderCode); 152 stubHelperEntrySize = sizeof(stubHelperEntryCode); 153 } 154 155 namespace { 156 struct Adrp { 157 uint32_t destRegister; 158 }; 159 160 struct Add { 161 uint8_t destRegister; 162 uint8_t srcRegister; 163 uint32_t addend; 164 }; 165 166 enum ExtendType { ZeroExtend = 1, Sign64 = 2, Sign32 = 3 }; 167 168 struct Ldr { 169 uint8_t destRegister; 170 uint8_t baseRegister; 171 uint8_t size; 172 bool isFloat; 173 ExtendType extendType; 174 uint64_t offset; 175 }; 176 177 struct PerformedReloc { 178 const Reloc &rel; 179 uint64_t referentVA; 180 }; 181 182 class OptimizationHintContext { 183 public: 184 OptimizationHintContext(uint8_t *buf, const ConcatInputSection *isec, 185 ArrayRef<uint64_t> relocTargets) 186 : buf(buf), isec(isec), relocTargets(relocTargets), 187 relocIt(isec->relocs.rbegin()) {} 188 189 void applyAdrpAdd(const OptimizationHint &); 190 void applyAdrpAdrp(const OptimizationHint &); 191 void applyAdrpLdr(const OptimizationHint &); 192 void applyAdrpLdrGot(const OptimizationHint &); 193 194 private: 195 uint8_t *buf; 196 const ConcatInputSection *isec; 197 ArrayRef<uint64_t> relocTargets; 198 std::vector<Reloc>::const_reverse_iterator relocIt; 199 200 uint64_t getRelocTarget(const Reloc &); 201 202 Optional<PerformedReloc> findPrimaryReloc(uint64_t offset); 203 Optional<PerformedReloc> findReloc(uint64_t offset); 204 }; 205 } // namespace 206 207 static bool parseAdrp(uint32_t insn, Adrp &adrp) { 208 if ((insn & 0x9f000000) != 0x90000000) 209 return false; 210 adrp.destRegister = insn & 0x1f; 211 return true; 212 } 213 214 static bool parseAdd(uint32_t insn, Add &add) { 215 if ((insn & 0xffc00000) != 0x91000000) 216 return false; 217 add.destRegister = insn & 0x1f; 218 add.srcRegister = (insn >> 5) & 0x1f; 219 add.addend = (insn >> 10) & 0xfff; 220 return true; 221 } 222 223 static bool parseLdr(uint32_t insn, Ldr &ldr) { 224 ldr.destRegister = insn & 0x1f; 225 ldr.baseRegister = (insn >> 5) & 0x1f; 226 uint8_t size = insn >> 30; 227 uint8_t opc = (insn >> 22) & 3; 228 229 if ((insn & 0x3fc00000) == 0x39400000) { 230 // LDR (immediate), LDRB (immediate), LDRH (immediate) 231 ldr.size = 1 << size; 232 ldr.extendType = ZeroExtend; 233 ldr.isFloat = false; 234 } else if ((insn & 0x3f800000) == 0x39800000) { 235 // LDRSB (immediate), LDRSH (immediate), LDRSW (immediate) 236 ldr.size = 1 << size; 237 ldr.extendType = static_cast<ExtendType>(opc); 238 ldr.isFloat = false; 239 } else if ((insn & 0x3f400000) == 0x3d400000) { 240 // LDR (immediate, SIMD&FP) 241 ldr.extendType = ZeroExtend; 242 ldr.isFloat = true; 243 if (size == 2 && opc == 1) 244 ldr.size = 4; 245 else if (size == 3 && opc == 1) 246 ldr.size = 8; 247 else if (size == 0 && opc == 3) 248 ldr.size = 16; 249 else 250 return false; 251 } else { 252 return false; 253 } 254 ldr.offset = ((insn >> 10) & 0xfff) * ldr.size; 255 return true; 256 } 257 258 static void writeAdr(void *loc, uint32_t dest, int32_t delta) { 259 uint32_t opcode = 0x10000000; 260 uint32_t immHi = (delta & 0x001ffffc) << 3; 261 uint32_t immLo = (delta & 0x00000003) << 29; 262 write32le(loc, opcode | immHi | immLo | dest); 263 } 264 265 static void writeNop(void *loc) { write32le(loc, 0xd503201f); } 266 267 static void writeLiteralLdr(void *loc, Ldr original, int32_t delta) { 268 uint32_t imm19 = (delta & 0x001ffffc) << 3; 269 uint32_t opcode = 0; 270 switch (original.size) { 271 case 4: 272 if (original.isFloat) 273 opcode = 0x1c000000; 274 else 275 opcode = original.extendType == Sign64 ? 0x98000000 : 0x18000000; 276 break; 277 case 8: 278 opcode = original.isFloat ? 0x5c000000 : 0x58000000; 279 break; 280 case 16: 281 opcode = 0x9c000000; 282 break; 283 default: 284 assert(false && "Invalid size for literal ldr"); 285 } 286 write32le(loc, opcode | imm19 | original.destRegister); 287 } 288 289 uint64_t OptimizationHintContext::getRelocTarget(const Reloc &reloc) { 290 size_t relocIdx = &reloc - isec->relocs.data(); 291 return relocTargets[relocIdx]; 292 } 293 294 // Optimization hints are sorted in a monotonically increasing order by their 295 // first address as are relocations (albeit in decreasing order), so if we keep 296 // a pointer around to the last found relocation, we don't have to do a full 297 // binary search every time. 298 Optional<PerformedReloc> 299 OptimizationHintContext::findPrimaryReloc(uint64_t offset) { 300 const auto end = isec->relocs.rend(); 301 while (relocIt != end && relocIt->offset < offset) 302 ++relocIt; 303 if (relocIt == end || relocIt->offset != offset) 304 return None; 305 return PerformedReloc{*relocIt, getRelocTarget(*relocIt)}; 306 } 307 308 // The second and third addresses of optimization hints have no such 309 // monotonicity as the first, so we search the entire range of relocations. 310 Optional<PerformedReloc> OptimizationHintContext::findReloc(uint64_t offset) { 311 // Optimization hints often apply to successive relocations, so we check for 312 // that first before doing a full binary search. 313 auto end = isec->relocs.rend(); 314 if (relocIt < end - 1 && (relocIt + 1)->offset == offset) 315 return PerformedReloc{*(relocIt + 1), getRelocTarget(*(relocIt + 1))}; 316 317 auto reloc = lower_bound(isec->relocs, offset, 318 [](const Reloc &reloc, uint64_t offset) { 319 return offset < reloc.offset; 320 }); 321 322 if (reloc == isec->relocs.end() || reloc->offset != offset) 323 return None; 324 return PerformedReloc{*reloc, getRelocTarget(*reloc)}; 325 } 326 327 // Transforms a pair of adrp+add instructions into an adr instruction if the 328 // target is within the +/- 1 MiB range allowed by the adr's 21 bit signed 329 // immediate offset. 330 // 331 // adrp xN, _foo@PAGE 332 // add xM, xN, _foo@PAGEOFF 333 // -> 334 // adr xM, _foo 335 // nop 336 void OptimizationHintContext::applyAdrpAdd(const OptimizationHint &hint) { 337 uint32_t ins1 = read32le(buf + hint.offset0); 338 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 339 Adrp adrp; 340 if (!parseAdrp(ins1, adrp)) 341 return; 342 Add add; 343 if (!parseAdd(ins2, add)) 344 return; 345 if (adrp.destRegister != add.srcRegister) 346 return; 347 348 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 349 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 350 if (!rel1 || !rel2) 351 return; 352 if (rel1->referentVA != rel2->referentVA) 353 return; 354 int64_t delta = rel1->referentVA - rel1->rel.offset - isec->getVA(); 355 if (delta >= (1 << 20) || delta < -(1 << 20)) 356 return; 357 358 writeAdr(buf + hint.offset0, add.destRegister, delta); 359 writeNop(buf + hint.offset0 + hint.delta[0]); 360 } 361 362 // Transforms two adrp instructions into a single adrp if their referent 363 // addresses are located on the same 4096 byte page. 364 // 365 // adrp xN, _foo@PAGE 366 // adrp xN, _bar@PAGE 367 // -> 368 // adrp xN, _foo@PAGE 369 // nop 370 void OptimizationHintContext::applyAdrpAdrp(const OptimizationHint &hint) { 371 uint32_t ins1 = read32le(buf + hint.offset0); 372 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 373 Adrp adrp1, adrp2; 374 if (!parseAdrp(ins1, adrp1) || !parseAdrp(ins2, adrp2)) 375 return; 376 if (adrp1.destRegister != adrp2.destRegister) 377 return; 378 379 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 380 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 381 if (!rel1 || !rel2) 382 return; 383 if ((rel1->referentVA & ~0xfffULL) != (rel2->referentVA & ~0xfffULL)) 384 return; 385 386 writeNop(buf + hint.offset0 + hint.delta[0]); 387 } 388 389 // Transforms a pair of adrp+ldr (immediate) instructions into an ldr (literal) 390 // load from a PC-relative address if it is 4-byte aligned and within +/- 1 MiB, 391 // as ldr can encode a signed 19-bit offset that gets multiplied by 4. 392 // 393 // adrp xN, _foo@PAGE 394 // ldr xM, [xN, _foo@PAGEOFF] 395 // -> 396 // nop 397 // ldr xM, _foo 398 void OptimizationHintContext::applyAdrpLdr(const OptimizationHint &hint) { 399 uint32_t ins1 = read32le(buf + hint.offset0); 400 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 401 Adrp adrp; 402 if (!parseAdrp(ins1, adrp)) 403 return; 404 Ldr ldr; 405 if (!parseLdr(ins2, ldr)) 406 return; 407 if (adrp.destRegister != ldr.baseRegister) 408 return; 409 410 Optional<PerformedReloc> rel1 = findPrimaryReloc(hint.offset0); 411 Optional<PerformedReloc> rel2 = findReloc(hint.offset0 + hint.delta[0]); 412 if (!rel1 || !rel2) 413 return; 414 if (ldr.offset != (rel1->referentVA & 0xfff)) 415 return; 416 if ((rel1->referentVA & 3) != 0) 417 return; 418 if (ldr.size == 1 || ldr.size == 2) 419 return; 420 int64_t delta = rel1->referentVA - rel2->rel.offset - isec->getVA(); 421 if (delta >= (1 << 20) || delta < -(1 << 20)) 422 return; 423 424 writeNop(buf + hint.offset0); 425 writeLiteralLdr(buf + hint.offset0 + hint.delta[0], ldr, delta); 426 } 427 428 // GOT loads are emitted by the compiler as a pair of adrp and ldr instructions, 429 // but they may be changed to adrp+add by relaxGotLoad(). This hint performs 430 // the AdrpLdr or AdrpAdd transformation depending on whether it was relaxed. 431 void OptimizationHintContext::applyAdrpLdrGot(const OptimizationHint &hint) { 432 uint32_t ins2 = read32le(buf + hint.offset0 + hint.delta[0]); 433 Add add; 434 Ldr ldr; 435 if (parseAdd(ins2, add)) 436 applyAdrpAdd(hint); 437 else if (parseLdr(ins2, ldr)) 438 applyAdrpLdr(hint); 439 } 440 441 void ARM64::applyOptimizationHints(uint8_t *buf, const ConcatInputSection *isec, 442 ArrayRef<uint64_t> relocTargets) const { 443 assert(isec); 444 assert(relocTargets.size() == isec->relocs.size()); 445 446 // Note: Some of these optimizations might not be valid when shared regions 447 // are in use. Will need to revisit this if splitSegInfo is added. 448 449 OptimizationHintContext ctx1(buf, isec, relocTargets); 450 for (const OptimizationHint &hint : isec->optimizationHints) { 451 switch (hint.type) { 452 case LOH_ARM64_ADRP_ADRP: 453 // This is done in another pass because the other optimization hints 454 // might cause its targets to be turned into NOPs. 455 break; 456 case LOH_ARM64_ADRP_LDR: 457 ctx1.applyAdrpLdr(hint); 458 break; 459 case LOH_ARM64_ADRP_ADD_LDR: 460 case LOH_ARM64_ADRP_LDR_GOT_LDR: 461 case LOH_ARM64_ADRP_ADD_STR: 462 case LOH_ARM64_ADRP_LDR_GOT_STR: 463 // TODO: Implement these 464 break; 465 case LOH_ARM64_ADRP_ADD: 466 ctx1.applyAdrpAdd(hint); 467 break; 468 case LOH_ARM64_ADRP_LDR_GOT: 469 ctx1.applyAdrpLdrGot(hint); 470 break; 471 } 472 } 473 474 OptimizationHintContext ctx2(buf, isec, relocTargets); 475 for (const OptimizationHint &hint : isec->optimizationHints) 476 if (hint.type == LOH_ARM64_ADRP_ADRP) 477 ctx2.applyAdrpAdrp(hint); 478 } 479 480 TargetInfo *macho::createARM64TargetInfo() { 481 static ARM64 t; 482 return &t; 483 } 484