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