LLVM  10.0.0
LoopUnswitch.cpp
Go to the documentation of this file.
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:
11 //
12 // for (...) if (lic)
13 // A for (...)
14 // if (lic) A; B; C
15 // B else
16 // C for (...)
17 // A; C
18 //
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.
22 //
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.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/LoopPass.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/BasicBlock.h"
45 #include "llvm/IR/CallSite.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DerivedTypes.h"
49 #include "llvm/IR/Dominators.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/IRBuilder.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/User.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/InitializePasses.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/Debug.h"
68 #include "llvm/Transforms/Scalar.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <map>
78 #include <set>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "loop-unswitch"
86 
87 STATISTIC(NumBranches, "Number of branches unswitched");
88 STATISTIC(NumSwitches, "Number of switches unswitched");
89 STATISTIC(NumGuards, "Number of guards unswitched");
90 STATISTIC(NumSelects , "Number of selects unswitched");
91 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
92 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
93 STATISTIC(TotalInsts, "Total number of instructions analyzed");
94 
95 // The specific value of 100 here was chosen based only on intuition and a
96 // few specific examples.
97 static cl::opt<unsigned>
98 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
99  cl::init(100), cl::Hidden);
100 
101 namespace {
102 
103  class LUAnalysisCache {
104  using UnswitchedValsMap =
106  using UnswitchedValsIt = UnswitchedValsMap::iterator;
107 
108  struct LoopProperties {
109  unsigned CanBeUnswitchedCount;
110  unsigned WasUnswitchedCount;
111  unsigned SizeEstimation;
112  UnswitchedValsMap UnswitchedVals;
113  };
114 
115  // Here we use std::map instead of DenseMap, since we need to keep valid
116  // LoopProperties pointer for current loop for better performance.
117  using LoopPropsMap = std::map<const Loop *, LoopProperties>;
118  using LoopPropsMapIt = LoopPropsMap::iterator;
119 
120  LoopPropsMap LoopsProperties;
121  UnswitchedValsMap *CurLoopInstructions = nullptr;
122  LoopProperties *CurrentLoopProperties = nullptr;
123 
124  // A loop unswitching with an estimated cost above this threshold
125  // is not performed. MaxSize is turned into unswitching quota for
126  // the current loop, and reduced correspondingly, though note that
127  // the quota is returned by releaseMemory() when the loop has been
128  // processed, so that MaxSize will return to its previous
129  // value. So in most cases MaxSize will equal the Threshold flag
130  // when a new loop is processed. An exception to that is that
131  // MaxSize will have a smaller value while processing nested loops
132  // that were introduced due to loop unswitching of an outer loop.
133  //
134  // FIXME: The way that MaxSize works is subtle and depends on the
135  // pass manager processing loops and calling releaseMemory() in a
136  // specific order. It would be good to find a more straightforward
137  // way of doing what MaxSize does.
138  unsigned MaxSize;
139 
140  public:
141  LUAnalysisCache() : MaxSize(Threshold) {}
142 
143  // Analyze loop. Check its size, calculate is it possible to unswitch
144  // it. Returns true if we can unswitch this loop.
145  bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
146  AssumptionCache *AC);
147 
148  // Clean all data related to given loop.
149  void forgetLoop(const Loop *L);
150 
151  // Mark case value as unswitched.
152  // Since SI instruction can be partly unswitched, in order to avoid
153  // extra unswitching in cloned loops keep track all unswitched values.
154  void setUnswitched(const SwitchInst *SI, const Value *V);
155 
156  // Check was this case value unswitched before or not.
157  bool isUnswitched(const SwitchInst *SI, const Value *V);
158 
159  // Returns true if another unswitching could be done within the cost
160  // threshold.
161  bool CostAllowsUnswitching();
162 
163  // Clone all loop-unswitch related loop properties.
164  // Redistribute unswitching quotas.
165  // Note, that new loop data is stored inside the VMap.
166  void cloneData(const Loop *NewLoop, const Loop *OldLoop,
167  const ValueToValueMapTy &VMap);
168  };
169 
170  class LoopUnswitch : public LoopPass {
171  LoopInfo *LI; // Loop information
172  LPPassManager *LPM;
173  AssumptionCache *AC;
174 
175  // Used to check if second loop needs processing after
176  // RewriteLoopBodyWithConditionConstant rewrites first loop.
177  std::vector<Loop*> LoopProcessWorklist;
178 
179  LUAnalysisCache BranchesInfo;
180 
181  bool OptimizeForSize;
182  bool redoLoop = false;
183 
184  Loop *currentLoop = nullptr;
185  DominatorTree *DT = nullptr;
186  MemorySSA *MSSA = nullptr;
187  std::unique_ptr<MemorySSAUpdater> MSSAU;
188  BasicBlock *loopHeader = nullptr;
189  BasicBlock *loopPreheader = nullptr;
190 
191  bool SanitizeMemory;
192  SimpleLoopSafetyInfo SafetyInfo;
193 
194  // LoopBlocks contains all of the basic blocks of the loop, including the
195  // preheader of the loop, the body of the loop, and the exit blocks of the
196  // loop, in that order.
197  std::vector<BasicBlock*> LoopBlocks;
198  // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
199  std::vector<BasicBlock*> NewBlocks;
200 
201  bool hasBranchDivergence;
202 
203  public:
204  static char ID; // Pass ID, replacement for typeid
205 
206  explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false)
207  : LoopPass(ID), OptimizeForSize(Os),
208  hasBranchDivergence(hasBranchDivergence) {
210  }
211 
212  bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213  bool processCurrentLoop();
214  bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
215 
216  /// This transformation requires natural loop information & requires that
217  /// loop preheaders be inserted into the CFG.
218  ///
219  void getAnalysisUsage(AnalysisUsage &AU) const override {
225  }
226  if (hasBranchDivergence)
229  }
230 
231  private:
232  void releaseMemory() override {
233  BranchesInfo.forgetLoop(currentLoop);
234  }
235 
236  void initLoopData() {
237  loopHeader = currentLoop->getHeader();
238  loopPreheader = currentLoop->getLoopPreheader();
239  }
240 
241  /// Split all of the edges from inside the loop to their exit blocks.
242  /// Update the appropriate Phi nodes as we do so.
243  void SplitExitEdges(Loop *L,
244  const SmallVectorImpl<BasicBlock *> &ExitBlocks);
245 
246  bool TryTrivialLoopUnswitch(bool &Changed);
247 
248  bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
249  Instruction *TI = nullptr);
250  void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
251  BasicBlock *ExitBlock, Instruction *TI);
252  void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
253  Instruction *TI);
254 
255  void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
256  Constant *Val, bool isEqual);
257 
258  void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
259  BasicBlock *TrueDest,
260  BasicBlock *FalseDest,
261  BranchInst *OldBranch, Instruction *TI);
262 
263  void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
264 
265  /// Given that the Invariant is not equal to Val. Simplify instructions
266  /// in the loop.
267  Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
268  Constant *Val);
269  };
270 
271 } // end anonymous namespace
272 
273 // Analyze loop. Check its size, calculate is it possible to unswitch
274 // it. Returns true if we can unswitch this loop.
275 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
276  AssumptionCache *AC) {
277  LoopPropsMapIt PropsIt;
278  bool Inserted;
279  std::tie(PropsIt, Inserted) =
280  LoopsProperties.insert(std::make_pair(L, LoopProperties()));
281 
282  LoopProperties &Props = PropsIt->second;
283 
284  if (Inserted) {
285  // New loop.
286 
287  // Limit the number of instructions to avoid causing significant code
288  // expansion, and the number of basic blocks, to avoid loops with
289  // large numbers of branches which cause loop unswitching to go crazy.
290  // This is a very ad-hoc heuristic.
291 
293  CodeMetrics::collectEphemeralValues(L, AC, EphValues);
294 
295  // FIXME: This is overly conservative because it does not take into
296  // consideration code simplification opportunities and code that can
297  // be shared by the resultant unswitched loops.
299  for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
300  ++I)
301  Metrics.analyzeBasicBlock(*I, TTI, EphValues);
302 
303  Props.SizeEstimation = Metrics.NumInsts;
304  Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
305  Props.WasUnswitchedCount = 0;
306  MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
307 
308  if (Metrics.notDuplicatable) {
309  LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
310  << ", contents cannot be "
311  << "duplicated!\n");
312  return false;
313  }
314  }
315 
316  // Be careful. This links are good only before new loop addition.
317  CurrentLoopProperties = &Props;
318  CurLoopInstructions = &Props.UnswitchedVals;
319 
320  return true;
321 }
322 
323 // Clean all data related to given loop.
324 void LUAnalysisCache::forgetLoop(const Loop *L) {
325  LoopPropsMapIt LIt = LoopsProperties.find(L);
326 
327  if (LIt != LoopsProperties.end()) {
328  LoopProperties &Props = LIt->second;
329  MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
330  Props.SizeEstimation;
331  LoopsProperties.erase(LIt);
332  }
333 
334  CurrentLoopProperties = nullptr;
335  CurLoopInstructions = nullptr;
336 }
337 
338 // Mark case value as unswitched.
339 // Since SI instruction can be partly unswitched, in order to avoid
340 // extra unswitching in cloned loops keep track all unswitched values.
341 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
342  (*CurLoopInstructions)[SI].insert(V);
343 }
344 
345 // Check was this case value unswitched before or not.
346 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
347  return (*CurLoopInstructions)[SI].count(V);
348 }
349 
350 bool LUAnalysisCache::CostAllowsUnswitching() {
351  return CurrentLoopProperties->CanBeUnswitchedCount > 0;
352 }
353 
354 // Clone all loop-unswitch related loop properties.
355 // Redistribute unswitching quotas.
356 // Note, that new loop data is stored inside the VMap.
357 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
358  const ValueToValueMapTy &VMap) {
359  LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360  LoopProperties &OldLoopProps = *CurrentLoopProperties;
361  UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
362 
363  // Reallocate "can-be-unswitched quota"
364 
365  --OldLoopProps.CanBeUnswitchedCount;
366  ++OldLoopProps.WasUnswitchedCount;
367  NewLoopProps.WasUnswitchedCount = 0;
368  unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369  NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370  OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
371 
372  NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
373 
374  // Clone unswitched values info:
375  // for new loop switches we clone info about values that was
376  // already unswitched and has redundant successors.
377  for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
378  const SwitchInst *OldInst = I->first;
379  Value *NewI = VMap.lookup(OldInst);
380  const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
381  assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
382 
383  NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
384  }
385 }
386 
387 char LoopUnswitch::ID = 0;
388 
389 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
390  false, false)
396 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
397  false, false)
398 
399 Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
400  return new LoopUnswitch(Os, hasBranchDivergence);
401 }
402 
403 /// Operator chain lattice.
405  OC_OpChainNone, ///< There is no operator.
406  OC_OpChainOr, ///< There are only ORs.
407  OC_OpChainAnd, ///< There are only ANDs.
408  OC_OpChainMixed ///< There are ANDs and ORs.
409 };
410 
411 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
412 /// an invariant piece, return the invariant. Otherwise, return null.
413 //
414 /// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
415 /// mixed operator chain, as we can not reliably find a value which will simplify
416 /// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
417 /// to simplify the chain.
418 ///
419 /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
420 /// simplify the condition itself to a loop variant condition, but at the
421 /// cost of creating an entirely new loop.
422 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
423  OperatorChain &ParentChain,
425  MemorySSAUpdater *MSSAU) {
426  auto CacheIt = Cache.find(Cond);
427  if (CacheIt != Cache.end())
428  return CacheIt->second;
429 
430  // We started analyze new instruction, increment scanned instructions counter.
431  ++TotalInsts;
432 
433  // We can never unswitch on vector conditions.
434  if (Cond->getType()->isVectorTy())
435  return nullptr;
436 
437  // Constants should be folded, not unswitched on!
438  if (isa<Constant>(Cond)) return nullptr;
439 
440  // TODO: Handle: br (VARIANT|INVARIANT).
441 
442  // Hoist simple values out.
443  if (L->makeLoopInvariant(Cond, Changed, nullptr, MSSAU)) {
444  Cache[Cond] = Cond;
445  return Cond;
446  }
447 
448  // Walk up the operator chain to find partial invariant conditions.
449  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
450  if (BO->getOpcode() == Instruction::And ||
451  BO->getOpcode() == Instruction::Or) {
452  // Given the previous operator, compute the current operator chain status.
453  OperatorChain NewChain;
454  switch (ParentChain) {
455  case OC_OpChainNone:
456  NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
457  OC_OpChainOr;
458  break;
459  case OC_OpChainOr:
460  NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
462  break;
463  case OC_OpChainAnd:
464  NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
466  break;
467  case OC_OpChainMixed:
468  NewChain = OC_OpChainMixed;
469  break;
470  }
471 
472  // If we reach a Mixed state, we do not want to keep walking up as we can not
473  // reliably find a value that will simplify the chain. With this check, we
474  // will return null on the first sight of mixed chain and the caller will
475  // either backtrack to find partial LIV in other operand or return null.
476  if (NewChain != OC_OpChainMixed) {
477  // Update the current operator chain type before we search up the chain.
478  ParentChain = NewChain;
479  // If either the left or right side is invariant, we can unswitch on this,
480  // which will cause the branch to go away in one loop and the condition to
481  // simplify in the other one.
482  if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
483  ParentChain, Cache, MSSAU)) {
484  Cache[Cond] = LHS;
485  return LHS;
486  }
487  // We did not manage to find a partial LIV in operand(0). Backtrack and try
488  // operand(1).
489  ParentChain = NewChain;
490  if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
491  ParentChain, Cache, MSSAU)) {
492  Cache[Cond] = RHS;
493  return RHS;
494  }
495  }
496  }
497 
498  Cache[Cond] = nullptr;
499  return nullptr;
500 }
501 
502 /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
503 /// an invariant piece, return the invariant along with the operator chain type.
504 /// Otherwise, return null.
505 static std::pair<Value *, OperatorChain>
506 FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
507  MemorySSAUpdater *MSSAU) {
509  OperatorChain OpChain = OC_OpChainNone;
510  Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache, MSSAU);
511 
512  // In case we do find a LIV, it can not be obtained by walking up a mixed
513  // operator chain.
514  assert((!FCond || OpChain != OC_OpChainMixed) &&
515  "Do not expect a partial LIV with mixed operator chain");
516  return {FCond, OpChain};
517 }
518 
519 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
520  if (skipLoop(L))
521  return false;
522 
523  AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
524  *L->getHeader()->getParent());
525  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
526  LPM = &LPM_Ref;
527  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
529  MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
530  MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
531  assert(DT && "Cannot update MemorySSA without a valid DomTree.");
532  }
533  currentLoop = L;
534  Function *F = currentLoop->getHeader()->getParent();
535 
536  SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
537  if (SanitizeMemory)
538  SafetyInfo.computeLoopSafetyInfo(L);
539 
540  if (MSSA && VerifyMemorySSA)
541  MSSA->verifyMemorySSA();
542 
543  bool Changed = false;
544  do {
545  assert(currentLoop->isLCSSAForm(*DT));
546  if (MSSA && VerifyMemorySSA)
547  MSSA->verifyMemorySSA();
548  redoLoop = false;
549  Changed |= processCurrentLoop();
550  } while(redoLoop);
551 
552  if (MSSA && VerifyMemorySSA)
553  MSSA->verifyMemorySSA();
554 
555  return Changed;
556 }
557 
558 // Return true if the BasicBlock BB is unreachable from the loop header.
559 // Return false, otherwise.
560 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
561  auto *Node = DT->getNode(BB)->getIDom();
562  BasicBlock *DomBB = Node->getBlock();
563  while (currentLoop->contains(DomBB)) {
564  BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
565 
566  Node = DT->getNode(DomBB)->getIDom();
567  DomBB = Node->getBlock();
568 
569  if (!BInst || !BInst->isConditional())
570  continue;
571 
572  Value *Cond = BInst->getCondition();
573  if (!isa<ConstantInt>(Cond))
574  continue;
575 
576  BasicBlock *UnreachableSucc =
577  Cond == ConstantInt::getTrue(Cond->getContext())
578  ? BInst->getSuccessor(1)
579  : BInst->getSuccessor(0);
580 
581  if (DT->dominates(UnreachableSucc, BB))
582  return true;
583  }
584  return false;
585 }
586 
587 /// FIXME: Remove this workaround when freeze related patches are done.
588 /// LoopUnswitch and Equality propagation in GVN have discrepancy about
589 /// whether branch on undef/poison has undefine behavior. Here it is to
590 /// rule out some common cases that we found such discrepancy already
591 /// causing problems. Detail could be found in PR31652. Note if the
592 /// func returns true, it is unsafe. But if it is false, it doesn't mean
593 /// it is necessarily safe.
594 static bool EqualityPropUnSafe(Value &LoopCond) {
595  ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
596  if (!CI || !CI->isEquality())
597  return false;
598 
599  Value *LHS = CI->getOperand(0);
600  Value *RHS = CI->getOperand(1);
601  if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
602  return true;
603 
604  auto hasUndefInPHI = [](PHINode &PN) {
605  for (Value *Opd : PN.incoming_values()) {
606  if (isa<UndefValue>(Opd))
607  return true;
608  }
609  return false;
610  };
611  PHINode *LPHI = dyn_cast<PHINode>(LHS);
612  PHINode *RPHI = dyn_cast<PHINode>(RHS);
613  if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
614  return true;
615 
616  auto hasUndefInSelect = [](SelectInst &SI) {
617  if (isa<UndefValue>(SI.getTrueValue()) ||
618  isa<UndefValue>(SI.getFalseValue()))
619  return true;
620  return false;
621  };
622  SelectInst *LSI = dyn_cast<SelectInst>(LHS);
623  SelectInst *RSI = dyn_cast<SelectInst>(RHS);
624  if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
625  return true;
626  return false;
627 }
628 
629 /// Do actual work and unswitch loop if possible and profitable.
630 bool LoopUnswitch::processCurrentLoop() {
631  bool Changed = false;
632 
633  initLoopData();
634 
635  // If LoopSimplify was unable to form a preheader, don't do any unswitching.
636  if (!loopPreheader)
637  return false;
638 
639  // Loops with indirectbr cannot be cloned.
640  if (!currentLoop->isSafeToClone())
641  return false;
642 
643  // Without dedicated exits, splitting the exit edge may fail.
644  if (!currentLoop->hasDedicatedExits())
645  return false;
646 
647  LLVMContext &Context = loopHeader->getContext();
648 
649  // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
650  if (!BranchesInfo.countLoop(
651  currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
652  *currentLoop->getHeader()->getParent()),
653  AC))
654  return false;
655 
656  // Try trivial unswitch first before loop over other basic blocks in the loop.
657  if (TryTrivialLoopUnswitch(Changed)) {
658  return true;
659  }
660 
661  // Do not do non-trivial unswitch while optimizing for size.
662  // FIXME: Use Function::hasOptSize().
663  if (OptimizeForSize ||
664  loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
665  return false;
666 
667  // Run through the instructions in the loop, keeping track of three things:
668  //
669  // - That we do not unswitch loops containing convergent operations, as we
670  // might be making them control dependent on the unswitch value when they
671  // were not before.
672  // FIXME: This could be refined to only bail if the convergent operation is
673  // not already control-dependent on the unswitch value.
674  //
675  // - That basic blocks in the loop contain invokes whose predecessor edges we
676  // cannot split.
677  //
678  // - The set of guard intrinsics encountered (these are non terminator
679  // instructions that are also profitable to be unswitched).
680 
682 
683  for (const auto BB : currentLoop->blocks()) {
684  for (auto &I : *BB) {
685  auto CS = CallSite(&I);
686  if (!CS) continue;
687  if (CS.isConvergent())
688  return false;
689  if (auto *II = dyn_cast<InvokeInst>(&I))
690  if (!II->getUnwindDest()->canSplitPredecessors())
691  return false;
692  if (auto *II = dyn_cast<IntrinsicInst>(&I))
693  if (II->getIntrinsicID() == Intrinsic::experimental_guard)
694  Guards.push_back(II);
695  }
696  }
697 
698  for (IntrinsicInst *Guard : Guards) {
699  Value *LoopCond = FindLIVLoopCondition(Guard->getOperand(0), currentLoop,
700  Changed, MSSAU.get())
701  .first;
702  if (LoopCond &&
703  UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
704  // NB! Unswitching (if successful) could have erased some of the
705  // instructions in Guards leaving dangling pointers there. This is fine
706  // because we're returning now, and won't look at Guards again.
707  ++NumGuards;
708  return true;
709  }
710  }
711 
712  // Loop over all of the basic blocks in the loop. If we find an interior
713  // block that is branching on a loop-invariant condition, we can unswitch this
714  // loop.
715  for (Loop::block_iterator I = currentLoop->block_begin(),
716  E = currentLoop->block_end(); I != E; ++I) {
717  Instruction *TI = (*I)->getTerminator();
718 
719  // Unswitching on a potentially uninitialized predicate is not
720  // MSan-friendly. Limit this to the cases when the original predicate is
721  // guaranteed to execute, to avoid creating a use-of-uninitialized-value
722  // in the code that did not have one.
723  // This is a workaround for the discrepancy between LLVM IR and MSan
724  // semantics. See PR28054 for more details.
725  if (SanitizeMemory &&
726  !SafetyInfo.isGuaranteedToExecute(*TI, DT, currentLoop))
727  continue;
728 
729  if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
730  // Some branches may be rendered unreachable because of previous
731  // unswitching.
732  // Unswitch only those branches that are reachable.
733  if (isUnreachableDueToPreviousUnswitching(*I))
734  continue;
735 
736  // If this isn't branching on an invariant condition, we can't unswitch
737  // it.
738  if (BI->isConditional()) {
739  // See if this, or some part of it, is loop invariant. If so, we can
740  // unswitch on it if we desire.
741  Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), currentLoop,
742  Changed, MSSAU.get())
743  .first;
744  if (LoopCond && !EqualityPropUnSafe(*LoopCond) &&
745  UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
746  ++NumBranches;
747  return true;
748  }
749  }
750  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
751  Value *SC = SI->getCondition();
752  Value *LoopCond;
753  OperatorChain OpChain;
754  std::tie(LoopCond, OpChain) =
755  FindLIVLoopCondition(SC, currentLoop, Changed, MSSAU.get());
756 
757  unsigned NumCases = SI->getNumCases();
758  if (LoopCond && NumCases) {
759  // Find a value to unswitch on:
760  // FIXME: this should chose the most expensive case!
761  // FIXME: scan for a case with a non-critical edge?
762  Constant *UnswitchVal = nullptr;
763  // Find a case value such that at least one case value is unswitched
764  // out.
765  if (OpChain == OC_OpChainAnd) {
766  // If the chain only has ANDs and the switch has a case value of 0.
767  // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
768  auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
769  if (BranchesInfo.isUnswitched(SI, AllZero))
770  continue;
771  // We are unswitching 0 out.
772  UnswitchVal = AllZero;
773  } else if (OpChain == OC_OpChainOr) {
774  // If the chain only has ORs and the switch has a case value of ~0.
775  // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
776  auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
777  if (BranchesInfo.isUnswitched(SI, AllOne))
778  continue;
779  // We are unswitching ~0 out.
780  UnswitchVal = AllOne;
781  } else {
782  assert(OpChain == OC_OpChainNone &&
783  "Expect to unswitch on trivial chain");
784  // Do not process same value again and again.
785  // At this point we have some cases already unswitched and
786  // some not yet unswitched. Let's find the first not yet unswitched one.
787  for (auto Case : SI->cases()) {
788  Constant *UnswitchValCandidate = Case.getCaseValue();
789  if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
790  UnswitchVal = UnswitchValCandidate;
791  break;
792  }
793  }
794  }
795 
796  if (!UnswitchVal)
797  continue;
798 
799  if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
800  ++NumSwitches;
801  // In case of a full LIV, UnswitchVal is the value we unswitched out.
802  // In case of a partial LIV, we only unswitch when its an AND-chain
803  // or OR-chain. In both cases switch input value simplifies to
804  // UnswitchVal.
805  BranchesInfo.setUnswitched(SI, UnswitchVal);
806  return true;
807  }
808  }
809  }
810 
811  // Scan the instructions to check for unswitchable values.
812  for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
813  BBI != E; ++BBI)
814  if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
815  Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), currentLoop,
816  Changed, MSSAU.get())
817  .first;
818  if (LoopCond && UnswitchIfProfitable(LoopCond,
819  ConstantInt::getTrue(Context))) {
820  ++NumSelects;
821  return true;
822  }
823  }
824  }
825  return Changed;
826 }
827 
828 /// Check to see if all paths from BB exit the loop with no side effects
829 /// (including infinite loops).
830 ///
831 /// If true, we return true and set ExitBB to the block we
832 /// exit through.
833 ///
835  BasicBlock *&ExitBB,
836  std::set<BasicBlock*> &Visited) {
837  if (!Visited.insert(BB).second) {
838  // Already visited. Without more analysis, this could indicate an infinite
839  // loop.
840  return false;
841  }
842  if (!L->contains(BB)) {
843  // Otherwise, this is a loop exit, this is fine so long as this is the
844  // first exit.
845  if (ExitBB) return false;
846  ExitBB = BB;
847  return true;
848  }
849 
850  // Otherwise, this is an unvisited intra-loop node. Check all successors.
851  for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
852  // Check to see if the successor is a trivial loop exit.
853  if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
854  return false;
855  }
856 
857  // Okay, everything after this looks good, check to make sure that this block
858  // doesn't include any side effects.
859  for (Instruction &I : *BB)
860  if (I.mayHaveSideEffects())
861  return false;
862 
863  return true;
864 }
865 
866 /// Return true if the specified block unconditionally leads to an exit from
867 /// the specified loop, and has no side-effects in the process. If so, return
868 /// the block that is exited to, otherwise return null.
870  std::set<BasicBlock*> Visited;
871  Visited.insert(L->getHeader()); // Branches to header make infinite loops.
872  BasicBlock *ExitBB = nullptr;
873  if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
874  return ExitBB;
875  return nullptr;
876 }
877 
878 /// We have found that we can unswitch currentLoop when LoopCond == Val to
879 /// simplify the loop. If we decide that this is profitable,
880 /// unswitch the loop, reprocess the pieces, then return true.
881 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
882  Instruction *TI) {
883  // Check to see if it would be profitable to unswitch current loop.
884  if (!BranchesInfo.CostAllowsUnswitching()) {
885  LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
886  << currentLoop->getHeader()->getName()
887  << " at non-trivial condition '" << *Val
888  << "' == " << *LoopCond << "\n"
889  << ". Cost too high.\n");
890  return false;
891  }
892  if (hasBranchDivergence &&
893  getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
894  LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
895  << currentLoop->getHeader()->getName()
896  << " at non-trivial condition '" << *Val
897  << "' == " << *LoopCond << "\n"
898  << ". Condition is divergent.\n");
899  return false;
900  }
901 
902  UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
903  return true;
904 }
905 
906 /// Recursively clone the specified loop and all of its children,
907 /// mapping the blocks with the specified map.
909  LoopInfo *LI, LPPassManager *LPM) {
910  Loop &New = *LI->AllocateLoop();
911  if (PL)
912  PL->addChildLoop(&New);
913  else
914  LI->addTopLevelLoop(&New);
915  LPM->addLoop(New);
916 
917  // Add all of the blocks in L to the new loop.
918  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
919  I != E; ++I)
920  if (LI->getLoopFor(*I) == L)
921  New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
922 
923  // Add all of the subloops to the new loop.
924  for (Loop *I : *L)
925  CloneLoop(I, &New, VM, LI, LPM);
926 
927  return &New;
928 }
929 
930 /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
931 /// otherwise branch to FalseDest. Insert the code immediately before OldBranch
932 /// and remove (but not erase!) it from the function.
933 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
934  BasicBlock *TrueDest,
935  BasicBlock *FalseDest,
936  BranchInst *OldBranch,
937  Instruction *TI) {
938  assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
939  assert(TrueDest != FalseDest && "Branch targets should be different");
940  // Insert a conditional branch on LIC to the two preheaders. The original
941  // code is the true version and the new code is the false version.
942  Value *BranchVal = LIC;
943  bool Swapped = false;
944  if (!isa<ConstantInt>(Val) ||
945  Val->getType() != Type::getInt1Ty(LIC->getContext()))
946  BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
947  else if (Val != ConstantInt::getTrue(Val->getContext())) {
948  // We want to enter the new loop when the condition is true.
949  std::swap(TrueDest, FalseDest);
950  Swapped = true;
951  }
952 
953  // Old branch will be removed, so save its parent and successor to update the
954  // DomTree.
955  auto *OldBranchSucc = OldBranch->getSuccessor(0);
956  auto *OldBranchParent = OldBranch->getParent();
957 
958  // Insert the new branch.
959  BranchInst *BI =
960  IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
961  if (Swapped)
962  BI->swapProfMetadata();
963 
964  // Remove the old branch so there is only one branch at the end. This is
965  // needed to perform DomTree's internal DFS walk on the function's CFG.
966  OldBranch->removeFromParent();
967 
968  // Inform the DT about the new branch.
969  if (DT) {
970  // First, add both successors.
972  if (TrueDest != OldBranchSucc)
973  Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
974  if (FalseDest != OldBranchSucc)
975  Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
976  // If both of the new successors are different from the old one, inform the
977  // DT that the edge was deleted.
978  if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
979  Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
980  }
981  DT->applyUpdates(Updates);
982 
983  if (MSSAU)
984  MSSAU->applyUpdates(Updates, *DT);
985  }
986 
987  // If either edge is critical, split it. This helps preserve LoopSimplify
988  // form for enclosing loops.
989  auto Options =
990  CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
991  SplitCriticalEdge(BI, 0, Options);
992  SplitCriticalEdge(BI, 1, Options);
993 }
994 
995 /// Given a loop that has a trivial unswitchable condition in it (a cond branch
996 /// from its header block to its latch block, where the path through the loop
997 /// that doesn't execute its body has no side-effects), unswitch it. This
998 /// doesn't involve any code duplication, just moving the conditional branch
999 /// outside of the loop and updating loop info.
1000 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
1001  BasicBlock *ExitBlock,
1002  Instruction *TI) {
1003  LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
1004  << loopHeader->getName() << " [" << L->getBlocks().size()
1005  << " blocks] in Function "
1006  << L->getHeader()->getParent()->getName()
1007  << " on cond: " << *Val << " == " << *Cond << "\n");
1008  // We are going to make essential changes to CFG. This may invalidate cached
1009  // information for L or one of its parent loops in SCEV.
1010  if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1011  SEWP->getSE().forgetTopmostLoop(L);
1012 
1013  // First step, split the preheader, so that we know that there is a safe place
1014  // to insert the conditional branch. We will change loopPreheader to have a
1015  // conditional branch on Cond.
1016  BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1017 
1018  // Now that we have a place to insert the conditional branch, create a place
1019  // to branch to: this is the exit block out of the loop that we should
1020  // short-circuit to.
1021 
1022  // Split this block now, so that the loop maintains its exit block, and so
1023  // that the jump from the preheader can execute the contents of the exit block
1024  // without actually branching to it (the exit block should be dominated by the
1025  // loop header, not the preheader).
1026  assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
1027  BasicBlock *NewExit =
1028  SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
1029 
1030  // Okay, now we have a position to branch from and a position to branch to,
1031  // insert the new conditional branch.
1032  auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
1033  assert(OldBranch && "Failed to split the preheader");
1034  EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1035  LPM->deleteSimpleAnalysisValue(OldBranch, L);
1036 
1037  // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
1038  // Delete it, as it is no longer needed.
1039  delete OldBranch;
1040 
1041  // We need to reprocess this loop, it could be unswitched again.
1042  redoLoop = true;
1043 
1044  // Now that we know that the loop is never entered when this condition is a
1045  // particular value, rewrite the loop with this info. We know that this will
1046  // at least eliminate the old branch.
1047  RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
1048 
1049  ++NumTrivial;
1050 }
1051 
1052 /// Check if the first non-constant condition starting from the loop header is
1053 /// a trivial unswitch condition: that is, a condition controls whether or not
1054 /// the loop does anything at all. If it is a trivial condition, unswitching
1055 /// produces no code duplications (equivalently, it produces a simpler loop and
1056 /// a new empty loop, which gets deleted). Therefore always unswitch trivial
1057 /// condition.
1058 bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
1059  BasicBlock *CurrentBB = currentLoop->getHeader();
1060  Instruction *CurrentTerm = CurrentBB->getTerminator();
1061  LLVMContext &Context = CurrentBB->getContext();
1062 
1063  // If loop header has only one reachable successor (currently via an
1064  // unconditional branch or constant foldable conditional branch, but
1065  // should also consider adding constant foldable switch instruction in
1066  // future), we should keep looking for trivial condition candidates in
1067  // the successor as well. An alternative is to constant fold conditions
1068  // and merge successors into loop header (then we only need to check header's
1069  // terminator). The reason for not doing this in LoopUnswitch pass is that
1070  // it could potentially break LoopPassManager's invariants. Folding dead
1071  // branches could either eliminate the current loop or make other loops
1072  // unreachable. LCSSA form might also not be preserved after deleting
1073  // branches. The following code keeps traversing loop header's successors
1074  // until it finds the trivial condition candidate (condition that is not a
1075  // constant). Since unswitching generates branches with constant conditions,
1076  // this scenario could be very common in practice.
1078 
1079  while (true) {
1080  // If we exit loop or reach a previous visited block, then
1081  // we can not reach any trivial condition candidates (unfoldable
1082  // branch instructions or switch instructions) and no unswitch
1083  // can happen. Exit and return false.
1084  if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
1085  return false;
1086 
1087  // Check if this loop will execute any side-effecting instructions (e.g.
1088  // stores, calls, volatile loads) in the part of the loop that the code
1089  // *would* execute. Check the header first.
1090  for (Instruction &I : *CurrentBB)
1091  if (I.mayHaveSideEffects())
1092  return false;
1093 
1094  if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1095  if (BI->isUnconditional()) {
1096  CurrentBB = BI->getSuccessor(0);
1097  } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
1098  CurrentBB = BI->getSuccessor(0);
1099  } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
1100  CurrentBB = BI->getSuccessor(1);
1101  } else {
1102  // Found a trivial condition candidate: non-foldable conditional branch.
1103  break;
1104  }
1105  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1106  // At this point, any constant-foldable instructions should have probably
1107  // been folded.
1108  ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
1109  if (!Cond)
1110  break;
1111  // Find the target block we are definitely going to.
1112  CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
1113  } else {
1114  // We do not understand these terminator instructions.
1115  break;
1116  }
1117 
1118  CurrentTerm = CurrentBB->getTerminator();
1119  }
1120 
1121  // CondVal is the condition that controls the trivial condition.
1122  // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
1123  Constant *CondVal = nullptr;
1124  BasicBlock *LoopExitBB = nullptr;
1125 
1126  if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1127  // If this isn't branching on an invariant condition, we can't unswitch it.
1128  if (!BI->isConditional())
1129  return false;
1130 
1131  Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), currentLoop,
1132  Changed, MSSAU.get())
1133  .first;
1134 
1135  // Unswitch only if the trivial condition itself is an LIV (not
1136  // partial LIV which could occur in and/or)
1137  if (!LoopCond || LoopCond != BI->getCondition())
1138  return false;
1139 
1140  // Check to see if a successor of the branch is guaranteed to
1141  // exit through a unique exit block without having any
1142  // side-effects. If so, determine the value of Cond that causes
1143  // it to do this.
1144  if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1145  BI->getSuccessor(0)))) {
1146  CondVal = ConstantInt::getTrue(Context);
1147  } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
1148  BI->getSuccessor(1)))) {
1149  CondVal = ConstantInt::getFalse(Context);
1150  }
1151 
1152  // If we didn't find a single unique LoopExit block, or if the loop exit
1153  // block contains phi nodes, this isn't trivial.
1154  if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1155  return false; // Can't handle this.
1156 
1157  if (EqualityPropUnSafe(*LoopCond))
1158  return false;
1159 
1160  UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1161  CurrentTerm);
1162  ++NumBranches;
1163  return true;
1164  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1165  // If this isn't switching on an invariant condition, we can't unswitch it.
1166  Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), currentLoop,
1167  Changed, MSSAU.get())
1168  .first;
1169 
1170  // Unswitch only if the trivial condition itself is an LIV (not
1171  // partial LIV which could occur in and/or)
1172  if (!LoopCond || LoopCond != SI->getCondition())
1173  return false;
1174 
1175  // Check to see if a successor of the switch is guaranteed to go to the
1176  // latch block or exit through a one exit block without having any
1177  // side-effects. If so, determine the value of Cond that causes it to do
1178  // this.
1179  // Note that we can't trivially unswitch on the default case or
1180  // on already unswitched cases.
1181  for (auto Case : SI->cases()) {
1182  BasicBlock *LoopExitCandidate;
1183  if ((LoopExitCandidate =
1184  isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
1185  // Okay, we found a trivial case, remember the value that is trivial.
1186  ConstantInt *CaseVal = Case.getCaseValue();
1187 
1188  // Check that it was not unswitched before, since already unswitched
1189  // trivial vals are looks trivial too.
1190  if (BranchesInfo.isUnswitched(SI, CaseVal))
1191  continue;
1192  LoopExitBB = LoopExitCandidate;
1193  CondVal = CaseVal;
1194  break;
1195  }
1196  }
1197 
1198  // If we didn't find a single unique LoopExit block, or if the loop exit
1199  // block contains phi nodes, this isn't trivial.
1200  if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
1201  return false; // Can't handle this.
1202 
1203  UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1204  nullptr);
1205 
1206  // We are only unswitching full LIV.
1207  BranchesInfo.setUnswitched(SI, CondVal);
1208  ++NumSwitches;
1209  return true;
1210  }
1211  return false;
1212 }
1213 
1214 /// Split all of the edges from inside the loop to their exit blocks.
1215 /// Update the appropriate Phi nodes as we do so.
1216 void LoopUnswitch::SplitExitEdges(Loop *L,
1217  const SmallVectorImpl<BasicBlock *> &ExitBlocks){
1218 
1219  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1220  BasicBlock *ExitBlock = ExitBlocks[i];
1221  SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1222  pred_end(ExitBlock));
1223 
1224  // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1225  // general, if we call it on all predecessors of all exits then it does.
1226  SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
1227  /*PreserveLCSSA*/ true);
1228  }
1229 }
1230 
1231 /// We determined that the loop is profitable to unswitch when LIC equal Val.
1232 /// Split it into loop versions and test the condition outside of either loop.
1233 /// Return the loops created as Out1/Out2.
1234 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
1235  Loop *L, Instruction *TI) {
1236  Function *F = loopHeader->getParent();
1237  LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1238  << loopHeader->getName() << " [" << L->getBlocks().size()
1239  << " blocks] in Function " << F->getName() << " when '"
1240  << *Val << "' == " << *LIC << "\n");
1241 
1242  // We are going to make essential changes to CFG. This may invalidate cached
1243  // information for L or one of its parent loops in SCEV.
1244  if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1245  SEWP->getSE().forgetTopmostLoop(L);
1246 
1247  LoopBlocks.clear();
1248  NewBlocks.clear();
1249 
1250  if (MSSAU && VerifyMemorySSA)
1251  MSSA->verifyMemorySSA();
1252 
1253  // First step, split the preheader and exit blocks, and add these blocks to
1254  // the LoopBlocks list.
1255  BasicBlock *NewPreheader =
1256  SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1257  LoopBlocks.push_back(NewPreheader);
1258 
1259  // We want the loop to come after the preheader, but before the exit blocks.
1260  LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1261 
1262  SmallVector<BasicBlock*, 8> ExitBlocks;
1263  L->getUniqueExitBlocks(ExitBlocks);
1264 
1265  // Split all of the edges from inside the loop to their exit blocks. Update
1266  // the appropriate Phi nodes as we do so.
1267  SplitExitEdges(L, ExitBlocks);
1268 
1269  // The exit blocks may have been changed due to edge splitting, recompute.
1270  ExitBlocks.clear();
1271  L->getUniqueExitBlocks(ExitBlocks);
1272 
1273  // Add exit blocks to the loop blocks.
1274  LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
1275 
1276  // Next step, clone all of the basic blocks that make up the loop (including
1277  // the loop preheader and exit blocks), keeping track of the mapping between
1278  // the instructions and blocks.
1279  NewBlocks.reserve(LoopBlocks.size());
1280  ValueToValueMapTy VMap;
1281  for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1282  BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
1283 
1284  NewBlocks.push_back(NewBB);
1285  VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
1286  LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1287  }
1288 
1289  // Splice the newly inserted blocks into the function right before the
1290  // original preheader.
1291  F->getBasicBlockList().splice(NewPreheader->getIterator(),
1292  F->getBasicBlockList(),
1293  NewBlocks[0]->getIterator(), F->end());
1294 
1295  // Now we create the new Loop object for the versioned loop.
1296  Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1297 
1298  // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1299  // Probably clone more loop-unswitch related loop properties.
1300  BranchesInfo.cloneData(NewLoop, L, VMap);
1301 
1302  Loop *ParentLoop = L->getParentLoop();
1303  if (ParentLoop) {
1304  // Make sure to add the cloned preheader and exit blocks to the parent loop
1305  // as well.
1306  ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1307  }
1308 
1309  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1310  BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1311  // The new exit block should be in the same loop as the old one.
1312  if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1313  ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1314 
1315  assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1316  "Exit block should have been split to have one successor!");
1317  BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1318 
1319  // If the successor of the exit block had PHI nodes, add an entry for
1320  // NewExit.
1321  for (PHINode &PN : ExitSucc->phis()) {
1322  Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
1323  ValueToValueMapTy::iterator It = VMap.find(V);
1324  if (It != VMap.end()) V = It->second;
1325  PN.addIncoming(V, NewExit);
1326  }
1327 
1328  if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1329  PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1330  &*ExitSucc->getFirstInsertionPt());
1331 
1332  for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1333  I != E; ++I) {
1334  BasicBlock *BB = *I;
1335  LandingPadInst *LPI = BB->getLandingPadInst();
1336  LPI->replaceAllUsesWith(PN);
1337  PN->addIncoming(LPI, BB);
1338  }
1339  }
1340  }
1341 
1342  // Rewrite the code to refer to itself.
1343  for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1344  for (Instruction &I : *NewBlocks[i]) {
1345  RemapInstruction(&I, VMap,
1347  if (auto *II = dyn_cast<IntrinsicInst>(&I))
1348  if (II->getIntrinsicID() == Intrinsic::assume)
1349  AC->registerAssumption(II);
1350  }
1351  }
1352 
1353  // Rewrite the original preheader to select between versions of the loop.
1354  BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1355  assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1356  "Preheader splitting did not work correctly!");
1357 
1358  if (MSSAU) {
1359  // Update MemorySSA after cloning, and before splitting to unreachables,
1360  // since that invalidates the 1:1 mapping of clones in VMap.
1361  LoopBlocksRPO LBRPO(L);
1362  LBRPO.perform(LI);
1363  MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1364  }
1365 
1366  // Emit the new branch that selects between the two versions of this loop.
1367  EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1368  TI);
1369  LPM->deleteSimpleAnalysisValue(OldBR, L);
1370  if (MSSAU) {
1371  // Update MemoryPhis in Exit blocks.
1372  MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1373  if (VerifyMemorySSA)
1374  MSSA->verifyMemorySSA();
1375  }
1376 
1377  // The OldBr was replaced by a new one and removed (but not erased) by
1378  // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
1379  delete OldBR;
1380 
1381  LoopProcessWorklist.push_back(NewLoop);
1382  redoLoop = true;
1383 
1384  // Keep a WeakTrackingVH holding onto LIC. If the first call to
1385  // RewriteLoopBody
1386  // deletes the instruction (for example by simplifying a PHI that feeds into
1387  // the condition that we're unswitching on), we don't rewrite the second
1388  // iteration.
1389  WeakTrackingVH LICHandle(LIC);
1390 
1391  // Now we rewrite the original code to know that the condition is true and the
1392  // new code to know that the condition is false.
1393  RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1394 
1395  // It's possible that simplifying one loop could cause the other to be
1396  // changed to another value or a constant. If its a constant, don't simplify
1397  // it.
1398  if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1399  LICHandle && !isa<Constant>(LICHandle))
1400  RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1401 
1402  if (MSSA && VerifyMemorySSA)
1403  MSSA->verifyMemorySSA();
1404 }
1405 
1406 /// Remove all instances of I from the worklist vector specified.
1408  std::vector<Instruction*> &Worklist) {
1409 
1410  Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1411  Worklist.end());
1412 }
1413 
1414 /// When we find that I really equals V, remove I from the
1415 /// program, replacing all uses with V and update the worklist.
1417  std::vector<Instruction *> &Worklist, Loop *L,
1418  LPPassManager *LPM, MemorySSAUpdater *MSSAU) {
1419  LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
1420 
1421  // Add uses to the worklist, which may be dead now.
1422  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1423  if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1424  Worklist.push_back(Use);
1425 
1426  // Add users to the worklist which may be simplified now.
1427  for (User *U : I->users())
1428  Worklist.push_back(cast<Instruction>(U));
1429  LPM->deleteSimpleAnalysisValue(I, L);
1430  RemoveFromWorklist(I, Worklist);
1431  I->replaceAllUsesWith(V);
1432  if (!I->mayHaveSideEffects()) {
1433  if (MSSAU)
1434  MSSAU->removeMemoryAccess(I);
1435  I->eraseFromParent();
1436  }
1437  ++NumSimplify;
1438 }
1439 
1440 /// We know either that the value LIC has the value specified by Val in the
1441 /// specified loop, or we know it does NOT have that value.
1442 /// Rewrite any uses of LIC or of properties correlated to it.
1443 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1444  Constant *Val,
1445  bool IsEqual) {
1446  assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1447 
1448  // FIXME: Support correlated properties, like:
1449  // for (...)
1450  // if (li1 < li2)
1451  // ...
1452  // if (li1 > li2)
1453  // ...
1454 
1455  // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1456  // selects, switches.
1457  std::vector<Instruction*> Worklist;
1458  LLVMContext &Context = Val->getContext();
1459 
1460  // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1461  // in the loop with the appropriate one directly.
1462  if (IsEqual || (isa<ConstantInt>(Val) &&
1463  Val->getType()->isIntegerTy(1))) {
1464  Value *Replacement;
1465  if (IsEqual)
1466  Replacement = Val;
1467  else
1468  Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1469  !cast<ConstantInt>(Val)->getZExtValue());
1470 
1471  for (User *U : LIC->users()) {
1472  Instruction *UI = dyn_cast<Instruction>(U);
1473  if (!UI || !L->contains(UI))
1474  continue;
1475  Worklist.push_back(UI);
1476  }
1477 
1478  for (Instruction *UI : Worklist)
1479  UI->replaceUsesOfWith(LIC, Replacement);
1480 
1481  SimplifyCode(Worklist, L);
1482  return;
1483  }
1484 
1485  // Otherwise, we don't know the precise value of LIC, but we do know that it
1486  // is certainly NOT "Val". As such, simplify any uses in the loop that we
1487  // can. This case occurs when we unswitch switch statements.
1488  for (User *U : LIC->users()) {
1489  Instruction *UI = dyn_cast<Instruction>(U);
1490  if (!UI || !L->contains(UI))
1491  continue;
1492 
1493  // At this point, we know LIC is definitely not Val. Try to use some simple
1494  // logic to simplify the user w.r.t. to the context.
1495  if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1496  if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1497  // This in-loop instruction has been simplified w.r.t. its context,
1498  // i.e. LIC != Val, make sure we propagate its replacement value to
1499  // all its users.
1500  //
1501  // We can not yet delete UI, the LIC user, yet, because that would invalidate
1502  // the LIC->users() iterator !. However, we can make this instruction
1503  // dead by replacing all its users and push it onto the worklist so that
1504  // it can be properly deleted and its operands simplified.
1505  UI->replaceAllUsesWith(Replacement);
1506  }
1507  }
1508 
1509  // This is a LIC user, push it into the worklist so that SimplifyCode can
1510  // attempt to simplify it.
1511  Worklist.push_back(UI);
1512 
1513  // If we know that LIC is not Val, use this info to simplify code.
1514  SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1515  if (!SI || !isa<ConstantInt>(Val)) continue;
1516 
1517  // NOTE: if a case value for the switch is unswitched out, we record it
1518  // after the unswitch finishes. We can not record it here as the switch
1519  // is not a direct user of the partial LIV.
1520  SwitchInst::CaseHandle DeadCase =
1521  *SI->findCaseValue(cast<ConstantInt>(Val));
1522  // Default case is live for multiple values.
1523  if (DeadCase == *SI->case_default())
1524  continue;
1525 
1526  // Found a dead case value. Don't remove PHI nodes in the
1527  // successor if they become single-entry, those PHI nodes may
1528  // be in the Users list.
1529 
1530  BasicBlock *Switch = SI->getParent();
1531  BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1532  BasicBlock *Latch = L->getLoopLatch();
1533 
1534  if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
1535  // If the DeadCase successor dominates the loop latch, then the
1536  // transformation isn't safe since it will delete the sole predecessor edge
1537  // to the latch.
1538  if (Latch && DT->dominates(SISucc, Latch))
1539  continue;
1540 
1541  // FIXME: This is a hack. We need to keep the successor around
1542  // and hooked up so as to preserve the loop structure, because
1543  // trying to update it is complicated. So instead we preserve the
1544  // loop structure and put the block on a dead code path.
1545  SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1546  // Compute the successors instead of relying on the return value
1547  // of SplitEdge, since it may have split the switch successor
1548  // after PHI nodes.
1549  BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1550  BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1551  // Create an "unreachable" destination.
1552  BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1553  Switch->getParent(),
1554  OldSISucc);
1555  new UnreachableInst(Context, Abort);
1556  // Force the new case destination to branch to the "unreachable"
1557  // block while maintaining a (dead) CFG edge to the old block.
1558  NewSISucc->getTerminator()->eraseFromParent();
1559  BranchInst::Create(Abort, OldSISucc,
1560  ConstantInt::getTrue(Context), NewSISucc);
1561  // Release the PHI operands for this edge.
1562  for (PHINode &PN : NewSISucc->phis())
1563  PN.setIncomingValueForBlock(Switch, UndefValue::get(PN.getType()));
1564  // Tell the domtree about the new block. We don't fully update the
1565  // domtree here -- instead we force it to do a full recomputation
1566  // after the pass is complete -- but we do need to inform it of
1567  // new blocks.
1568  DT->addNewBlock(Abort, NewSISucc);
1569  }
1570 
1571  SimplifyCode(Worklist, L);
1572 }
1573 
1574 /// Now that we have simplified some instructions in the loop, walk over it and
1575 /// constant prop, dce, and fold control flow where possible. Note that this is
1576 /// effectively a very simple loop-structure-aware optimizer. During processing
1577 /// of this loop, L could very well be deleted, so it must not be used.
1578 ///
1579 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1580 /// pass.
1581 ///
1582 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1583  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1584  while (!Worklist.empty()) {
1585  Instruction *I = Worklist.back();
1586  Worklist.pop_back();
1587 
1588  // Simple DCE.
1589  if (isInstructionTriviallyDead(I)) {
1590  LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
1591 
1592  // Add uses to the worklist, which may be dead now.
1593  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1594  if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1595  Worklist.push_back(Use);
1596  LPM->deleteSimpleAnalysisValue(I, L);
1597  RemoveFromWorklist(I, Worklist);
1598  if (MSSAU)
1599  MSSAU->removeMemoryAccess(I);
1600  I->eraseFromParent();
1601  ++NumSimplify;
1602  continue;
1603  }
1604 
1605  // See if instruction simplification can hack this up. This is common for
1606  // things like "select false, X, Y" after unswitching made the condition be
1607  // 'false'. TODO: update the domtree properly so we can pass it here.
1608  if (Value *V = SimplifyInstruction(I, DL))
1609  if (LI->replacementPreservesLCSSAForm(I, V)) {
1610  ReplaceUsesOfWith(I, V, Worklist, L, LPM, MSSAU.get());
1611  continue;
1612  }
1613 
1614  // Special case hacks that appear commonly in unswitched code.
1615  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1616  if (BI->isUnconditional()) {
1617  // If BI's parent is the only pred of the successor, fold the two blocks
1618  // together.
1619  BasicBlock *Pred = BI->getParent();
1620  (void)Pred;
1621  BasicBlock *Succ = BI->getSuccessor(0);
1622  BasicBlock *SinglePred = Succ->getSinglePredecessor();
1623  if (!SinglePred) continue; // Nothing to do.
1624  assert(SinglePred == Pred && "CFG broken");
1625 
1626  // Make the LPM and Worklist updates specific to LoopUnswitch.
1627  LPM->deleteSimpleAnalysisValue(BI, L);
1628  RemoveFromWorklist(BI, Worklist);
1629  LPM->deleteSimpleAnalysisValue(Succ, L);
1630  auto SuccIt = Succ->begin();
1631  while (PHINode *PN = dyn_cast<PHINode>(SuccIt++)) {
1632  for (unsigned It = 0, E = PN->getNumOperands(); It != E; ++It)
1633  if (Instruction *Use = dyn_cast<Instruction>(PN->getOperand(It)))
1634  Worklist.push_back(Use);
1635  for (User *U : PN->users())
1636  Worklist.push_back(cast<Instruction>(U));
1637  LPM->deleteSimpleAnalysisValue(PN, L);
1638  RemoveFromWorklist(PN, Worklist);
1639  ++NumSimplify;
1640  }
1641  // Merge the block and make the remaining analyses updates.
1643  MergeBlockIntoPredecessor(Succ, &DTU, LI, MSSAU.get());
1644  ++NumSimplify;
1645  continue;
1646  }
1647 
1648  continue;
1649  }
1650  }
1651 }
1652 
1653 /// Simple simplifications we can do given the information that Cond is
1654 /// definitely not equal to Val.
1655 Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
1656  Value *Invariant,
1657  Constant *Val) {
1658  // icmp eq cond, val -> false
1659  ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
1660  if (CI && CI->isEquality()) {
1661  Value *Op0 = CI->getOperand(0);
1662  Value *Op1 = CI->getOperand(1);
1663  if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
1664  LLVMContext &Ctx = Inst->getContext();
1665  if (CI->getPredicate() == CmpInst::ICMP_EQ)
1666  return ConstantInt::getFalse(Ctx);
1667  else
1668  return ConstantInt::getTrue(Ctx);
1669  }
1670  }
1671 
1672  // FIXME: there may be other opportunities, e.g. comparison with floating
1673  // point, or Invariant - Val != 0, etc.
1674  return nullptr;
1675 }
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: MustExecute.cpp:51
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:78
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop&#39;s ephemeral values (those used only by an assume or similar intrinsics in the loop)...
Definition: CodeMetrics.cpp:70
unsigned getNumCases() const
Return the number of &#39;cases&#39; in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
void initializeLoopUnswitchPass(PassRegistry &)
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:667
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:177
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:209
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
LLVMContext & Context
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:84
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
ArrayRef< BasicBlock *>::const_iterator block_iterator
Definition: LoopInfo.h:158
OperatorChain
Operator chain lattice.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
iterator end()
Definition: Function.h:693
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:85
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:449
static void ReplaceUsesOfWith(Instruction *I, Value *V, std::vector< Instruction *> &Worklist, Loop *L, LPPassManager *LPM, MemorySSAUpdater *MSSAU)
When we find that I really equals V, remove I from the program, replacing all uses with V and update ...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:160
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
loop Unswitch loops
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
F(f)
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
There are only ANDs.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
bool notDuplicatable
True if this function cannot be duplicated.
Definition: CodeMetrics.h:44
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:32
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:318
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:273
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
Definition: MustExecute.h:109
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:140
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Legacy analysis pass which computes MemorySSA.
Definition: MemorySSA.h:964
static Loop * CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
This class represents the LLVM &#39;select&#39; instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Option class for critical edge splitting.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:939
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:704
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockT * getHeader() const
Definition: LoopInfo.h:105
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
There are ANDs and ORs.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:200
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Definition: LoopInfoImpl.h:235
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once. ...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:990
iterator find(const KeyT &Val)
Definition: ValueMap.h:156
static Value * FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed, OperatorChain &ParentChain, DenseMap< Value *, Value *> &Cache, MemorySSAUpdater *MSSAU)
Cond is a condition that occurs in L.
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:165
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Definition: User.h:169
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:72
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:20
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Wrapper pass for TargetTransformInfo.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:240
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void RemoveFromWorklist(Instruction *I, std::vector< Instruction *> &Worklist)
Remove all instances of I from the worklist vector specified.
const Instruction & front() const
Definition: BasicBlock.h:285
Machine Trace Metrics
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:582
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:327
static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, BasicBlock *&ExitBB, std::set< BasicBlock *> &Visited)
Check to see if all paths from BB exit the loop with no side effects (including infinite loops)...
This instruction compares its operands according to the predicate given to the constructor.
constexpr double e
Definition: MathExtras.h:57
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
self_iterator getIterator()
Definition: ilist_node.h:81
static bool EqualityPropUnSafe(Value &LoopCond)
FIXME: Remove this workaround when freeze related patches are done.
INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops", false, false) INITIALIZE_PASS_END(LoopUnswitch
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:372
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1514
size_t size() const
Definition: SmallVector.h:52
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
loop unswitch
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned first
iterator end()
Definition: ValueMap.h:136
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
Definition: LoopPass.cpp:107
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:115
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:191
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1872
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
There is no operator.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:32
LoopT * AllocateLoop(ArgsTy &&... Args)
Definition: LoopInfo.h:903
CHAIN = SC CHAIN, Imm128 - System call.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:660
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
Pass * createLoopUnswitchPass(bool OptimizeForSize=false, bool hasBranchDivergence=false)
iterator_range< user_iterator > users()
Definition: Value.h:420
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
Definition: ValueMapper.h:251
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
Definition: ValueMapper.h:90
void removeFromParent()
This method unlinks &#39;this&#39; from the containing basic block, but does not delete it.
Definition: Instruction.cpp:63
LoopT * getParentLoop() const
Definition: LoopInfo.h:106
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:807
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function&#39;s cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:375
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
Definition: LoopPass.cpp:98
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:154
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void addLoop(Loop &L)
Definition: LoopPass.cpp:78
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass&#39;s AnalysisUsage.
Definition: LoopUtils.cpp:138
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Definition: Function.h:668
block_iterator block_end() const
Definition: LoopInfo.h:160
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
Definition: LoopInfo.cpp:472
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
Definition: LoopIterator.h:172
Multiway switch.
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
Definition: Local.cpp:359
LLVM Value Representation.
Definition: Value.h:74
There are only ORs.
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:115
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:475
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
Definition: LoopInfo.h:1081
This pass exposes codegen information to IR-level passes.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopIterator.h:180
#define LLVM_DEBUG(X)
Definition: Debug.h:122
unsigned NumInsts
Number of instructions in the analyzed blocks.
Definition: CodeMetrics.h:53
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:161
static BasicBlock * isTrivialLoopExitBlock(Loop *L, BasicBlock *BB)
Return true if the specified block unconditionally leads to an exit from the specified loop...
block_iterator block_begin() const
Definition: LoopInfo.h:159
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
const BasicBlock * getParent() const
Definition: Instruction.h:66
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
Definition: LoopInfo.cpp:72