1 //===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines a pass that optimizes call sequences on x86. 11 // Currently, it converts movs of function parameters onto the stack into 12 // pushes. This is beneficial for two main reasons: 13 // 1) The push instruction encoding is much smaller than an esp-relative mov 14 // 2) It is possible to push memory arguments directly. So, if the 15 // the transformation is preformed pre-reg-alloc, it can help relieve 16 // register pressure. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include <algorithm> 21 22 #include "X86.h" 23 #include "X86InstrInfo.h" 24 #include "X86Subtarget.h" 25 #include "X86MachineFunctionInfo.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/CodeGen/MachineFunctionPass.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineModuleInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/Passes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetInstrInfo.h" 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "x86-cf-opt" 40 41 static cl::opt<bool> 42 NoX86CFOpt("no-x86-call-frame-opt", 43 cl::desc("Avoid optimizing x86 call frames for size"), 44 cl::init(false), cl::Hidden); 45 46 namespace { 47 class X86CallFrameOptimization : public MachineFunctionPass { 48 public: 49 X86CallFrameOptimization() : MachineFunctionPass(ID) {} 50 51 bool runOnMachineFunction(MachineFunction &MF) override; 52 53 private: 54 // Information we know about a particular call site 55 struct CallContext { 56 CallContext() 57 : FrameSetup(nullptr), Call(nullptr), SPCopy(nullptr), ExpectedDist(0), 58 MovVector(4, nullptr), NoStackParams(false), UsePush(false){} 59 60 // Iterator referring to the frame setup instruction 61 MachineBasicBlock::iterator FrameSetup; 62 63 // Actual call instruction 64 MachineInstr *Call; 65 66 // A copy of the stack pointer 67 MachineInstr *SPCopy; 68 69 // The total displacement of all passed parameters 70 int64_t ExpectedDist; 71 72 // The sequence of movs used to pass the parameters 73 SmallVector<MachineInstr *, 4> MovVector; 74 75 // True if this call site has no stack parameters 76 bool NoStackParams; 77 78 // True of this callsite can use push instructions 79 bool UsePush; 80 }; 81 82 typedef SmallVector<CallContext, 8> ContextVector; 83 84 bool isLegal(MachineFunction &MF); 85 86 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap); 87 88 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB, 89 MachineBasicBlock::iterator I, CallContext &Context); 90 91 bool adjustCallSequence(MachineFunction &MF, const CallContext &Context); 92 93 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup, 94 unsigned Reg); 95 96 enum InstClassification { Convert, Skip, Exit }; 97 98 InstClassification classifyInstruction(MachineBasicBlock &MBB, 99 MachineBasicBlock::iterator MI, 100 const X86RegisterInfo &RegInfo, 101 DenseSet<unsigned int> &UsedRegs); 102 103 const char *getPassName() const override { return "X86 Optimize Call Frame"; } 104 105 const TargetInstrInfo *TII; 106 const X86FrameLowering *TFL; 107 const X86Subtarget *STI; 108 const MachineRegisterInfo *MRI; 109 static char ID; 110 }; 111 112 char X86CallFrameOptimization::ID = 0; 113 } // end anonymous namespace 114 115 FunctionPass *llvm::createX86CallFrameOptimization() { 116 return new X86CallFrameOptimization(); 117 } 118 119 // This checks whether the transformation is legal. 120 // Also returns false in cases where it's potentially legal, but 121 // we don't even want to try. 122 bool X86CallFrameOptimization::isLegal(MachineFunction &MF) { 123 if (NoX86CFOpt.getValue()) 124 return false; 125 126 // We currently only support call sequences where *all* parameters. 127 // are passed on the stack. 128 // No point in running this in 64-bit mode, since some arguments are 129 // passed in-register in all common calling conventions, so the pattern 130 // we're looking for will never match. 131 if (STI->is64Bit()) 132 return false; 133 134 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset 135 // in the compact unwind encoding that Darwin uses. So, bail if there 136 // is a danger of that being generated. 137 if (STI->isTargetDarwin() && 138 (!MF.getMMI().getLandingPads().empty() || 139 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF)))) 140 return false; 141 142 // You would expect straight-line code between call-frame setup and 143 // call-frame destroy. You would be wrong. There are circumstances (e.g. 144 // CMOV_GR8 expansion of a select that feeds a function call!) where we can 145 // end up with the setup and the destroy in different basic blocks. 146 // This is bad, and breaks SP adjustment. 147 // So, check that all of the frames in the function are closed inside 148 // the same block, and, for good measure, that there are no nested frames. 149 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 150 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 151 for (MachineBasicBlock &BB : MF) { 152 bool InsideFrameSequence = false; 153 for (MachineInstr &MI : BB) { 154 if (MI.getOpcode() == FrameSetupOpcode) { 155 if (InsideFrameSequence) 156 return false; 157 InsideFrameSequence = true; 158 } else if (MI.getOpcode() == FrameDestroyOpcode) { 159 if (!InsideFrameSequence) 160 return false; 161 InsideFrameSequence = false; 162 } 163 } 164 165 if (InsideFrameSequence) 166 return false; 167 } 168 169 return true; 170 } 171 172 // Check whether this transformation is profitable for a particular 173 // function - in terms of code size. 174 bool X86CallFrameOptimization::isProfitable(MachineFunction &MF, 175 ContextVector &CallSeqVector) { 176 // This transformation is always a win when we do not expect to have 177 // a reserved call frame. Under other circumstances, it may be either 178 // a win or a loss, and requires a heuristic. 179 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects(); 180 if (CannotReserveFrame) 181 return true; 182 183 unsigned StackAlign = TFL->getStackAlignment(); 184 185 int64_t Advantage = 0; 186 for (auto CC : CallSeqVector) { 187 // Call sites where no parameters are passed on the stack 188 // do not affect the cost, since there needs to be no 189 // stack adjustment. 190 if (CC.NoStackParams) 191 continue; 192 193 if (!CC.UsePush) { 194 // If we don't use pushes for a particular call site, 195 // we pay for not having a reserved call frame with an 196 // additional sub/add esp pair. The cost is ~3 bytes per instruction, 197 // depending on the size of the constant. 198 // TODO: Callee-pop functions should have a smaller penalty, because 199 // an add is needed even with a reserved call frame. 200 Advantage -= 6; 201 } else { 202 // We can use pushes. First, account for the fixed costs. 203 // We'll need a add after the call. 204 Advantage -= 3; 205 // If we have to realign the stack, we'll also need and sub before 206 if (CC.ExpectedDist % StackAlign) 207 Advantage -= 3; 208 // Now, for each push, we save ~3 bytes. For small constants, we actually, 209 // save more (up to 5 bytes), but 3 should be a good approximation. 210 Advantage += (CC.ExpectedDist / 4) * 3; 211 } 212 } 213 214 return (Advantage >= 0); 215 } 216 217 bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) { 218 STI = &MF.getSubtarget<X86Subtarget>(); 219 TII = STI->getInstrInfo(); 220 TFL = STI->getFrameLowering(); 221 MRI = &MF.getRegInfo(); 222 223 if (!isLegal(MF)) 224 return false; 225 226 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode(); 227 228 bool Changed = false; 229 230 ContextVector CallSeqVector; 231 232 for (auto &MBB : MF) 233 for (auto &MI : MBB) 234 if (MI.getOpcode() == FrameSetupOpcode) { 235 CallContext Context; 236 collectCallInfo(MF, MBB, MI, Context); 237 CallSeqVector.push_back(Context); 238 } 239 240 if (!isProfitable(MF, CallSeqVector)) 241 return false; 242 243 for (auto CC : CallSeqVector) 244 if (CC.UsePush) 245 Changed |= adjustCallSequence(MF, CC); 246 247 return Changed; 248 } 249 250 X86CallFrameOptimization::InstClassification 251 X86CallFrameOptimization::classifyInstruction( 252 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 253 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) { 254 if (MI == MBB.end()) 255 return Exit; 256 257 // The instructions we actually care about are movs onto the stack 258 int Opcode = MI->getOpcode(); 259 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr) 260 return Convert; 261 262 // Not all calling conventions have only stack MOVs between the stack 263 // adjust and the call. 264 265 // We want to tolerate other instructions, to cover more cases. 266 // In particular: 267 // a) PCrel calls, where we expect an additional COPY of the basereg. 268 // b) Passing frame-index addresses. 269 // c) Calling conventions that have inreg parameters. These generate 270 // both copies and movs into registers. 271 // To avoid creating lots of special cases, allow any instruction 272 // that does not write into memory, does not def or use the stack 273 // pointer, and does not def any register that was used by a preceding 274 // push. 275 // (Reading from memory is allowed, even if referenced through a 276 // frame index, since these will get adjusted properly in PEI) 277 278 // The reason for the last condition is that the pushes can't replace 279 // the movs in place, because the order must be reversed. 280 // So if we have a MOV32mr that uses EDX, then an instruction that defs 281 // EDX, and then the call, after the transformation the push will use 282 // the modified version of EDX, and not the original one. 283 // Since we are still in SSA form at this point, we only need to 284 // make sure we don't clobber any *physical* registers that were 285 // used by an earlier mov that will become a push. 286 287 if (MI->isCall() || MI->mayStore()) 288 return Exit; 289 290 for (const MachineOperand &MO : MI->operands()) { 291 if (!MO.isReg()) 292 continue; 293 unsigned int Reg = MO.getReg(); 294 if (!RegInfo.isPhysicalRegister(Reg)) 295 continue; 296 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister())) 297 return Exit; 298 if (MO.isDef()) { 299 for (unsigned int U : UsedRegs) 300 if (RegInfo.regsOverlap(Reg, U)) 301 return Exit; 302 } 303 } 304 305 return Skip; 306 } 307 308 void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF, 309 MachineBasicBlock &MBB, 310 MachineBasicBlock::iterator I, 311 CallContext &Context) { 312 // Check that this particular call sequence is amenable to the 313 // transformation. 314 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>( 315 STI->getRegisterInfo()); 316 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode(); 317 318 // We expect to enter this at the beginning of a call sequence 319 assert(I->getOpcode() == TII->getCallFrameSetupOpcode()); 320 MachineBasicBlock::iterator FrameSetup = I++; 321 Context.FrameSetup = FrameSetup; 322 323 // How much do we adjust the stack? This puts an upper bound on 324 // the number of parameters actually passed on it. 325 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4; 326 327 // A zero adjustment means no stack parameters 328 if (!MaxAdjust) { 329 Context.NoStackParams = true; 330 return; 331 } 332 333 // For globals in PIC mode, we can have some LEAs here. 334 // Ignore them, they don't bother us. 335 // TODO: Extend this to something that covers more cases. 336 while (I->getOpcode() == X86::LEA32r) 337 ++I; 338 339 // We expect a copy instruction here. 340 // TODO: The copy instruction is a lowering artifact. 341 // We should also support a copy-less version, where the stack 342 // pointer is used directly. 343 if (!I->isCopy() || !I->getOperand(0).isReg()) 344 return; 345 Context.SPCopy = I++; 346 347 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg(); 348 349 // Scan the call setup sequence for the pattern we're looking for. 350 // We only handle a simple case - a sequence of MOV32mi or MOV32mr 351 // instructions, that push a sequence of 32-bit values onto the stack, with 352 // no gaps between them. 353 if (MaxAdjust > 4) 354 Context.MovVector.resize(MaxAdjust, nullptr); 355 356 InstClassification Classification; 357 DenseSet<unsigned int> UsedRegs; 358 359 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) != 360 Exit) { 361 if (Classification == Skip) { 362 ++I; 363 continue; 364 } 365 366 // We know the instruction is a MOV32mi/MOV32mr. 367 // We only want movs of the form: 368 // movl imm/r32, k(%esp) 369 // If we run into something else, bail. 370 // Note that AddrBaseReg may, counter to its name, not be a register, 371 // but rather a frame index. 372 // TODO: Support the fi case. This should probably work now that we 373 // have the infrastructure to track the stack pointer within a call 374 // sequence. 375 if (!I->getOperand(X86::AddrBaseReg).isReg() || 376 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) || 377 !I->getOperand(X86::AddrScaleAmt).isImm() || 378 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) || 379 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) || 380 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) || 381 !I->getOperand(X86::AddrDisp).isImm()) 382 return; 383 384 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm(); 385 assert(StackDisp >= 0 && 386 "Negative stack displacement when passing parameters"); 387 388 // We really don't want to consider the unaligned case. 389 if (StackDisp % 4) 390 return; 391 StackDisp /= 4; 392 393 assert((size_t)StackDisp < Context.MovVector.size() && 394 "Function call has more parameters than the stack is adjusted for."); 395 396 // If the same stack slot is being filled twice, something's fishy. 397 if (Context.MovVector[StackDisp] != nullptr) 398 return; 399 Context.MovVector[StackDisp] = I; 400 401 for (const MachineOperand &MO : I->uses()) { 402 if (!MO.isReg()) 403 continue; 404 unsigned int Reg = MO.getReg(); 405 if (RegInfo.isPhysicalRegister(Reg)) 406 UsedRegs.insert(Reg); 407 } 408 409 ++I; 410 } 411 412 // We now expect the end of the sequence. If we stopped early, 413 // or reached the end of the block without finding a call, bail. 414 if (I == MBB.end() || !I->isCall()) 415 return; 416 417 Context.Call = I; 418 if ((++I)->getOpcode() != FrameDestroyOpcode) 419 return; 420 421 // Now, go through the vector, and see that we don't have any gaps, 422 // but only a series of 32-bit MOVs. 423 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end(); 424 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4) 425 if (*MMI == nullptr) 426 break; 427 428 // If the call had no parameters, do nothing 429 if (MMI == Context.MovVector.begin()) 430 return; 431 432 // We are either at the last parameter, or a gap. 433 // Make sure it's not a gap 434 for (; MMI != MME; ++MMI) 435 if (*MMI != nullptr) 436 return; 437 438 Context.UsePush = true; 439 } 440 441 bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF, 442 const CallContext &Context) { 443 // Ok, we can in fact do the transformation for this call. 444 // Do not remove the FrameSetup instruction, but adjust the parameters. 445 // PEI will end up finalizing the handling of this. 446 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup; 447 MachineBasicBlock &MBB = *(FrameSetup->getParent()); 448 FrameSetup->getOperand(1).setImm(Context.ExpectedDist); 449 450 DebugLoc DL = FrameSetup->getDebugLoc(); 451 // Now, iterate through the vector in reverse order, and replace the movs 452 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to 453 // replace uses. 454 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) { 455 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx]; 456 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands); 457 MachineBasicBlock::iterator Push = nullptr; 458 if (MOV->getOpcode() == X86::MOV32mi) { 459 unsigned PushOpcode = X86::PUSHi32; 460 // If the operand is a small (8-bit) immediate, we can use a 461 // PUSH instruction with a shorter encoding. 462 // Note that isImm() may fail even though this is a MOVmi, because 463 // the operand can also be a symbol. 464 if (PushOp.isImm()) { 465 int64_t Val = PushOp.getImm(); 466 if (isInt<8>(Val)) 467 PushOpcode = X86::PUSH32i8; 468 } 469 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)) 470 .addOperand(PushOp); 471 } else { 472 unsigned int Reg = PushOp.getReg(); 473 474 // If PUSHrmm is not slow on this target, try to fold the source of the 475 // push into the instruction. 476 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM(); 477 478 // Check that this is legal to fold. Right now, we're extremely 479 // conservative about that. 480 MachineInstr *DefMov = nullptr; 481 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) { 482 Push = BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm)); 483 484 unsigned NumOps = DefMov->getDesc().getNumOperands(); 485 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i) 486 Push->addOperand(DefMov->getOperand(i)); 487 488 DefMov->eraseFromParent(); 489 } else { 490 Push = BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r)) 491 .addReg(Reg) 492 .getInstr(); 493 } 494 } 495 496 // For debugging, when using SP-based CFA, we need to adjust the CFA 497 // offset after each push. 498 // TODO: This is needed only if we require precise CFA. 499 if (!TFL->hasFP(MF)) 500 TFL->BuildCFI(MBB, std::next(Push), DL, 501 MCCFIInstruction::createAdjustCfaOffset(nullptr, 4)); 502 503 MBB.erase(MOV); 504 } 505 506 // The stack-pointer copy is no longer used in the call sequences. 507 // There should not be any other users, but we can't commit to that, so: 508 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg())) 509 Context.SPCopy->eraseFromParent(); 510 511 // Once we've done this, we need to make sure PEI doesn't assume a reserved 512 // frame. 513 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 514 FuncInfo->setHasPushSequences(true); 515 516 return true; 517 } 518 519 MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush( 520 MachineBasicBlock::iterator FrameSetup, unsigned Reg) { 521 // Do an extremely restricted form of load folding. 522 // ISel will often create patterns like: 523 // movl 4(%edi), %eax 524 // movl 8(%edi), %ecx 525 // movl 12(%edi), %edx 526 // movl %edx, 8(%esp) 527 // movl %ecx, 4(%esp) 528 // movl %eax, (%esp) 529 // call 530 // Get rid of those with prejudice. 531 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 532 return nullptr; 533 534 // Make sure this is the only use of Reg. 535 if (!MRI->hasOneNonDBGUse(Reg)) 536 return nullptr; 537 538 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg); 539 540 // Make sure the def is a MOV from memory. 541 // If the def is an another block, give up. 542 if (DefMI->getOpcode() != X86::MOV32rm || 543 DefMI->getParent() != FrameSetup->getParent()) 544 return nullptr; 545 546 // Make sure we don't have any instructions between DefMI and the 547 // push that make folding the load illegal. 548 for (auto I = DefMI; I != FrameSetup; ++I) 549 if (I->isLoadFoldBarrier()) 550 return nullptr; 551 552 return DefMI; 553 } 554