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