[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / Transforms / Scalar / LoopUnswitch.cpp
blob977046554547333468a639b01b7ac7ea1e2cfd63
1 //===- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop -------===//
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 pass transforms loops that contain branches on loop-invariant conditions
10 // to multiple loops. For example, it turns the left into the right code:
12 // for (...) if (lic)
13 // A for (...)
14 // if (lic) A; B; C
15 // B else
16 // C for (...)
17 // A; C
19 // This can increase the size of the code exponentially (doubling it every time
20 // a loop is unswitched) so we only unswitch if the resultant code will be
21 // smaller than a threshold.
23 // This pass expects LICM to be run before it to hoist invariant conditions out
24 // of the loop, to make the unswitching opportunity obvious.
26 //===----------------------------------------------------------------------===//
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/AssumptionCache.h"
34 #include "llvm/Analysis/CodeMetrics.h"
35 #include "llvm/Analysis/InstructionSimplify.h"
36 #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
37 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopIterator.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/MemorySSA.h"
42 #include "llvm/Analysis/MemorySSAUpdater.h"
43 #include "llvm/Analysis/MustExecute.h"
44 #include "llvm/Analysis/ScalarEvolution.h"
45 #include "llvm/Analysis/TargetTransformInfo.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/BasicBlock.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Dominators.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/InstrTypes.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/User.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/IR/ValueHandle.h"
64 #include "llvm/InitializePasses.h"
65 #include "llvm/Pass.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Transforms/Scalar.h"
71 #include "llvm/Transforms/Scalar/LoopPassManager.h"
72 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
73 #include "llvm/Transforms/Utils/Cloning.h"
74 #include "llvm/Transforms/Utils/Local.h"
75 #include "llvm/Transforms/Utils/LoopUtils.h"
76 #include "llvm/Transforms/Utils/ValueMapper.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <map>
80 #include <set>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
85 using namespace llvm;
87 #define DEBUG_TYPE "loop-unswitch"
89 STATISTIC(NumBranches, "Number of branches unswitched");
90 STATISTIC(NumSwitches, "Number of switches unswitched");
91 STATISTIC(NumGuards, "Number of guards unswitched");
92 STATISTIC(NumSelects , "Number of selects unswitched");
93 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
94 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
95 STATISTIC(TotalInsts, "Total number of instructions analyzed");
97 // The specific value of 100 here was chosen based only on intuition and a
98 // few specific examples.
99 static cl::opt<unsigned>
100 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
101 cl::init(100), cl::Hidden);
103 static cl::opt<unsigned>
104 MSSAThreshold("loop-unswitch-memoryssa-threshold",
105 cl::desc("Max number of memory uses to explore during "
106 "partial unswitching analysis"),
107 cl::init(100), cl::Hidden);
109 namespace {
111 class LUAnalysisCache {
112 using UnswitchedValsMap =
113 DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
114 using UnswitchedValsIt = UnswitchedValsMap::iterator;
116 struct LoopProperties {
117 unsigned CanBeUnswitchedCount;
118 unsigned WasUnswitchedCount;
119 unsigned SizeEstimation;
120 UnswitchedValsMap UnswitchedVals;
123 // Here we use std::map instead of DenseMap, since we need to keep valid
124 // LoopProperties pointer for current loop for better performance.
125 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
126 using LoopPropsMapIt = LoopPropsMap::iterator;
128 LoopPropsMap LoopsProperties;
129 UnswitchedValsMap *CurLoopInstructions = nullptr;
130 LoopProperties *CurrentLoopProperties = nullptr;
132 // A loop unswitching with an estimated cost above this threshold
133 // is not performed. MaxSize is turned into unswitching quota for
134 // the current loop, and reduced correspondingly, though note that
135 // the quota is returned by releaseMemory() when the loop has been
136 // processed, so that MaxSize will return to its previous
137 // value. So in most cases MaxSize will equal the Threshold flag
138 // when a new loop is processed. An exception to that is that
139 // MaxSize will have a smaller value while processing nested loops
140 // that were introduced due to loop unswitching of an outer loop.
142 // FIXME: The way that MaxSize works is subtle and depends on the
143 // pass manager processing loops and calling releaseMemory() in a
144 // specific order. It would be good to find a more straightforward
145 // way of doing what MaxSize does.
146 unsigned MaxSize;
148 public:
149 LUAnalysisCache() : MaxSize(Threshold) {}
151 // Analyze loop. Check its size, calculate is it possible to unswitch
152 // it. Returns true if we can unswitch this loop.
153 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
154 AssumptionCache *AC);
156 // Clean all data related to given loop.
157 void forgetLoop(const Loop *L);
159 // Mark case value as unswitched.
160 // Since SI instruction can be partly unswitched, in order to avoid
161 // extra unswitching in cloned loops keep track all unswitched values.
162 void setUnswitched(const SwitchInst *SI, const Value *V);
164 // Check was this case value unswitched before or not.
165 bool isUnswitched(const SwitchInst *SI, const Value *V);
167 // Returns true if another unswitching could be done within the cost
168 // threshold.
169 bool costAllowsUnswitching();
171 // Clone all loop-unswitch related loop properties.
172 // Redistribute unswitching quotas.
173 // Note, that new loop data is stored inside the VMap.
174 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
175 const ValueToValueMapTy &VMap);
178 class LoopUnswitch : public LoopPass {
179 LoopInfo *LI; // Loop information
180 LPPassManager *LPM;
181 AssumptionCache *AC;
183 // Used to check if second loop needs processing after
184 // rewriteLoopBodyWithConditionConstant rewrites first loop.
185 std::vector<Loop*> LoopProcessWorklist;
187 LUAnalysisCache BranchesInfo;
189 bool OptimizeForSize;
190 bool RedoLoop = false;
192 Loop *CurrentLoop = nullptr;
193 DominatorTree *DT = nullptr;
194 MemorySSA *MSSA = nullptr;
195 AAResults *AA = nullptr;
196 std::unique_ptr<MemorySSAUpdater> MSSAU;
197 BasicBlock *LoopHeader = nullptr;
198 BasicBlock *LoopPreheader = nullptr;
200 bool SanitizeMemory;
201 SimpleLoopSafetyInfo SafetyInfo;
203 // LoopBlocks contains all of the basic blocks of the loop, including the
204 // preheader of the loop, the body of the loop, and the exit blocks of the
205 // loop, in that order.
206 std::vector<BasicBlock*> LoopBlocks;
207 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
208 std::vector<BasicBlock*> NewBlocks;
210 bool HasBranchDivergence;
212 public:
213 static char ID; // Pass ID, replacement for typeid
215 explicit LoopUnswitch(bool Os = false, bool HasBranchDivergence = false)
216 : LoopPass(ID), OptimizeForSize(Os),
217 HasBranchDivergence(HasBranchDivergence) {
218 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
221 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
222 bool processCurrentLoop();
223 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
225 /// This transformation requires natural loop information & requires that
226 /// loop preheaders be inserted into the CFG.
228 void getAnalysisUsage(AnalysisUsage &AU) const override {
229 // Lazy BFI and BPI are marked as preserved here so Loop Unswitching
230 // can remain part of the same loop pass as LICM
231 AU.addPreserved<LazyBlockFrequencyInfoPass>();
232 AU.addPreserved<LazyBranchProbabilityInfoPass>();
233 AU.addRequired<AssumptionCacheTracker>();
234 AU.addRequired<TargetTransformInfoWrapperPass>();
235 AU.addRequired<MemorySSAWrapperPass>();
236 AU.addPreserved<MemorySSAWrapperPass>();
237 if (HasBranchDivergence)
238 AU.addRequired<LegacyDivergenceAnalysis>();
239 getLoopAnalysisUsage(AU);
242 private:
243 void releaseMemory() override { BranchesInfo.forgetLoop(CurrentLoop); }
245 void initLoopData() {
246 LoopHeader = CurrentLoop->getHeader();
247 LoopPreheader = CurrentLoop->getLoopPreheader();
250 /// Split all of the edges from inside the loop to their exit blocks.
251 /// Update the appropriate Phi nodes as we do so.
252 void splitExitEdges(Loop *L,
253 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
255 bool tryTrivialLoopUnswitch(bool &Changed);
257 bool unswitchIfProfitable(Value *LoopCond, Constant *Val,
258 Instruction *TI = nullptr,
259 ArrayRef<Instruction *> ToDuplicate = {});
260 void unswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
261 BasicBlock *ExitBlock, Instruction *TI);
262 void unswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
263 Instruction *TI,
264 ArrayRef<Instruction *> ToDuplicate = {});
266 void rewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
267 Constant *Val, bool IsEqual);
269 void
270 emitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
271 BasicBlock *TrueDest, BasicBlock *FalseDest,
272 BranchInst *OldBranch, Instruction *TI,
273 ArrayRef<Instruction *> ToDuplicate = {});
275 void simplifyCode(std::vector<Instruction *> &Worklist, Loop *L);
277 /// Given that the Invariant is not equal to Val. Simplify instructions
278 /// in the loop.
279 Value *simplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
280 Constant *Val);
283 } // end anonymous namespace
285 // Analyze loop. Check its size, calculate is it possible to unswitch
286 // it. Returns true if we can unswitch this loop.
287 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
288 AssumptionCache *AC) {
289 LoopPropsMapIt PropsIt;
290 bool Inserted;
291 std::tie(PropsIt, Inserted) =
292 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
294 LoopProperties &Props = PropsIt->second;
296 if (Inserted) {
297 // New loop.
299 // Limit the number of instructions to avoid causing significant code
300 // expansion, and the number of basic blocks, to avoid loops with
301 // large numbers of branches which cause loop unswitching to go crazy.
302 // This is a very ad-hoc heuristic.
304 SmallPtrSet<const Value *, 32> EphValues;
305 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
307 // FIXME: This is overly conservative because it does not take into
308 // consideration code simplification opportunities and code that can
309 // be shared by the resultant unswitched loops.
310 CodeMetrics Metrics;
311 for (BasicBlock *BB : L->blocks())
312 Metrics.analyzeBasicBlock(BB, TTI, EphValues);
314 Props.SizeEstimation = Metrics.NumInsts;
315 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
316 Props.WasUnswitchedCount = 0;
317 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
319 if (Metrics.notDuplicatable) {
320 LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
321 << ", contents cannot be "
322 << "duplicated!\n");
323 return false;
327 // Be careful. This links are good only before new loop addition.
328 CurrentLoopProperties = &Props;
329 CurLoopInstructions = &Props.UnswitchedVals;
331 return true;
334 // Clean all data related to given loop.
335 void LUAnalysisCache::forgetLoop(const Loop *L) {
336 LoopPropsMapIt LIt = LoopsProperties.find(L);
338 if (LIt != LoopsProperties.end()) {
339 LoopProperties &Props = LIt->second;
340 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
341 Props.SizeEstimation;
342 LoopsProperties.erase(LIt);
345 CurrentLoopProperties = nullptr;
346 CurLoopInstructions = nullptr;
349 // Mark case value as unswitched.
350 // Since SI instruction can be partly unswitched, in order to avoid
351 // extra unswitching in cloned loops keep track all unswitched values.
352 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
353 (*CurLoopInstructions)[SI].insert(V);
356 // Check was this case value unswitched before or not.
357 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
358 return (*CurLoopInstructions)[SI].count(V);
361 bool LUAnalysisCache::costAllowsUnswitching() {
362 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
365 // Clone all loop-unswitch related loop properties.
366 // Redistribute unswitching quotas.
367 // Note, that new loop data is stored inside the VMap.
368 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
369 const ValueToValueMapTy &VMap) {
370 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
371 LoopProperties &OldLoopProps = *CurrentLoopProperties;
372 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
374 // Reallocate "can-be-unswitched quota"
376 --OldLoopProps.CanBeUnswitchedCount;
377 ++OldLoopProps.WasUnswitchedCount;
378 NewLoopProps.WasUnswitchedCount = 0;
379 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
380 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
381 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
383 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
385 // Clone unswitched values info:
386 // for new loop switches we clone info about values that was
387 // already unswitched and has redundant successors.
388 for (const auto &I : Insts) {
389 const SwitchInst *OldInst = I.first;
390 Value *NewI = VMap.lookup(OldInst);
391 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
392 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
394 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
398 char LoopUnswitch::ID = 0;
400 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
401 false, false)
402 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
403 INITIALIZE_PASS_DEPENDENCY(LoopPass)
404 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
405 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
406 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
407 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
408 false, false)
410 Pass *llvm::createLoopUnswitchPass(bool Os, bool HasBranchDivergence) {
411 return new LoopUnswitch(Os, HasBranchDivergence);
414 /// Operator chain lattice.
415 enum OperatorChain {
416 OC_OpChainNone, ///< There is no operator.
417 OC_OpChainOr, ///< There are only ORs.
418 OC_OpChainAnd, ///< There are only ANDs.
419 OC_OpChainMixed ///< There are ANDs and ORs.
422 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
423 /// an invariant piece, return the invariant. Otherwise, return null.
425 /// NOTE: findLIVLoopCondition will not return a partial LIV by walking up a
426 /// mixed operator chain, as we can not reliably find a value which will
427 /// simplify the operator chain. If the chain is AND-only or OR-only, we can use
428 /// 0 or ~0 to simplify the chain.
430 /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
431 /// simplify the condition itself to a loop variant condition, but at the
432 /// cost of creating an entirely new loop.
433 static Value *findLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
434 OperatorChain &ParentChain,
435 DenseMap<Value *, Value *> &Cache,
436 MemorySSAUpdater *MSSAU) {
437 auto CacheIt = Cache.find(Cond);
438 if (CacheIt != Cache.end())
439 return CacheIt->second;
441 // We started analyze new instruction, increment scanned instructions counter.
442 ++TotalInsts;
444 // We can never unswitch on vector conditions.
445 if (Cond->getType()->isVectorTy())
446 return nullptr;
448 // Constants should be folded, not unswitched on!
449 if (isa<Constant>(Cond)) return nullptr;
451 // TODO: Handle: br (VARIANT|INVARIANT).
453 // Hoist simple values out.
454 if (L->makeLoopInvariant(Cond, Changed, nullptr, MSSAU)) {
455 Cache[Cond] = Cond;
456 return Cond;
459 // Walk up the operator chain to find partial invariant conditions.
460 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
461 if (BO->getOpcode() == Instruction::And ||
462 BO->getOpcode() == Instruction::Or) {
463 // Given the previous operator, compute the current operator chain status.
464 OperatorChain NewChain;
465 switch (ParentChain) {
466 case OC_OpChainNone:
467 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
468 OC_OpChainOr;
469 break;
470 case OC_OpChainOr:
471 NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
472 OC_OpChainMixed;
473 break;
474 case OC_OpChainAnd:
475 NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
476 OC_OpChainMixed;
477 break;
478 case OC_OpChainMixed:
479 NewChain = OC_OpChainMixed;
480 break;
483 // If we reach a Mixed state, we do not want to keep walking up as we can not
484 // reliably find a value that will simplify the chain. With this check, we
485 // will return null on the first sight of mixed chain and the caller will
486 // either backtrack to find partial LIV in other operand or return null.
487 if (NewChain != OC_OpChainMixed) {
488 // Update the current operator chain type before we search up the chain.
489 ParentChain = NewChain;
490 // If either the left or right side is invariant, we can unswitch on this,
491 // which will cause the branch to go away in one loop and the condition to
492 // simplify in the other one.
493 if (Value *LHS = findLIVLoopCondition(BO->getOperand(0), L, Changed,
494 ParentChain, Cache, MSSAU)) {
495 Cache[Cond] = LHS;
496 return LHS;
498 // We did not manage to find a partial LIV in operand(0). Backtrack and try
499 // operand(1).
500 ParentChain = NewChain;
501 if (Value *RHS = findLIVLoopCondition(BO->getOperand(1), L, Changed,
502 ParentChain, Cache, MSSAU)) {
503 Cache[Cond] = RHS;
504 return RHS;
509 Cache[Cond] = nullptr;
510 return nullptr;
513 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
514 /// an invariant piece, return the invariant along with the operator chain type.
515 /// Otherwise, return null.
516 static std::pair<Value *, OperatorChain>
517 findLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
518 MemorySSAUpdater *MSSAU) {
519 DenseMap<Value *, Value *> Cache;
520 OperatorChain OpChain = OC_OpChainNone;
521 Value *FCond = findLIVLoopCondition(Cond, L, Changed, OpChain, Cache, MSSAU);
523 // In case we do find a LIV, it can not be obtained by walking up a mixed
524 // operator chain.
525 assert((!FCond || OpChain != OC_OpChainMixed) &&
526 "Do not expect a partial LIV with mixed operator chain");
527 return {FCond, OpChain};
530 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPMRef) {
531 if (skipLoop(L))
532 return false;
534 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
535 *L->getHeader()->getParent());
536 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
537 LPM = &LPMRef;
538 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
539 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
540 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
541 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
542 CurrentLoop = L;
543 Function *F = CurrentLoop->getHeader()->getParent();
545 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
546 if (SanitizeMemory)
547 SafetyInfo.computeLoopSafetyInfo(L);
549 if (VerifyMemorySSA)
550 MSSA->verifyMemorySSA();
552 bool Changed = false;
553 do {
554 assert(CurrentLoop->isLCSSAForm(*DT));
555 if (VerifyMemorySSA)
556 MSSA->verifyMemorySSA();
557 RedoLoop = false;
558 Changed |= processCurrentLoop();
559 } while (RedoLoop);
561 if (VerifyMemorySSA)
562 MSSA->verifyMemorySSA();
564 return Changed;
567 // Return true if the BasicBlock BB is unreachable from the loop header.
568 // Return false, otherwise.
569 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
570 auto *Node = DT->getNode(BB)->getIDom();
571 BasicBlock *DomBB = Node->getBlock();
572 while (CurrentLoop->contains(DomBB)) {
573 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
575 Node = DT->getNode(DomBB)->getIDom();
576 DomBB = Node->getBlock();
578 if (!BInst || !BInst->isConditional())
579 continue;
581 Value *Cond = BInst->getCondition();
582 if (!isa<ConstantInt>(Cond))
583 continue;
585 BasicBlock *UnreachableSucc =
586 Cond == ConstantInt::getTrue(Cond->getContext())
587 ? BInst->getSuccessor(1)
588 : BInst->getSuccessor(0);
590 if (DT->dominates(UnreachableSucc, BB))
591 return true;
593 return false;
596 /// FIXME: Remove this workaround when freeze related patches are done.
597 /// LoopUnswitch and Equality propagation in GVN have discrepancy about
598 /// whether branch on undef/poison has undefine behavior. Here it is to
599 /// rule out some common cases that we found such discrepancy already
600 /// causing problems. Detail could be found in PR31652. Note if the
601 /// func returns true, it is unsafe. But if it is false, it doesn't mean
602 /// it is necessarily safe.
603 static bool equalityPropUnSafe(Value &LoopCond) {
604 ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
605 if (!CI || !CI->isEquality())
606 return false;
608 Value *LHS = CI->getOperand(0);
609 Value *RHS = CI->getOperand(1);
610 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
611 return true;
613 auto HasUndefInPHI = [](PHINode &PN) {
614 for (Value *Opd : PN.incoming_values()) {
615 if (isa<UndefValue>(Opd))
616 return true;
618 return false;
620 PHINode *LPHI = dyn_cast<PHINode>(LHS);
621 PHINode *RPHI = dyn_cast<PHINode>(RHS);
622 if ((LPHI && HasUndefInPHI(*LPHI)) || (RPHI && HasUndefInPHI(*RPHI)))
623 return true;
625 auto HasUndefInSelect = [](SelectInst &SI) {
626 if (isa<UndefValue>(SI.getTrueValue()) ||
627 isa<UndefValue>(SI.getFalseValue()))
628 return true;
629 return false;
631 SelectInst *LSI = dyn_cast<SelectInst>(LHS);
632 SelectInst *RSI = dyn_cast<SelectInst>(RHS);
633 if ((LSI && HasUndefInSelect(*LSI)) || (RSI && HasUndefInSelect(*RSI)))
634 return true;
635 return false;
638 /// Do actual work and unswitch loop if possible and profitable.
639 bool LoopUnswitch::processCurrentLoop() {
640 bool Changed = false;
642 initLoopData();
644 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
645 if (!LoopPreheader)
646 return false;
648 // Loops with indirectbr cannot be cloned.
649 if (!CurrentLoop->isSafeToClone())
650 return false;
652 // Without dedicated exits, splitting the exit edge may fail.
653 if (!CurrentLoop->hasDedicatedExits())
654 return false;
656 LLVMContext &Context = LoopHeader->getContext();
658 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
659 if (!BranchesInfo.countLoop(
660 CurrentLoop,
661 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
662 *CurrentLoop->getHeader()->getParent()),
663 AC))
664 return false;
666 // Try trivial unswitch first before loop over other basic blocks in the loop.
667 if (tryTrivialLoopUnswitch(Changed)) {
668 return true;
671 // Do not do non-trivial unswitch while optimizing for size.
672 // FIXME: Use Function::hasOptSize().
673 if (OptimizeForSize ||
674 LoopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
675 return Changed;
677 // Run through the instructions in the loop, keeping track of three things:
679 // - That we do not unswitch loops containing convergent operations, as we
680 // might be making them control dependent on the unswitch value when they
681 // were not before.
682 // FIXME: This could be refined to only bail if the convergent operation is
683 // not already control-dependent on the unswitch value.
685 // - That basic blocks in the loop contain invokes whose predecessor edges we
686 // cannot split.
688 // - The set of guard intrinsics encountered (these are non terminator
689 // instructions that are also profitable to be unswitched).
691 SmallVector<IntrinsicInst *, 4> Guards;
693 for (const auto BB : CurrentLoop->blocks()) {
694 for (auto &I : *BB) {
695 auto *CB = dyn_cast<CallBase>(&I);
696 if (!CB)
697 continue;
698 if (CB->isConvergent())
699 return Changed;
700 if (auto *II = dyn_cast<InvokeInst>(&I))
701 if (!II->getUnwindDest()->canSplitPredecessors())
702 return Changed;
703 if (auto *II = dyn_cast<IntrinsicInst>(&I))
704 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
705 Guards.push_back(II);
709 for (IntrinsicInst *Guard : Guards) {
710 Value *LoopCond = findLIVLoopCondition(Guard->getOperand(0), CurrentLoop,
711 Changed, MSSAU.get())
712 .first;
713 if (LoopCond &&
714 unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
715 // NB! Unswitching (if successful) could have erased some of the
716 // instructions in Guards leaving dangling pointers there. This is fine
717 // because we're returning now, and won't look at Guards again.
718 ++NumGuards;
719 return true;
723 // Loop over all of the basic blocks in the loop. If we find an interior
724 // block that is branching on a loop-invariant condition, we can unswitch this
725 // loop.
726 for (Loop::block_iterator I = CurrentLoop->block_begin(),
727 E = CurrentLoop->block_end();
728 I != E; ++I) {
729 Instruction *TI = (*I)->getTerminator();
731 // Unswitching on a potentially uninitialized predicate is not
732 // MSan-friendly. Limit this to the cases when the original predicate is
733 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
734 // in the code that did not have one.
735 // This is a workaround for the discrepancy between LLVM IR and MSan
736 // semantics. See PR28054 for more details.
737 if (SanitizeMemory &&
738 !SafetyInfo.isGuaranteedToExecute(*TI, DT, CurrentLoop))
739 continue;
741 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
742 // Some branches may be rendered unreachable because of previous
743 // unswitching.
744 // Unswitch only those branches that are reachable.
745 if (isUnreachableDueToPreviousUnswitching(*I))
746 continue;
748 // If this isn't branching on an invariant condition, we can't unswitch
749 // it.
750 if (BI->isConditional()) {
751 // See if this, or some part of it, is loop invariant. If so, we can
752 // unswitch on it if we desire.
753 Value *LoopCond = findLIVLoopCondition(BI->getCondition(), CurrentLoop,
754 Changed, MSSAU.get())
755 .first;
756 if (LoopCond && !equalityPropUnSafe(*LoopCond) &&
757 unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
758 ++NumBranches;
759 return true;
762 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
763 Value *SC = SI->getCondition();
764 Value *LoopCond;
765 OperatorChain OpChain;
766 std::tie(LoopCond, OpChain) =
767 findLIVLoopCondition(SC, CurrentLoop, Changed, MSSAU.get());
769 unsigned NumCases = SI->getNumCases();
770 if (LoopCond && NumCases) {
771 // Find a value to unswitch on:
772 // FIXME: this should chose the most expensive case!
773 // FIXME: scan for a case with a non-critical edge?
774 Constant *UnswitchVal = nullptr;
775 // Find a case value such that at least one case value is unswitched
776 // out.
777 if (OpChain == OC_OpChainAnd) {
778 // If the chain only has ANDs and the switch has a case value of 0.
779 // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
780 auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
781 if (BranchesInfo.isUnswitched(SI, AllZero))
782 continue;
783 // We are unswitching 0 out.
784 UnswitchVal = AllZero;
785 } else if (OpChain == OC_OpChainOr) {
786 // If the chain only has ORs and the switch has a case value of ~0.
787 // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
788 auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
789 if (BranchesInfo.isUnswitched(SI, AllOne))
790 continue;
791 // We are unswitching ~0 out.
792 UnswitchVal = AllOne;
793 } else {
794 assert(OpChain == OC_OpChainNone &&
795 "Expect to unswitch on trivial chain");
796 // Do not process same value again and again.
797 // At this point we have some cases already unswitched and
798 // some not yet unswitched. Let's find the first not yet unswitched one.
799 for (auto Case : SI->cases()) {
800 Constant *UnswitchValCandidate = Case.getCaseValue();
801 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
802 UnswitchVal = UnswitchValCandidate;
803 break;
808 if (!UnswitchVal)
809 continue;
811 if (unswitchIfProfitable(LoopCond, UnswitchVal)) {
812 ++NumSwitches;
813 // In case of a full LIV, UnswitchVal is the value we unswitched out.
814 // In case of a partial LIV, we only unswitch when its an AND-chain
815 // or OR-chain. In both cases switch input value simplifies to
816 // UnswitchVal.
817 BranchesInfo.setUnswitched(SI, UnswitchVal);
818 return true;
823 // Scan the instructions to check for unswitchable values.
824 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
825 BBI != E; ++BBI)
826 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
827 Value *LoopCond = findLIVLoopCondition(SI->getCondition(), CurrentLoop,
828 Changed, MSSAU.get())
829 .first;
830 if (LoopCond &&
831 unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
832 ++NumSelects;
833 return true;
838 // Check if there is a header condition that is invariant along the patch from
839 // either the true or false successors to the header. This allows unswitching
840 // conditions depending on memory accesses, if there's a path not clobbering
841 // the memory locations. Check if this transform has been disabled using
842 // metadata, to avoid unswitching the same loop multiple times.
843 if (MSSA &&
844 !findOptionMDForLoop(CurrentLoop, "llvm.loop.unswitch.partial.disable")) {
845 if (auto Info =
846 hasPartialIVCondition(*CurrentLoop, MSSAThreshold, *MSSA, *AA)) {
847 assert(!Info->InstToDuplicate.empty() &&
848 "need at least a partially invariant condition");
849 LLVM_DEBUG(dbgs() << "loop-unswitch: Found partially invariant condition "
850 << *Info->InstToDuplicate[0] << "\n");
852 Instruction *TI = CurrentLoop->getHeader()->getTerminator();
853 Value *LoopCond = Info->InstToDuplicate[0];
855 // If the partially unswitched path is a no-op and has a single exit
856 // block, we do not need to do full unswitching. Instead, we can directly
857 // branch to the exit.
858 // TODO: Instead of duplicating the checks, we could also just directly
859 // branch to the exit from the conditional branch in the loop.
860 if (Info->PathIsNoop) {
861 if (HasBranchDivergence &&
862 getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
863 LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
864 << CurrentLoop->getHeader()->getName()
865 << " at non-trivial condition '"
866 << *Info->KnownValue << "' == " << *LoopCond << "\n"
867 << ". Condition is divergent.\n");
868 return false;
871 ++NumBranches;
873 BasicBlock *TrueDest = LoopHeader;
874 BasicBlock *FalseDest = Info->ExitForPath;
875 if (Info->KnownValue->isOneValue())
876 std::swap(TrueDest, FalseDest);
878 auto *OldBr =
879 cast<BranchInst>(CurrentLoop->getLoopPreheader()->getTerminator());
880 emitPreheaderBranchOnCondition(LoopCond, Info->KnownValue, TrueDest,
881 FalseDest, OldBr, TI,
882 Info->InstToDuplicate);
883 delete OldBr;
884 RedoLoop = false;
885 return true;
888 // Otherwise, the path is not a no-op. Run regular unswitching.
889 if (unswitchIfProfitable(LoopCond, Info->KnownValue,
890 CurrentLoop->getHeader()->getTerminator(),
891 Info->InstToDuplicate)) {
892 ++NumBranches;
893 RedoLoop = false;
894 return true;
899 return Changed;
902 /// Check to see if all paths from BB exit the loop with no side effects
903 /// (including infinite loops).
905 /// If true, we return true and set ExitBB to the block we
906 /// exit through.
908 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
909 BasicBlock *&ExitBB,
910 std::set<BasicBlock*> &Visited) {
911 if (!Visited.insert(BB).second) {
912 // Already visited. Without more analysis, this could indicate an infinite
913 // loop.
914 return false;
916 if (!L->contains(BB)) {
917 // Otherwise, this is a loop exit, this is fine so long as this is the
918 // first exit.
919 if (ExitBB) return false;
920 ExitBB = BB;
921 return true;
924 // Otherwise, this is an unvisited intra-loop node. Check all successors.
925 for (BasicBlock *Succ : successors(BB)) {
926 // Check to see if the successor is a trivial loop exit.
927 if (!isTrivialLoopExitBlockHelper(L, Succ, ExitBB, Visited))
928 return false;
931 // Okay, everything after this looks good, check to make sure that this block
932 // doesn't include any side effects.
933 for (Instruction &I : *BB)
934 if (I.mayHaveSideEffects())
935 return false;
937 return true;
940 /// Return true if the specified block unconditionally leads to an exit from
941 /// the specified loop, and has no side-effects in the process. If so, return
942 /// the block that is exited to, otherwise return null.
943 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
944 std::set<BasicBlock*> Visited;
945 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
946 BasicBlock *ExitBB = nullptr;
947 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
948 return ExitBB;
949 return nullptr;
952 /// We have found that we can unswitch CurrentLoop when LoopCond == Val to
953 /// simplify the loop. If we decide that this is profitable,
954 /// unswitch the loop, reprocess the pieces, then return true.
955 bool LoopUnswitch::unswitchIfProfitable(Value *LoopCond, Constant *Val,
956 Instruction *TI,
957 ArrayRef<Instruction *> ToDuplicate) {
958 // Check to see if it would be profitable to unswitch current loop.
959 if (!BranchesInfo.costAllowsUnswitching()) {
960 LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
961 << CurrentLoop->getHeader()->getName()
962 << " at non-trivial condition '" << *Val
963 << "' == " << *LoopCond << "\n"
964 << ". Cost too high.\n");
965 return false;
967 if (HasBranchDivergence &&
968 getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
969 LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
970 << CurrentLoop->getHeader()->getName()
971 << " at non-trivial condition '" << *Val
972 << "' == " << *LoopCond << "\n"
973 << ". Condition is divergent.\n");
974 return false;
977 unswitchNontrivialCondition(LoopCond, Val, CurrentLoop, TI, ToDuplicate);
978 return true;
981 /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
982 /// otherwise branch to FalseDest. Insert the code immediately before OldBranch
983 /// and remove (but not erase!) it from the function.
984 void LoopUnswitch::emitPreheaderBranchOnCondition(
985 Value *LIC, Constant *Val, BasicBlock *TrueDest, BasicBlock *FalseDest,
986 BranchInst *OldBranch, Instruction *TI,
987 ArrayRef<Instruction *> ToDuplicate) {
988 assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
989 assert(TrueDest != FalseDest && "Branch targets should be different");
991 // Insert a conditional branch on LIC to the two preheaders. The original
992 // code is the true version and the new code is the false version.
993 Value *BranchVal = LIC;
994 bool Swapped = false;
996 if (!ToDuplicate.empty()) {
997 ValueToValueMapTy Old2New;
998 for (Instruction *I : reverse(ToDuplicate)) {
999 auto *New = I->clone();
1000 New->insertBefore(OldBranch);
1001 RemapInstruction(New, Old2New,
1002 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1003 Old2New[I] = New;
1005 if (MSSAU) {
1006 MemorySSA *MSSA = MSSAU->getMemorySSA();
1007 auto *MemA = dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(I));
1008 if (!MemA)
1009 continue;
1011 Loop *L = LI->getLoopFor(I->getParent());
1012 auto *DefiningAccess = MemA->getDefiningAccess();
1013 // Get the first defining access before the loop.
1014 while (L->contains(DefiningAccess->getBlock())) {
1015 // If the defining access is a MemoryPhi, get the incoming
1016 // value for the pre-header as defining access.
1017 if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess)) {
1018 DefiningAccess =
1019 MemPhi->getIncomingValueForBlock(L->getLoopPreheader());
1020 } else {
1021 DefiningAccess =
1022 cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
1025 MSSAU->createMemoryAccessInBB(New, DefiningAccess, New->getParent(),
1026 MemorySSA::BeforeTerminator);
1029 BranchVal = Old2New[ToDuplicate[0]];
1030 } else {
1032 if (!isa<ConstantInt>(Val) ||
1033 Val->getType() != Type::getInt1Ty(LIC->getContext()))
1034 BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
1035 else if (Val != ConstantInt::getTrue(Val->getContext())) {
1036 // We want to enter the new loop when the condition is true.
1037 std::swap(TrueDest, FalseDest);
1038 Swapped = true;
1042 // Old branch will be removed, so save its parent and successor to update the
1043 // DomTree.
1044 auto *OldBranchSucc = OldBranch->getSuccessor(0);
1045 auto *OldBranchParent = OldBranch->getParent();
1047 // Insert the new branch.
1048 BranchInst *BI =
1049 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
1050 if (Swapped)
1051 BI->swapProfMetadata();
1053 // Remove the old branch so there is only one branch at the end. This is
1054 // needed to perform DomTree's internal DFS walk on the function's CFG.
1055 OldBranch->removeFromParent();
1057 // Inform the DT about the new branch.
1058 if (DT) {
1059 // First, add both successors.
1060 SmallVector<DominatorTree::UpdateType, 3> Updates;
1061 if (TrueDest != OldBranchSucc)
1062 Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
1063 if (FalseDest != OldBranchSucc)
1064 Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
1065 // If both of the new successors are different from the old one, inform the
1066 // DT that the edge was deleted.
1067 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
1068 Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
1071 if (MSSAU)
1072 MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
1073 else
1074 DT->applyUpdates(Updates);
1077 // If either edge is critical, split it. This helps preserve LoopSimplify
1078 // form for enclosing loops.
1079 auto Options =
1080 CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
1081 SplitCriticalEdge(BI, 0, Options);
1082 SplitCriticalEdge(BI, 1, Options);
1085 /// Given a loop that has a trivial unswitchable condition in it (a cond branch
1086 /// from its header block to its latch block, where the path through the loop
1087 /// that doesn't execute its body has no side-effects), unswitch it. This
1088 /// doesn't involve any code duplication, just moving the conditional branch
1089 /// outside of the loop and updating loop info.
1090 void LoopUnswitch::unswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
1091 BasicBlock *ExitBlock,
1092 Instruction *TI) {
1093 LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
1094 << LoopHeader->getName() << " [" << L->getBlocks().size()
1095 << " blocks] in Function "
1096 << L->getHeader()->getParent()->getName()
1097 << " on cond: " << *Val << " == " << *Cond << "\n");
1098 // We are going to make essential changes to CFG. This may invalidate cached
1099 // information for L or one of its parent loops in SCEV.
1100 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1101 SEWP->getSE().forgetTopmostLoop(L);
1103 // First step, split the preheader, so that we know that there is a safe place
1104 // to insert the conditional branch. We will change LoopPreheader to have a
1105 // conditional branch on Cond.
1106 BasicBlock *NewPH = SplitEdge(LoopPreheader, LoopHeader, DT, LI, MSSAU.get());
1108 // Now that we have a place to insert the conditional branch, create a place
1109 // to branch to: this is the exit block out of the loop that we should
1110 // short-circuit to.
1112 // Split this block now, so that the loop maintains its exit block, and so
1113 // that the jump from the preheader can execute the contents of the exit block
1114 // without actually branching to it (the exit block should be dominated by the
1115 // loop header, not the preheader).
1116 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
1117 BasicBlock *NewExit =
1118 SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
1120 // Okay, now we have a position to branch from and a position to branch to,
1121 // insert the new conditional branch.
1122 auto *OldBranch = dyn_cast<BranchInst>(LoopPreheader->getTerminator());
1123 assert(OldBranch && "Failed to split the preheader");
1124 emitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1126 // emitPreheaderBranchOnCondition removed the OldBranch from the function.
1127 // Delete it, as it is no longer needed.
1128 delete OldBranch;
1130 // We need to reprocess this loop, it could be unswitched again.
1131 RedoLoop = true;
1133 // Now that we know that the loop is never entered when this condition is a
1134 // particular value, rewrite the loop with this info. We know that this will
1135 // at least eliminate the old branch.
1136 rewriteLoopBodyWithConditionConstant(L, Cond, Val, /*IsEqual=*/false);
1138 ++NumTrivial;
1141 /// Check if the first non-constant condition starting from the loop header is
1142 /// a trivial unswitch condition: that is, a condition controls whether or not
1143 /// the loop does anything at all. If it is a trivial condition, unswitching
1144 /// produces no code duplications (equivalently, it produces a simpler loop and
1145 /// a new empty loop, which gets deleted). Therefore always unswitch trivial
1146 /// condition.
1147 bool LoopUnswitch::tryTrivialLoopUnswitch(bool &Changed) {
1148 BasicBlock *CurrentBB = CurrentLoop->getHeader();
1149 Instruction *CurrentTerm = CurrentBB->getTerminator();
1150 LLVMContext &Context = CurrentBB->getContext();
1152 // If loop header has only one reachable successor (currently via an
1153 // unconditional branch or constant foldable conditional branch, but
1154 // should also consider adding constant foldable switch instruction in
1155 // future), we should keep looking for trivial condition candidates in
1156 // the successor as well. An alternative is to constant fold conditions
1157 // and merge successors into loop header (then we only need to check header's
1158 // terminator). The reason for not doing this in LoopUnswitch pass is that
1159 // it could potentially break LoopPassManager's invariants. Folding dead
1160 // branches could either eliminate the current loop or make other loops
1161 // unreachable. LCSSA form might also not be preserved after deleting
1162 // branches. The following code keeps traversing loop header's successors
1163 // until it finds the trivial condition candidate (condition that is not a
1164 // constant). Since unswitching generates branches with constant conditions,
1165 // this scenario could be very common in practice.
1166 SmallPtrSet<BasicBlock*, 8> Visited;
1168 while (true) {
1169 // If we exit loop or reach a previous visited block, then
1170 // we can not reach any trivial condition candidates (unfoldable
1171 // branch instructions or switch instructions) and no unswitch
1172 // can happen. Exit and return false.
1173 if (!CurrentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
1174 return false;
1176 // Check if this loop will execute any side-effecting instructions (e.g.
1177 // stores, calls, volatile loads) in the part of the loop that the code
1178 // *would* execute. Check the header first.
1179 for (Instruction &I : *CurrentBB)
1180 if (I.mayHaveSideEffects())
1181 return false;
1183 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1184 if (BI->isUnconditional()) {
1185 CurrentBB = BI->getSuccessor(0);
1186 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1187 CurrentBB = BI->getSuccessor(0);
1188 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1189 CurrentBB = BI->getSuccessor(1);
1190 } else {
1191 // Found a trivial condition candidate: non-foldable conditional branch.
1192 break;
1194 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1195 // At this point, any constant-foldable instructions should have probably
1196 // been folded.
1197 ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1198 if (!Cond)
1199 break;
1200 // Find the target block we are definitely going to.
1201 CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
1202 } else {
1203 // We do not understand these terminator instructions.
1204 break;
1207 CurrentTerm = CurrentBB->getTerminator();
1210 // CondVal is the condition that controls the trivial condition.
1211 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1212 Constant *CondVal = nullptr;
1213 BasicBlock *LoopExitBB = nullptr;
1215 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1216 // If this isn't branching on an invariant condition, we can't unswitch it.
1217 if (!BI->isConditional())
1218 return false;
1220 Value *LoopCond = findLIVLoopCondition(BI->getCondition(), CurrentLoop,
1221 Changed, MSSAU.get())
1222 .first;
1224 // Unswitch only if the trivial condition itself is an LIV (not
1225 // partial LIV which could occur in and/or)
1226 if (!LoopCond || LoopCond != BI->getCondition())
1227 return false;
1229 // Check to see if a successor of the branch is guaranteed to
1230 // exit through a unique exit block without having any
1231 // side-effects. If so, determine the value of Cond that causes
1232 // it to do this.
1233 if ((LoopExitBB =
1234 isTrivialLoopExitBlock(CurrentLoop, BI->getSuccessor(0)))) {
1235 CondVal = ConstantInt::getTrue(Context);
1236 } else if ((LoopExitBB =
1237 isTrivialLoopExitBlock(CurrentLoop, BI->getSuccessor(1)))) {
1238 CondVal = ConstantInt::getFalse(Context);
1241 // If we didn't find a single unique LoopExit block, or if the loop exit
1242 // block contains phi nodes, this isn't trivial.
1243 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1244 return false; // Can't handle this.
1246 if (equalityPropUnSafe(*LoopCond))
1247 return false;
1249 unswitchTrivialCondition(CurrentLoop, LoopCond, CondVal, LoopExitBB,
1250 CurrentTerm);
1251 ++NumBranches;
1252 return true;
1253 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1254 // If this isn't switching on an invariant condition, we can't unswitch it.
1255 Value *LoopCond = findLIVLoopCondition(SI->getCondition(), CurrentLoop,
1256 Changed, MSSAU.get())
1257 .first;
1259 // Unswitch only if the trivial condition itself is an LIV (not
1260 // partial LIV which could occur in and/or)
1261 if (!LoopCond || LoopCond != SI->getCondition())
1262 return false;
1264 // Check to see if a successor of the switch is guaranteed to go to the
1265 // latch block or exit through a one exit block without having any
1266 // side-effects. If so, determine the value of Cond that causes it to do
1267 // this.
1268 // Note that we can't trivially unswitch on the default case or
1269 // on already unswitched cases.
1270 for (auto Case : SI->cases()) {
1271 BasicBlock *LoopExitCandidate;
1272 if ((LoopExitCandidate =
1273 isTrivialLoopExitBlock(CurrentLoop, Case.getCaseSuccessor()))) {
1274 // Okay, we found a trivial case, remember the value that is trivial.
1275 ConstantInt *CaseVal = Case.getCaseValue();
1277 // Check that it was not unswitched before, since already unswitched
1278 // trivial vals are looks trivial too.
1279 if (BranchesInfo.isUnswitched(SI, CaseVal))
1280 continue;
1281 LoopExitBB = LoopExitCandidate;
1282 CondVal = CaseVal;
1283 break;
1287 // If we didn't find a single unique LoopExit block, or if the loop exit
1288 // block contains phi nodes, this isn't trivial.
1289 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1290 return false; // Can't handle this.
1292 unswitchTrivialCondition(CurrentLoop, LoopCond, CondVal, LoopExitBB,
1293 nullptr);
1295 // We are only unswitching full LIV.
1296 BranchesInfo.setUnswitched(SI, CondVal);
1297 ++NumSwitches;
1298 return true;
1300 return false;
1303 /// Split all of the edges from inside the loop to their exit blocks.
1304 /// Update the appropriate Phi nodes as we do so.
1305 void LoopUnswitch::splitExitEdges(
1306 Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
1308 for (unsigned I = 0, E = ExitBlocks.size(); I != E; ++I) {
1309 BasicBlock *ExitBlock = ExitBlocks[I];
1310 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1311 pred_end(ExitBlock));
1313 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1314 // general, if we call it on all predecessors of all exits then it does.
1315 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
1316 /*PreserveLCSSA*/ true);
1320 /// We determined that the loop is profitable to unswitch when LIC equal Val.
1321 /// Split it into loop versions and test the condition outside of either loop.
1322 /// Return the loops created as Out1/Out2.
1323 void LoopUnswitch::unswitchNontrivialCondition(
1324 Value *LIC, Constant *Val, Loop *L, Instruction *TI,
1325 ArrayRef<Instruction *> ToDuplicate) {
1326 Function *F = LoopHeader->getParent();
1327 LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1328 << LoopHeader->getName() << " [" << L->getBlocks().size()
1329 << " blocks] in Function " << F->getName() << " when '"
1330 << *Val << "' == " << *LIC << "\n");
1332 // We are going to make essential changes to CFG. This may invalidate cached
1333 // information for L or one of its parent loops in SCEV.
1334 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1335 SEWP->getSE().forgetTopmostLoop(L);
1337 LoopBlocks.clear();
1338 NewBlocks.clear();
1340 if (MSSAU && VerifyMemorySSA)
1341 MSSA->verifyMemorySSA();
1343 // First step, split the preheader and exit blocks, and add these blocks to
1344 // the LoopBlocks list.
1345 BasicBlock *NewPreheader =
1346 SplitEdge(LoopPreheader, LoopHeader, DT, LI, MSSAU.get());
1347 LoopBlocks.push_back(NewPreheader);
1349 // We want the loop to come after the preheader, but before the exit blocks.
1350 llvm::append_range(LoopBlocks, L->blocks());
1352 SmallVector<BasicBlock*, 8> ExitBlocks;
1353 L->getUniqueExitBlocks(ExitBlocks);
1355 // Split all of the edges from inside the loop to their exit blocks. Update
1356 // the appropriate Phi nodes as we do so.
1357 splitExitEdges(L, ExitBlocks);
1359 // The exit blocks may have been changed due to edge splitting, recompute.
1360 ExitBlocks.clear();
1361 L->getUniqueExitBlocks(ExitBlocks);
1363 // Add exit blocks to the loop blocks.
1364 llvm::append_range(LoopBlocks, ExitBlocks);
1366 // Next step, clone all of the basic blocks that make up the loop (including
1367 // the loop preheader and exit blocks), keeping track of the mapping between
1368 // the instructions and blocks.
1369 NewBlocks.reserve(LoopBlocks.size());
1370 ValueToValueMapTy VMap;
1371 for (unsigned I = 0, E = LoopBlocks.size(); I != E; ++I) {
1372 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[I], VMap, ".us", F);
1374 NewBlocks.push_back(NewBB);
1375 VMap[LoopBlocks[I]] = NewBB; // Keep the BB mapping.
1378 // Splice the newly inserted blocks into the function right before the
1379 // original preheader.
1380 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1381 F->getBasicBlockList(),
1382 NewBlocks[0]->getIterator(), F->end());
1384 // Now we create the new Loop object for the versioned loop.
1385 Loop *NewLoop = cloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1387 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1388 // Probably clone more loop-unswitch related loop properties.
1389 BranchesInfo.cloneData(NewLoop, L, VMap);
1391 Loop *ParentLoop = L->getParentLoop();
1392 if (ParentLoop) {
1393 // Make sure to add the cloned preheader and exit blocks to the parent loop
1394 // as well.
1395 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1398 for (unsigned EBI = 0, EBE = ExitBlocks.size(); EBI != EBE; ++EBI) {
1399 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[EBI]]);
1400 // The new exit block should be in the same loop as the old one.
1401 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[EBI]))
1402 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1404 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1405 "Exit block should have been split to have one successor!");
1406 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1408 // If the successor of the exit block had PHI nodes, add an entry for
1409 // NewExit.
1410 for (PHINode &PN : ExitSucc->phis()) {
1411 Value *V = PN.getIncomingValueForBlock(ExitBlocks[EBI]);
1412 ValueToValueMapTy::iterator It = VMap.find(V);
1413 if (It != VMap.end()) V = It->second;
1414 PN.addIncoming(V, NewExit);
1417 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1418 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1419 &*ExitSucc->getFirstInsertionPt());
1421 for (BasicBlock *BB : predecessors(ExitSucc)) {
1422 LandingPadInst *LPI = BB->getLandingPadInst();
1423 LPI->replaceAllUsesWith(PN);
1424 PN->addIncoming(LPI, BB);
1429 // Rewrite the code to refer to itself.
1430 for (unsigned NBI = 0, NBE = NewBlocks.size(); NBI != NBE; ++NBI) {
1431 for (Instruction &I : *NewBlocks[NBI]) {
1432 RemapInstruction(&I, VMap,
1433 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1434 if (auto *II = dyn_cast<AssumeInst>(&I))
1435 AC->registerAssumption(II);
1439 // Rewrite the original preheader to select between versions of the loop.
1440 BranchInst *OldBR = cast<BranchInst>(LoopPreheader->getTerminator());
1441 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1442 "Preheader splitting did not work correctly!");
1444 if (MSSAU) {
1445 // Update MemorySSA after cloning, and before splitting to unreachables,
1446 // since that invalidates the 1:1 mapping of clones in VMap.
1447 LoopBlocksRPO LBRPO(L);
1448 LBRPO.perform(LI);
1449 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1452 // Emit the new branch that selects between the two versions of this loop.
1453 emitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1454 TI, ToDuplicate);
1455 if (MSSAU) {
1456 // Update MemoryPhis in Exit blocks.
1457 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1458 if (VerifyMemorySSA)
1459 MSSA->verifyMemorySSA();
1462 // The OldBr was replaced by a new one and removed (but not erased) by
1463 // emitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1464 delete OldBR;
1466 LoopProcessWorklist.push_back(NewLoop);
1467 RedoLoop = true;
1469 // Keep a WeakTrackingVH holding onto LIC. If the first call to
1470 // RewriteLoopBody
1471 // deletes the instruction (for example by simplifying a PHI that feeds into
1472 // the condition that we're unswitching on), we don't rewrite the second
1473 // iteration.
1474 WeakTrackingVH LICHandle(LIC);
1476 if (ToDuplicate.empty()) {
1477 // Now we rewrite the original code to know that the condition is true and
1478 // the new code to know that the condition is false.
1479 rewriteLoopBodyWithConditionConstant(L, LIC, Val, /*IsEqual=*/false);
1481 // It's possible that simplifying one loop could cause the other to be
1482 // changed to another value or a constant. If its a constant, don't
1483 // simplify it.
1484 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1485 LICHandle && !isa<Constant>(LICHandle))
1486 rewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
1487 /*IsEqual=*/true);
1488 } else {
1489 // Partial unswitching. Update the condition in the right loop with the
1490 // constant.
1491 auto *CC = cast<ConstantInt>(Val);
1492 if (CC->isOneValue()) {
1493 rewriteLoopBodyWithConditionConstant(NewLoop, VMap[LIC], Val,
1494 /*IsEqual=*/true);
1495 } else
1496 rewriteLoopBodyWithConditionConstant(L, LIC, Val, /*IsEqual=*/true);
1498 // Mark the new loop as partially unswitched, to avoid unswitching on the
1499 // same condition again.
1500 auto &Context = NewLoop->getHeader()->getContext();
1501 MDNode *DisableUnswitchMD = MDNode::get(
1502 Context, MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
1503 MDNode *NewLoopID = makePostTransformationMetadata(
1504 Context, L->getLoopID(), {"llvm.loop.unswitch.partial"},
1505 {DisableUnswitchMD});
1506 NewLoop->setLoopID(NewLoopID);
1509 if (MSSA && VerifyMemorySSA)
1510 MSSA->verifyMemorySSA();
1513 /// Remove all instances of I from the worklist vector specified.
1514 static void removeFromWorklist(Instruction *I,
1515 std::vector<Instruction *> &Worklist) {
1516 llvm::erase_value(Worklist, I);
1519 /// When we find that I really equals V, remove I from the
1520 /// program, replacing all uses with V and update the worklist.
1521 static void replaceUsesOfWith(Instruction *I, Value *V,
1522 std::vector<Instruction *> &Worklist, Loop *L,
1523 LPPassManager *LPM, MemorySSAUpdater *MSSAU) {
1524 LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
1526 // Add uses to the worklist, which may be dead now.
1527 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1528 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1529 Worklist.push_back(Use);
1531 // Add users to the worklist which may be simplified now.
1532 for (User *U : I->users())
1533 Worklist.push_back(cast<Instruction>(U));
1534 removeFromWorklist(I, Worklist);
1535 I->replaceAllUsesWith(V);
1536 if (!I->mayHaveSideEffects()) {
1537 if (MSSAU)
1538 MSSAU->removeMemoryAccess(I);
1539 I->eraseFromParent();
1541 ++NumSimplify;
1544 /// We know either that the value LIC has the value specified by Val in the
1545 /// specified loop, or we know it does NOT have that value.
1546 /// Rewrite any uses of LIC or of properties correlated to it.
1547 void LoopUnswitch::rewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1548 Constant *Val,
1549 bool IsEqual) {
1550 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1552 // FIXME: Support correlated properties, like:
1553 // for (...)
1554 // if (li1 < li2)
1555 // ...
1556 // if (li1 > li2)
1557 // ...
1559 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1560 // selects, switches.
1561 std::vector<Instruction*> Worklist;
1562 LLVMContext &Context = Val->getContext();
1564 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1565 // in the loop with the appropriate one directly.
1566 if (IsEqual || (isa<ConstantInt>(Val) &&
1567 Val->getType()->isIntegerTy(1))) {
1568 Value *Replacement;
1569 if (IsEqual)
1570 Replacement = Val;
1571 else
1572 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1573 !cast<ConstantInt>(Val)->getZExtValue());
1575 for (User *U : LIC->users()) {
1576 Instruction *UI = dyn_cast<Instruction>(U);
1577 if (!UI || !L->contains(UI))
1578 continue;
1579 Worklist.push_back(UI);
1582 for (Instruction *UI : Worklist)
1583 UI->replaceUsesOfWith(LIC, Replacement);
1585 simplifyCode(Worklist, L);
1586 return;
1589 // Otherwise, we don't know the precise value of LIC, but we do know that it
1590 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1591 // can. This case occurs when we unswitch switch statements.
1592 for (User *U : LIC->users()) {
1593 Instruction *UI = dyn_cast<Instruction>(U);
1594 if (!UI || !L->contains(UI))
1595 continue;
1597 // At this point, we know LIC is definitely not Val. Try to use some simple
1598 // logic to simplify the user w.r.t. to the context.
1599 if (Value *Replacement = simplifyInstructionWithNotEqual(UI, LIC, Val)) {
1600 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1601 // This in-loop instruction has been simplified w.r.t. its context,
1602 // i.e. LIC != Val, make sure we propagate its replacement value to
1603 // all its users.
1605 // We can not yet delete UI, the LIC user, yet, because that would invalidate
1606 // the LIC->users() iterator !. However, we can make this instruction
1607 // dead by replacing all its users and push it onto the worklist so that
1608 // it can be properly deleted and its operands simplified.
1609 UI->replaceAllUsesWith(Replacement);
1613 // This is a LIC user, push it into the worklist so that simplifyCode can
1614 // attempt to simplify it.
1615 Worklist.push_back(UI);
1617 // If we know that LIC is not Val, use this info to simplify code.
1618 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1619 if (!SI || !isa<ConstantInt>(Val)) continue;
1621 // NOTE: if a case value for the switch is unswitched out, we record it
1622 // after the unswitch finishes. We can not record it here as the switch
1623 // is not a direct user of the partial LIV.
1624 SwitchInst::CaseHandle DeadCase =
1625 *SI->findCaseValue(cast<ConstantInt>(Val));
1626 // Default case is live for multiple values.
1627 if (DeadCase == *SI->case_default())
1628 continue;
1630 // Found a dead case value. Don't remove PHI nodes in the
1631 // successor if they become single-entry, those PHI nodes may
1632 // be in the Users list.
1634 BasicBlock *Switch = SI->getParent();
1635 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1636 BasicBlock *Latch = L->getLoopLatch();
1638 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1639 // If the DeadCase successor dominates the loop latch, then the
1640 // transformation isn't safe since it will delete the sole predecessor edge
1641 // to the latch.
1642 if (Latch && DT->dominates(SISucc, Latch))
1643 continue;
1645 // FIXME: This is a hack. We need to keep the successor around
1646 // and hooked up so as to preserve the loop structure, because
1647 // trying to update it is complicated. So instead we preserve the
1648 // loop structure and put the block on a dead code path.
1649 SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1650 // Compute the successors instead of relying on the return value
1651 // of SplitEdge, since it may have split the switch successor
1652 // after PHI nodes.
1653 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1654 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1655 // Create an "unreachable" destination.
1656 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1657 Switch->getParent(),
1658 OldSISucc);
1659 new UnreachableInst(Context, Abort);
1660 // Force the new case destination to branch to the "unreachable"
1661 // block while maintaining a (dead) CFG edge to the old block.
1662 NewSISucc->getTerminator()->eraseFromParent();
1663 BranchInst::Create(Abort, OldSISucc,
1664 ConstantInt::getTrue(Context), NewSISucc);
1665 // Release the PHI operands for this edge.
1666 for (PHINode &PN : NewSISucc->phis())
1667 PN.setIncomingValueForBlock(Switch, UndefValue::get(PN.getType()));
1668 // Tell the domtree about the new block. We don't fully update the
1669 // domtree here -- instead we force it to do a full recomputation
1670 // after the pass is complete -- but we do need to inform it of
1671 // new blocks.
1672 DT->addNewBlock(Abort, NewSISucc);
1675 simplifyCode(Worklist, L);
1678 /// Now that we have simplified some instructions in the loop, walk over it and
1679 /// constant prop, dce, and fold control flow where possible. Note that this is
1680 /// effectively a very simple loop-structure-aware optimizer. During processing
1681 /// of this loop, L could very well be deleted, so it must not be used.
1683 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1684 /// pass.
1686 void LoopUnswitch::simplifyCode(std::vector<Instruction *> &Worklist, Loop *L) {
1687 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1688 while (!Worklist.empty()) {
1689 Instruction *I = Worklist.back();
1690 Worklist.pop_back();
1692 // Simple DCE.
1693 if (isInstructionTriviallyDead(I)) {
1694 LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
1696 // Add uses to the worklist, which may be dead now.
1697 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1698 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1699 Worklist.push_back(Use);
1700 removeFromWorklist(I, Worklist);
1701 if (MSSAU)
1702 MSSAU->removeMemoryAccess(I);
1703 I->eraseFromParent();
1704 ++NumSimplify;
1705 continue;
1708 // See if instruction simplification can hack this up. This is common for
1709 // things like "select false, X, Y" after unswitching made the condition be
1710 // 'false'. TODO: update the domtree properly so we can pass it here.
1711 if (Value *V = SimplifyInstruction(I, DL))
1712 if (LI->replacementPreservesLCSSAForm(I, V)) {
1713 replaceUsesOfWith(I, V, Worklist, L, LPM, MSSAU.get());
1714 continue;
1717 // Special case hacks that appear commonly in unswitched code.
1718 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1719 if (BI->isUnconditional()) {
1720 // If BI's parent is the only pred of the successor, fold the two blocks
1721 // together.
1722 BasicBlock *Pred = BI->getParent();
1723 (void)Pred;
1724 BasicBlock *Succ = BI->getSuccessor(0);
1725 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1726 if (!SinglePred) continue; // Nothing to do.
1727 assert(SinglePred == Pred && "CFG broken");
1729 // Make the LPM and Worklist updates specific to LoopUnswitch.
1730 removeFromWorklist(BI, Worklist);
1731 auto SuccIt = Succ->begin();
1732 while (PHINode *PN = dyn_cast<PHINode>(SuccIt++)) {
1733 for (unsigned It = 0, E = PN->getNumOperands(); It != E; ++It)
1734 if (Instruction *Use = dyn_cast<Instruction>(PN->getOperand(It)))
1735 Worklist.push_back(Use);
1736 for (User *U : PN->users())
1737 Worklist.push_back(cast<Instruction>(U));
1738 removeFromWorklist(PN, Worklist);
1739 ++NumSimplify;
1741 // Merge the block and make the remaining analyses updates.
1742 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1743 MergeBlockIntoPredecessor(Succ, &DTU, LI, MSSAU.get());
1744 ++NumSimplify;
1745 continue;
1748 continue;
1753 /// Simple simplifications we can do given the information that Cond is
1754 /// definitely not equal to Val.
1755 Value *LoopUnswitch::simplifyInstructionWithNotEqual(Instruction *Inst,
1756 Value *Invariant,
1757 Constant *Val) {
1758 // icmp eq cond, val -> false
1759 ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1760 if (CI && CI->isEquality()) {
1761 Value *Op0 = CI->getOperand(0);
1762 Value *Op1 = CI->getOperand(1);
1763 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1764 LLVMContext &Ctx = Inst->getContext();
1765 if (CI->getPredicate() == CmpInst::ICMP_EQ)
1766 return ConstantInt::getFalse(Ctx);
1767 else
1768 return ConstantInt::getTrue(Ctx);
1772 // FIXME: there may be other opportunities, e.g. comparison with floating
1773 // point, or Invariant - Val != 0, etc.
1774 return nullptr;