LLVM 24.0.0git
IfConversion.cpp
Go to the documentation of this file.
1//===- IfConversion.cpp - Machine code if conversion pass -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the machine instruction level if-conversion pass, which
10// tries to convert conditional branches into predicated instructions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "BranchFolding.h"
16#include "CodeGenOptions.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/SparseSet.h"
22#include "llvm/ADT/Statistic.h"
43#include "llvm/IR/Analysis.h"
44#include "llvm/IR/DebugLoc.h"
46#include "llvm/Pass.h"
48#include "llvm/Support/Debug.h"
51#include <algorithm>
52#include <cassert>
53#include <functional>
54#include <iterator>
55#include <memory>
56#include <utility>
57#include <vector>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "if-converter"
62
63STATISTIC(NumSimple, "Number of simple if-conversions performed");
64STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
65STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
66STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
67STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
68STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
69STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
70STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
71STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
72STATISTIC(NumDupBBs, "Number of duplicated blocks");
73STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
74
75namespace {
76
77class IfConverterImpl {
78 enum IfcvtKind {
79 ICNotClassfied, // BB data valid, but not classified.
80 ICSimpleFalse, // Same as ICSimple, but on the false path.
81 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
82 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
83 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
84 ICTriangleFalse, // Same as ICTriangle, but on the false path.
85 ICTriangle, // BB is entry of a triangle sub-CFG.
86 ICDiamond, // BB is entry of a diamond sub-CFG.
87 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
88 // common tail that can be shared.
89 };
90
91 /// One per MachineBasicBlock, this is used to cache the result
92 /// if-conversion feasibility analysis. This includes results from
93 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
94 /// classification, and common tail block of its successors (if it's a
95 /// diamond shape), its size, whether it's predicable, and whether any
96 /// instruction can clobber the 'would-be' predicate.
97 ///
98 /// IsDone - True if BB is not to be considered for ifcvt.
99 /// IsBeingAnalyzed - True if BB is currently being analyzed.
100 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
101 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
102 /// IsBrAnalyzable - True if analyzeBranch() returns false.
103 /// HasFallThrough - True if BB has fallthrough to the following BB.
104 /// Note that BB may have a fallthrough if both
105 /// !HasFallThrough and !IsBrAnalyzable is true. Also note
106 /// that blockNeverFallThrough() can be used to prove that
107 /// there is no fall through.
108 /// IsUnpredicable - True if BB is known to be unpredicable.
109 /// ClobbersPred - True if BB could modify predicates (e.g. has
110 /// cmp, call, etc.)
111 /// NonPredSize - Number of non-predicated instructions.
112 /// ExtraCost - Extra cost for multi-cycle instructions.
113 /// ExtraCost2 - Some instructions are slower when predicated
114 /// BB - Corresponding MachineBasicBlock.
115 /// TrueBB / FalseBB- See analyzeBranch(), but note that FalseBB can be set
116 /// by AnalyzeBranches even if there is a fallthrough. So
117 /// it doesn't correspond exactly to the result from
118 /// TTI::analyzeBranch.
119 /// BrCond - Conditions for end of block conditional branches.
120 /// Predicate - Predicate used in the BB.
121 struct BBInfo {
122 bool IsDone : 1;
123 bool IsBeingAnalyzed : 1;
124 bool IsAnalyzed : 1;
125 bool IsEnqueued : 1;
126 bool IsBrAnalyzable : 1;
127 bool IsBrReversible : 1;
128 bool HasFallThrough : 1;
129 bool IsUnpredicable : 1;
130 bool CannotBeCopied : 1;
131 bool ClobbersPred : 1;
132 unsigned NonPredSize = 0;
133 unsigned ExtraCost = 0;
134 unsigned ExtraCost2 = 0;
135 MachineBasicBlock *BB = nullptr;
136 MachineBasicBlock *TrueBB = nullptr;
137 MachineBasicBlock *FalseBB = nullptr;
138 SmallVector<MachineOperand, 4> BrCond;
139 SmallVector<MachineOperand, 4> Predicate;
140
141 BBInfo()
142 : IsDone(false), IsBeingAnalyzed(false), IsAnalyzed(false),
143 IsEnqueued(false), IsBrAnalyzable(false), IsBrReversible(false),
144 HasFallThrough(false), IsUnpredicable(false), CannotBeCopied(false),
145 ClobbersPred(false) {}
146 };
147
148 /// Record information about pending if-conversions to attempt:
149 /// BBI - Corresponding BBInfo.
150 /// Kind - Type of block. See IfcvtKind.
151 /// NeedSubsumption - True if the to-be-predicated BB has already been
152 /// predicated.
153 /// NumDups - Number of instructions that would be duplicated due
154 /// to this if-conversion. (For diamonds, the number of
155 /// identical instructions at the beginnings of both
156 /// paths).
157 /// NumDups2 - For diamonds, the number of identical instructions
158 /// at the ends of both paths.
159 struct IfcvtToken {
160 BBInfo &BBI;
161 IfcvtKind Kind;
162 unsigned NumDups;
163 unsigned NumDups2;
164 bool NeedSubsumption : 1;
165 bool TClobbersPred : 1;
166 bool FClobbersPred : 1;
167
168 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
169 bool tc = false, bool fc = false)
170 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
171 TClobbersPred(tc), FClobbersPred(fc) {}
172 };
173
174 /// Results of if-conversion feasibility analysis indexed by basic block
175 /// number.
176 std::vector<BBInfo> BBAnalysis;
177 TargetSchedModel SchedModel;
178
179 const TargetInstrInfo *TII = nullptr;
180 const TargetRegisterInfo *TRI = nullptr;
181 const MachineBranchProbabilityInfo *MBPI = nullptr;
182 MachineRegisterInfo *MRI = nullptr;
183
184 LivePhysRegs Redefs;
185
186 bool PreRegAlloc = true;
187 bool MadeChange = false;
188 int FnNum = -1;
189
190 bool reverseBranchCondition(BBInfo &BBI) const;
191 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
192 BranchProbability Prediction) const;
193 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI, bool FalseBranch,
194 unsigned &Dups, BranchProbability Prediction) const;
195 bool CountDuplicatedInstructions(
198 unsigned &Dups1, unsigned &Dups2, MachineBasicBlock &TBB,
199 MachineBasicBlock &FBB, bool SkipUnconditionalBranches) const;
200 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, unsigned &Dups1,
201 unsigned &Dups2, BBInfo &TrueBBICalc,
202 BBInfo &FalseBBICalc) const;
203 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI, unsigned &Dups1,
204 unsigned &Dups2, BBInfo &TrueBBICalc,
205 BBInfo &FalseBBICalc) const;
206 void AnalyzeBranches(BBInfo &BBI);
207 void ScanInstructions(BBInfo &BBI, MachineBasicBlock::iterator &Begin,
209 bool BranchUnpredicable = false) const;
210 bool RescanInstructions(MachineBasicBlock::iterator &TIB,
213 MachineBasicBlock::iterator &FIE, BBInfo &TrueBBI,
214 BBInfo &FalseBBI) const;
215 void AnalyzeBlock(MachineBasicBlock &MBB,
216 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
217 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
218 bool isTriangle = false, bool RevBranch = false,
219 bool hasCommonTail = false);
220 void AnalyzeBlocks(MachineFunction &MF,
221 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
222 void InvalidatePreds(MachineBasicBlock &MBB);
223 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
224 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
225 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
226 unsigned NumDups1, unsigned NumDups2,
227 bool TClobbersPred, bool FClobbersPred,
228 bool RemoveBranch, bool MergeAddEdges);
229 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind, unsigned NumDups1,
230 unsigned NumDups2, bool TClobbers, bool FClobbers);
231 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind, unsigned NumDups1,
232 unsigned NumDups2, bool TClobbers,
233 bool FClobbers);
234 void PredicateBlock(BBInfo &BBI, MachineBasicBlock::iterator E,
235 SmallVectorImpl<MachineOperand> &Cond,
236 SmallSet<MCRegister, 4> *LaterRedefs = nullptr);
237 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
238 SmallVectorImpl<MachineOperand> &Cond,
239 bool IgnoreBr = false);
240 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
241
242 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Cycle, unsigned Extra,
243 BranchProbability Prediction) const {
244 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra, Prediction);
245 }
246
247 bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
248 MachineBasicBlock &CommBB, unsigned Dups,
249 BranchProbability Prediction, bool Forked) const {
250 const MachineFunction &MF = *TBBInfo.BB->getParent();
251 if (MF.getFunction().hasMinSize()) {
252 MachineBasicBlock::iterator TIB = TBBInfo.BB->begin();
253 MachineBasicBlock::iterator FIB = FBBInfo.BB->begin();
254 MachineBasicBlock::iterator TIE = TBBInfo.BB->end();
255 MachineBasicBlock::iterator FIE = FBBInfo.BB->end();
256
257 unsigned Dups1 = 0, Dups2 = 0;
258 if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
259 *TBBInfo.BB, *FBBInfo.BB,
260 /*SkipUnconditionalBranches*/ true))
261 llvm_unreachable("should already have been checked by ValidDiamond");
262
263 unsigned BranchBytes = 0;
264 unsigned CommonBytes = 0;
265
266 // Count common instructions at the start of the true and false blocks.
267 for (auto &I : make_range(TBBInfo.BB->begin(), TIB)) {
268 LLVM_DEBUG(dbgs() << "Common inst: " << I);
269 CommonBytes += TII->getInstSizeInBytes(I);
270 }
271 for (auto &I : make_range(FBBInfo.BB->begin(), FIB)) {
272 LLVM_DEBUG(dbgs() << "Common inst: " << I);
273 CommonBytes += TII->getInstSizeInBytes(I);
274 }
275
276 // Count instructions at the end of the true and false blocks, after
277 // the ones we plan to predicate. Analyzable branches will be removed
278 // (unless this is a forked diamond), and all other instructions are
279 // common between the two blocks.
280 for (auto &I : make_range(TIE, TBBInfo.BB->end())) {
281 if (I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
282 LLVM_DEBUG(dbgs() << "Saving branch: " << I);
283 BranchBytes += TII->predictBranchSizeForIfCvt(I);
284 } else {
285 LLVM_DEBUG(dbgs() << "Common inst: " << I);
286 CommonBytes += TII->getInstSizeInBytes(I);
287 }
288 }
289 for (auto &I : make_range(FIE, FBBInfo.BB->end())) {
290 if (I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
291 LLVM_DEBUG(dbgs() << "Saving branch: " << I);
292 BranchBytes += TII->predictBranchSizeForIfCvt(I);
293 } else {
294 LLVM_DEBUG(dbgs() << "Common inst: " << I);
295 CommonBytes += TII->getInstSizeInBytes(I);
296 }
297 }
298 for (auto &I : CommBB.terminators()) {
299 if (I.isBranch()) {
300 LLVM_DEBUG(dbgs() << "Saving branch: " << I);
301 BranchBytes += TII->predictBranchSizeForIfCvt(I);
302 }
303 }
304
305 // The common instructions in one branch will be eliminated, halving
306 // their code size.
307 CommonBytes /= 2;
308
309 // Count the instructions which we need to predicate.
310 unsigned NumPredicatedInstructions = 0;
311 for (auto &I : make_range(TIB, TIE)) {
312 if (!I.isDebugInstr()) {
313 LLVM_DEBUG(dbgs() << "Predicating: " << I);
314 NumPredicatedInstructions++;
315 }
316 }
317 for (auto &I : make_range(FIB, FIE)) {
318 if (!I.isDebugInstr()) {
319 LLVM_DEBUG(dbgs() << "Predicating: " << I);
320 NumPredicatedInstructions++;
321 }
322 }
323
324 // Even though we're optimising for size at the expense of performance,
325 // avoid creating really long predicated blocks.
326 if (NumPredicatedInstructions > 15)
327 return false;
328
329 // Some targets (e.g. Thumb2) need to insert extra instructions to
330 // start predicated blocks.
331 unsigned ExtraPredicateBytes =
332 TII->extraSizeToPredicateInstructions(MF, NumPredicatedInstructions);
333
335 dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
336 << ", CommonBytes=" << CommonBytes
337 << ", NumPredicatedInstructions=" << NumPredicatedInstructions
338 << ", ExtraPredicateBytes=" << ExtraPredicateBytes << ")\n");
339 return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
340 } else {
341 unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
342 unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
343 bool Res = TCycle > 0 && FCycle > 0 &&
344 TII->isProfitableToIfCvt(
345 *TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
346 FCycle, FBBInfo.ExtraCost2, Prediction);
347 LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle << ", FCycle="
348 << FCycle << ", TExtra=" << TBBInfo.ExtraCost2
349 << ", FExtra=" << FBBInfo.ExtraCost2 << ") = " << Res
350 << "\n");
351 return Res;
352 }
353 }
354
355 /// Returns true if Block ends without a terminator.
356 bool blockAlwaysFallThrough(BBInfo &BBI) const {
357 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
358 }
359
360 /// Returns true if Block is known not to fallthrough to the following BB.
361 bool blockNeverFallThrough(BBInfo &BBI) const {
362 // Trust "HasFallThrough" if we could analyze branches.
363 if (BBI.IsBrAnalyzable)
364 return !BBI.HasFallThrough;
365 // If this is the last MBB in the function, or if the textual successor
366 // isn't in the successor list, then there is no fallthrough.
367 MachineFunction::iterator PI = BBI.BB->getIterator();
368 MachineFunction::iterator I = std::next(PI);
369 if (I == BBI.BB->getParent()->end() || !PI->isSuccessor(&*I))
370 return true;
371 // Could not prove that there is no fallthrough.
372 return false;
373 }
374
375 /// Used to sort if-conversion candidates.
376 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
377 const std::unique_ptr<IfcvtToken> &C2) {
378 int Incr1 = (C1->Kind == ICDiamond) ? -(int)(C1->NumDups + C1->NumDups2)
379 : (int)C1->NumDups;
380 int Incr2 = (C2->Kind == ICDiamond) ? -(int)(C2->NumDups + C2->NumDups2)
381 : (int)C2->NumDups;
382 if (Incr1 > Incr2)
383 return true;
384 else if (Incr1 == Incr2) {
385 // Favors subsumption.
386 if (!C1->NeedSubsumption && C2->NeedSubsumption)
387 return true;
388 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
389 // Favors diamond over triangle, etc.
390 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
391 return true;
392 else if (C1->Kind == C2->Kind)
393 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
394 }
395 }
396 return false;
397 }
398
399public:
400 bool runOnMachineFunction(
401 MachineFunction &MF, function_ref<MachineBlockFrequencyInfo &()> GetMBFI,
402 function_ref<MachineBranchProbabilityInfo *()> GetMBPI,
403 function_ref<ProfileSummaryInfo *()> GetPSI,
404 function_ref<bool(const MachineFunction &MF)> PredicateFtor);
405};
406
407class IfConverterLegacy : public MachineFunctionPass {
408 std::function<bool(const MachineFunction &)> PredicateFtor;
409
410public:
411 static char ID;
412
413 IfConverterLegacy(std::function<bool(const MachineFunction &)> Ftor = nullptr)
414 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {}
415
416 void getAnalysisUsage(AnalysisUsage &AU) const override {
417 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
418 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
419 AU.addRequired<ProfileSummaryInfoWrapperPass>();
420 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
422 }
423
424 bool runOnMachineFunction(MachineFunction &MF) override;
425
426 MachineFunctionProperties getRequiredProperties() const override {
427 return MachineFunctionProperties().setNoVRegs();
428 }
429};
430
431} // end anonymous namespace
432
433char IfConverterLegacy::ID = 0;
434
435char &llvm::IfConverterID = IfConverterLegacy::ID;
436
437INITIALIZE_PASS_BEGIN(IfConverterLegacy, DEBUG_TYPE, "If Converter", false,
438 false)
441INITIALIZE_PASS_END(IfConverterLegacy, DEBUG_TYPE, "If Converter", false, false)
442
443bool IfConverterImpl::runOnMachineFunction(
447 function_ref<bool(const MachineFunction &MF)> PredicateFtor) {
448 if (PredicateFtor(MF))
449 return false;
450
451 const CodeGenOptions &Opts = getCodeGenOptions(MF);
452 const TargetSubtargetInfo &ST = MF.getSubtarget();
453 TII = ST.getInstrInfo();
454 TRI = ST.getRegisterInfo();
455 MBFIWrapper MBFI(GetMBFI());
456 MBPI = GetMBPI();
457 ProfileSummaryInfo *PSI = GetPSI();
458 MRI = &MF.getRegInfo();
459 SchedModel.init(&ST);
460
461 if (!TII) return false;
462
463 PreRegAlloc = MRI->isSSA();
464
465 bool BFChange = false;
466 if (!PreRegAlloc) {
467 // Tail merge tend to expose more if-conversion opportunities.
468 BranchFolder BF(true, false, MBFI, *MBPI, PSI);
469 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo());
470 }
471
472 LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
473 << MF.getName() << "\'");
474
475 if (FnNum < Opts.ifcvt_fn_start ||
476 (Opts.ifcvt_fn_stop != -1 && FnNum > Opts.ifcvt_fn_stop)) {
477 LLVM_DEBUG(dbgs() << " skipped\n");
478 return false;
479 }
480 LLVM_DEBUG(dbgs() << "\n");
481
482 MF.RenumberBlocks();
483 BBAnalysis.resize(MF.getNumBlockIDs());
484
485 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
486 MadeChange = false;
487 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
488 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
489 while (Opts.ifcvt_limit == -1 || (int)NumIfCvts < Opts.ifcvt_limit) {
490 // Do an initial analysis for each basic block and find all the potential
491 // candidates to perform if-conversion.
492 bool Change = false;
493 AnalyzeBlocks(MF, Tokens);
494 while (!Tokens.empty()) {
495 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
496 Tokens.pop_back();
497 BBInfo &BBI = Token->BBI;
498 IfcvtKind Kind = Token->Kind;
499 unsigned NumDups = Token->NumDups;
500 unsigned NumDups2 = Token->NumDups2;
501
502 // If the block has been evicted out of the queue or it has already been
503 // marked dead (due to it being predicated), then skip it.
504 if (BBI.IsDone)
505 BBI.IsEnqueued = false;
506 if (!BBI.IsEnqueued)
507 continue;
508
509 BBI.IsEnqueued = false;
510
511 bool RetVal = false;
512 switch (Kind) {
513 default: llvm_unreachable("Unexpected!");
514 case ICSimple:
515 case ICSimpleFalse: {
516 bool isFalse = Kind == ICSimpleFalse;
517 if ((isFalse && !Opts.ifcvt_simple_false) ||
518 (!isFalse && !Opts.ifcvt_simple))
519 break;
520 LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
521 << (Kind == ICSimpleFalse ? " false" : "")
522 << "): " << printMBBReference(*BBI.BB) << " ("
523 << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
524 : BBI.TrueBB->getNumber())
525 << ") ");
526 RetVal = IfConvertSimple(BBI, Kind);
527 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
528 if (RetVal) {
529 if (isFalse) ++NumSimpleFalse;
530 else ++NumSimple;
531 }
532 break;
533 }
534 case ICTriangle:
535 case ICTriangleRev:
536 case ICTriangleFalse:
537 case ICTriangleFRev: {
538 bool isFalse = Kind == ICTriangleFalse;
539 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
540 if (!Opts.ifcvt_triangle && !isFalse && !isRev)
541 break;
542 if (!Opts.ifcvt_triangle_rev && !isFalse && isRev)
543 break;
544 if (!Opts.ifcvt_triangle_false && isFalse && !isRev)
545 break;
546 LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
547 if (isFalse)
548 LLVM_DEBUG(dbgs() << " false");
549 if (isRev)
550 LLVM_DEBUG(dbgs() << " rev");
551 LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
552 << " (T:" << BBI.TrueBB->getNumber()
553 << ",F:" << BBI.FalseBB->getNumber() << ") ");
554 RetVal = IfConvertTriangle(BBI, Kind);
555 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
556 if (RetVal) {
557 if (isFalse)
558 ++NumTriangleFalse;
559 else if (isRev)
560 ++NumTriangleRev;
561 else
562 ++NumTriangle;
563 }
564 break;
565 }
566 case ICDiamond:
567 if (!Opts.ifcvt_diamond)
568 break;
569 LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
570 << " (T:" << BBI.TrueBB->getNumber()
571 << ",F:" << BBI.FalseBB->getNumber() << ") ");
572 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
573 Token->TClobbersPred,
574 Token->FClobbersPred);
575 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
576 if (RetVal) ++NumDiamonds;
577 break;
578 case ICForkedDiamond:
579 if (!Opts.ifcvt_forked_diamond)
580 break;
581 LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
582 << printMBBReference(*BBI.BB)
583 << " (T:" << BBI.TrueBB->getNumber()
584 << ",F:" << BBI.FalseBB->getNumber() << ") ");
585 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
586 Token->TClobbersPred,
587 Token->FClobbersPred);
588 LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
589 if (RetVal) ++NumForkedDiamonds;
590 break;
591 }
592
593 if (RetVal && MRI->tracksLiveness())
594 recomputeLivenessFlags(*BBI.BB);
595
596 Change |= RetVal;
597
598 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
599 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
600 if (Opts.ifcvt_limit != -1 && (int)NumIfCvts >= Opts.ifcvt_limit)
601 break;
602 }
603
604 if (!Change)
605 break;
606 MadeChange |= Change;
607 }
608
609 Tokens.clear();
610 BBAnalysis.clear();
611
612 if (MadeChange && Opts.ifcvt_branch_fold) {
613 BranchFolder BF(false, false, MBFI, *MBPI, PSI);
614 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo());
615 }
616
617 MadeChange |= BFChange;
618 return MadeChange;
619}
620
621/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
623 MachineBasicBlock *TrueBB) {
624 for (MachineBasicBlock *SuccBB : BB->successors()) {
625 if (SuccBB != TrueBB)
626 return SuccBB;
627 }
628 return nullptr;
629}
630
631/// Reverse the condition of the end of the block branch. Swap block's 'true'
632/// and 'false' successors.
633bool IfConverterImpl::reverseBranchCondition(BBInfo &BBI) const {
634 DebugLoc dl; // FIXME: this is nowhere
635 if (!TII->reverseBranchCondition(BBI.BrCond)) {
636 TII->removeBranch(*BBI.BB);
637 TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
638 std::swap(BBI.TrueBB, BBI.FalseBB);
639 return true;
640 }
641 return false;
642}
643
644/// Returns the next block in the function blocks ordering. If it is the end,
645/// returns NULL.
647 MachineFunction::iterator I = MBB.getIterator();
648 MachineFunction::iterator E = MBB.getParent()->end();
649 if (++I == E)
650 return nullptr;
651 return &*I;
652}
653
654/// Returns true if the 'true' block (along with its predecessor) forms a valid
655/// simple shape for ifcvt. It also returns the number of instructions that the
656/// ifcvt would need to duplicate if performed in Dups.
657bool IfConverterImpl::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
658 BranchProbability Prediction) const {
659 Dups = 0;
660 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
661 return false;
662
663 if (TrueBBI.IsBrAnalyzable)
664 return false;
665
666 if (TrueBBI.BB->pred_size() > 1) {
667 if (TrueBBI.CannotBeCopied ||
668 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
669 Prediction))
670 return false;
671 Dups = TrueBBI.NonPredSize;
672 }
673
674 return true;
675}
676
677/// Returns true if the 'true' and 'false' blocks (along with their common
678/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
679/// true, it checks if 'true' block's false branch branches to the 'false' block
680/// rather than the other way around. It also returns the number of instructions
681/// that the ifcvt would need to duplicate if performed in 'Dups'.
682bool IfConverterImpl::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
683 bool FalseBranch, unsigned &Dups,
684 BranchProbability Prediction) const {
685 Dups = 0;
686 if (TrueBBI.BB == FalseBBI.BB)
687 return false;
688
689 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
690 return false;
691
692 if (TrueBBI.BB->pred_size() > 1) {
693 if (TrueBBI.CannotBeCopied)
694 return false;
695
696 unsigned Size = TrueBBI.NonPredSize;
697 if (TrueBBI.IsBrAnalyzable) {
698 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
699 // Ends with an unconditional branch. It will be removed.
700 --Size;
701 else {
702 MachineBasicBlock *FExit = FalseBranch
703 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
704 if (FExit)
705 // Require a conditional branch
706 ++Size;
707 }
708 }
709 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
710 return false;
711 Dups = Size;
712 }
713
714 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
715 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
716 MachineFunction::iterator I = TrueBBI.BB->getIterator();
717 if (++I == TrueBBI.BB->getParent()->end())
718 return false;
719 TExit = &*I;
720 }
721 return TExit && TExit == FalseBBI.BB;
722}
723
724/// Count duplicated instructions and move the iterators to show where they
725/// are.
726/// @param TIB True Iterator Begin
727/// @param FIB False Iterator Begin
728/// These two iterators initially point to the first instruction of the two
729/// blocks, and finally point to the first non-shared instruction.
730/// @param TIE True Iterator End
731/// @param FIE False Iterator End
732/// These two iterators initially point to End() for the two blocks() and
733/// finally point to the first shared instruction in the tail.
734/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
735/// two blocks.
736/// @param Dups1 count of duplicated instructions at the beginning of the 2
737/// blocks.
738/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
739/// @param SkipUnconditionalBranches if true, Don't make sure that
740/// unconditional branches at the end of the blocks are the same. True is
741/// passed when the blocks are analyzable to allow for fallthrough to be
742/// handled.
743/// @return false if the shared portion prevents if conversion.
744bool IfConverterImpl::CountDuplicatedInstructions(
747 unsigned &Dups1, unsigned &Dups2, MachineBasicBlock &TBB,
748 MachineBasicBlock &FBB, bool SkipUnconditionalBranches) const {
749 while (TIB != TIE && FIB != FIE) {
750 // Skip dbg_value instructions. These do not count.
751 TIB = skipDebugInstructionsForward(TIB, TIE, false);
752 FIB = skipDebugInstructionsForward(FIB, FIE, false);
753 if (TIB == TIE || FIB == FIE)
754 break;
755 if (!TIB->isIdenticalTo(*FIB))
756 break;
757 // A pred-clobbering instruction in the shared portion prevents
758 // if-conversion.
759 std::vector<MachineOperand> PredDefs;
760 if (TII->ClobbersPredicate(*TIB, PredDefs, false))
761 return false;
762 // If we get all the way to the branch instructions, don't count them.
763 if (!TIB->isBranch())
764 ++Dups1;
765 ++TIB;
766 ++FIB;
767 }
768
769 // Check for already containing all of the block.
770 if (TIB == TIE || FIB == FIE)
771 return true;
772 // Now, in preparation for counting duplicate instructions at the ends of the
773 // blocks, switch to reverse_iterators. Note that getReverse() returns an
774 // iterator that points to the same instruction, unlike std::reverse_iterator.
775 // We have to do our own shifting so that we get the same range.
776 MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
777 MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
778 const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
779 const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
780
781 if (!TBB.succ_empty() || !FBB.succ_empty()) {
782 if (SkipUnconditionalBranches) {
783 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
784 ++RTIE;
785 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
786 ++RFIE;
787 }
788 }
789
790 // Count duplicate instructions at the ends of the blocks.
791 while (RTIE != RTIB && RFIE != RFIB) {
792 // Skip dbg_value instructions. These do not count.
793 // Note that these are reverse iterators going forward.
794 RTIE = skipDebugInstructionsForward(RTIE, RTIB, false);
795 RFIE = skipDebugInstructionsForward(RFIE, RFIB, false);
796 if (RTIE == RTIB || RFIE == RFIB)
797 break;
798 if (!RTIE->isIdenticalTo(*RFIE))
799 break;
800 // We have to verify that any branch instructions are the same, and then we
801 // don't count them toward the # of duplicate instructions.
802 if (!RTIE->isBranch())
803 ++Dups2;
804 ++RTIE;
805 ++RFIE;
806 }
807 TIE = std::next(RTIE.getReverse());
808 FIE = std::next(RFIE.getReverse());
809 return true;
810}
811
812/// RescanInstructions - Run ScanInstructions on a pair of blocks.
813/// @param TIB - True Iterator Begin, points to first non-shared instruction
814/// @param FIB - False Iterator Begin, points to first non-shared instruction
815/// @param TIE - True Iterator End, points past last non-shared instruction
816/// @param FIE - False Iterator End, points past last non-shared instruction
817/// @param TrueBBI - BBInfo to update for the true block.
818/// @param FalseBBI - BBInfo to update for the false block.
819/// @returns - false if either block cannot be predicated or if both blocks end
820/// with a predicate-clobbering instruction.
821bool IfConverterImpl::RescanInstructions(MachineBasicBlock::iterator &TIB,
825 BBInfo &TrueBBI,
826 BBInfo &FalseBBI) const {
827 bool BranchUnpredicable = true;
828 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
829 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
830 if (TrueBBI.IsUnpredicable)
831 return false;
832 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
833 if (FalseBBI.IsUnpredicable)
834 return false;
835 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
836 return false;
837 return true;
838}
839
840#ifndef NDEBUG
842 MachineBasicBlock *MBB1,
843 MachineBasicBlock *MBB2) {
844 const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
845 const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
848 while (E1 != B1 && E2 != B2) {
849 skipDebugInstructionsForward(E1, B1, false);
850 skipDebugInstructionsForward(E2, B2, false);
851 if (E1 == B1 && E2 == B2)
852 break;
853
854 if (E1 == B1) {
855 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
856 break;
857 }
858 if (E2 == B2) {
859 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
860 break;
861 }
862
863 if (E1->isBranch() || E2->isBranch())
864 assert(E1->isIdenticalTo(*E2) &&
865 "Branch mis-match, branch instructions don't match.");
866 else
867 break;
868 ++E1;
869 ++E2;
870 }
871}
872#endif
873
874/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
875/// with their common predecessor) form a diamond if a common tail block is
876/// extracted.
877/// While not strictly a diamond, this pattern would form a diamond if
878/// tail-merging had merged the shared tails.
879/// EBB
880/// _/ \_
881/// | |
882/// TBB FBB
883/// / \ / \
884/// FalseBB TrueBB FalseBB
885/// Currently only handles analyzable branches.
886/// Specifically excludes actual diamonds to avoid overlap.
887bool IfConverterImpl::ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
888 unsigned &Dups1, unsigned &Dups2,
889 BBInfo &TrueBBICalc,
890 BBInfo &FalseBBICalc) const {
891 Dups1 = Dups2 = 0;
892 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
893 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
894 return false;
895
896 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
897 return false;
898 // Don't IfConvert blocks that can't be folded into their predecessor.
899 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
900 return false;
901
902 // This function is specifically looking for conditional tails, as
903 // unconditional tails are already handled by the standard diamond case.
904 if (TrueBBI.BrCond.size() == 0 ||
905 FalseBBI.BrCond.size() == 0)
906 return false;
907
908 MachineBasicBlock *TT = TrueBBI.TrueBB;
909 MachineBasicBlock *TF = TrueBBI.FalseBB;
910 MachineBasicBlock *FT = FalseBBI.TrueBB;
911 MachineBasicBlock *FF = FalseBBI.FalseBB;
912
913 if (!TT)
914 TT = getNextBlock(*TrueBBI.BB);
915 if (!TF)
916 TF = getNextBlock(*TrueBBI.BB);
917 if (!FT)
918 FT = getNextBlock(*FalseBBI.BB);
919 if (!FF)
920 FF = getNextBlock(*FalseBBI.BB);
921
922 if (!TT || !TF)
923 return false;
924
925 // Check successors. If they don't match, bail.
926 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
927 return false;
928
929 bool FalseReversed = false;
930 if (TF == FT && TT == FF) {
931 // If the branches are opposing, but we can't reverse, don't do it.
932 if (!FalseBBI.IsBrReversible)
933 return false;
934 FalseReversed = true;
935 reverseBranchCondition(FalseBBI);
936 }
937 llvm::scope_exit UnReverseOnExit([&]() {
938 if (FalseReversed)
939 reverseBranchCondition(FalseBBI);
940 });
941
942 // Count duplicate instructions at the beginning of the true and false blocks.
943 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
944 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
945 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
946 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
947 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
948 *TrueBBI.BB, *FalseBBI.BB,
949 /* SkipUnconditionalBranches */ true))
950 return false;
951
952 TrueBBICalc.BB = TrueBBI.BB;
953 FalseBBICalc.BB = FalseBBI.BB;
954 TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
955 FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
956 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
957 return false;
958
959 // The size is used to decide whether to if-convert, and the shared portions
960 // are subtracted off. Because of the subtraction, we just use the size that
961 // was calculated by the original ScanInstructions, as it is correct.
962 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
963 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
964 return true;
965}
966
967/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
968/// with their common predecessor) forms a valid diamond shape for ifcvt.
969bool IfConverterImpl::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
970 unsigned &Dups1, unsigned &Dups2,
971 BBInfo &TrueBBICalc,
972 BBInfo &FalseBBICalc) const {
973 Dups1 = Dups2 = 0;
974 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
975 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
976 return false;
977
978 // If the True and False BBs are equal we're dealing with a degenerate case
979 // that we don't treat as a diamond.
980 if (TrueBBI.BB == FalseBBI.BB)
981 return false;
982
983 MachineBasicBlock *TT = TrueBBI.TrueBB;
984 MachineBasicBlock *FT = FalseBBI.TrueBB;
985
986 if (!TT && blockAlwaysFallThrough(TrueBBI))
987 TT = getNextBlock(*TrueBBI.BB);
988 if (!FT && blockAlwaysFallThrough(FalseBBI))
989 FT = getNextBlock(*FalseBBI.BB);
990 if (TT != FT)
991 return false;
992 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
993 return false;
994 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
995 return false;
996
997 // FIXME: Allow true block to have an early exit?
998 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
999 return false;
1000
1001 // Count duplicate instructions at the beginning and end of the true and
1002 // false blocks.
1003 // Skip unconditional branches only if we are considering an analyzable
1004 // diamond. Otherwise the branches must be the same.
1005 bool SkipUnconditionalBranches =
1006 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
1007 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
1008 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
1009 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
1010 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
1011 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
1012 *TrueBBI.BB, *FalseBBI.BB,
1013 SkipUnconditionalBranches))
1014 return false;
1015
1016 TrueBBICalc.BB = TrueBBI.BB;
1017 FalseBBICalc.BB = FalseBBI.BB;
1018 TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
1019 FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
1020 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
1021 return false;
1022 // The size is used to decide whether to if-convert, and the shared portions
1023 // are subtracted off. Because of the subtraction, we just use the size that
1024 // was calculated by the original ScanInstructions, as it is correct.
1025 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
1026 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
1027 return true;
1028}
1029
1030/// AnalyzeBranches - Look at the branches at the end of a block to determine if
1031/// the block is predicable.
1032void IfConverterImpl::AnalyzeBranches(BBInfo &BBI) {
1033 if (BBI.IsDone)
1034 return;
1035
1036 BBI.TrueBB = BBI.FalseBB = nullptr;
1037 BBI.BrCond.clear();
1038 BBI.IsBrAnalyzable =
1039 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
1040 if (!BBI.IsBrAnalyzable) {
1041 BBI.TrueBB = nullptr;
1042 BBI.FalseBB = nullptr;
1043 BBI.BrCond.clear();
1044 }
1045
1046 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1047 BBI.IsBrReversible = (RevCond.size() == 0) ||
1048 !TII->reverseBranchCondition(RevCond);
1049 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
1050
1051 if (BBI.BrCond.size()) {
1052 // No false branch. This BB must end with a conditional branch and a
1053 // fallthrough.
1054 if (!BBI.FalseBB)
1055 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
1056 if (!BBI.FalseBB) {
1057 // Malformed bcc? True and false blocks are the same?
1058 BBI.IsUnpredicable = true;
1059 }
1060 }
1061}
1062
1063/// ScanInstructions - Scan all the instructions in the block to determine if
1064/// the block is predicable. In most cases, that means all the instructions
1065/// in the block are isPredicable(). Also checks if the block contains any
1066/// instruction which can clobber a predicate (e.g. condition code register).
1067/// If so, the block is not predicable unless it's the last instruction.
1068void IfConverterImpl::ScanInstructions(BBInfo &BBI,
1071 bool BranchUnpredicable) const {
1072 if (BBI.IsDone || BBI.IsUnpredicable)
1073 return;
1074
1075 bool AlreadyPredicated = !BBI.Predicate.empty();
1076
1077 BBI.NonPredSize = 0;
1078 BBI.ExtraCost = 0;
1079 BBI.ExtraCost2 = 0;
1080 BBI.ClobbersPred = false;
1081 for (MachineInstr &MI : make_range(Begin, End)) {
1082 if (MI.isDebugInstr())
1083 continue;
1084
1085 // It's unsafe to duplicate convergent instructions in this context, so set
1086 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
1087 // following CFG, which is subject to our "simple" transformation.
1088 //
1089 // BB0 // if (c1) goto BB1; else goto BB2;
1090 // / \
1091 // BB1 |
1092 // | BB2 // if (c2) goto TBB; else goto FBB;
1093 // | / |
1094 // | / |
1095 // TBB |
1096 // | |
1097 // | FBB
1098 // |
1099 // exit
1100 //
1101 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
1102 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
1103 // TBB contains a convergent instruction. This is safe iff doing so does
1104 // not add a control-flow dependency to the convergent instruction -- i.e.,
1105 // it's safe iff the set of control flows that leads us to the convergent
1106 // instruction does not get smaller after the transformation.
1107 //
1108 // Originally we executed TBB if c1 || c2. After the transformation, there
1109 // are two copies of TBB's instructions. We get to the first if c1, and we
1110 // get to the second if !c1 && c2.
1111 //
1112 // There are clearly fewer ways to satisfy the condition "c1" than
1113 // "c1 || c2". Since we've shrunk the set of control flows which lead to
1114 // our convergent instruction, the transformation is unsafe.
1115 if (MI.isNotDuplicable() || MI.isConvergent())
1116 BBI.CannotBeCopied = true;
1117
1119 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
1120
1121 if (BranchUnpredicable && MI.isBranch()) {
1122 BBI.IsUnpredicable = true;
1123 return;
1124 }
1125
1126 // A conditional branch is not predicable, but it may be eliminated.
1127 if (isCondBr)
1128 continue;
1129
1130 if (!isPredicated) {
1131 BBI.NonPredSize++;
1132 unsigned ExtraPredCost = TII->getPredicationCost(MI);
1133 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1134 if (NumCycles > 1)
1135 BBI.ExtraCost += NumCycles-1;
1136 BBI.ExtraCost2 += ExtraPredCost;
1137 } else if (!AlreadyPredicated) {
1138 // FIXME: This instruction is already predicated before the
1139 // if-conversion pass. It's probably something like a conditional move.
1140 // Mark this block unpredicable for now.
1141 BBI.IsUnpredicable = true;
1142 return;
1143 }
1144
1145 if (BBI.ClobbersPred && !isPredicated) {
1146 // Predicate modification instruction should end the block (except for
1147 // already predicated instructions and end of block branches).
1148 // Predicate may have been modified, the subsequent (currently)
1149 // unpredicated instructions cannot be correctly predicated.
1150 BBI.IsUnpredicable = true;
1151 return;
1152 }
1153
1154 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1155 // still potentially predicable.
1156 std::vector<MachineOperand> PredDefs;
1157 if (TII->ClobbersPredicate(MI, PredDefs, true))
1158 BBI.ClobbersPred = true;
1159
1160 if (!TII->isPredicable(MI)) {
1161 BBI.IsUnpredicable = true;
1162 return;
1163 }
1164 }
1165}
1166
1167/// Determine if the block is a suitable candidate to be predicated by the
1168/// specified predicate.
1169/// @param BBI BBInfo for the block to check
1170/// @param Pred Predicate array for the branch that leads to BBI
1171/// @param isTriangle true if the Analysis is for a triangle
1172/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1173/// case
1174/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1175/// contains any instruction that would make the block unpredicable.
1176bool IfConverterImpl::FeasibilityAnalysis(BBInfo &BBI,
1177 SmallVectorImpl<MachineOperand> &Pred,
1178 bool isTriangle, bool RevBranch,
1179 bool hasCommonTail) {
1180 // If the block is dead or unpredicable, then it cannot be predicated.
1181 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1182 // them from being if-converted. The non-shared portion is assumed to have
1183 // been checked
1184 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1185 return false;
1186
1187 // If it is already predicated but we couldn't analyze its terminator, the
1188 // latter might fallthrough, but we can't determine where to.
1189 // Conservatively avoid if-converting again.
1190 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1191 return false;
1192
1193 // If it is already predicated, check if the new predicate subsumes
1194 // its predicate.
1195 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1196 return false;
1197
1198 if (!hasCommonTail && BBI.BrCond.size()) {
1199 if (!isTriangle)
1200 return false;
1201
1202 // Test predicate subsumption.
1203 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1204 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1205 if (RevBranch) {
1207 return false;
1208 }
1209 if (TII->reverseBranchCondition(RevPred) ||
1210 !TII->SubsumesPredicate(Cond, RevPred))
1211 return false;
1212 }
1213
1214 return true;
1215}
1216
1217/// Analyze the structure of the sub-CFG starting from the specified block.
1218/// Record its successors and whether it looks like an if-conversion candidate.
1219void IfConverterImpl::AnalyzeBlock(
1220 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1221 struct BBState {
1222 BBState(MachineBasicBlock &MBB) : MBB(&MBB) {}
1223 MachineBasicBlock *MBB;
1224
1225 /// This flag is true if MBB's successors have been analyzed.
1226 bool SuccsAnalyzed = false;
1227 };
1228
1229 // Push MBB to the stack.
1230 SmallVector<BBState, 16> BBStack(1, MBB);
1231
1232 while (!BBStack.empty()) {
1233 BBState &State = BBStack.back();
1234 MachineBasicBlock *BB = State.MBB;
1235 BBInfo &BBI = BBAnalysis[BB->getNumber()];
1236
1237 if (!State.SuccsAnalyzed) {
1238 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1239 BBStack.pop_back();
1240 continue;
1241 }
1242
1243 BBI.BB = BB;
1244 BBI.IsBeingAnalyzed = true;
1245
1246 AnalyzeBranches(BBI);
1247 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1248 MachineBasicBlock::iterator End = BBI.BB->end();
1249 ScanInstructions(BBI, Begin, End);
1250
1251 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1252 // not considered for ifcvt anymore.
1253 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1254 BBI.IsBeingAnalyzed = false;
1255 BBI.IsAnalyzed = true;
1256 BBStack.pop_back();
1257 continue;
1258 }
1259
1260 // Do not ifcvt if either path is a back edge to the entry block.
1261 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1262 BBI.IsBeingAnalyzed = false;
1263 BBI.IsAnalyzed = true;
1264 BBStack.pop_back();
1265 continue;
1266 }
1267
1268 // Do not ifcvt if true and false fallthrough blocks are the same.
1269 if (!BBI.FalseBB) {
1270 BBI.IsBeingAnalyzed = false;
1271 BBI.IsAnalyzed = true;
1272 BBStack.pop_back();
1273 continue;
1274 }
1275
1276 // Push the False and True blocks to the stack.
1277 State.SuccsAnalyzed = true;
1278 BBStack.push_back(*BBI.FalseBB);
1279 BBStack.push_back(*BBI.TrueBB);
1280 continue;
1281 }
1282
1283 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1284 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1285
1286 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1287 BBI.IsBeingAnalyzed = false;
1288 BBI.IsAnalyzed = true;
1289 BBStack.pop_back();
1290 continue;
1291 }
1292
1293 SmallVector<MachineOperand, 4>
1294 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1295 bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1296
1297 unsigned Dups = 0;
1298 unsigned Dups2 = 0;
1299 bool TNeedSub = !TrueBBI.Predicate.empty();
1300 bool FNeedSub = !FalseBBI.Predicate.empty();
1301 bool Enqueued = false;
1302
1303 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1304
1305 if (CanRevCond) {
1306 BBInfo TrueBBICalc, FalseBBICalc;
1307 auto feasibleDiamond = [&](bool Forked) {
1308 bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
1309 Dups + Dups2, Prediction, Forked);
1310 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1311 /* IsTriangle */ false, /* RevCond */ false,
1312 /* hasCommonTail */ true);
1313 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1314 /* IsTriangle */ false, /* RevCond */ false,
1315 /* hasCommonTail */ true);
1316 return MeetsSize && TrueFeasible && FalseFeasible;
1317 };
1318
1319 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1320 TrueBBICalc, FalseBBICalc)) {
1321 if (feasibleDiamond(false)) {
1322 // Diamond:
1323 // EBB
1324 // / \_
1325 // | |
1326 // TBB FBB
1327 // \ /
1328 // TailBB
1329 // Note TailBB can be empty.
1330 Tokens.push_back(std::make_unique<IfcvtToken>(
1331 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1332 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1333 Enqueued = true;
1334 }
1335 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1336 TrueBBICalc, FalseBBICalc)) {
1337 if (feasibleDiamond(true)) {
1338 // ForkedDiamond:
1339 // if TBB and FBB have a common tail that includes their conditional
1340 // branch instructions, then we can If Convert this pattern.
1341 // EBB
1342 // _/ \_
1343 // | |
1344 // TBB FBB
1345 // / \ / \
1346 // FalseBB TrueBB FalseBB
1347 //
1348 Tokens.push_back(std::make_unique<IfcvtToken>(
1349 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1350 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1351 Enqueued = true;
1352 }
1353 }
1354 }
1355
1356 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1357 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1358 TrueBBI.ExtraCost2, Prediction) &&
1359 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1360 // Triangle:
1361 // EBB
1362 // | \_
1363 // | |
1364 // | TBB
1365 // | /
1366 // FBB
1367 Tokens.push_back(
1368 std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1369 Enqueued = true;
1370 }
1371
1372 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1373 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1374 TrueBBI.ExtraCost2, Prediction) &&
1375 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1376 Tokens.push_back(
1377 std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1378 Enqueued = true;
1379 }
1380
1381 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1382 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1383 TrueBBI.ExtraCost2, Prediction) &&
1384 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1385 // Simple (split, no rejoin):
1386 // EBB
1387 // | \_
1388 // | |
1389 // | TBB---> exit
1390 // |
1391 // FBB
1392 Tokens.push_back(
1393 std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1394 Enqueued = true;
1395 }
1396
1397 if (CanRevCond) {
1398 // Try the other path...
1399 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1400 Prediction.getCompl()) &&
1401 MeetIfcvtSizeLimit(*FalseBBI.BB,
1402 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1403 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1404 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1405 Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1406 FNeedSub, Dups));
1407 Enqueued = true;
1408 }
1409
1410 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1411 Prediction.getCompl()) &&
1412 MeetIfcvtSizeLimit(*FalseBBI.BB,
1413 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1414 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1415 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1416 Tokens.push_back(
1417 std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1418 Enqueued = true;
1419 }
1420
1421 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1422 MeetIfcvtSizeLimit(*FalseBBI.BB,
1423 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1424 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1425 FeasibilityAnalysis(FalseBBI, RevCond)) {
1426 Tokens.push_back(
1427 std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1428 Enqueued = true;
1429 }
1430 }
1431
1432 BBI.IsEnqueued = Enqueued;
1433 BBI.IsBeingAnalyzed = false;
1434 BBI.IsAnalyzed = true;
1435 BBStack.pop_back();
1436 }
1437}
1438
1439/// Analyze all blocks and find entries for all if-conversion candidates.
1440void IfConverterImpl::AnalyzeBlocks(
1441 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1442 for (MachineBasicBlock &MBB : MF)
1443 AnalyzeBlock(MBB, Tokens);
1444
1445 // Sort to favor more complex ifcvt scheme.
1446 llvm::stable_sort(Tokens, IfcvtTokenCmp);
1447}
1448
1449/// Returns true either if ToMBB is the next block after MBB or that all the
1450/// intervening blocks are empty (given MBB can fall through to its next block).
1452 MachineFunction::iterator PI = MBB.getIterator();
1453 MachineFunction::iterator I = std::next(PI);
1455 MachineFunction::iterator E = MBB.getParent()->end();
1456 while (I != TI) {
1457 // Check isSuccessor to avoid case where the next block is empty, but
1458 // it's not a successor.
1459 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1460 return false;
1461 PI = I++;
1462 }
1463 // Finally see if the last I is indeed a successor to PI.
1464 return PI->isSuccessor(&*I);
1465}
1466
1467/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1468/// can be if-converted. If predecessor is already enqueued, dequeue it!
1469void IfConverterImpl::InvalidatePreds(MachineBasicBlock &MBB) {
1470 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1471 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1472 if (PBBI.IsDone || PBBI.BB == &MBB)
1473 continue;
1474 PBBI.IsAnalyzed = false;
1475 PBBI.IsEnqueued = false;
1476 }
1477}
1478
1479/// Inserts an unconditional branch from \p MBB to \p ToMBB.
1481 const TargetInstrInfo *TII) {
1482 DebugLoc dl; // FIXME: this is nowhere
1484 TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1485}
1486
1487/// Behaves like LivePhysRegs::stepForward() but also adds implicit uses to all
1488/// values defined in MI which are also live/used by MI.
1490 const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
1491
1492 // Before stepping forward past MI, remember which regs were live
1493 // before MI. This is needed to set the Undef flag only when reg is
1494 // dead.
1496 LiveBeforeMI.setUniverse(TRI->getNumRegs());
1497 for (unsigned Reg : Redefs)
1498 LiveBeforeMI.insert(Reg);
1499
1501 Redefs.stepForward(MI, Clobbers);
1502
1503 // Now add the implicit uses for each of the clobbered values.
1504 for (auto Clobber : Clobbers) {
1505 // FIXME: Const cast here is nasty, but better than making StepForward
1506 // take a mutable instruction instead of const.
1507 unsigned Reg = Clobber.first;
1508 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1509 MachineInstr *OpMI = Op.getParent();
1510 MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
1511 if (Op.isRegMask()) {
1512 // First handle regmasks. They clobber any entries in the mask which
1513 // means that we need a def for those registers.
1514 if (LiveBeforeMI.count(Reg))
1516
1517 // We also need to add an implicit def of this register for the later
1518 // use to read from.
1519 // For the register allocator to have allocated a register clobbered
1520 // by the call which is used later, it must be the case that
1521 // the call doesn't return.
1523 continue;
1524 }
1525 if (any_of(TRI->subregs_inclusive(Reg),
1526 [&](MCPhysReg S) { return LiveBeforeMI.count(S); }))
1528 }
1529}
1530
1531/// If convert a simple (split, no rejoin) sub-CFG.
1532bool IfConverterImpl::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1533 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1534 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1535 BBInfo *CvtBBI = &TrueBBI;
1536 BBInfo *NextBBI = &FalseBBI;
1537
1538 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1539 if (Kind == ICSimpleFalse)
1540 std::swap(CvtBBI, NextBBI);
1541
1542 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1543 MachineBasicBlock &NextMBB = *NextBBI->BB;
1544 if (CvtBBI->IsDone ||
1545 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1546 // Something has changed. It's no longer safe to predicate this block.
1547 BBI.IsAnalyzed = false;
1548 CvtBBI->IsAnalyzed = false;
1549 return false;
1550 }
1551
1552 if (CvtMBB.hasAddressTaken())
1553 // Conservatively abort if-conversion if BB's address is taken.
1554 return false;
1555
1556 if (Kind == ICSimpleFalse)
1558 llvm_unreachable("Unable to reverse branch condition!");
1559
1560 Redefs.init(*TRI);
1561
1562 if (MRI->tracksLiveness()) {
1563 // Initialize liveins to the first BB. These are potentially redefined by
1564 // predicated instructions.
1565 Redefs.addLiveInsNoPristines(CvtMBB);
1566 Redefs.addLiveInsNoPristines(NextMBB);
1567 }
1568
1569 // Remove the branches from the entry so we can add the contents of the true
1570 // block to it.
1571 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1572
1573 if (CvtMBB.pred_size() > 1) {
1574 // Copy instructions in the true block, predicate them, and add them to
1575 // the entry block.
1576 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1577
1578 // Keep the CFG updated.
1579 BBI.BB->removeSuccessor(&CvtMBB, true);
1580 } else {
1581 // Predicate the instructions in the true block.
1582 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1583
1584 // Merge converted block into entry block. The BB to Cvt edge is removed
1585 // by MergeBlocks.
1586 MergeBlocks(BBI, *CvtBBI);
1587 }
1588
1589 bool IterIfcvt = true;
1590 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1591 InsertUncondBranch(*BBI.BB, NextMBB, TII);
1592 BBI.HasFallThrough = false;
1593 // Now ifcvt'd block will look like this:
1594 // BB:
1595 // ...
1596 // t, f = cmp
1597 // if t op
1598 // b BBf
1599 //
1600 // We cannot further ifcvt this block because the unconditional branch
1601 // will have to be predicated on the new condition, that will not be
1602 // available if cmp executes.
1603 IterIfcvt = false;
1604 }
1605
1606 // Update block info. BB can be iteratively if-converted.
1607 if (!IterIfcvt)
1608 BBI.IsDone = true;
1609 InvalidatePreds(*BBI.BB);
1610 CvtBBI->IsDone = true;
1611
1612 // FIXME: Must maintain LiveIns.
1613 return true;
1614}
1615
1616/// If convert a triangle sub-CFG.
1617bool IfConverterImpl::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1618 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1619 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1620 BBInfo *CvtBBI = &TrueBBI;
1621 BBInfo *NextBBI = &FalseBBI;
1622 DebugLoc dl; // FIXME: this is nowhere
1623
1624 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1625 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1626 std::swap(CvtBBI, NextBBI);
1627
1628 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1629 MachineBasicBlock &NextMBB = *NextBBI->BB;
1630 if (CvtBBI->IsDone ||
1631 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1632 // Something has changed. It's no longer safe to predicate this block.
1633 BBI.IsAnalyzed = false;
1634 CvtBBI->IsAnalyzed = false;
1635 return false;
1636 }
1637
1638 if (CvtMBB.hasAddressTaken())
1639 // Conservatively abort if-conversion if BB's address is taken.
1640 return false;
1641
1642 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1644 llvm_unreachable("Unable to reverse branch condition!");
1645
1646 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1647 if (reverseBranchCondition(*CvtBBI)) {
1648 // BB has been changed, modify its predecessors (except for this
1649 // one) so they don't get ifcvt'ed based on bad intel.
1650 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1651 if (PBB == BBI.BB)
1652 continue;
1653 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1654 if (PBBI.IsEnqueued) {
1655 PBBI.IsAnalyzed = false;
1656 PBBI.IsEnqueued = false;
1657 }
1658 }
1659 }
1660 }
1661
1662 // Initialize liveins to the first BB. These are potentially redefined by
1663 // predicated instructions.
1664 Redefs.init(*TRI);
1665 if (MRI->tracksLiveness()) {
1666 Redefs.addLiveInsNoPristines(CvtMBB);
1667 Redefs.addLiveInsNoPristines(NextMBB);
1668 }
1669
1670 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1671 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1672
1673 if (HasEarlyExit) {
1674 // Get probabilities before modifying CvtMBB and BBI.BB.
1675 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1676 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1677 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1678 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1679 }
1680
1681 // Remove the branches from the entry so we can add the contents of the true
1682 // block to it.
1683 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1684
1685 if (CvtMBB.pred_size() > 1) {
1686 // Copy instructions in the true block, predicate them, and add them to
1687 // the entry block.
1688 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1689 } else {
1690 // Predicate the 'true' block after removing its branch.
1691 CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1692 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1693
1694 // Now merge the entry of the triangle with the true block.
1695 MergeBlocks(BBI, *CvtBBI, false);
1696 }
1697
1698 // Keep the CFG updated.
1699 BBI.BB->removeSuccessor(&CvtMBB, true);
1700
1701 // If 'true' block has a 'false' successor, add an exit branch to it.
1702 if (HasEarlyExit) {
1703 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1704 CvtBBI->BrCond.end());
1705 if (TII->reverseBranchCondition(RevCond))
1706 llvm_unreachable("Unable to reverse branch condition!");
1707
1708 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1709 // NewNext = New_Prob(BBI.BB, NextMBB) =
1710 // Prob(BBI.BB, NextMBB) +
1711 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1712 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1713 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1714 auto NewTrueBB = getNextBlock(*BBI.BB);
1715 auto NewNext = BBNext + BBCvt * CvtNext;
1716 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1717 if (NewTrueBBIter != BBI.BB->succ_end())
1718 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1719
1720 auto NewFalse = BBCvt * CvtFalse;
1721 TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1722 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1723 }
1724
1725 // Merge in the 'false' block if the 'false' block has no other
1726 // predecessors. Otherwise, add an unconditional branch to 'false'.
1727 bool FalseBBDead = false;
1728 bool IterIfcvt = true;
1729 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1730 if (!isFallThrough) {
1731 // Only merge them if the true block does not fallthrough to the false
1732 // block. By not merging them, we make it possible to iteratively
1733 // ifcvt the blocks.
1734 if (!HasEarlyExit && NextMBB.pred_size() == 1 &&
1735 blockNeverFallThrough(*NextBBI) && !NextMBB.hasAddressTaken()) {
1736 MergeBlocks(BBI, *NextBBI);
1737 FalseBBDead = true;
1738 } else {
1739 InsertUncondBranch(*BBI.BB, NextMBB, TII);
1740 BBI.HasFallThrough = false;
1741 }
1742 // Mixed predicated and unpredicated code. This cannot be iteratively
1743 // predicated.
1744 IterIfcvt = false;
1745 }
1746
1747 // Update block info. BB can be iteratively if-converted.
1748 if (!IterIfcvt)
1749 BBI.IsDone = true;
1750 InvalidatePreds(*BBI.BB);
1751 CvtBBI->IsDone = true;
1752 if (FalseBBDead)
1753 NextBBI->IsDone = true;
1754
1755 // FIXME: Must maintain LiveIns.
1756 return true;
1757}
1758
1759/// Common code shared between diamond conversions.
1760/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1761/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1762/// and FalseBBI
1763/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1764/// and \p FalseBBI
1765/// \p RemoveBranch - Remove the common branch of the two blocks before
1766/// predicating. Only false for unanalyzable fallthrough
1767/// cases. The caller will replace the branch if necessary.
1768/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1769/// unanalyzable fallthrough
1770bool IfConverterImpl::IfConvertDiamondCommon(
1771 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI, unsigned NumDups1,
1772 unsigned NumDups2, bool TClobbersPred, bool FClobbersPred,
1773 bool RemoveBranch, bool MergeAddEdges) {
1774
1775 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1776 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1777 // Something has changed. It's no longer safe to predicate these blocks.
1778 BBI.IsAnalyzed = false;
1779 TrueBBI.IsAnalyzed = false;
1780 FalseBBI.IsAnalyzed = false;
1781 return false;
1782 }
1783
1784 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1785 // Conservatively abort if-conversion if either BB has its address taken.
1786 return false;
1787
1788 // Put the predicated instructions from the 'true' block before the
1789 // instructions from the 'false' block, unless the true block would clobber
1790 // the predicate, in which case, do the opposite.
1791 BBInfo *BBI1 = &TrueBBI;
1792 BBInfo *BBI2 = &FalseBBI;
1793 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1794 if (TII->reverseBranchCondition(RevCond))
1795 llvm_unreachable("Unable to reverse branch condition!");
1796 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1797 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1798
1799 // Figure out the more profitable ordering.
1800 bool DoSwap = false;
1801 if (TClobbersPred && !FClobbersPred)
1802 DoSwap = true;
1803 else if (!TClobbersPred && !FClobbersPred) {
1804 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1805 DoSwap = true;
1806 } else if (TClobbersPred && FClobbersPred)
1807 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1808 if (DoSwap) {
1809 std::swap(BBI1, BBI2);
1810 std::swap(Cond1, Cond2);
1811 }
1812
1813 // Remove the conditional branch from entry to the blocks.
1814 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1815
1816 MachineBasicBlock &MBB1 = *BBI1->BB;
1817 MachineBasicBlock &MBB2 = *BBI2->BB;
1818
1819 // Initialize the Redefs:
1820 // - BB2 live-in regs need implicit uses before being redefined by BB1
1821 // instructions.
1822 // - BB1 live-out regs need implicit uses before being redefined by BB2
1823 // instructions. We start with BB1 live-ins so we have the live-out regs
1824 // after tracking the BB1 instructions.
1825 Redefs.init(*TRI);
1826 if (MRI->tracksLiveness()) {
1827 Redefs.addLiveInsNoPristines(MBB1);
1828 Redefs.addLiveInsNoPristines(MBB2);
1829 }
1830
1831 // Remove the duplicated instructions at the beginnings of both paths.
1832 // Skip dbg_value instructions.
1835 BBI1->NonPredSize -= NumDups1;
1836 BBI2->NonPredSize -= NumDups1;
1837
1838 // Skip past the dups on each side separately since there may be
1839 // differing dbg_value entries. NumDups1 can include a "return"
1840 // instruction, if it's not marked as "branch".
1841 for (unsigned i = 0; i < NumDups1; ++DI1) {
1842 if (DI1 == MBB1.end())
1843 break;
1844 if (!DI1->isDebugInstr())
1845 ++i;
1846 }
1847 while (NumDups1 != 0) {
1848 // Since this instruction is going to be deleted, update call
1849 // info state if the instruction is call instruction.
1850 if (DI2->shouldUpdateAdditionalCallInfo())
1851 MBB2.getParent()->eraseAdditionalCallInfo(&*DI2);
1852
1853 ++DI2;
1854 if (DI2 == MBB2.end())
1855 break;
1856 if (!DI2->isDebugInstr())
1857 --NumDups1;
1858 }
1859
1860 if (MRI->tracksLiveness()) {
1861 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1863 Redefs.stepForward(MI, Dummy);
1864 }
1865 }
1866
1867 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1868 MBB2.erase(MBB2.begin(), DI2);
1869
1870 // The branches have been checked to match, so it is safe to remove the
1871 // branch in BB1 and rely on the copy in BB2. The complication is that
1872 // the blocks may end with a return instruction, which may or may not
1873 // be marked as "branch". If it's not, then it could be included in
1874 // "dups1", leaving the blocks potentially empty after moving the common
1875 // duplicates.
1876#ifndef NDEBUG
1877 // Unanalyzable branches must match exactly. Check that now.
1878 if (!BBI1->IsBrAnalyzable)
1879 verifySameBranchInstructions(&MBB1, &MBB2);
1880#endif
1881 // Remove duplicated instructions from the tail of MBB1: any branch
1882 // instructions, and the common instructions counted by NumDups2.
1883 DI1 = MBB1.end();
1884 while (DI1 != MBB1.begin()) {
1885 MachineBasicBlock::iterator Prev = std::prev(DI1);
1886 if (!Prev->isBranch() && !Prev->isDebugInstr())
1887 break;
1888 DI1 = Prev;
1889 }
1890 for (unsigned i = 0; i != NumDups2; ) {
1891 // NumDups2 only counted non-dbg_value instructions, so this won't
1892 // run off the head of the list.
1893 assert(DI1 != MBB1.begin());
1894
1895 --DI1;
1896
1897 // Since this instruction is going to be deleted, update call
1898 // info state if the instruction is call instruction.
1899 if (DI1->shouldUpdateAdditionalCallInfo())
1900 MBB1.getParent()->eraseAdditionalCallInfo(&*DI1);
1901
1902 // skip dbg_value instructions
1903 if (!DI1->isDebugInstr())
1904 ++i;
1905 }
1906 MBB1.erase(DI1, MBB1.end());
1907
1908 DI2 = BBI2->BB->end();
1909 // The branches have been checked to match. Skip over the branch in the false
1910 // block so that we don't try to predicate it.
1911 if (RemoveBranch)
1912 BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1913 else {
1914 // Make DI2 point to the end of the range where the common "tail"
1915 // instructions could be found.
1916 while (DI2 != MBB2.begin()) {
1917 MachineBasicBlock::iterator Prev = std::prev(DI2);
1918 if (!Prev->isBranch() && !Prev->isDebugInstr())
1919 break;
1920 DI2 = Prev;
1921 }
1922 }
1923 while (NumDups2 != 0) {
1924 // NumDups2 only counted non-dbg_value instructions, so this won't
1925 // run off the head of the list.
1926 assert(DI2 != MBB2.begin());
1927 --DI2;
1928 // skip dbg_value instructions
1929 if (!DI2->isDebugInstr())
1930 --NumDups2;
1931 }
1932
1933 // Remember which registers would later be defined by the false block.
1934 // This allows us not to predicate instructions in the true block that would
1935 // later be re-defined. That is, rather than
1936 // subeq r0, r1, #1
1937 // addne r0, r1, #1
1938 // generate:
1939 // sub r0, r1, #1
1940 // addne r0, r1, #1
1941 SmallSet<MCRegister, 4> RedefsByFalse;
1942 SmallSet<MCRegister, 4> ExtUses;
1943 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1944 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1945 if (FI.isDebugInstr())
1946 continue;
1948 for (const MachineOperand &MO : FI.operands()) {
1949 if (!MO.isReg())
1950 continue;
1951 Register Reg = MO.getReg();
1952 if (!Reg)
1953 continue;
1954 if (MO.isDef()) {
1955 Defs.push_back(Reg);
1956 } else if (!RedefsByFalse.count(Reg)) {
1957 // These are defined before ctrl flow reach the 'false' instructions.
1958 // They cannot be modified by the 'true' instructions.
1959 ExtUses.insert_range(TRI->subregs_inclusive(Reg));
1960 }
1961 }
1962
1963 for (MCRegister Reg : Defs) {
1964 if (!ExtUses.contains(Reg))
1965 RedefsByFalse.insert_range(TRI->subregs_inclusive(Reg));
1966 }
1967 }
1968 }
1969
1970 // Predicate the 'true' block.
1971 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1972
1973 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1974 // a non-predicated in BBI2, then we don't want to predicate the one from
1975 // BBI2. The reason is that if we merged these blocks, we would end up with
1976 // two predicated terminators in the same block.
1977 // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1978 // predicate them either. They were checked to be identical, and so the
1979 // same branch would happen regardless of which path was taken.
1980 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1983 bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
1984 bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
1985 if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
1986 --DI2;
1987 }
1988
1989 // Predicate the 'false' block.
1990 PredicateBlock(*BBI2, DI2, *Cond2);
1991
1992 // Merge the true block into the entry of the diamond.
1993 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1994 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1995 return true;
1996}
1997
1998/// If convert an almost-diamond sub-CFG where the true
1999/// and false blocks share a common tail.
2000bool IfConverterImpl::IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
2001 unsigned NumDups1,
2002 unsigned NumDups2,
2003 bool TClobbersPred,
2004 bool FClobbersPred) {
2005 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
2006 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
2007
2008 // Save the debug location for later.
2009 DebugLoc dl;
2010 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
2011 if (TIE != TrueBBI.BB->end())
2012 dl = TIE->getDebugLoc();
2013 // Removing branches from both blocks is safe, because we have already
2014 // determined that both blocks have the same branch instructions. The branch
2015 // will be added back at the end, unpredicated.
2016 if (!IfConvertDiamondCommon(
2017 BBI, TrueBBI, FalseBBI,
2018 NumDups1, NumDups2,
2019 TClobbersPred, FClobbersPred,
2020 /* RemoveBranch */ true, /* MergeAddEdges */ true))
2021 return false;
2022
2023 // Add back the branch.
2024 // Debug location saved above when removing the branch from BBI2
2025 TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
2026 TrueBBI.BrCond, dl);
2027
2028 // Update block info.
2029 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
2030 InvalidatePreds(*BBI.BB);
2031
2032 // FIXME: Must maintain LiveIns.
2033 return true;
2034}
2035
2036/// If convert a diamond sub-CFG.
2037bool IfConverterImpl::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
2038 unsigned NumDups1, unsigned NumDups2,
2039 bool TClobbersPred, bool FClobbersPred) {
2040 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
2041 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
2042 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
2043
2044 // True block must fall through or end with an unanalyzable terminator.
2045 if (!TailBB) {
2046 if (blockAlwaysFallThrough(TrueBBI))
2047 TailBB = FalseBBI.TrueBB;
2048 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
2049 }
2050
2051 if (!IfConvertDiamondCommon(
2052 BBI, TrueBBI, FalseBBI,
2053 NumDups1, NumDups2,
2054 TClobbersPred, FClobbersPred,
2055 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
2056 /* MergeAddEdges */ TailBB == nullptr))
2057 return false;
2058
2059 // If the if-converted block falls through or unconditionally branches into
2060 // the tail block, and the tail block does not have other predecessors, then
2061 // fold the tail block in as well. Otherwise, unless it falls through to the
2062 // tail, add a unconditional branch to it.
2063 if (TailBB) {
2064 // We need to remove the edges to the true and false blocks manually since
2065 // we didn't let IfConvertDiamondCommon update the CFG.
2066 BBI.BB->removeSuccessor(TrueBBI.BB);
2067 BBI.BB->removeSuccessor(FalseBBI.BB, true);
2068
2069 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
2070 bool CanMergeTail =
2071 blockNeverFallThrough(TailBBI) && !TailBBI.BB->hasAddressTaken();
2072 // The if-converted block can still have a predicated terminator
2073 // (e.g. a predicated return). If that is the case, we cannot merge
2074 // it with the tail block.
2075 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
2076 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
2077 CanMergeTail = false;
2078 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
2079 // check if there are any other predecessors besides those.
2080 unsigned NumPreds = TailBB->pred_size();
2081 if (NumPreds > 1)
2082 CanMergeTail = false;
2083 else if (NumPreds == 1 && CanMergeTail) {
2085 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
2086 CanMergeTail = false;
2087 }
2088 if (CanMergeTail) {
2089 MergeBlocks(BBI, TailBBI);
2090 TailBBI.IsDone = true;
2091 } else {
2092 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
2093 InsertUncondBranch(*BBI.BB, *TailBB, TII);
2094 BBI.HasFallThrough = false;
2095 }
2096 }
2097
2098 // Update block info.
2099 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
2100 InvalidatePreds(*BBI.BB);
2101
2102 // FIXME: Must maintain LiveIns.
2103 return true;
2104}
2105
2106static bool MaySpeculate(const MachineInstr &MI,
2107 SmallSet<MCRegister, 4> &LaterRedefs) {
2108 bool SawStore = true;
2109 if (!MI.isSafeToMove(SawStore))
2110 return false;
2111
2112 for (const MachineOperand &MO : MI.operands()) {
2113 if (!MO.isReg())
2114 continue;
2115 Register Reg = MO.getReg();
2116 if (!Reg)
2117 continue;
2118 if (MO.isDef() && !LaterRedefs.count(Reg))
2119 return false;
2120 }
2121
2122 return true;
2123}
2124
2125/// Predicate instructions from the start of the block to the specified end with
2126/// the specified condition.
2127void IfConverterImpl::PredicateBlock(BBInfo &BBI, MachineBasicBlock::iterator E,
2128 SmallVectorImpl<MachineOperand> &Cond,
2129 SmallSet<MCRegister, 4> *LaterRedefs) {
2130 bool AnyUnpred = false;
2131 bool MaySpec = LaterRedefs != nullptr;
2132 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2133 if (I.isDebugInstr() || TII->isPredicated(I))
2134 continue;
2135 // It may be possible not to predicate an instruction if it's the 'true'
2136 // side of a diamond and the 'false' side may re-define the instruction's
2137 // defs.
2138 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
2139 AnyUnpred = true;
2140 continue;
2141 }
2142 // If any instruction is predicated, then every instruction after it must
2143 // be predicated.
2144 MaySpec = false;
2145 if (!TII->PredicateInstruction(I, Cond)) {
2146#ifndef NDEBUG
2147 dbgs() << "Unable to predicate " << I << "!\n";
2148#endif
2149 llvm_unreachable(nullptr);
2150 }
2151
2152 // If the predicated instruction now redefines a register as the result of
2153 // if-conversion, add an implicit kill.
2154 UpdatePredRedefs(I, Redefs);
2155 }
2156
2157 BBI.Predicate.append(Cond.begin(), Cond.end());
2158
2159 BBI.IsAnalyzed = false;
2160 BBI.NonPredSize = 0;
2161
2162 ++NumIfConvBBs;
2163 if (AnyUnpred)
2164 ++NumUnpred;
2165}
2166
2167/// Copy and predicate instructions from source BB to the destination block.
2168/// Skip end of block branches if IgnoreBr is true.
2169void IfConverterImpl::CopyAndPredicateBlock(
2170 BBInfo &ToBBI, BBInfo &FromBBI, SmallVectorImpl<MachineOperand> &Cond,
2171 bool IgnoreBr) {
2172 MachineFunction &MF = *ToBBI.BB->getParent();
2173
2174 MachineBasicBlock &FromMBB = *FromBBI.BB;
2175 for (MachineInstr &I : FromMBB) {
2176 // Do not copy the end of the block branches.
2177 if (IgnoreBr && I.isBranch())
2178 break;
2179
2180 MachineInstr *MI = MF.CloneMachineInstr(&I);
2181 // Make a copy of the call info.
2182 if (I.isCandidateForAdditionalCallInfo())
2184
2185 ToBBI.BB->insert(ToBBI.BB->end(), MI);
2186 ToBBI.NonPredSize++;
2187 unsigned ExtraPredCost = TII->getPredicationCost(I);
2188 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2189 if (NumCycles > 1)
2190 ToBBI.ExtraCost += NumCycles-1;
2191 ToBBI.ExtraCost2 += ExtraPredCost;
2192
2193 if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
2194 if (!TII->PredicateInstruction(*MI, Cond)) {
2195#ifndef NDEBUG
2196 dbgs() << "Unable to predicate " << I << "!\n";
2197#endif
2198 llvm_unreachable(nullptr);
2199 }
2200 }
2201
2202 // If the predicated instruction now redefines a register as the result of
2203 // if-conversion, add an implicit kill.
2204 UpdatePredRedefs(*MI, Redefs);
2205 }
2206
2207 if (!IgnoreBr) {
2208 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2209 FromMBB.succ_end());
2210 MachineBasicBlock *NBB = getNextBlock(FromMBB);
2211 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2212
2213 for (MachineBasicBlock *Succ : Succs) {
2214 // Fallthrough edge can't be transferred.
2215 if (Succ == FallThrough)
2216 continue;
2217 ToBBI.BB->addSuccessor(Succ);
2218 }
2219 }
2220
2221 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2222 ToBBI.Predicate.append(Cond.begin(), Cond.end());
2223
2224 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2225 ToBBI.IsAnalyzed = false;
2226
2227 ++NumDupBBs;
2228}
2229
2230/// Move all instructions from FromBB to the end of ToBB. This will leave
2231/// FromBB as an empty block, so remove all of its successor edges and move it
2232/// to the end of the function. If AddEdges is true, i.e., when FromBBI's
2233/// branch is being moved, add those successor edges to ToBBI and remove the old
2234/// edge from ToBBI to FromBBI.
2235void IfConverterImpl::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI,
2236 bool AddEdges) {
2237 MachineBasicBlock &FromMBB = *FromBBI.BB;
2238 assert(!FromMBB.hasAddressTaken() &&
2239 "Removing a BB whose address is taken!");
2240
2241 // If we're about to splice an INLINEASM_BR from FromBBI, we need to update
2242 // ToBBI's successor list accordingly.
2243 if (FromMBB.mayHaveInlineAsmBr())
2244 for (MachineInstr &MI : FromMBB)
2245 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
2246 for (MachineOperand &MO : MI.operands())
2247 if (MO.isMBB() && !ToBBI.BB->isSuccessor(MO.getMBB()))
2248 ToBBI.BB->addSuccessor(MO.getMBB(), BranchProbability::getZero());
2249
2250 // In case FromMBB contains terminators (e.g. return instruction),
2251 // first move the non-terminator instructions, then the terminators.
2252 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
2253 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2254 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2255
2256 // If FromBB has non-predicated terminator we should copy it at the end.
2257 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
2258 ToTI = ToBBI.BB->end();
2259 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2260
2261 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2262 // unknown probabilities into known ones.
2263 // FIXME: This usage is too tricky and in the future we would like to
2264 // eliminate all unknown probabilities in MBB.
2265 if (ToBBI.IsBrAnalyzable)
2266 ToBBI.BB->normalizeSuccProbs();
2267
2268 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
2269 MachineBasicBlock *NBB = getNextBlock(FromMBB);
2270 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2271 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2272 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2273 auto To2FromProb = BranchProbability::getZero();
2274 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2275 // Remove the old edge but remember the edge probability so we can calculate
2276 // the correct weights on the new edges being added further down.
2277 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2278 ToBBI.BB->removeSuccessor(&FromMBB);
2279 }
2280
2281 for (MachineBasicBlock *Succ : FromSuccs) {
2282 // Fallthrough edge can't be transferred.
2283 if (Succ == FallThrough) {
2284 FromMBB.removeSuccessor(Succ);
2285 continue;
2286 }
2287
2288 auto NewProb = BranchProbability::getZero();
2289 if (AddEdges) {
2290 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2291 // which is a portion of the edge probability from FromMBB to Succ. The
2292 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2293 // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2294 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2295
2296 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2297 // only happens when if-converting a diamond CFG and FromMBB is the
2298 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2299 // could just use the probabilities on FromMBB's out-edges when adding
2300 // new successors.
2301 if (!To2FromProb.isZero())
2302 NewProb *= To2FromProb;
2303 }
2304
2305 FromMBB.removeSuccessor(Succ);
2306
2307 if (AddEdges) {
2308 // If the edge from ToBBI.BB to Succ already exists, update the
2309 // probability of this edge by adding NewProb to it. An example is shown
2310 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2311 // don't have to set C as A's successor as it already is. We only need to
2312 // update the edge probability on A->C. Note that B will not be
2313 // immediately removed from A's successors. It is possible that B->D is
2314 // not removed either if D is a fallthrough of B. Later the edge A->D
2315 // (generated here) and B->D will be combined into one edge. To maintain
2316 // correct edge probability of this combined edge, we need to set the edge
2317 // probability of A->B to zero, which is already done above. The edge
2318 // probability on A->D is calculated by scaling the original probability
2319 // on A->B by the probability of B->D.
2320 //
2321 // Before ifcvt: After ifcvt (assume B->D is kept):
2322 //
2323 // A A
2324 // /| /|\
2325 // / B / B|
2326 // | /| | ||
2327 // |/ | | |/
2328 // C D C D
2329 //
2330 if (ToBBI.BB->isSuccessor(Succ))
2331 ToBBI.BB->setSuccProbability(
2332 find(ToBBI.BB->successors(), Succ),
2333 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2334 else
2335 ToBBI.BB->addSuccessor(Succ, NewProb);
2336 }
2337 }
2338
2339 // Move the now empty FromMBB out of the way to the end of the function so
2340 // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2341 MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2342 if (Last != &FromMBB)
2343 FromMBB.moveAfter(Last);
2344
2345 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2346 // we've done above.
2347 if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2348 ToBBI.BB->normalizeSuccProbs();
2349
2350 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2351 FromBBI.Predicate.clear();
2352
2353 ToBBI.NonPredSize += FromBBI.NonPredSize;
2354 ToBBI.ExtraCost += FromBBI.ExtraCost;
2355 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2356 FromBBI.NonPredSize = 0;
2357 FromBBI.ExtraCost = 0;
2358 FromBBI.ExtraCost2 = 0;
2359
2360 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2361 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2362 ToBBI.IsAnalyzed = false;
2363 FromBBI.IsAnalyzed = false;
2364}
2365
2367 std::function<bool(const MachineFunction &)> Ftor) {
2368 return new IfConverterLegacy(std::move(Ftor));
2369}
2370
2371bool IfConverterLegacy::runOnMachineFunction(MachineFunction &MF) {
2372 if (skipFunction(MF.getFunction()))
2373 return false;
2374 IfConverterImpl Impl;
2375 return Impl.runOnMachineFunction(
2376 MF,
2377 [&]() -> MachineBlockFrequencyInfo & {
2378 return getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
2379 },
2380 [&]() {
2381 return &getAnalysis<MachineBranchProbabilityInfoWrapperPass>()
2382 .getMBPI();
2383 },
2384 [&]() { return &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); },
2385 [&](const MachineFunction &MF) {
2386 return PredicateFtor && !PredicateFtor(MF);
2387 });
2388}
2389
2392 IfConverterImpl Impl;
2393 bool Changed = Impl.runOnMachineFunction(
2394 MF,
2395 [&]() -> MachineBlockFrequencyInfo & {
2397 },
2398 [&]() { return &MFAM.getResult<MachineBranchProbabilityAnalysis>(MF); },
2399 [&]() {
2400 ProfileSummaryInfo *PSI =
2402 .getCachedResult<ProfileSummaryAnalysis>(
2403 *MF.getFunction().getParent());
2404 if (!PSI)
2405 reportFatalUsageError("if-converter requires profile-summary");
2406 return PSI;
2407 },
2408 [&](const MachineFunction &MF) {
2409 return PredicateFtor && !PredicateFtor(MF);
2410 });
2411 if (!Changed)
2412 return PreservedAnalyses::all();
2414}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
Function Alias Analysis false
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
findFalseBlock - BB has a fallthrough.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
BB has a fallthrough. Find its 'false' successor given its 'true' successor.
static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB, const TargetInstrInfo *TII)
Inserts an unconditional branch from MBB to ToMBB.
static void verifySameBranchInstructions(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2)
static MachineBasicBlock * getNextBlock(MachineBasicBlock &MBB)
Returns the next block in the function blocks ordering.
static bool MaySpeculate(const MachineInstr &MI, SmallSet< MCRegister, 4 > &LaterRedefs)
static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs)
Behaves like LivePhysRegs::stepForward() but also adds implicit uses to all values defined in MI whic...
static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB)
Returns true either if ToMBB is the next block after MBB or that all the intervening blocks are empty...
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineOperand, 4 > Cond
int64_t C1
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
bool OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineLoopInfo *mli=nullptr, bool AfterPlacement=false)
Perhaps branch folding, tail merging and other CFG optimizations on the given function.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
BranchProbability getCompl() const
A debug info location.
Definition DebugLoc.h:127
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
Module * getParent()
Get the module that this global value is contained inside of...
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool ClobbersPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred, bool SkipDead) const override
If the specified instruction defines any predicate or condition code register(s) used for predication...
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, BranchProbability Probability) const override
Return true if it's profitable for if-converter to duplicate instructions of specified accumulated in...
bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const override
Returns true if the first specified predicate subsumes the second, e.g.
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A set of physical registers with utility functions to track liveness when walking backward/forward th...
LLVM_ABI void stepForward(const MachineInstr &MI, SmallVectorImpl< std::pair< MCPhysReg, const MachineOperand * > > &Clobbers)
Simulates liveness when stepping forward over an instruction(bundle).
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
LLVM_ABI void addLiveInsNoPristines(const MachineBasicBlock &MBB)
Adds all live-in registers of basic block MBB but skips pristine registers.
MachineInstrBundleIterator< const MachineInstr > const_iterator
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool mayHaveInlineAsmBr() const
Returns true if this block may have an INLINEASM_BR (overestimate, by checking if any of the successo...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void eraseAdditionalCallInfo(const MachineInstr *MI)
Following functions update call site info.
void copyAdditionalCallInfo(const MachineInstr *Old, const MachineInstr *New)
Copy the call site info from Old to \ New.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
MachineOperand class - Representation of each machine instruction operand.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
void insert_range(Range &&R)
Definition SmallSet.h:196
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
Definition SparseSet.h:118
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition SparseSet.h:254
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise.
Definition SparseSet.h:240
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition SparseSet.h:153
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
TargetSubtargetInfo - Generic base class for all target subtargets.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isPredicated(const MCInst &MI, const MCInstrInfo *MCII)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Define
Register definition.
LLVM_ABI FunctionPass * createIfConverterLegacyPass(std::function< bool(const MachineFunction &)> Ftor)
scope_exit(Callable) -> scope_exit< Callable >
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI char & IfConverterID
IfConverter - This pass performs machine code if conversion.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881