1 //===-- AArch64ConditionalCompares.cpp --- CCMP formation for AArch64 -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AArch64ConditionalCompares pass which reduces
11 // branching and code size by using the conditional compare instructions CCMP,
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.
18 //===----------------------------------------------------------------------===//
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/CodeGen/TargetInstrInfo.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "aarch64-ccmp"
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."));
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"));
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)");
67 STATISTIC(NumSpeculateRejs, "Number of ccmps rejected (Can't speculate)");
69 STATISTIC(NumConverted, "Number of ccmp instructions created");
70 STATISTIC(NumCompBranches, "Number of cbz/cbnz branches converted");
72 //===----------------------------------------------------------------------===//
74 //===----------------------------------------------------------------------===//
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
81 // CCmp-formation works on a CFG representing chained conditions, typically
82 // from C's short-circuit || and && operators:
84 // From: Head To: Head
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.
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.
106 // if (a == 5 || b == 17)
123 // ccmp w1, #17, 4, ne ; 4 = nZcv
129 // The ccmp condition code is the one that would cause the Head terminator to
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.
135 // FIXME: Handle PHIs in Tail by turning them into selects (if-conversion).
140 const TargetInstrInfo *TII;
141 const TargetRegisterInfo *TRI;
142 MachineRegisterInfo *MRI;
143 const MachineBranchProbabilityInfo *MBPI;
146 /// The first block containing a conditional branch, dominating everything
148 MachineBasicBlock *Head;
150 /// The block containing cmp+br.cond with a successor shared with Head.
151 MachineBasicBlock *CmpBB;
153 /// The common successor for Head and CmpBB.
154 MachineBasicBlock *Tail;
156 /// The compare instruction in CmpBB that can be converted to a ccmp.
160 /// The branch condition in Head as determined by AnalyzeBranch.
161 SmallVector<MachineOperand, 4> HeadCond;
163 /// The condition code that makes Head branch to CmpBB.
164 AArch64CC::CondCode HeadCmpBBCC;
166 /// The branch condition in CmpBB.
167 SmallVector<MachineOperand, 4> CmpBBCond;
169 /// The condition code that makes CmpBB branch to Tail.
170 AArch64CC::CondCode CmpBBTailCC;
172 /// Check if the Tail PHIs are trivially convertible.
173 bool trivialTailPHIs();
175 /// Remove CmpBB from the Tail PHIs.
176 void updateTailPHIs();
178 /// Check if an operand defining DstReg is dead.
179 bool isDeadDef(unsigned DstReg);
181 /// Find the compare instruction in MBB that controls the conditional branch.
182 /// Return NULL if a convertible instruction can't be found.
183 MachineInstr *findConvertibleCompare(MachineBasicBlock *MBB);
185 /// Return true if all non-terminator instructions in MBB can be safely
187 bool canSpeculateInstrs(MachineBasicBlock *MBB, const MachineInstr *CmpMI);
190 /// runOnMachineFunction - Initialize per-function data structures.
191 void runOnMachineFunction(MachineFunction &MF,
192 const MachineBranchProbabilityInfo *MBPI) {
195 TII = MF.getSubtarget().getInstrInfo();
196 TRI = MF.getSubtarget().getRegisterInfo();
197 MRI = &MF.getRegInfo();
200 /// If the sub-CFG headed by MBB can be cmp-converted, initialize the
201 /// internal state, and return true.
202 bool canConvert(MachineBasicBlock *MBB);
204 /// Cmo-convert the last block passed to canConvertCmp(), assuming
205 /// it is possible. Add any erased blocks to RemovedBlocks.
206 void convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks);
208 /// Return the expected code size delta if the conversion into a
209 /// conditional compare is performed.
210 int expectedCodeSizeDelta() const;
212 } // end anonymous namespace
214 // Check that all PHIs in Tail are selecting the same value from Head and CmpBB.
215 // This means that no if-conversion is required when merging CmpBB into Head.
216 bool SSACCmpConv::trivialTailPHIs() {
217 for (auto &I : *Tail) {
220 unsigned HeadReg = 0, CmpBBReg = 0;
221 // PHI operands come in (VReg, MBB) pairs.
222 for (unsigned oi = 1, oe = I.getNumOperands(); oi != oe; oi += 2) {
223 MachineBasicBlock *MBB = I.getOperand(oi + 1).getMBB();
224 unsigned Reg = I.getOperand(oi).getReg();
226 assert((!HeadReg || HeadReg == Reg) && "Inconsistent PHI operands");
230 assert((!CmpBBReg || CmpBBReg == Reg) && "Inconsistent PHI operands");
234 if (HeadReg != CmpBBReg)
240 // Assuming that trivialTailPHIs() is true, update the Tail PHIs by simply
241 // removing the CmpBB operands. The Head operands will be identical.
242 void SSACCmpConv::updateTailPHIs() {
243 for (auto &I : *Tail) {
246 // I is a PHI. It can have multiple entries for CmpBB.
247 for (unsigned oi = I.getNumOperands(); oi > 2; oi -= 2) {
248 // PHI operands are (Reg, MBB) at (oi-2, oi-1).
249 if (I.getOperand(oi - 1).getMBB() == CmpBB) {
250 I.RemoveOperand(oi - 1);
251 I.RemoveOperand(oi - 2);
257 // This pass runs before the AArch64DeadRegisterDefinitions pass, so compares
258 // are still writing virtual registers without any uses.
259 bool SSACCmpConv::isDeadDef(unsigned DstReg) {
260 // Writes to the zero register are dead.
261 if (DstReg == AArch64::WZR || DstReg == AArch64::XZR)
263 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
265 // A virtual register def without any uses will be marked dead later, and
266 // eventually replaced by the zero register.
267 return MRI->use_nodbg_empty(DstReg);
270 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode
271 // corresponding to TBB.
273 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
274 // A normal br.cond simply has the condition code.
275 if (Cond[0].getImm() != -1) {
276 assert(Cond.size() == 1 && "Unknown Cond array format");
277 CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
280 // For tbz and cbz instruction, the opcode is next.
281 switch (Cond[1].getImm()) {
283 // This includes tbz / tbnz branches which can't be converted to
288 assert(Cond.size() == 3 && "Unknown Cond array format");
293 assert(Cond.size() == 3 && "Unknown Cond array format");
299 MachineInstr *SSACCmpConv::findConvertibleCompare(MachineBasicBlock *MBB) {
300 MachineBasicBlock::iterator I = MBB->getFirstTerminator();
303 // The terminator must be controlled by the flags.
304 if (!I->readsRegister(AArch64::NZCV)) {
305 switch (I->getOpcode()) {
310 // These can be converted into a ccmp against #0.
314 DEBUG(dbgs() << "Flags not used by terminator: " << *I);
318 // Now find the instruction controlling the terminator.
319 for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
321 assert(!I->isTerminator() && "Spurious terminator");
322 switch (I->getOpcode()) {
323 // cmp is an alias for subs with a dead destination register.
324 case AArch64::SUBSWri:
325 case AArch64::SUBSXri:
326 // cmn is an alias for adds with a dead destination register.
327 case AArch64::ADDSWri:
328 case AArch64::ADDSXri:
329 // Check that the immediate operand is within range, ccmp wants a uimm5.
330 // Rd = SUBSri Rn, imm, shift
331 if (I->getOperand(3).getImm() || !isUInt<5>(I->getOperand(2).getImm())) {
332 DEBUG(dbgs() << "Immediate out of range for ccmp: " << *I);
337 case AArch64::SUBSWrr:
338 case AArch64::SUBSXrr:
339 case AArch64::ADDSWrr:
340 case AArch64::ADDSXrr:
341 if (isDeadDef(I->getOperand(0).getReg()))
343 DEBUG(dbgs() << "Can't convert compare with live destination: " << *I);
346 case AArch64::FCMPSrr:
347 case AArch64::FCMPDrr:
348 case AArch64::FCMPESrr:
349 case AArch64::FCMPEDrr:
353 // Check for flag reads and clobbers.
354 MIOperands::PhysRegInfo PRI =
355 MIOperands(*I).analyzePhysReg(AArch64::NZCV, TRI);
358 // The ccmp doesn't produce exactly the same flags as the original
359 // compare, so reject the transform if there are uses of the flags
360 // besides the terminators.
361 DEBUG(dbgs() << "Can't create ccmp with multiple uses: " << *I);
366 if (PRI.Defined || PRI.Clobbered) {
367 DEBUG(dbgs() << "Not convertible compare: " << *I);
372 DEBUG(dbgs() << "Flags not defined in " << printMBBReference(*MBB) << '\n');
376 /// Determine if all the instructions in MBB can safely
377 /// be speculated. The terminators are not considered.
379 /// Only CmpMI is allowed to clobber the flags.
381 bool SSACCmpConv::canSpeculateInstrs(MachineBasicBlock *MBB,
382 const MachineInstr *CmpMI) {
383 // Reject any live-in physregs. It's probably NZCV/EFLAGS, and very hard to
385 if (!MBB->livein_empty()) {
386 DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
390 unsigned InstrCount = 0;
392 // Check all instructions, except the terminators. It is assumed that
393 // terminators never have side effects or define any used register values.
394 for (auto &I : make_range(MBB->begin(), MBB->getFirstTerminator())) {
395 if (I.isDebugValue())
398 if (++InstrCount > BlockInstrLimit && !Stress) {
399 DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
400 << BlockInstrLimit << " instructions.\n");
404 // There shouldn't normally be any phis in a single-predecessor block.
406 DEBUG(dbgs() << "Can't hoist: " << I);
410 // Don't speculate loads. Note that it may be possible and desirable to
411 // speculate GOT or constant pool loads that are guaranteed not to trap,
412 // but we don't support that for now.
414 DEBUG(dbgs() << "Won't speculate load: " << I);
418 // We never speculate stores, so an AA pointer isn't necessary.
419 bool DontMoveAcrossStore = true;
420 if (!I.isSafeToMove(nullptr, DontMoveAcrossStore)) {
421 DEBUG(dbgs() << "Can't speculate: " << I);
425 // Only CmpMI is allowed to clobber the flags.
426 if (&I != CmpMI && I.modifiesRegister(AArch64::NZCV, TRI)) {
427 DEBUG(dbgs() << "Clobbers flags: " << I);
434 /// Analyze the sub-cfg rooted in MBB, and return true if it is a potential
435 /// candidate for cmp-conversion. Fill out the internal state.
437 bool SSACCmpConv::canConvert(MachineBasicBlock *MBB) {
439 Tail = CmpBB = nullptr;
441 if (Head->succ_size() != 2)
443 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
444 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
446 // CmpBB can only have a single predecessor. Tail is allowed many.
447 if (Succ0->pred_size() != 1)
448 std::swap(Succ0, Succ1);
450 // Succ0 is our candidate for CmpBB.
451 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 2)
457 if (!CmpBB->isSuccessor(Tail))
460 // The CFG topology checks out.
461 DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
462 << printMBBReference(*CmpBB) << " -> "
463 << printMBBReference(*Tail) << '\n');
466 // Tail is allowed to have many predecessors, but we can't handle PHIs yet.
468 // FIXME: Real PHIs could be if-converted as long as the CmpBB values are
469 // defined before The CmpBB cmp clobbers the flags. Alternatively, it should
470 // always be safe to sink the ccmp down to immediately before the CmpBB
472 if (!trivialTailPHIs()) {
473 DEBUG(dbgs() << "Can't handle phis in Tail.\n");
478 if (!Tail->livein_empty()) {
479 DEBUG(dbgs() << "Can't handle live-in physregs in Tail.\n");
484 // CmpBB should never have PHIs since Head is its only predecessor.
485 // FIXME: Clean them up if it happens.
486 if (!CmpBB->empty() && CmpBB->front().isPHI()) {
487 DEBUG(dbgs() << "Can't handle phis in CmpBB.\n");
492 if (!CmpBB->livein_empty()) {
493 DEBUG(dbgs() << "Can't handle live-in physregs in CmpBB.\n");
498 // The branch we're looking to eliminate must be analyzable.
500 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
501 if (TII->analyzeBranch(*Head, TBB, FBB, HeadCond)) {
502 DEBUG(dbgs() << "Head branch not analyzable.\n");
507 // This is weird, probably some sort of degenerate CFG, or an edge to a
509 if (!TBB || HeadCond.empty()) {
510 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in Head.\n");
515 if (!parseCond(HeadCond, HeadCmpBBCC)) {
516 DEBUG(dbgs() << "Unsupported branch type on Head\n");
521 // Make sure the branch direction is right.
523 assert(TBB == Tail && "Unexpected TBB");
524 HeadCmpBBCC = AArch64CC::getInvertedCondCode(HeadCmpBBCC);
529 if (TII->analyzeBranch(*CmpBB, TBB, FBB, CmpBBCond)) {
530 DEBUG(dbgs() << "CmpBB branch not analyzable.\n");
535 if (!TBB || CmpBBCond.empty()) {
536 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch in CmpBB.\n");
541 if (!parseCond(CmpBBCond, CmpBBTailCC)) {
542 DEBUG(dbgs() << "Unsupported branch type on CmpBB\n");
548 CmpBBTailCC = AArch64CC::getInvertedCondCode(CmpBBTailCC);
550 DEBUG(dbgs() << "Head->CmpBB on " << AArch64CC::getCondCodeName(HeadCmpBBCC)
551 << ", CmpBB->Tail on " << AArch64CC::getCondCodeName(CmpBBTailCC)
554 CmpMI = findConvertibleCompare(CmpBB);
558 if (!canSpeculateInstrs(CmpBB, CmpMI)) {
565 void SSACCmpConv::convert(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks) {
566 DEBUG(dbgs() << "Merging " << printMBBReference(*CmpBB) << " into "
567 << printMBBReference(*Head) << ":\n"
570 // All CmpBB instructions are moved into Head, and CmpBB is deleted.
571 // Update the CFG first.
574 // Save successor probabilties before removing CmpBB and Tail from their
576 BranchProbability Head2CmpBB = MBPI->getEdgeProbability(Head, CmpBB);
577 BranchProbability CmpBB2Tail = MBPI->getEdgeProbability(CmpBB, Tail);
579 Head->removeSuccessor(CmpBB);
580 CmpBB->removeSuccessor(Tail);
582 // If Head and CmpBB had successor probabilties, udpate the probabilities to
583 // reflect the ccmp-conversion.
584 if (Head->hasSuccessorProbabilities() && CmpBB->hasSuccessorProbabilities()) {
586 // Head is allowed two successors. We've removed CmpBB, so the remaining
587 // successor is Tail. We need to increase the successor probability for
588 // Tail to account for the CmpBB path we removed.
590 // Pr(Tail|Head) += Pr(CmpBB|Head) * Pr(Tail|CmpBB).
591 assert(*Head->succ_begin() == Tail && "Head successor is not Tail");
592 BranchProbability Head2Tail = MBPI->getEdgeProbability(Head, Tail);
593 Head->setSuccProbability(Head->succ_begin(),
594 Head2Tail + Head2CmpBB * CmpBB2Tail);
596 // We will transfer successors of CmpBB to Head in a moment without
597 // normalizing the successor probabilities. Set the successor probabilites
600 // Pr(I|Head) = Pr(CmpBB|Head) * Pr(I|CmpBB).
601 for (auto I = CmpBB->succ_begin(), E = CmpBB->succ_end(); I != E; ++I) {
602 BranchProbability CmpBB2I = MBPI->getEdgeProbability(CmpBB, *I);
603 CmpBB->setSuccProbability(I, Head2CmpBB * CmpBB2I);
607 Head->transferSuccessorsAndUpdatePHIs(CmpBB);
608 DebugLoc TermDL = Head->getFirstTerminator()->getDebugLoc();
609 TII->removeBranch(*Head);
611 // If the Head terminator was one of the cbz / tbz branches with built-in
612 // compare, we need to insert an explicit compare instruction in its place.
613 if (HeadCond[0].getImm() == -1) {
616 switch (HeadCond[1].getImm()) {
619 Opc = AArch64::SUBSWri;
623 Opc = AArch64::SUBSXri;
626 llvm_unreachable("Cannot convert Head branch");
628 const MCInstrDesc &MCID = TII->get(Opc);
629 // Create a dummy virtual register for the SUBS def.
631 MRI->createVirtualRegister(TII->getRegClass(MCID, 0, TRI, *MF));
632 // Insert a SUBS Rn, #0 instruction instead of the cbz / cbnz.
633 BuildMI(*Head, Head->end(), TermDL, MCID)
634 .addReg(DestReg, RegState::Define | RegState::Dead)
638 // SUBS uses the GPR*sp register classes.
639 MRI->constrainRegClass(HeadCond[2].getReg(),
640 TII->getRegClass(MCID, 1, TRI, *MF));
643 Head->splice(Head->end(), CmpBB, CmpBB->begin(), CmpBB->end());
645 // Now replace CmpMI with a ccmp instruction that also considers the incoming
648 unsigned FirstOp = 1; // First CmpMI operand to copy.
649 bool isZBranch = false; // CmpMI is a cbz/cbnz instruction.
650 switch (CmpMI->getOpcode()) {
652 llvm_unreachable("Unknown compare opcode");
653 case AArch64::SUBSWri: Opc = AArch64::CCMPWi; break;
654 case AArch64::SUBSWrr: Opc = AArch64::CCMPWr; break;
655 case AArch64::SUBSXri: Opc = AArch64::CCMPXi; break;
656 case AArch64::SUBSXrr: Opc = AArch64::CCMPXr; break;
657 case AArch64::ADDSWri: Opc = AArch64::CCMNWi; break;
658 case AArch64::ADDSWrr: Opc = AArch64::CCMNWr; break;
659 case AArch64::ADDSXri: Opc = AArch64::CCMNXi; break;
660 case AArch64::ADDSXrr: Opc = AArch64::CCMNXr; break;
661 case AArch64::FCMPSrr: Opc = AArch64::FCCMPSrr; FirstOp = 0; break;
662 case AArch64::FCMPDrr: Opc = AArch64::FCCMPDrr; FirstOp = 0; break;
663 case AArch64::FCMPESrr: Opc = AArch64::FCCMPESrr; FirstOp = 0; break;
664 case AArch64::FCMPEDrr: Opc = AArch64::FCCMPEDrr; FirstOp = 0; break;
667 Opc = AArch64::CCMPWi;
673 Opc = AArch64::CCMPXi;
679 // The ccmp instruction should set the flags according to the comparison when
680 // Head would have branched to CmpBB.
681 // The NZCV immediate operand should provide flags for the case where Head
682 // would have branched to Tail. These flags should cause the new Head
683 // terminator to branch to tail.
684 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(CmpBBTailCC);
685 const MCInstrDesc &MCID = TII->get(Opc);
686 MRI->constrainRegClass(CmpMI->getOperand(FirstOp).getReg(),
687 TII->getRegClass(MCID, 0, TRI, *MF));
688 if (CmpMI->getOperand(FirstOp + 1).isReg())
689 MRI->constrainRegClass(CmpMI->getOperand(FirstOp + 1).getReg(),
690 TII->getRegClass(MCID, 1, TRI, *MF));
691 MachineInstrBuilder MIB = BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), MCID)
692 .add(CmpMI->getOperand(FirstOp)); // Register Rn
694 MIB.addImm(0); // cbz/cbnz Rn -> ccmp Rn, #0
696 MIB.add(CmpMI->getOperand(FirstOp + 1)); // Register Rm / Immediate
697 MIB.addImm(NZCV).addImm(HeadCmpBBCC);
699 // If CmpMI was a terminator, we need a new conditional branch to replace it.
700 // This now becomes a Head terminator.
702 bool isNZ = CmpMI->getOpcode() == AArch64::CBNZW ||
703 CmpMI->getOpcode() == AArch64::CBNZX;
704 BuildMI(*Head, CmpMI, CmpMI->getDebugLoc(), TII->get(AArch64::Bcc))
705 .addImm(isNZ ? AArch64CC::NE : AArch64CC::EQ)
706 .add(CmpMI->getOperand(1)); // Branch target.
708 CmpMI->eraseFromParent();
709 Head->updateTerminator();
711 RemovedBlocks.push_back(CmpBB);
712 CmpBB->eraseFromParent();
713 DEBUG(dbgs() << "Result:\n" << *Head);
717 int SSACCmpConv::expectedCodeSizeDelta() const {
719 // If the Head terminator was one of the cbz / tbz branches with built-in
720 // compare, we need to insert an explicit compare instruction in its place
721 // plus a branch instruction.
722 if (HeadCond[0].getImm() == -1) {
723 switch (HeadCond[1].getImm()) {
728 // Therefore delta += 1
732 llvm_unreachable("Cannot convert Head branch");
735 // If the Cmp terminator was one of the cbz / tbz branches with
736 // built-in compare, it will be turned into a compare instruction
737 // into Head, but we do not save any instruction.
738 // Otherwise, we save the branch instruction.
739 switch (CmpMI->getOpcode()) {
752 //===----------------------------------------------------------------------===//
753 // AArch64ConditionalCompares Pass
754 //===----------------------------------------------------------------------===//
757 class AArch64ConditionalCompares : public MachineFunctionPass {
758 const MachineBranchProbabilityInfo *MBPI;
759 const TargetInstrInfo *TII;
760 const TargetRegisterInfo *TRI;
761 MCSchedModel SchedModel;
762 // Does the proceeded function has Oz attribute.
764 MachineRegisterInfo *MRI;
765 MachineDominatorTree *DomTree;
766 MachineLoopInfo *Loops;
767 MachineTraceMetrics *Traces;
768 MachineTraceMetrics::Ensemble *MinInstr;
773 AArch64ConditionalCompares() : MachineFunctionPass(ID) {
774 initializeAArch64ConditionalComparesPass(*PassRegistry::getPassRegistry());
776 void getAnalysisUsage(AnalysisUsage &AU) const override;
777 bool runOnMachineFunction(MachineFunction &MF) override;
778 StringRef getPassName() const override {
779 return "AArch64 Conditional Compares";
783 bool tryConvert(MachineBasicBlock *);
784 void updateDomTree(ArrayRef<MachineBasicBlock *> Removed);
785 void updateLoops(ArrayRef<MachineBasicBlock *> Removed);
786 void invalidateTraces();
787 bool shouldConvert();
789 } // end anonymous namespace
791 char AArch64ConditionalCompares::ID = 0;
793 INITIALIZE_PASS_BEGIN(AArch64ConditionalCompares, "aarch64-ccmp",
794 "AArch64 CCMP Pass", false, false)
795 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
796 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
797 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
798 INITIALIZE_PASS_END(AArch64ConditionalCompares, "aarch64-ccmp",
799 "AArch64 CCMP Pass", false, false)
801 FunctionPass *llvm::createAArch64ConditionalCompares() {
802 return new AArch64ConditionalCompares();
805 void AArch64ConditionalCompares::getAnalysisUsage(AnalysisUsage &AU) const {
806 AU.addRequired<MachineBranchProbabilityInfo>();
807 AU.addRequired<MachineDominatorTree>();
808 AU.addPreserved<MachineDominatorTree>();
809 AU.addRequired<MachineLoopInfo>();
810 AU.addPreserved<MachineLoopInfo>();
811 AU.addRequired<MachineTraceMetrics>();
812 AU.addPreserved<MachineTraceMetrics>();
813 MachineFunctionPass::getAnalysisUsage(AU);
816 /// Update the dominator tree after if-conversion erased some blocks.
817 void AArch64ConditionalCompares::updateDomTree(
818 ArrayRef<MachineBasicBlock *> Removed) {
819 // convert() removes CmpBB which was previously dominated by Head.
820 // CmpBB children should be transferred to Head.
821 MachineDomTreeNode *HeadNode = DomTree->getNode(CmpConv.Head);
822 for (MachineBasicBlock *RemovedMBB : Removed) {
823 MachineDomTreeNode *Node = DomTree->getNode(RemovedMBB);
824 assert(Node != HeadNode && "Cannot erase the head node");
825 assert(Node->getIDom() == HeadNode && "CmpBB should be dominated by Head");
826 while (Node->getNumChildren())
827 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
828 DomTree->eraseNode(RemovedMBB);
832 /// Update LoopInfo after if-conversion.
834 AArch64ConditionalCompares::updateLoops(ArrayRef<MachineBasicBlock *> Removed) {
837 for (MachineBasicBlock *RemovedMBB : Removed)
838 Loops->removeBlock(RemovedMBB);
841 /// Invalidate MachineTraceMetrics before if-conversion.
842 void AArch64ConditionalCompares::invalidateTraces() {
843 Traces->invalidate(CmpConv.Head);
844 Traces->invalidate(CmpConv.CmpBB);
847 /// Apply cost model and heuristics to the if-conversion in IfConv.
848 /// Return true if the conversion is a good idea.
850 bool AArch64ConditionalCompares::shouldConvert() {
851 // Stress testing mode disables all cost considerations.
855 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
857 // Head dominates CmpBB, so it is always included in its trace.
858 MachineTraceMetrics::Trace Trace = MinInstr->getTrace(CmpConv.CmpBB);
860 // If code size is the main concern
862 int CodeSizeDelta = CmpConv.expectedCodeSizeDelta();
863 DEBUG(dbgs() << "Code size delta: " << CodeSizeDelta << '\n');
864 // If we are minimizing the code size, do the conversion whatever
866 if (CodeSizeDelta < 0)
868 if (CodeSizeDelta > 0) {
869 DEBUG(dbgs() << "Code size is increasing, give up on this one.\n");
872 // CodeSizeDelta == 0, continue with the regular heuristics
875 // Heuristic: The compare conversion delays the execution of the branch
876 // instruction because we must wait for the inputs to the second compare as
877 // well. The branch has no dependent instructions, but delaying it increases
878 // the cost of a misprediction.
880 // Set a limit on the delay we will accept.
881 unsigned DelayLimit = SchedModel.MispredictPenalty * 3 / 4;
883 // Instruction depths can be computed for all trace instructions above CmpBB.
885 Trace.getInstrCycles(*CmpConv.Head->getFirstTerminator()).Depth;
886 unsigned CmpBBDepth =
887 Trace.getInstrCycles(*CmpConv.CmpBB->getFirstTerminator()).Depth;
888 DEBUG(dbgs() << "Head depth: " << HeadDepth
889 << "\nCmpBB depth: " << CmpBBDepth << '\n');
890 if (CmpBBDepth > HeadDepth + DelayLimit) {
891 DEBUG(dbgs() << "Branch delay would be larger than " << DelayLimit
896 // Check the resource depth at the bottom of CmpBB - these instructions will
898 unsigned ResDepth = Trace.getResourceDepth(true);
899 DEBUG(dbgs() << "Resources: " << ResDepth << '\n');
901 // Heuristic: The speculatively executed instructions must all be able to
902 // merge into the Head block. The Head critical path should dominate the
903 // resource cost of the speculated instructions.
904 if (ResDepth > HeadDepth) {
905 DEBUG(dbgs() << "Too many instructions to speculate.\n");
911 bool AArch64ConditionalCompares::tryConvert(MachineBasicBlock *MBB) {
912 bool Changed = false;
913 while (CmpConv.canConvert(MBB) && shouldConvert()) {
915 SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
916 CmpConv.convert(RemovedBlocks);
918 updateDomTree(RemovedBlocks);
919 updateLoops(RemovedBlocks);
924 bool AArch64ConditionalCompares::runOnMachineFunction(MachineFunction &MF) {
925 DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
926 << "********** Function: " << MF.getName() << '\n');
927 if (skipFunction(MF.getFunction()))
930 TII = MF.getSubtarget().getInstrInfo();
931 TRI = MF.getSubtarget().getRegisterInfo();
932 SchedModel = MF.getSubtarget().getSchedModel();
933 MRI = &MF.getRegInfo();
934 DomTree = &getAnalysis<MachineDominatorTree>();
935 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
936 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
937 Traces = &getAnalysis<MachineTraceMetrics>();
939 MinSize = MF.getFunction().optForMinSize();
941 bool Changed = false;
942 CmpConv.runOnMachineFunction(MF, MBPI);
944 // Visit blocks in dominator tree pre-order. The pre-order enables multiple
945 // cmp-conversions from the same head block.
946 // Note that updateDomTree() modifies the children of the DomTree node
947 // currently being visited. The df_iterator supports that; it doesn't look at
948 // child_begin() / child_end() until after a node has been visited.
949 for (auto *I : depth_first(DomTree))
950 if (tryConvert(I->getBlock()))