1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===// 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 // This file contains the ARM implementation of TargetFrameLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ARMFrameLowering.h" 15 #include "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMConstantPoolValue.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "MCTargetDesc/ARMAddressingModes.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/RegisterScavenging.h" 26 #include "llvm/IR/CallingConv.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Target/TargetOptions.h" 31 32 using namespace llvm; 33 34 static cl::opt<bool> 35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), 36 cl::desc("Align ARM NEON spills in prolog and epilog")); 37 38 static MachineBasicBlock::iterator 39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 40 unsigned NumAlignedDPRCS2Regs); 41 42 /// hasFP - Return true if the specified function should have a dedicated frame 43 /// pointer register. This is true if the function has variable sized allocas 44 /// or if frame pointer elimination is disabled. 45 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const { 46 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 47 48 // iOS requires FP not to be clobbered for backtracing purpose. 49 if (STI.isTargetIOS()) 50 return true; 51 52 const MachineFrameInfo *MFI = MF.getFrameInfo(); 53 // Always eliminate non-leaf frame pointers. 54 return ((MF.getTarget().Options.DisableFramePointerElim(MF) && 55 MFI->hasCalls()) || 56 RegInfo->needsStackRealignment(MF) || 57 MFI->hasVarSizedObjects() || 58 MFI->isFrameAddressTaken()); 59 } 60 61 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 62 /// not required, we reserve argument space for call sites in the function 63 /// immediately on entry to the current function. This eliminates the need for 64 /// add/sub sp brackets around call sites. Returns true if the call frame is 65 /// included as part of the stack frame. 66 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 67 const MachineFrameInfo *FFI = MF.getFrameInfo(); 68 unsigned CFSize = FFI->getMaxCallFrameSize(); 69 // It's not always a good idea to include the call frame as part of the 70 // stack frame. ARM (especially Thumb) has small immediate offset to 71 // address the stack frame. So a large call frame can cause poor codegen 72 // and may even makes it impossible to scavenge a register. 73 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 74 return false; 75 76 return !MF.getFrameInfo()->hasVarSizedObjects(); 77 } 78 79 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 80 /// call frame pseudos can be simplified. Unlike most targets, having a FP 81 /// is not sufficient here since we still may reference some objects via SP 82 /// even when FP is available in Thumb2 mode. 83 bool 84 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 85 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects(); 86 } 87 88 static bool isCSRestore(MachineInstr *MI, 89 const ARMBaseInstrInfo &TII, 90 const uint16_t *CSRegs) { 91 // Integer spill area is handled with "pop". 92 if (isPopOpcode(MI->getOpcode())) { 93 // The first two operands are predicates. The last two are 94 // imp-def and imp-use of SP. Check everything in between. 95 for (int i = 5, e = MI->getNumOperands(); i != e; ++i) 96 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs)) 97 return false; 98 return true; 99 } 100 if ((MI->getOpcode() == ARM::LDR_POST_IMM || 101 MI->getOpcode() == ARM::LDR_POST_REG || 102 MI->getOpcode() == ARM::t2LDR_POST) && 103 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) && 104 MI->getOperand(1).getReg() == ARM::SP) 105 return true; 106 107 return false; 108 } 109 110 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB, 111 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 112 const ARMBaseInstrInfo &TII, unsigned DestReg, 113 unsigned SrcReg, int NumBytes, 114 unsigned MIFlags = MachineInstr::NoFlags, 115 ARMCC::CondCodes Pred = ARMCC::AL, 116 unsigned PredReg = 0) { 117 if (isARM) 118 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 119 Pred, PredReg, TII, MIFlags); 120 else 121 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 122 Pred, PredReg, TII, MIFlags); 123 } 124 125 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, 126 MachineBasicBlock::iterator &MBBI, DebugLoc dl, 127 const ARMBaseInstrInfo &TII, int NumBytes, 128 unsigned MIFlags = MachineInstr::NoFlags, 129 ARMCC::CondCodes Pred = ARMCC::AL, 130 unsigned PredReg = 0) { 131 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes, 132 MIFlags, Pred, PredReg); 133 } 134 135 static int sizeOfSPAdjustment(const MachineInstr *MI) { 136 assert(MI->getOpcode() == ARM::VSTMDDB_UPD); 137 int count = 0; 138 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 139 // pred) so the list starts at 4. 140 for (int i = MI->getNumOperands() - 1; i >= 4; --i) 141 count += 8; 142 return count; 143 } 144 145 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const { 146 MachineBasicBlock &MBB = MF.front(); 147 MachineBasicBlock::iterator MBBI = MBB.begin(); 148 MachineFrameInfo *MFI = MF.getFrameInfo(); 149 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 150 MachineModuleInfo &MMI = MF.getMMI(); 151 MCContext &Context = MMI.getContext(); 152 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 153 const ARMBaseRegisterInfo *RegInfo = 154 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 155 const ARMBaseInstrInfo &TII = 156 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 157 assert(!AFI->isThumb1OnlyFunction() && 158 "This emitPrologue does not support Thumb1!"); 159 bool isARM = !AFI->isThumbFunction(); 160 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment(); 161 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 162 unsigned NumBytes = MFI->getStackSize(); 163 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 164 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 165 unsigned FramePtr = RegInfo->getFrameRegister(MF); 166 int CFAOffset = 0; 167 168 // Determine the sizes of each callee-save spill areas and record which frame 169 // belongs to which callee-save spill areas. 170 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 171 int FramePtrSpillFI = 0; 172 int D8SpillFI = 0; 173 174 // All calls are tail calls in GHC calling conv, and functions have no 175 // prologue/epilogue. 176 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 177 return; 178 179 // Allocate the vararg register save area. 180 if (ArgRegsSaveSize) { 181 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize, 182 MachineInstr::FrameSetup); 183 CFAOffset -= ArgRegsSaveSize; 184 unsigned CFIIndex = MMI.addFrameInst( 185 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 186 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 187 .addCFIIndex(CFIIndex); 188 } 189 190 if (!AFI->hasStackFrame()) { 191 if (NumBytes - ArgRegsSaveSize != 0) { 192 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize), 193 MachineInstr::FrameSetup); 194 CFAOffset -= NumBytes - ArgRegsSaveSize; 195 unsigned CFIIndex = MMI.addFrameInst( 196 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 197 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 198 .addCFIIndex(CFIIndex); 199 } 200 return; 201 } 202 203 // Determine spill area sizes. 204 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 205 unsigned Reg = CSI[i].getReg(); 206 int FI = CSI[i].getFrameIdx(); 207 switch (Reg) { 208 case ARM::R8: 209 case ARM::R9: 210 case ARM::R10: 211 case ARM::R11: 212 case ARM::R12: 213 if (STI.isTargetMachO()) { 214 GPRCS2Size += 4; 215 break; 216 } 217 // fallthrough 218 case ARM::R0: 219 case ARM::R1: 220 case ARM::R2: 221 case ARM::R3: 222 case ARM::R4: 223 case ARM::R5: 224 case ARM::R6: 225 case ARM::R7: 226 case ARM::LR: 227 if (Reg == FramePtr) 228 FramePtrSpillFI = FI; 229 GPRCS1Size += 4; 230 break; 231 default: 232 // This is a DPR. Exclude the aligned DPRCS2 spills. 233 if (Reg == ARM::D8) 234 D8SpillFI = FI; 235 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) 236 DPRCSSize += 8; 237 } 238 } 239 240 // Move past area 1. 241 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push, 242 DPRCSPush; 243 if (GPRCS1Size > 0) 244 GPRCS1Push = LastPush = MBBI++; 245 246 // Determine starting offsets of spill areas. 247 bool HasFP = hasFP(MF); 248 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size 249 + GPRCS2Size + DPRCSSize); 250 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize; 251 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size; 252 int FramePtrOffsetInPush = 0; 253 if (HasFP) { 254 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI) 255 + GPRCS1Size + ArgRegsSaveSize; 256 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + 257 NumBytes); 258 } 259 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 260 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 261 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 262 263 // Move past area 2. 264 if (GPRCS2Size > 0) 265 GPRCS2Push = LastPush = MBBI++; 266 267 // Move past area 3. 268 if (DPRCSSize > 0) { 269 DPRCSPush = MBBI; 270 // Since vpush register list cannot have gaps, there may be multiple vpush 271 // instructions in the prologue. 272 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) 273 LastPush = MBBI++; 274 } 275 276 // Move past the aligned DPRCS2 area. 277 if (AFI->getNumAlignedDPRCS2Regs() > 0) { 278 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs()); 279 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and 280 // leaves the stack pointer pointing to the DPRCS2 area. 281 // 282 // Adjust NumBytes to represent the stack slots below the DPRCS2 area. 283 NumBytes += MFI->getObjectOffset(D8SpillFI); 284 } else 285 NumBytes = DPRCSOffset; 286 287 unsigned adjustedGPRCS1Size = GPRCS1Size; 288 if (NumBytes) { 289 // Adjust SP after all the callee-save spills. 290 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) { 291 if (LastPush == GPRCS1Push) { 292 FramePtrOffsetInPush += NumBytes; 293 adjustedGPRCS1Size += NumBytes; 294 NumBytes = 0; 295 } 296 } else 297 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 298 MachineInstr::FrameSetup); 299 300 if (HasFP && isARM) 301 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 302 // Note it's not safe to do this in Thumb2 mode because it would have 303 // taken two instructions: 304 // mov sp, r7 305 // sub sp, #24 306 // If an interrupt is taken between the two instructions, then sp is in 307 // an inconsistent state (pointing to the middle of callee-saved area). 308 // The interrupt handler can end up clobbering the registers. 309 AFI->setShouldRestoreSPFromFP(true); 310 } 311 312 if (adjustedGPRCS1Size > 0) { 313 CFAOffset -= adjustedGPRCS1Size; 314 unsigned CFIIndex = MMI.addFrameInst( 315 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 316 MachineBasicBlock::iterator Pos = ++GPRCS1Push; 317 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 318 .addCFIIndex(CFIIndex); 319 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(), 320 E = CSI.end(); I != E; ++I) { 321 unsigned Reg = I->getReg(); 322 int FI = I->getFrameIdx(); 323 switch (Reg) { 324 case ARM::R8: 325 case ARM::R9: 326 case ARM::R10: 327 case ARM::R11: 328 case ARM::R12: 329 if (STI.isTargetMachO()) 330 break; 331 // fallthrough 332 case ARM::R0: 333 case ARM::R1: 334 case ARM::R2: 335 case ARM::R3: 336 case ARM::R4: 337 case ARM::R5: 338 case ARM::R6: 339 case ARM::R7: 340 case ARM::LR: 341 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 342 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI))); 343 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 344 .addCFIIndex(CFIIndex); 345 break; 346 } 347 } 348 } 349 350 // Set FP to point to the stack slot that contains the previous FP. 351 // For iOS, FP is R7, which has now been stored in spill area 1. 352 // Otherwise, if this is not iOS, all the callee-saved registers go 353 // into spill area 1, including the FP in R11. In either case, it 354 // is in area one and the adjustment needs to take place just after 355 // that push. 356 if (HasFP) { 357 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII, 358 FramePtr, ARM::SP, FramePtrOffsetInPush, 359 MachineInstr::FrameSetup); 360 if (FramePtrOffsetInPush) { 361 CFAOffset += FramePtrOffsetInPush; 362 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa( 363 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset)); 364 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 365 .addCFIIndex(CFIIndex); 366 367 } else { 368 unsigned CFIIndex = 369 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister( 370 nullptr, MRI->getDwarfRegNum(FramePtr, true))); 371 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 372 .addCFIIndex(CFIIndex); 373 } 374 } 375 376 if (GPRCS2Size > 0) { 377 MachineBasicBlock::iterator Pos = ++GPRCS2Push; 378 if (!HasFP) { 379 CFAOffset -= GPRCS2Size; 380 unsigned CFIIndex = MMI.addFrameInst( 381 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 382 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 383 .addCFIIndex(CFIIndex); 384 } 385 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(), 386 E = CSI.end(); I != E; ++I) { 387 unsigned Reg = I->getReg(); 388 int FI = I->getFrameIdx(); 389 switch (Reg) { 390 case ARM::R8: 391 case ARM::R9: 392 case ARM::R10: 393 case ARM::R11: 394 case ARM::R12: 395 if (STI.isTargetMachO()) { 396 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 397 unsigned Offset = MFI->getObjectOffset(FI); 398 unsigned CFIIndex = MMI.addFrameInst( 399 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 400 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 401 .addCFIIndex(CFIIndex); 402 } 403 break; 404 } 405 } 406 } 407 408 if (DPRCSSize > 0) { 409 // Since vpush register list cannot have gaps, there may be multiple vpush 410 // instructions in the prologue. 411 do { 412 MachineBasicBlock::iterator Push = DPRCSPush++; 413 if (!HasFP) { 414 CFAOffset -= sizeOfSPAdjustment(Push);; 415 unsigned CFIIndex = MMI.addFrameInst( 416 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 417 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 418 .addCFIIndex(CFIIndex); 419 } 420 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD); 421 422 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(), 423 E = CSI.end(); I != E; ++I) { 424 unsigned Reg = I->getReg(); 425 int FI = I->getFrameIdx(); 426 if ((Reg >= ARM::D0 && Reg <= ARM::D31) && 427 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) { 428 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 429 unsigned Offset = MFI->getObjectOffset(FI); 430 unsigned CFIIndex = MMI.addFrameInst( 431 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 432 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 433 .addCFIIndex(CFIIndex); 434 } 435 } 436 } 437 438 if (NumBytes) { 439 if (!HasFP) { 440 CFAOffset -= NumBytes; 441 unsigned CFIIndex = MMI.addFrameInst( 442 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset)); 443 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 444 .addCFIIndex(CFIIndex); 445 } 446 } 447 448 if (STI.isTargetELF() && hasFP(MF)) 449 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() - 450 AFI->getFramePtrSpillOffset()); 451 452 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 453 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 454 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 455 456 // If we need dynamic stack realignment, do it here. Be paranoid and make 457 // sure if we also have VLAs, we have a base pointer for frame access. 458 // If aligned NEON registers were spilled, the stack has already been 459 // realigned. 460 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) { 461 unsigned MaxAlign = MFI->getMaxAlignment(); 462 assert (!AFI->isThumb1OnlyFunction()); 463 if (!AFI->isThumbFunction()) { 464 // Emit bic sp, sp, MaxAlign 465 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 466 TII.get(ARM::BICri), ARM::SP) 467 .addReg(ARM::SP, RegState::Kill) 468 .addImm(MaxAlign-1))); 469 } else { 470 // We cannot use sp as source/dest register here, thus we're emitting the 471 // following sequence: 472 // mov r4, sp 473 // bic r4, r4, MaxAlign 474 // mov sp, r4 475 // FIXME: It will be better just to find spare register here. 476 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4) 477 .addReg(ARM::SP, RegState::Kill)); 478 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, 479 TII.get(ARM::t2BICri), ARM::R4) 480 .addReg(ARM::R4, RegState::Kill) 481 .addImm(MaxAlign-1))); 482 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 483 .addReg(ARM::R4, RegState::Kill)); 484 } 485 486 AFI->setShouldRestoreSPFromFP(true); 487 } 488 489 // If we need a base pointer, set it up here. It's whatever the value 490 // of the stack pointer is at this point. Any variable size objects 491 // will be allocated after this, so we can still use the base pointer 492 // to reference locals. 493 // FIXME: Clarify FrameSetup flags here. 494 if (RegInfo->hasBasePointer(MF)) { 495 if (isARM) 496 BuildMI(MBB, MBBI, dl, 497 TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 498 .addReg(ARM::SP) 499 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 500 else 501 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 502 RegInfo->getBaseRegister()) 503 .addReg(ARM::SP)); 504 } 505 506 // If the frame has variable sized objects then the epilogue must restore 507 // the sp from fp. We can assume there's an FP here since hasFP already 508 // checks for hasVarSizedObjects. 509 if (MFI->hasVarSizedObjects()) 510 AFI->setShouldRestoreSPFromFP(true); 511 } 512 513 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 514 MachineBasicBlock &MBB) const { 515 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 516 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks"); 517 unsigned RetOpcode = MBBI->getOpcode(); 518 DebugLoc dl = MBBI->getDebugLoc(); 519 MachineFrameInfo *MFI = MF.getFrameInfo(); 520 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 521 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); 522 const ARMBaseInstrInfo &TII = 523 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 524 assert(!AFI->isThumb1OnlyFunction() && 525 "This emitEpilogue does not support Thumb1!"); 526 bool isARM = !AFI->isThumbFunction(); 527 528 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment(); 529 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align); 530 int NumBytes = (int)MFI->getStackSize(); 531 unsigned FramePtr = RegInfo->getFrameRegister(MF); 532 533 // All calls are tail calls in GHC calling conv, and functions have no 534 // prologue/epilogue. 535 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 536 return; 537 538 if (!AFI->hasStackFrame()) { 539 if (NumBytes - ArgRegsSaveSize != 0) 540 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize); 541 } else { 542 // Unwind MBBI to point to first LDR / VLDRD. 543 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 544 if (MBBI != MBB.begin()) { 545 do { 546 --MBBI; 547 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs)); 548 if (!isCSRestore(MBBI, TII, CSRegs)) 549 ++MBBI; 550 } 551 552 // Move SP to start of FP callee save spill area. 553 NumBytes -= (ArgRegsSaveSize + 554 AFI->getGPRCalleeSavedArea1Size() + 555 AFI->getGPRCalleeSavedArea2Size() + 556 AFI->getDPRCalleeSavedAreaSize()); 557 558 // Reset SP based on frame pointer only if the stack frame extends beyond 559 // frame pointer stack slot or target is ELF and the function has FP. 560 if (AFI->shouldRestoreSPFromFP()) { 561 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 562 if (NumBytes) { 563 if (isARM) 564 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 565 ARMCC::AL, 0, TII); 566 else { 567 // It's not possible to restore SP from FP in a single instruction. 568 // For iOS, this looks like: 569 // mov sp, r7 570 // sub sp, #24 571 // This is bad, if an interrupt is taken after the mov, sp is in an 572 // inconsistent state. 573 // Use the first callee-saved register as a scratch register. 574 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) && 575 "No scratch register to restore SP from FP!"); 576 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 577 ARMCC::AL, 0, TII); 578 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 579 ARM::SP) 580 .addReg(ARM::R4)); 581 } 582 } else { 583 // Thumb2 or ARM. 584 if (isARM) 585 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 586 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 587 else 588 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), 589 ARM::SP) 590 .addReg(FramePtr)); 591 } 592 } else if (NumBytes && 593 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes)) 594 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes); 595 596 // Increment past our save areas. 597 if (AFI->getDPRCalleeSavedAreaSize()) { 598 MBBI++; 599 // Since vpop register list cannot have gaps, there may be multiple vpop 600 // instructions in the epilogue. 601 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD) 602 MBBI++; 603 } 604 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++; 605 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 606 } 607 608 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) { 609 // Tail call return: adjust the stack pointer and jump to callee. 610 MBBI = MBB.getLastNonDebugInstr(); 611 MachineOperand &JumpTarget = MBBI->getOperand(0); 612 613 // Jump to label or value in register. 614 if (RetOpcode == ARM::TCRETURNdi) { 615 unsigned TCOpcode = STI.isThumb() ? 616 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) : 617 ARM::TAILJMPd; 618 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode)); 619 if (JumpTarget.isGlobal()) 620 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(), 621 JumpTarget.getTargetFlags()); 622 else { 623 assert(JumpTarget.isSymbol()); 624 MIB.addExternalSymbol(JumpTarget.getSymbolName(), 625 JumpTarget.getTargetFlags()); 626 } 627 628 // Add the default predicate in Thumb mode. 629 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0); 630 } else if (RetOpcode == ARM::TCRETURNri) { 631 BuildMI(MBB, MBBI, dl, 632 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)). 633 addReg(JumpTarget.getReg(), RegState::Kill); 634 } 635 636 MachineInstr *NewMI = std::prev(MBBI); 637 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i) 638 NewMI->addOperand(MBBI->getOperand(i)); 639 640 // Delete the pseudo instruction TCRETURN. 641 MBB.erase(MBBI); 642 MBBI = NewMI; 643 } 644 645 if (ArgRegsSaveSize) 646 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize); 647 } 648 649 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 650 /// debug info. It's the same as what we use for resolving the code-gen 651 /// references for now. FIXME: This can go wrong when references are 652 /// SP-relative and simple call frames aren't used. 653 int 654 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 655 unsigned &FrameReg) const { 656 return ResolveFrameIndexReference(MF, FI, FrameReg, 0); 657 } 658 659 int 660 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 661 int FI, unsigned &FrameReg, 662 int SPAdj) const { 663 const MachineFrameInfo *MFI = MF.getFrameInfo(); 664 const ARMBaseRegisterInfo *RegInfo = 665 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 666 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 667 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize(); 668 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 669 bool isFixed = MFI->isFixedObjectIndex(FI); 670 671 FrameReg = ARM::SP; 672 Offset += SPAdj; 673 674 // SP can move around if there are allocas. We may also lose track of SP 675 // when emergency spilling inside a non-reserved call frame setup. 676 bool hasMovingSP = !hasReservedCallFrame(MF); 677 678 // When dynamically realigning the stack, use the frame pointer for 679 // parameters, and the stack/base pointer for locals. 680 if (RegInfo->needsStackRealignment(MF)) { 681 assert (hasFP(MF) && "dynamic stack realignment without a FP!"); 682 if (isFixed) { 683 FrameReg = RegInfo->getFrameRegister(MF); 684 Offset = FPOffset; 685 } else if (hasMovingSP) { 686 assert(RegInfo->hasBasePointer(MF) && 687 "VLAs and dynamic stack alignment, but missing base pointer!"); 688 FrameReg = RegInfo->getBaseRegister(); 689 } 690 return Offset; 691 } 692 693 // If there is a frame pointer, use it when we can. 694 if (hasFP(MF) && AFI->hasStackFrame()) { 695 // Use frame pointer to reference fixed objects. Use it for locals if 696 // there are VLAs (and thus the SP isn't reliable as a base). 697 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) { 698 FrameReg = RegInfo->getFrameRegister(MF); 699 return FPOffset; 700 } else if (hasMovingSP) { 701 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 702 if (AFI->isThumb2Function()) { 703 // Try to use the frame pointer if we can, else use the base pointer 704 // since it's available. This is handy for the emergency spill slot, in 705 // particular. 706 if (FPOffset >= -255 && FPOffset < 0) { 707 FrameReg = RegInfo->getFrameRegister(MF); 708 return FPOffset; 709 } 710 } 711 } else if (AFI->isThumb2Function()) { 712 // Use add <rd>, sp, #<imm8> 713 // ldr <rd>, [sp, #<imm8>] 714 // if at all possible to save space. 715 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020) 716 return Offset; 717 // In Thumb2 mode, the negative offset is very limited. Try to avoid 718 // out of range references. ldr <rt>,[<rn>, #-<imm8>] 719 if (FPOffset >= -255 && FPOffset < 0) { 720 FrameReg = RegInfo->getFrameRegister(MF); 721 return FPOffset; 722 } 723 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 724 // Otherwise, use SP or FP, whichever is closer to the stack slot. 725 FrameReg = RegInfo->getFrameRegister(MF); 726 return FPOffset; 727 } 728 } 729 // Use the base pointer if we have one. 730 if (RegInfo->hasBasePointer(MF)) 731 FrameReg = RegInfo->getBaseRegister(); 732 return Offset; 733 } 734 735 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF, 736 int FI) const { 737 unsigned FrameReg; 738 return getFrameIndexReference(MF, FI, FrameReg); 739 } 740 741 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 742 MachineBasicBlock::iterator MI, 743 const std::vector<CalleeSavedInfo> &CSI, 744 unsigned StmOpc, unsigned StrOpc, 745 bool NoGap, 746 bool(*Func)(unsigned, bool), 747 unsigned NumAlignedDPRCS2Regs, 748 unsigned MIFlags) const { 749 MachineFunction &MF = *MBB.getParent(); 750 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 751 752 DebugLoc DL; 753 if (MI != MBB.end()) DL = MI->getDebugLoc(); 754 755 SmallVector<std::pair<unsigned,bool>, 4> Regs; 756 unsigned i = CSI.size(); 757 while (i != 0) { 758 unsigned LastReg = 0; 759 for (; i != 0; --i) { 760 unsigned Reg = CSI[i-1].getReg(); 761 if (!(Func)(Reg, STI.isTargetMachO())) continue; 762 763 // D-registers in the aligned area DPRCS2 are NOT spilled here. 764 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 765 continue; 766 767 // Add the callee-saved register as live-in unless it's LR and 768 // @llvm.returnaddress is called. If LR is returned for 769 // @llvm.returnaddress then it's already added to the function and 770 // entry block live-in sets. 771 bool isKill = true; 772 if (Reg == ARM::LR) { 773 if (MF.getFrameInfo()->isReturnAddressTaken() && 774 MF.getRegInfo().isLiveIn(Reg)) 775 isKill = false; 776 } 777 778 if (isKill) 779 MBB.addLiveIn(Reg); 780 781 // If NoGap is true, push consecutive registers and then leave the rest 782 // for other instructions. e.g. 783 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 784 if (NoGap && LastReg && LastReg != Reg-1) 785 break; 786 LastReg = Reg; 787 Regs.push_back(std::make_pair(Reg, isKill)); 788 } 789 790 if (Regs.empty()) 791 continue; 792 if (Regs.size() > 1 || StrOpc== 0) { 793 MachineInstrBuilder MIB = 794 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 795 .addReg(ARM::SP).setMIFlags(MIFlags)); 796 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 797 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 798 } else if (Regs.size() == 1) { 799 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc), 800 ARM::SP) 801 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 802 .addReg(ARM::SP).setMIFlags(MIFlags) 803 .addImm(-4); 804 AddDefaultPred(MIB); 805 } 806 Regs.clear(); 807 808 // Put any subsequent vpush instructions before this one: they will refer to 809 // higher register numbers so need to be pushed first in order to preserve 810 // monotonicity. 811 --MI; 812 } 813 } 814 815 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 816 MachineBasicBlock::iterator MI, 817 const std::vector<CalleeSavedInfo> &CSI, 818 unsigned LdmOpc, unsigned LdrOpc, 819 bool isVarArg, bool NoGap, 820 bool(*Func)(unsigned, bool), 821 unsigned NumAlignedDPRCS2Regs) const { 822 MachineFunction &MF = *MBB.getParent(); 823 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 824 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 825 DebugLoc DL = MI->getDebugLoc(); 826 unsigned RetOpcode = MI->getOpcode(); 827 bool isTailCall = (RetOpcode == ARM::TCRETURNdi || 828 RetOpcode == ARM::TCRETURNri); 829 bool isInterrupt = 830 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR; 831 832 SmallVector<unsigned, 4> Regs; 833 unsigned i = CSI.size(); 834 while (i != 0) { 835 unsigned LastReg = 0; 836 bool DeleteRet = false; 837 for (; i != 0; --i) { 838 unsigned Reg = CSI[i-1].getReg(); 839 if (!(Func)(Reg, STI.isTargetMachO())) continue; 840 841 // The aligned reloads from area DPRCS2 are not inserted here. 842 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 843 continue; 844 845 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt && 846 STI.hasV5TOps()) { 847 Reg = ARM::PC; 848 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 849 // Fold the return instruction into the LDM. 850 DeleteRet = true; 851 } 852 853 // If NoGap is true, pop consecutive registers and then leave the rest 854 // for other instructions. e.g. 855 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 856 if (NoGap && LastReg && LastReg != Reg-1) 857 break; 858 859 LastReg = Reg; 860 Regs.push_back(Reg); 861 } 862 863 if (Regs.empty()) 864 continue; 865 if (Regs.size() > 1 || LdrOpc == 0) { 866 MachineInstrBuilder MIB = 867 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 868 .addReg(ARM::SP)); 869 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 870 MIB.addReg(Regs[i], getDefRegState(true)); 871 if (DeleteRet) { 872 MIB.copyImplicitOps(&*MI); 873 MI->eraseFromParent(); 874 } 875 MI = MIB; 876 } else if (Regs.size() == 1) { 877 // If we adjusted the reg to PC from LR above, switch it back here. We 878 // only do that for LDM. 879 if (Regs[0] == ARM::PC) 880 Regs[0] = ARM::LR; 881 MachineInstrBuilder MIB = 882 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 883 .addReg(ARM::SP, RegState::Define) 884 .addReg(ARM::SP); 885 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 886 // that refactoring is complete (eventually). 887 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) { 888 MIB.addReg(0); 889 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 890 } else 891 MIB.addImm(4); 892 AddDefaultPred(MIB); 893 } 894 Regs.clear(); 895 896 // Put any subsequent vpop instructions after this one: they will refer to 897 // higher register numbers so need to be popped afterwards. 898 ++MI; 899 } 900 } 901 902 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers 903 /// starting from d8. Also insert stack realignment code and leave the stack 904 /// pointer pointing to the d8 spill slot. 905 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, 906 MachineBasicBlock::iterator MI, 907 unsigned NumAlignedDPRCS2Regs, 908 const std::vector<CalleeSavedInfo> &CSI, 909 const TargetRegisterInfo *TRI) { 910 MachineFunction &MF = *MBB.getParent(); 911 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 912 DebugLoc DL = MI->getDebugLoc(); 913 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 914 MachineFrameInfo &MFI = *MF.getFrameInfo(); 915 916 // Mark the D-register spill slots as properly aligned. Since MFI computes 917 // stack slot layout backwards, this can actually mean that the d-reg stack 918 // slot offsets can be wrong. The offset for d8 will always be correct. 919 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 920 unsigned DNum = CSI[i].getReg() - ARM::D8; 921 if (DNum >= 8) 922 continue; 923 int FI = CSI[i].getFrameIdx(); 924 // The even-numbered registers will be 16-byte aligned, the odd-numbered 925 // registers will be 8-byte aligned. 926 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16); 927 928 // The stack slot for D8 needs to be maximally aligned because this is 929 // actually the point where we align the stack pointer. MachineFrameInfo 930 // computes all offsets relative to the incoming stack pointer which is a 931 // bit weird when realigning the stack. Any extra padding for this 932 // over-alignment is not realized because the code inserted below adjusts 933 // the stack pointer by numregs * 8 before aligning the stack pointer. 934 if (DNum == 0) 935 MFI.setObjectAlignment(FI, MFI.getMaxAlignment()); 936 } 937 938 // Move the stack pointer to the d8 spill slot, and align it at the same 939 // time. Leave the stack slot address in the scratch register r4. 940 // 941 // sub r4, sp, #numregs * 8 942 // bic r4, r4, #align - 1 943 // mov sp, r4 944 // 945 bool isThumb = AFI->isThumbFunction(); 946 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 947 AFI->setShouldRestoreSPFromFP(true); 948 949 // sub r4, sp, #numregs * 8 950 // The immediate is <= 64, so it doesn't need any special encoding. 951 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri; 952 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 953 .addReg(ARM::SP) 954 .addImm(8 * NumAlignedDPRCS2Regs))); 955 956 // bic r4, r4, #align-1 957 Opc = isThumb ? ARM::t2BICri : ARM::BICri; 958 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment(); 959 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 960 .addReg(ARM::R4, RegState::Kill) 961 .addImm(MaxAlign - 1))); 962 963 // mov sp, r4 964 // The stack pointer must be adjusted before spilling anything, otherwise 965 // the stack slots could be clobbered by an interrupt handler. 966 // Leave r4 live, it is used below. 967 Opc = isThumb ? ARM::tMOVr : ARM::MOVr; 968 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP) 969 .addReg(ARM::R4); 970 MIB = AddDefaultPred(MIB); 971 if (!isThumb) 972 AddDefaultCC(MIB); 973 974 // Now spill NumAlignedDPRCS2Regs registers starting from d8. 975 // r4 holds the stack slot address. 976 unsigned NextReg = ARM::D8; 977 978 // 16-byte aligned vst1.64 with 4 d-regs and address writeback. 979 // The writeback is only needed when emitting two vst1.64 instructions. 980 if (NumAlignedDPRCS2Regs >= 6) { 981 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 982 &ARM::QQPRRegClass); 983 MBB.addLiveIn(SupReg); 984 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), 985 ARM::R4) 986 .addReg(ARM::R4, RegState::Kill).addImm(16) 987 .addReg(NextReg) 988 .addReg(SupReg, RegState::ImplicitKill)); 989 NextReg += 4; 990 NumAlignedDPRCS2Regs -= 4; 991 } 992 993 // We won't modify r4 beyond this point. It currently points to the next 994 // register to be spilled. 995 unsigned R4BaseReg = NextReg; 996 997 // 16-byte aligned vst1.64 with 4 d-regs, no writeback. 998 if (NumAlignedDPRCS2Regs >= 4) { 999 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1000 &ARM::QQPRRegClass); 1001 MBB.addLiveIn(SupReg); 1002 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q)) 1003 .addReg(ARM::R4).addImm(16).addReg(NextReg) 1004 .addReg(SupReg, RegState::ImplicitKill)); 1005 NextReg += 4; 1006 NumAlignedDPRCS2Regs -= 4; 1007 } 1008 1009 // 16-byte aligned vst1.64 with 2 d-regs. 1010 if (NumAlignedDPRCS2Regs >= 2) { 1011 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1012 &ARM::QPRRegClass); 1013 MBB.addLiveIn(SupReg); 1014 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64)) 1015 .addReg(ARM::R4).addImm(16).addReg(SupReg)); 1016 NextReg += 2; 1017 NumAlignedDPRCS2Regs -= 2; 1018 } 1019 1020 // Finally, use a vanilla vstr.64 for the odd last register. 1021 if (NumAlignedDPRCS2Regs) { 1022 MBB.addLiveIn(NextReg); 1023 // vstr.64 uses addrmode5 which has an offset scale of 4. 1024 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD)) 1025 .addReg(NextReg) 1026 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2)); 1027 } 1028 1029 // The last spill instruction inserted should kill the scratch register r4. 1030 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1031 } 1032 1033 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an 1034 /// iterator to the following instruction. 1035 static MachineBasicBlock::iterator 1036 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 1037 unsigned NumAlignedDPRCS2Regs) { 1038 // sub r4, sp, #numregs * 8 1039 // bic r4, r4, #align - 1 1040 // mov sp, r4 1041 ++MI; ++MI; ++MI; 1042 assert(MI->mayStore() && "Expecting spill instruction"); 1043 1044 // These switches all fall through. 1045 switch(NumAlignedDPRCS2Regs) { 1046 case 7: 1047 ++MI; 1048 assert(MI->mayStore() && "Expecting spill instruction"); 1049 default: 1050 ++MI; 1051 assert(MI->mayStore() && "Expecting spill instruction"); 1052 case 1: 1053 case 2: 1054 case 4: 1055 assert(MI->killsRegister(ARM::R4) && "Missed kill flag"); 1056 ++MI; 1057 } 1058 return MI; 1059 } 1060 1061 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers 1062 /// starting from d8. These instructions are assumed to execute while the 1063 /// stack is still aligned, unlike the code inserted by emitPopInst. 1064 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, 1065 MachineBasicBlock::iterator MI, 1066 unsigned NumAlignedDPRCS2Regs, 1067 const std::vector<CalleeSavedInfo> &CSI, 1068 const TargetRegisterInfo *TRI) { 1069 MachineFunction &MF = *MBB.getParent(); 1070 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1071 DebugLoc DL = MI->getDebugLoc(); 1072 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); 1073 1074 // Find the frame index assigned to d8. 1075 int D8SpillFI = 0; 1076 for (unsigned i = 0, e = CSI.size(); i != e; ++i) 1077 if (CSI[i].getReg() == ARM::D8) { 1078 D8SpillFI = CSI[i].getFrameIdx(); 1079 break; 1080 } 1081 1082 // Materialize the address of the d8 spill slot into the scratch register r4. 1083 // This can be fairly complicated if the stack frame is large, so just use 1084 // the normal frame index elimination mechanism to do it. This code runs as 1085 // the initial part of the epilog where the stack and base pointers haven't 1086 // been changed yet. 1087 bool isThumb = AFI->isThumbFunction(); 1088 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1089 1090 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri; 1091 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1092 .addFrameIndex(D8SpillFI).addImm(0))); 1093 1094 // Now restore NumAlignedDPRCS2Regs registers starting from d8. 1095 unsigned NextReg = ARM::D8; 1096 1097 // 16-byte aligned vld1.64 with 4 d-regs and writeback. 1098 if (NumAlignedDPRCS2Regs >= 6) { 1099 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1100 &ARM::QQPRRegClass); 1101 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg) 1102 .addReg(ARM::R4, RegState::Define) 1103 .addReg(ARM::R4, RegState::Kill).addImm(16) 1104 .addReg(SupReg, RegState::ImplicitDefine)); 1105 NextReg += 4; 1106 NumAlignedDPRCS2Regs -= 4; 1107 } 1108 1109 // We won't modify r4 beyond this point. It currently points to the next 1110 // register to be spilled. 1111 unsigned R4BaseReg = NextReg; 1112 1113 // 16-byte aligned vld1.64 with 4 d-regs, no writeback. 1114 if (NumAlignedDPRCS2Regs >= 4) { 1115 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1116 &ARM::QQPRRegClass); 1117 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg) 1118 .addReg(ARM::R4).addImm(16) 1119 .addReg(SupReg, RegState::ImplicitDefine)); 1120 NextReg += 4; 1121 NumAlignedDPRCS2Regs -= 4; 1122 } 1123 1124 // 16-byte aligned vld1.64 with 2 d-regs. 1125 if (NumAlignedDPRCS2Regs >= 2) { 1126 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1127 &ARM::QPRRegClass); 1128 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg) 1129 .addReg(ARM::R4).addImm(16)); 1130 NextReg += 2; 1131 NumAlignedDPRCS2Regs -= 2; 1132 } 1133 1134 // Finally, use a vanilla vldr.64 for the remaining odd register. 1135 if (NumAlignedDPRCS2Regs) 1136 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg) 1137 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg))); 1138 1139 // Last store kills r4. 1140 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1141 } 1142 1143 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB, 1144 MachineBasicBlock::iterator MI, 1145 const std::vector<CalleeSavedInfo> &CSI, 1146 const TargetRegisterInfo *TRI) const { 1147 if (CSI.empty()) 1148 return false; 1149 1150 MachineFunction &MF = *MBB.getParent(); 1151 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1152 1153 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 1154 unsigned PushOneOpc = AFI->isThumbFunction() ? 1155 ARM::t2STR_PRE : ARM::STR_PRE_IMM; 1156 unsigned FltOpc = ARM::VSTMDDB_UPD; 1157 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1158 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0, 1159 MachineInstr::FrameSetup); 1160 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0, 1161 MachineInstr::FrameSetup); 1162 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register, 1163 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup); 1164 1165 // The code above does not insert spill code for the aligned DPRCS2 registers. 1166 // The stack realignment code will be inserted between the push instructions 1167 // and these spills. 1168 if (NumAlignedDPRCS2Regs) 1169 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1170 1171 return true; 1172 } 1173 1174 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB, 1175 MachineBasicBlock::iterator MI, 1176 const std::vector<CalleeSavedInfo> &CSI, 1177 const TargetRegisterInfo *TRI) const { 1178 if (CSI.empty()) 1179 return false; 1180 1181 MachineFunction &MF = *MBB.getParent(); 1182 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1183 bool isVarArg = AFI->getArgRegsSaveSize() > 0; 1184 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 1185 1186 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2 1187 // registers. Do that here instead. 1188 if (NumAlignedDPRCS2Regs) 1189 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 1190 1191 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 1192 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM; 1193 unsigned FltOpc = ARM::VLDMDIA_UPD; 1194 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register, 1195 NumAlignedDPRCS2Regs); 1196 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1197 &isARMArea2Register, 0); 1198 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, 1199 &isARMArea1Register, 0); 1200 1201 return true; 1202 } 1203 1204 // FIXME: Make generic? 1205 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF, 1206 const ARMBaseInstrInfo &TII) { 1207 unsigned FnSize = 0; 1208 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end(); 1209 MBBI != E; ++MBBI) { 1210 const MachineBasicBlock &MBB = *MBBI; 1211 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end(); 1212 I != E; ++I) 1213 FnSize += TII.GetInstSizeInBytes(I); 1214 } 1215 return FnSize; 1216 } 1217 1218 /// estimateRSStackSizeLimit - Look at each instruction that references stack 1219 /// frames and return the stack size limit beyond which some of these 1220 /// instructions will require a scratch register during their expansion later. 1221 // FIXME: Move to TII? 1222 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 1223 const TargetFrameLowering *TFI) { 1224 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1225 unsigned Limit = (1 << 12) - 1; 1226 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) { 1227 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); 1228 I != E; ++I) { 1229 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1230 if (!I->getOperand(i).isFI()) continue; 1231 1232 // When using ADDri to get the address of a stack object, 255 is the 1233 // largest offset guaranteed to fit in the immediate offset. 1234 if (I->getOpcode() == ARM::ADDri) { 1235 Limit = std::min(Limit, (1U << 8) - 1); 1236 break; 1237 } 1238 1239 // Otherwise check the addressing mode. 1240 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) { 1241 case ARMII::AddrMode3: 1242 case ARMII::AddrModeT2_i8: 1243 Limit = std::min(Limit, (1U << 8) - 1); 1244 break; 1245 case ARMII::AddrMode5: 1246 case ARMII::AddrModeT2_i8s4: 1247 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 1248 break; 1249 case ARMII::AddrModeT2_i12: 1250 // i12 supports only positive offset so these will be converted to 1251 // i8 opcodes. See llvm::rewriteT2FrameIndex. 1252 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 1253 Limit = std::min(Limit, (1U << 8) - 1); 1254 break; 1255 case ARMII::AddrMode4: 1256 case ARMII::AddrMode6: 1257 // Addressing modes 4 & 6 (load/store) instructions can't encode an 1258 // immediate offset for stack references. 1259 return 0; 1260 default: 1261 break; 1262 } 1263 break; // At most one FI per instruction 1264 } 1265 } 1266 } 1267 1268 return Limit; 1269 } 1270 1271 // In functions that realign the stack, it can be an advantage to spill the 1272 // callee-saved vector registers after realigning the stack. The vst1 and vld1 1273 // instructions take alignment hints that can improve performance. 1274 // 1275 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) { 1276 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0); 1277 if (!SpillAlignedNEONRegs) 1278 return; 1279 1280 // Naked functions don't spill callee-saved registers. 1281 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1282 Attribute::Naked)) 1283 return; 1284 1285 // We are planning to use NEON instructions vst1 / vld1. 1286 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON()) 1287 return; 1288 1289 // Don't bother if the default stack alignment is sufficiently high. 1290 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8) 1291 return; 1292 1293 // Aligned spills require stack realignment. 1294 const ARMBaseRegisterInfo *RegInfo = 1295 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 1296 if (!RegInfo->canRealignStack(MF)) 1297 return; 1298 1299 // We always spill contiguous d-registers starting from d8. Count how many 1300 // needs spilling. The register allocator will almost always use the 1301 // callee-saved registers in order, but it can happen that there are holes in 1302 // the range. Registers above the hole will be spilled to the standard DPRCS 1303 // area. 1304 MachineRegisterInfo &MRI = MF.getRegInfo(); 1305 unsigned NumSpills = 0; 1306 for (; NumSpills < 8; ++NumSpills) 1307 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills)) 1308 break; 1309 1310 // Don't do this for just one d-register. It's not worth it. 1311 if (NumSpills < 2) 1312 return; 1313 1314 // Spill the first NumSpills D-registers after realigning the stack. 1315 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills); 1316 1317 // A scratch register is required for the vst1 / vld1 instructions. 1318 MF.getRegInfo().setPhysRegUsed(ARM::R4); 1319 } 1320 1321 void 1322 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF, 1323 RegScavenger *RS) const { 1324 // This tells PEI to spill the FP as if it is any other callee-save register 1325 // to take advantage the eliminateFrameIndex machinery. This also ensures it 1326 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 1327 // to combine multiple loads / stores. 1328 bool CanEliminateFrame = true; 1329 bool CS1Spilled = false; 1330 bool LRSpilled = false; 1331 unsigned NumGPRSpills = 0; 1332 SmallVector<unsigned, 4> UnspilledCS1GPRs; 1333 SmallVector<unsigned, 4> UnspilledCS2GPRs; 1334 const ARMBaseRegisterInfo *RegInfo = 1335 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo()); 1336 const ARMBaseInstrInfo &TII = 1337 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 1338 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1339 MachineFrameInfo *MFI = MF.getFrameInfo(); 1340 MachineRegisterInfo &MRI = MF.getRegInfo(); 1341 unsigned FramePtr = RegInfo->getFrameRegister(MF); 1342 1343 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 1344 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 1345 // since it's not always possible to restore sp from fp in a single 1346 // instruction. 1347 // FIXME: It will be better just to find spare register here. 1348 if (AFI->isThumb2Function() && 1349 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF))) 1350 MRI.setPhysRegUsed(ARM::R4); 1351 1352 if (AFI->isThumb1OnlyFunction()) { 1353 // Spill LR if Thumb1 function uses variable length argument lists. 1354 if (AFI->getArgRegsSaveSize() > 0) 1355 MRI.setPhysRegUsed(ARM::LR); 1356 1357 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know 1358 // for sure what the stack size will be, but for this, an estimate is good 1359 // enough. If there anything changes it, it'll be a spill, which implies 1360 // we've used all the registers and so R4 is already used, so not marking 1361 // it here will be OK. 1362 // FIXME: It will be better just to find spare register here. 1363 unsigned StackSize = MFI->estimateStackSize(MF); 1364 if (MFI->hasVarSizedObjects() || StackSize > 508) 1365 MRI.setPhysRegUsed(ARM::R4); 1366 } 1367 1368 // See if we can spill vector registers to aligned stack. 1369 checkNumAlignedDPRCS2Regs(MF); 1370 1371 // Spill the BasePtr if it's used. 1372 if (RegInfo->hasBasePointer(MF)) 1373 MRI.setPhysRegUsed(RegInfo->getBaseRegister()); 1374 1375 // Don't spill FP if the frame can be eliminated. This is determined 1376 // by scanning the callee-save registers to see if any is used. 1377 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 1378 for (unsigned i = 0; CSRegs[i]; ++i) { 1379 unsigned Reg = CSRegs[i]; 1380 bool Spilled = false; 1381 if (MRI.isPhysRegUsed(Reg)) { 1382 Spilled = true; 1383 CanEliminateFrame = false; 1384 } 1385 1386 if (!ARM::GPRRegClass.contains(Reg)) 1387 continue; 1388 1389 if (Spilled) { 1390 NumGPRSpills++; 1391 1392 if (!STI.isTargetMachO()) { 1393 if (Reg == ARM::LR) 1394 LRSpilled = true; 1395 CS1Spilled = true; 1396 continue; 1397 } 1398 1399 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 1400 switch (Reg) { 1401 case ARM::LR: 1402 LRSpilled = true; 1403 // Fallthrough 1404 case ARM::R0: case ARM::R1: 1405 case ARM::R2: case ARM::R3: 1406 case ARM::R4: case ARM::R5: 1407 case ARM::R6: case ARM::R7: 1408 CS1Spilled = true; 1409 break; 1410 default: 1411 break; 1412 } 1413 } else { 1414 if (!STI.isTargetMachO()) { 1415 UnspilledCS1GPRs.push_back(Reg); 1416 continue; 1417 } 1418 1419 switch (Reg) { 1420 case ARM::R0: case ARM::R1: 1421 case ARM::R2: case ARM::R3: 1422 case ARM::R4: case ARM::R5: 1423 case ARM::R6: case ARM::R7: 1424 case ARM::LR: 1425 UnspilledCS1GPRs.push_back(Reg); 1426 break; 1427 default: 1428 UnspilledCS2GPRs.push_back(Reg); 1429 break; 1430 } 1431 } 1432 } 1433 1434 bool ForceLRSpill = false; 1435 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 1436 unsigned FnSize = GetFunctionSizeInBytes(MF, TII); 1437 // Force LR to be spilled if the Thumb function size is > 2048. This enables 1438 // use of BL to implement far jump. If it turns out that it's not needed 1439 // then the branch fix up path will undo it. 1440 if (FnSize >= (1 << 11)) { 1441 CanEliminateFrame = false; 1442 ForceLRSpill = true; 1443 } 1444 } 1445 1446 // If any of the stack slot references may be out of range of an immediate 1447 // offset, make sure a register (or a spill slot) is available for the 1448 // register scavenger. Note that if we're indexing off the frame pointer, the 1449 // effective stack size is 4 bytes larger since the FP points to the stack 1450 // slot of the previous FP. Also, if we have variable sized objects in the 1451 // function, stack slot references will often be negative, and some of 1452 // our instructions are positive-offset only, so conservatively consider 1453 // that case to want a spill slot (or register) as well. Similarly, if 1454 // the function adjusts the stack pointer during execution and the 1455 // adjustments aren't already part of our stack size estimate, our offset 1456 // calculations may be off, so be conservative. 1457 // FIXME: We could add logic to be more precise about negative offsets 1458 // and which instructions will need a scratch register for them. Is it 1459 // worth the effort and added fragility? 1460 bool BigStack = 1461 (RS && 1462 (MFI->estimateStackSize(MF) + 1463 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >= 1464 estimateRSStackSizeLimit(MF, this))) 1465 || MFI->hasVarSizedObjects() 1466 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF)); 1467 1468 bool ExtraCSSpill = false; 1469 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 1470 AFI->setHasStackFrame(true); 1471 1472 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 1473 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 1474 if (!LRSpilled && CS1Spilled) { 1475 MRI.setPhysRegUsed(ARM::LR); 1476 NumGPRSpills++; 1477 SmallVectorImpl<unsigned>::iterator LRPos; 1478 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(), 1479 (unsigned)ARM::LR); 1480 if (LRPos != UnspilledCS1GPRs.end()) 1481 UnspilledCS1GPRs.erase(LRPos); 1482 1483 ForceLRSpill = false; 1484 ExtraCSSpill = true; 1485 } 1486 1487 if (hasFP(MF)) { 1488 MRI.setPhysRegUsed(FramePtr); 1489 NumGPRSpills++; 1490 } 1491 1492 // If stack and double are 8-byte aligned and we are spilling an odd number 1493 // of GPRs, spill one extra callee save GPR so we won't have to pad between 1494 // the integer and double callee save areas. 1495 unsigned TargetAlign = getStackAlignment(); 1496 if (TargetAlign == 8 && (NumGPRSpills & 1)) { 1497 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 1498 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) { 1499 unsigned Reg = UnspilledCS1GPRs[i]; 1500 // Don't spill high register if the function is thumb1 1501 if (!AFI->isThumb1OnlyFunction() || 1502 isARMLowRegister(Reg) || Reg == ARM::LR) { 1503 MRI.setPhysRegUsed(Reg); 1504 if (!MRI.isReserved(Reg)) 1505 ExtraCSSpill = true; 1506 break; 1507 } 1508 } 1509 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 1510 unsigned Reg = UnspilledCS2GPRs.front(); 1511 MRI.setPhysRegUsed(Reg); 1512 if (!MRI.isReserved(Reg)) 1513 ExtraCSSpill = true; 1514 } 1515 } 1516 1517 // Estimate if we might need to scavenge a register at some point in order 1518 // to materialize a stack offset. If so, either spill one additional 1519 // callee-saved register or reserve a special spill slot to facilitate 1520 // register scavenging. Thumb1 needs a spill slot for stack pointer 1521 // adjustments also, even when the frame itself is small. 1522 if (BigStack && !ExtraCSSpill) { 1523 // If any non-reserved CS register isn't spilled, just spill one or two 1524 // extra. That should take care of it! 1525 unsigned NumExtras = TargetAlign / 4; 1526 SmallVector<unsigned, 2> Extras; 1527 while (NumExtras && !UnspilledCS1GPRs.empty()) { 1528 unsigned Reg = UnspilledCS1GPRs.back(); 1529 UnspilledCS1GPRs.pop_back(); 1530 if (!MRI.isReserved(Reg) && 1531 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) || 1532 Reg == ARM::LR)) { 1533 Extras.push_back(Reg); 1534 NumExtras--; 1535 } 1536 } 1537 // For non-Thumb1 functions, also check for hi-reg CS registers 1538 if (!AFI->isThumb1OnlyFunction()) { 1539 while (NumExtras && !UnspilledCS2GPRs.empty()) { 1540 unsigned Reg = UnspilledCS2GPRs.back(); 1541 UnspilledCS2GPRs.pop_back(); 1542 if (!MRI.isReserved(Reg)) { 1543 Extras.push_back(Reg); 1544 NumExtras--; 1545 } 1546 } 1547 } 1548 if (Extras.size() && NumExtras == 0) { 1549 for (unsigned i = 0, e = Extras.size(); i != e; ++i) { 1550 MRI.setPhysRegUsed(Extras[i]); 1551 } 1552 } else if (!AFI->isThumb1OnlyFunction()) { 1553 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot 1554 // closest to SP or frame pointer. 1555 const TargetRegisterClass *RC = &ARM::GPRRegClass; 1556 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(), 1557 RC->getAlignment(), 1558 false)); 1559 } 1560 } 1561 } 1562 1563 if (ForceLRSpill) { 1564 MRI.setPhysRegUsed(ARM::LR); 1565 AFI->setLRIsSpilledForFarJump(true); 1566 } 1567 } 1568 1569 1570 void ARMFrameLowering:: 1571 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, 1572 MachineBasicBlock::iterator I) const { 1573 const ARMBaseInstrInfo &TII = 1574 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 1575 if (!hasReservedCallFrame(MF)) { 1576 // If we have alloca, convert as follows: 1577 // ADJCALLSTACKDOWN -> sub, sp, sp, amount 1578 // ADJCALLSTACKUP -> add, sp, sp, amount 1579 MachineInstr *Old = I; 1580 DebugLoc dl = Old->getDebugLoc(); 1581 unsigned Amount = Old->getOperand(0).getImm(); 1582 if (Amount != 0) { 1583 // We need to keep the stack aligned properly. To do this, we round the 1584 // amount of space needed for the outgoing arguments up to the next 1585 // alignment boundary. 1586 unsigned Align = getStackAlignment(); 1587 Amount = (Amount+Align-1)/Align*Align; 1588 1589 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1590 assert(!AFI->isThumb1OnlyFunction() && 1591 "This eliminateCallFramePseudoInstr does not support Thumb1!"); 1592 bool isARM = !AFI->isThumbFunction(); 1593 1594 // Replace the pseudo instruction with a new instruction... 1595 unsigned Opc = Old->getOpcode(); 1596 int PIdx = Old->findFirstPredOperandIdx(); 1597 ARMCC::CondCodes Pred = (PIdx == -1) 1598 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm(); 1599 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) { 1600 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN. 1601 unsigned PredReg = Old->getOperand(2).getReg(); 1602 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags, 1603 Pred, PredReg); 1604 } else { 1605 // Note: PredReg is operand 3 for ADJCALLSTACKUP. 1606 unsigned PredReg = Old->getOperand(3).getReg(); 1607 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP); 1608 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags, 1609 Pred, PredReg); 1610 } 1611 } 1612 } 1613 MBB.erase(I); 1614 } 1615 1616 /// Get the minimum constant for ARM that is greater than or equal to the 1617 /// argument. In ARM, constants can have any value that can be produced by 1618 /// rotating an 8-bit value to the right by an even number of bits within a 1619 /// 32-bit word. 1620 static uint32_t alignToARMConstant(uint32_t Value) { 1621 unsigned Shifted = 0; 1622 1623 if (Value == 0) 1624 return 0; 1625 1626 while (!(Value & 0xC0000000)) { 1627 Value = Value << 2; 1628 Shifted += 2; 1629 } 1630 1631 bool Carry = (Value & 0x00FFFFFF); 1632 Value = ((Value & 0xFF000000) >> 24) + Carry; 1633 1634 if (Value & 0x0000100) 1635 Value = Value & 0x000001FC; 1636 1637 if (Shifted > 24) 1638 Value = Value >> (Shifted - 24); 1639 else 1640 Value = Value << (24 - Shifted); 1641 1642 return Value; 1643 } 1644 1645 // The stack limit in the TCB is set to this many bytes above the actual 1646 // stack limit. 1647 static const uint64_t kSplitStackAvailable = 256; 1648 1649 // Adjust the function prologue to enable split stacks. This currently only 1650 // supports android and linux. 1651 // 1652 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but 1653 // must be well defined in order to allow for consistent implementations of the 1654 // __morestack helper function. The ABI is also not a normal ABI in that it 1655 // doesn't follow the normal calling conventions because this allows the 1656 // prologue of each function to be optimized further. 1657 // 1658 // Currently, the ABI looks like (when calling __morestack) 1659 // 1660 // * r4 holds the minimum stack size requested for this function call 1661 // * r5 holds the stack size of the arguments to the function 1662 // * the beginning of the function is 3 instructions after the call to 1663 // __morestack 1664 // 1665 // Implementations of __morestack should use r4 to allocate a new stack, r5 to 1666 // place the arguments on to the new stack, and the 3-instruction knowledge to 1667 // jump directly to the body of the function when working on the new stack. 1668 // 1669 // An old (and possibly no longer compatible) implementation of __morestack for 1670 // ARM can be found at [1]. 1671 // 1672 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S 1673 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const { 1674 unsigned Opcode; 1675 unsigned CFIIndex; 1676 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>(); 1677 bool Thumb = ST->isThumb(); 1678 1679 // Sadly, this currently doesn't support varargs, platforms other than 1680 // android/linux. Note that thumb1/thumb2 are support for android/linux. 1681 if (MF.getFunction()->isVarArg()) 1682 report_fatal_error("Segmented stacks do not support vararg functions."); 1683 if (!ST->isTargetAndroid() && !ST->isTargetLinux()) 1684 report_fatal_error("Segmented stacks not supported on this platfrom."); 1685 1686 MachineBasicBlock &prologueMBB = MF.front(); 1687 MachineFrameInfo *MFI = MF.getFrameInfo(); 1688 MachineModuleInfo &MMI = MF.getMMI(); 1689 MCContext &Context = MMI.getContext(); 1690 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 1691 const ARMBaseInstrInfo &TII = 1692 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo()); 1693 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>(); 1694 DebugLoc DL; 1695 1696 // Use R4 and R5 as scratch registers. 1697 // We save R4 and R5 before use and restore them before leaving the function. 1698 unsigned ScratchReg0 = ARM::R4; 1699 unsigned ScratchReg1 = ARM::R5; 1700 uint64_t AlignedStackSize; 1701 1702 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock(); 1703 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock(); 1704 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock(); 1705 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock(); 1706 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock(); 1707 1708 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(), 1709 e = prologueMBB.livein_end(); 1710 i != e; ++i) { 1711 AllocMBB->addLiveIn(*i); 1712 GetMBB->addLiveIn(*i); 1713 McrMBB->addLiveIn(*i); 1714 PrevStackMBB->addLiveIn(*i); 1715 PostStackMBB->addLiveIn(*i); 1716 } 1717 1718 MF.push_front(PostStackMBB); 1719 MF.push_front(AllocMBB); 1720 MF.push_front(GetMBB); 1721 MF.push_front(McrMBB); 1722 MF.push_front(PrevStackMBB); 1723 1724 // The required stack size that is aligned to ARM constant criterion. 1725 uint64_t StackSize = MFI->getStackSize(); 1726 1727 AlignedStackSize = alignToARMConstant(StackSize); 1728 1729 // When the frame size is less than 256 we just compare the stack 1730 // boundary directly to the value of the stack pointer, per gcc. 1731 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable; 1732 1733 // We will use two of the callee save registers as scratch registers so we 1734 // need to save those registers onto the stack. 1735 // We will use SR0 to hold stack limit and SR1 to hold the stack size 1736 // requested and arguments for __morestack(). 1737 // SR0: Scratch Register #0 1738 // SR1: Scratch Register #1 1739 // push {SR0, SR1} 1740 if (Thumb) { 1741 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))) 1742 .addReg(ScratchReg0).addReg(ScratchReg1); 1743 } else { 1744 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD)) 1745 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP)) 1746 .addReg(ScratchReg0).addReg(ScratchReg1); 1747 } 1748 1749 // Emit the relevant DWARF information about the change in stack pointer as 1750 // well as where to find both r4 and r5 (the callee-save registers) 1751 CFIIndex = 1752 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8)); 1753 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1754 .addCFIIndex(CFIIndex); 1755 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 1756 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4)); 1757 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1758 .addCFIIndex(CFIIndex); 1759 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 1760 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8)); 1761 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1762 .addCFIIndex(CFIIndex); 1763 1764 // mov SR1, sp 1765 if (Thumb) { 1766 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1) 1767 .addReg(ARM::SP)); 1768 } else if (CompareStackPointer) { 1769 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1) 1770 .addReg(ARM::SP)).addReg(0); 1771 } 1772 1773 // sub SR1, sp, #StackSize 1774 if (!CompareStackPointer && Thumb) { 1775 AddDefaultPred( 1776 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)) 1777 .addReg(ScratchReg1).addImm(AlignedStackSize)); 1778 } else if (!CompareStackPointer) { 1779 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1) 1780 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0); 1781 } 1782 1783 if (Thumb && ST->isThumb1Only()) { 1784 unsigned PCLabelId = ARMFI->createPICLabelUId(); 1785 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create( 1786 MF.getFunction()->getContext(), "STACK_LIMIT", PCLabelId, 0); 1787 MachineConstantPool *MCP = MF.getConstantPool(); 1788 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment()); 1789 1790 // ldr SR0, [pc, offset(STACK_LIMIT)] 1791 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0) 1792 .addConstantPoolIndex(CPI)); 1793 1794 // ldr SR0, [SR0] 1795 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0) 1796 .addReg(ScratchReg0).addImm(0)); 1797 } else { 1798 // Get TLS base address from the coprocessor 1799 // mrc p15, #0, SR0, c13, c0, #3 1800 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0) 1801 .addImm(15) 1802 .addImm(0) 1803 .addImm(13) 1804 .addImm(0) 1805 .addImm(3)); 1806 1807 // Use the last tls slot on android and a private field of the TCP on linux. 1808 assert(ST->isTargetAndroid() || ST->isTargetLinux()); 1809 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1; 1810 1811 // Get the stack limit from the right offset 1812 // ldr SR0, [sr0, #4 * TlsOffset] 1813 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0) 1814 .addReg(ScratchReg0).addImm(4 * TlsOffset)); 1815 } 1816 1817 // Compare stack limit with stack size requested. 1818 // cmp SR0, SR1 1819 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr; 1820 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode)) 1821 .addReg(ScratchReg0) 1822 .addReg(ScratchReg1)); 1823 1824 // This jump is taken if StackLimit < SP - stack required. 1825 Opcode = Thumb ? ARM::tBcc : ARM::Bcc; 1826 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB) 1827 .addImm(ARMCC::LO) 1828 .addReg(ARM::CPSR); 1829 1830 1831 // Calling __morestack(StackSize, Size of stack arguments). 1832 // __morestack knows that the stack size requested is in SR0(r4) 1833 // and amount size of stack arguments is in SR1(r5). 1834 1835 // Pass first argument for the __morestack by Scratch Register #0. 1836 // The amount size of stack required 1837 if (Thumb) { 1838 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), 1839 ScratchReg0)).addImm(AlignedStackSize)); 1840 } else { 1841 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0) 1842 .addImm(AlignedStackSize)).addReg(0); 1843 } 1844 // Pass second argument for the __morestack by Scratch Register #1. 1845 // The amount size of stack consumed to save function arguments. 1846 if (Thumb) { 1847 AddDefaultPred( 1848 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)) 1849 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))); 1850 } else { 1851 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1) 1852 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))) 1853 .addReg(0); 1854 } 1855 1856 // push {lr} - Save return address of this function. 1857 if (Thumb) { 1858 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))) 1859 .addReg(ARM::LR); 1860 } else { 1861 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD)) 1862 .addReg(ARM::SP, RegState::Define) 1863 .addReg(ARM::SP)) 1864 .addReg(ARM::LR); 1865 } 1866 1867 // Emit the DWARF info about the change in stack as well as where to find the 1868 // previous link register 1869 CFIIndex = 1870 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12)); 1871 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1872 .addCFIIndex(CFIIndex); 1873 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset( 1874 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12)); 1875 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1876 .addCFIIndex(CFIIndex); 1877 1878 // Call __morestack(). 1879 if (Thumb) { 1880 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL))) 1881 .addExternalSymbol("__morestack"); 1882 } else { 1883 BuildMI(AllocMBB, DL, TII.get(ARM::BL)) 1884 .addExternalSymbol("__morestack"); 1885 } 1886 1887 // pop {lr} - Restore return address of this original function. 1888 if (Thumb) { 1889 if (ST->isThumb1Only()) { 1890 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))) 1891 .addReg(ScratchReg0); 1892 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR) 1893 .addReg(ScratchReg0)); 1894 } else { 1895 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST)) 1896 .addReg(ARM::LR, RegState::Define) 1897 .addReg(ARM::SP, RegState::Define) 1898 .addReg(ARM::SP) 1899 .addImm(4)); 1900 } 1901 } else { 1902 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 1903 .addReg(ARM::SP, RegState::Define) 1904 .addReg(ARM::SP)) 1905 .addReg(ARM::LR); 1906 } 1907 1908 // Restore SR0 and SR1 in case of __morestack() was called. 1909 // __morestack() will skip PostStackMBB block so we need to restore 1910 // scratch registers from here. 1911 // pop {SR0, SR1} 1912 if (Thumb) { 1913 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))) 1914 .addReg(ScratchReg0) 1915 .addReg(ScratchReg1); 1916 } else { 1917 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 1918 .addReg(ARM::SP, RegState::Define) 1919 .addReg(ARM::SP)) 1920 .addReg(ScratchReg0) 1921 .addReg(ScratchReg1); 1922 } 1923 1924 // Update the CFA offset now that we've popped 1925 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0)); 1926 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1927 .addCFIIndex(CFIIndex); 1928 1929 // bx lr - Return from this function. 1930 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET; 1931 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode))); 1932 1933 // Restore SR0 and SR1 in case of __morestack() was not called. 1934 // pop {SR0, SR1} 1935 if (Thumb) { 1936 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))) 1937 .addReg(ScratchReg0) 1938 .addReg(ScratchReg1); 1939 } else { 1940 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD)) 1941 .addReg(ARM::SP, RegState::Define) 1942 .addReg(ARM::SP)) 1943 .addReg(ScratchReg0) 1944 .addReg(ScratchReg1); 1945 } 1946 1947 // Update the CFA offset now that we've popped 1948 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0)); 1949 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1950 .addCFIIndex(CFIIndex); 1951 1952 // Tell debuggers that r4 and r5 are now the same as they were in the 1953 // previous function, that they're the "Same Value". 1954 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue( 1955 nullptr, MRI->getDwarfRegNum(ScratchReg0, true))); 1956 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1957 .addCFIIndex(CFIIndex); 1958 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue( 1959 nullptr, MRI->getDwarfRegNum(ScratchReg1, true))); 1960 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1961 .addCFIIndex(CFIIndex); 1962 1963 // Organizing MBB lists 1964 PostStackMBB->addSuccessor(&prologueMBB); 1965 1966 AllocMBB->addSuccessor(PostStackMBB); 1967 1968 GetMBB->addSuccessor(PostStackMBB); 1969 GetMBB->addSuccessor(AllocMBB); 1970 1971 McrMBB->addSuccessor(GetMBB); 1972 1973 PrevStackMBB->addSuccessor(McrMBB); 1974 1975 #ifdef XDEBUG 1976 MF.verify(); 1977 #endif 1978 } 1979