1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===// 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 machine instruction level if-conversion pass, which 11 // tries to convert conditional branches into predicated instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/Passes.h" 16 #include "BranchFolding.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/CodeGen/LivePhysRegs.h" 21 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 22 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 23 #include "llvm/CodeGen/MachineFunctionPass.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/CodeGen/MachineModuleInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/TargetSchedule.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Target/TargetInstrInfo.h" 33 #include "llvm/Target/TargetLowering.h" 34 #include "llvm/Target/TargetRegisterInfo.h" 35 #include "llvm/Target/TargetSubtargetInfo.h" 36 #include <algorithm> 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "ifcvt" 41 42 // Hidden options for help debugging. 43 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden); 44 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden); 45 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden); 46 static cl::opt<bool> DisableSimple("disable-ifcvt-simple", 47 cl::init(false), cl::Hidden); 48 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false", 49 cl::init(false), cl::Hidden); 50 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 51 cl::init(false), cl::Hidden); 52 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev", 53 cl::init(false), cl::Hidden); 54 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 55 cl::init(false), cl::Hidden); 56 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 57 cl::init(false), cl::Hidden); 58 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 59 cl::init(false), cl::Hidden); 60 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold", 61 cl::init(true), cl::Hidden); 62 63 STATISTIC(NumSimple, "Number of simple if-conversions performed"); 64 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed"); 65 STATISTIC(NumTriangle, "Number of triangle if-conversions performed"); 66 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed"); 67 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed"); 68 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed"); 69 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed"); 70 STATISTIC(NumIfConvBBs, "Number of if-converted blocks"); 71 STATISTIC(NumDupBBs, "Number of duplicated blocks"); 72 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated"); 73 74 namespace { 75 class IfConverter : public MachineFunctionPass { 76 enum IfcvtKind { 77 ICNotClassfied, // BB data valid, but not classified. 78 ICSimpleFalse, // Same as ICSimple, but on the false path. 79 ICSimple, // BB is entry of an one split, no rejoin sub-CFG. 80 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition. 81 ICTriangleRev, // Same as ICTriangle, but true path rev condition. 82 ICTriangleFalse, // Same as ICTriangle, but on the false path. 83 ICTriangle, // BB is entry of a triangle sub-CFG. 84 ICDiamond // BB is entry of a diamond sub-CFG. 85 }; 86 87 /// BBInfo - One per MachineBasicBlock, this is used to cache the result 88 /// if-conversion feasibility analysis. This includes results from 89 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its 90 /// classification, and common tail block of its successors (if it's a 91 /// diamond shape), its size, whether it's predicable, and whether any 92 /// instruction can clobber the 'would-be' predicate. 93 /// 94 /// IsDone - True if BB is not to be considered for ifcvt. 95 /// IsBeingAnalyzed - True if BB is currently being analyzed. 96 /// IsAnalyzed - True if BB has been analyzed (info is still valid). 97 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed. 98 /// IsBrAnalyzable - True if AnalyzeBranch() returns false. 99 /// HasFallThrough - True if BB may fallthrough to the following BB. 100 /// IsUnpredicable - True if BB is known to be unpredicable. 101 /// ClobbersPred - True if BB could modify predicates (e.g. has 102 /// cmp, call, etc.) 103 /// NonPredSize - Number of non-predicated instructions. 104 /// ExtraCost - Extra cost for multi-cycle instructions. 105 /// ExtraCost2 - Some instructions are slower when predicated 106 /// BB - Corresponding MachineBasicBlock. 107 /// TrueBB / FalseBB- See AnalyzeBranch(). 108 /// BrCond - Conditions for end of block conditional branches. 109 /// Predicate - Predicate used in the BB. 110 struct BBInfo { 111 bool IsDone : 1; 112 bool IsBeingAnalyzed : 1; 113 bool IsAnalyzed : 1; 114 bool IsEnqueued : 1; 115 bool IsBrAnalyzable : 1; 116 bool HasFallThrough : 1; 117 bool IsUnpredicable : 1; 118 bool CannotBeCopied : 1; 119 bool ClobbersPred : 1; 120 unsigned NonPredSize; 121 unsigned ExtraCost; 122 unsigned ExtraCost2; 123 MachineBasicBlock *BB; 124 MachineBasicBlock *TrueBB; 125 MachineBasicBlock *FalseBB; 126 SmallVector<MachineOperand, 4> BrCond; 127 SmallVector<MachineOperand, 4> Predicate; 128 BBInfo() : IsDone(false), IsBeingAnalyzed(false), 129 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false), 130 HasFallThrough(false), IsUnpredicable(false), 131 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0), 132 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr), 133 FalseBB(nullptr) {} 134 }; 135 136 /// IfcvtToken - Record information about pending if-conversions to attempt: 137 /// BBI - Corresponding BBInfo. 138 /// Kind - Type of block. See IfcvtKind. 139 /// NeedSubsumption - True if the to-be-predicated BB has already been 140 /// predicated. 141 /// NumDups - Number of instructions that would be duplicated due 142 /// to this if-conversion. (For diamonds, the number of 143 /// identical instructions at the beginnings of both 144 /// paths). 145 /// NumDups2 - For diamonds, the number of identical instructions 146 /// at the ends of both paths. 147 struct IfcvtToken { 148 BBInfo &BBI; 149 IfcvtKind Kind; 150 bool NeedSubsumption; 151 unsigned NumDups; 152 unsigned NumDups2; 153 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0) 154 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {} 155 }; 156 157 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by 158 /// basic block number. 159 std::vector<BBInfo> BBAnalysis; 160 TargetSchedModel SchedModel; 161 162 const TargetLoweringBase *TLI; 163 const TargetInstrInfo *TII; 164 const TargetRegisterInfo *TRI; 165 const MachineBlockFrequencyInfo *MBFI; 166 const MachineBranchProbabilityInfo *MBPI; 167 MachineRegisterInfo *MRI; 168 169 LivePhysRegs Redefs; 170 LivePhysRegs DontKill; 171 172 bool PreRegAlloc; 173 bool MadeChange; 174 int FnNum; 175 std::function<bool(const Function &)> PredicateFtor; 176 177 public: 178 static char ID; 179 IfConverter(std::function<bool(const Function &)> Ftor = nullptr) 180 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) { 181 initializeIfConverterPass(*PassRegistry::getPassRegistry()); 182 } 183 184 void getAnalysisUsage(AnalysisUsage &AU) const override { 185 AU.addRequired<MachineBlockFrequencyInfo>(); 186 AU.addRequired<MachineBranchProbabilityInfo>(); 187 MachineFunctionPass::getAnalysisUsage(AU); 188 } 189 190 bool runOnMachineFunction(MachineFunction &MF) override; 191 192 MachineFunctionProperties getRequiredProperties() const override { 193 return MachineFunctionProperties().set( 194 MachineFunctionProperties::Property::AllVRegsAllocated); 195 } 196 197 private: 198 bool ReverseBranchCondition(BBInfo &BBI); 199 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups, 200 BranchProbability Prediction) const; 201 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 202 bool FalseBranch, unsigned &Dups, 203 BranchProbability Prediction) const; 204 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 205 unsigned &Dups1, unsigned &Dups2) const; 206 void ScanInstructions(BBInfo &BBI); 207 void AnalyzeBlock(MachineBasicBlock *MBB, 208 std::vector<std::unique_ptr<IfcvtToken>> &Tokens); 209 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond, 210 bool isTriangle = false, bool RevBranch = false); 211 void AnalyzeBlocks(MachineFunction &MF, 212 std::vector<std::unique_ptr<IfcvtToken>> &Tokens); 213 void InvalidatePreds(MachineBasicBlock *BB); 214 void RemoveExtraEdges(BBInfo &BBI); 215 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind); 216 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind); 217 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 218 unsigned NumDups1, unsigned NumDups2); 219 void PredicateBlock(BBInfo &BBI, 220 MachineBasicBlock::iterator E, 221 SmallVectorImpl<MachineOperand> &Cond, 222 SmallSet<unsigned, 4> *LaterRedefs = nullptr); 223 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 224 SmallVectorImpl<MachineOperand> &Cond, 225 bool IgnoreBr = false); 226 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true); 227 228 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, 229 unsigned Cycle, unsigned Extra, 230 BranchProbability Prediction) const { 231 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra, 232 Prediction); 233 } 234 235 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, 236 unsigned TCycle, unsigned TExtra, 237 MachineBasicBlock &FBB, 238 unsigned FCycle, unsigned FExtra, 239 BranchProbability Prediction) const { 240 return TCycle > 0 && FCycle > 0 && 241 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra, 242 Prediction); 243 } 244 245 // blockAlwaysFallThrough - Block ends without a terminator. 246 bool blockAlwaysFallThrough(BBInfo &BBI) const { 247 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr; 248 } 249 250 // IfcvtTokenCmp - Used to sort if-conversion candidates. 251 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1, 252 const std::unique_ptr<IfcvtToken> &C2) { 253 int Incr1 = (C1->Kind == ICDiamond) 254 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups; 255 int Incr2 = (C2->Kind == ICDiamond) 256 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups; 257 if (Incr1 > Incr2) 258 return true; 259 else if (Incr1 == Incr2) { 260 // Favors subsumption. 261 if (!C1->NeedSubsumption && C2->NeedSubsumption) 262 return true; 263 else if (C1->NeedSubsumption == C2->NeedSubsumption) { 264 // Favors diamond over triangle, etc. 265 if ((unsigned)C1->Kind < (unsigned)C2->Kind) 266 return true; 267 else if (C1->Kind == C2->Kind) 268 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber(); 269 } 270 } 271 return false; 272 } 273 }; 274 275 char IfConverter::ID = 0; 276 } 277 278 char &llvm::IfConverterID = IfConverter::ID; 279 280 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false) 281 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 282 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false) 283 284 bool IfConverter::runOnMachineFunction(MachineFunction &MF) { 285 if (PredicateFtor && !PredicateFtor(*MF.getFunction())) 286 return false; 287 288 const TargetSubtargetInfo &ST = MF.getSubtarget(); 289 TLI = ST.getTargetLowering(); 290 TII = ST.getInstrInfo(); 291 TRI = ST.getRegisterInfo(); 292 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 293 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 294 MRI = &MF.getRegInfo(); 295 SchedModel.init(ST.getSchedModel(), &ST, TII); 296 297 if (!TII) return false; 298 299 PreRegAlloc = MRI->isSSA(); 300 301 bool BFChange = false; 302 if (!PreRegAlloc) { 303 // Tail merge tend to expose more if-conversion opportunities. 304 BranchFolder BF(true, false, *MBFI, *MBPI); 305 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(), 306 getAnalysisIfAvailable<MachineModuleInfo>()); 307 } 308 309 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'" 310 << MF.getName() << "\'"); 311 312 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) { 313 DEBUG(dbgs() << " skipped\n"); 314 return false; 315 } 316 DEBUG(dbgs() << "\n"); 317 318 MF.RenumberBlocks(); 319 BBAnalysis.resize(MF.getNumBlockIDs()); 320 321 std::vector<std::unique_ptr<IfcvtToken>> Tokens; 322 MadeChange = false; 323 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + 324 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds; 325 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) { 326 // Do an initial analysis for each basic block and find all the potential 327 // candidates to perform if-conversion. 328 bool Change = false; 329 AnalyzeBlocks(MF, Tokens); 330 while (!Tokens.empty()) { 331 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back()); 332 Tokens.pop_back(); 333 BBInfo &BBI = Token->BBI; 334 IfcvtKind Kind = Token->Kind; 335 unsigned NumDups = Token->NumDups; 336 unsigned NumDups2 = Token->NumDups2; 337 338 // If the block has been evicted out of the queue or it has already been 339 // marked dead (due to it being predicated), then skip it. 340 if (BBI.IsDone) 341 BBI.IsEnqueued = false; 342 if (!BBI.IsEnqueued) 343 continue; 344 345 BBI.IsEnqueued = false; 346 347 bool RetVal = false; 348 switch (Kind) { 349 default: llvm_unreachable("Unexpected!"); 350 case ICSimple: 351 case ICSimpleFalse: { 352 bool isFalse = Kind == ICSimpleFalse; 353 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break; 354 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? 355 " false" : "") 356 << "): BB#" << BBI.BB->getNumber() << " (" 357 << ((Kind == ICSimpleFalse) 358 ? BBI.FalseBB->getNumber() 359 : BBI.TrueBB->getNumber()) << ") "); 360 RetVal = IfConvertSimple(BBI, Kind); 361 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 362 if (RetVal) { 363 if (isFalse) ++NumSimpleFalse; 364 else ++NumSimple; 365 } 366 break; 367 } 368 case ICTriangle: 369 case ICTriangleRev: 370 case ICTriangleFalse: 371 case ICTriangleFRev: { 372 bool isFalse = Kind == ICTriangleFalse; 373 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev); 374 if (DisableTriangle && !isFalse && !isRev) break; 375 if (DisableTriangleR && !isFalse && isRev) break; 376 if (DisableTriangleF && isFalse && !isRev) break; 377 if (DisableTriangleFR && isFalse && isRev) break; 378 DEBUG(dbgs() << "Ifcvt (Triangle"); 379 if (isFalse) 380 DEBUG(dbgs() << " false"); 381 if (isRev) 382 DEBUG(dbgs() << " rev"); 383 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:" 384 << BBI.TrueBB->getNumber() << ",F:" 385 << BBI.FalseBB->getNumber() << ") "); 386 RetVal = IfConvertTriangle(BBI, Kind); 387 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 388 if (RetVal) { 389 if (isFalse) { 390 if (isRev) ++NumTriangleFRev; 391 else ++NumTriangleFalse; 392 } else { 393 if (isRev) ++NumTriangleRev; 394 else ++NumTriangle; 395 } 396 } 397 break; 398 } 399 case ICDiamond: { 400 if (DisableDiamond) break; 401 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:" 402 << BBI.TrueBB->getNumber() << ",F:" 403 << BBI.FalseBB->getNumber() << ") "); 404 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2); 405 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n"); 406 if (RetVal) ++NumDiamonds; 407 break; 408 } 409 } 410 411 Change |= RetVal; 412 413 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev + 414 NumTriangleFalse + NumTriangleFRev + NumDiamonds; 415 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit) 416 break; 417 } 418 419 if (!Change) 420 break; 421 MadeChange |= Change; 422 } 423 424 Tokens.clear(); 425 BBAnalysis.clear(); 426 427 if (MadeChange && IfCvtBranchFold) { 428 BranchFolder BF(false, false, *MBFI, *MBPI); 429 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), 430 getAnalysisIfAvailable<MachineModuleInfo>()); 431 } 432 433 MadeChange |= BFChange; 434 return MadeChange; 435 } 436 437 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 438 /// its 'true' successor. 439 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 440 MachineBasicBlock *TrueBB) { 441 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 442 E = BB->succ_end(); SI != E; ++SI) { 443 MachineBasicBlock *SuccBB = *SI; 444 if (SuccBB != TrueBB) 445 return SuccBB; 446 } 447 return nullptr; 448 } 449 450 /// ReverseBranchCondition - Reverse the condition of the end of the block 451 /// branch. Swap block's 'true' and 'false' successors. 452 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) { 453 DebugLoc dl; // FIXME: this is nowhere 454 if (!TII->ReverseBranchCondition(BBI.BrCond)) { 455 TII->RemoveBranch(*BBI.BB); 456 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl); 457 std::swap(BBI.TrueBB, BBI.FalseBB); 458 return true; 459 } 460 return false; 461 } 462 463 /// getNextBlock - Returns the next block in the function blocks ordering. If 464 /// it is the end, returns NULL. 465 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) { 466 MachineFunction::iterator I = BB->getIterator(); 467 MachineFunction::iterator E = BB->getParent()->end(); 468 if (++I == E) 469 return nullptr; 470 return &*I; 471 } 472 473 /// ValidSimple - Returns true if the 'true' block (along with its 474 /// predecessor) forms a valid simple shape for ifcvt. It also returns the 475 /// number of instructions that the ifcvt would need to duplicate if performed 476 /// in Dups. 477 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups, 478 BranchProbability Prediction) const { 479 Dups = 0; 480 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 481 return false; 482 483 if (TrueBBI.IsBrAnalyzable) 484 return false; 485 486 if (TrueBBI.BB->pred_size() > 1) { 487 if (TrueBBI.CannotBeCopied || 488 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize, 489 Prediction)) 490 return false; 491 Dups = TrueBBI.NonPredSize; 492 } 493 494 return true; 495 } 496 497 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along 498 /// with their common predecessor) forms a valid triangle shape for ifcvt. 499 /// If 'FalseBranch' is true, it checks if 'true' block's false branch 500 /// branches to the 'false' block rather than the other way around. It also 501 /// returns the number of instructions that the ifcvt would need to duplicate 502 /// if performed in 'Dups'. 503 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, 504 bool FalseBranch, unsigned &Dups, 505 BranchProbability Prediction) const { 506 Dups = 0; 507 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone) 508 return false; 509 510 if (TrueBBI.BB->pred_size() > 1) { 511 if (TrueBBI.CannotBeCopied) 512 return false; 513 514 unsigned Size = TrueBBI.NonPredSize; 515 if (TrueBBI.IsBrAnalyzable) { 516 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty()) 517 // Ends with an unconditional branch. It will be removed. 518 --Size; 519 else { 520 MachineBasicBlock *FExit = FalseBranch 521 ? TrueBBI.TrueBB : TrueBBI.FalseBB; 522 if (FExit) 523 // Require a conditional branch 524 ++Size; 525 } 526 } 527 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction)) 528 return false; 529 Dups = Size; 530 } 531 532 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB; 533 if (!TExit && blockAlwaysFallThrough(TrueBBI)) { 534 MachineFunction::iterator I = TrueBBI.BB->getIterator(); 535 if (++I == TrueBBI.BB->getParent()->end()) 536 return false; 537 TExit = &*I; 538 } 539 return TExit && TExit == FalseBBI.BB; 540 } 541 542 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along 543 /// with their common predecessor) forms a valid diamond shape for ifcvt. 544 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, 545 unsigned &Dups1, unsigned &Dups2) const { 546 Dups1 = Dups2 = 0; 547 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone || 548 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone) 549 return false; 550 551 MachineBasicBlock *TT = TrueBBI.TrueBB; 552 MachineBasicBlock *FT = FalseBBI.TrueBB; 553 554 if (!TT && blockAlwaysFallThrough(TrueBBI)) 555 TT = getNextBlock(TrueBBI.BB); 556 if (!FT && blockAlwaysFallThrough(FalseBBI)) 557 FT = getNextBlock(FalseBBI.BB); 558 if (TT != FT) 559 return false; 560 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable)) 561 return false; 562 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) 563 return false; 564 565 // FIXME: Allow true block to have an early exit? 566 if (TrueBBI.FalseBB || FalseBBI.FalseBB || 567 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)) 568 return false; 569 570 // Count duplicate instructions at the beginning of the true and false blocks. 571 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin(); 572 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin(); 573 MachineBasicBlock::iterator TIE = TrueBBI.BB->end(); 574 MachineBasicBlock::iterator FIE = FalseBBI.BB->end(); 575 while (TIB != TIE && FIB != FIE) { 576 // Skip dbg_value instructions. These do not count. 577 if (TIB->isDebugValue()) { 578 while (TIB != TIE && TIB->isDebugValue()) 579 ++TIB; 580 if (TIB == TIE) 581 break; 582 } 583 if (FIB->isDebugValue()) { 584 while (FIB != FIE && FIB->isDebugValue()) 585 ++FIB; 586 if (FIB == FIE) 587 break; 588 } 589 if (!TIB->isIdenticalTo(*FIB)) 590 break; 591 ++Dups1; 592 ++TIB; 593 ++FIB; 594 } 595 596 // Now, in preparation for counting duplicate instructions at the ends of the 597 // blocks, move the end iterators up past any branch instructions. 598 // If both blocks are returning don't skip the branches, since they will 599 // likely be both identical return instructions. In such cases the return 600 // can be left unpredicated. 601 // Check for already containing all of the block. 602 if (TIB == TIE || FIB == FIE) 603 return true; 604 --TIE; 605 --FIE; 606 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) { 607 while (TIE != TIB && TIE->isBranch()) 608 --TIE; 609 while (FIE != FIB && FIE->isBranch()) 610 --FIE; 611 } 612 613 // If Dups1 includes all of a block, then don't count duplicate 614 // instructions at the end of the blocks. 615 if (TIB == TIE || FIB == FIE) 616 return true; 617 618 // Count duplicate instructions at the ends of the blocks. 619 while (TIE != TIB && FIE != FIB) { 620 // Skip dbg_value instructions. These do not count. 621 if (TIE->isDebugValue()) { 622 while (TIE != TIB && TIE->isDebugValue()) 623 --TIE; 624 if (TIE == TIB) 625 break; 626 } 627 if (FIE->isDebugValue()) { 628 while (FIE != FIB && FIE->isDebugValue()) 629 --FIE; 630 if (FIE == FIB) 631 break; 632 } 633 if (!TIE->isIdenticalTo(*FIE)) 634 break; 635 ++Dups2; 636 --TIE; 637 --FIE; 638 } 639 640 return true; 641 } 642 643 /// ScanInstructions - Scan all the instructions in the block to determine if 644 /// the block is predicable. In most cases, that means all the instructions 645 /// in the block are isPredicable(). Also checks if the block contains any 646 /// instruction which can clobber a predicate (e.g. condition code register). 647 /// If so, the block is not predicable unless it's the last instruction. 648 void IfConverter::ScanInstructions(BBInfo &BBI) { 649 if (BBI.IsDone) 650 return; 651 652 bool AlreadyPredicated = !BBI.Predicate.empty(); 653 // First analyze the end of BB branches. 654 BBI.TrueBB = BBI.FalseBB = nullptr; 655 BBI.BrCond.clear(); 656 BBI.IsBrAnalyzable = 657 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond); 658 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr; 659 660 if (BBI.BrCond.size()) { 661 // No false branch. This BB must end with a conditional branch and a 662 // fallthrough. 663 if (!BBI.FalseBB) 664 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB); 665 if (!BBI.FalseBB) { 666 // Malformed bcc? True and false blocks are the same? 667 BBI.IsUnpredicable = true; 668 return; 669 } 670 } 671 672 // Then scan all the instructions. 673 BBI.NonPredSize = 0; 674 BBI.ExtraCost = 0; 675 BBI.ExtraCost2 = 0; 676 BBI.ClobbersPred = false; 677 for (auto &MI : *BBI.BB) { 678 if (MI.isDebugValue()) 679 continue; 680 681 // It's unsafe to duplicate convergent instructions in this context, so set 682 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the 683 // following CFG, which is subject to our "simple" transformation. 684 // 685 // BB0 // if (c1) goto BB1; else goto BB2; 686 // / \ 687 // BB1 | 688 // | BB2 // if (c2) goto TBB; else goto FBB; 689 // | / | 690 // | / | 691 // TBB | 692 // | | 693 // | FBB 694 // | 695 // exit 696 // 697 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd 698 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose 699 // TBB contains a convergent instruction. This is safe iff doing so does 700 // not add a control-flow dependency to the convergent instruction -- i.e., 701 // it's safe iff the set of control flows that leads us to the convergent 702 // instruction does not get smaller after the transformation. 703 // 704 // Originally we executed TBB if c1 || c2. After the transformation, there 705 // are two copies of TBB's instructions. We get to the first if c1, and we 706 // get to the second if !c1 && c2. 707 // 708 // There are clearly fewer ways to satisfy the condition "c1" than 709 // "c1 || c2". Since we've shrunk the set of control flows which lead to 710 // our convergent instruction, the transformation is unsafe. 711 if (MI.isNotDuplicable() || MI.isConvergent()) 712 BBI.CannotBeCopied = true; 713 714 bool isPredicated = TII->isPredicated(MI); 715 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch(); 716 717 // A conditional branch is not predicable, but it may be eliminated. 718 if (isCondBr) 719 continue; 720 721 if (!isPredicated) { 722 BBI.NonPredSize++; 723 unsigned ExtraPredCost = TII->getPredicationCost(MI); 724 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false); 725 if (NumCycles > 1) 726 BBI.ExtraCost += NumCycles-1; 727 BBI.ExtraCost2 += ExtraPredCost; 728 } else if (!AlreadyPredicated) { 729 // FIXME: This instruction is already predicated before the 730 // if-conversion pass. It's probably something like a conditional move. 731 // Mark this block unpredicable for now. 732 BBI.IsUnpredicable = true; 733 return; 734 } 735 736 if (BBI.ClobbersPred && !isPredicated) { 737 // Predicate modification instruction should end the block (except for 738 // already predicated instructions and end of block branches). 739 // Predicate may have been modified, the subsequent (currently) 740 // unpredicated instructions cannot be correctly predicated. 741 BBI.IsUnpredicable = true; 742 return; 743 } 744 745 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are 746 // still potentially predicable. 747 std::vector<MachineOperand> PredDefs; 748 if (TII->DefinesPredicate(MI, PredDefs)) 749 BBI.ClobbersPred = true; 750 751 if (!TII->isPredicable(MI)) { 752 BBI.IsUnpredicable = true; 753 return; 754 } 755 } 756 } 757 758 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be 759 /// predicated by the specified predicate. 760 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI, 761 SmallVectorImpl<MachineOperand> &Pred, 762 bool isTriangle, bool RevBranch) { 763 // If the block is dead or unpredicable, then it cannot be predicated. 764 if (BBI.IsDone || BBI.IsUnpredicable) 765 return false; 766 767 // If it is already predicated but we couldn't analyze its terminator, the 768 // latter might fallthrough, but we can't determine where to. 769 // Conservatively avoid if-converting again. 770 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable) 771 return false; 772 773 // If it is already predicated, check if the new predicate subsumes 774 // its predicate. 775 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate)) 776 return false; 777 778 if (BBI.BrCond.size()) { 779 if (!isTriangle) 780 return false; 781 782 // Test predicate subsumption. 783 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end()); 784 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 785 if (RevBranch) { 786 if (TII->ReverseBranchCondition(Cond)) 787 return false; 788 } 789 if (TII->ReverseBranchCondition(RevPred) || 790 !TII->SubsumesPredicate(Cond, RevPred)) 791 return false; 792 } 793 794 return true; 795 } 796 797 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from 798 /// the specified block. Record its successors and whether it looks like an 799 /// if-conversion candidate. 800 void IfConverter::AnalyzeBlock( 801 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) { 802 struct BBState { 803 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {} 804 MachineBasicBlock *MBB; 805 806 /// This flag is true if MBB's successors have been analyzed. 807 bool SuccsAnalyzed; 808 }; 809 810 // Push MBB to the stack. 811 SmallVector<BBState, 16> BBStack(1, MBB); 812 813 while (!BBStack.empty()) { 814 BBState &State = BBStack.back(); 815 MachineBasicBlock *BB = State.MBB; 816 BBInfo &BBI = BBAnalysis[BB->getNumber()]; 817 818 if (!State.SuccsAnalyzed) { 819 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) { 820 BBStack.pop_back(); 821 continue; 822 } 823 824 BBI.BB = BB; 825 BBI.IsBeingAnalyzed = true; 826 827 ScanInstructions(BBI); 828 829 // Unanalyzable or ends with fallthrough or unconditional branch, or if is 830 // not considered for ifcvt anymore. 831 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) { 832 BBI.IsBeingAnalyzed = false; 833 BBI.IsAnalyzed = true; 834 BBStack.pop_back(); 835 continue; 836 } 837 838 // Do not ifcvt if either path is a back edge to the entry block. 839 if (BBI.TrueBB == BB || BBI.FalseBB == BB) { 840 BBI.IsBeingAnalyzed = false; 841 BBI.IsAnalyzed = true; 842 BBStack.pop_back(); 843 continue; 844 } 845 846 // Do not ifcvt if true and false fallthrough blocks are the same. 847 if (!BBI.FalseBB) { 848 BBI.IsBeingAnalyzed = false; 849 BBI.IsAnalyzed = true; 850 BBStack.pop_back(); 851 continue; 852 } 853 854 // Push the False and True blocks to the stack. 855 State.SuccsAnalyzed = true; 856 BBStack.push_back(BBI.FalseBB); 857 BBStack.push_back(BBI.TrueBB); 858 continue; 859 } 860 861 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 862 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 863 864 if (TrueBBI.IsDone && FalseBBI.IsDone) { 865 BBI.IsBeingAnalyzed = false; 866 BBI.IsAnalyzed = true; 867 BBStack.pop_back(); 868 continue; 869 } 870 871 SmallVector<MachineOperand, 4> 872 RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 873 bool CanRevCond = !TII->ReverseBranchCondition(RevCond); 874 875 unsigned Dups = 0; 876 unsigned Dups2 = 0; 877 bool TNeedSub = !TrueBBI.Predicate.empty(); 878 bool FNeedSub = !FalseBBI.Predicate.empty(); 879 bool Enqueued = false; 880 881 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB); 882 883 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) && 884 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) + 885 TrueBBI.ExtraCost), TrueBBI.ExtraCost2, 886 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) + 887 FalseBBI.ExtraCost),FalseBBI.ExtraCost2, 888 Prediction) && 889 FeasibilityAnalysis(TrueBBI, BBI.BrCond) && 890 FeasibilityAnalysis(FalseBBI, RevCond)) { 891 // Diamond: 892 // EBB 893 // / \_ 894 // | | 895 // TBB FBB 896 // \ / 897 // TailBB 898 // Note TailBB can be empty. 899 Tokens.push_back(llvm::make_unique<IfcvtToken>( 900 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2)); 901 Enqueued = true; 902 } 903 904 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) && 905 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 906 TrueBBI.ExtraCost2, Prediction) && 907 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) { 908 // Triangle: 909 // EBB 910 // | \_ 911 // | | 912 // | TBB 913 // | / 914 // FBB 915 Tokens.push_back( 916 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups)); 917 Enqueued = true; 918 } 919 920 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) && 921 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 922 TrueBBI.ExtraCost2, Prediction) && 923 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) { 924 Tokens.push_back( 925 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups)); 926 Enqueued = true; 927 } 928 929 if (ValidSimple(TrueBBI, Dups, Prediction) && 930 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost, 931 TrueBBI.ExtraCost2, Prediction) && 932 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) { 933 // Simple (split, no rejoin): 934 // EBB 935 // | \_ 936 // | | 937 // | TBB---> exit 938 // | 939 // FBB 940 Tokens.push_back( 941 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups)); 942 Enqueued = true; 943 } 944 945 if (CanRevCond) { 946 // Try the other path... 947 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups, 948 Prediction.getCompl()) && 949 MeetIfcvtSizeLimit(*FalseBBI.BB, 950 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 951 FalseBBI.ExtraCost2, Prediction.getCompl()) && 952 FeasibilityAnalysis(FalseBBI, RevCond, true)) { 953 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse, 954 FNeedSub, Dups)); 955 Enqueued = true; 956 } 957 958 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups, 959 Prediction.getCompl()) && 960 MeetIfcvtSizeLimit(*FalseBBI.BB, 961 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 962 FalseBBI.ExtraCost2, Prediction.getCompl()) && 963 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) { 964 Tokens.push_back( 965 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups)); 966 Enqueued = true; 967 } 968 969 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) && 970 MeetIfcvtSizeLimit(*FalseBBI.BB, 971 FalseBBI.NonPredSize + FalseBBI.ExtraCost, 972 FalseBBI.ExtraCost2, Prediction.getCompl()) && 973 FeasibilityAnalysis(FalseBBI, RevCond)) { 974 Tokens.push_back( 975 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups)); 976 Enqueued = true; 977 } 978 } 979 980 BBI.IsEnqueued = Enqueued; 981 BBI.IsBeingAnalyzed = false; 982 BBI.IsAnalyzed = true; 983 BBStack.pop_back(); 984 } 985 } 986 987 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion 988 /// candidates. 989 void IfConverter::AnalyzeBlocks( 990 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) { 991 for (auto &BB : MF) 992 AnalyzeBlock(&BB, Tokens); 993 994 // Sort to favor more complex ifcvt scheme. 995 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp); 996 } 997 998 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or 999 /// that all the intervening blocks are empty (given BB can fall through to its 1000 /// next block). 1001 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) { 1002 MachineFunction::iterator PI = BB->getIterator(); 1003 MachineFunction::iterator I = std::next(PI); 1004 MachineFunction::iterator TI = ToBB->getIterator(); 1005 MachineFunction::iterator E = BB->getParent()->end(); 1006 while (I != TI) { 1007 // Check isSuccessor to avoid case where the next block is empty, but 1008 // it's not a successor. 1009 if (I == E || !I->empty() || !PI->isSuccessor(&*I)) 1010 return false; 1011 PI = I++; 1012 } 1013 return true; 1014 } 1015 1016 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed 1017 /// to determine if it can be if-converted. If predecessor is already enqueued, 1018 /// dequeue it! 1019 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) { 1020 for (const auto &Predecessor : BB->predecessors()) { 1021 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()]; 1022 if (PBBI.IsDone || PBBI.BB == BB) 1023 continue; 1024 PBBI.IsAnalyzed = false; 1025 PBBI.IsEnqueued = false; 1026 } 1027 } 1028 1029 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB. 1030 /// 1031 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB, 1032 const TargetInstrInfo *TII) { 1033 DebugLoc dl; // FIXME: this is nowhere 1034 SmallVector<MachineOperand, 0> NoCond; 1035 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl); 1036 } 1037 1038 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer 1039 /// successors. 1040 void IfConverter::RemoveExtraEdges(BBInfo &BBI) { 1041 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1042 SmallVector<MachineOperand, 4> Cond; 1043 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond)) 1044 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 1045 } 1046 1047 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all 1048 /// values defined in MI which are not live/used by MI. 1049 static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) { 1050 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers; 1051 Redefs.stepForward(MI, Clobbers); 1052 1053 // Now add the implicit uses for each of the clobbered values. 1054 for (auto Reg : Clobbers) { 1055 // FIXME: Const cast here is nasty, but better than making StepForward 1056 // take a mutable instruction instead of const. 1057 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second); 1058 MachineInstr *OpMI = Op.getParent(); 1059 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI); 1060 if (Op.isRegMask()) { 1061 // First handle regmasks. They clobber any entries in the mask which 1062 // means that we need a def for those registers. 1063 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef); 1064 1065 // We also need to add an implicit def of this register for the later 1066 // use to read from. 1067 // For the register allocator to have allocated a register clobbered 1068 // by the call which is used later, it must be the case that 1069 // the call doesn't return. 1070 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define); 1071 continue; 1072 } 1073 assert(Op.isReg() && "Register operand required"); 1074 if (Op.isDead()) { 1075 // If we found a dead def, but it needs to be live, then remove the dead 1076 // flag. 1077 if (Redefs.contains(Op.getReg())) 1078 Op.setIsDead(false); 1079 } 1080 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef); 1081 } 1082 } 1083 1084 /** 1085 * Remove kill flags from operands with a registers in the @p DontKill set. 1086 */ 1087 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) { 1088 for (MIBundleOperands O(MI); O.isValid(); ++O) { 1089 if (!O->isReg() || !O->isKill()) 1090 continue; 1091 if (DontKill.contains(O->getReg())) 1092 O->setIsKill(false); 1093 } 1094 } 1095 1096 /** 1097 * Walks a range of machine instructions and removes kill flags for registers 1098 * in the @p DontKill set. 1099 */ 1100 static void RemoveKills(MachineBasicBlock::iterator I, 1101 MachineBasicBlock::iterator E, 1102 const LivePhysRegs &DontKill, 1103 const MCRegisterInfo &MCRI) { 1104 for ( ; I != E; ++I) 1105 RemoveKills(*I, DontKill); 1106 } 1107 1108 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG. 1109 /// 1110 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) { 1111 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1112 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1113 BBInfo *CvtBBI = &TrueBBI; 1114 BBInfo *NextBBI = &FalseBBI; 1115 1116 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 1117 if (Kind == ICSimpleFalse) 1118 std::swap(CvtBBI, NextBBI); 1119 1120 if (CvtBBI->IsDone || 1121 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 1122 // Something has changed. It's no longer safe to predicate this block. 1123 BBI.IsAnalyzed = false; 1124 CvtBBI->IsAnalyzed = false; 1125 return false; 1126 } 1127 1128 if (CvtBBI->BB->hasAddressTaken()) 1129 // Conservatively abort if-conversion if BB's address is taken. 1130 return false; 1131 1132 if (Kind == ICSimpleFalse) 1133 if (TII->ReverseBranchCondition(Cond)) 1134 llvm_unreachable("Unable to reverse branch condition!"); 1135 1136 // Initialize liveins to the first BB. These are potentiall redefined by 1137 // predicated instructions. 1138 Redefs.init(TRI); 1139 Redefs.addLiveIns(CvtBBI->BB); 1140 Redefs.addLiveIns(NextBBI->BB); 1141 1142 // Compute a set of registers which must not be killed by instructions in 1143 // BB1: This is everything live-in to BB2. 1144 DontKill.init(TRI); 1145 DontKill.addLiveIns(NextBBI->BB); 1146 1147 if (CvtBBI->BB->pred_size() > 1) { 1148 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1149 // Copy instructions in the true block, predicate them, and add them to 1150 // the entry block. 1151 CopyAndPredicateBlock(BBI, *CvtBBI, Cond); 1152 1153 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so 1154 // explicitly remove CvtBBI as a successor. 1155 BBI.BB->removeSuccessor(CvtBBI->BB, true); 1156 } else { 1157 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI); 1158 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 1159 1160 // Merge converted block into entry block. 1161 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1162 MergeBlocks(BBI, *CvtBBI); 1163 } 1164 1165 bool IterIfcvt = true; 1166 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) { 1167 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 1168 BBI.HasFallThrough = false; 1169 // Now ifcvt'd block will look like this: 1170 // BB: 1171 // ... 1172 // t, f = cmp 1173 // if t op 1174 // b BBf 1175 // 1176 // We cannot further ifcvt this block because the unconditional branch 1177 // will have to be predicated on the new condition, that will not be 1178 // available if cmp executes. 1179 IterIfcvt = false; 1180 } 1181 1182 RemoveExtraEdges(BBI); 1183 1184 // Update block info. BB can be iteratively if-converted. 1185 if (!IterIfcvt) 1186 BBI.IsDone = true; 1187 InvalidatePreds(BBI.BB); 1188 CvtBBI->IsDone = true; 1189 1190 // FIXME: Must maintain LiveIns. 1191 return true; 1192 } 1193 1194 /// IfConvertTriangle - If convert a triangle sub-CFG. 1195 /// 1196 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { 1197 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1198 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1199 BBInfo *CvtBBI = &TrueBBI; 1200 BBInfo *NextBBI = &FalseBBI; 1201 DebugLoc dl; // FIXME: this is nowhere 1202 1203 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end()); 1204 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 1205 std::swap(CvtBBI, NextBBI); 1206 1207 if (CvtBBI->IsDone || 1208 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) { 1209 // Something has changed. It's no longer safe to predicate this block. 1210 BBI.IsAnalyzed = false; 1211 CvtBBI->IsAnalyzed = false; 1212 return false; 1213 } 1214 1215 if (CvtBBI->BB->hasAddressTaken()) 1216 // Conservatively abort if-conversion if BB's address is taken. 1217 return false; 1218 1219 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev) 1220 if (TII->ReverseBranchCondition(Cond)) 1221 llvm_unreachable("Unable to reverse branch condition!"); 1222 1223 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) { 1224 if (ReverseBranchCondition(*CvtBBI)) { 1225 // BB has been changed, modify its predecessors (except for this 1226 // one) so they don't get ifcvt'ed based on bad intel. 1227 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(), 1228 E = CvtBBI->BB->pred_end(); PI != E; ++PI) { 1229 MachineBasicBlock *PBB = *PI; 1230 if (PBB == BBI.BB) 1231 continue; 1232 BBInfo &PBBI = BBAnalysis[PBB->getNumber()]; 1233 if (PBBI.IsEnqueued) { 1234 PBBI.IsAnalyzed = false; 1235 PBBI.IsEnqueued = false; 1236 } 1237 } 1238 } 1239 } 1240 1241 // Initialize liveins to the first BB. These are potentially redefined by 1242 // predicated instructions. 1243 Redefs.init(TRI); 1244 Redefs.addLiveIns(CvtBBI->BB); 1245 Redefs.addLiveIns(NextBBI->BB); 1246 1247 DontKill.clear(); 1248 1249 bool HasEarlyExit = CvtBBI->FalseBB != nullptr; 1250 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt; 1251 1252 if (HasEarlyExit) { 1253 // Get probabilities before modifying CvtBBI->BB and BBI.BB. 1254 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB); 1255 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB); 1256 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB); 1257 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB); 1258 } 1259 1260 if (CvtBBI->BB->pred_size() > 1) { 1261 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1262 // Copy instructions in the true block, predicate them, and add them to 1263 // the entry block. 1264 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true); 1265 1266 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so 1267 // explicitly remove CvtBBI as a successor. 1268 BBI.BB->removeSuccessor(CvtBBI->BB, true); 1269 } else { 1270 // Predicate the 'true' block after removing its branch. 1271 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB); 1272 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond); 1273 1274 // Now merge the entry of the triangle with the true block. 1275 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1276 MergeBlocks(BBI, *CvtBBI, false); 1277 } 1278 1279 // If 'true' block has a 'false' successor, add an exit branch to it. 1280 if (HasEarlyExit) { 1281 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(), 1282 CvtBBI->BrCond.end()); 1283 if (TII->ReverseBranchCondition(RevCond)) 1284 llvm_unreachable("Unable to reverse branch condition!"); 1285 1286 // Update the edge probability for both CvtBBI->FalseBB and NextBBI. 1287 // NewNext = New_Prob(BBI.BB, NextBBI->BB) = 1288 // Prob(BBI.BB, NextBBI->BB) + 1289 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB) 1290 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) = 1291 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB) 1292 auto NewTrueBB = getNextBlock(BBI.BB); 1293 auto NewNext = BBNext + BBCvt * CvtNext; 1294 auto NewTrueBBIter = 1295 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB); 1296 if (NewTrueBBIter != BBI.BB->succ_end()) 1297 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext); 1298 1299 auto NewFalse = BBCvt * CvtFalse; 1300 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl); 1301 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse); 1302 } 1303 1304 // Merge in the 'false' block if the 'false' block has no other 1305 // predecessors. Otherwise, add an unconditional branch to 'false'. 1306 bool FalseBBDead = false; 1307 bool IterIfcvt = true; 1308 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB); 1309 if (!isFallThrough) { 1310 // Only merge them if the true block does not fallthrough to the false 1311 // block. By not merging them, we make it possible to iteratively 1312 // ifcvt the blocks. 1313 if (!HasEarlyExit && 1314 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough && 1315 !NextBBI->BB->hasAddressTaken()) { 1316 MergeBlocks(BBI, *NextBBI); 1317 FalseBBDead = true; 1318 } else { 1319 InsertUncondBranch(BBI.BB, NextBBI->BB, TII); 1320 BBI.HasFallThrough = false; 1321 } 1322 // Mixed predicated and unpredicated code. This cannot be iteratively 1323 // predicated. 1324 IterIfcvt = false; 1325 } 1326 1327 RemoveExtraEdges(BBI); 1328 1329 // Update block info. BB can be iteratively if-converted. 1330 if (!IterIfcvt) 1331 BBI.IsDone = true; 1332 InvalidatePreds(BBI.BB); 1333 CvtBBI->IsDone = true; 1334 if (FalseBBDead) 1335 NextBBI->IsDone = true; 1336 1337 // FIXME: Must maintain LiveIns. 1338 return true; 1339 } 1340 1341 /// IfConvertDiamond - If convert a diamond sub-CFG. 1342 /// 1343 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, 1344 unsigned NumDups1, unsigned NumDups2) { 1345 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()]; 1346 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()]; 1347 MachineBasicBlock *TailBB = TrueBBI.TrueBB; 1348 // True block must fall through or end with an unanalyzable terminator. 1349 if (!TailBB) { 1350 if (blockAlwaysFallThrough(TrueBBI)) 1351 TailBB = FalseBBI.TrueBB; 1352 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!"); 1353 } 1354 1355 if (TrueBBI.IsDone || FalseBBI.IsDone || 1356 TrueBBI.BB->pred_size() > 1 || 1357 FalseBBI.BB->pred_size() > 1) { 1358 // Something has changed. It's no longer safe to predicate these blocks. 1359 BBI.IsAnalyzed = false; 1360 TrueBBI.IsAnalyzed = false; 1361 FalseBBI.IsAnalyzed = false; 1362 return false; 1363 } 1364 1365 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken()) 1366 // Conservatively abort if-conversion if either BB has its address taken. 1367 return false; 1368 1369 // Put the predicated instructions from the 'true' block before the 1370 // instructions from the 'false' block, unless the true block would clobber 1371 // the predicate, in which case, do the opposite. 1372 BBInfo *BBI1 = &TrueBBI; 1373 BBInfo *BBI2 = &FalseBBI; 1374 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end()); 1375 if (TII->ReverseBranchCondition(RevCond)) 1376 llvm_unreachable("Unable to reverse branch condition!"); 1377 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond; 1378 SmallVector<MachineOperand, 4> *Cond2 = &RevCond; 1379 1380 // Figure out the more profitable ordering. 1381 bool DoSwap = false; 1382 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) 1383 DoSwap = true; 1384 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) { 1385 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize) 1386 DoSwap = true; 1387 } 1388 if (DoSwap) { 1389 std::swap(BBI1, BBI2); 1390 std::swap(Cond1, Cond2); 1391 } 1392 1393 // Remove the conditional branch from entry to the blocks. 1394 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB); 1395 1396 // Initialize liveins to the first BB. These are potentially redefined by 1397 // predicated instructions. 1398 Redefs.init(TRI); 1399 Redefs.addLiveIns(BBI1->BB); 1400 1401 // Remove the duplicated instructions at the beginnings of both paths. 1402 // Skip dbg_value instructions 1403 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr(); 1404 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr(); 1405 BBI1->NonPredSize -= NumDups1; 1406 BBI2->NonPredSize -= NumDups1; 1407 1408 // Skip past the dups on each side separately since there may be 1409 // differing dbg_value entries. 1410 for (unsigned i = 0; i < NumDups1; ++DI1) { 1411 if (!DI1->isDebugValue()) 1412 ++i; 1413 } 1414 while (NumDups1 != 0) { 1415 ++DI2; 1416 if (!DI2->isDebugValue()) 1417 --NumDups1; 1418 } 1419 1420 // Compute a set of registers which must not be killed by instructions in BB1: 1421 // This is everything used+live in BB2 after the duplicated instructions. We 1422 // can compute this set by simulating liveness backwards from the end of BB2. 1423 DontKill.init(TRI); 1424 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(), 1425 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) { 1426 DontKill.stepBackward(*I); 1427 } 1428 1429 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E; 1430 ++I) { 1431 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers; 1432 Redefs.stepForward(*I, IgnoredClobbers); 1433 } 1434 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1); 1435 BBI2->BB->erase(BBI2->BB->begin(), DI2); 1436 1437 // Remove branch from the 'true' block, unless it was not analyzable. 1438 // Non-analyzable branches need to be preserved, since in such cases, 1439 // the CFG structure is not an actual diamond (the join block may not 1440 // be present). 1441 if (BBI1->IsBrAnalyzable) 1442 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB); 1443 // Remove duplicated instructions. 1444 DI1 = BBI1->BB->end(); 1445 for (unsigned i = 0; i != NumDups2; ) { 1446 // NumDups2 only counted non-dbg_value instructions, so this won't 1447 // run off the head of the list. 1448 assert (DI1 != BBI1->BB->begin()); 1449 --DI1; 1450 // skip dbg_value instructions 1451 if (!DI1->isDebugValue()) 1452 ++i; 1453 } 1454 BBI1->BB->erase(DI1, BBI1->BB->end()); 1455 1456 // Kill flags in the true block for registers living into the false block 1457 // must be removed. 1458 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI); 1459 1460 // Remove 'false' block branch (unless it was not analyzable), and find 1461 // the last instruction to predicate. 1462 if (BBI2->IsBrAnalyzable) 1463 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB); 1464 DI2 = BBI2->BB->end(); 1465 while (NumDups2 != 0) { 1466 // NumDups2 only counted non-dbg_value instructions, so this won't 1467 // run off the head of the list. 1468 assert (DI2 != BBI2->BB->begin()); 1469 --DI2; 1470 // skip dbg_value instructions 1471 if (!DI2->isDebugValue()) 1472 --NumDups2; 1473 } 1474 1475 // Remember which registers would later be defined by the false block. 1476 // This allows us not to predicate instructions in the true block that would 1477 // later be re-defined. That is, rather than 1478 // subeq r0, r1, #1 1479 // addne r0, r1, #1 1480 // generate: 1481 // sub r0, r1, #1 1482 // addne r0, r1, #1 1483 SmallSet<unsigned, 4> RedefsByFalse; 1484 SmallSet<unsigned, 4> ExtUses; 1485 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) { 1486 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) { 1487 if (FI->isDebugValue()) 1488 continue; 1489 SmallVector<unsigned, 4> Defs; 1490 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) { 1491 const MachineOperand &MO = FI->getOperand(i); 1492 if (!MO.isReg()) 1493 continue; 1494 unsigned Reg = MO.getReg(); 1495 if (!Reg) 1496 continue; 1497 if (MO.isDef()) { 1498 Defs.push_back(Reg); 1499 } else if (!RedefsByFalse.count(Reg)) { 1500 // These are defined before ctrl flow reach the 'false' instructions. 1501 // They cannot be modified by the 'true' instructions. 1502 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1503 SubRegs.isValid(); ++SubRegs) 1504 ExtUses.insert(*SubRegs); 1505 } 1506 } 1507 1508 for (unsigned i = 0, e = Defs.size(); i != e; ++i) { 1509 unsigned Reg = Defs[i]; 1510 if (!ExtUses.count(Reg)) { 1511 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1512 SubRegs.isValid(); ++SubRegs) 1513 RedefsByFalse.insert(*SubRegs); 1514 } 1515 } 1516 } 1517 } 1518 1519 // Predicate the 'true' block. 1520 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse); 1521 1522 // After predicating BBI1, if there is a predicated terminator in BBI1 and 1523 // a non-predicated in BBI2, then we don't want to predicate the one from 1524 // BBI2. The reason is that if we merged these blocks, we would end up with 1525 // two predicated terminators in the same block. 1526 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) { 1527 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator(); 1528 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator(); 1529 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) && 1530 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T)) 1531 --DI2; 1532 } 1533 1534 // Predicate the 'false' block. 1535 PredicateBlock(*BBI2, DI2, *Cond2); 1536 1537 // Merge the true block into the entry of the diamond. 1538 MergeBlocks(BBI, *BBI1, TailBB == nullptr); 1539 MergeBlocks(BBI, *BBI2, TailBB == nullptr); 1540 1541 // If the if-converted block falls through or unconditionally branches into 1542 // the tail block, and the tail block does not have other predecessors, then 1543 // fold the tail block in as well. Otherwise, unless it falls through to the 1544 // tail, add a unconditional branch to it. 1545 if (TailBB) { 1546 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()]; 1547 bool CanMergeTail = !TailBBI.HasFallThrough && 1548 !TailBBI.BB->hasAddressTaken(); 1549 // The if-converted block can still have a predicated terminator 1550 // (e.g. a predicated return). If that is the case, we cannot merge 1551 // it with the tail block. 1552 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator(); 1553 if (TI != BBI.BB->end() && TII->isPredicated(*TI)) 1554 CanMergeTail = false; 1555 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB; 1556 // check if there are any other predecessors besides those. 1557 unsigned NumPreds = TailBB->pred_size(); 1558 if (NumPreds > 1) 1559 CanMergeTail = false; 1560 else if (NumPreds == 1 && CanMergeTail) { 1561 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin(); 1562 if (*PI != BBI1->BB && *PI != BBI2->BB) 1563 CanMergeTail = false; 1564 } 1565 if (CanMergeTail) { 1566 MergeBlocks(BBI, TailBBI); 1567 TailBBI.IsDone = true; 1568 } else { 1569 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne()); 1570 InsertUncondBranch(BBI.BB, TailBB, TII); 1571 BBI.HasFallThrough = false; 1572 } 1573 } 1574 1575 // RemoveExtraEdges won't work if the block has an unanalyzable branch, 1576 // which can happen here if TailBB is unanalyzable and is merged, so 1577 // explicitly remove BBI1 and BBI2 as successors. 1578 BBI.BB->removeSuccessor(BBI1->BB); 1579 BBI.BB->removeSuccessor(BBI2->BB, true); 1580 RemoveExtraEdges(BBI); 1581 1582 // Update block info. 1583 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true; 1584 InvalidatePreds(BBI.BB); 1585 1586 // FIXME: Must maintain LiveIns. 1587 return true; 1588 } 1589 1590 static bool MaySpeculate(const MachineInstr *MI, 1591 SmallSet<unsigned, 4> &LaterRedefs) { 1592 bool SawStore = true; 1593 if (!MI->isSafeToMove(nullptr, SawStore)) 1594 return false; 1595 1596 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1597 const MachineOperand &MO = MI->getOperand(i); 1598 if (!MO.isReg()) 1599 continue; 1600 unsigned Reg = MO.getReg(); 1601 if (!Reg) 1602 continue; 1603 if (MO.isDef() && !LaterRedefs.count(Reg)) 1604 return false; 1605 } 1606 1607 return true; 1608 } 1609 1610 /// PredicateBlock - Predicate instructions from the start of the block to the 1611 /// specified end with the specified condition. 1612 void IfConverter::PredicateBlock(BBInfo &BBI, 1613 MachineBasicBlock::iterator E, 1614 SmallVectorImpl<MachineOperand> &Cond, 1615 SmallSet<unsigned, 4> *LaterRedefs) { 1616 bool AnyUnpred = false; 1617 bool MaySpec = LaterRedefs != nullptr; 1618 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) { 1619 if (I->isDebugValue() || TII->isPredicated(*I)) 1620 continue; 1621 // It may be possible not to predicate an instruction if it's the 'true' 1622 // side of a diamond and the 'false' side may re-define the instruction's 1623 // defs. 1624 if (MaySpec && MaySpeculate(I, *LaterRedefs)) { 1625 AnyUnpred = true; 1626 continue; 1627 } 1628 // If any instruction is predicated, then every instruction after it must 1629 // be predicated. 1630 MaySpec = false; 1631 if (!TII->PredicateInstruction(*I, Cond)) { 1632 #ifndef NDEBUG 1633 dbgs() << "Unable to predicate " << *I << "!\n"; 1634 #endif 1635 llvm_unreachable(nullptr); 1636 } 1637 1638 // If the predicated instruction now redefines a register as the result of 1639 // if-conversion, add an implicit kill. 1640 UpdatePredRedefs(*I, Redefs); 1641 } 1642 1643 BBI.Predicate.append(Cond.begin(), Cond.end()); 1644 1645 BBI.IsAnalyzed = false; 1646 BBI.NonPredSize = 0; 1647 1648 ++NumIfConvBBs; 1649 if (AnyUnpred) 1650 ++NumUnpred; 1651 } 1652 1653 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to 1654 /// the destination block. Skip end of block branches if IgnoreBr is true. 1655 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI, 1656 SmallVectorImpl<MachineOperand> &Cond, 1657 bool IgnoreBr) { 1658 MachineFunction &MF = *ToBBI.BB->getParent(); 1659 1660 for (auto &I : *FromBBI.BB) { 1661 // Do not copy the end of the block branches. 1662 if (IgnoreBr && I.isBranch()) 1663 break; 1664 1665 MachineInstr *MI = MF.CloneMachineInstr(&I); 1666 ToBBI.BB->insert(ToBBI.BB->end(), MI); 1667 ToBBI.NonPredSize++; 1668 unsigned ExtraPredCost = TII->getPredicationCost(I); 1669 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false); 1670 if (NumCycles > 1) 1671 ToBBI.ExtraCost += NumCycles-1; 1672 ToBBI.ExtraCost2 += ExtraPredCost; 1673 1674 if (!TII->isPredicated(I) && !MI->isDebugValue()) { 1675 if (!TII->PredicateInstruction(*MI, Cond)) { 1676 #ifndef NDEBUG 1677 dbgs() << "Unable to predicate " << I << "!\n"; 1678 #endif 1679 llvm_unreachable(nullptr); 1680 } 1681 } 1682 1683 // If the predicated instruction now redefines a register as the result of 1684 // if-conversion, add an implicit kill. 1685 UpdatePredRedefs(*MI, Redefs); 1686 1687 // Some kill flags may not be correct anymore. 1688 if (!DontKill.empty()) 1689 RemoveKills(*MI, DontKill); 1690 } 1691 1692 if (!IgnoreBr) { 1693 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(), 1694 FromBBI.BB->succ_end()); 1695 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1696 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr; 1697 1698 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 1699 MachineBasicBlock *Succ = Succs[i]; 1700 // Fallthrough edge can't be transferred. 1701 if (Succ == FallThrough) 1702 continue; 1703 ToBBI.BB->addSuccessor(Succ); 1704 } 1705 } 1706 1707 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end()); 1708 ToBBI.Predicate.append(Cond.begin(), Cond.end()); 1709 1710 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1711 ToBBI.IsAnalyzed = false; 1712 1713 ++NumDupBBs; 1714 } 1715 1716 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB. 1717 /// This will leave FromBB as an empty block, so remove all of its 1718 /// successor edges except for the fall-through edge. If AddEdges is true, 1719 /// i.e., when FromBBI's branch is being moved, add those successor edges to 1720 /// ToBBI. 1721 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) { 1722 assert(!FromBBI.BB->hasAddressTaken() && 1723 "Removing a BB whose address is taken!"); 1724 1725 // In case FromBBI.BB contains terminators (e.g. return instruction), 1726 // first move the non-terminator instructions, then the terminators. 1727 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator(); 1728 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator(); 1729 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI); 1730 1731 // If FromBB has non-predicated terminator we should copy it at the end. 1732 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI)) 1733 ToTI = ToBBI.BB->end(); 1734 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end()); 1735 1736 // Force normalizing the successors' probabilities of ToBBI.BB to convert all 1737 // unknown probabilities into known ones. 1738 // FIXME: This usage is too tricky and in the future we would like to 1739 // eliminate all unknown probabilities in MBB. 1740 ToBBI.BB->normalizeSuccProbs(); 1741 1742 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(), 1743 FromBBI.BB->succ_end()); 1744 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB); 1745 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr; 1746 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when 1747 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB. 1748 auto To2FromProb = BranchProbability::getZero(); 1749 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) { 1750 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB); 1751 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the 1752 // edge probability being merged to other edges when this edge is removed 1753 // later. 1754 ToBBI.BB->setSuccProbability( 1755 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB), 1756 BranchProbability::getZero()); 1757 } 1758 1759 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) { 1760 MachineBasicBlock *Succ = FromSuccs[i]; 1761 // Fallthrough edge can't be transferred. 1762 if (Succ == FallThrough) 1763 continue; 1764 1765 auto NewProb = BranchProbability::getZero(); 1766 if (AddEdges) { 1767 // Calculate the edge probability for the edge from ToBBI.BB to Succ, 1768 // which is a portion of the edge probability from FromBBI.BB to Succ. The 1769 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if 1770 // FromBBI is a successor of ToBBI.BB. See comment below for excepion). 1771 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ); 1772 1773 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This 1774 // only happens when if-converting a diamond CFG and FromBBI.BB is the 1775 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we 1776 // could just use the probabilities on FromBBI.BB's out-edges when adding 1777 // new successors. 1778 if (!To2FromProb.isZero()) 1779 NewProb *= To2FromProb; 1780 } 1781 1782 FromBBI.BB->removeSuccessor(Succ); 1783 1784 if (AddEdges) { 1785 // If the edge from ToBBI.BB to Succ already exists, update the 1786 // probability of this edge by adding NewProb to it. An example is shown 1787 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we 1788 // don't have to set C as A's successor as it already is. We only need to 1789 // update the edge probability on A->C. Note that B will not be 1790 // immediately removed from A's successors. It is possible that B->D is 1791 // not removed either if D is a fallthrough of B. Later the edge A->D 1792 // (generated here) and B->D will be combined into one edge. To maintain 1793 // correct edge probability of this combined edge, we need to set the edge 1794 // probability of A->B to zero, which is already done above. The edge 1795 // probability on A->D is calculated by scaling the original probability 1796 // on A->B by the probability of B->D. 1797 // 1798 // Before ifcvt: After ifcvt (assume B->D is kept): 1799 // 1800 // A A 1801 // /| /|\ 1802 // / B / B| 1803 // | /| | || 1804 // |/ | | |/ 1805 // C D C D 1806 // 1807 if (ToBBI.BB->isSuccessor(Succ)) 1808 ToBBI.BB->setSuccProbability( 1809 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ), 1810 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb); 1811 else 1812 ToBBI.BB->addSuccessor(Succ, NewProb); 1813 } 1814 } 1815 1816 // Now FromBBI always falls through to the next block! 1817 if (NBB && !FromBBI.BB->isSuccessor(NBB)) 1818 FromBBI.BB->addSuccessor(NBB); 1819 1820 // Normalize the probabilities of ToBBI.BB's successors with all adjustment 1821 // we've done above. 1822 ToBBI.BB->normalizeSuccProbs(); 1823 1824 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end()); 1825 FromBBI.Predicate.clear(); 1826 1827 ToBBI.NonPredSize += FromBBI.NonPredSize; 1828 ToBBI.ExtraCost += FromBBI.ExtraCost; 1829 ToBBI.ExtraCost2 += FromBBI.ExtraCost2; 1830 FromBBI.NonPredSize = 0; 1831 FromBBI.ExtraCost = 0; 1832 FromBBI.ExtraCost2 = 0; 1833 1834 ToBBI.ClobbersPred |= FromBBI.ClobbersPred; 1835 ToBBI.HasFallThrough = FromBBI.HasFallThrough; 1836 ToBBI.IsAnalyzed = false; 1837 FromBBI.IsAnalyzed = false; 1838 } 1839 1840 FunctionPass * 1841 llvm::createIfConverter(std::function<bool(const Function &)> Ftor) { 1842 return new IfConverter(Ftor); 1843 } 1844