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