1 //===-- AArch64ConditionalCompares.cpp --- CCMP formation for AArch64 -----===// 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 implements the AArch64ConditionalCompares pass which reduces 11 // branching and code size by using the conditional compare instructions CCMP, 12 // CCMN, and FCMP. 13 // 14 // The CFG transformations for forming conditional compares are very similar to 15 // if-conversion, and this pass should run immediately before the early 16 // if-conversion pass. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "AArch64.h" 21 #include "llvm/ADT/DepthFirstIterator.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 26 #include "llvm/CodeGen/MachineDominators.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineFunctionPass.h" 29 #include "llvm/CodeGen/MachineInstrBuilder.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/MachineTraceMetrics.h" 33 #include "llvm/CodeGen/Passes.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetInstrInfo.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "aarch64-ccmp" 44 45 // Absolute maximum number of instructions allowed per speculated block. 46 // This bypasses all other heuristics, so it should be set fairly high. 47 static cl::opt<unsigned> BlockInstrLimit( 48 "aarch64-ccmp-limit", cl::init(30), cl::Hidden, 49 cl::desc("Maximum number of instructions per speculated block.")); 50 51 // Stress testing mode - disable heuristics. 52 static cl::opt<bool> Stress("aarch64-stress-ccmp", cl::Hidden, 53 cl::desc("Turn all knobs to 11")); 54 55 STATISTIC(NumConsidered, "Number of ccmps considered"); 56 STATISTIC(NumPhiRejs, "Number of ccmps rejected (PHI)"); 57 STATISTIC(NumPhysRejs, "Number of ccmps rejected (Physregs)"); 58 STATISTIC(NumPhi2Rejs, "Number of ccmps rejected (PHI2)"); 59 STATISTIC(NumHeadBranchRejs, "Number of ccmps rejected (Head branch)"); 60 STATISTIC(NumCmpBranchRejs, "Number of ccmps rejected (CmpBB branch)"); 61 STATISTIC(NumCmpTermRejs, "Number of ccmps rejected (CmpBB is cbz...)"); 62 STATISTIC(NumImmRangeRejs, "Number of ccmps rejected (Imm out of range)"); 63 STATISTIC(NumLiveDstRejs, "Number of ccmps rejected (Cmp dest live)"); 64 STATISTIC(NumMultNZCVUses, "Number of ccmps rejected (NZCV used)"); 65 STATISTIC(NumUnknNZCVDefs, "Number of ccmps rejected (NZCV def unknown)"); 66 67 STATISTIC(NumSpeculateRejs, "Number of ccmps rejected (Can't speculate)"); 68 69 STATISTIC(NumConverted, "Number of ccmp instructions created"); 70 STATISTIC(NumCompBranches, "Number of cbz/cbnz branches converted"); 71 72 //===----------------------------------------------------------------------===// 73 // SSACCmpConv 74 //===----------------------------------------------------------------------===// 75 // 76 // The SSACCmpConv class performs ccmp-conversion on SSA form machine code 77 // after determining if it is possible. The class contains no heuristics; 78 // external code should be used to determine when ccmp-conversion is a good 79 // idea. 80 // 81 // CCmp-formation works on a CFG representing chained conditions, typically 82 // from C's short-circuit || and && operators: 83 // 84 // From: Head To: Head 85 // / | CmpBB 86 // / | / | 87 // | CmpBB / | 88 // | / | Tail | 89 // | / | | | 90 // Tail | | | 91 // | | | | 92 // ... ... ... ... 93 // 94 // The Head block is terminated by a br.cond instruction, and the CmpBB block 95 // contains compare + br.cond. Tail must be a successor of both. 96 // 97 // The cmp-conversion turns the compare instruction in CmpBB into a conditional 98 // compare, and merges CmpBB into Head, speculatively executing its 99 // instructions. The AArch64 conditional compare instructions have an immediate 100 // operand that specifies the NZCV flag values when the condition is false and 101 // the compare isn't executed. This makes it possible to chain compares with 102 // different condition codes. 103 // 104 // Example: 105 // 106 // if (a == 5 || b == 17) 107 // foo(); 108 // 109 // Head: 110 // cmp w0, #5 111 // b.eq Tail 112 // CmpBB: 113 // cmp w1, #17 114 // b.eq Tail 115 // ... 116 // Tail: 117 // bl _foo 118 // 119 // Becomes: 120 // 121 // Head: 122 // cmp w0, #5 123 // ccmp w1, #17, 4, ne ; 4 = nZcv 124 // b.eq Tail 125 // ... 126 // Tail: 127 // bl _foo 128 // 129 // The ccmp condition code is the one that would cause the Head terminator to 130 // branch to CmpBB. 131 // 132 // FIXME: It should also be possible to speculate a block on the critical edge 133 // between Head and Tail, just like if-converting a diamond. 134 // 135 // FIXME: Handle PHIs in Tail by turning them into selects (if-conversion). 136 137 namespace { 138 class SSACCmpConv { 139 MachineFunction *MF; 140 const TargetInstrInfo *TII; 141 const TargetRegisterInfo *TRI; 142 MachineRegisterInfo *MRI; 143 144 public: 145 /// The first block containing a conditional branch, dominating everything 146 /// else. 147 MachineBasicBlock *Head; 148 149 /// The block containing cmp+br.cond with a successor shared with Head. 150 MachineBasicBlock *CmpBB; 151 152 /// The common successor for Head and CmpBB. 153 MachineBasicBlock *Tail; 154 155 /// The compare instruction in CmpBB that can be converted to a ccmp. 156 MachineInstr *CmpMI; 157 158 private: 159 /// The branch condition in Head as determined by AnalyzeBranch. 160 SmallVector<MachineOperand, 4> HeadCond; 161 162 /// The condition code that makes Head branch to CmpBB. 163 AArch64CC::CondCode HeadCmpBBCC; 164 165 /// The branch condition in CmpBB. 166 SmallVector<MachineOperand, 4> CmpBBCond; 167 168 /// The condition code that makes CmpBB branch to Tail. 169 AArch64CC::CondCode CmpBBTailCC; 170 171 /// Check if the Tail PHIs are trivially convertible. 172 bool trivialTailPHIs(); 173 174 /// Remove CmpBB from the Tail PHIs. 175 void updateTailPHIs(); 176 177 /// Check if an operand defining DstReg is dead. 178 bool isDeadDef(unsigned DstReg); 179 180 /// Find the compare instruction in MBB that controls the conditional branch. 181 /// Return NULL if a convertible instruction can't be found. 182 MachineInstr *findConvertibleCompare(MachineBasicBlock *MBB); 183 184 /// Return true if all non-terminator instructions in MBB can be safely 185 /// speculated. 186 bool canSpeculateInstrs(MachineBasicBlock *MBB, const MachineInstr *CmpMI); 187 188 public: 189 /// runOnMachineFunction - Initialize per-function data structures. 190 void runOnMachineFunction(MachineFunction &MF) { 191 this->MF = &MF; 192 TII = MF.getSubtarget().getInstrInfo(); 193 TRI = MF.getSubtarget().getRegisterInfo(); 194 MRI = &MF.getRegInfo(); 195 } 196 197 /// If the sub-CFG headed by MBB can be cmp-converted, initialize the 198 /// internal state, and return true. 199 bool canConvert(MachineBasicBlock *MBB); 200 201 /// Cmo-convert the last block passed to canConvertCmp(), assuming 202 /// it is possible. Add any erased blocks to RemovedBlocks. 203 void convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks); 204 205 /// Return the expected code size delta if the conversion into a 206 /// conditional compare is performed. 207 int expectedCodeSizeDelta() const; 208 }; 209 } // end anonymous namespace 210 211 // Check that all PHIs in Tail are selecting the same value from Head and CmpBB. 212 // This means that no if-conversion is required when merging CmpBB into Head. 213 bool SSACCmpConv::trivialTailPHIs() { 214 for (auto &I : *Tail) { 215 if (!I.isPHI()) 216 break; 217 unsigned HeadReg = 0, CmpBBReg = 0; 218 // PHI operands come in (VReg, MBB) pairs. 219 for (unsigned oi = 1, oe = I.getNumOperands(); oi != oe; oi += 2) { 220 MachineBasicBlock *MBB = I.getOperand(oi + 1).getMBB(); 221 unsigned Reg = I.getOperand(oi).getReg(); 222 if (MBB == Head) { 223 assert((!HeadReg || HeadReg == Reg) && "Inconsistent PHI operands"); 224 HeadReg = Reg; 225 } 226 if (MBB == CmpBB) { 227 assert((!CmpBBReg || CmpBBReg == Reg) && "Inconsistent PHI operands"); 228 CmpBBReg = Reg; 229 } 230 } 231 if (HeadReg != CmpBBReg) 232 return false; 233 } 234 return true; 235 } 236 237 // Assuming that trivialTailPHIs() is true, update the Tail PHIs by simply 238 // removing the CmpBB operands. The Head operands will be identical. 239 void SSACCmpConv::updateTailPHIs() { 240 for (auto &I : *Tail) { 241 if (!I.isPHI()) 242 break; 243 // I is a PHI. It can have multiple entries for CmpBB. 244 for (unsigned oi = I.getNumOperands(); oi > 2; oi -= 2) { 245 // PHI operands are (Reg, MBB) at (oi-2, oi-1). 246 if (I.getOperand(oi - 1).getMBB() == CmpBB) { 247 I.RemoveOperand(oi - 1); 248 I.RemoveOperand(oi - 2); 249 } 250 } 251 } 252 } 253 254 // This pass runs before the AArch64DeadRegisterDefinitions pass, so compares 255 // are still writing virtual registers without any uses. 256 bool SSACCmpConv::isDeadDef(unsigned DstReg) { 257 // Writes to the zero register are dead. 258 if (DstReg == AArch64::WZR || DstReg == AArch64::XZR) 259 return true; 260 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 261 return false; 262 // A virtual register def without any uses will be marked dead later, and 263 // eventually replaced by the zero register. 264 return MRI->use_nodbg_empty(DstReg); 265 } 266 267 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode 268 // corresponding to TBB. 269 // Return 270 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) { 271 // A normal br.cond simply has the condition code. 272 if (Cond[0].getImm() != -1) { 273 assert(Cond.size() == 1 && "Unknown Cond array format"); 274 CC = (AArch64CC::CondCode)(int)Cond[0].getImm(); 275 return true; 276 } 277 // For tbz and cbz instruction, the opcode is next. 278 switch (Cond[1].getImm()) { 279 default: 280 // This includes tbz / tbnz branches which can't be converted to 281 // ccmp + br.cond. 282 return false; 283 case AArch64::CBZW: 284 case AArch64::CBZX: 285 assert(Cond.size() == 3 && "Unknown Cond array format"); 286 CC = AArch64CC::EQ; 287 return true; 288 case AArch64::CBNZW: 289 case AArch64::CBNZX: 290 assert(Cond.size() == 3 && "Unknown Cond array format"); 291 CC = AArch64CC::NE; 292 return true; 293 } 294 } 295 296 MachineInstr *SSACCmpConv::findConvertibleCompare(MachineBasicBlock *MBB) { 297 MachineBasicBlock::iterator I = MBB->getFirstTerminator(); 298 if (I == MBB->end()) 299 return nullptr; 300 // The terminator must be controlled by the flags. 301 if (!I->readsRegister(AArch64::NZCV)) { 302 switch (I->getOpcode()) { 303 case AArch64::CBZW: 304 case AArch64::CBZX: 305 case AArch64::CBNZW: 306 case AArch64::CBNZX: 307 // These can be converted into a ccmp against #0. 308 return I; 309 } 310 ++NumCmpTermRejs; 311 DEBUG(dbgs() << "Flags not used by terminator: " << *I); 312 return nullptr; 313 } 314 315 // Now find the instruction controlling the terminator. 316 for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) { 317 --I; 318 assert(!I->isTerminator() && "Spurious terminator"); 319 switch (I->getOpcode()) { 320 // cmp is an alias for subs with a dead destination register. 321 case AArch64::SUBSWri: 322 case AArch64::SUBSXri: 323 // cmn is an alias for adds with a dead destination register. 324 case AArch64::ADDSWri: 325 case AArch64::ADDSXri: 326 // Check that the immediate operand is within range, ccmp wants a uimm5. 327 // Rd = SUBSri Rn, imm, shift 328 if (I->getOperand(3).getImm() || !isUInt<5>(I->getOperand(2).getImm())) { 329 DEBUG(dbgs() << "Immediate out of range for ccmp: " << *I); 330 ++NumImmRangeRejs; 331 return nullptr; 332 } 333 // Fall through. 334 case AArch64::SUBSWrr: 335 case AArch64::SUBSXrr: 336 case AArch64::ADDSWrr: 337 case AArch64::ADDSXrr: 338 if (isDeadDef(I->getOperand(0).getReg())) 339 return I; 340 DEBUG(dbgs() << "Can't convert compare with live destination: " << *I); 341 ++NumLiveDstRejs; 342 return nullptr; 343 case AArch64::FCMPSrr: 344 case AArch64::FCMPDrr: 345 case AArch64::FCMPESrr: 346 case AArch64::FCMPEDrr: 347 return I; 348 } 349 350 // Check for flag reads and clobbers. 351 MIOperands::PhysRegInfo PRI = 352 MIOperands(*I).analyzePhysReg(AArch64::NZCV, TRI); 353 354 if (PRI.Read) { 355 // The ccmp doesn't produce exactly the same flags as the original 356 // compare, so reject the transform if there are uses of the flags 357 // besides the terminators. 358 DEBUG(dbgs() << "Can't create ccmp with multiple uses: " << *I); 359 ++NumMultNZCVUses; 360 return nullptr; 361 } 362 363 if (PRI.Defined || PRI.Clobbered) { 364 DEBUG(dbgs() << "Not convertible compare: " << *I); 365 ++NumUnknNZCVDefs; 366 return nullptr; 367 } 368 } 369 DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n'); 370 return nullptr; 371 } 372 373 /// Determine if all the instructions in MBB can safely 374 /// be speculated. The terminators are not considered. 375 /// 376 /// Only CmpMI is allowed to clobber the flags. 377 /// 378 bool SSACCmpConv::canSpeculateInstrs(MachineBasicBlock *MBB, 379 const MachineInstr *CmpMI) { 380 // Reject any live-in physregs. It's probably NZCV/EFLAGS, and very hard to 381 // get right. 382 if (!MBB->livein_empty()) { 383 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n"); 384 return false; 385 } 386 387 unsigned InstrCount = 0; 388 389 // Check all instructions, except the terminators. It is assumed that 390 // terminators never have side effects or define any used register values. 391 for (auto &I : make_range(MBB->begin(), MBB->getFirstTerminator())) { 392 if (I.isDebugValue()) 393 continue; 394 395 if (++InstrCount > BlockInstrLimit && !Stress) { 396 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than " 397 << BlockInstrLimit << " instructions.\n"); 398 return false; 399 } 400 401 // There shouldn't normally be any phis in a single-predecessor block. 402 if (I.isPHI()) { 403 DEBUG(dbgs() << "Can't hoist: " << I); 404 return false; 405 } 406 407 // Don't speculate loads. Note that it may be possible and desirable to 408 // speculate GOT or constant pool loads that are guaranteed not to trap, 409 // but we don't support that for now. 410 if (I.mayLoad()) { 411 DEBUG(dbgs() << "Won't speculate load: " << I); 412 return false; 413 } 414 415 // We never speculate stores, so an AA pointer isn't necessary. 416 bool DontMoveAcrossStore = true; 417 if (!I.isSafeToMove(nullptr, DontMoveAcrossStore)) { 418 DEBUG(dbgs() << "Can't speculate: " << I); 419 return false; 420 } 421 422 // Only CmpMI is allowed to clobber the flags. 423 if (&I != CmpMI && I.modifiesRegister(AArch64::NZCV, TRI)) { 424 DEBUG(dbgs() << "Clobbers flags: " << I); 425 return false; 426 } 427 } 428 return true; 429 } 430 431 /// Analyze the sub-cfg rooted in MBB, and return true if it is a potential 432 /// candidate for cmp-conversion. Fill out the internal state. 433 /// 434 bool SSACCmpConv::canConvert(MachineBasicBlock *MBB) { 435 Head = MBB; 436 Tail = CmpBB = nullptr; 437 438 if (Head->succ_size() != 2) 439 return false; 440 MachineBasicBlock *Succ0 = Head->succ_begin()[0]; 441 MachineBasicBlock *Succ1 = Head->succ_begin()[1]; 442 443 // CmpBB can only have a single predecessor. Tail is allowed many. 444 if (Succ0->pred_size() != 1) 445 std::swap(Succ0, Succ1); 446 447 // Succ0 is our candidate for CmpBB. 448 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 2) 449 return false; 450 451 CmpBB = Succ0; 452 Tail = Succ1; 453 454 if (!CmpBB->isSuccessor(Tail)) 455 return false; 456 457 // The CFG topology checks out. 458 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber() << " -> BB#" 459 << CmpBB->getNumber() << " -> BB#" << Tail->getNumber() << '\n'); 460 ++NumConsidered; 461 462 // Tail is allowed to have many predecessors, but we can't handle PHIs yet. 463 // 464 // FIXME: Real PHIs could be if-converted as long as the CmpBB values are 465 // defined before The CmpBB cmp clobbers the flags. Alternatively, it should 466 // always be safe to sink the ccmp down to immediately before the CmpBB 467 // terminators. 468 if (!trivialTailPHIs()) { 469 DEBUG(dbgs() << "Can't handle phis in Tail.\n"); 470 ++NumPhiRejs; 471 return false; 472 } 473 474 if (!Tail->livein_empty()) { 475 DEBUG(dbgs() << "Can't handle live-in physregs in Tail.\n"); 476 ++NumPhysRejs; 477 return false; 478 } 479 480 // CmpBB should never have PHIs since Head is its only predecessor. 481 // FIXME: Clean them up if it happens. 482 if (!CmpBB->empty() && CmpBB->front().isPHI()) { 483 DEBUG(dbgs() << "Can't handle phis in CmpBB.\n"); 484 ++NumPhi2Rejs; 485 return false; 486 } 487 488 if (!CmpBB->livein_empty()) { 489 DEBUG(dbgs() << "Can't handle live-in physregs in CmpBB.\n"); 490 ++NumPhysRejs; 491 return false; 492 } 493 494 // The branch we're looking to eliminate must be analyzable. 495 HeadCond.clear(); 496 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 497 if (TII->AnalyzeBranch(*Head, TBB, FBB, HeadCond)) { 498 DEBUG(dbgs() << "Head branch not analyzable.\n"); 499 ++NumHeadBranchRejs; 500 return false; 501 } 502 503 // This is weird, probably some sort of degenerate CFG, or an edge to a 504 // landing pad. 505 if (!TBB || HeadCond.empty()) { 506 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in Head.\n"); 507 ++NumHeadBranchRejs; 508 return false; 509 } 510 511 if (!parseCond(HeadCond, HeadCmpBBCC)) { 512 DEBUG(dbgs() << "Unsupported branch type on Head\n"); 513 ++NumHeadBranchRejs; 514 return false; 515 } 516 517 // Make sure the branch direction is right. 518 if (TBB != CmpBB) { 519 assert(TBB == Tail && "Unexpected TBB"); 520 HeadCmpBBCC = AArch64CC::getInvertedCondCode(HeadCmpBBCC); 521 } 522 523 CmpBBCond.clear(); 524 TBB = FBB = nullptr; 525 if (TII->AnalyzeBranch(*CmpBB, TBB, FBB, CmpBBCond)) { 526 DEBUG(dbgs() << "CmpBB branch not analyzable.\n"); 527 ++NumCmpBranchRejs; 528 return false; 529 } 530 531 if (!TBB || CmpBBCond.empty()) { 532 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in CmpBB.\n"); 533 ++NumCmpBranchRejs; 534 return false; 535 } 536 537 if (!parseCond(CmpBBCond, CmpBBTailCC)) { 538 DEBUG(dbgs() << "Unsupported branch type on CmpBB\n"); 539 ++NumCmpBranchRejs; 540 return false; 541 } 542 543 if (TBB != Tail) 544 CmpBBTailCC = AArch64CC::getInvertedCondCode(CmpBBTailCC); 545 546 DEBUG(dbgs() << "Head->CmpBB on " << AArch64CC::getCondCodeName(HeadCmpBBCC) 547 << ", CmpBB->Tail on " << AArch64CC::getCondCodeName(CmpBBTailCC) 548 << '\n'); 549 550 CmpMI = findConvertibleCompare(CmpBB); 551 if (!CmpMI) 552 return false; 553 554 if (!canSpeculateInstrs(CmpBB, CmpMI)) { 555 ++NumSpeculateRejs; 556 return false; 557 } 558 return true; 559 } 560 561 void SSACCmpConv::convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks) { 562 DEBUG(dbgs() << "Merging BB#" << CmpBB->getNumber() << " into BB#" 563 << Head->getNumber() << ":\n" << *CmpBB); 564 565 // All CmpBB instructions are moved into Head, and CmpBB is deleted. 566 // Update the CFG first. 567 updateTailPHIs(); 568 Head->removeSuccessor(CmpBB, true); 569 CmpBB->removeSuccessor(Tail, true); 570 Head->transferSuccessorsAndUpdatePHIs(CmpBB); 571 DebugLoc TermDL = Head->getFirstTerminator()->getDebugLoc(); 572 TII->RemoveBranch(*Head); 573 574 // If the Head terminator was one of the cbz / tbz branches with built-in 575 // compare, we need to insert an explicit compare instruction in its place. 576 if (HeadCond[0].getImm() == -1) { 577 ++NumCompBranches; 578 unsigned Opc = 0; 579 switch (HeadCond[1].getImm()) { 580 case AArch64::CBZW: 581 case AArch64::CBNZW: 582 Opc = AArch64::SUBSWri; 583 break; 584 case AArch64::CBZX: 585 case AArch64::CBNZX: 586 Opc = AArch64::SUBSXri; 587 break; 588 default: 589 llvm_unreachable("Cannot convert Head branch"); 590 } 591 const MCInstrDesc &MCID = TII->get(Opc); 592 // Create a dummy virtual register for the SUBS def. 593 unsigned DestReg = 594 MRI->createVirtualRegister(TII->getRegClass(MCID, 0, TRI, *MF)); 595 // Insert a SUBS Rn, #0 instruction instead of the cbz / cbnz. 596 BuildMI(*Head, Head->end(), TermDL, MCID) 597 .addReg(DestReg, RegState::Define | RegState::Dead) 598 .addOperand(HeadCond[2]) 599 .addImm(0) 600 .addImm(0); 601 // SUBS uses the GPR*sp register classes. 602 MRI->constrainRegClass(HeadCond[2].getReg(), 603 TII->getRegClass(MCID, 1, TRI, *MF)); 604 } 605 606 Head->splice(Head->end(), CmpBB, CmpBB->begin(), CmpBB->end()); 607 608 // Now replace CmpMI with a ccmp instruction that also considers the incoming 609 // flags. 610 unsigned Opc = 0; 611 unsigned FirstOp = 1; // First CmpMI operand to copy. 612 bool isZBranch = false; // CmpMI is a cbz/cbnz instruction. 613 switch (CmpMI->getOpcode()) { 614 default: 615 llvm_unreachable("Unknown compare opcode"); 616 case AArch64::SUBSWri: Opc = AArch64::CCMPWi; break; 617 case AArch64::SUBSWrr: Opc = AArch64::CCMPWr; break; 618 case AArch64::SUBSXri: Opc = AArch64::CCMPXi; break; 619 case AArch64::SUBSXrr: Opc = AArch64::CCMPXr; break; 620 case AArch64::ADDSWri: Opc = AArch64::CCMNWi; break; 621 case AArch64::ADDSWrr: Opc = AArch64::CCMNWr; break; 622 case AArch64::ADDSXri: Opc = AArch64::CCMNXi; break; 623 case AArch64::ADDSXrr: Opc = AArch64::CCMNXr; break; 624 case AArch64::FCMPSrr: Opc = AArch64::FCCMPSrr; FirstOp = 0; break; 625 case AArch64::FCMPDrr: Opc = AArch64::FCCMPDrr; FirstOp = 0; break; 626 case AArch64::FCMPESrr: Opc = AArch64::FCCMPESrr; FirstOp = 0; break; 627 case AArch64::FCMPEDrr: Opc = AArch64::FCCMPEDrr; FirstOp = 0; break; 628 case AArch64::CBZW: 629 case AArch64::CBNZW: 630 Opc = AArch64::CCMPWi; 631 FirstOp = 0; 632 isZBranch = true; 633 break; 634 case AArch64::CBZX: 635 case AArch64::CBNZX: 636 Opc = AArch64::CCMPXi; 637 FirstOp = 0; 638 isZBranch = true; 639 break; 640 } 641 642 // The ccmp instruction should set the flags according to the comparison when 643 // Head would have branched to CmpBB. 644 // The NZCV immediate operand should provide flags for the case where Head 645 // would have branched to Tail. These flags should cause the new Head 646 // terminator to branch to tail. 647 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(CmpBBTailCC); 648 const MCInstrDesc &MCID = TII->get(Opc); 649 MRI->constrainRegClass(CmpMI->getOperand(FirstOp).getReg(), 650 TII->getRegClass(MCID, 0, TRI, *MF)); 651 if (CmpMI->getOperand(FirstOp + 1).isReg()) 652 MRI->constrainRegClass(CmpMI->getOperand(FirstOp + 1).getReg(), 653 TII->getRegClass(MCID, 1, TRI, *MF)); 654 MachineInstrBuilder MIB = 655 BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), MCID) 656 .addOperand(CmpMI->getOperand(FirstOp)); // Register Rn 657 if (isZBranch) 658 MIB.addImm(0); // cbz/cbnz Rn -> ccmp Rn, #0 659 else 660 MIB.addOperand(CmpMI->getOperand(FirstOp + 1)); // Register Rm / Immediate 661 MIB.addImm(NZCV).addImm(HeadCmpBBCC); 662 663 // If CmpMI was a terminator, we need a new conditional branch to replace it. 664 // This now becomes a Head terminator. 665 if (isZBranch) { 666 bool isNZ = CmpMI->getOpcode() == AArch64::CBNZW || 667 CmpMI->getOpcode() == AArch64::CBNZX; 668 BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), TII->get(AArch64::Bcc)) 669 .addImm(isNZ ? AArch64CC::NE : AArch64CC::EQ) 670 .addOperand(CmpMI->getOperand(1)); // Branch target. 671 } 672 CmpMI->eraseFromParent(); 673 Head->updateTerminator(); 674 675 RemovedBlocks.push_back(CmpBB); 676 CmpBB->eraseFromParent(); 677 DEBUG(dbgs() << "Result:\n" << *Head); 678 ++NumConverted; 679 } 680 681 int SSACCmpConv::expectedCodeSizeDelta() const { 682 int delta = 0; 683 // If the Head terminator was one of the cbz / tbz branches with built-in 684 // compare, we need to insert an explicit compare instruction in its place 685 // plus a branch instruction. 686 if (HeadCond[0].getImm() == -1) { 687 switch (HeadCond[1].getImm()) { 688 case AArch64::CBZW: 689 case AArch64::CBNZW: 690 case AArch64::CBZX: 691 case AArch64::CBNZX: 692 // Therefore delta += 1 693 delta = 1; 694 break; 695 default: 696 llvm_unreachable("Cannot convert Head branch"); 697 } 698 } 699 // If the Cmp terminator was one of the cbz / tbz branches with 700 // built-in compare, it will be turned into a compare instruction 701 // into Head, but we do not save any instruction. 702 // Otherwise, we save the branch instruction. 703 switch (CmpMI->getOpcode()) { 704 default: 705 --delta; 706 break; 707 case AArch64::CBZW: 708 case AArch64::CBNZW: 709 case AArch64::CBZX: 710 case AArch64::CBNZX: 711 break; 712 } 713 return delta; 714 } 715 716 //===----------------------------------------------------------------------===// 717 // AArch64ConditionalCompares Pass 718 //===----------------------------------------------------------------------===// 719 720 namespace { 721 class AArch64ConditionalCompares : public MachineFunctionPass { 722 const TargetInstrInfo *TII; 723 const TargetRegisterInfo *TRI; 724 MCSchedModel SchedModel; 725 // Does the proceeded function has Oz attribute. 726 bool MinSize; 727 MachineRegisterInfo *MRI; 728 MachineDominatorTree *DomTree; 729 MachineLoopInfo *Loops; 730 MachineTraceMetrics *Traces; 731 MachineTraceMetrics::Ensemble *MinInstr; 732 SSACCmpConv CmpConv; 733 734 public: 735 static char ID; 736 AArch64ConditionalCompares() : MachineFunctionPass(ID) {} 737 void getAnalysisUsage(AnalysisUsage &AU) const override; 738 bool runOnMachineFunction(MachineFunction &MF) override; 739 const char *getPassName() const override { 740 return "AArch64 Conditional Compares"; 741 } 742 743 private: 744 bool tryConvert(MachineBasicBlock *); 745 void updateDomTree(ArrayRef<MachineBasicBlock *> Removed); 746 void updateLoops(ArrayRef<MachineBasicBlock *> Removed); 747 void invalidateTraces(); 748 bool shouldConvert(); 749 }; 750 } // end anonymous namespace 751 752 char AArch64ConditionalCompares::ID = 0; 753 754 namespace llvm { 755 void initializeAArch64ConditionalComparesPass(PassRegistry &); 756 } 757 758 INITIALIZE_PASS_BEGIN(AArch64ConditionalCompares, "aarch64-ccmp", 759 "AArch64 CCMP Pass", false, false) 760 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 761 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 762 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics) 763 INITIALIZE_PASS_END(AArch64ConditionalCompares, "aarch64-ccmp", 764 "AArch64 CCMP Pass", false, false) 765 766 FunctionPass *llvm::createAArch64ConditionalCompares() { 767 return new AArch64ConditionalCompares(); 768 } 769 770 void AArch64ConditionalCompares::getAnalysisUsage(AnalysisUsage &AU) const { 771 AU.addRequired<MachineBranchProbabilityInfo>(); 772 AU.addRequired<MachineDominatorTree>(); 773 AU.addPreserved<MachineDominatorTree>(); 774 AU.addRequired<MachineLoopInfo>(); 775 AU.addPreserved<MachineLoopInfo>(); 776 AU.addRequired<MachineTraceMetrics>(); 777 AU.addPreserved<MachineTraceMetrics>(); 778 MachineFunctionPass::getAnalysisUsage(AU); 779 } 780 781 /// Update the dominator tree after if-conversion erased some blocks. 782 void AArch64ConditionalCompares::updateDomTree( 783 ArrayRef<MachineBasicBlock *> Removed) { 784 // convert() removes CmpBB which was previously dominated by Head. 785 // CmpBB children should be transferred to Head. 786 MachineDomTreeNode *HeadNode = DomTree->getNode(CmpConv.Head); 787 for (MachineBasicBlock *RemovedMBB : Removed) { 788 MachineDomTreeNode *Node = DomTree->getNode(RemovedMBB); 789 assert(Node != HeadNode && "Cannot erase the head node"); 790 assert(Node->getIDom() == HeadNode && "CmpBB should be dominated by Head"); 791 while (Node->getNumChildren()) 792 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode); 793 DomTree->eraseNode(RemovedMBB); 794 } 795 } 796 797 /// Update LoopInfo after if-conversion. 798 void 799 AArch64ConditionalCompares::updateLoops(ArrayRef<MachineBasicBlock *> Removed) { 800 if (!Loops) 801 return; 802 for (MachineBasicBlock *RemovedMBB : Removed) 803 Loops->removeBlock(RemovedMBB); 804 } 805 806 /// Invalidate MachineTraceMetrics before if-conversion. 807 void AArch64ConditionalCompares::invalidateTraces() { 808 Traces->invalidate(CmpConv.Head); 809 Traces->invalidate(CmpConv.CmpBB); 810 } 811 812 /// Apply cost model and heuristics to the if-conversion in IfConv. 813 /// Return true if the conversion is a good idea. 814 /// 815 bool AArch64ConditionalCompares::shouldConvert() { 816 // Stress testing mode disables all cost considerations. 817 if (Stress) 818 return true; 819 if (!MinInstr) 820 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount); 821 822 // Head dominates CmpBB, so it is always included in its trace. 823 MachineTraceMetrics::Trace Trace = MinInstr->getTrace(CmpConv.CmpBB); 824 825 // If code size is the main concern 826 if (MinSize) { 827 int CodeSizeDelta = CmpConv.expectedCodeSizeDelta(); 828 DEBUG(dbgs() << "Code size delta: " << CodeSizeDelta << '\n'); 829 // If we are minimizing the code size, do the conversion whatever 830 // the cost is. 831 if (CodeSizeDelta < 0) 832 return true; 833 if (CodeSizeDelta > 0) { 834 DEBUG(dbgs() << "Code size is increasing, give up on this one.\n"); 835 return false; 836 } 837 // CodeSizeDelta == 0, continue with the regular heuristics 838 } 839 840 // Heuristic: The compare conversion delays the execution of the branch 841 // instruction because we must wait for the inputs to the second compare as 842 // well. The branch has no dependent instructions, but delaying it increases 843 // the cost of a misprediction. 844 // 845 // Set a limit on the delay we will accept. 846 unsigned DelayLimit = SchedModel.MispredictPenalty * 3 / 4; 847 848 // Instruction depths can be computed for all trace instructions above CmpBB. 849 unsigned HeadDepth = 850 Trace.getInstrCycles(*CmpConv.Head->getFirstTerminator()).Depth; 851 unsigned CmpBBDepth = 852 Trace.getInstrCycles(*CmpConv.CmpBB->getFirstTerminator()).Depth; 853 DEBUG(dbgs() << "Head depth: " << HeadDepth 854 << "\nCmpBB depth: " << CmpBBDepth << '\n'); 855 if (CmpBBDepth > HeadDepth + DelayLimit) { 856 DEBUG(dbgs() << "Branch delay would be larger than " << DelayLimit 857 << " cycles.\n"); 858 return false; 859 } 860 861 // Check the resource depth at the bottom of CmpBB - these instructions will 862 // be speculated. 863 unsigned ResDepth = Trace.getResourceDepth(true); 864 DEBUG(dbgs() << "Resources: " << ResDepth << '\n'); 865 866 // Heuristic: The speculatively executed instructions must all be able to 867 // merge into the Head block. The Head critical path should dominate the 868 // resource cost of the speculated instructions. 869 if (ResDepth > HeadDepth) { 870 DEBUG(dbgs() << "Too many instructions to speculate.\n"); 871 return false; 872 } 873 return true; 874 } 875 876 bool AArch64ConditionalCompares::tryConvert(MachineBasicBlock *MBB) { 877 bool Changed = false; 878 while (CmpConv.canConvert(MBB) && shouldConvert()) { 879 invalidateTraces(); 880 SmallVector<MachineBasicBlock *, 4> RemovedBlocks; 881 CmpConv.convert(RemovedBlocks); 882 Changed = true; 883 updateDomTree(RemovedBlocks); 884 updateLoops(RemovedBlocks); 885 } 886 return Changed; 887 } 888 889 bool AArch64ConditionalCompares::runOnMachineFunction(MachineFunction &MF) { 890 DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n" 891 << "********** Function: " << MF.getName() << '\n'); 892 if (skipFunction(*MF.getFunction())) 893 return false; 894 895 TII = MF.getSubtarget().getInstrInfo(); 896 TRI = MF.getSubtarget().getRegisterInfo(); 897 SchedModel = MF.getSubtarget().getSchedModel(); 898 MRI = &MF.getRegInfo(); 899 DomTree = &getAnalysis<MachineDominatorTree>(); 900 Loops = getAnalysisIfAvailable<MachineLoopInfo>(); 901 Traces = &getAnalysis<MachineTraceMetrics>(); 902 MinInstr = nullptr; 903 MinSize = MF.getFunction()->optForMinSize(); 904 905 bool Changed = false; 906 CmpConv.runOnMachineFunction(MF); 907 908 // Visit blocks in dominator tree pre-order. The pre-order enables multiple 909 // cmp-conversions from the same head block. 910 // Note that updateDomTree() modifies the children of the DomTree node 911 // currently being visited. The df_iterator supports that; it doesn't look at 912 // child_begin() / child_end() until after a node has been visited. 913 for (auto *I : depth_first(DomTree)) 914 if (tryConvert(I->getBlock())) 915 Changed = true; 916 917 return Changed; 918 } 919