1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the X86 implementation of TargetFrameLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "X86FrameLowering.h" 14 #include "X86InstrBuilder.h" 15 #include "X86InstrInfo.h" 16 #include "X86MachineFunctionInfo.h" 17 #include "X86Subtarget.h" 18 #include "X86TargetMachine.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/EHPersonalities.h" 22 #include "llvm/CodeGen/MachineFrameInfo.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/WinEHFuncInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/MC/MCAsmInfo.h" 31 #include "llvm/MC/MCSymbol.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Target/TargetOptions.h" 34 #include <cstdlib> 35 36 #define DEBUG_TYPE "x86-fl" 37 38 STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue"); 39 STATISTIC(NumFrameExtraProbe, 40 "Number of extra stack probes generated in prologue"); 41 42 using namespace llvm; 43 44 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI, 45 MaybeAlign StackAlignOverride) 46 : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(), 47 STI.is64Bit() ? -8 : -4), 48 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) { 49 // Cache a bunch of frame-related predicates for this subtarget. 50 SlotSize = TRI->getSlotSize(); 51 Is64Bit = STI.is64Bit(); 52 IsLP64 = STI.isTarget64BitLP64(); 53 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. 54 Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64(); 55 StackPtr = TRI->getStackRegister(); 56 } 57 58 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 59 return !MF.getFrameInfo().hasVarSizedObjects() && 60 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences(); 61 } 62 63 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 64 /// call frame pseudos can be simplified. Having a FP, as in the default 65 /// implementation, is not sufficient here since we can't always use it. 66 /// Use a more nuanced condition. 67 bool 68 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 69 return hasReservedCallFrame(MF) || 70 (hasFP(MF) && !TRI->needsStackRealignment(MF)) || 71 TRI->hasBasePointer(MF); 72 } 73 74 // needsFrameIndexResolution - Do we need to perform FI resolution for 75 // this function. Normally, this is required only when the function 76 // has any stack objects. However, FI resolution actually has another job, 77 // not apparent from the title - it resolves callframesetup/destroy 78 // that were not simplified earlier. 79 // So, this is required for x86 functions that have push sequences even 80 // when there are no stack objects. 81 bool 82 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const { 83 return MF.getFrameInfo().hasStackObjects() || 84 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences(); 85 } 86 87 /// hasFP - Return true if the specified function should have a dedicated frame 88 /// pointer register. This is true if the function has variable sized allocas 89 /// or if frame pointer elimination is disabled. 90 bool X86FrameLowering::hasFP(const MachineFunction &MF) const { 91 const MachineFrameInfo &MFI = MF.getFrameInfo(); 92 return (MF.getTarget().Options.DisableFramePointerElim(MF) || 93 TRI->needsStackRealignment(MF) || 94 MFI.hasVarSizedObjects() || 95 MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() || 96 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() || 97 MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() || 98 MFI.hasStackMap() || MFI.hasPatchPoint() || 99 MFI.hasCopyImplyingStackAdjustment()); 100 } 101 102 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) { 103 if (IsLP64) { 104 if (isInt<8>(Imm)) 105 return X86::SUB64ri8; 106 return X86::SUB64ri32; 107 } else { 108 if (isInt<8>(Imm)) 109 return X86::SUB32ri8; 110 return X86::SUB32ri; 111 } 112 } 113 114 static unsigned getADDriOpcode(bool IsLP64, int64_t Imm) { 115 if (IsLP64) { 116 if (isInt<8>(Imm)) 117 return X86::ADD64ri8; 118 return X86::ADD64ri32; 119 } else { 120 if (isInt<8>(Imm)) 121 return X86::ADD32ri8; 122 return X86::ADD32ri; 123 } 124 } 125 126 static unsigned getSUBrrOpcode(bool IsLP64) { 127 return IsLP64 ? X86::SUB64rr : X86::SUB32rr; 128 } 129 130 static unsigned getADDrrOpcode(bool IsLP64) { 131 return IsLP64 ? X86::ADD64rr : X86::ADD32rr; 132 } 133 134 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) { 135 if (IsLP64) { 136 if (isInt<8>(Imm)) 137 return X86::AND64ri8; 138 return X86::AND64ri32; 139 } 140 if (isInt<8>(Imm)) 141 return X86::AND32ri8; 142 return X86::AND32ri; 143 } 144 145 static unsigned getLEArOpcode(bool IsLP64) { 146 return IsLP64 ? X86::LEA64r : X86::LEA32r; 147 } 148 149 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live 150 /// when it reaches the "return" instruction. We can then pop a stack object 151 /// to this register without worry about clobbering it. 152 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB, 153 MachineBasicBlock::iterator &MBBI, 154 const X86RegisterInfo *TRI, 155 bool Is64Bit) { 156 const MachineFunction *MF = MBB.getParent(); 157 if (MF->callsEHReturn()) 158 return 0; 159 160 const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF); 161 162 if (MBBI == MBB.end()) 163 return 0; 164 165 switch (MBBI->getOpcode()) { 166 default: return 0; 167 case TargetOpcode::PATCHABLE_RET: 168 case X86::RET: 169 case X86::RETL: 170 case X86::RETQ: 171 case X86::RETIL: 172 case X86::RETIQ: 173 case X86::TCRETURNdi: 174 case X86::TCRETURNri: 175 case X86::TCRETURNmi: 176 case X86::TCRETURNdi64: 177 case X86::TCRETURNri64: 178 case X86::TCRETURNmi64: 179 case X86::EH_RETURN: 180 case X86::EH_RETURN64: { 181 SmallSet<uint16_t, 8> Uses; 182 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) { 183 MachineOperand &MO = MBBI->getOperand(i); 184 if (!MO.isReg() || MO.isDef()) 185 continue; 186 Register Reg = MO.getReg(); 187 if (!Reg) 188 continue; 189 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 190 Uses.insert(*AI); 191 } 192 193 for (auto CS : AvailableRegs) 194 if (!Uses.count(CS) && CS != X86::RIP && CS != X86::RSP && 195 CS != X86::ESP) 196 return CS; 197 } 198 } 199 200 return 0; 201 } 202 203 static bool isEAXLiveIn(MachineBasicBlock &MBB) { 204 for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) { 205 unsigned Reg = RegMask.PhysReg; 206 207 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX || 208 Reg == X86::AH || Reg == X86::AL) 209 return true; 210 } 211 212 return false; 213 } 214 215 /// Check if the flags need to be preserved before the terminators. 216 /// This would be the case, if the eflags is live-in of the region 217 /// composed by the terminators or live-out of that region, without 218 /// being defined by a terminator. 219 static bool 220 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) { 221 for (const MachineInstr &MI : MBB.terminators()) { 222 bool BreakNext = false; 223 for (const MachineOperand &MO : MI.operands()) { 224 if (!MO.isReg()) 225 continue; 226 Register Reg = MO.getReg(); 227 if (Reg != X86::EFLAGS) 228 continue; 229 230 // This terminator needs an eflags that is not defined 231 // by a previous another terminator: 232 // EFLAGS is live-in of the region composed by the terminators. 233 if (!MO.isDef()) 234 return true; 235 // This terminator defines the eflags, i.e., we don't need to preserve it. 236 // However, we still need to check this specific terminator does not 237 // read a live-in value. 238 BreakNext = true; 239 } 240 // We found a definition of the eflags, no need to preserve them. 241 if (BreakNext) 242 return false; 243 } 244 245 // None of the terminators use or define the eflags. 246 // Check if they are live-out, that would imply we need to preserve them. 247 for (const MachineBasicBlock *Succ : MBB.successors()) 248 if (Succ->isLiveIn(X86::EFLAGS)) 249 return true; 250 251 return false; 252 } 253 254 /// emitSPUpdate - Emit a series of instructions to increment / decrement the 255 /// stack pointer by a constant value. 256 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB, 257 MachineBasicBlock::iterator &MBBI, 258 const DebugLoc &DL, 259 int64_t NumBytes, bool InEpilogue) const { 260 bool isSub = NumBytes < 0; 261 uint64_t Offset = isSub ? -NumBytes : NumBytes; 262 MachineInstr::MIFlag Flag = 263 isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy; 264 265 uint64_t Chunk = (1LL << 31) - 1; 266 267 MachineFunction &MF = *MBB.getParent(); 268 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 269 const X86TargetLowering &TLI = *STI.getTargetLowering(); 270 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF); 271 272 // It's ok to not take into account large chunks when probing, as the 273 // allocation is split in smaller chunks anyway. 274 if (EmitInlineStackProbe && !InEpilogue) { 275 276 // stack probing may involve looping, and control flow generations is 277 // disallowed at this point. Rely to later processing through 278 // `inlineStackProbe`. 279 MachineInstr *Stub = emitStackProbeInlineStub(MF, MBB, MBBI, DL, true); 280 281 // Encode the static offset as a metadata attached to the stub. 282 LLVMContext &Context = MF.getFunction().getContext(); 283 MachineInstrBuilder(MF, Stub).addMetadata( 284 MDTuple::get(Context, {ConstantAsMetadata::get(ConstantInt::get( 285 IntegerType::get(Context, 64), Offset))})); 286 return; 287 } else if (Offset > Chunk) { 288 // Rather than emit a long series of instructions for large offsets, 289 // load the offset into a register and do one sub/add 290 unsigned Reg = 0; 291 unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX); 292 293 if (isSub && !isEAXLiveIn(MBB)) 294 Reg = Rax; 295 else 296 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit); 297 298 unsigned MovRIOpc = Is64Bit ? X86::MOV64ri : X86::MOV32ri; 299 unsigned AddSubRROpc = 300 isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit); 301 if (Reg) { 302 BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Reg) 303 .addImm(Offset) 304 .setMIFlag(Flag); 305 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr) 306 .addReg(StackPtr) 307 .addReg(Reg); 308 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 309 return; 310 } else if (Offset > 8 * Chunk) { 311 // If we would need more than 8 add or sub instructions (a >16GB stack 312 // frame), it's worth spilling RAX to materialize this immediate. 313 // pushq %rax 314 // movabsq +-$Offset+-SlotSize, %rax 315 // addq %rsp, %rax 316 // xchg %rax, (%rsp) 317 // movq (%rsp), %rsp 318 assert(Is64Bit && "can't have 32-bit 16GB stack frame"); 319 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 320 .addReg(Rax, RegState::Kill) 321 .setMIFlag(Flag); 322 // Subtract is not commutative, so negate the offset and always use add. 323 // Subtract 8 less and add 8 more to account for the PUSH we just did. 324 if (isSub) 325 Offset = -(Offset - SlotSize); 326 else 327 Offset = Offset + SlotSize; 328 BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Rax) 329 .addImm(Offset) 330 .setMIFlag(Flag); 331 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax) 332 .addReg(Rax) 333 .addReg(StackPtr); 334 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 335 // Exchange the new SP in RAX with the top of the stack. 336 addRegOffset( 337 BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax), 338 StackPtr, false, 0); 339 // Load new SP from the top of the stack into RSP. 340 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr), 341 StackPtr, false, 0); 342 return; 343 } 344 } 345 346 while (Offset) { 347 uint64_t ThisVal = std::min(Offset, Chunk); 348 if (ThisVal == SlotSize) { 349 // Use push / pop for slot sized adjustments as a size optimization. We 350 // need to find a dead register when using pop. 351 unsigned Reg = isSub 352 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX) 353 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit); 354 if (Reg) { 355 unsigned Opc = isSub 356 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r) 357 : (Is64Bit ? X86::POP64r : X86::POP32r); 358 BuildMI(MBB, MBBI, DL, TII.get(Opc)) 359 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub)) 360 .setMIFlag(Flag); 361 Offset -= ThisVal; 362 continue; 363 } 364 } 365 366 BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue) 367 .setMIFlag(Flag); 368 369 Offset -= ThisVal; 370 } 371 } 372 373 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment( 374 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 375 const DebugLoc &DL, int64_t Offset, bool InEpilogue) const { 376 assert(Offset != 0 && "zero offset stack adjustment requested"); 377 378 // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue 379 // is tricky. 380 bool UseLEA; 381 if (!InEpilogue) { 382 // Check if inserting the prologue at the beginning 383 // of MBB would require to use LEA operations. 384 // We need to use LEA operations if EFLAGS is live in, because 385 // it means an instruction will read it before it gets defined. 386 UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS); 387 } else { 388 // If we can use LEA for SP but we shouldn't, check that none 389 // of the terminators uses the eflags. Otherwise we will insert 390 // a ADD that will redefine the eflags and break the condition. 391 // Alternatively, we could move the ADD, but this may not be possible 392 // and is an optimization anyway. 393 UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent()); 394 if (UseLEA && !STI.useLeaForSP()) 395 UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB); 396 // If that assert breaks, that means we do not do the right thing 397 // in canUseAsEpilogue. 398 assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) && 399 "We shouldn't have allowed this insertion point"); 400 } 401 402 MachineInstrBuilder MI; 403 if (UseLEA) { 404 MI = addRegOffset(BuildMI(MBB, MBBI, DL, 405 TII.get(getLEArOpcode(Uses64BitFramePtr)), 406 StackPtr), 407 StackPtr, false, Offset); 408 } else { 409 bool IsSub = Offset < 0; 410 uint64_t AbsOffset = IsSub ? -Offset : Offset; 411 const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset) 412 : getADDriOpcode(Uses64BitFramePtr, AbsOffset); 413 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr) 414 .addReg(StackPtr) 415 .addImm(AbsOffset); 416 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 417 } 418 return MI; 419 } 420 421 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB, 422 MachineBasicBlock::iterator &MBBI, 423 bool doMergeWithPrevious) const { 424 if ((doMergeWithPrevious && MBBI == MBB.begin()) || 425 (!doMergeWithPrevious && MBBI == MBB.end())) 426 return 0; 427 428 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI; 429 430 PI = skipDebugInstructionsBackward(PI, MBB.begin()); 431 // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI 432 // instruction, and that there are no DBG_VALUE or other instructions between 433 // ADD/SUB/LEA and its corresponding CFI instruction. 434 /* TODO: Add support for the case where there are multiple CFI instructions 435 below the ADD/SUB/LEA, e.g.: 436 ... 437 add 438 cfi_def_cfa_offset 439 cfi_offset 440 ... 441 */ 442 if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction()) 443 PI = std::prev(PI); 444 445 unsigned Opc = PI->getOpcode(); 446 int Offset = 0; 447 448 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 || 449 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) && 450 PI->getOperand(0).getReg() == StackPtr){ 451 assert(PI->getOperand(1).getReg() == StackPtr); 452 Offset = PI->getOperand(2).getImm(); 453 } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) && 454 PI->getOperand(0).getReg() == StackPtr && 455 PI->getOperand(1).getReg() == StackPtr && 456 PI->getOperand(2).getImm() == 1 && 457 PI->getOperand(3).getReg() == X86::NoRegister && 458 PI->getOperand(5).getReg() == X86::NoRegister) { 459 // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg. 460 Offset = PI->getOperand(4).getImm(); 461 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 || 462 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) && 463 PI->getOperand(0).getReg() == StackPtr) { 464 assert(PI->getOperand(1).getReg() == StackPtr); 465 Offset = -PI->getOperand(2).getImm(); 466 } else 467 return 0; 468 469 PI = MBB.erase(PI); 470 if (PI != MBB.end() && PI->isCFIInstruction()) PI = MBB.erase(PI); 471 if (!doMergeWithPrevious) 472 MBBI = skipDebugInstructionsForward(PI, MBB.end()); 473 474 return Offset; 475 } 476 477 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB, 478 MachineBasicBlock::iterator MBBI, 479 const DebugLoc &DL, 480 const MCCFIInstruction &CFIInst) const { 481 MachineFunction &MF = *MBB.getParent(); 482 unsigned CFIIndex = MF.addFrameInst(CFIInst); 483 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 484 .addCFIIndex(CFIIndex); 485 } 486 487 void X86FrameLowering::emitCalleeSavedFrameMoves( 488 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 489 const DebugLoc &DL) const { 490 MachineFunction &MF = *MBB.getParent(); 491 MachineFrameInfo &MFI = MF.getFrameInfo(); 492 MachineModuleInfo &MMI = MF.getMMI(); 493 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo(); 494 495 // Add callee saved registers to move list. 496 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 497 if (CSI.empty()) return; 498 499 // Calculate offsets. 500 for (std::vector<CalleeSavedInfo>::const_iterator 501 I = CSI.begin(), E = CSI.end(); I != E; ++I) { 502 int64_t Offset = MFI.getObjectOffset(I->getFrameIdx()); 503 unsigned Reg = I->getReg(); 504 505 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 506 BuildCFI(MBB, MBBI, DL, 507 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 508 } 509 } 510 511 void X86FrameLowering::emitStackProbe(MachineFunction &MF, 512 MachineBasicBlock &MBB, 513 MachineBasicBlock::iterator MBBI, 514 const DebugLoc &DL, bool InProlog) const { 515 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 516 if (STI.isTargetWindowsCoreCLR()) { 517 if (InProlog) { 518 emitStackProbeInlineStub(MF, MBB, MBBI, DL, true); 519 } else { 520 emitStackProbeInline(MF, MBB, MBBI, DL, false); 521 } 522 } else { 523 emitStackProbeCall(MF, MBB, MBBI, DL, InProlog); 524 } 525 } 526 527 void X86FrameLowering::inlineStackProbe(MachineFunction &MF, 528 MachineBasicBlock &PrologMBB) const { 529 const StringRef ChkStkStubSymbol = "__chkstk_stub"; 530 MachineInstr *ChkStkStub = nullptr; 531 532 for (MachineInstr &MI : PrologMBB) { 533 if (MI.isCall() && MI.getOperand(0).isSymbol() && 534 ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) { 535 ChkStkStub = &MI; 536 break; 537 } 538 } 539 540 if (ChkStkStub != nullptr) { 541 assert(!ChkStkStub->isBundled() && 542 "Not expecting bundled instructions here"); 543 MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator()); 544 assert(std::prev(MBBI) == ChkStkStub && 545 "MBBI expected after __chkstk_stub."); 546 DebugLoc DL = PrologMBB.findDebugLoc(MBBI); 547 emitStackProbeInline(MF, PrologMBB, MBBI, DL, true); 548 ChkStkStub->eraseFromParent(); 549 } 550 } 551 552 void X86FrameLowering::emitStackProbeInline(MachineFunction &MF, 553 MachineBasicBlock &MBB, 554 MachineBasicBlock::iterator MBBI, 555 const DebugLoc &DL, 556 bool InProlog) const { 557 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 558 if (STI.isTargetWindowsCoreCLR() && STI.is64Bit()) 559 emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog); 560 else 561 emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog); 562 } 563 564 void X86FrameLowering::emitStackProbeInlineGeneric( 565 MachineFunction &MF, MachineBasicBlock &MBB, 566 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const { 567 MachineInstr &CallToInline = *std::prev(MBBI); 568 assert(CallToInline.getOperand(1).isMetadata() && 569 "no metadata attached to that probe"); 570 uint64_t Offset = 571 cast<ConstantInt>( 572 cast<ConstantAsMetadata>( 573 cast<MDTuple>(CallToInline.getOperand(1).getMetadata()) 574 ->getOperand(0)) 575 ->getValue()) 576 ->getZExtValue(); 577 578 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 579 const X86TargetLowering &TLI = *STI.getTargetLowering(); 580 assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) && 581 "different expansion expected for CoreCLR 64 bit"); 582 583 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 584 uint64_t ProbeChunk = StackProbeSize * 8; 585 586 // Synthesize a loop or unroll it, depending on the number of iterations. 587 if (Offset > ProbeChunk) { 588 emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset); 589 } else { 590 emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset); 591 } 592 } 593 594 void X86FrameLowering::emitStackProbeInlineGenericBlock( 595 MachineFunction &MF, MachineBasicBlock &MBB, 596 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, 597 uint64_t Offset) const { 598 599 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 600 const X86TargetLowering &TLI = *STI.getTargetLowering(); 601 const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset); 602 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi; 603 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 604 uint64_t CurrentOffset = 0; 605 // 0 Thanks to return address being saved on the stack 606 uint64_t CurrentProbeOffset = 0; 607 608 // For the first N - 1 pages, just probe. I tried to take advantage of 609 // natural probes but it implies much more logic and there was very few 610 // interesting natural probes to interleave. 611 while (CurrentOffset + StackProbeSize < Offset) { 612 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr) 613 .addReg(StackPtr) 614 .addImm(StackProbeSize) 615 .setMIFlag(MachineInstr::FrameSetup); 616 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 617 618 619 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc)) 620 .setMIFlag(MachineInstr::FrameSetup), 621 StackPtr, false, 0) 622 .addImm(0) 623 .setMIFlag(MachineInstr::FrameSetup); 624 NumFrameExtraProbe++; 625 CurrentOffset += StackProbeSize; 626 CurrentProbeOffset += StackProbeSize; 627 } 628 629 uint64_t ChunkSize = Offset - CurrentOffset; 630 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr) 631 .addReg(StackPtr) 632 .addImm(ChunkSize) 633 .setMIFlag(MachineInstr::FrameSetup); 634 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead. 635 } 636 637 void X86FrameLowering::emitStackProbeInlineGenericLoop( 638 MachineFunction &MF, MachineBasicBlock &MBB, 639 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, 640 uint64_t Offset) const { 641 642 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 643 const X86TargetLowering &TLI = *STI.getTargetLowering(); 644 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi; 645 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF); 646 647 // Synthesize a loop 648 NumFrameLoopProbe++; 649 const BasicBlock *LLVM_BB = MBB.getBasicBlock(); 650 651 MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB); 652 MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB); 653 654 MachineFunction::iterator MBBIter = ++MBB.getIterator(); 655 MF.insert(MBBIter, testMBB); 656 MF.insert(MBBIter, tailMBB); 657 658 unsigned FinalStackPtr = Uses64BitFramePtr ? X86::R11 : X86::R11D; 659 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FinalStackPtr) 660 .addReg(StackPtr) 661 .setMIFlag(MachineInstr::FrameSetup); 662 663 // save loop bound 664 { 665 const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset); 666 BuildMI(MBB, MBBI, DL, TII.get(Opc), FinalStackPtr) 667 .addReg(FinalStackPtr) 668 .addImm(Offset / StackProbeSize * StackProbeSize) 669 .setMIFlag(MachineInstr::FrameSetup); 670 } 671 672 // allocate a page 673 { 674 const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, StackProbeSize); 675 BuildMI(testMBB, DL, TII.get(Opc), StackPtr) 676 .addReg(StackPtr) 677 .addImm(StackProbeSize) 678 .setMIFlag(MachineInstr::FrameSetup); 679 } 680 681 // touch the page 682 addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc)) 683 .setMIFlag(MachineInstr::FrameSetup), 684 StackPtr, false, 0) 685 .addImm(0) 686 .setMIFlag(MachineInstr::FrameSetup); 687 688 // cmp with stack pointer bound 689 BuildMI(testMBB, DL, TII.get(IsLP64 ? X86::CMP64rr : X86::CMP32rr)) 690 .addReg(StackPtr) 691 .addReg(FinalStackPtr) 692 .setMIFlag(MachineInstr::FrameSetup); 693 694 // jump 695 BuildMI(testMBB, DL, TII.get(X86::JCC_1)) 696 .addMBB(testMBB) 697 .addImm(X86::COND_NE) 698 .setMIFlag(MachineInstr::FrameSetup); 699 testMBB->addSuccessor(testMBB); 700 testMBB->addSuccessor(tailMBB); 701 testMBB->addLiveIn(FinalStackPtr); 702 703 // allocate a block and touch it 704 705 tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end()); 706 tailMBB->transferSuccessorsAndUpdatePHIs(&MBB); 707 MBB.addSuccessor(testMBB); 708 709 if (Offset % StackProbeSize) { 710 const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset); 711 BuildMI(*tailMBB, tailMBB->begin(), DL, TII.get(Opc), StackPtr) 712 .addReg(StackPtr) 713 .addImm(Offset % StackProbeSize) 714 .setMIFlag(MachineInstr::FrameSetup); 715 } 716 } 717 718 void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64( 719 MachineFunction &MF, MachineBasicBlock &MBB, 720 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const { 721 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>(); 722 assert(STI.is64Bit() && "different expansion needed for 32 bit"); 723 assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR"); 724 const TargetInstrInfo &TII = *STI.getInstrInfo(); 725 const BasicBlock *LLVM_BB = MBB.getBasicBlock(); 726 727 // RAX contains the number of bytes of desired stack adjustment. 728 // The handling here assumes this value has already been updated so as to 729 // maintain stack alignment. 730 // 731 // We need to exit with RSP modified by this amount and execute suitable 732 // page touches to notify the OS that we're growing the stack responsibly. 733 // All stack probing must be done without modifying RSP. 734 // 735 // MBB: 736 // SizeReg = RAX; 737 // ZeroReg = 0 738 // CopyReg = RSP 739 // Flags, TestReg = CopyReg - SizeReg 740 // FinalReg = !Flags.Ovf ? TestReg : ZeroReg 741 // LimitReg = gs magic thread env access 742 // if FinalReg >= LimitReg goto ContinueMBB 743 // RoundBB: 744 // RoundReg = page address of FinalReg 745 // LoopMBB: 746 // LoopReg = PHI(LimitReg,ProbeReg) 747 // ProbeReg = LoopReg - PageSize 748 // [ProbeReg] = 0 749 // if (ProbeReg > RoundReg) goto LoopMBB 750 // ContinueMBB: 751 // RSP = RSP - RAX 752 // [rest of original MBB] 753 754 // Set up the new basic blocks 755 MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB); 756 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 757 MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB); 758 759 MachineFunction::iterator MBBIter = std::next(MBB.getIterator()); 760 MF.insert(MBBIter, RoundMBB); 761 MF.insert(MBBIter, LoopMBB); 762 MF.insert(MBBIter, ContinueMBB); 763 764 // Split MBB and move the tail portion down to ContinueMBB. 765 MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI); 766 ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end()); 767 ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB); 768 769 // Some useful constants 770 const int64_t ThreadEnvironmentStackLimit = 0x10; 771 const int64_t PageSize = 0x1000; 772 const int64_t PageMask = ~(PageSize - 1); 773 774 // Registers we need. For the normal case we use virtual 775 // registers. For the prolog expansion we use RAX, RCX and RDX. 776 MachineRegisterInfo &MRI = MF.getRegInfo(); 777 const TargetRegisterClass *RegClass = &X86::GR64RegClass; 778 const Register SizeReg = InProlog ? X86::RAX 779 : MRI.createVirtualRegister(RegClass), 780 ZeroReg = InProlog ? X86::RCX 781 : MRI.createVirtualRegister(RegClass), 782 CopyReg = InProlog ? X86::RDX 783 : MRI.createVirtualRegister(RegClass), 784 TestReg = InProlog ? X86::RDX 785 : MRI.createVirtualRegister(RegClass), 786 FinalReg = InProlog ? X86::RDX 787 : MRI.createVirtualRegister(RegClass), 788 RoundedReg = InProlog ? X86::RDX 789 : MRI.createVirtualRegister(RegClass), 790 LimitReg = InProlog ? X86::RCX 791 : MRI.createVirtualRegister(RegClass), 792 JoinReg = InProlog ? X86::RCX 793 : MRI.createVirtualRegister(RegClass), 794 ProbeReg = InProlog ? X86::RCX 795 : MRI.createVirtualRegister(RegClass); 796 797 // SP-relative offsets where we can save RCX and RDX. 798 int64_t RCXShadowSlot = 0; 799 int64_t RDXShadowSlot = 0; 800 801 // If inlining in the prolog, save RCX and RDX. 802 if (InProlog) { 803 // Compute the offsets. We need to account for things already 804 // pushed onto the stack at this point: return address, frame 805 // pointer (if used), and callee saves. 806 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 807 const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize(); 808 const bool HasFP = hasFP(MF); 809 810 // Check if we need to spill RCX and/or RDX. 811 // Here we assume that no earlier prologue instruction changes RCX and/or 812 // RDX, so checking the block live-ins is enough. 813 const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX); 814 const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX); 815 int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0); 816 // Assign the initial slot to both registers, then change RDX's slot if both 817 // need to be spilled. 818 if (IsRCXLiveIn) 819 RCXShadowSlot = InitSlot; 820 if (IsRDXLiveIn) 821 RDXShadowSlot = InitSlot; 822 if (IsRDXLiveIn && IsRCXLiveIn) 823 RDXShadowSlot += 8; 824 // Emit the saves if needed. 825 if (IsRCXLiveIn) 826 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false, 827 RCXShadowSlot) 828 .addReg(X86::RCX); 829 if (IsRDXLiveIn) 830 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false, 831 RDXShadowSlot) 832 .addReg(X86::RDX); 833 } else { 834 // Not in the prolog. Copy RAX to a virtual reg. 835 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX); 836 } 837 838 // Add code to MBB to check for overflow and set the new target stack pointer 839 // to zero if so. 840 BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg) 841 .addReg(ZeroReg, RegState::Undef) 842 .addReg(ZeroReg, RegState::Undef); 843 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP); 844 BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg) 845 .addReg(CopyReg) 846 .addReg(SizeReg); 847 BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg) 848 .addReg(TestReg) 849 .addReg(ZeroReg) 850 .addImm(X86::COND_B); 851 852 // FinalReg now holds final stack pointer value, or zero if 853 // allocation would overflow. Compare against the current stack 854 // limit from the thread environment block. Note this limit is the 855 // lowest touched page on the stack, not the point at which the OS 856 // will cause an overflow exception, so this is just an optimization 857 // to avoid unnecessarily touching pages that are below the current 858 // SP but already committed to the stack by the OS. 859 BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg) 860 .addReg(0) 861 .addImm(1) 862 .addReg(0) 863 .addImm(ThreadEnvironmentStackLimit) 864 .addReg(X86::GS); 865 BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg); 866 // Jump if the desired stack pointer is at or above the stack limit. 867 BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE); 868 869 // Add code to roundMBB to round the final stack pointer to a page boundary. 870 RoundMBB->addLiveIn(FinalReg); 871 BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg) 872 .addReg(FinalReg) 873 .addImm(PageMask); 874 BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB); 875 876 // LimitReg now holds the current stack limit, RoundedReg page-rounded 877 // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page 878 // and probe until we reach RoundedReg. 879 if (!InProlog) { 880 BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg) 881 .addReg(LimitReg) 882 .addMBB(RoundMBB) 883 .addReg(ProbeReg) 884 .addMBB(LoopMBB); 885 } 886 887 LoopMBB->addLiveIn(JoinReg); 888 addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg, 889 false, -PageSize); 890 891 // Probe by storing a byte onto the stack. 892 BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi)) 893 .addReg(ProbeReg) 894 .addImm(1) 895 .addReg(0) 896 .addImm(0) 897 .addReg(0) 898 .addImm(0); 899 900 LoopMBB->addLiveIn(RoundedReg); 901 BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr)) 902 .addReg(RoundedReg) 903 .addReg(ProbeReg); 904 BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE); 905 906 MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI(); 907 908 // If in prolog, restore RDX and RCX. 909 if (InProlog) { 910 if (RCXShadowSlot) // It means we spilled RCX in the prologue. 911 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, 912 TII.get(X86::MOV64rm), X86::RCX), 913 X86::RSP, false, RCXShadowSlot); 914 if (RDXShadowSlot) // It means we spilled RDX in the prologue. 915 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, 916 TII.get(X86::MOV64rm), X86::RDX), 917 X86::RSP, false, RDXShadowSlot); 918 } 919 920 // Now that the probing is done, add code to continueMBB to update 921 // the stack pointer for real. 922 ContinueMBB->addLiveIn(SizeReg); 923 BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP) 924 .addReg(X86::RSP) 925 .addReg(SizeReg); 926 927 // Add the control flow edges we need. 928 MBB.addSuccessor(ContinueMBB); 929 MBB.addSuccessor(RoundMBB); 930 RoundMBB->addSuccessor(LoopMBB); 931 LoopMBB->addSuccessor(ContinueMBB); 932 LoopMBB->addSuccessor(LoopMBB); 933 934 // Mark all the instructions added to the prolog as frame setup. 935 if (InProlog) { 936 for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) { 937 BeforeMBBI->setFlag(MachineInstr::FrameSetup); 938 } 939 for (MachineInstr &MI : *RoundMBB) { 940 MI.setFlag(MachineInstr::FrameSetup); 941 } 942 for (MachineInstr &MI : *LoopMBB) { 943 MI.setFlag(MachineInstr::FrameSetup); 944 } 945 for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin(); 946 CMBBI != ContinueMBBI; ++CMBBI) { 947 CMBBI->setFlag(MachineInstr::FrameSetup); 948 } 949 } 950 } 951 952 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF, 953 MachineBasicBlock &MBB, 954 MachineBasicBlock::iterator MBBI, 955 const DebugLoc &DL, 956 bool InProlog) const { 957 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large; 958 959 // FIXME: Add indirect thunk support and remove this. 960 if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls()) 961 report_fatal_error("Emitting stack probe calls on 64-bit with the large " 962 "code model and indirect thunks not yet implemented."); 963 964 unsigned CallOp; 965 if (Is64Bit) 966 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32; 967 else 968 CallOp = X86::CALLpcrel32; 969 970 StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF); 971 972 MachineInstrBuilder CI; 973 MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI); 974 975 // All current stack probes take AX and SP as input, clobber flags, and 976 // preserve all registers. x86_64 probes leave RSP unmodified. 977 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) { 978 // For the large code model, we have to call through a register. Use R11, 979 // as it is scratch in all supported calling conventions. 980 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11) 981 .addExternalSymbol(MF.createExternalSymbolName(Symbol)); 982 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11); 983 } else { 984 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)) 985 .addExternalSymbol(MF.createExternalSymbolName(Symbol)); 986 } 987 988 unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX; 989 unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP; 990 CI.addReg(AX, RegState::Implicit) 991 .addReg(SP, RegState::Implicit) 992 .addReg(AX, RegState::Define | RegState::Implicit) 993 .addReg(SP, RegState::Define | RegState::Implicit) 994 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 995 996 if (STI.isTargetWin64() || !STI.isOSWindows()) { 997 // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves. 998 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp 999 // themselves. They also does not clobber %rax so we can reuse it when 1000 // adjusting %rsp. 1001 // All other platforms do not specify a particular ABI for the stack probe 1002 // function, so we arbitrarily define it to not adjust %esp/%rsp itself. 1003 BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP) 1004 .addReg(SP) 1005 .addReg(AX); 1006 } 1007 1008 if (InProlog) { 1009 // Apply the frame setup flag to all inserted instrs. 1010 for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI) 1011 ExpansionMBBI->setFlag(MachineInstr::FrameSetup); 1012 } 1013 } 1014 1015 MachineInstr *X86FrameLowering::emitStackProbeInlineStub( 1016 MachineFunction &MF, MachineBasicBlock &MBB, 1017 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const { 1018 1019 assert(InProlog && "ChkStkStub called outside prolog!"); 1020 1021 return BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32)) 1022 .addExternalSymbol("__chkstk_stub"); 1023 } 1024 1025 static unsigned calculateSetFPREG(uint64_t SPAdjust) { 1026 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well 1027 // and might require smaller successive adjustments. 1028 const uint64_t Win64MaxSEHOffset = 128; 1029 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset); 1030 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode. 1031 return SEHFrameOffset & -16; 1032 } 1033 1034 // If we're forcing a stack realignment we can't rely on just the frame 1035 // info, we need to know the ABI stack alignment as well in case we 1036 // have a call out. Otherwise just make sure we have some alignment - we'll 1037 // go with the minimum SlotSize. 1038 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const { 1039 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1040 Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment. 1041 Align StackAlign = getStackAlign(); 1042 if (MF.getFunction().hasFnAttribute("stackrealign")) { 1043 if (MFI.hasCalls()) 1044 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign; 1045 else if (MaxAlign < SlotSize) 1046 MaxAlign = Align(SlotSize); 1047 } 1048 return MaxAlign.value(); 1049 } 1050 1051 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB, 1052 MachineBasicBlock::iterator MBBI, 1053 const DebugLoc &DL, unsigned Reg, 1054 uint64_t MaxAlign) const { 1055 uint64_t Val = -MaxAlign; 1056 unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val); 1057 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg) 1058 .addReg(Reg) 1059 .addImm(Val) 1060 .setMIFlag(MachineInstr::FrameSetup); 1061 1062 // The EFLAGS implicit def is dead. 1063 MI->getOperand(3).setIsDead(); 1064 } 1065 1066 bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const { 1067 // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be 1068 // clobbered by any interrupt handler. 1069 assert(&STI == &MF.getSubtarget<X86Subtarget>() && 1070 "MF used frame lowering for wrong subtarget"); 1071 const Function &Fn = MF.getFunction(); 1072 const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv()); 1073 return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone); 1074 } 1075 1076 1077 /// emitPrologue - Push callee-saved registers onto the stack, which 1078 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate 1079 /// space for local variables. Also emit labels used by the exception handler to 1080 /// generate the exception handling frames. 1081 1082 /* 1083 Here's a gist of what gets emitted: 1084 1085 ; Establish frame pointer, if needed 1086 [if needs FP] 1087 push %rbp 1088 .cfi_def_cfa_offset 16 1089 .cfi_offset %rbp, -16 1090 .seh_pushreg %rpb 1091 mov %rsp, %rbp 1092 .cfi_def_cfa_register %rbp 1093 1094 ; Spill general-purpose registers 1095 [for all callee-saved GPRs] 1096 pushq %<reg> 1097 [if not needs FP] 1098 .cfi_def_cfa_offset (offset from RETADDR) 1099 .seh_pushreg %<reg> 1100 1101 ; If the required stack alignment > default stack alignment 1102 ; rsp needs to be re-aligned. This creates a "re-alignment gap" 1103 ; of unknown size in the stack frame. 1104 [if stack needs re-alignment] 1105 and $MASK, %rsp 1106 1107 ; Allocate space for locals 1108 [if target is Windows and allocated space > 4096 bytes] 1109 ; Windows needs special care for allocations larger 1110 ; than one page. 1111 mov $NNN, %rax 1112 call ___chkstk_ms/___chkstk 1113 sub %rax, %rsp 1114 [else] 1115 sub $NNN, %rsp 1116 1117 [if needs FP] 1118 .seh_stackalloc (size of XMM spill slots) 1119 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots 1120 [else] 1121 .seh_stackalloc NNN 1122 1123 ; Spill XMMs 1124 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved, 1125 ; they may get spilled on any platform, if the current function 1126 ; calls @llvm.eh.unwind.init 1127 [if needs FP] 1128 [for all callee-saved XMM registers] 1129 movaps %<xmm reg>, -MMM(%rbp) 1130 [for all callee-saved XMM registers] 1131 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset) 1132 ; i.e. the offset relative to (%rbp - SEHFrameOffset) 1133 [else] 1134 [for all callee-saved XMM registers] 1135 movaps %<xmm reg>, KKK(%rsp) 1136 [for all callee-saved XMM registers] 1137 .seh_savexmm %<xmm reg>, KKK 1138 1139 .seh_endprologue 1140 1141 [if needs base pointer] 1142 mov %rsp, %rbx 1143 [if needs to restore base pointer] 1144 mov %rsp, -MMM(%rbp) 1145 1146 ; Emit CFI info 1147 [if needs FP] 1148 [for all callee-saved registers] 1149 .cfi_offset %<reg>, (offset from %rbp) 1150 [else] 1151 .cfi_def_cfa_offset (offset from RETADDR) 1152 [for all callee-saved registers] 1153 .cfi_offset %<reg>, (offset from %rsp) 1154 1155 Notes: 1156 - .seh directives are emitted only for Windows 64 ABI 1157 - .cv_fpo directives are emitted on win32 when emitting CodeView 1158 - .cfi directives are emitted for all other ABIs 1159 - for 32-bit code, substitute %e?? registers for %r?? 1160 */ 1161 1162 void X86FrameLowering::emitPrologue(MachineFunction &MF, 1163 MachineBasicBlock &MBB) const { 1164 assert(&STI == &MF.getSubtarget<X86Subtarget>() && 1165 "MF used frame lowering for wrong subtarget"); 1166 MachineBasicBlock::iterator MBBI = MBB.begin(); 1167 MachineFrameInfo &MFI = MF.getFrameInfo(); 1168 const Function &Fn = MF.getFunction(); 1169 MachineModuleInfo &MMI = MF.getMMI(); 1170 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 1171 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment. 1172 uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate. 1173 bool IsFunclet = MBB.isEHFuncletEntry(); 1174 EHPersonality Personality = EHPersonality::Unknown; 1175 if (Fn.hasPersonalityFn()) 1176 Personality = classifyEHPersonality(Fn.getPersonalityFn()); 1177 bool FnHasClrFunclet = 1178 MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR; 1179 bool IsClrFunclet = IsFunclet && FnHasClrFunclet; 1180 bool HasFP = hasFP(MF); 1181 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 1182 bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry(); 1183 // FIXME: Emit FPO data for EH funclets. 1184 bool NeedsWinFPO = 1185 !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag(); 1186 bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO; 1187 bool NeedsDwarfCFI = !IsWin64Prologue && MF.needsFrameMoves(); 1188 Register FramePtr = TRI->getFrameRegister(MF); 1189 const Register MachineFramePtr = 1190 STI.isTarget64BitILP32() 1191 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr; 1192 Register BasePtr = TRI->getBaseRegister(); 1193 bool HasWinCFI = false; 1194 1195 // Debug location must be unknown since the first debug location is used 1196 // to determine the end of the prologue. 1197 DebugLoc DL; 1198 1199 // Add RETADDR move area to callee saved frame size. 1200 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta(); 1201 if (TailCallReturnAddrDelta && IsWin64Prologue) 1202 report_fatal_error("Can't handle guaranteed tail call under win64 yet"); 1203 1204 if (TailCallReturnAddrDelta < 0) 1205 X86FI->setCalleeSavedFrameSize( 1206 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta); 1207 1208 const bool EmitStackProbeCall = 1209 STI.getTargetLowering()->hasStackProbeSymbol(MF); 1210 unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF); 1211 1212 // Re-align the stack on 64-bit if the x86-interrupt calling convention is 1213 // used and an error code was pushed, since the x86-64 ABI requires a 16-byte 1214 // stack alignment. 1215 if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit && 1216 Fn.arg_size() == 2) { 1217 StackSize += 8; 1218 MFI.setStackSize(StackSize); 1219 emitSPUpdate(MBB, MBBI, DL, -8, /*InEpilogue=*/false); 1220 } 1221 1222 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf 1223 // function, and use up to 128 bytes of stack space, don't have a frame 1224 // pointer, calls, or dynamic alloca then we do not need to adjust the 1225 // stack pointer (we fit in the Red Zone). We also check that we don't 1226 // push and pop from the stack. 1227 if (has128ByteRedZone(MF) && !TRI->needsStackRealignment(MF) && 1228 !MFI.hasVarSizedObjects() && // No dynamic alloca. 1229 !MFI.adjustsStack() && // No calls. 1230 !EmitStackProbeCall && // No stack probes. 1231 !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop. 1232 !MF.shouldSplitStack()) { // Regular stack 1233 uint64_t MinSize = X86FI->getCalleeSavedFrameSize(); 1234 if (HasFP) MinSize += SlotSize; 1235 X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0); 1236 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0); 1237 MFI.setStackSize(StackSize); 1238 } 1239 1240 // Insert stack pointer adjustment for later moving of return addr. Only 1241 // applies to tail call optimized functions where the callee argument stack 1242 // size is bigger than the callers. 1243 if (TailCallReturnAddrDelta < 0) { 1244 BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta, 1245 /*InEpilogue=*/false) 1246 .setMIFlag(MachineInstr::FrameSetup); 1247 } 1248 1249 // Mapping for machine moves: 1250 // 1251 // DST: VirtualFP AND 1252 // SRC: VirtualFP => DW_CFA_def_cfa_offset 1253 // ELSE => DW_CFA_def_cfa 1254 // 1255 // SRC: VirtualFP AND 1256 // DST: Register => DW_CFA_def_cfa_register 1257 // 1258 // ELSE 1259 // OFFSET < 0 => DW_CFA_offset_extended_sf 1260 // REG < 64 => DW_CFA_offset + Reg 1261 // ELSE => DW_CFA_offset_extended 1262 1263 uint64_t NumBytes = 0; 1264 int stackGrowth = -SlotSize; 1265 1266 // Find the funclet establisher parameter 1267 Register Establisher = X86::NoRegister; 1268 if (IsClrFunclet) 1269 Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX; 1270 else if (IsFunclet) 1271 Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX; 1272 1273 if (IsWin64Prologue && IsFunclet && !IsClrFunclet) { 1274 // Immediately spill establisher into the home slot. 1275 // The runtime cares about this. 1276 // MOV64mr %rdx, 16(%rsp) 1277 unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 1278 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16) 1279 .addReg(Establisher) 1280 .setMIFlag(MachineInstr::FrameSetup); 1281 MBB.addLiveIn(Establisher); 1282 } 1283 1284 if (HasFP) { 1285 assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved"); 1286 1287 // Calculate required stack adjustment. 1288 uint64_t FrameSize = StackSize - SlotSize; 1289 // If required, include space for extra hidden slot for stashing base pointer. 1290 if (X86FI->getRestoreBasePointer()) 1291 FrameSize += SlotSize; 1292 1293 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize(); 1294 1295 // Callee-saved registers are pushed on stack before the stack is realigned. 1296 if (TRI->needsStackRealignment(MF) && !IsWin64Prologue) 1297 NumBytes = alignTo(NumBytes, MaxAlign); 1298 1299 // Save EBP/RBP into the appropriate stack slot. 1300 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r)) 1301 .addReg(MachineFramePtr, RegState::Kill) 1302 .setMIFlag(MachineInstr::FrameSetup); 1303 1304 if (NeedsDwarfCFI) { 1305 // Mark the place where EBP/RBP was saved. 1306 // Define the current CFA rule to use the provided offset. 1307 assert(StackSize); 1308 BuildCFI(MBB, MBBI, DL, 1309 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth)); 1310 1311 // Change the rule for the FramePtr to be an "offset" rule. 1312 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true); 1313 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset( 1314 nullptr, DwarfFramePtr, 2 * stackGrowth)); 1315 } 1316 1317 if (NeedsWinCFI) { 1318 HasWinCFI = true; 1319 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 1320 .addImm(FramePtr) 1321 .setMIFlag(MachineInstr::FrameSetup); 1322 } 1323 1324 if (!IsWin64Prologue && !IsFunclet) { 1325 // Update EBP with the new base value. 1326 BuildMI(MBB, MBBI, DL, 1327 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), 1328 FramePtr) 1329 .addReg(StackPtr) 1330 .setMIFlag(MachineInstr::FrameSetup); 1331 1332 if (NeedsDwarfCFI) { 1333 // Mark effective beginning of when frame pointer becomes valid. 1334 // Define the current CFA to use the EBP/RBP register. 1335 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true); 1336 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister( 1337 nullptr, DwarfFramePtr)); 1338 } 1339 1340 if (NeedsWinFPO) { 1341 // .cv_fpo_setframe $FramePtr 1342 HasWinCFI = true; 1343 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame)) 1344 .addImm(FramePtr) 1345 .addImm(0) 1346 .setMIFlag(MachineInstr::FrameSetup); 1347 } 1348 } 1349 } else { 1350 assert(!IsFunclet && "funclets without FPs not yet implemented"); 1351 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize(); 1352 } 1353 1354 // Update the offset adjustment, which is mainly used by codeview to translate 1355 // from ESP to VFRAME relative local variable offsets. 1356 if (!IsFunclet) { 1357 if (HasFP && TRI->needsStackRealignment(MF)) 1358 MFI.setOffsetAdjustment(-NumBytes); 1359 else 1360 MFI.setOffsetAdjustment(-StackSize); 1361 } 1362 1363 // For EH funclets, only allocate enough space for outgoing calls. Save the 1364 // NumBytes value that we would've used for the parent frame. 1365 unsigned ParentFrameNumBytes = NumBytes; 1366 if (IsFunclet) 1367 NumBytes = getWinEHFuncletFrameSize(MF); 1368 1369 // Skip the callee-saved push instructions. 1370 bool PushedRegs = false; 1371 int StackOffset = 2 * stackGrowth; 1372 1373 while (MBBI != MBB.end() && 1374 MBBI->getFlag(MachineInstr::FrameSetup) && 1375 (MBBI->getOpcode() == X86::PUSH32r || 1376 MBBI->getOpcode() == X86::PUSH64r)) { 1377 PushedRegs = true; 1378 Register Reg = MBBI->getOperand(0).getReg(); 1379 ++MBBI; 1380 1381 if (!HasFP && NeedsDwarfCFI) { 1382 // Mark callee-saved push instruction. 1383 // Define the current CFA rule to use the provided offset. 1384 assert(StackSize); 1385 BuildCFI(MBB, MBBI, DL, 1386 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset)); 1387 StackOffset += stackGrowth; 1388 } 1389 1390 if (NeedsWinCFI) { 1391 HasWinCFI = true; 1392 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)) 1393 .addImm(Reg) 1394 .setMIFlag(MachineInstr::FrameSetup); 1395 } 1396 } 1397 1398 // Realign stack after we pushed callee-saved registers (so that we'll be 1399 // able to calculate their offsets from the frame pointer). 1400 // Don't do this for Win64, it needs to realign the stack after the prologue. 1401 if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) { 1402 assert(HasFP && "There should be a frame pointer if stack is realigned."); 1403 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign); 1404 1405 if (NeedsWinCFI) { 1406 HasWinCFI = true; 1407 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign)) 1408 .addImm(MaxAlign) 1409 .setMIFlag(MachineInstr::FrameSetup); 1410 } 1411 } 1412 1413 // If there is an SUB32ri of ESP immediately before this instruction, merge 1414 // the two. This can be the case when tail call elimination is enabled and 1415 // the callee has more arguments then the caller. 1416 NumBytes -= mergeSPUpdates(MBB, MBBI, true); 1417 1418 // Adjust stack pointer: ESP -= numbytes. 1419 1420 // Windows and cygwin/mingw require a prologue helper routine when allocating 1421 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw 1422 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the 1423 // stack and adjust the stack pointer in one go. The 64-bit version of 1424 // __chkstk is only responsible for probing the stack. The 64-bit prologue is 1425 // responsible for adjusting the stack pointer. Touching the stack at 4K 1426 // increments is necessary to ensure that the guard pages used by the OS 1427 // virtual memory manager are allocated in correct sequence. 1428 uint64_t AlignedNumBytes = NumBytes; 1429 if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) 1430 AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign); 1431 if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) { 1432 assert(!X86FI->getUsesRedZone() && 1433 "The Red Zone is not accounted for in stack probes"); 1434 1435 // Check whether EAX is livein for this block. 1436 bool isEAXAlive = isEAXLiveIn(MBB); 1437 1438 if (isEAXAlive) { 1439 if (Is64Bit) { 1440 // Save RAX 1441 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r)) 1442 .addReg(X86::RAX, RegState::Kill) 1443 .setMIFlag(MachineInstr::FrameSetup); 1444 } else { 1445 // Save EAX 1446 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r)) 1447 .addReg(X86::EAX, RegState::Kill) 1448 .setMIFlag(MachineInstr::FrameSetup); 1449 } 1450 } 1451 1452 if (Is64Bit) { 1453 // Handle the 64-bit Windows ABI case where we need to call __chkstk. 1454 // Function prologue is responsible for adjusting the stack pointer. 1455 int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes; 1456 if (isUInt<32>(Alloc)) { 1457 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) 1458 .addImm(Alloc) 1459 .setMIFlag(MachineInstr::FrameSetup); 1460 } else if (isInt<32>(Alloc)) { 1461 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX) 1462 .addImm(Alloc) 1463 .setMIFlag(MachineInstr::FrameSetup); 1464 } else { 1465 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX) 1466 .addImm(Alloc) 1467 .setMIFlag(MachineInstr::FrameSetup); 1468 } 1469 } else { 1470 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive. 1471 // We'll also use 4 already allocated bytes for EAX. 1472 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) 1473 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes) 1474 .setMIFlag(MachineInstr::FrameSetup); 1475 } 1476 1477 // Call __chkstk, __chkstk_ms, or __alloca. 1478 emitStackProbe(MF, MBB, MBBI, DL, true); 1479 1480 if (isEAXAlive) { 1481 // Restore RAX/EAX 1482 MachineInstr *MI; 1483 if (Is64Bit) 1484 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX), 1485 StackPtr, false, NumBytes - 8); 1486 else 1487 MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX), 1488 StackPtr, false, NumBytes - 4); 1489 MI->setFlag(MachineInstr::FrameSetup); 1490 MBB.insert(MBBI, MI); 1491 } 1492 } else if (NumBytes) { 1493 emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false); 1494 } 1495 1496 if (NeedsWinCFI && NumBytes) { 1497 HasWinCFI = true; 1498 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc)) 1499 .addImm(NumBytes) 1500 .setMIFlag(MachineInstr::FrameSetup); 1501 } 1502 1503 int SEHFrameOffset = 0; 1504 unsigned SPOrEstablisher; 1505 if (IsFunclet) { 1506 if (IsClrFunclet) { 1507 // The establisher parameter passed to a CLR funclet is actually a pointer 1508 // to the (mostly empty) frame of its nearest enclosing funclet; we have 1509 // to find the root function establisher frame by loading the PSPSym from 1510 // the intermediate frame. 1511 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF); 1512 MachinePointerInfo NoInfo; 1513 MBB.addLiveIn(Establisher); 1514 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher), 1515 Establisher, false, PSPSlotOffset) 1516 .addMemOperand(MF.getMachineMemOperand( 1517 NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize))); 1518 ; 1519 // Save the root establisher back into the current funclet's (mostly 1520 // empty) frame, in case a sub-funclet or the GC needs it. 1521 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, 1522 false, PSPSlotOffset) 1523 .addReg(Establisher) 1524 .addMemOperand(MF.getMachineMemOperand( 1525 NoInfo, 1526 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 1527 SlotSize, Align(SlotSize))); 1528 } 1529 SPOrEstablisher = Establisher; 1530 } else { 1531 SPOrEstablisher = StackPtr; 1532 } 1533 1534 if (IsWin64Prologue && HasFP) { 1535 // Set RBP to a small fixed offset from RSP. In the funclet case, we base 1536 // this calculation on the incoming establisher, which holds the value of 1537 // RSP from the parent frame at the end of the prologue. 1538 SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes); 1539 if (SEHFrameOffset) 1540 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr), 1541 SPOrEstablisher, false, SEHFrameOffset); 1542 else 1543 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr) 1544 .addReg(SPOrEstablisher); 1545 1546 // If this is not a funclet, emit the CFI describing our frame pointer. 1547 if (NeedsWinCFI && !IsFunclet) { 1548 assert(!NeedsWinFPO && "this setframe incompatible with FPO data"); 1549 HasWinCFI = true; 1550 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame)) 1551 .addImm(FramePtr) 1552 .addImm(SEHFrameOffset) 1553 .setMIFlag(MachineInstr::FrameSetup); 1554 if (isAsynchronousEHPersonality(Personality)) 1555 MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset; 1556 } 1557 } else if (IsFunclet && STI.is32Bit()) { 1558 // Reset EBP / ESI to something good for funclets. 1559 MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL); 1560 // If we're a catch funclet, we can be returned to via catchret. Save ESP 1561 // into the registration node so that the runtime will restore it for us. 1562 if (!MBB.isCleanupFuncletEntry()) { 1563 assert(Personality == EHPersonality::MSVC_CXX); 1564 Register FrameReg; 1565 int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex; 1566 int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg); 1567 // ESP is the first field, so no extra displacement is needed. 1568 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg, 1569 false, EHRegOffset) 1570 .addReg(X86::ESP); 1571 } 1572 } 1573 1574 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) { 1575 const MachineInstr &FrameInstr = *MBBI; 1576 ++MBBI; 1577 1578 if (NeedsWinCFI) { 1579 int FI; 1580 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) { 1581 if (X86::FR64RegClass.contains(Reg)) { 1582 int Offset; 1583 Register IgnoredFrameReg; 1584 if (IsWin64Prologue && IsFunclet) 1585 Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg); 1586 else 1587 Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg) + 1588 SEHFrameOffset; 1589 1590 HasWinCFI = true; 1591 assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data"); 1592 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM)) 1593 .addImm(Reg) 1594 .addImm(Offset) 1595 .setMIFlag(MachineInstr::FrameSetup); 1596 } 1597 } 1598 } 1599 } 1600 1601 if (NeedsWinCFI && HasWinCFI) 1602 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue)) 1603 .setMIFlag(MachineInstr::FrameSetup); 1604 1605 if (FnHasClrFunclet && !IsFunclet) { 1606 // Save the so-called Initial-SP (i.e. the value of the stack pointer 1607 // immediately after the prolog) into the PSPSlot so that funclets 1608 // and the GC can recover it. 1609 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF); 1610 auto PSPInfo = MachinePointerInfo::getFixedStack( 1611 MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx); 1612 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false, 1613 PSPSlotOffset) 1614 .addReg(StackPtr) 1615 .addMemOperand(MF.getMachineMemOperand( 1616 PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 1617 SlotSize, Align(SlotSize))); 1618 } 1619 1620 // Realign stack after we spilled callee-saved registers (so that we'll be 1621 // able to calculate their offsets from the frame pointer). 1622 // Win64 requires aligning the stack after the prologue. 1623 if (IsWin64Prologue && TRI->needsStackRealignment(MF)) { 1624 assert(HasFP && "There should be a frame pointer if stack is realigned."); 1625 BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign); 1626 } 1627 1628 // We already dealt with stack realignment and funclets above. 1629 if (IsFunclet && STI.is32Bit()) 1630 return; 1631 1632 // If we need a base pointer, set it up here. It's whatever the value 1633 // of the stack pointer is at this point. Any variable size objects 1634 // will be allocated after this, so we can still use the base pointer 1635 // to reference locals. 1636 if (TRI->hasBasePointer(MF)) { 1637 // Update the base pointer with the current stack pointer. 1638 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr; 1639 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr) 1640 .addReg(SPOrEstablisher) 1641 .setMIFlag(MachineInstr::FrameSetup); 1642 if (X86FI->getRestoreBasePointer()) { 1643 // Stash value of base pointer. Saving RSP instead of EBP shortens 1644 // dependence chain. Used by SjLj EH. 1645 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 1646 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), 1647 FramePtr, true, X86FI->getRestoreBasePointerOffset()) 1648 .addReg(SPOrEstablisher) 1649 .setMIFlag(MachineInstr::FrameSetup); 1650 } 1651 1652 if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) { 1653 // Stash the value of the frame pointer relative to the base pointer for 1654 // Win32 EH. This supports Win32 EH, which does the inverse of the above: 1655 // it recovers the frame pointer from the base pointer rather than the 1656 // other way around. 1657 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr; 1658 Register UsedReg; 1659 int Offset = 1660 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg); 1661 assert(UsedReg == BasePtr); 1662 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset) 1663 .addReg(FramePtr) 1664 .setMIFlag(MachineInstr::FrameSetup); 1665 } 1666 } 1667 1668 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) { 1669 // Mark end of stack pointer adjustment. 1670 if (!HasFP && NumBytes) { 1671 // Define the current CFA rule to use the provided offset. 1672 assert(StackSize); 1673 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset( 1674 nullptr, -StackSize + stackGrowth)); 1675 } 1676 1677 // Emit DWARF info specifying the offsets of the callee-saved registers. 1678 emitCalleeSavedFrameMoves(MBB, MBBI, DL); 1679 } 1680 1681 // X86 Interrupt handling function cannot assume anything about the direction 1682 // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction 1683 // in each prologue of interrupt handler function. 1684 // 1685 // FIXME: Create "cld" instruction only in these cases: 1686 // 1. The interrupt handling function uses any of the "rep" instructions. 1687 // 2. Interrupt handling function calls another function. 1688 // 1689 if (Fn.getCallingConv() == CallingConv::X86_INTR) 1690 BuildMI(MBB, MBBI, DL, TII.get(X86::CLD)) 1691 .setMIFlag(MachineInstr::FrameSetup); 1692 1693 // At this point we know if the function has WinCFI or not. 1694 MF.setHasWinCFI(HasWinCFI); 1695 } 1696 1697 bool X86FrameLowering::canUseLEAForSPInEpilogue( 1698 const MachineFunction &MF) const { 1699 // We can't use LEA instructions for adjusting the stack pointer if we don't 1700 // have a frame pointer in the Win64 ABI. Only ADD instructions may be used 1701 // to deallocate the stack. 1702 // This means that we can use LEA for SP in two situations: 1703 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA. 1704 // 2. We *have* a frame pointer which means we are permitted to use LEA. 1705 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF); 1706 } 1707 1708 static bool isFuncletReturnInstr(MachineInstr &MI) { 1709 switch (MI.getOpcode()) { 1710 case X86::CATCHRET: 1711 case X86::CLEANUPRET: 1712 return true; 1713 default: 1714 return false; 1715 } 1716 llvm_unreachable("impossible"); 1717 } 1718 1719 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the 1720 // stack. It holds a pointer to the bottom of the root function frame. The 1721 // establisher frame pointer passed to a nested funclet may point to the 1722 // (mostly empty) frame of its parent funclet, but it will need to find 1723 // the frame of the root function to access locals. To facilitate this, 1724 // every funclet copies the pointer to the bottom of the root function 1725 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the 1726 // same offset for the PSPSym in the root function frame that's used in the 1727 // funclets' frames allows each funclet to dynamically accept any ancestor 1728 // frame as its establisher argument (the runtime doesn't guarantee the 1729 // immediate parent for some reason lost to history), and also allows the GC, 1730 // which uses the PSPSym for some bookkeeping, to find it in any funclet's 1731 // frame with only a single offset reported for the entire method. 1732 unsigned 1733 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const { 1734 const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo(); 1735 Register SPReg; 1736 int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg, 1737 /*IgnoreSPUpdates*/ true); 1738 assert(Offset >= 0 && SPReg == TRI->getStackRegister()); 1739 return static_cast<unsigned>(Offset); 1740 } 1741 1742 unsigned 1743 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const { 1744 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 1745 // This is the size of the pushed CSRs. 1746 unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 1747 // This is the size of callee saved XMMs. 1748 const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 1749 unsigned XMMSize = WinEHXMMSlotInfo.size() * 1750 TRI->getSpillSize(X86::VR128RegClass); 1751 // This is the amount of stack a funclet needs to allocate. 1752 unsigned UsedSize; 1753 EHPersonality Personality = 1754 classifyEHPersonality(MF.getFunction().getPersonalityFn()); 1755 if (Personality == EHPersonality::CoreCLR) { 1756 // CLR funclets need to hold enough space to include the PSPSym, at the 1757 // same offset from the stack pointer (immediately after the prolog) as it 1758 // resides at in the main function. 1759 UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize; 1760 } else { 1761 // Other funclets just need enough stack for outgoing call arguments. 1762 UsedSize = MF.getFrameInfo().getMaxCallFrameSize(); 1763 } 1764 // RBP is not included in the callee saved register block. After pushing RBP, 1765 // everything is 16 byte aligned. Everything we allocate before an outgoing 1766 // call must also be 16 byte aligned. 1767 unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign()); 1768 // Subtract out the size of the callee saved registers. This is how much stack 1769 // each funclet will allocate. 1770 return FrameSizeMinusRBP + XMMSize - CSSize; 1771 } 1772 1773 static bool isTailCallOpcode(unsigned Opc) { 1774 return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi || 1775 Opc == X86::TCRETURNmi || 1776 Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 || 1777 Opc == X86::TCRETURNmi64; 1778 } 1779 1780 void X86FrameLowering::emitEpilogue(MachineFunction &MF, 1781 MachineBasicBlock &MBB) const { 1782 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1783 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 1784 MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator(); 1785 MachineBasicBlock::iterator MBBI = Terminator; 1786 DebugLoc DL; 1787 if (MBBI != MBB.end()) 1788 DL = MBBI->getDebugLoc(); 1789 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit. 1790 const bool Is64BitILP32 = STI.isTarget64BitILP32(); 1791 Register FramePtr = TRI->getFrameRegister(MF); 1792 unsigned MachineFramePtr = 1793 Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr; 1794 1795 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 1796 bool NeedsWin64CFI = 1797 IsWin64Prologue && MF.getFunction().needsUnwindTableEntry(); 1798 bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI); 1799 1800 // Get the number of bytes to allocate from the FrameInfo. 1801 uint64_t StackSize = MFI.getStackSize(); 1802 uint64_t MaxAlign = calculateMaxStackAlign(MF); 1803 unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 1804 bool HasFP = hasFP(MF); 1805 uint64_t NumBytes = 0; 1806 1807 bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() && 1808 !MF.getTarget().getTargetTriple().isOSWindows()) && 1809 MF.needsFrameMoves(); 1810 1811 if (IsFunclet) { 1812 assert(HasFP && "EH funclets without FP not yet implemented"); 1813 NumBytes = getWinEHFuncletFrameSize(MF); 1814 } else if (HasFP) { 1815 // Calculate required stack adjustment. 1816 uint64_t FrameSize = StackSize - SlotSize; 1817 NumBytes = FrameSize - CSSize; 1818 1819 // Callee-saved registers were pushed on stack before the stack was 1820 // realigned. 1821 if (TRI->needsStackRealignment(MF) && !IsWin64Prologue) 1822 NumBytes = alignTo(FrameSize, MaxAlign); 1823 } else { 1824 NumBytes = StackSize - CSSize; 1825 } 1826 uint64_t SEHStackAllocAmt = NumBytes; 1827 1828 if (HasFP) { 1829 // Pop EBP. 1830 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r), 1831 MachineFramePtr) 1832 .setMIFlag(MachineInstr::FrameDestroy); 1833 if (NeedsDwarfCFI) { 1834 unsigned DwarfStackPtr = 1835 TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true); 1836 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfa( 1837 nullptr, DwarfStackPtr, -SlotSize)); 1838 --MBBI; 1839 } 1840 } 1841 1842 MachineBasicBlock::iterator FirstCSPop = MBBI; 1843 // Skip the callee-saved pop instructions. 1844 while (MBBI != MBB.begin()) { 1845 MachineBasicBlock::iterator PI = std::prev(MBBI); 1846 unsigned Opc = PI->getOpcode(); 1847 1848 if (Opc != X86::DBG_VALUE && !PI->isTerminator()) { 1849 if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) && 1850 (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy))) 1851 break; 1852 FirstCSPop = PI; 1853 } 1854 1855 --MBBI; 1856 } 1857 MBBI = FirstCSPop; 1858 1859 if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET) 1860 emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator); 1861 1862 if (MBBI != MBB.end()) 1863 DL = MBBI->getDebugLoc(); 1864 1865 // If there is an ADD32ri or SUB32ri of ESP immediately before this 1866 // instruction, merge the two instructions. 1867 if (NumBytes || MFI.hasVarSizedObjects()) 1868 NumBytes += mergeSPUpdates(MBB, MBBI, true); 1869 1870 // If dynamic alloca is used, then reset esp to point to the last callee-saved 1871 // slot before popping them off! Same applies for the case, when stack was 1872 // realigned. Don't do this if this was a funclet epilogue, since the funclets 1873 // will not do realignment or dynamic stack allocation. 1874 if ((TRI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) && 1875 !IsFunclet) { 1876 if (TRI->needsStackRealignment(MF)) 1877 MBBI = FirstCSPop; 1878 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt); 1879 uint64_t LEAAmount = 1880 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize; 1881 1882 // There are only two legal forms of epilogue: 1883 // - add SEHAllocationSize, %rsp 1884 // - lea SEHAllocationSize(%FramePtr), %rsp 1885 // 1886 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence. 1887 // However, we may use this sequence if we have a frame pointer because the 1888 // effects of the prologue can safely be undone. 1889 if (LEAAmount != 0) { 1890 unsigned Opc = getLEArOpcode(Uses64BitFramePtr); 1891 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr), 1892 FramePtr, false, LEAAmount); 1893 --MBBI; 1894 } else { 1895 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr); 1896 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr) 1897 .addReg(FramePtr); 1898 --MBBI; 1899 } 1900 } else if (NumBytes) { 1901 // Adjust stack pointer back: ESP += numbytes. 1902 emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true); 1903 if (!hasFP(MF) && NeedsDwarfCFI) { 1904 // Define the current CFA rule to use the provided offset. 1905 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset( 1906 nullptr, -CSSize - SlotSize)); 1907 } 1908 --MBBI; 1909 } 1910 1911 // Windows unwinder will not invoke function's exception handler if IP is 1912 // either in prologue or in epilogue. This behavior causes a problem when a 1913 // call immediately precedes an epilogue, because the return address points 1914 // into the epilogue. To cope with that, we insert an epilogue marker here, 1915 // then replace it with a 'nop' if it ends up immediately after a CALL in the 1916 // final emitted code. 1917 if (NeedsWin64CFI && MF.hasWinCFI()) 1918 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue)); 1919 1920 if (!hasFP(MF) && NeedsDwarfCFI) { 1921 MBBI = FirstCSPop; 1922 int64_t Offset = -CSSize - SlotSize; 1923 // Mark callee-saved pop instruction. 1924 // Define the current CFA rule to use the provided offset. 1925 while (MBBI != MBB.end()) { 1926 MachineBasicBlock::iterator PI = MBBI; 1927 unsigned Opc = PI->getOpcode(); 1928 ++MBBI; 1929 if (Opc == X86::POP32r || Opc == X86::POP64r) { 1930 Offset += SlotSize; 1931 BuildCFI(MBB, MBBI, DL, 1932 MCCFIInstruction::createDefCfaOffset(nullptr, Offset)); 1933 } 1934 } 1935 } 1936 1937 if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) { 1938 // Add the return addr area delta back since we are not tail calling. 1939 int Offset = -1 * X86FI->getTCReturnAddrDelta(); 1940 assert(Offset >= 0 && "TCDelta should never be positive"); 1941 if (Offset) { 1942 // Check for possible merge with preceding ADD instruction. 1943 Offset += mergeSPUpdates(MBB, Terminator, true); 1944 emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true); 1945 } 1946 } 1947 } 1948 1949 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, 1950 Register &FrameReg) const { 1951 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1952 1953 bool IsFixed = MFI.isFixedObjectIndex(FI); 1954 // We can't calculate offset from frame pointer if the stack is realigned, 1955 // so enforce usage of stack/base pointer. The base pointer is used when we 1956 // have dynamic allocas in addition to dynamic realignment. 1957 if (TRI->hasBasePointer(MF)) 1958 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister(); 1959 else if (TRI->needsStackRealignment(MF)) 1960 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister(); 1961 else 1962 FrameReg = TRI->getFrameRegister(MF); 1963 1964 // Offset will hold the offset from the stack pointer at function entry to the 1965 // object. 1966 // We need to factor in additional offsets applied during the prologue to the 1967 // frame, base, and stack pointer depending on which is used. 1968 int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea(); 1969 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 1970 unsigned CSSize = X86FI->getCalleeSavedFrameSize(); 1971 uint64_t StackSize = MFI.getStackSize(); 1972 bool HasFP = hasFP(MF); 1973 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 1974 int64_t FPDelta = 0; 1975 1976 // In an x86 interrupt, remove the offset we added to account for the return 1977 // address from any stack object allocated in the caller's frame. Interrupts 1978 // do not have a standard return address. Fixed objects in the current frame, 1979 // such as SSE register spills, should not get this treatment. 1980 if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR && 1981 Offset >= 0) { 1982 Offset += getOffsetOfLocalArea(); 1983 } 1984 1985 if (IsWin64Prologue) { 1986 assert(!MFI.hasCalls() || (StackSize % 16) == 8); 1987 1988 // Calculate required stack adjustment. 1989 uint64_t FrameSize = StackSize - SlotSize; 1990 // If required, include space for extra hidden slot for stashing base pointer. 1991 if (X86FI->getRestoreBasePointer()) 1992 FrameSize += SlotSize; 1993 uint64_t NumBytes = FrameSize - CSSize; 1994 1995 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes); 1996 if (FI && FI == X86FI->getFAIndex()) 1997 return -SEHFrameOffset; 1998 1999 // FPDelta is the offset from the "traditional" FP location of the old base 2000 // pointer followed by return address and the location required by the 2001 // restricted Win64 prologue. 2002 // Add FPDelta to all offsets below that go through the frame pointer. 2003 FPDelta = FrameSize - SEHFrameOffset; 2004 assert((!MFI.hasCalls() || (FPDelta % 16) == 0) && 2005 "FPDelta isn't aligned per the Win64 ABI!"); 2006 } 2007 2008 2009 if (TRI->hasBasePointer(MF)) { 2010 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!"); 2011 if (FI < 0) { 2012 // Skip the saved EBP. 2013 return Offset + SlotSize + FPDelta; 2014 } else { 2015 assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize))); 2016 return Offset + StackSize; 2017 } 2018 } else if (TRI->needsStackRealignment(MF)) { 2019 if (FI < 0) { 2020 // Skip the saved EBP. 2021 return Offset + SlotSize + FPDelta; 2022 } else { 2023 assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize))); 2024 return Offset + StackSize; 2025 } 2026 // FIXME: Support tail calls 2027 } else { 2028 if (!HasFP) 2029 return Offset + StackSize; 2030 2031 // Skip the saved EBP. 2032 Offset += SlotSize; 2033 2034 // Skip the RETADDR move area 2035 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta(); 2036 if (TailCallReturnAddrDelta < 0) 2037 Offset -= TailCallReturnAddrDelta; 2038 } 2039 2040 return Offset + FPDelta; 2041 } 2042 2043 int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI, 2044 Register &FrameReg) const { 2045 const MachineFrameInfo &MFI = MF.getFrameInfo(); 2046 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 2047 const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 2048 const auto it = WinEHXMMSlotInfo.find(FI); 2049 2050 if (it == WinEHXMMSlotInfo.end()) 2051 return getFrameIndexReference(MF, FI, FrameReg); 2052 2053 FrameReg = TRI->getStackRegister(); 2054 return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) + 2055 it->second; 2056 } 2057 2058 int X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, 2059 int FI, Register &FrameReg, 2060 int Adjustment) const { 2061 const MachineFrameInfo &MFI = MF.getFrameInfo(); 2062 FrameReg = TRI->getStackRegister(); 2063 return MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + Adjustment; 2064 } 2065 2066 int X86FrameLowering::getFrameIndexReferencePreferSP( 2067 const MachineFunction &MF, int FI, Register &FrameReg, 2068 bool IgnoreSPUpdates) const { 2069 2070 const MachineFrameInfo &MFI = MF.getFrameInfo(); 2071 // Does not include any dynamic realign. 2072 const uint64_t StackSize = MFI.getStackSize(); 2073 // LLVM arranges the stack as follows: 2074 // ... 2075 // ARG2 2076 // ARG1 2077 // RETADDR 2078 // PUSH RBP <-- RBP points here 2079 // PUSH CSRs 2080 // ~~~~~~~ <-- possible stack realignment (non-win64) 2081 // ... 2082 // STACK OBJECTS 2083 // ... <-- RSP after prologue points here 2084 // ~~~~~~~ <-- possible stack realignment (win64) 2085 // 2086 // if (hasVarSizedObjects()): 2087 // ... <-- "base pointer" (ESI/RBX) points here 2088 // DYNAMIC ALLOCAS 2089 // ... <-- RSP points here 2090 // 2091 // Case 1: In the simple case of no stack realignment and no dynamic 2092 // allocas, both "fixed" stack objects (arguments and CSRs) are addressable 2093 // with fixed offsets from RSP. 2094 // 2095 // Case 2: In the case of stack realignment with no dynamic allocas, fixed 2096 // stack objects are addressed with RBP and regular stack objects with RSP. 2097 // 2098 // Case 3: In the case of dynamic allocas and stack realignment, RSP is used 2099 // to address stack arguments for outgoing calls and nothing else. The "base 2100 // pointer" points to local variables, and RBP points to fixed objects. 2101 // 2102 // In cases 2 and 3, we can only answer for non-fixed stack objects, and the 2103 // answer we give is relative to the SP after the prologue, and not the 2104 // SP in the middle of the function. 2105 2106 if (MFI.isFixedObjectIndex(FI) && TRI->needsStackRealignment(MF) && 2107 !STI.isTargetWin64()) 2108 return getFrameIndexReference(MF, FI, FrameReg); 2109 2110 // If !hasReservedCallFrame the function might have SP adjustement in the 2111 // body. So, even though the offset is statically known, it depends on where 2112 // we are in the function. 2113 if (!IgnoreSPUpdates && !hasReservedCallFrame(MF)) 2114 return getFrameIndexReference(MF, FI, FrameReg); 2115 2116 // We don't handle tail calls, and shouldn't be seeing them either. 2117 assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 && 2118 "we don't handle this case!"); 2119 2120 // This is how the math works out: 2121 // 2122 // %rsp grows (i.e. gets lower) left to right. Each box below is 2123 // one word (eight bytes). Obj0 is the stack slot we're trying to 2124 // get to. 2125 // 2126 // ---------------------------------- 2127 // | BP | Obj0 | Obj1 | ... | ObjN | 2128 // ---------------------------------- 2129 // ^ ^ ^ ^ 2130 // A B C E 2131 // 2132 // A is the incoming stack pointer. 2133 // (B - A) is the local area offset (-8 for x86-64) [1] 2134 // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2] 2135 // 2136 // |(E - B)| is the StackSize (absolute value, positive). For a 2137 // stack that grown down, this works out to be (B - E). [3] 2138 // 2139 // E is also the value of %rsp after stack has been set up, and we 2140 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now 2141 // (C - E) == (C - A) - (B - A) + (B - E) 2142 // { Using [1], [2] and [3] above } 2143 // == getObjectOffset - LocalAreaOffset + StackSize 2144 2145 return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize); 2146 } 2147 2148 bool X86FrameLowering::assignCalleeSavedSpillSlots( 2149 MachineFunction &MF, const TargetRegisterInfo *TRI, 2150 std::vector<CalleeSavedInfo> &CSI) const { 2151 MachineFrameInfo &MFI = MF.getFrameInfo(); 2152 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 2153 2154 unsigned CalleeSavedFrameSize = 0; 2155 unsigned XMMCalleeSavedFrameSize = 0; 2156 auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo(); 2157 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta(); 2158 2159 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta(); 2160 2161 if (TailCallReturnAddrDelta < 0) { 2162 // create RETURNADDR area 2163 // arg 2164 // arg 2165 // RETADDR 2166 // { ... 2167 // RETADDR area 2168 // ... 2169 // } 2170 // [EBP] 2171 MFI.CreateFixedObject(-TailCallReturnAddrDelta, 2172 TailCallReturnAddrDelta - SlotSize, true); 2173 } 2174 2175 // Spill the BasePtr if it's used. 2176 if (this->TRI->hasBasePointer(MF)) { 2177 // Allocate a spill slot for EBP if we have a base pointer and EH funclets. 2178 if (MF.hasEHFunclets()) { 2179 int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize)); 2180 X86FI->setHasSEHFramePtrSave(true); 2181 X86FI->setSEHFramePtrSaveIndex(FI); 2182 } 2183 } 2184 2185 if (hasFP(MF)) { 2186 // emitPrologue always spills frame register the first thing. 2187 SpillSlotOffset -= SlotSize; 2188 MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 2189 2190 // Since emitPrologue and emitEpilogue will handle spilling and restoring of 2191 // the frame register, we can delete it from CSI list and not have to worry 2192 // about avoiding it later. 2193 Register FPReg = TRI->getFrameRegister(MF); 2194 for (unsigned i = 0; i < CSI.size(); ++i) { 2195 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) { 2196 CSI.erase(CSI.begin() + i); 2197 break; 2198 } 2199 } 2200 } 2201 2202 // Assign slots for GPRs. It increases frame size. 2203 for (unsigned i = CSI.size(); i != 0; --i) { 2204 unsigned Reg = CSI[i - 1].getReg(); 2205 2206 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg)) 2207 continue; 2208 2209 SpillSlotOffset -= SlotSize; 2210 CalleeSavedFrameSize += SlotSize; 2211 2212 int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset); 2213 CSI[i - 1].setFrameIdx(SlotIndex); 2214 } 2215 2216 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize); 2217 MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize); 2218 2219 // Assign slots for XMMs. 2220 for (unsigned i = CSI.size(); i != 0; --i) { 2221 unsigned Reg = CSI[i - 1].getReg(); 2222 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg)) 2223 continue; 2224 2225 // If this is k-register make sure we lookup via the largest legal type. 2226 MVT VT = MVT::Other; 2227 if (X86::VK16RegClass.contains(Reg)) 2228 VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 2229 2230 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2231 unsigned Size = TRI->getSpillSize(*RC); 2232 Align Alignment = TRI->getSpillAlign(*RC); 2233 // ensure alignment 2234 assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86"); 2235 SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment); 2236 2237 // spill into slot 2238 SpillSlotOffset -= Size; 2239 int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset); 2240 CSI[i - 1].setFrameIdx(SlotIndex); 2241 MFI.ensureMaxAlignment(Alignment); 2242 2243 // Save the start offset and size of XMM in stack frame for funclets. 2244 if (X86::VR128RegClass.contains(Reg)) { 2245 WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize; 2246 XMMCalleeSavedFrameSize += Size; 2247 } 2248 } 2249 2250 return true; 2251 } 2252 2253 bool X86FrameLowering::spillCalleeSavedRegisters( 2254 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 2255 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 2256 DebugLoc DL = MBB.findDebugLoc(MI); 2257 2258 // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI 2259 // for us, and there are no XMM CSRs on Win32. 2260 if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows()) 2261 return true; 2262 2263 // Push GPRs. It increases frame size. 2264 const MachineFunction &MF = *MBB.getParent(); 2265 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r; 2266 for (unsigned i = CSI.size(); i != 0; --i) { 2267 unsigned Reg = CSI[i - 1].getReg(); 2268 2269 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg)) 2270 continue; 2271 2272 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2273 bool isLiveIn = MRI.isLiveIn(Reg); 2274 if (!isLiveIn) 2275 MBB.addLiveIn(Reg); 2276 2277 // Decide whether we can add a kill flag to the use. 2278 bool CanKill = !isLiveIn; 2279 // Check if any subregister is live-in 2280 if (CanKill) { 2281 for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) { 2282 if (MRI.isLiveIn(*AReg)) { 2283 CanKill = false; 2284 break; 2285 } 2286 } 2287 } 2288 2289 // Do not set a kill flag on values that are also marked as live-in. This 2290 // happens with the @llvm-returnaddress intrinsic and with arguments 2291 // passed in callee saved registers. 2292 // Omitting the kill flags is conservatively correct even if the live-in 2293 // is not used after all. 2294 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill)) 2295 .setMIFlag(MachineInstr::FrameSetup); 2296 } 2297 2298 // Make XMM regs spilled. X86 does not have ability of push/pop XMM. 2299 // It can be done by spilling XMMs to stack frame. 2300 for (unsigned i = CSI.size(); i != 0; --i) { 2301 unsigned Reg = CSI[i-1].getReg(); 2302 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg)) 2303 continue; 2304 2305 // If this is k-register make sure we lookup via the largest legal type. 2306 MVT VT = MVT::Other; 2307 if (X86::VK16RegClass.contains(Reg)) 2308 VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 2309 2310 // Add the callee-saved register as live-in. It's killed at the spill. 2311 MBB.addLiveIn(Reg); 2312 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2313 2314 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC, 2315 TRI); 2316 --MI; 2317 MI->setFlag(MachineInstr::FrameSetup); 2318 ++MI; 2319 } 2320 2321 return true; 2322 } 2323 2324 void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB, 2325 MachineBasicBlock::iterator MBBI, 2326 MachineInstr *CatchRet) const { 2327 // SEH shouldn't use catchret. 2328 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 2329 MBB.getParent()->getFunction().getPersonalityFn())) && 2330 "SEH should not use CATCHRET"); 2331 DebugLoc DL = CatchRet->getDebugLoc(); 2332 MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB(); 2333 2334 // Fill EAX/RAX with the address of the target block. 2335 if (STI.is64Bit()) { 2336 // LEA64r CatchRetTarget(%rip), %rax 2337 BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX) 2338 .addReg(X86::RIP) 2339 .addImm(0) 2340 .addReg(0) 2341 .addMBB(CatchRetTarget) 2342 .addReg(0); 2343 } else { 2344 // MOV32ri $CatchRetTarget, %eax 2345 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX) 2346 .addMBB(CatchRetTarget); 2347 } 2348 2349 // Record that we've taken the address of CatchRetTarget and no longer just 2350 // reference it in a terminator. 2351 CatchRetTarget->setHasAddressTaken(); 2352 } 2353 2354 bool X86FrameLowering::restoreCalleeSavedRegisters( 2355 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 2356 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 2357 if (CSI.empty()) 2358 return false; 2359 2360 if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) { 2361 // Don't restore CSRs in 32-bit EH funclets. Matches 2362 // spillCalleeSavedRegisters. 2363 if (STI.is32Bit()) 2364 return true; 2365 // Don't restore CSRs before an SEH catchret. SEH except blocks do not form 2366 // funclets. emitEpilogue transforms these to normal jumps. 2367 if (MI->getOpcode() == X86::CATCHRET) { 2368 const Function &F = MBB.getParent()->getFunction(); 2369 bool IsSEH = isAsynchronousEHPersonality( 2370 classifyEHPersonality(F.getPersonalityFn())); 2371 if (IsSEH) 2372 return true; 2373 } 2374 } 2375 2376 DebugLoc DL = MBB.findDebugLoc(MI); 2377 2378 // Reload XMMs from stack frame. 2379 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 2380 unsigned Reg = CSI[i].getReg(); 2381 if (X86::GR64RegClass.contains(Reg) || 2382 X86::GR32RegClass.contains(Reg)) 2383 continue; 2384 2385 // If this is k-register make sure we lookup via the largest legal type. 2386 MVT VT = MVT::Other; 2387 if (X86::VK16RegClass.contains(Reg)) 2388 VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1; 2389 2390 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2391 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI); 2392 } 2393 2394 // POP GPRs. 2395 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r; 2396 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 2397 unsigned Reg = CSI[i].getReg(); 2398 if (!X86::GR64RegClass.contains(Reg) && 2399 !X86::GR32RegClass.contains(Reg)) 2400 continue; 2401 2402 BuildMI(MBB, MI, DL, TII.get(Opc), Reg) 2403 .setMIFlag(MachineInstr::FrameDestroy); 2404 } 2405 return true; 2406 } 2407 2408 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF, 2409 BitVector &SavedRegs, 2410 RegScavenger *RS) const { 2411 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 2412 2413 // Spill the BasePtr if it's used. 2414 if (TRI->hasBasePointer(MF)){ 2415 Register BasePtr = TRI->getBaseRegister(); 2416 if (STI.isTarget64BitILP32()) 2417 BasePtr = getX86SubSuperRegister(BasePtr, 64); 2418 SavedRegs.set(BasePtr); 2419 } 2420 } 2421 2422 static bool 2423 HasNestArgument(const MachineFunction *MF) { 2424 const Function &F = MF->getFunction(); 2425 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 2426 I != E; I++) { 2427 if (I->hasNestAttr() && !I->use_empty()) 2428 return true; 2429 } 2430 return false; 2431 } 2432 2433 /// GetScratchRegister - Get a temp register for performing work in the 2434 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform 2435 /// and the properties of the function either one or two registers will be 2436 /// needed. Set primary to true for the first register, false for the second. 2437 static unsigned 2438 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) { 2439 CallingConv::ID CallingConvention = MF.getFunction().getCallingConv(); 2440 2441 // Erlang stuff. 2442 if (CallingConvention == CallingConv::HiPE) { 2443 if (Is64Bit) 2444 return Primary ? X86::R14 : X86::R13; 2445 else 2446 return Primary ? X86::EBX : X86::EDI; 2447 } 2448 2449 if (Is64Bit) { 2450 if (IsLP64) 2451 return Primary ? X86::R11 : X86::R12; 2452 else 2453 return Primary ? X86::R11D : X86::R12D; 2454 } 2455 2456 bool IsNested = HasNestArgument(&MF); 2457 2458 if (CallingConvention == CallingConv::X86_FastCall || 2459 CallingConvention == CallingConv::Fast || 2460 CallingConvention == CallingConv::Tail) { 2461 if (IsNested) 2462 report_fatal_error("Segmented stacks does not support fastcall with " 2463 "nested function."); 2464 return Primary ? X86::EAX : X86::ECX; 2465 } 2466 if (IsNested) 2467 return Primary ? X86::EDX : X86::EAX; 2468 return Primary ? X86::ECX : X86::EAX; 2469 } 2470 2471 // The stack limit in the TCB is set to this many bytes above the actual stack 2472 // limit. 2473 static const uint64_t kSplitStackAvailable = 256; 2474 2475 void X86FrameLowering::adjustForSegmentedStacks( 2476 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 2477 MachineFrameInfo &MFI = MF.getFrameInfo(); 2478 uint64_t StackSize; 2479 unsigned TlsReg, TlsOffset; 2480 DebugLoc DL; 2481 2482 // To support shrink-wrapping we would need to insert the new blocks 2483 // at the right place and update the branches to PrologueMBB. 2484 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet"); 2485 2486 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true); 2487 assert(!MF.getRegInfo().isLiveIn(ScratchReg) && 2488 "Scratch register is live-in"); 2489 2490 if (MF.getFunction().isVarArg()) 2491 report_fatal_error("Segmented stacks do not support vararg functions."); 2492 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() && 2493 !STI.isTargetWin64() && !STI.isTargetFreeBSD() && 2494 !STI.isTargetDragonFly()) 2495 report_fatal_error("Segmented stacks not supported on this platform."); 2496 2497 // Eventually StackSize will be calculated by a link-time pass; which will 2498 // also decide whether checking code needs to be injected into this particular 2499 // prologue. 2500 StackSize = MFI.getStackSize(); 2501 2502 // Do not generate a prologue for leaf functions with a stack of size zero. 2503 // For non-leaf functions we have to allow for the possibility that the 2504 // callis to a non-split function, as in PR37807. This function could also 2505 // take the address of a non-split function. When the linker tries to adjust 2506 // its non-existent prologue, it would fail with an error. Mark the object 2507 // file so that such failures are not errors. See this Go language bug-report 2508 // https://go-review.googlesource.com/c/go/+/148819/ 2509 if (StackSize == 0 && !MFI.hasTailCall()) { 2510 MF.getMMI().setHasNosplitStack(true); 2511 return; 2512 } 2513 2514 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock(); 2515 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock(); 2516 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 2517 bool IsNested = false; 2518 2519 // We need to know if the function has a nest argument only in 64 bit mode. 2520 if (Is64Bit) 2521 IsNested = HasNestArgument(&MF); 2522 2523 // The MOV R10, RAX needs to be in a different block, since the RET we emit in 2524 // allocMBB needs to be last (terminating) instruction. 2525 2526 for (const auto &LI : PrologueMBB.liveins()) { 2527 allocMBB->addLiveIn(LI); 2528 checkMBB->addLiveIn(LI); 2529 } 2530 2531 if (IsNested) 2532 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D); 2533 2534 MF.push_front(allocMBB); 2535 MF.push_front(checkMBB); 2536 2537 // When the frame size is less than 256 we just compare the stack 2538 // boundary directly to the value of the stack pointer, per gcc. 2539 bool CompareStackPointer = StackSize < kSplitStackAvailable; 2540 2541 // Read the limit off the current stacklet off the stack_guard location. 2542 if (Is64Bit) { 2543 if (STI.isTargetLinux()) { 2544 TlsReg = X86::FS; 2545 TlsOffset = IsLP64 ? 0x70 : 0x40; 2546 } else if (STI.isTargetDarwin()) { 2547 TlsReg = X86::GS; 2548 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90. 2549 } else if (STI.isTargetWin64()) { 2550 TlsReg = X86::GS; 2551 TlsOffset = 0x28; // pvArbitrary, reserved for application use 2552 } else if (STI.isTargetFreeBSD()) { 2553 TlsReg = X86::FS; 2554 TlsOffset = 0x18; 2555 } else if (STI.isTargetDragonFly()) { 2556 TlsReg = X86::FS; 2557 TlsOffset = 0x20; // use tls_tcb.tcb_segstack 2558 } else { 2559 report_fatal_error("Segmented stacks not supported on this platform."); 2560 } 2561 2562 if (CompareStackPointer) 2563 ScratchReg = IsLP64 ? X86::RSP : X86::ESP; 2564 else 2565 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP) 2566 .addImm(1).addReg(0).addImm(-StackSize).addReg(0); 2567 2568 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg) 2569 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg); 2570 } else { 2571 if (STI.isTargetLinux()) { 2572 TlsReg = X86::GS; 2573 TlsOffset = 0x30; 2574 } else if (STI.isTargetDarwin()) { 2575 TlsReg = X86::GS; 2576 TlsOffset = 0x48 + 90*4; 2577 } else if (STI.isTargetWin32()) { 2578 TlsReg = X86::FS; 2579 TlsOffset = 0x14; // pvArbitrary, reserved for application use 2580 } else if (STI.isTargetDragonFly()) { 2581 TlsReg = X86::FS; 2582 TlsOffset = 0x10; // use tls_tcb.tcb_segstack 2583 } else if (STI.isTargetFreeBSD()) { 2584 report_fatal_error("Segmented stacks not supported on FreeBSD i386."); 2585 } else { 2586 report_fatal_error("Segmented stacks not supported on this platform."); 2587 } 2588 2589 if (CompareStackPointer) 2590 ScratchReg = X86::ESP; 2591 else 2592 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP) 2593 .addImm(1).addReg(0).addImm(-StackSize).addReg(0); 2594 2595 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() || 2596 STI.isTargetDragonFly()) { 2597 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg) 2598 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg); 2599 } else if (STI.isTargetDarwin()) { 2600 2601 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register. 2602 unsigned ScratchReg2; 2603 bool SaveScratch2; 2604 if (CompareStackPointer) { 2605 // The primary scratch register is available for holding the TLS offset. 2606 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true); 2607 SaveScratch2 = false; 2608 } else { 2609 // Need to use a second register to hold the TLS offset 2610 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false); 2611 2612 // Unfortunately, with fastcc the second scratch register may hold an 2613 // argument. 2614 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2); 2615 } 2616 2617 // If Scratch2 is live-in then it needs to be saved. 2618 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) && 2619 "Scratch register is live-in and not saved"); 2620 2621 if (SaveScratch2) 2622 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r)) 2623 .addReg(ScratchReg2, RegState::Kill); 2624 2625 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2) 2626 .addImm(TlsOffset); 2627 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)) 2628 .addReg(ScratchReg) 2629 .addReg(ScratchReg2).addImm(1).addReg(0) 2630 .addImm(0) 2631 .addReg(TlsReg); 2632 2633 if (SaveScratch2) 2634 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2); 2635 } 2636 } 2637 2638 // This jump is taken if SP >= (Stacklet Limit + Stack Space required). 2639 // It jumps to normal execution of the function body. 2640 BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A); 2641 2642 // On 32 bit we first push the arguments size and then the frame size. On 64 2643 // bit, we pass the stack frame size in r10 and the argument size in r11. 2644 if (Is64Bit) { 2645 // Functions with nested arguments use R10, so it needs to be saved across 2646 // the call to _morestack 2647 2648 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX; 2649 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D; 2650 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D; 2651 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr; 2652 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri; 2653 2654 if (IsNested) 2655 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10); 2656 2657 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10) 2658 .addImm(StackSize); 2659 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11) 2660 .addImm(X86FI->getArgumentStackSize()); 2661 } else { 2662 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32)) 2663 .addImm(X86FI->getArgumentStackSize()); 2664 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32)) 2665 .addImm(StackSize); 2666 } 2667 2668 // __morestack is in libgcc 2669 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) { 2670 // Under the large code model, we cannot assume that __morestack lives 2671 // within 2^31 bytes of the call site, so we cannot use pc-relative 2672 // addressing. We cannot perform the call via a temporary register, 2673 // as the rax register may be used to store the static chain, and all 2674 // other suitable registers may be either callee-save or used for 2675 // parameter passing. We cannot use the stack at this point either 2676 // because __morestack manipulates the stack directly. 2677 // 2678 // To avoid these issues, perform an indirect call via a read-only memory 2679 // location containing the address. 2680 // 2681 // This solution is not perfect, as it assumes that the .rodata section 2682 // is laid out within 2^31 bytes of each function body, but this seems 2683 // to be sufficient for JIT. 2684 // FIXME: Add retpoline support and remove the error here.. 2685 if (STI.useIndirectThunkCalls()) 2686 report_fatal_error("Emitting morestack calls on 64-bit with the large " 2687 "code model and thunks not yet implemented."); 2688 BuildMI(allocMBB, DL, TII.get(X86::CALL64m)) 2689 .addReg(X86::RIP) 2690 .addImm(0) 2691 .addReg(0) 2692 .addExternalSymbol("__morestack_addr") 2693 .addReg(0); 2694 MF.getMMI().setUsesMorestackAddr(true); 2695 } else { 2696 if (Is64Bit) 2697 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32)) 2698 .addExternalSymbol("__morestack"); 2699 else 2700 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32)) 2701 .addExternalSymbol("__morestack"); 2702 } 2703 2704 if (IsNested) 2705 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10)); 2706 else 2707 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET)); 2708 2709 allocMBB->addSuccessor(&PrologueMBB); 2710 2711 checkMBB->addSuccessor(allocMBB, BranchProbability::getZero()); 2712 checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne()); 2713 2714 #ifdef EXPENSIVE_CHECKS 2715 MF.verify(); 2716 #endif 2717 } 2718 2719 /// Lookup an ERTS parameter in the !hipe.literals named metadata node. 2720 /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets 2721 /// to fields it needs, through a named metadata node "hipe.literals" containing 2722 /// name-value pairs. 2723 static unsigned getHiPELiteral( 2724 NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) { 2725 for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) { 2726 MDNode *Node = HiPELiteralsMD->getOperand(i); 2727 if (Node->getNumOperands() != 2) continue; 2728 MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0)); 2729 ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1)); 2730 if (!NodeName || !NodeVal) continue; 2731 ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue()); 2732 if (ValConst && NodeName->getString() == LiteralName) { 2733 return ValConst->getZExtValue(); 2734 } 2735 } 2736 2737 report_fatal_error("HiPE literal " + LiteralName 2738 + " required but not provided"); 2739 } 2740 2741 // Return true if there are no non-ehpad successors to MBB and there are no 2742 // non-meta instructions between MBBI and MBB.end(). 2743 static bool blockEndIsUnreachable(const MachineBasicBlock &MBB, 2744 MachineBasicBlock::const_iterator MBBI) { 2745 return std::all_of( 2746 MBB.succ_begin(), MBB.succ_end(), 2747 [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) && 2748 std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) { 2749 return MI.isMetaInstruction(); 2750 }); 2751 } 2752 2753 /// Erlang programs may need a special prologue to handle the stack size they 2754 /// might need at runtime. That is because Erlang/OTP does not implement a C 2755 /// stack but uses a custom implementation of hybrid stack/heap architecture. 2756 /// (for more information see Eric Stenman's Ph.D. thesis: 2757 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf) 2758 /// 2759 /// CheckStack: 2760 /// temp0 = sp - MaxStack 2761 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart 2762 /// OldStart: 2763 /// ... 2764 /// IncStack: 2765 /// call inc_stack # doubles the stack space 2766 /// temp0 = sp - MaxStack 2767 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart 2768 void X86FrameLowering::adjustForHiPEPrologue( 2769 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 2770 MachineFrameInfo &MFI = MF.getFrameInfo(); 2771 DebugLoc DL; 2772 2773 // To support shrink-wrapping we would need to insert the new blocks 2774 // at the right place and update the branches to PrologueMBB. 2775 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet"); 2776 2777 // HiPE-specific values 2778 NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule() 2779 ->getNamedMetadata("hipe.literals"); 2780 if (!HiPELiteralsMD) 2781 report_fatal_error( 2782 "Can't generate HiPE prologue without runtime parameters"); 2783 const unsigned HipeLeafWords 2784 = getHiPELiteral(HiPELiteralsMD, 2785 Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS"); 2786 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5; 2787 const unsigned Guaranteed = HipeLeafWords * SlotSize; 2788 unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ? 2789 MF.getFunction().arg_size() - CCRegisteredArgs : 0; 2790 unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize; 2791 2792 assert(STI.isTargetLinux() && 2793 "HiPE prologue is only supported on Linux operating systems."); 2794 2795 // Compute the largest caller's frame that is needed to fit the callees' 2796 // frames. This 'MaxStack' is computed from: 2797 // 2798 // a) the fixed frame size, which is the space needed for all spilled temps, 2799 // b) outgoing on-stack parameter areas, and 2800 // c) the minimum stack space this function needs to make available for the 2801 // functions it calls (a tunable ABI property). 2802 if (MFI.hasCalls()) { 2803 unsigned MoreStackForCalls = 0; 2804 2805 for (auto &MBB : MF) { 2806 for (auto &MI : MBB) { 2807 if (!MI.isCall()) 2808 continue; 2809 2810 // Get callee operand. 2811 const MachineOperand &MO = MI.getOperand(0); 2812 2813 // Only take account of global function calls (no closures etc.). 2814 if (!MO.isGlobal()) 2815 continue; 2816 2817 const Function *F = dyn_cast<Function>(MO.getGlobal()); 2818 if (!F) 2819 continue; 2820 2821 // Do not update 'MaxStack' for primitive and built-in functions 2822 // (encoded with names either starting with "erlang."/"bif_" or not 2823 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an 2824 // "_", such as the BIF "suspend_0") as they are executed on another 2825 // stack. 2826 if (F->getName().find("erlang.") != StringRef::npos || 2827 F->getName().find("bif_") != StringRef::npos || 2828 F->getName().find_first_of("._") == StringRef::npos) 2829 continue; 2830 2831 unsigned CalleeStkArity = 2832 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0; 2833 if (HipeLeafWords - 1 > CalleeStkArity) 2834 MoreStackForCalls = std::max(MoreStackForCalls, 2835 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize); 2836 } 2837 } 2838 MaxStack += MoreStackForCalls; 2839 } 2840 2841 // If the stack frame needed is larger than the guaranteed then runtime checks 2842 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue. 2843 if (MaxStack > Guaranteed) { 2844 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock(); 2845 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock(); 2846 2847 for (const auto &LI : PrologueMBB.liveins()) { 2848 stackCheckMBB->addLiveIn(LI); 2849 incStackMBB->addLiveIn(LI); 2850 } 2851 2852 MF.push_front(incStackMBB); 2853 MF.push_front(stackCheckMBB); 2854 2855 unsigned ScratchReg, SPReg, PReg, SPLimitOffset; 2856 unsigned LEAop, CMPop, CALLop; 2857 SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT"); 2858 if (Is64Bit) { 2859 SPReg = X86::RSP; 2860 PReg = X86::RBP; 2861 LEAop = X86::LEA64r; 2862 CMPop = X86::CMP64rm; 2863 CALLop = X86::CALL64pcrel32; 2864 } else { 2865 SPReg = X86::ESP; 2866 PReg = X86::EBP; 2867 LEAop = X86::LEA32r; 2868 CMPop = X86::CMP32rm; 2869 CALLop = X86::CALLpcrel32; 2870 } 2871 2872 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true); 2873 assert(!MF.getRegInfo().isLiveIn(ScratchReg) && 2874 "HiPE prologue scratch register is live-in"); 2875 2876 // Create new MBB for StackCheck: 2877 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg), 2878 SPReg, false, -MaxStack); 2879 // SPLimitOffset is in a fixed heap location (pointed by BP). 2880 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop)) 2881 .addReg(ScratchReg), PReg, false, SPLimitOffset); 2882 BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE); 2883 2884 // Create new MBB for IncStack: 2885 BuildMI(incStackMBB, DL, TII.get(CALLop)). 2886 addExternalSymbol("inc_stack_0"); 2887 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg), 2888 SPReg, false, -MaxStack); 2889 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop)) 2890 .addReg(ScratchReg), PReg, false, SPLimitOffset); 2891 BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE); 2892 2893 stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100}); 2894 stackCheckMBB->addSuccessor(incStackMBB, {1, 100}); 2895 incStackMBB->addSuccessor(&PrologueMBB, {99, 100}); 2896 incStackMBB->addSuccessor(incStackMBB, {1, 100}); 2897 } 2898 #ifdef EXPENSIVE_CHECKS 2899 MF.verify(); 2900 #endif 2901 } 2902 2903 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB, 2904 MachineBasicBlock::iterator MBBI, 2905 const DebugLoc &DL, 2906 int Offset) const { 2907 2908 if (Offset <= 0) 2909 return false; 2910 2911 if (Offset % SlotSize) 2912 return false; 2913 2914 int NumPops = Offset / SlotSize; 2915 // This is only worth it if we have at most 2 pops. 2916 if (NumPops != 1 && NumPops != 2) 2917 return false; 2918 2919 // Handle only the trivial case where the adjustment directly follows 2920 // a call. This is the most common one, anyway. 2921 if (MBBI == MBB.begin()) 2922 return false; 2923 MachineBasicBlock::iterator Prev = std::prev(MBBI); 2924 if (!Prev->isCall() || !Prev->getOperand(1).isRegMask()) 2925 return false; 2926 2927 unsigned Regs[2]; 2928 unsigned FoundRegs = 0; 2929 2930 auto &MRI = MBB.getParent()->getRegInfo(); 2931 auto RegMask = Prev->getOperand(1); 2932 2933 auto &RegClass = 2934 Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass; 2935 // Try to find up to NumPops free registers. 2936 for (auto Candidate : RegClass) { 2937 2938 // Poor man's liveness: 2939 // Since we're immediately after a call, any register that is clobbered 2940 // by the call and not defined by it can be considered dead. 2941 if (!RegMask.clobbersPhysReg(Candidate)) 2942 continue; 2943 2944 // Don't clobber reserved registers 2945 if (MRI.isReserved(Candidate)) 2946 continue; 2947 2948 bool IsDef = false; 2949 for (const MachineOperand &MO : Prev->implicit_operands()) { 2950 if (MO.isReg() && MO.isDef() && 2951 TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) { 2952 IsDef = true; 2953 break; 2954 } 2955 } 2956 2957 if (IsDef) 2958 continue; 2959 2960 Regs[FoundRegs++] = Candidate; 2961 if (FoundRegs == (unsigned)NumPops) 2962 break; 2963 } 2964 2965 if (FoundRegs == 0) 2966 return false; 2967 2968 // If we found only one free register, but need two, reuse the same one twice. 2969 while (FoundRegs < (unsigned)NumPops) 2970 Regs[FoundRegs++] = Regs[0]; 2971 2972 for (int i = 0; i < NumPops; ++i) 2973 BuildMI(MBB, MBBI, DL, 2974 TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]); 2975 2976 return true; 2977 } 2978 2979 MachineBasicBlock::iterator X86FrameLowering:: 2980 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, 2981 MachineBasicBlock::iterator I) const { 2982 bool reserveCallFrame = hasReservedCallFrame(MF); 2983 unsigned Opcode = I->getOpcode(); 2984 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode(); 2985 DebugLoc DL = I->getDebugLoc(); 2986 uint64_t Amount = TII.getFrameSize(*I); 2987 uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0; 2988 I = MBB.erase(I); 2989 auto InsertPos = skipDebugInstructionsForward(I, MBB.end()); 2990 2991 // Try to avoid emitting dead SP adjustments if the block end is unreachable, 2992 // typically because the function is marked noreturn (abort, throw, 2993 // assert_fail, etc). 2994 if (isDestroy && blockEndIsUnreachable(MBB, I)) 2995 return I; 2996 2997 if (!reserveCallFrame) { 2998 // If the stack pointer can be changed after prologue, turn the 2999 // adjcallstackup instruction into a 'sub ESP, <amt>' and the 3000 // adjcallstackdown instruction into 'add ESP, <amt>' 3001 3002 // We need to keep the stack aligned properly. To do this, we round the 3003 // amount of space needed for the outgoing arguments up to the next 3004 // alignment boundary. 3005 Amount = alignTo(Amount, getStackAlign()); 3006 3007 const Function &F = MF.getFunction(); 3008 bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 3009 bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves(); 3010 3011 // If we have any exception handlers in this function, and we adjust 3012 // the SP before calls, we may need to indicate this to the unwinder 3013 // using GNU_ARGS_SIZE. Note that this may be necessary even when 3014 // Amount == 0, because the preceding function may have set a non-0 3015 // GNU_ARGS_SIZE. 3016 // TODO: We don't need to reset this between subsequent functions, 3017 // if it didn't change. 3018 bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty(); 3019 3020 if (HasDwarfEHHandlers && !isDestroy && 3021 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences()) 3022 BuildCFI(MBB, InsertPos, DL, 3023 MCCFIInstruction::createGnuArgsSize(nullptr, Amount)); 3024 3025 if (Amount == 0) 3026 return I; 3027 3028 // Factor out the amount that gets handled inside the sequence 3029 // (Pushes of argument for frame setup, callee pops for frame destroy) 3030 Amount -= InternalAmt; 3031 3032 // TODO: This is needed only if we require precise CFA. 3033 // If this is a callee-pop calling convention, emit a CFA adjust for 3034 // the amount the callee popped. 3035 if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF)) 3036 BuildCFI(MBB, InsertPos, DL, 3037 MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt)); 3038 3039 // Add Amount to SP to destroy a frame, or subtract to setup. 3040 int64_t StackAdjustment = isDestroy ? Amount : -Amount; 3041 3042 if (StackAdjustment) { 3043 // Merge with any previous or following adjustment instruction. Note: the 3044 // instructions merged with here do not have CFI, so their stack 3045 // adjustments do not feed into CfaAdjustment. 3046 StackAdjustment += mergeSPUpdates(MBB, InsertPos, true); 3047 StackAdjustment += mergeSPUpdates(MBB, InsertPos, false); 3048 3049 if (StackAdjustment) { 3050 if (!(F.hasMinSize() && 3051 adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment))) 3052 BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment, 3053 /*InEpilogue=*/false); 3054 } 3055 } 3056 3057 if (DwarfCFI && !hasFP(MF)) { 3058 // If we don't have FP, but need to generate unwind information, 3059 // we need to set the correct CFA offset after the stack adjustment. 3060 // How much we adjust the CFA offset depends on whether we're emitting 3061 // CFI only for EH purposes or for debugging. EH only requires the CFA 3062 // offset to be correct at each call site, while for debugging we want 3063 // it to be more precise. 3064 3065 int64_t CfaAdjustment = -StackAdjustment; 3066 // TODO: When not using precise CFA, we also need to adjust for the 3067 // InternalAmt here. 3068 if (CfaAdjustment) { 3069 BuildCFI(MBB, InsertPos, DL, 3070 MCCFIInstruction::createAdjustCfaOffset(nullptr, 3071 CfaAdjustment)); 3072 } 3073 } 3074 3075 return I; 3076 } 3077 3078 if (InternalAmt) { 3079 MachineBasicBlock::iterator CI = I; 3080 MachineBasicBlock::iterator B = MBB.begin(); 3081 while (CI != B && !std::prev(CI)->isCall()) 3082 --CI; 3083 BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false); 3084 } 3085 3086 return I; 3087 } 3088 3089 bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const { 3090 assert(MBB.getParent() && "Block is not attached to a function!"); 3091 const MachineFunction &MF = *MBB.getParent(); 3092 return !TRI->needsStackRealignment(MF) || !MBB.isLiveIn(X86::EFLAGS); 3093 } 3094 3095 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const { 3096 assert(MBB.getParent() && "Block is not attached to a function!"); 3097 3098 // Win64 has strict requirements in terms of epilogue and we are 3099 // not taking a chance at messing with them. 3100 // I.e., unless this block is already an exit block, we can't use 3101 // it as an epilogue. 3102 if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock()) 3103 return false; 3104 3105 if (canUseLEAForSPInEpilogue(*MBB.getParent())) 3106 return true; 3107 3108 // If we cannot use LEA to adjust SP, we may need to use ADD, which 3109 // clobbers the EFLAGS. Check that we do not need to preserve it, 3110 // otherwise, conservatively assume this is not 3111 // safe to insert the epilogue here. 3112 return !flagsNeedToBePreservedBeforeTheTerminators(MBB); 3113 } 3114 3115 bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const { 3116 // If we may need to emit frameless compact unwind information, give 3117 // up as this is currently broken: PR25614. 3118 return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF)) && 3119 // The lowering of segmented stack and HiPE only support entry blocks 3120 // as prologue blocks: PR26107. 3121 // This limitation may be lifted if we fix: 3122 // - adjustForSegmentedStacks 3123 // - adjustForHiPEPrologue 3124 MF.getFunction().getCallingConv() != CallingConv::HiPE && 3125 !MF.shouldSplitStack(); 3126 } 3127 3128 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers( 3129 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 3130 const DebugLoc &DL, bool RestoreSP) const { 3131 assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env"); 3132 assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32"); 3133 assert(STI.is32Bit() && !Uses64BitFramePtr && 3134 "restoring EBP/ESI on non-32-bit target"); 3135 3136 MachineFunction &MF = *MBB.getParent(); 3137 Register FramePtr = TRI->getFrameRegister(MF); 3138 Register BasePtr = TRI->getBaseRegister(); 3139 WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo(); 3140 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>(); 3141 MachineFrameInfo &MFI = MF.getFrameInfo(); 3142 3143 // FIXME: Don't set FrameSetup flag in catchret case. 3144 3145 int FI = FuncInfo.EHRegNodeFrameIndex; 3146 int EHRegSize = MFI.getObjectSize(FI); 3147 3148 if (RestoreSP) { 3149 // MOV32rm -EHRegSize(%ebp), %esp 3150 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP), 3151 X86::EBP, true, -EHRegSize) 3152 .setMIFlag(MachineInstr::FrameSetup); 3153 } 3154 3155 Register UsedReg; 3156 int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg); 3157 int EndOffset = -EHRegOffset - EHRegSize; 3158 FuncInfo.EHRegNodeEndOffset = EndOffset; 3159 3160 if (UsedReg == FramePtr) { 3161 // ADD $offset, %ebp 3162 unsigned ADDri = getADDriOpcode(false, EndOffset); 3163 BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr) 3164 .addReg(FramePtr) 3165 .addImm(EndOffset) 3166 .setMIFlag(MachineInstr::FrameSetup) 3167 ->getOperand(3) 3168 .setIsDead(); 3169 assert(EndOffset >= 0 && 3170 "end of registration object above normal EBP position!"); 3171 } else if (UsedReg == BasePtr) { 3172 // LEA offset(%ebp), %esi 3173 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr), 3174 FramePtr, false, EndOffset) 3175 .setMIFlag(MachineInstr::FrameSetup); 3176 // MOV32rm SavedEBPOffset(%esi), %ebp 3177 assert(X86FI->getHasSEHFramePtrSave()); 3178 int Offset = 3179 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg); 3180 assert(UsedReg == BasePtr); 3181 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr), 3182 UsedReg, true, Offset) 3183 .setMIFlag(MachineInstr::FrameSetup); 3184 } else { 3185 llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr"); 3186 } 3187 return MBBI; 3188 } 3189 3190 int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const { 3191 return TRI->getSlotSize(); 3192 } 3193 3194 Register 3195 X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const { 3196 return TRI->getDwarfRegNum(StackPtr, true); 3197 } 3198 3199 namespace { 3200 // Struct used by orderFrameObjects to help sort the stack objects. 3201 struct X86FrameSortingObject { 3202 bool IsValid = false; // true if we care about this Object. 3203 unsigned ObjectIndex = 0; // Index of Object into MFI list. 3204 unsigned ObjectSize = 0; // Size of Object in bytes. 3205 Align ObjectAlignment = Align(1); // Alignment of Object in bytes. 3206 unsigned ObjectNumUses = 0; // Object static number of uses. 3207 }; 3208 3209 // The comparison function we use for std::sort to order our local 3210 // stack symbols. The current algorithm is to use an estimated 3211 // "density". This takes into consideration the size and number of 3212 // uses each object has in order to roughly minimize code size. 3213 // So, for example, an object of size 16B that is referenced 5 times 3214 // will get higher priority than 4 4B objects referenced 1 time each. 3215 // It's not perfect and we may be able to squeeze a few more bytes out of 3216 // it (for example : 0(esp) requires fewer bytes, symbols allocated at the 3217 // fringe end can have special consideration, given their size is less 3218 // important, etc.), but the algorithmic complexity grows too much to be 3219 // worth the extra gains we get. This gets us pretty close. 3220 // The final order leaves us with objects with highest priority going 3221 // at the end of our list. 3222 struct X86FrameSortingComparator { 3223 inline bool operator()(const X86FrameSortingObject &A, 3224 const X86FrameSortingObject &B) { 3225 uint64_t DensityAScaled, DensityBScaled; 3226 3227 // For consistency in our comparison, all invalid objects are placed 3228 // at the end. This also allows us to stop walking when we hit the 3229 // first invalid item after it's all sorted. 3230 if (!A.IsValid) 3231 return false; 3232 if (!B.IsValid) 3233 return true; 3234 3235 // The density is calculated by doing : 3236 // (double)DensityA = A.ObjectNumUses / A.ObjectSize 3237 // (double)DensityB = B.ObjectNumUses / B.ObjectSize 3238 // Since this approach may cause inconsistencies in 3239 // the floating point <, >, == comparisons, depending on the floating 3240 // point model with which the compiler was built, we're going 3241 // to scale both sides by multiplying with 3242 // A.ObjectSize * B.ObjectSize. This ends up factoring away 3243 // the division and, with it, the need for any floating point 3244 // arithmetic. 3245 DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) * 3246 static_cast<uint64_t>(B.ObjectSize); 3247 DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) * 3248 static_cast<uint64_t>(A.ObjectSize); 3249 3250 // If the two densities are equal, prioritize highest alignment 3251 // objects. This allows for similar alignment objects 3252 // to be packed together (given the same density). 3253 // There's room for improvement here, also, since we can pack 3254 // similar alignment (different density) objects next to each 3255 // other to save padding. This will also require further 3256 // complexity/iterations, and the overall gain isn't worth it, 3257 // in general. Something to keep in mind, though. 3258 if (DensityAScaled == DensityBScaled) 3259 return A.ObjectAlignment < B.ObjectAlignment; 3260 3261 return DensityAScaled < DensityBScaled; 3262 } 3263 }; 3264 } // namespace 3265 3266 // Order the symbols in the local stack. 3267 // We want to place the local stack objects in some sort of sensible order. 3268 // The heuristic we use is to try and pack them according to static number 3269 // of uses and size of object in order to minimize code size. 3270 void X86FrameLowering::orderFrameObjects( 3271 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const { 3272 const MachineFrameInfo &MFI = MF.getFrameInfo(); 3273 3274 // Don't waste time if there's nothing to do. 3275 if (ObjectsToAllocate.empty()) 3276 return; 3277 3278 // Create an array of all MFI objects. We won't need all of these 3279 // objects, but we're going to create a full array of them to make 3280 // it easier to index into when we're counting "uses" down below. 3281 // We want to be able to easily/cheaply access an object by simply 3282 // indexing into it, instead of having to search for it every time. 3283 std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd()); 3284 3285 // Walk the objects we care about and mark them as such in our working 3286 // struct. 3287 for (auto &Obj : ObjectsToAllocate) { 3288 SortingObjects[Obj].IsValid = true; 3289 SortingObjects[Obj].ObjectIndex = Obj; 3290 SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj); 3291 // Set the size. 3292 int ObjectSize = MFI.getObjectSize(Obj); 3293 if (ObjectSize == 0) 3294 // Variable size. Just use 4. 3295 SortingObjects[Obj].ObjectSize = 4; 3296 else 3297 SortingObjects[Obj].ObjectSize = ObjectSize; 3298 } 3299 3300 // Count the number of uses for each object. 3301 for (auto &MBB : MF) { 3302 for (auto &MI : MBB) { 3303 if (MI.isDebugInstr()) 3304 continue; 3305 for (const MachineOperand &MO : MI.operands()) { 3306 // Check to see if it's a local stack symbol. 3307 if (!MO.isFI()) 3308 continue; 3309 int Index = MO.getIndex(); 3310 // Check to see if it falls within our range, and is tagged 3311 // to require ordering. 3312 if (Index >= 0 && Index < MFI.getObjectIndexEnd() && 3313 SortingObjects[Index].IsValid) 3314 SortingObjects[Index].ObjectNumUses++; 3315 } 3316 } 3317 } 3318 3319 // Sort the objects using X86FrameSortingAlgorithm (see its comment for 3320 // info). 3321 llvm::stable_sort(SortingObjects, X86FrameSortingComparator()); 3322 3323 // Now modify the original list to represent the final order that 3324 // we want. The order will depend on whether we're going to access them 3325 // from the stack pointer or the frame pointer. For SP, the list should 3326 // end up with the END containing objects that we want with smaller offsets. 3327 // For FP, it should be flipped. 3328 int i = 0; 3329 for (auto &Obj : SortingObjects) { 3330 // All invalid items are sorted at the end, so it's safe to stop. 3331 if (!Obj.IsValid) 3332 break; 3333 ObjectsToAllocate[i++] = Obj.ObjectIndex; 3334 } 3335 3336 // Flip it if we're accessing off of the FP. 3337 if (!TRI->needsStackRealignment(MF) && hasFP(MF)) 3338 std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end()); 3339 } 3340 3341 3342 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const { 3343 // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue. 3344 unsigned Offset = 16; 3345 // RBP is immediately pushed. 3346 Offset += SlotSize; 3347 // All callee-saved registers are then pushed. 3348 Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize(); 3349 // Every funclet allocates enough stack space for the largest outgoing call. 3350 Offset += getWinEHFuncletFrameSize(MF); 3351 return Offset; 3352 } 3353 3354 void X86FrameLowering::processFunctionBeforeFrameFinalized( 3355 MachineFunction &MF, RegScavenger *RS) const { 3356 // Mark the function as not having WinCFI. We will set it back to true in 3357 // emitPrologue if it gets called and emits CFI. 3358 MF.setHasWinCFI(false); 3359 3360 // If this function isn't doing Win64-style C++ EH, we don't need to do 3361 // anything. 3362 const Function &F = MF.getFunction(); 3363 if (!STI.is64Bit() || !MF.hasEHFunclets() || 3364 classifyEHPersonality(F.getPersonalityFn()) != EHPersonality::MSVC_CXX) 3365 return; 3366 3367 // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset 3368 // relative to RSP after the prologue. Find the offset of the last fixed 3369 // object, so that we can allocate a slot immediately following it. If there 3370 // were no fixed objects, use offset -SlotSize, which is immediately after the 3371 // return address. Fixed objects have negative frame indices. 3372 MachineFrameInfo &MFI = MF.getFrameInfo(); 3373 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo(); 3374 int64_t MinFixedObjOffset = -SlotSize; 3375 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) 3376 MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I)); 3377 3378 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) { 3379 for (WinEHHandlerType &H : TBME.HandlerArray) { 3380 int FrameIndex = H.CatchObj.FrameIndex; 3381 if (FrameIndex != INT_MAX) { 3382 // Ensure alignment. 3383 unsigned Align = MFI.getObjectAlign(FrameIndex).value(); 3384 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align; 3385 MinFixedObjOffset -= MFI.getObjectSize(FrameIndex); 3386 MFI.setObjectOffset(FrameIndex, MinFixedObjOffset); 3387 } 3388 } 3389 } 3390 3391 // Ensure alignment. 3392 MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8; 3393 int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize; 3394 int UnwindHelpFI = 3395 MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false); 3396 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI; 3397 3398 // Store -2 into UnwindHelp on function entry. We have to scan forwards past 3399 // other frame setup instructions. 3400 MachineBasicBlock &MBB = MF.front(); 3401 auto MBBI = MBB.begin(); 3402 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) 3403 ++MBBI; 3404 3405 DebugLoc DL = MBB.findDebugLoc(MBBI); 3406 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)), 3407 UnwindHelpFI) 3408 .addImm(-2); 3409 } 3410 3411 void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced( 3412 MachineFunction &MF, RegScavenger *RS) const { 3413 if (STI.is32Bit() && MF.hasEHFunclets()) 3414 restoreWinEHStackPointersInParent(MF); 3415 } 3416 3417 void X86FrameLowering::restoreWinEHStackPointersInParent( 3418 MachineFunction &MF) const { 3419 // 32-bit functions have to restore stack pointers when control is transferred 3420 // back to the parent function. These blocks are identified as eh pads that 3421 // are not funclet entries. 3422 bool IsSEH = isAsynchronousEHPersonality( 3423 classifyEHPersonality(MF.getFunction().getPersonalityFn())); 3424 for (MachineBasicBlock &MBB : MF) { 3425 bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry(); 3426 if (NeedsRestore) 3427 restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(), 3428 /*RestoreSP=*/IsSEH); 3429 } 3430 } 3431