1 //===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 // 9 //===----------------------------------------------------------------------===// 10 11 #include "HexagonFrameLowering.h" 12 #include "HexagonBlockRanges.h" 13 #include "HexagonInstrInfo.h" 14 #include "HexagonMachineFunctionInfo.h" 15 #include "HexagonRegisterInfo.h" 16 #include "HexagonSubtarget.h" 17 #include "HexagonTargetMachine.h" 18 #include "MCTargetDesc/HexagonBaseInfo.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/SetVector.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/CodeGen/LivePhysRegs.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineDominators.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineFunctionPass.h" 33 #include "llvm/CodeGen/MachineInstr.h" 34 #include "llvm/CodeGen/MachineInstrBuilder.h" 35 #include "llvm/CodeGen/MachineMemOperand.h" 36 #include "llvm/CodeGen/MachineModuleInfo.h" 37 #include "llvm/CodeGen/MachineOperand.h" 38 #include "llvm/CodeGen/MachinePostDominators.h" 39 #include "llvm/CodeGen/MachineRegisterInfo.h" 40 #include "llvm/CodeGen/RegisterScavenging.h" 41 #include "llvm/IR/DebugLoc.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/MC/MCDwarf.h" 44 #include "llvm/MC/MCRegisterInfo.h" 45 #include "llvm/Pass.h" 46 #include "llvm/Support/CodeGen.h" 47 #include "llvm/Support/CommandLine.h" 48 #include "llvm/Support/Debug.h" 49 #include "llvm/Support/ErrorHandling.h" 50 #include "llvm/Support/MathExtras.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include "llvm/Target/TargetMachine.h" 53 #include "llvm/Target/TargetRegisterInfo.h" 54 #include <algorithm> 55 #include <cassert> 56 #include <cstdint> 57 #include <iterator> 58 #include <limits> 59 #include <map> 60 #include <new> 61 #include <utility> 62 #include <vector> 63 64 #define DEBUG_TYPE "hexagon-pei" 65 66 // Hexagon stack frame layout as defined by the ABI: 67 // 68 // Incoming arguments 69 // passed via stack 70 // | 71 // | 72 // SP during function's FP during function's | 73 // +-- runtime (top of stack) runtime (bottom) --+ | 74 // | | | 75 // --++---------------------+------------------+-----------------++-+------- 76 // | parameter area for | variable-size | fixed-size |LR| arg 77 // | called functions | local objects | local objects |FP| 78 // --+----------------------+------------------+-----------------+--+------- 79 // <- size known -> <- size unknown -> <- size known -> 80 // 81 // Low address High address 82 // 83 // <--- stack growth 84 // 85 // 86 // - In any circumstances, the outgoing function arguments are always accessi- 87 // ble using the SP, and the incoming arguments are accessible using the FP. 88 // - If the local objects are not aligned, they can always be accessed using 89 // the FP. 90 // - If there are no variable-sized objects, the local objects can always be 91 // accessed using the SP, regardless whether they are aligned or not. (The 92 // alignment padding will be at the bottom of the stack (highest address), 93 // and so the offset with respect to the SP will be known at the compile- 94 // -time.) 95 // 96 // The only complication occurs if there are both, local aligned objects, and 97 // dynamically allocated (variable-sized) objects. The alignment pad will be 98 // placed between the FP and the local objects, thus preventing the use of the 99 // FP to access the local objects. At the same time, the variable-sized objects 100 // will be between the SP and the local objects, thus introducing an unknown 101 // distance from the SP to the locals. 102 // 103 // To avoid this problem, a new register is created that holds the aligned 104 // address of the bottom of the stack, referred in the sources as AP (aligned 105 // pointer). The AP will be equal to "FP-p", where "p" is the smallest pad 106 // that aligns AP to the required boundary (a maximum of the alignments of 107 // all stack objects, fixed- and variable-sized). All local objects[1] will 108 // then use AP as the base pointer. 109 // [1] The exception is with "fixed" stack objects. "Fixed" stack objects get 110 // their name from being allocated at fixed locations on the stack, relative 111 // to the FP. In the presence of dynamic allocation and local alignment, such 112 // objects can only be accessed through the FP. 113 // 114 // Illustration of the AP: 115 // FP --+ 116 // | 117 // ---------------+---------------------+-----+-----------------------++-+-- 118 // Rest of the | Local stack objects | Pad | Fixed stack objects |LR| 119 // stack frame | (aligned) | | (CSR, spills, etc.) |FP| 120 // ---------------+---------------------+-----+-----------------+-----+--+-- 121 // |<-- Multiple of the -->| 122 // stack alignment +-- AP 123 // 124 // The AP is set up at the beginning of the function. Since it is not a dedi- 125 // cated (reserved) register, it needs to be kept live throughout the function 126 // to be available as the base register for local object accesses. 127 // Normally, an address of a stack objects is obtained by a pseudo-instruction 128 // PS_fi. To access local objects with the AP register present, a different 129 // pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra 130 // argument compared to PS_fi: the first input register is the AP register. 131 // This keeps the register live between its definition and its uses. 132 133 // The AP register is originally set up using pseudo-instruction PS_aligna: 134 // AP = PS_aligna A 135 // where 136 // A - required stack alignment 137 // The alignment value must be the maximum of all alignments required by 138 // any stack object. 139 140 // The dynamic allocation uses a pseudo-instruction PS_alloca: 141 // Rd = PS_alloca Rs, A 142 // where 143 // Rd - address of the allocated space 144 // Rs - minimum size (the actual allocated can be larger to accommodate 145 // alignment) 146 // A - required alignment 147 148 using namespace llvm; 149 150 static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret", 151 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target")); 152 153 static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots", 154 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2), 155 cl::ZeroOrMore); 156 157 static cl::opt<int> SpillFuncThreshold("spill-func-threshold", 158 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"), 159 cl::init(6), cl::ZeroOrMore); 160 161 static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os", 162 cl::Hidden, cl::desc("Specify Os spill func threshold"), 163 cl::init(1), cl::ZeroOrMore); 164 165 static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer", 166 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."), 167 cl::init(false), cl::ZeroOrMore); 168 169 static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame", 170 cl::init(true), cl::Hidden, cl::ZeroOrMore, 171 cl::desc("Enable stack frame shrink wrapping")); 172 173 static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit", 174 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore, 175 cl::desc("Max count of stack frame shrink-wraps")); 176 177 static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long", 178 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."), 179 cl::init(false), cl::ZeroOrMore); 180 181 static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true), 182 cl::Hidden, cl::desc("Refrain from using FP whenever possible")); 183 184 static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden, 185 cl::init(true), cl::desc("Optimize spill slots")); 186 187 #ifndef NDEBUG 188 static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden, 189 cl::init(std::numeric_limits<unsigned>::max())); 190 static unsigned SpillOptCount = 0; 191 #endif 192 193 namespace llvm { 194 195 void initializeHexagonCallFrameInformationPass(PassRegistry&); 196 FunctionPass *createHexagonCallFrameInformation(); 197 198 } // end namespace llvm 199 200 namespace { 201 202 class HexagonCallFrameInformation : public MachineFunctionPass { 203 public: 204 static char ID; 205 206 HexagonCallFrameInformation() : MachineFunctionPass(ID) { 207 PassRegistry &PR = *PassRegistry::getPassRegistry(); 208 initializeHexagonCallFrameInformationPass(PR); 209 } 210 211 bool runOnMachineFunction(MachineFunction &MF) override; 212 213 MachineFunctionProperties getRequiredProperties() const override { 214 return MachineFunctionProperties().set( 215 MachineFunctionProperties::Property::NoVRegs); 216 } 217 }; 218 219 char HexagonCallFrameInformation::ID = 0; 220 221 } // end anonymous namespace 222 223 bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) { 224 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering(); 225 bool NeedCFI = MF.getMMI().hasDebugInfo() || 226 MF.getFunction()->needsUnwindTableEntry(); 227 228 if (!NeedCFI) 229 return false; 230 HFI.insertCFIInstructions(MF); 231 return true; 232 } 233 234 INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi", 235 "Hexagon call frame information", false, false) 236 237 FunctionPass *llvm::createHexagonCallFrameInformation() { 238 return new HexagonCallFrameInformation(); 239 } 240 241 /// Map a register pair Reg to the subregister that has the greater "number", 242 /// i.e. D3 (aka R7:6) will be mapped to R7, etc. 243 static unsigned getMax32BitSubRegister(unsigned Reg, 244 const TargetRegisterInfo &TRI, 245 bool hireg = true) { 246 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) 247 return Reg; 248 249 unsigned RegNo = 0; 250 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) { 251 if (hireg) { 252 if (*SubRegs > RegNo) 253 RegNo = *SubRegs; 254 } else { 255 if (!RegNo || *SubRegs < RegNo) 256 RegNo = *SubRegs; 257 } 258 } 259 return RegNo; 260 } 261 262 /// Returns the callee saved register with the largest id in the vector. 263 static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI, 264 const TargetRegisterInfo &TRI) { 265 static_assert(Hexagon::R1 > 0, 266 "Assume physical registers are encoded as positive integers"); 267 if (CSI.empty()) 268 return 0; 269 270 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI); 271 for (unsigned I = 1, E = CSI.size(); I < E; ++I) { 272 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI); 273 if (Reg > Max) 274 Max = Reg; 275 } 276 return Max; 277 } 278 279 /// Checks if the basic block contains any instruction that needs a stack 280 /// frame to be already in place. 281 static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR, 282 const HexagonRegisterInfo &HRI) { 283 for (auto &I : MBB) { 284 const MachineInstr *MI = &I; 285 if (MI->isCall()) 286 return true; 287 unsigned Opc = MI->getOpcode(); 288 switch (Opc) { 289 case Hexagon::PS_alloca: 290 case Hexagon::PS_aligna: 291 return true; 292 default: 293 break; 294 } 295 // Check individual operands. 296 for (const MachineOperand &MO : MI->operands()) { 297 // While the presence of a frame index does not prove that a stack 298 // frame will be required, all frame indexes should be within alloc- 299 // frame/deallocframe. Otherwise, the code that translates a frame 300 // index into an offset would have to be aware of the placement of 301 // the frame creation/destruction instructions. 302 if (MO.isFI()) 303 return true; 304 if (MO.isReg()) { 305 unsigned R = MO.getReg(); 306 // Virtual registers will need scavenging, which then may require 307 // a stack slot. 308 if (TargetRegisterInfo::isVirtualRegister(R)) 309 return true; 310 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S) 311 if (CSR[*S]) 312 return true; 313 continue; 314 } 315 if (MO.isRegMask()) { 316 // A regmask would normally have all callee-saved registers marked 317 // as preserved, so this check would not be needed, but in case of 318 // ever having other regmasks (for other calling conventions), 319 // make sure they would be processed correctly. 320 const uint32_t *BM = MO.getRegMask(); 321 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) { 322 unsigned R = x; 323 // If this regmask does not preserve a CSR, a frame will be needed. 324 if (!(BM[R/32] & (1u << (R%32)))) 325 return true; 326 } 327 } 328 } 329 } 330 return false; 331 } 332 333 /// Returns true if MBB has a machine instructions that indicates a tail call 334 /// in the block. 335 static bool hasTailCall(const MachineBasicBlock &MBB) { 336 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(); 337 unsigned RetOpc = I->getOpcode(); 338 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r; 339 } 340 341 /// Returns true if MBB contains an instruction that returns. 342 static bool hasReturn(const MachineBasicBlock &MBB) { 343 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I) 344 if (I->isReturn()) 345 return true; 346 return false; 347 } 348 349 /// Returns the "return" instruction from this block, or nullptr if there 350 /// isn't any. 351 static MachineInstr *getReturn(MachineBasicBlock &MBB) { 352 for (auto &I : MBB) 353 if (I.isReturn()) 354 return &I; 355 return nullptr; 356 } 357 358 static bool isRestoreCall(unsigned Opc) { 359 switch (Opc) { 360 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4: 361 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC: 362 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT: 363 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC: 364 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT: 365 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC: 366 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4: 367 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC: 368 return true; 369 } 370 return false; 371 } 372 373 static inline bool isOptNone(const MachineFunction &MF) { 374 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) || 375 MF.getTarget().getOptLevel() == CodeGenOpt::None; 376 } 377 378 static inline bool isOptSize(const MachineFunction &MF) { 379 const Function &F = *MF.getFunction(); 380 return F.optForSize() && !F.optForMinSize(); 381 } 382 383 static inline bool isMinSize(const MachineFunction &MF) { 384 return MF.getFunction()->optForMinSize(); 385 } 386 387 /// Implements shrink-wrapping of the stack frame. By default, stack frame 388 /// is created in the function entry block, and is cleaned up in every block 389 /// that returns. This function finds alternate blocks: one for the frame 390 /// setup (prolog) and one for the cleanup (epilog). 391 void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF, 392 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const { 393 static unsigned ShrinkCounter = 0; 394 395 if (ShrinkLimit.getPosition()) { 396 if (ShrinkCounter >= ShrinkLimit) 397 return; 398 ShrinkCounter++; 399 } 400 401 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 402 auto &HRI = *HST.getRegisterInfo(); 403 404 MachineDominatorTree MDT; 405 MDT.runOnMachineFunction(MF); 406 MachinePostDominatorTree MPT; 407 MPT.runOnMachineFunction(MF); 408 409 typedef DenseMap<unsigned,unsigned> UnsignedMap; 410 UnsignedMap RPO; 411 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType; 412 RPOTType RPOT(&MF); 413 unsigned RPON = 0; 414 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) 415 RPO[(*I)->getNumber()] = RPON++; 416 417 // Don't process functions that have loops, at least for now. Placement 418 // of prolog and epilog must take loop structure into account. For simpli- 419 // city don't do it right now. 420 for (auto &I : MF) { 421 unsigned BN = RPO[I.getNumber()]; 422 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) { 423 // If found a back-edge, return. 424 if (RPO[(*SI)->getNumber()] <= BN) 425 return; 426 } 427 } 428 429 // Collect the set of blocks that need a stack frame to execute. Scan 430 // each block for uses/defs of callee-saved registers, calls, etc. 431 SmallVector<MachineBasicBlock*,16> SFBlocks; 432 BitVector CSR(Hexagon::NUM_TARGET_REGS); 433 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P) 434 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S) 435 CSR[*S] = true; 436 437 for (auto &I : MF) 438 if (needsStackFrame(I, CSR, HRI)) 439 SFBlocks.push_back(&I); 440 441 DEBUG({ 442 dbgs() << "Blocks needing SF: {"; 443 for (auto &B : SFBlocks) 444 dbgs() << " BB#" << B->getNumber(); 445 dbgs() << " }\n"; 446 }); 447 // No frame needed? 448 if (SFBlocks.empty()) 449 return; 450 451 // Pick a common dominator and a common post-dominator. 452 MachineBasicBlock *DomB = SFBlocks[0]; 453 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) { 454 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]); 455 if (!DomB) 456 break; 457 } 458 MachineBasicBlock *PDomB = SFBlocks[0]; 459 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) { 460 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]); 461 if (!PDomB) 462 break; 463 } 464 DEBUG({ 465 dbgs() << "Computed dom block: BB#"; 466 if (DomB) dbgs() << DomB->getNumber(); 467 else dbgs() << "<null>"; 468 dbgs() << ", computed pdom block: BB#"; 469 if (PDomB) dbgs() << PDomB->getNumber(); 470 else dbgs() << "<null>"; 471 dbgs() << "\n"; 472 }); 473 if (!DomB || !PDomB) 474 return; 475 476 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB. 477 if (!MDT.dominates(DomB, PDomB)) { 478 DEBUG(dbgs() << "Dom block does not dominate pdom block\n"); 479 return; 480 } 481 if (!MPT.dominates(PDomB, DomB)) { 482 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n"); 483 return; 484 } 485 486 // Finally, everything seems right. 487 PrologB = DomB; 488 EpilogB = PDomB; 489 } 490 491 /// Perform most of the PEI work here: 492 /// - saving/restoring of the callee-saved registers, 493 /// - stack frame creation and destruction. 494 /// Normally, this work is distributed among various functions, but doing it 495 /// in one place allows shrink-wrapping of the stack frame. 496 void HexagonFrameLowering::emitPrologue(MachineFunction &MF, 497 MachineBasicBlock &MBB) const { 498 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 499 auto &HRI = *HST.getRegisterInfo(); 500 501 MachineFrameInfo &MFI = MF.getFrameInfo(); 502 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 503 504 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr; 505 if (EnableShrinkWrapping) 506 findShrunkPrologEpilog(MF, PrologB, EpilogB); 507 508 bool PrologueStubs = false; 509 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs); 510 insertPrologueInBlock(*PrologB, PrologueStubs); 511 updateEntryPaths(MF, *PrologB); 512 513 if (EpilogB) { 514 insertCSRRestoresInBlock(*EpilogB, CSI, HRI); 515 insertEpilogueInBlock(*EpilogB); 516 } else { 517 for (auto &B : MF) 518 if (B.isReturnBlock()) 519 insertCSRRestoresInBlock(B, CSI, HRI); 520 521 for (auto &B : MF) 522 if (B.isReturnBlock()) 523 insertEpilogueInBlock(B); 524 525 for (auto &B : MF) { 526 if (B.empty()) 527 continue; 528 MachineInstr *RetI = getReturn(B); 529 if (!RetI || isRestoreCall(RetI->getOpcode())) 530 continue; 531 for (auto &R : CSI) 532 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true)); 533 } 534 } 535 536 if (EpilogB) { 537 // If there is an epilog block, it may not have a return instruction. 538 // In such case, we need to add the callee-saved registers as live-ins 539 // in all blocks on all paths from the epilog to any return block. 540 unsigned MaxBN = MF.getNumBlockIDs(); 541 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1); 542 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path); 543 } 544 } 545 546 void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB, 547 bool PrologueStubs) const { 548 MachineFunction &MF = *MBB.getParent(); 549 MachineFrameInfo &MFI = MF.getFrameInfo(); 550 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 551 auto &HII = *HST.getInstrInfo(); 552 auto &HRI = *HST.getRegisterInfo(); 553 554 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment()); 555 556 // Calculate the total stack frame size. 557 // Get the number of bytes to allocate from the FrameInfo. 558 unsigned FrameSize = MFI.getStackSize(); 559 // Round up the max call frame size to the max alignment on the stack. 560 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign); 561 MFI.setMaxCallFrameSize(MaxCFA); 562 563 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign); 564 MFI.setStackSize(FrameSize); 565 566 bool AlignStack = (MaxAlign > getStackAlignment()); 567 568 // Get the number of bytes to allocate from the FrameInfo. 569 unsigned NumBytes = MFI.getStackSize(); 570 unsigned SP = HRI.getStackRegister(); 571 unsigned MaxCF = MFI.getMaxCallFrameSize(); 572 MachineBasicBlock::iterator InsertPt = MBB.begin(); 573 574 SmallVector<MachineInstr *, 4> AdjustRegs; 575 for (auto &MBB : MF) 576 for (auto &MI : MBB) 577 if (MI.getOpcode() == Hexagon::PS_alloca) 578 AdjustRegs.push_back(&MI); 579 580 for (auto MI : AdjustRegs) { 581 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca"); 582 expandAlloca(MI, HII, SP, MaxCF); 583 MI->eraseFromParent(); 584 } 585 586 DebugLoc dl = MBB.findDebugLoc(InsertPt); 587 588 if (hasFP(MF)) { 589 insertAllocframe(MBB, InsertPt, NumBytes); 590 if (AlignStack) { 591 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP) 592 .addReg(SP) 593 .addImm(-int64_t(MaxAlign)); 594 } 595 // If the stack-checking is enabled, and we spilled the callee-saved 596 // registers inline (i.e. did not use a spill function), then call 597 // the stack checker directly. 598 if (EnableStackOVFSanitizer && !PrologueStubs) 599 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk)) 600 .addExternalSymbol("__runtime_stack_check"); 601 } else if (NumBytes > 0) { 602 assert(alignTo(NumBytes, 8) == NumBytes); 603 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP) 604 .addReg(SP) 605 .addImm(-int(NumBytes)); 606 } 607 } 608 609 void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const { 610 MachineFunction &MF = *MBB.getParent(); 611 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 612 auto &HII = *HST.getInstrInfo(); 613 auto &HRI = *HST.getRegisterInfo(); 614 unsigned SP = HRI.getStackRegister(); 615 616 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator(); 617 DebugLoc dl = MBB.findDebugLoc(InsertPt); 618 619 if (!hasFP(MF)) { 620 MachineFrameInfo &MFI = MF.getFrameInfo(); 621 if (unsigned NumBytes = MFI.getStackSize()) { 622 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP) 623 .addReg(SP) 624 .addImm(NumBytes); 625 } 626 return; 627 } 628 629 MachineInstr *RetI = getReturn(MBB); 630 unsigned RetOpc = RetI ? RetI->getOpcode() : 0; 631 632 // Handle EH_RETURN. 633 if (RetOpc == Hexagon::EH_RETURN_JMPR) { 634 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe)); 635 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP) 636 .addReg(SP) 637 .addReg(Hexagon::R28); 638 return; 639 } 640 641 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc- 642 // frame instruction if we encounter it. 643 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 || 644 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC || 645 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT || 646 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) { 647 MachineBasicBlock::iterator It = RetI; 648 ++It; 649 // Delete all instructions after the RESTORE (except labels). 650 while (It != MBB.end()) { 651 if (!It->isLabel()) 652 It = MBB.erase(It); 653 else 654 ++It; 655 } 656 return; 657 } 658 659 // It is possible that the restoring code is a call to a library function. 660 // All of the restore* functions include "deallocframe", so we need to make 661 // sure that we don't add an extra one. 662 bool NeedsDeallocframe = true; 663 if (!MBB.empty() && InsertPt != MBB.begin()) { 664 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt); 665 unsigned COpc = PrevIt->getOpcode(); 666 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 || 667 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC || 668 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT || 669 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC || 670 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr) 671 NeedsDeallocframe = false; 672 } 673 674 if (!NeedsDeallocframe) 675 return; 676 // If the returning instruction is PS_jmpret, replace it with dealloc_return, 677 // otherwise just add deallocframe. The function could be returning via a 678 // tail call. 679 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) { 680 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe)); 681 return; 682 } 683 unsigned NewOpc = Hexagon::L4_return; 684 MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc)); 685 // Transfer the function live-out registers. 686 NewI->copyImplicitOps(MF, *RetI); 687 MBB.erase(RetI); 688 } 689 690 void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB, 691 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const { 692 MachineFunction &MF = *MBB.getParent(); 693 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 694 auto &HII = *HST.getInstrInfo(); 695 auto &HRI = *HST.getRegisterInfo(); 696 697 // Check for overflow. 698 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used? 699 const unsigned int ALLOCFRAME_MAX = 16384; 700 701 // Create a dummy memory operand to avoid allocframe from being treated as 702 // a volatile memory reference. 703 auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0), 704 MachineMemOperand::MOStore, 4, 4); 705 706 DebugLoc dl = MBB.findDebugLoc(InsertPt); 707 708 if (NumBytes >= ALLOCFRAME_MAX) { 709 // Emit allocframe(#0). 710 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe)) 711 .addImm(0) 712 .addMemOperand(MMO); 713 714 // Subtract the size from the stack pointer. 715 unsigned SP = HRI.getStackRegister(); 716 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP) 717 .addReg(SP) 718 .addImm(-int(NumBytes)); 719 } else { 720 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe)) 721 .addImm(NumBytes) 722 .addMemOperand(MMO); 723 } 724 } 725 726 void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF, 727 MachineBasicBlock &SaveB) const { 728 SetVector<unsigned> Worklist; 729 730 MachineBasicBlock &EntryB = MF.front(); 731 Worklist.insert(EntryB.getNumber()); 732 733 unsigned SaveN = SaveB.getNumber(); 734 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo(); 735 736 for (unsigned i = 0; i < Worklist.size(); ++i) { 737 unsigned BN = Worklist[i]; 738 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN); 739 for (auto &R : CSI) 740 if (!MBB.isLiveIn(R.getReg())) 741 MBB.addLiveIn(R.getReg()); 742 if (BN != SaveN) 743 for (auto &SB : MBB.successors()) 744 Worklist.insert(SB->getNumber()); 745 } 746 } 747 748 bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB, 749 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF, 750 BitVector &Path) const { 751 assert(MBB.getNumber() >= 0); 752 unsigned BN = MBB.getNumber(); 753 if (Path[BN] || DoneF[BN]) 754 return false; 755 if (DoneT[BN]) 756 return true; 757 758 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo(); 759 760 Path[BN] = true; 761 bool ReachedExit = false; 762 for (auto &SB : MBB.successors()) 763 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path); 764 765 if (!MBB.empty() && MBB.back().isReturn()) { 766 // Add implicit uses of all callee-saved registers to the reached 767 // return instructions. This is to prevent the anti-dependency breaker 768 // from renaming these registers. 769 MachineInstr &RetI = MBB.back(); 770 if (!isRestoreCall(RetI.getOpcode())) 771 for (auto &R : CSI) 772 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true)); 773 ReachedExit = true; 774 } 775 776 // We don't want to add unnecessary live-ins to the restore block: since 777 // the callee-saved registers are being defined in it, the entry of the 778 // restore block cannot be on the path from the definitions to any exit. 779 if (ReachedExit && &MBB != &RestoreB) { 780 for (auto &R : CSI) 781 if (!MBB.isLiveIn(R.getReg())) 782 MBB.addLiveIn(R.getReg()); 783 DoneT[BN] = true; 784 } 785 if (!ReachedExit) 786 DoneF[BN] = true; 787 788 Path[BN] = false; 789 return ReachedExit; 790 } 791 792 static Optional<MachineBasicBlock::iterator> 793 findCFILocation(MachineBasicBlock &B) { 794 // The CFI instructions need to be inserted right after allocframe. 795 // An exception to this is a situation where allocframe is bundled 796 // with a call: then the CFI instructions need to be inserted before 797 // the packet with the allocframe+call (in case the call throws an 798 // exception). 799 auto End = B.instr_end(); 800 801 for (MachineInstr &I : B) { 802 MachineBasicBlock::iterator It = I.getIterator(); 803 if (!I.isBundle()) { 804 if (I.getOpcode() == Hexagon::S2_allocframe) 805 return std::next(It); 806 continue; 807 } 808 // I is a bundle. 809 bool HasCall = false, HasAllocFrame = false; 810 auto T = It.getInstrIterator(); 811 while (++T != End && T->isBundled()) { 812 if (T->getOpcode() == Hexagon::S2_allocframe) 813 HasAllocFrame = true; 814 else if (T->isCall()) 815 HasCall = true; 816 } 817 if (HasAllocFrame) 818 return HasCall ? It : std::next(It); 819 } 820 return None; 821 } 822 823 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const { 824 for (auto &B : MF) { 825 auto At = findCFILocation(B); 826 if (At.hasValue()) 827 insertCFIInstructionsAt(B, At.getValue()); 828 } 829 } 830 831 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB, 832 MachineBasicBlock::iterator At) const { 833 MachineFunction &MF = *MBB.getParent(); 834 MachineFrameInfo &MFI = MF.getFrameInfo(); 835 MachineModuleInfo &MMI = MF.getMMI(); 836 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 837 auto &HII = *HST.getInstrInfo(); 838 auto &HRI = *HST.getRegisterInfo(); 839 840 // If CFI instructions have debug information attached, something goes 841 // wrong with the final assembly generation: the prolog_end is placed 842 // in a wrong location. 843 DebugLoc DL; 844 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION); 845 846 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol(); 847 bool HasFP = hasFP(MF); 848 849 if (HasFP) { 850 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true); 851 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true); 852 853 // Define CFA via an offset from the value of FP. 854 // 855 // -8 -4 0 (SP) 856 // --+----+----+--------------------- 857 // | FP | LR | increasing addresses --> 858 // --+----+----+--------------------- 859 // | +-- Old SP (before allocframe) 860 // +-- New FP (after allocframe) 861 // 862 // MCCFIInstruction::createDefCfa subtracts the offset from the register. 863 // MCCFIInstruction::createOffset takes the offset without sign change. 864 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8); 865 BuildMI(MBB, At, DL, CFID) 866 .addCFIIndex(MF.addFrameInst(DefCfa)); 867 // R31 (return addr) = CFA - 4 868 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4); 869 BuildMI(MBB, At, DL, CFID) 870 .addCFIIndex(MF.addFrameInst(OffR31)); 871 // R30 (frame ptr) = CFA - 8 872 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8); 873 BuildMI(MBB, At, DL, CFID) 874 .addCFIIndex(MF.addFrameInst(OffR30)); 875 } 876 877 static unsigned int RegsToMove[] = { 878 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2, 879 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18, 880 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22, 881 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26, 882 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9, 883 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13, 884 Hexagon::NoRegister 885 }; 886 887 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 888 889 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) { 890 unsigned Reg = RegsToMove[i]; 891 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool { 892 return C.getReg() == Reg; 893 }; 894 auto F = find_if(CSI, IfR); 895 if (F == CSI.end()) 896 continue; 897 898 int64_t Offset; 899 if (HasFP) { 900 // If the function has a frame pointer (i.e. has an allocframe), 901 // then the CFA has been defined in terms of FP. Any offsets in 902 // the following CFI instructions have to be defined relative 903 // to FP, which points to the bottom of the stack frame. 904 // The function getFrameIndexReference can still choose to use SP 905 // for the offset calculation, so we cannot simply call it here. 906 // Instead, get the offset (relative to the FP) directly. 907 Offset = MFI.getObjectOffset(F->getFrameIdx()); 908 } else { 909 unsigned FrameReg; 910 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg); 911 } 912 // Subtract 8 to make room for R30 and R31, which are added above. 913 Offset -= 8; 914 915 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) { 916 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true); 917 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg, 918 Offset); 919 BuildMI(MBB, At, DL, CFID) 920 .addCFIIndex(MF.addFrameInst(OffReg)); 921 } else { 922 // Split the double regs into subregs, and generate appropriate 923 // cfi_offsets. 924 // The only reason, we are split double regs is, llvm-mc does not 925 // understand paired registers for cfi_offset. 926 // Eg .cfi_offset r1:0, -64 927 928 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi); 929 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo); 930 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true); 931 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true); 932 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg, 933 Offset+4); 934 BuildMI(MBB, At, DL, CFID) 935 .addCFIIndex(MF.addFrameInst(OffHi)); 936 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg, 937 Offset); 938 BuildMI(MBB, At, DL, CFID) 939 .addCFIIndex(MF.addFrameInst(OffLo)); 940 } 941 } 942 } 943 944 bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const { 945 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 946 return false; 947 948 auto &MFI = MF.getFrameInfo(); 949 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 950 bool HasExtraAlign = HRI.needsStackRealignment(MF); 951 bool HasAlloca = MFI.hasVarSizedObjects(); 952 953 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think 954 // that this shouldn't be required, but doing so now because gcc does and 955 // gdb can't break at the start of the function without it. Will remove if 956 // this turns out to be a gdb bug. 957 // 958 if (MF.getTarget().getOptLevel() == CodeGenOpt::None) 959 return true; 960 961 // By default we want to use SP (since it's always there). FP requires 962 // some setup (i.e. ALLOCFRAME). 963 // Both, alloca and stack alignment modify the stack pointer by an 964 // undetermined value, so we need to save it at the entry to the function 965 // (i.e. use allocframe). 966 if (HasAlloca || HasExtraAlign) 967 return true; 968 969 if (MFI.getStackSize() > 0) { 970 // If FP-elimination is disabled, we have to use FP at this point. 971 const TargetMachine &TM = MF.getTarget(); 972 if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer) 973 return true; 974 if (EnableStackOVFSanitizer) 975 return true; 976 } 977 978 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>(); 979 if (MFI.hasCalls() || HMFI.hasClobberLR()) 980 return true; 981 982 return false; 983 } 984 985 enum SpillKind { 986 SK_ToMem, 987 SK_FromMem, 988 SK_FromMemTailcall 989 }; 990 991 static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType, 992 bool Stkchk = false) { 993 const char * V4SpillToMemoryFunctions[] = { 994 "__save_r16_through_r17", 995 "__save_r16_through_r19", 996 "__save_r16_through_r21", 997 "__save_r16_through_r23", 998 "__save_r16_through_r25", 999 "__save_r16_through_r27" }; 1000 1001 const char * V4SpillToMemoryStkchkFunctions[] = { 1002 "__save_r16_through_r17_stkchk", 1003 "__save_r16_through_r19_stkchk", 1004 "__save_r16_through_r21_stkchk", 1005 "__save_r16_through_r23_stkchk", 1006 "__save_r16_through_r25_stkchk", 1007 "__save_r16_through_r27_stkchk" }; 1008 1009 const char * V4SpillFromMemoryFunctions[] = { 1010 "__restore_r16_through_r17_and_deallocframe", 1011 "__restore_r16_through_r19_and_deallocframe", 1012 "__restore_r16_through_r21_and_deallocframe", 1013 "__restore_r16_through_r23_and_deallocframe", 1014 "__restore_r16_through_r25_and_deallocframe", 1015 "__restore_r16_through_r27_and_deallocframe" }; 1016 1017 const char * V4SpillFromMemoryTailcallFunctions[] = { 1018 "__restore_r16_through_r17_and_deallocframe_before_tailcall", 1019 "__restore_r16_through_r19_and_deallocframe_before_tailcall", 1020 "__restore_r16_through_r21_and_deallocframe_before_tailcall", 1021 "__restore_r16_through_r23_and_deallocframe_before_tailcall", 1022 "__restore_r16_through_r25_and_deallocframe_before_tailcall", 1023 "__restore_r16_through_r27_and_deallocframe_before_tailcall" 1024 }; 1025 1026 const char **SpillFunc = nullptr; 1027 1028 switch(SpillType) { 1029 case SK_ToMem: 1030 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions 1031 : V4SpillToMemoryFunctions; 1032 break; 1033 case SK_FromMem: 1034 SpillFunc = V4SpillFromMemoryFunctions; 1035 break; 1036 case SK_FromMemTailcall: 1037 SpillFunc = V4SpillFromMemoryTailcallFunctions; 1038 break; 1039 } 1040 assert(SpillFunc && "Unknown spill kind"); 1041 1042 // Spill all callee-saved registers up to the highest register used. 1043 switch (MaxReg) { 1044 case Hexagon::R17: 1045 return SpillFunc[0]; 1046 case Hexagon::R19: 1047 return SpillFunc[1]; 1048 case Hexagon::R21: 1049 return SpillFunc[2]; 1050 case Hexagon::R23: 1051 return SpillFunc[3]; 1052 case Hexagon::R25: 1053 return SpillFunc[4]; 1054 case Hexagon::R27: 1055 return SpillFunc[5]; 1056 default: 1057 llvm_unreachable("Unhandled maximum callee save register"); 1058 } 1059 return nullptr; 1060 } 1061 1062 int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF, 1063 int FI, unsigned &FrameReg) const { 1064 auto &MFI = MF.getFrameInfo(); 1065 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1066 1067 int Offset = MFI.getObjectOffset(FI); 1068 bool HasAlloca = MFI.hasVarSizedObjects(); 1069 bool HasExtraAlign = HRI.needsStackRealignment(MF); 1070 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None; 1071 1072 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>(); 1073 unsigned FrameSize = MFI.getStackSize(); 1074 unsigned SP = HRI.getStackRegister(); 1075 unsigned FP = HRI.getFrameRegister(); 1076 unsigned AP = HMFI.getStackAlignBasePhysReg(); 1077 // It may happen that AP will be absent even HasAlloca && HasExtraAlign 1078 // is true. HasExtraAlign may be set because of vector spills, without 1079 // aligned locals or aligned outgoing function arguments. Since vector 1080 // spills will ultimately be "unaligned", it is safe to use FP as the 1081 // base register. 1082 // In fact, in such a scenario the stack is actually not required to be 1083 // aligned, although it may end up being aligned anyway, since this 1084 // particular case is not easily detectable. The alignment will be 1085 // unnecessary, but not incorrect. 1086 // Unfortunately there is no quick way to verify that the above is 1087 // indeed the case (and that it's not a result of an error), so just 1088 // assume that missing AP will be replaced by FP. 1089 // (A better fix would be to rematerialize AP from FP and always align 1090 // vector spills.) 1091 if (AP == 0) 1092 AP = FP; 1093 1094 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0). 1095 // Use FP at -O0, except when there are objects with extra alignment. 1096 // That additional alignment requirement may cause a pad to be inserted, 1097 // which will make it impossible to use FP to access objects located 1098 // past the pad. 1099 if (NoOpt && !HasExtraAlign) 1100 UseFP = true; 1101 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) { 1102 // Fixed and preallocated objects will be located before any padding 1103 // so FP must be used to access them. 1104 UseFP |= (HasAlloca || HasExtraAlign); 1105 } else { 1106 if (HasAlloca) { 1107 if (HasExtraAlign) 1108 UseAP = true; 1109 else 1110 UseFP = true; 1111 } 1112 } 1113 1114 // If FP was picked, then there had better be FP. 1115 bool HasFP = hasFP(MF); 1116 assert((HasFP || !UseFP) && "This function must have frame pointer"); 1117 1118 // Having FP implies allocframe. Allocframe will store extra 8 bytes: 1119 // FP/LR. If the base register is used to access an object across these 1120 // 8 bytes, then the offset will need to be adjusted by 8. 1121 // 1122 // After allocframe: 1123 // HexagonISelLowering adds 8 to ---+ 1124 // the offsets of all stack-based | 1125 // arguments (*) | 1126 // | 1127 // getObjectOffset < 0 0 8 getObjectOffset >= 8 1128 // ------------------------+-----+------------------------> increasing 1129 // <local objects> |FP/LR| <input arguments> addresses 1130 // -----------------+------+-----+------------------------> 1131 // | | 1132 // SP/AP point --+ +-- FP points here (**) 1133 // somewhere on 1134 // this side of FP/LR 1135 // 1136 // (*) See LowerFormalArguments. The FP/LR is assumed to be present. 1137 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR. 1138 1139 // The lowering assumes that FP/LR is present, and so the offsets of 1140 // the formal arguments start at 8. If FP/LR is not there we need to 1141 // reduce the offset by 8. 1142 if (Offset > 0 && !HasFP) 1143 Offset -= 8; 1144 1145 if (UseFP) 1146 FrameReg = FP; 1147 else if (UseAP) 1148 FrameReg = AP; 1149 else 1150 FrameReg = SP; 1151 1152 // Calculate the actual offset in the instruction. If there is no FP 1153 // (in other words, no allocframe), then SP will not be adjusted (i.e. 1154 // there will be no SP -= FrameSize), so the frame size should not be 1155 // added to the calculated offset. 1156 int RealOffset = Offset; 1157 if (!UseFP && !UseAP) 1158 RealOffset = FrameSize+Offset; 1159 return RealOffset; 1160 } 1161 1162 bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB, 1163 const CSIVect &CSI, const HexagonRegisterInfo &HRI, 1164 bool &PrologueStubs) const { 1165 if (CSI.empty()) 1166 return true; 1167 1168 MachineBasicBlock::iterator MI = MBB.begin(); 1169 PrologueStubs = false; 1170 MachineFunction &MF = *MBB.getParent(); 1171 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1172 auto &HII = *HST.getInstrInfo(); 1173 1174 if (useSpillFunction(MF, CSI)) { 1175 PrologueStubs = true; 1176 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI); 1177 bool StkOvrFlowEnabled = EnableStackOVFSanitizer; 1178 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem, 1179 StkOvrFlowEnabled); 1180 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget()); 1181 bool IsPIC = HTM.isPositionIndependent(); 1182 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong; 1183 1184 // Call spill function. 1185 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc(); 1186 unsigned SpillOpc; 1187 if (StkOvrFlowEnabled) { 1188 if (LongCalls) 1189 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC 1190 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT; 1191 else 1192 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC 1193 : Hexagon::SAVE_REGISTERS_CALL_V4STK; 1194 } else { 1195 if (LongCalls) 1196 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC 1197 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT; 1198 else 1199 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC 1200 : Hexagon::SAVE_REGISTERS_CALL_V4; 1201 } 1202 1203 MachineInstr *SaveRegsCall = 1204 BuildMI(MBB, MI, DL, HII.get(SpillOpc)) 1205 .addExternalSymbol(SpillFun); 1206 1207 // Add callee-saved registers as use. 1208 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true); 1209 // Add live in registers. 1210 for (unsigned I = 0; I < CSI.size(); ++I) 1211 MBB.addLiveIn(CSI[I].getReg()); 1212 return true; 1213 } 1214 1215 for (unsigned i = 0, n = CSI.size(); i < n; ++i) { 1216 unsigned Reg = CSI[i].getReg(); 1217 // Add live in registers. We treat eh_return callee saved register r0 - r3 1218 // specially. They are not really callee saved registers as they are not 1219 // supposed to be killed. 1220 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg); 1221 int FI = CSI[i].getFrameIdx(); 1222 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg); 1223 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI); 1224 if (IsKill) 1225 MBB.addLiveIn(Reg); 1226 } 1227 return true; 1228 } 1229 1230 bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB, 1231 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const { 1232 if (CSI.empty()) 1233 return false; 1234 1235 MachineBasicBlock::iterator MI = MBB.getFirstTerminator(); 1236 MachineFunction &MF = *MBB.getParent(); 1237 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1238 auto &HII = *HST.getInstrInfo(); 1239 1240 if (useRestoreFunction(MF, CSI)) { 1241 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB); 1242 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI); 1243 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem; 1244 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind); 1245 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget()); 1246 bool IsPIC = HTM.isPositionIndependent(); 1247 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong; 1248 1249 // Call spill function. 1250 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() 1251 : MBB.getLastNonDebugInstr()->getDebugLoc(); 1252 MachineInstr *DeallocCall = nullptr; 1253 1254 if (HasTC) { 1255 unsigned RetOpc; 1256 if (LongCalls) 1257 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC 1258 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT; 1259 else 1260 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC 1261 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4; 1262 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc)) 1263 .addExternalSymbol(RestoreFn); 1264 } else { 1265 // The block has a return. 1266 MachineBasicBlock::iterator It = MBB.getFirstTerminator(); 1267 assert(It->isReturn() && std::next(It) == MBB.end()); 1268 unsigned RetOpc; 1269 if (LongCalls) 1270 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC 1271 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT; 1272 else 1273 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC 1274 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4; 1275 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc)) 1276 .addExternalSymbol(RestoreFn); 1277 // Transfer the function live-out registers. 1278 DeallocCall->copyImplicitOps(MF, *It); 1279 } 1280 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false); 1281 return true; 1282 } 1283 1284 for (unsigned i = 0; i < CSI.size(); ++i) { 1285 unsigned Reg = CSI[i].getReg(); 1286 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg); 1287 int FI = CSI[i].getFrameIdx(); 1288 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI); 1289 } 1290 1291 return true; 1292 } 1293 1294 MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr( 1295 MachineFunction &MF, MachineBasicBlock &MBB, 1296 MachineBasicBlock::iterator I) const { 1297 MachineInstr &MI = *I; 1298 unsigned Opc = MI.getOpcode(); 1299 (void)Opc; // Silence compiler warning. 1300 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) && 1301 "Cannot handle this call frame pseudo instruction"); 1302 return MBB.erase(I); 1303 } 1304 1305 void HexagonFrameLowering::processFunctionBeforeFrameFinalized( 1306 MachineFunction &MF, RegScavenger *RS) const { 1307 // If this function has uses aligned stack and also has variable sized stack 1308 // objects, then we need to map all spill slots to fixed positions, so that 1309 // they can be accessed through FP. Otherwise they would have to be accessed 1310 // via AP, which may not be available at the particular place in the program. 1311 MachineFrameInfo &MFI = MF.getFrameInfo(); 1312 bool HasAlloca = MFI.hasVarSizedObjects(); 1313 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment()); 1314 1315 if (!HasAlloca || !NeedsAlign) 1316 return; 1317 1318 unsigned LFS = MFI.getLocalFrameSize(); 1319 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 1320 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i)) 1321 continue; 1322 unsigned S = MFI.getObjectSize(i); 1323 // Reduce the alignment to at most 8. This will require unaligned vector 1324 // stores if they happen here. 1325 unsigned A = std::max(MFI.getObjectAlignment(i), 8U); 1326 MFI.setObjectAlignment(i, 8); 1327 LFS = alignTo(LFS+S, A); 1328 MFI.mapLocalFrameObject(i, -LFS); 1329 } 1330 1331 MFI.setLocalFrameSize(LFS); 1332 unsigned A = MFI.getLocalFrameMaxAlign(); 1333 assert(A <= 8 && "Unexpected local frame alignment"); 1334 if (A == 0) 1335 MFI.setLocalFrameMaxAlign(8); 1336 MFI.setUseLocalStackAllocationBlock(true); 1337 1338 // Set the physical aligned-stack base address register. 1339 unsigned AP = 0; 1340 if (const MachineInstr *AI = getAlignaInstr(MF)) 1341 AP = AI->getOperand(0).getReg(); 1342 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>(); 1343 HMFI.setStackAlignBasePhysReg(AP); 1344 } 1345 1346 /// Returns true if there are no caller-saved registers available in class RC. 1347 static bool needToReserveScavengingSpillSlots(MachineFunction &MF, 1348 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) { 1349 MachineRegisterInfo &MRI = MF.getRegInfo(); 1350 1351 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool { 1352 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI) 1353 if (MRI.isPhysRegUsed(*AI)) 1354 return true; 1355 return false; 1356 }; 1357 1358 // Check for an unused caller-saved register. Callee-saved registers 1359 // have become pristine by now. 1360 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P) 1361 if (!IsUsed(*P)) 1362 return false; 1363 1364 // All caller-saved registers are used. 1365 return true; 1366 } 1367 1368 #ifndef NDEBUG 1369 static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) { 1370 dbgs() << '{'; 1371 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) { 1372 unsigned R = x; 1373 dbgs() << ' ' << PrintReg(R, &TRI); 1374 } 1375 dbgs() << " }"; 1376 } 1377 #endif 1378 1379 bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF, 1380 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const { 1381 DEBUG(dbgs() << __func__ << " on " 1382 << MF.getFunction()->getName() << '\n'); 1383 MachineFrameInfo &MFI = MF.getFrameInfo(); 1384 BitVector SRegs(Hexagon::NUM_TARGET_REGS); 1385 1386 // Generate a set of unique, callee-saved registers (SRegs), where each 1387 // register in the set is maximal in terms of sub-/super-register relation, 1388 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs. 1389 1390 // (1) For each callee-saved register, add that register and all of its 1391 // sub-registers to SRegs. 1392 DEBUG(dbgs() << "Initial CS registers: {"); 1393 for (unsigned i = 0, n = CSI.size(); i < n; ++i) { 1394 unsigned R = CSI[i].getReg(); 1395 DEBUG(dbgs() << ' ' << PrintReg(R, TRI)); 1396 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) 1397 SRegs[*SR] = true; 1398 } 1399 DEBUG(dbgs() << " }\n"); 1400 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n"); 1401 1402 // (2) For each reserved register, remove that register and all of its 1403 // sub- and super-registers from SRegs. 1404 BitVector Reserved = TRI->getReservedRegs(MF); 1405 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) { 1406 unsigned R = x; 1407 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR) 1408 SRegs[*SR] = false; 1409 } 1410 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n"); 1411 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n"); 1412 1413 // (3) Collect all registers that have at least one sub-register in SRegs, 1414 // and also have no sub-registers that are reserved. These will be the can- 1415 // didates for saving as a whole instead of their individual sub-registers. 1416 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.) 1417 BitVector TmpSup(Hexagon::NUM_TARGET_REGS); 1418 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) { 1419 unsigned R = x; 1420 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) 1421 TmpSup[*SR] = true; 1422 } 1423 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) { 1424 unsigned R = x; 1425 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) { 1426 if (!Reserved[*SR]) 1427 continue; 1428 TmpSup[R] = false; 1429 break; 1430 } 1431 } 1432 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n"); 1433 1434 // (4) Include all super-registers found in (3) into SRegs. 1435 SRegs |= TmpSup; 1436 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n"); 1437 1438 // (5) For each register R in SRegs, if any super-register of R is in SRegs, 1439 // remove R from SRegs. 1440 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) { 1441 unsigned R = x; 1442 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) { 1443 if (!SRegs[*SR]) 1444 continue; 1445 SRegs[R] = false; 1446 break; 1447 } 1448 } 1449 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n"); 1450 1451 // Now, for each register that has a fixed stack slot, create the stack 1452 // object for it. 1453 CSI.clear(); 1454 1455 typedef TargetFrameLowering::SpillSlot SpillSlot; 1456 unsigned NumFixed; 1457 int MinOffset = 0; // CS offsets are negative. 1458 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed); 1459 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) { 1460 if (!SRegs[S->Reg]) 1461 continue; 1462 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg); 1463 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset); 1464 MinOffset = std::min(MinOffset, S->Offset); 1465 CSI.push_back(CalleeSavedInfo(S->Reg, FI)); 1466 SRegs[S->Reg] = false; 1467 } 1468 1469 // There can be some registers that don't have fixed slots. For example, 1470 // we need to store R0-R3 in functions with exception handling. For each 1471 // such register, create a non-fixed stack object. 1472 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) { 1473 unsigned R = x; 1474 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R); 1475 unsigned Size = TRI->getSpillSize(*RC); 1476 int Off = MinOffset - Size; 1477 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment()); 1478 assert(isPowerOf2_32(Align)); 1479 Off &= -Align; 1480 int FI = MFI.CreateFixedSpillStackObject(Size, Off); 1481 MinOffset = std::min(MinOffset, Off); 1482 CSI.push_back(CalleeSavedInfo(R, FI)); 1483 SRegs[R] = false; 1484 } 1485 1486 DEBUG({ 1487 dbgs() << "CS information: {"; 1488 for (unsigned i = 0, n = CSI.size(); i < n; ++i) { 1489 int FI = CSI[i].getFrameIdx(); 1490 int Off = MFI.getObjectOffset(FI); 1491 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp"; 1492 if (Off >= 0) 1493 dbgs() << '+'; 1494 dbgs() << Off; 1495 } 1496 dbgs() << " }\n"; 1497 }); 1498 1499 #ifndef NDEBUG 1500 // Verify that all registers were handled. 1501 bool MissedReg = false; 1502 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) { 1503 unsigned R = x; 1504 dbgs() << PrintReg(R, TRI) << ' '; 1505 MissedReg = true; 1506 } 1507 if (MissedReg) 1508 llvm_unreachable("...there are unhandled callee-saved registers!"); 1509 #endif 1510 1511 return true; 1512 } 1513 1514 bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B, 1515 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1516 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1517 MachineInstr *MI = &*It; 1518 DebugLoc DL = MI->getDebugLoc(); 1519 unsigned DstR = MI->getOperand(0).getReg(); 1520 unsigned SrcR = MI->getOperand(1).getReg(); 1521 if (!Hexagon::ModRegsRegClass.contains(DstR) || 1522 !Hexagon::ModRegsRegClass.contains(SrcR)) 1523 return false; 1524 1525 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass); 1526 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1)); 1527 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR) 1528 .addReg(TmpR, RegState::Kill); 1529 1530 NewRegs.push_back(TmpR); 1531 B.erase(It); 1532 return true; 1533 } 1534 1535 bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B, 1536 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1537 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1538 MachineInstr *MI = &*It; 1539 if (!MI->getOperand(0).isFI()) 1540 return false; 1541 1542 DebugLoc DL = MI->getDebugLoc(); 1543 unsigned Opc = MI->getOpcode(); 1544 unsigned SrcR = MI->getOperand(2).getReg(); 1545 bool IsKill = MI->getOperand(2).isKill(); 1546 int FI = MI->getOperand(0).getIndex(); 1547 1548 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register 1549 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register 1550 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass); 1551 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr 1552 : Hexagon::A2_tfrcrr; 1553 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR) 1554 .addReg(SrcR, getKillRegState(IsKill)); 1555 1556 // S2_storeri_io FI, 0, TmpR 1557 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io)) 1558 .addFrameIndex(FI) 1559 .addImm(0) 1560 .addReg(TmpR, RegState::Kill) 1561 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1562 1563 NewRegs.push_back(TmpR); 1564 B.erase(It); 1565 return true; 1566 } 1567 1568 bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B, 1569 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1570 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1571 MachineInstr *MI = &*It; 1572 if (!MI->getOperand(1).isFI()) 1573 return false; 1574 1575 DebugLoc DL = MI->getDebugLoc(); 1576 unsigned Opc = MI->getOpcode(); 1577 unsigned DstR = MI->getOperand(0).getReg(); 1578 int FI = MI->getOperand(1).getIndex(); 1579 1580 // TmpR = L2_loadri_io FI, 0 1581 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass); 1582 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR) 1583 .addFrameIndex(FI) 1584 .addImm(0) 1585 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1586 1587 // DstR = C2_tfrrp TmpR if DstR is a predicate register 1588 // DstR = A2_tfrrcr TmpR if DstR is a modifier register 1589 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp 1590 : Hexagon::A2_tfrrcr; 1591 BuildMI(B, It, DL, HII.get(TfrOpc), DstR) 1592 .addReg(TmpR, RegState::Kill); 1593 1594 NewRegs.push_back(TmpR); 1595 B.erase(It); 1596 return true; 1597 } 1598 1599 bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B, 1600 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1601 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1602 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>(); 1603 MachineInstr *MI = &*It; 1604 if (!MI->getOperand(0).isFI()) 1605 return false; 1606 1607 DebugLoc DL = MI->getDebugLoc(); 1608 unsigned SrcR = MI->getOperand(2).getReg(); 1609 bool IsKill = MI->getOperand(2).isKill(); 1610 int FI = MI->getOperand(0).getIndex(); 1611 1612 bool Is128B = HST.useHVXDblOps(); 1613 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass 1614 : &Hexagon::VectorRegs128BRegClass; 1615 1616 // Insert transfer to general vector register. 1617 // TmpR0 = A2_tfrsi 0x01010101 1618 // TmpR1 = V6_vandqrt Qx, TmpR0 1619 // store FI, 0, TmpR1 1620 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass); 1621 unsigned TmpR1 = MRI.createVirtualRegister(RC); 1622 1623 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0) 1624 .addImm(0x01010101); 1625 1626 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B; 1627 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1) 1628 .addReg(SrcR, getKillRegState(IsKill)) 1629 .addReg(TmpR0, RegState::Kill); 1630 1631 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1632 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI); 1633 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs); 1634 1635 NewRegs.push_back(TmpR0); 1636 NewRegs.push_back(TmpR1); 1637 B.erase(It); 1638 return true; 1639 } 1640 1641 bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B, 1642 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1643 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1644 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>(); 1645 MachineInstr *MI = &*It; 1646 if (!MI->getOperand(1).isFI()) 1647 return false; 1648 1649 DebugLoc DL = MI->getDebugLoc(); 1650 unsigned DstR = MI->getOperand(0).getReg(); 1651 int FI = MI->getOperand(1).getIndex(); 1652 1653 bool Is128B = HST.useHVXDblOps(); 1654 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass 1655 : &Hexagon::VectorRegs128BRegClass; 1656 1657 // TmpR0 = A2_tfrsi 0x01010101 1658 // TmpR1 = load FI, 0 1659 // DstR = V6_vandvrt TmpR1, TmpR0 1660 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass); 1661 unsigned TmpR1 = MRI.createVirtualRegister(RC); 1662 1663 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0) 1664 .addImm(0x01010101); 1665 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1666 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI); 1667 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs); 1668 1669 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B; 1670 BuildMI(B, It, DL, HII.get(VandOpc), DstR) 1671 .addReg(TmpR1, RegState::Kill) 1672 .addReg(TmpR0, RegState::Kill); 1673 1674 NewRegs.push_back(TmpR0); 1675 NewRegs.push_back(TmpR1); 1676 B.erase(It); 1677 return true; 1678 } 1679 1680 bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B, 1681 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1682 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1683 MachineFunction &MF = *B.getParent(); 1684 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1685 auto &MFI = MF.getFrameInfo(); 1686 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1687 MachineInstr *MI = &*It; 1688 if (!MI->getOperand(0).isFI()) 1689 return false; 1690 1691 // It is possible that the double vector being stored is only partially 1692 // defined. From the point of view of the liveness tracking, it is ok to 1693 // store it as a whole, but if we break it up we may end up storing a 1694 // register that is entirely undefined. 1695 LivePhysRegs LPR(HRI); 1696 LPR.addLiveIns(B); 1697 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers; 1698 for (auto R = B.begin(); R != It; ++R) { 1699 Clobbers.clear(); 1700 LPR.stepForward(*R, Clobbers); 1701 // Dead defs are recorded in Clobbers, but are not automatically removed 1702 // from the live set. 1703 for (auto &C : Clobbers) 1704 if (C.second->isReg() && C.second->isDead()) 1705 LPR.removeReg(C.first); 1706 } 1707 1708 DebugLoc DL = MI->getDebugLoc(); 1709 unsigned SrcR = MI->getOperand(2).getReg(); 1710 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo); 1711 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi); 1712 bool IsKill = MI->getOperand(2).isKill(); 1713 int FI = MI->getOperand(0).getIndex(); 1714 1715 bool Is128B = HST.useHVXDblOps(); 1716 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass 1717 : Hexagon::VectorRegs128BRegClass; 1718 unsigned Size = HRI.getSpillSize(RC); 1719 unsigned NeedAlign = HRI.getSpillAlignment(RC); 1720 unsigned HasAlign = MFI.getObjectAlignment(FI); 1721 unsigned StoreOpc; 1722 1723 // Store low part. 1724 if (LPR.contains(SrcLo)) { 1725 if (NeedAlign <= HasAlign) 1726 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B; 1727 else 1728 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B; 1729 1730 BuildMI(B, It, DL, HII.get(StoreOpc)) 1731 .addFrameIndex(FI) 1732 .addImm(0) 1733 .addReg(SrcLo, getKillRegState(IsKill)) 1734 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1735 } 1736 1737 // Store high part. 1738 if (LPR.contains(SrcHi)) { 1739 if (NeedAlign <= MinAlign(HasAlign, Size)) 1740 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B; 1741 else 1742 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B; 1743 1744 BuildMI(B, It, DL, HII.get(StoreOpc)) 1745 .addFrameIndex(FI) 1746 .addImm(Size) 1747 .addReg(SrcHi, getKillRegState(IsKill)) 1748 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1749 } 1750 1751 B.erase(It); 1752 return true; 1753 } 1754 1755 bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B, 1756 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1757 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1758 MachineFunction &MF = *B.getParent(); 1759 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1760 auto &MFI = MF.getFrameInfo(); 1761 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1762 MachineInstr *MI = &*It; 1763 if (!MI->getOperand(1).isFI()) 1764 return false; 1765 1766 DebugLoc DL = MI->getDebugLoc(); 1767 unsigned DstR = MI->getOperand(0).getReg(); 1768 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi); 1769 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo); 1770 int FI = MI->getOperand(1).getIndex(); 1771 1772 bool Is128B = HST.useHVXDblOps(); 1773 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass 1774 : Hexagon::VectorRegs128BRegClass; 1775 unsigned Size = HRI.getSpillSize(RC); 1776 unsigned NeedAlign = HRI.getSpillAlignment(RC); 1777 unsigned HasAlign = MFI.getObjectAlignment(FI); 1778 unsigned LoadOpc; 1779 1780 // Load low part. 1781 if (NeedAlign <= HasAlign) 1782 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B; 1783 else 1784 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B; 1785 1786 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo) 1787 .addFrameIndex(FI) 1788 .addImm(0) 1789 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1790 1791 // Load high part. 1792 if (NeedAlign <= MinAlign(HasAlign, Size)) 1793 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B; 1794 else 1795 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B; 1796 1797 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi) 1798 .addFrameIndex(FI) 1799 .addImm(Size) 1800 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1801 1802 B.erase(It); 1803 return true; 1804 } 1805 1806 bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B, 1807 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1808 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1809 MachineFunction &MF = *B.getParent(); 1810 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1811 auto &MFI = MF.getFrameInfo(); 1812 MachineInstr *MI = &*It; 1813 if (!MI->getOperand(0).isFI()) 1814 return false; 1815 1816 auto &HRI = *HST.getRegisterInfo(); 1817 DebugLoc DL = MI->getDebugLoc(); 1818 unsigned SrcR = MI->getOperand(2).getReg(); 1819 bool IsKill = MI->getOperand(2).isKill(); 1820 int FI = MI->getOperand(0).getIndex(); 1821 1822 bool Is128B = HST.useHVXDblOps(); 1823 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass 1824 : Hexagon::VectorRegs128BRegClass; 1825 unsigned NeedAlign = HRI.getSpillAlignment(RC); 1826 unsigned HasAlign = MFI.getObjectAlignment(FI); 1827 unsigned StoreOpc; 1828 1829 if (NeedAlign <= HasAlign) 1830 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B; 1831 else 1832 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B; 1833 1834 BuildMI(B, It, DL, HII.get(StoreOpc)) 1835 .addFrameIndex(FI) 1836 .addImm(0) 1837 .addReg(SrcR, getKillRegState(IsKill)) 1838 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1839 1840 B.erase(It); 1841 return true; 1842 } 1843 1844 bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B, 1845 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, 1846 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const { 1847 MachineFunction &MF = *B.getParent(); 1848 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1849 auto &MFI = MF.getFrameInfo(); 1850 MachineInstr *MI = &*It; 1851 if (!MI->getOperand(1).isFI()) 1852 return false; 1853 1854 auto &HRI = *HST.getRegisterInfo(); 1855 DebugLoc DL = MI->getDebugLoc(); 1856 unsigned DstR = MI->getOperand(0).getReg(); 1857 int FI = MI->getOperand(1).getIndex(); 1858 1859 bool Is128B = HST.useHVXDblOps(); 1860 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass 1861 : Hexagon::VectorRegs128BRegClass; 1862 unsigned NeedAlign = HRI.getSpillAlignment(RC); 1863 unsigned HasAlign = MFI.getObjectAlignment(FI); 1864 unsigned LoadOpc; 1865 1866 if (NeedAlign <= HasAlign) 1867 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B; 1868 else 1869 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B; 1870 1871 BuildMI(B, It, DL, HII.get(LoadOpc), DstR) 1872 .addFrameIndex(FI) 1873 .addImm(0) 1874 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 1875 1876 B.erase(It); 1877 return true; 1878 } 1879 1880 bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF, 1881 SmallVectorImpl<unsigned> &NewRegs) const { 1882 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1883 auto &HII = *HST.getInstrInfo(); 1884 MachineRegisterInfo &MRI = MF.getRegInfo(); 1885 bool Changed = false; 1886 1887 for (auto &B : MF) { 1888 // Traverse the basic block. 1889 MachineBasicBlock::iterator NextI; 1890 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) { 1891 MachineInstr *MI = &*I; 1892 NextI = std::next(I); 1893 unsigned Opc = MI->getOpcode(); 1894 1895 switch (Opc) { 1896 case TargetOpcode::COPY: 1897 Changed |= expandCopy(B, I, MRI, HII, NewRegs); 1898 break; 1899 case Hexagon::STriw_pred: 1900 case Hexagon::STriw_mod: 1901 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs); 1902 break; 1903 case Hexagon::LDriw_pred: 1904 case Hexagon::LDriw_mod: 1905 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs); 1906 break; 1907 case Hexagon::PS_vstorerq_ai: 1908 case Hexagon::PS_vstorerq_ai_128B: 1909 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs); 1910 break; 1911 case Hexagon::PS_vloadrq_ai: 1912 case Hexagon::PS_vloadrq_ai_128B: 1913 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs); 1914 break; 1915 case Hexagon::PS_vloadrw_ai: 1916 case Hexagon::PS_vloadrwu_ai: 1917 case Hexagon::PS_vloadrw_ai_128B: 1918 case Hexagon::PS_vloadrwu_ai_128B: 1919 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs); 1920 break; 1921 case Hexagon::PS_vstorerw_ai: 1922 case Hexagon::PS_vstorerwu_ai: 1923 case Hexagon::PS_vstorerw_ai_128B: 1924 case Hexagon::PS_vstorerwu_ai_128B: 1925 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs); 1926 break; 1927 } 1928 } 1929 } 1930 1931 return Changed; 1932 } 1933 1934 void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF, 1935 BitVector &SavedRegs, 1936 RegScavenger *RS) const { 1937 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 1938 auto &HRI = *HST.getRegisterInfo(); 1939 1940 SavedRegs.resize(HRI.getNumRegs()); 1941 1942 // If we have a function containing __builtin_eh_return we want to spill and 1943 // restore all callee saved registers. Pretend that they are used. 1944 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn()) 1945 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R) 1946 SavedRegs.set(*R); 1947 1948 // Replace predicate register pseudo spill code. 1949 SmallVector<unsigned,8> NewRegs; 1950 expandSpillMacros(MF, NewRegs); 1951 if (OptimizeSpillSlots && !isOptNone(MF)) 1952 optimizeSpillSlots(MF, NewRegs); 1953 1954 // We need to reserve a a spill slot if scavenging could potentially require 1955 // spilling a scavenged register. 1956 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) { 1957 MachineFrameInfo &MFI = MF.getFrameInfo(); 1958 MachineRegisterInfo &MRI = MF.getRegInfo(); 1959 SetVector<const TargetRegisterClass*> SpillRCs; 1960 // Reserve an int register in any case, because it could be used to hold 1961 // the stack offset in case it does not fit into a spill instruction. 1962 SpillRCs.insert(&Hexagon::IntRegsRegClass); 1963 1964 for (unsigned VR : NewRegs) 1965 SpillRCs.insert(MRI.getRegClass(VR)); 1966 1967 for (auto *RC : SpillRCs) { 1968 if (!needToReserveScavengingSpillSlots(MF, HRI, RC)) 1969 continue; 1970 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1; 1971 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC); 1972 for (unsigned i = 0; i < Num; i++) { 1973 int NewFI = MFI.CreateSpillStackObject(S, A); 1974 RS->addScavengingFrameIndex(NewFI); 1975 } 1976 } 1977 } 1978 1979 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 1980 } 1981 1982 unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF, 1983 HexagonBlockRanges::IndexRange &FIR, 1984 HexagonBlockRanges::InstrIndexMap &IndexMap, 1985 HexagonBlockRanges::RegToRangeMap &DeadMap, 1986 const TargetRegisterClass *RC) const { 1987 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 1988 auto &MRI = MF.getRegInfo(); 1989 1990 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool { 1991 auto F = DeadMap.find({Reg,0}); 1992 if (F == DeadMap.end()) 1993 return false; 1994 for (auto &DR : F->second) 1995 if (DR.contains(FIR)) 1996 return true; 1997 return false; 1998 }; 1999 2000 for (unsigned Reg : RC->getRawAllocationOrder(MF)) { 2001 bool Dead = true; 2002 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) { 2003 if (isDead(R.Reg)) 2004 continue; 2005 Dead = false; 2006 break; 2007 } 2008 if (Dead) 2009 return Reg; 2010 } 2011 return 0; 2012 } 2013 2014 void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF, 2015 SmallVectorImpl<unsigned> &VRegs) const { 2016 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 2017 auto &HII = *HST.getInstrInfo(); 2018 auto &HRI = *HST.getRegisterInfo(); 2019 auto &MRI = MF.getRegInfo(); 2020 HexagonBlockRanges HBR(MF); 2021 2022 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap> 2023 BlockIndexMap; 2024 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList> 2025 BlockRangeMap; 2026 typedef HexagonBlockRanges::IndexType IndexType; 2027 2028 struct SlotInfo { 2029 BlockRangeMap Map; 2030 unsigned Size = 0; 2031 const TargetRegisterClass *RC = nullptr; 2032 2033 SlotInfo() = default; 2034 }; 2035 2036 BlockIndexMap BlockIndexes; 2037 SmallSet<int,4> BadFIs; 2038 std::map<int,SlotInfo> FIRangeMap; 2039 2040 // Accumulate register classes: get a common class for a pre-existing 2041 // class HaveRC and a new class NewRC. Return nullptr if a common class 2042 // cannot be found, otherwise return the resulting class. If HaveRC is 2043 // nullptr, assume that it is still unset. 2044 auto getCommonRC = 2045 [](const TargetRegisterClass *HaveRC, 2046 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * { 2047 if (HaveRC == nullptr || HaveRC == NewRC) 2048 return NewRC; 2049 // Different classes, both non-null. Pick the more general one. 2050 if (HaveRC->hasSubClassEq(NewRC)) 2051 return HaveRC; 2052 if (NewRC->hasSubClassEq(HaveRC)) 2053 return NewRC; 2054 return nullptr; 2055 }; 2056 2057 // Scan all blocks in the function. Check all occurrences of frame indexes, 2058 // and collect relevant information. 2059 for (auto &B : MF) { 2060 std::map<int,IndexType> LastStore, LastLoad; 2061 // Emplace appears not to be supported in gcc 4.7.2-4. 2062 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B)); 2063 auto P = BlockIndexes.insert( 2064 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B))); 2065 auto &IndexMap = P.first->second; 2066 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n" 2067 << IndexMap << '\n'); 2068 2069 for (auto &In : B) { 2070 int LFI, SFI; 2071 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In); 2072 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In); 2073 if (Load && Store) { 2074 // If it's both a load and a store, then we won't handle it. 2075 BadFIs.insert(LFI); 2076 BadFIs.insert(SFI); 2077 continue; 2078 } 2079 // Check for register classes of the register used as the source for 2080 // the store, and the register used as the destination for the load. 2081 // Also, only accept base+imm_offset addressing modes. Other addressing 2082 // modes can have side-effects (post-increments, etc.). For stack 2083 // slots they are very unlikely, so there is not much loss due to 2084 // this restriction. 2085 if (Load || Store) { 2086 int TFI = Load ? LFI : SFI; 2087 unsigned AM = HII.getAddrMode(In); 2088 SlotInfo &SI = FIRangeMap[TFI]; 2089 bool Bad = (AM != HexagonII::BaseImmOffset); 2090 if (!Bad) { 2091 // If the addressing mode is ok, check the register class. 2092 unsigned OpNum = Load ? 0 : 2; 2093 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF); 2094 RC = getCommonRC(SI.RC, RC); 2095 if (RC == nullptr) 2096 Bad = true; 2097 else 2098 SI.RC = RC; 2099 } 2100 if (!Bad) { 2101 // Check sizes. 2102 unsigned S = (1U << (HII.getMemAccessSize(In) - 1)); 2103 if (SI.Size != 0 && SI.Size != S) 2104 Bad = true; 2105 else 2106 SI.Size = S; 2107 } 2108 if (!Bad) { 2109 for (auto *Mo : In.memoperands()) { 2110 if (!Mo->isVolatile()) 2111 continue; 2112 Bad = true; 2113 break; 2114 } 2115 } 2116 if (Bad) 2117 BadFIs.insert(TFI); 2118 } 2119 2120 // Locate uses of frame indices. 2121 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) { 2122 const MachineOperand &Op = In.getOperand(i); 2123 if (!Op.isFI()) 2124 continue; 2125 int FI = Op.getIndex(); 2126 // Make sure that the following operand is an immediate and that 2127 // it is 0. This is the offset in the stack object. 2128 if (i+1 >= n || !In.getOperand(i+1).isImm() || 2129 In.getOperand(i+1).getImm() != 0) 2130 BadFIs.insert(FI); 2131 if (BadFIs.count(FI)) 2132 continue; 2133 2134 IndexType Index = IndexMap.getIndex(&In); 2135 if (Load) { 2136 if (LastStore[FI] == IndexType::None) 2137 LastStore[FI] = IndexType::Entry; 2138 LastLoad[FI] = Index; 2139 } else if (Store) { 2140 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B]; 2141 if (LastStore[FI] != IndexType::None) 2142 RL.add(LastStore[FI], LastLoad[FI], false, false); 2143 else if (LastLoad[FI] != IndexType::None) 2144 RL.add(IndexType::Entry, LastLoad[FI], false, false); 2145 LastLoad[FI] = IndexType::None; 2146 LastStore[FI] = Index; 2147 } else { 2148 BadFIs.insert(FI); 2149 } 2150 } 2151 } 2152 2153 for (auto &I : LastLoad) { 2154 IndexType LL = I.second; 2155 if (LL == IndexType::None) 2156 continue; 2157 auto &RL = FIRangeMap[I.first].Map[&B]; 2158 IndexType &LS = LastStore[I.first]; 2159 if (LS != IndexType::None) 2160 RL.add(LS, LL, false, false); 2161 else 2162 RL.add(IndexType::Entry, LL, false, false); 2163 LS = IndexType::None; 2164 } 2165 for (auto &I : LastStore) { 2166 IndexType LS = I.second; 2167 if (LS == IndexType::None) 2168 continue; 2169 auto &RL = FIRangeMap[I.first].Map[&B]; 2170 RL.add(LS, IndexType::None, false, false); 2171 } 2172 } 2173 2174 DEBUG({ 2175 for (auto &P : FIRangeMap) { 2176 dbgs() << "fi#" << P.first; 2177 if (BadFIs.count(P.first)) 2178 dbgs() << " (bad)"; 2179 dbgs() << " RC: "; 2180 if (P.second.RC != nullptr) 2181 dbgs() << HRI.getRegClassName(P.second.RC) << '\n'; 2182 else 2183 dbgs() << "<null>\n"; 2184 for (auto &R : P.second.Map) 2185 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n"; 2186 } 2187 }); 2188 2189 // When a slot is loaded from in a block without being stored to in the 2190 // same block, it is live-on-entry to this block. To avoid CFG analysis, 2191 // consider this slot to be live-on-exit from all blocks. 2192 SmallSet<int,4> LoxFIs; 2193 2194 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap; 2195 2196 for (auto &P : FIRangeMap) { 2197 // P = pair(FI, map: BB->RangeList) 2198 if (BadFIs.count(P.first)) 2199 continue; 2200 for (auto &B : MF) { 2201 auto F = P.second.Map.find(&B); 2202 // F = pair(BB, RangeList) 2203 if (F == P.second.Map.end() || F->second.empty()) 2204 continue; 2205 HexagonBlockRanges::IndexRange &IR = F->second.front(); 2206 if (IR.start() == IndexType::Entry) 2207 LoxFIs.insert(P.first); 2208 BlockFIMap[&B].push_back(P.first); 2209 } 2210 } 2211 2212 DEBUG({ 2213 dbgs() << "Block-to-FI map (* -- live-on-exit):\n"; 2214 for (auto &P : BlockFIMap) { 2215 auto &FIs = P.second; 2216 if (FIs.empty()) 2217 continue; 2218 dbgs() << " BB#" << P.first->getNumber() << ": {"; 2219 for (auto I : FIs) { 2220 dbgs() << " fi#" << I; 2221 if (LoxFIs.count(I)) 2222 dbgs() << '*'; 2223 } 2224 dbgs() << " }\n"; 2225 } 2226 }); 2227 2228 #ifndef NDEBUG 2229 bool HasOptLimit = SpillOptMax.getPosition(); 2230 #endif 2231 2232 // eliminate loads, when all loads eliminated, eliminate all stores. 2233 for (auto &B : MF) { 2234 auto F = BlockIndexes.find(&B); 2235 assert(F != BlockIndexes.end()); 2236 HexagonBlockRanges::InstrIndexMap &IM = F->second; 2237 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM); 2238 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM); 2239 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n" 2240 << HexagonBlockRanges::PrintRangeMap(DM, HRI)); 2241 2242 for (auto FI : BlockFIMap[&B]) { 2243 if (BadFIs.count(FI)) 2244 continue; 2245 DEBUG(dbgs() << "Working on fi#" << FI << '\n'); 2246 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B]; 2247 for (auto &Range : RL) { 2248 DEBUG(dbgs() << "--Examining range:" << RL << '\n'); 2249 if (!IndexType::isInstr(Range.start()) || 2250 !IndexType::isInstr(Range.end())) 2251 continue; 2252 MachineInstr &SI = *IM.getInstr(Range.start()); 2253 MachineInstr &EI = *IM.getInstr(Range.end()); 2254 assert(SI.mayStore() && "Unexpected start instruction"); 2255 assert(EI.mayLoad() && "Unexpected end instruction"); 2256 MachineOperand &SrcOp = SI.getOperand(2); 2257 2258 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(), 2259 SrcOp.getSubReg() }; 2260 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF); 2261 // The this-> is needed to unconfuse MSVC. 2262 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC); 2263 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n'); 2264 if (FoundR == 0) 2265 continue; 2266 #ifndef NDEBUG 2267 if (HasOptLimit) { 2268 if (SpillOptCount >= SpillOptMax) 2269 return; 2270 SpillOptCount++; 2271 } 2272 #endif 2273 2274 // Generate the copy-in: "FoundR = COPY SrcR" at the store location. 2275 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt; 2276 MachineInstr *CopyIn = nullptr; 2277 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) { 2278 const DebugLoc &DL = SI.getDebugLoc(); 2279 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR) 2280 .add(SrcOp); 2281 } 2282 2283 ++StartIt; 2284 // Check if this is a last store and the FI is live-on-exit. 2285 if (LoxFIs.count(FI) && (&Range == &RL.back())) { 2286 // Update store's source register. 2287 if (unsigned SR = SrcOp.getSubReg()) 2288 SrcOp.setReg(HRI.getSubReg(FoundR, SR)); 2289 else 2290 SrcOp.setReg(FoundR); 2291 SrcOp.setSubReg(0); 2292 // We are keeping this register live. 2293 SrcOp.setIsKill(false); 2294 } else { 2295 B.erase(&SI); 2296 IM.replaceInstr(&SI, CopyIn); 2297 } 2298 2299 auto EndIt = std::next(EI.getIterator()); 2300 for (auto It = StartIt; It != EndIt; It = NextIt) { 2301 MachineInstr &MI = *It; 2302 NextIt = std::next(It); 2303 int TFI; 2304 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI) 2305 continue; 2306 unsigned DstR = MI.getOperand(0).getReg(); 2307 assert(MI.getOperand(0).getSubReg() == 0); 2308 MachineInstr *CopyOut = nullptr; 2309 if (DstR != FoundR) { 2310 DebugLoc DL = MI.getDebugLoc(); 2311 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1)); 2312 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset); 2313 unsigned CopyOpc = TargetOpcode::COPY; 2314 if (HII.isSignExtendingLoad(MI)) 2315 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth; 2316 else if (HII.isZeroExtendingLoad(MI)) 2317 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth; 2318 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR) 2319 .addReg(FoundR, getKillRegState(&MI == &EI)); 2320 } 2321 IM.replaceInstr(&MI, CopyOut); 2322 B.erase(It); 2323 } 2324 2325 // Update the dead map. 2326 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 }; 2327 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI)) 2328 DM[RR].subtract(Range); 2329 } // for Range in range list 2330 } 2331 } 2332 } 2333 2334 void HexagonFrameLowering::expandAlloca(MachineInstr *AI, 2335 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const { 2336 MachineBasicBlock &MB = *AI->getParent(); 2337 DebugLoc DL = AI->getDebugLoc(); 2338 unsigned A = AI->getOperand(2).getImm(); 2339 2340 // Have 2341 // Rd = alloca Rs, #A 2342 // 2343 // If Rs and Rd are different registers, use this sequence: 2344 // Rd = sub(r29, Rs) 2345 // r29 = sub(r29, Rs) 2346 // Rd = and(Rd, #-A) ; if necessary 2347 // r29 = and(r29, #-A) ; if necessary 2348 // Rd = add(Rd, #CF) ; CF size aligned to at most A 2349 // otherwise, do 2350 // Rd = sub(r29, Rs) 2351 // Rd = and(Rd, #-A) ; if necessary 2352 // r29 = Rd 2353 // Rd = add(Rd, #CF) ; CF size aligned to at most A 2354 2355 MachineOperand &RdOp = AI->getOperand(0); 2356 MachineOperand &RsOp = AI->getOperand(1); 2357 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg(); 2358 2359 // Rd = sub(r29, Rs) 2360 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd) 2361 .addReg(SP) 2362 .addReg(Rs); 2363 if (Rs != Rd) { 2364 // r29 = sub(r29, Rs) 2365 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP) 2366 .addReg(SP) 2367 .addReg(Rs); 2368 } 2369 if (A > 8) { 2370 // Rd = and(Rd, #-A) 2371 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd) 2372 .addReg(Rd) 2373 .addImm(-int64_t(A)); 2374 if (Rs != Rd) 2375 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP) 2376 .addReg(SP) 2377 .addImm(-int64_t(A)); 2378 } 2379 if (Rs == Rd) { 2380 // r29 = Rd 2381 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP) 2382 .addReg(Rd); 2383 } 2384 if (CF > 0) { 2385 // Rd = add(Rd, #CF) 2386 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd) 2387 .addReg(Rd) 2388 .addImm(CF); 2389 } 2390 } 2391 2392 bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const { 2393 const MachineFrameInfo &MFI = MF.getFrameInfo(); 2394 if (!MFI.hasVarSizedObjects()) 2395 return false; 2396 unsigned MaxA = MFI.getMaxAlignment(); 2397 if (MaxA <= getStackAlignment()) 2398 return false; 2399 return true; 2400 } 2401 2402 const MachineInstr *HexagonFrameLowering::getAlignaInstr( 2403 const MachineFunction &MF) const { 2404 for (auto &B : MF) 2405 for (auto &I : B) 2406 if (I.getOpcode() == Hexagon::PS_aligna) 2407 return &I; 2408 return nullptr; 2409 } 2410 2411 /// Adds all callee-saved registers as implicit uses or defs to the 2412 /// instruction. 2413 void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI, 2414 const CSIVect &CSI, bool IsDef, bool IsKill) const { 2415 // Add the callee-saved registers as implicit uses. 2416 for (auto &R : CSI) 2417 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill)); 2418 } 2419 2420 /// Determine whether the callee-saved register saves and restores should 2421 /// be generated via inline code. If this function returns "true", inline 2422 /// code will be generated. If this function returns "false", additional 2423 /// checks are performed, which may still lead to the inline code. 2424 bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF, 2425 const CSIVect &CSI) const { 2426 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn()) 2427 return true; 2428 if (!hasFP(MF)) 2429 return true; 2430 if (!isOptSize(MF) && !isMinSize(MF)) 2431 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default) 2432 return true; 2433 2434 // Check if CSI only has double registers, and if the registers form 2435 // a contiguous block starting from D8. 2436 BitVector Regs(Hexagon::NUM_TARGET_REGS); 2437 for (unsigned i = 0, n = CSI.size(); i < n; ++i) { 2438 unsigned R = CSI[i].getReg(); 2439 if (!Hexagon::DoubleRegsRegClass.contains(R)) 2440 return true; 2441 Regs[R] = true; 2442 } 2443 int F = Regs.find_first(); 2444 if (F != Hexagon::D8) 2445 return true; 2446 while (F >= 0) { 2447 int N = Regs.find_next(F); 2448 if (N >= 0 && N != F+1) 2449 return true; 2450 F = N; 2451 } 2452 2453 return false; 2454 } 2455 2456 bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF, 2457 const CSIVect &CSI) const { 2458 if (shouldInlineCSR(MF, CSI)) 2459 return false; 2460 unsigned NumCSI = CSI.size(); 2461 if (NumCSI <= 1) 2462 return false; 2463 2464 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs 2465 : SpillFuncThreshold; 2466 return Threshold < NumCSI; 2467 } 2468 2469 bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF, 2470 const CSIVect &CSI) const { 2471 if (shouldInlineCSR(MF, CSI)) 2472 return false; 2473 // The restore functions do a bit more than just restoring registers. 2474 // The non-returning versions will go back directly to the caller's 2475 // caller, others will clean up the stack frame in preparation for 2476 // a tail call. Using them can still save code size even if only one 2477 // register is getting restores. Make the decision based on -Oz: 2478 // using -Os will use inline restore for a single register. 2479 if (isMinSize(MF)) 2480 return true; 2481 unsigned NumCSI = CSI.size(); 2482 if (NumCSI <= 1) 2483 return false; 2484 2485 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1 2486 : SpillFuncThreshold; 2487 return Threshold < NumCSI; 2488 } 2489 2490 bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const { 2491 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF); 2492 auto &HST = MF.getSubtarget<HexagonSubtarget>(); 2493 // A fairly simplistic guess as to whether a potential load/store to a 2494 // stack location could require an extra register. 2495 if (HST.useHVXOps() && StackSize > 256) 2496 return true; 2497 2498 // Check if the function has store-immediate instructions that access 2499 // the stack. Since the offset field is not extendable, if the stack 2500 // size exceeds the offset limit (6 bits, shifted), the stores will 2501 // require a new base register. 2502 bool HasImmStack = false; 2503 unsigned MinLS = ~0u; // Log_2 of the memory access size. 2504 2505 for (const MachineBasicBlock &B : MF) { 2506 for (const MachineInstr &MI : B) { 2507 unsigned LS = 0; 2508 switch (MI.getOpcode()) { 2509 case Hexagon::S4_storeirit_io: 2510 case Hexagon::S4_storeirif_io: 2511 case Hexagon::S4_storeiri_io: 2512 ++LS; 2513 LLVM_FALLTHROUGH; 2514 case Hexagon::S4_storeirht_io: 2515 case Hexagon::S4_storeirhf_io: 2516 case Hexagon::S4_storeirh_io: 2517 ++LS; 2518 LLVM_FALLTHROUGH; 2519 case Hexagon::S4_storeirbt_io: 2520 case Hexagon::S4_storeirbf_io: 2521 case Hexagon::S4_storeirb_io: 2522 if (MI.getOperand(0).isFI()) 2523 HasImmStack = true; 2524 MinLS = std::min(MinLS, LS); 2525 break; 2526 } 2527 } 2528 } 2529 2530 if (HasImmStack) 2531 return !isUInt<6>(StackSize >> MinLS); 2532 2533 return false; 2534 } 2535