Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1 | //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | a704ac8 | 2002-10-08 21:36:33 +0000 | [diff] [blame] | 10 | // Peephole optimize the CFG. |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/DenseMap.h" |
| 15 | #include "llvm/ADT/STLExtras.h" |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/SetOperations.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/SetVector.h" |
| 18 | #include "llvm/ADT/SmallPtrSet.h" |
| 19 | #include "llvm/ADT/SmallVector.h" |
| 20 | #include "llvm/ADT/Statistic.h" |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/ConstantFolding.h" |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/EHPersonalities.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 26 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 27 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Constants.h" |
| 29 | #include "llvm/IR/DataLayout.h" |
| 30 | #include "llvm/IR/DerivedTypes.h" |
| 31 | #include "llvm/IR/GlobalVariable.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/Instructions.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
| 35 | #include "llvm/IR/LLVMContext.h" |
| 36 | #include "llvm/IR/MDBuilder.h" |
| 37 | #include "llvm/IR/Metadata.h" |
| 38 | #include "llvm/IR/Module.h" |
Chandler Carruth | 64396b0 | 2014-03-04 12:05:47 +0000 | [diff] [blame] | 39 | #include "llvm/IR/NoFolder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 40 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 41 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 42 | #include "llvm/IR/Type.h" |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 43 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 44 | #include "llvm/Support/Debug.h" |
| 45 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/Local.h" |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 49 | #include <algorithm> |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 50 | #include <map> |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 51 | #include <set> |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 52 | using namespace llvm; |
Benjamin Kramer | 3717222 | 2013-07-04 14:22:02 +0000 | [diff] [blame] | 53 | using namespace PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 54 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 55 | #define DEBUG_TYPE "simplifycfg" |
| 56 | |
James Molloy | 1b6207e | 2015-02-13 10:48:30 +0000 | [diff] [blame] | 57 | // Chosen as 2 so as to be cheap, but still to have enough power to fold |
| 58 | // a select, so the "clamp" idiom (of a min followed by a max) will be caught. |
| 59 | // To catch this, we need to fold a compare and a select, hence '2' being the |
| 60 | // minimum reasonable default. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 61 | static cl::opt<unsigned> PHINodeFoldingThreshold( |
| 62 | "phi-node-folding-threshold", cl::Hidden, cl::init(2), |
| 63 | cl::desc( |
| 64 | "Control the amount of phi node folding to perform (default = 2)")); |
| 65 | |
| 66 | static cl::opt<bool> DupRet( |
| 67 | "simplifycfg-dup-ret", cl::Hidden, cl::init(false), |
| 68 | cl::desc("Duplicate return instructions into unconditional branches")); |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 69 | |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 70 | static cl::opt<bool> |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 71 | SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), |
| 72 | cl::desc("Sink common instructions down to the end block")); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 73 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 74 | static cl::opt<bool> HoistCondStores( |
| 75 | "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), |
| 76 | cl::desc("Hoist conditional stores if an unconditional store precedes")); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 77 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 78 | static cl::opt<bool> MergeCondStores( |
| 79 | "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), |
| 80 | cl::desc("Hoist conditional stores even if an unconditional store does not " |
| 81 | "precede - hoist multiple conditional stores into a single " |
| 82 | "predicated store")); |
| 83 | |
| 84 | static cl::opt<bool> MergeCondStoresAggressively( |
| 85 | "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), |
| 86 | cl::desc("When merging conditional stores, do so even if the resultant " |
| 87 | "basic blocks are unlikely to be if-converted as a result")); |
| 88 | |
David Majnemer | fccf5c6 | 2016-01-27 02:59:41 +0000 | [diff] [blame] | 89 | static cl::opt<bool> SpeculateOneExpensiveInst( |
| 90 | "speculate-one-expensive-inst", cl::Hidden, cl::init(true), |
| 91 | cl::desc("Allow exactly one expensive instruction to be speculatively " |
| 92 | "executed")); |
| 93 | |
Sanjay Patel | 5264cc7 | 2016-01-27 19:22:45 +0000 | [diff] [blame] | 94 | static cl::opt<unsigned> MaxSpeculationDepth( |
| 95 | "max-speculation-depth", cl::Hidden, cl::init(10), |
| 96 | cl::desc("Limit maximum recursion depth when calculating costs of " |
| 97 | "speculatively executed instructions")); |
| 98 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 99 | STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 100 | STATISTIC(NumLinearMaps, |
| 101 | "Number of switch instructions turned into linear mapping"); |
| 102 | STATISTIC(NumLookupTables, |
| 103 | "Number of switch instructions turned into lookup tables"); |
| 104 | STATISTIC( |
| 105 | NumLookupTablesHoles, |
| 106 | "Number of switch instructions turned into lookup tables (holes checked)"); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 107 | STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 108 | STATISTIC(NumSinkCommons, |
| 109 | "Number of common instructions sunk down to the end block"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 110 | STATISTIC(NumSpeculations, "Number of speculative executed instructions"); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 111 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 112 | namespace { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 113 | // The first field contains the value that the switch produces when a certain |
| 114 | // case group is selected, and the second field is a vector containing the |
| 115 | // cases composing the case group. |
| 116 | typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2> |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 117 | SwitchCaseResultVectorTy; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 118 | // The first field contains the phi node that generates a result of the switch |
| 119 | // and the second field contains the value generated for a certain case in the |
| 120 | // switch for that PHI. |
| 121 | typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy; |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 122 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 123 | /// ValueEqualityComparisonCase - Represents a case of a switch. |
| 124 | struct ValueEqualityComparisonCase { |
| 125 | ConstantInt *Value; |
| 126 | BasicBlock *Dest; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 127 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 128 | ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 129 | : Value(Value), Dest(Dest) {} |
| 130 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 131 | bool operator<(ValueEqualityComparisonCase RHS) const { |
| 132 | // Comparing pointers is ok as we only rely on the order for uniquing. |
| 133 | return Value < RHS.Value; |
| 134 | } |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 135 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 136 | bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } |
| 137 | }; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 138 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 139 | class SimplifyCFGOpt { |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 140 | const TargetTransformInfo &TTI; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 141 | const DataLayout &DL; |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 142 | unsigned BonusInstThreshold; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 143 | AssumptionCache *AC; |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 144 | SmallPtrSetImpl<BasicBlock *> *LoopHeaders; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 145 | Value *isValueEqualityComparison(TerminatorInst *TI); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 146 | BasicBlock *GetValueEqualityComparisonCases( |
| 147 | TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 148 | bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 149 | BasicBlock *Pred, |
| 150 | IRBuilder<> &Builder); |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 151 | bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 152 | IRBuilder<> &Builder); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 153 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 154 | bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 155 | bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 156 | bool SimplifySingleResume(ResumeInst *RI); |
| 157 | bool SimplifyCommonResume(ResumeInst *RI); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 158 | bool SimplifyCleanupReturn(CleanupReturnInst *RI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 159 | bool SimplifyUnreachable(UnreachableInst *UI); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 160 | bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 161 | bool SimplifyIndirectBr(IndirectBrInst *IBI); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 162 | bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder); |
| 163 | bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 164 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 165 | public: |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 166 | SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 167 | unsigned BonusInstThreshold, AssumptionCache *AC, |
| 168 | SmallPtrSetImpl<BasicBlock *> *LoopHeaders) |
| 169 | : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC), |
| 170 | LoopHeaders(LoopHeaders) {} |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 171 | bool run(BasicBlock *BB); |
| 172 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 173 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 174 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 175 | /// Return true if it is safe to merge these two |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 176 | /// terminator instructions together. |
James Molloy | 8e69b03 | 2016-08-31 10:46:39 +0000 | [diff] [blame] | 177 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2, |
| 178 | std::vector<BasicBlock*> *FailBlocks = nullptr) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 179 | if (SI1 == SI2) |
| 180 | return false; // Can't merge with self! |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 181 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 182 | // It is not safe to merge these two switch instructions if they have a common |
| 183 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 184 | // conflicting incoming values from the two switch blocks. |
| 185 | BasicBlock *SI1BB = SI1->getParent(); |
| 186 | BasicBlock *SI2BB = SI2->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 187 | |
James Molloy | 8e69b03 | 2016-08-31 10:46:39 +0000 | [diff] [blame] | 188 | SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
| 189 | bool Fail = false; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 190 | for (BasicBlock *Succ : successors(SI2BB)) |
| 191 | if (SI1Succs.count(Succ)) |
| 192 | for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 193 | PHINode *PN = cast<PHINode>(BBI); |
| 194 | if (PN->getIncomingValueForBlock(SI1BB) != |
James Molloy | 8e69b03 | 2016-08-31 10:46:39 +0000 | [diff] [blame] | 195 | PN->getIncomingValueForBlock(SI2BB)) { |
| 196 | if (FailBlocks) |
| 197 | FailBlocks->push_back(Succ); |
| 198 | Fail = true; |
| 199 | } |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 200 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 201 | |
James Molloy | 8e69b03 | 2016-08-31 10:46:39 +0000 | [diff] [blame] | 202 | return !Fail; |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 203 | } |
| 204 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 205 | /// Return true if it is safe and profitable to merge these two terminator |
| 206 | /// instructions together, where SI1 is an unconditional branch. PhiNodes will |
| 207 | /// store all PHI nodes in common successors. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 208 | static bool |
| 209 | isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, |
| 210 | Instruction *Cond, |
| 211 | SmallVectorImpl<PHINode *> &PhiNodes) { |
| 212 | if (SI1 == SI2) |
| 213 | return false; // Can't merge with self! |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 214 | assert(SI1->isUnconditional() && SI2->isConditional()); |
| 215 | |
| 216 | // We fold the unconditional branch if we can easily update all PHI nodes in |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 217 | // common successors: |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 218 | // 1> We have a constant incoming value for the conditional branch; |
| 219 | // 2> We have "Cond" as the incoming value for the unconditional branch; |
| 220 | // 3> SI2->getCondition() and Cond have same operands. |
| 221 | CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 222 | if (!Ci2) |
| 223 | return false; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 224 | if (!(Cond->getOperand(0) == Ci2->getOperand(0) && |
| 225 | Cond->getOperand(1) == Ci2->getOperand(1)) && |
| 226 | !(Cond->getOperand(0) == Ci2->getOperand(1) && |
| 227 | Cond->getOperand(1) == Ci2->getOperand(0))) |
| 228 | return false; |
| 229 | |
| 230 | BasicBlock *SI1BB = SI1->getParent(); |
| 231 | BasicBlock *SI2BB = SI2->getParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 232 | SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 233 | for (BasicBlock *Succ : successors(SI2BB)) |
| 234 | if (SI1Succs.count(Succ)) |
| 235 | for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 236 | PHINode *PN = cast<PHINode>(BBI); |
| 237 | if (PN->getIncomingValueForBlock(SI1BB) != Cond || |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 238 | !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 239 | return false; |
| 240 | PhiNodes.push_back(PN); |
| 241 | } |
| 242 | return true; |
| 243 | } |
| 244 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 245 | /// Update PHI nodes in Succ to indicate that there will now be entries in it |
| 246 | /// from the 'NewPred' block. The values that will be flowing into the PHI nodes |
| 247 | /// will be the same as those coming in from ExistPred, an existing predecessor |
| 248 | /// of Succ. |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 249 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 250 | BasicBlock *ExistPred) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 251 | if (!isa<PHINode>(Succ->begin())) |
| 252 | return; // Quick exit if nothing to do |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 253 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 254 | PHINode *PN; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 255 | for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I) |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 256 | PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 257 | } |
| 258 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 259 | /// Compute an abstract "cost" of speculating the given instruction, |
| 260 | /// which is assumed to be safe to speculate. TCC_Free means cheap, |
| 261 | /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 262 | /// expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 263 | static unsigned ComputeSpeculationCost(const User *I, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 264 | const TargetTransformInfo &TTI) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 265 | assert(isSafeToSpeculativelyExecute(I) && |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 266 | "Instruction is not safe to speculatively execute!"); |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 267 | return TTI.getUserCost(I); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 268 | } |
Sanjay Patel | f9b7763 | 2015-09-15 15:24:42 +0000 | [diff] [blame] | 269 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 270 | /// If we have a merge point of an "if condition" as accepted above, |
| 271 | /// return true if the specified value dominates the block. We |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 272 | /// don't handle the true generality of domination here, just a special case |
| 273 | /// which works well enough for us. |
| 274 | /// |
| 275 | /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 276 | /// see if V (which must be an instruction) and its recursive operands |
| 277 | /// that do not dominate BB have a combined cost lower than CostRemaining and |
| 278 | /// are non-trapping. If both are true, the instruction is inserted into the |
| 279 | /// set and true is returned. |
| 280 | /// |
| 281 | /// The cost for most non-trapping instructions is defined as 1 except for |
| 282 | /// Select whose cost is 2. |
| 283 | /// |
| 284 | /// After this function returns, CostRemaining is decreased by the cost of |
| 285 | /// V plus its non-dominating operands. If that cost is greater than |
| 286 | /// CostRemaining, false is returned and CostRemaining is undefined. |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 287 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 288 | SmallPtrSetImpl<Instruction *> *AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 289 | unsigned &CostRemaining, |
David Majnemer | fccf5c6 | 2016-01-27 02:59:41 +0000 | [diff] [blame] | 290 | const TargetTransformInfo &TTI, |
| 291 | unsigned Depth = 0) { |
Sanjay Patel | 5264cc7 | 2016-01-27 19:22:45 +0000 | [diff] [blame] | 292 | // It is possible to hit a zero-cost cycle (phi/gep instructions for example), |
| 293 | // so limit the recursion depth. |
| 294 | // TODO: While this recursion limit does prevent pathological behavior, it |
| 295 | // would be better to track visited instructions to avoid cycles. |
| 296 | if (Depth == MaxSpeculationDepth) |
| 297 | return false; |
| 298 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 299 | Instruction *I = dyn_cast<Instruction>(V); |
Chris Lattner | b8b1159 | 2006-10-20 00:42:07 +0000 | [diff] [blame] | 300 | if (!I) { |
| 301 | // Non-instructions all dominate instructions, but not all constantexprs |
| 302 | // can be executed unconditionally. |
| 303 | if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| 304 | if (C->canTrap()) |
| 305 | return false; |
| 306 | return true; |
| 307 | } |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 308 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 309 | |
Chris Lattner | 0ce80cd | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 310 | // We don't want to allow weird loops that might have the "if condition" in |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 311 | // the bottom of this block. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 312 | if (PBB == BB) |
| 313 | return false; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 314 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 315 | // If this instruction is defined in a block that contains an unconditional |
| 316 | // branch to BB, then it must be in the 'conditional' part of the "if |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 317 | // statement". If not, it definitely dominates the region. |
| 318 | BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 319 | if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 320 | return true; |
Eli Friedman | b8f6a4f | 2009-07-17 04:28:42 +0000 | [diff] [blame] | 321 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 322 | // If we aren't allowing aggressive promotion anymore, then don't consider |
| 323 | // instructions in the 'if region'. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 324 | if (!AggressiveInsts) |
| 325 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 326 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 327 | // If we have seen this instruction before, don't count it again. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 328 | if (AggressiveInsts->count(I)) |
| 329 | return true; |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 330 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 331 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 332 | // see if it's a cheap instruction to unconditionally compute, and if it |
| 333 | // only uses stuff defined outside of the condition. If so, hoist it out. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 334 | if (!isSafeToSpeculativelyExecute(I)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 335 | return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 336 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 337 | unsigned Cost = ComputeSpeculationCost(I, TTI); |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 338 | |
David Majnemer | fccf5c6 | 2016-01-27 02:59:41 +0000 | [diff] [blame] | 339 | // Allow exactly one instruction to be speculated regardless of its cost |
| 340 | // (as long as it is safe to do so). |
| 341 | // This is intended to flatten the CFG even if the instruction is a division |
| 342 | // or other expensive operation. The speculation of an expensive instruction |
| 343 | // is expected to be undone in CodeGenPrepare if the speculation has not |
| 344 | // enabled further IR optimizations. |
| 345 | if (Cost > CostRemaining && |
| 346 | (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0)) |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 347 | return false; |
| 348 | |
David Majnemer | fccf5c6 | 2016-01-27 02:59:41 +0000 | [diff] [blame] | 349 | // Avoid unsigned wrap. |
| 350 | CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost; |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 351 | |
| 352 | // Okay, we can only really hoist these out if their operands do |
| 353 | // not take us over the cost threshold. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 354 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
David Majnemer | fccf5c6 | 2016-01-27 02:59:41 +0000 | [diff] [blame] | 355 | if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI, |
| 356 | Depth + 1)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 357 | return false; |
| 358 | // Okay, it's safe to do this! Remember this instruction. |
| 359 | AggressiveInsts->insert(I); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 360 | return true; |
| 361 | } |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 362 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 363 | /// Extract ConstantInt from value, looking through IntToPtr |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 364 | /// and PointerNullValue. Return NULL if value is not a constant int. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 365 | static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 366 | // Normal constant int. |
| 367 | ConstantInt *CI = dyn_cast<ConstantInt>(V); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 368 | if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 369 | return CI; |
| 370 | |
| 371 | // This is some kind of pointer constant. Turn it into a pointer-sized |
| 372 | // ConstantInt if possible. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 373 | IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 374 | |
| 375 | // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). |
| 376 | if (isa<ConstantPointerNull>(V)) |
| 377 | return ConstantInt::get(PtrTy, 0); |
| 378 | |
| 379 | // IntToPtr const int. |
| 380 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 381 | if (CE->getOpcode() == Instruction::IntToPtr) |
| 382 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { |
| 383 | // The constant is very likely to have the right type already. |
| 384 | if (CI->getType() == PtrTy) |
| 385 | return CI; |
| 386 | else |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 387 | return cast<ConstantInt>( |
| 388 | ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 389 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 390 | return nullptr; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 391 | } |
| 392 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 393 | namespace { |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 394 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 395 | /// Given a chain of or (||) or and (&&) comparison of a value against a |
| 396 | /// constant, this will try to recover the information required for a switch |
| 397 | /// structure. |
| 398 | /// It will depth-first traverse the chain of comparison, seeking for patterns |
| 399 | /// like %a == 12 or %a < 4 and combine them to produce a set of integer |
| 400 | /// representing the different cases for the switch. |
| 401 | /// Note that if the chain is composed of '||' it will build the set of elements |
| 402 | /// that matches the comparisons (i.e. any of this value validate the chain) |
| 403 | /// while for a chain of '&&' it will build the set elements that make the test |
| 404 | /// fail. |
| 405 | struct ConstantComparesGatherer { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 406 | const DataLayout &DL; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 407 | Value *CompValue; /// Value found for the switch comparison |
| 408 | Value *Extra; /// Extra clause to be checked before the switch |
| 409 | SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch |
| 410 | unsigned UsedICmps; /// Number of comparisons matched in the and/or chain |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 411 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 412 | /// Construct and compute the result for the comparison instruction Cond |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 413 | ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) |
| 414 | : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) { |
| 415 | gather(Cond); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 416 | } |
| 417 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 418 | /// Prevent copy |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 419 | ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 420 | ConstantComparesGatherer & |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 421 | operator=(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 422 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 423 | private: |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 424 | /// Try to set the current value used for the comparison, it succeeds only if |
| 425 | /// it wasn't set before or if the new value is the same as the old one |
| 426 | bool setValueOnce(Value *NewVal) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 427 | if (CompValue && CompValue != NewVal) |
| 428 | return false; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 429 | CompValue = NewVal; |
| 430 | return (CompValue != nullptr); |
| 431 | } |
| 432 | |
| 433 | /// Try to match Instruction "I" as a comparison against a constant and |
| 434 | /// populates the array Vals with the set of values that match (or do not |
| 435 | /// match depending on isEQ). |
| 436 | /// Return false on failure. On success, the Value the comparison matched |
| 437 | /// against is placed in CompValue. |
| 438 | /// If CompValue is already set, the function is expected to fail if a match |
| 439 | /// is found but the value compared to is different. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 440 | bool matchInstruction(Instruction *I, bool isEQ) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 441 | // If this is an icmp against a constant, handle this as one of the cases. |
| 442 | ICmpInst *ICI; |
| 443 | ConstantInt *C; |
| 444 | if (!((ICI = dyn_cast<ICmpInst>(I)) && |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 445 | (C = GetConstantInt(I->getOperand(1), DL)))) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 446 | return false; |
| 447 | } |
| 448 | |
| 449 | Value *RHSVal; |
Chuang-Yu Cheng | 5078f94 | 2016-06-17 00:04:39 +0000 | [diff] [blame] | 450 | const APInt *RHSC; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 451 | |
| 452 | // Pattern match a special case |
David Majnemer | c761afd | 2016-01-27 02:43:28 +0000 | [diff] [blame] | 453 | // (x & ~2^z) == y --> x == y || x == y|2^z |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 454 | // This undoes a transformation done by instcombine to fuse 2 compares. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 455 | if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) { |
Chuang-Yu Cheng | dbe00d5 | 2016-06-16 04:44:25 +0000 | [diff] [blame] | 456 | |
| 457 | // It's a little bit hard to see why the following transformations are |
| 458 | // correct. Here is a CVC3 program to verify them for 64-bit values: |
| 459 | |
| 460 | /* |
| 461 | ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63); |
| 462 | x : BITVECTOR(64); |
| 463 | y : BITVECTOR(64); |
| 464 | z : BITVECTOR(64); |
| 465 | mask : BITVECTOR(64) = BVSHL(ONE, z); |
| 466 | QUERY( (y & ~mask = y) => |
| 467 | ((x & ~mask = y) <=> (x = y OR x = (y | mask))) |
| 468 | ); |
Chuang-Yu Cheng | 68f7f1c | 2016-06-24 01:59:00 +0000 | [diff] [blame] | 469 | QUERY( (y | mask = y) => |
| 470 | ((x | mask = y) <=> (x = y OR x = (y & ~mask))) |
| 471 | ); |
Chuang-Yu Cheng | dbe00d5 | 2016-06-16 04:44:25 +0000 | [diff] [blame] | 472 | */ |
| 473 | |
| 474 | // Please note that each pattern must be a dual implication (<--> or |
| 475 | // iff). One directional implication can create spurious matches. If the |
| 476 | // implication is only one-way, an unsatisfiable condition on the left |
| 477 | // side can imply a satisfiable condition on the right side. Dual |
| 478 | // implication ensures that satisfiable conditions are transformed to |
| 479 | // other satisfiable conditions and unsatisfiable conditions are |
| 480 | // transformed to other unsatisfiable conditions. |
| 481 | |
| 482 | // Here is a concrete example of a unsatisfiable condition on the left |
| 483 | // implying a satisfiable condition on the right: |
| 484 | // |
| 485 | // mask = (1 << z) |
| 486 | // (x & ~mask) == y --> (x == y || x == (y | mask)) |
| 487 | // |
| 488 | // Substituting y = 3, z = 0 yields: |
| 489 | // (x & -2) == 3 --> (x == 3 || x == 2) |
| 490 | |
| 491 | // Pattern match a special case: |
| 492 | /* |
| 493 | QUERY( (y & ~mask = y) => |
| 494 | ((x & ~mask = y) <=> (x = y OR x = (y | mask))) |
| 495 | ); |
| 496 | */ |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 497 | if (match(ICI->getOperand(0), |
Chuang-Yu Cheng | 5078f94 | 2016-06-17 00:04:39 +0000 | [diff] [blame] | 498 | m_And(m_Value(RHSVal), m_APInt(RHSC)))) { |
| 499 | APInt Mask = ~*RHSC; |
Chuang-Yu Cheng | dbe00d5 | 2016-06-16 04:44:25 +0000 | [diff] [blame] | 500 | if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 501 | // If we already have a value for the switch, it has to match! |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 502 | if (!setValueOnce(RHSVal)) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 503 | return false; |
| 504 | |
| 505 | Vals.push_back(C); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 506 | Vals.push_back( |
Chuang-Yu Cheng | dbe00d5 | 2016-06-16 04:44:25 +0000 | [diff] [blame] | 507 | ConstantInt::get(C->getContext(), |
| 508 | C->getValue() | Mask)); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 509 | UsedICmps++; |
| 510 | return true; |
| 511 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 512 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 513 | |
Chuang-Yu Cheng | 68f7f1c | 2016-06-24 01:59:00 +0000 | [diff] [blame] | 514 | // Pattern match a special case: |
| 515 | /* |
| 516 | QUERY( (y | mask = y) => |
| 517 | ((x | mask = y) <=> (x = y OR x = (y & ~mask))) |
| 518 | ); |
| 519 | */ |
| 520 | if (match(ICI->getOperand(0), |
| 521 | m_Or(m_Value(RHSVal), m_APInt(RHSC)))) { |
| 522 | APInt Mask = *RHSC; |
| 523 | if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) { |
| 524 | // If we already have a value for the switch, it has to match! |
| 525 | if (!setValueOnce(RHSVal)) |
| 526 | return false; |
| 527 | |
| 528 | Vals.push_back(C); |
| 529 | Vals.push_back(ConstantInt::get(C->getContext(), |
| 530 | C->getValue() & ~Mask)); |
| 531 | UsedICmps++; |
| 532 | return true; |
| 533 | } |
| 534 | } |
| 535 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 536 | // If we already have a value for the switch, it has to match! |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 537 | if (!setValueOnce(ICI->getOperand(0))) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 538 | return false; |
| 539 | |
| 540 | UsedICmps++; |
| 541 | Vals.push_back(C); |
| 542 | return ICI->getOperand(0); |
| 543 | } |
| 544 | |
| 545 | // If we have "x ult 3", for example, then we can add 0,1,2 to the set. |
Sanjoy Das | 7182d36 | 2015-03-18 00:41:24 +0000 | [diff] [blame] | 546 | ConstantRange Span = ConstantRange::makeAllowedICmpRegion( |
| 547 | ICI->getPredicate(), C->getValue()); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 548 | |
| 549 | // Shift the range if the compare is fed by an add. This is the range |
| 550 | // compare idiom as emitted by instcombine. |
| 551 | Value *CandidateVal = I->getOperand(0); |
Chuang-Yu Cheng | 5078f94 | 2016-06-17 00:04:39 +0000 | [diff] [blame] | 552 | if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) { |
| 553 | Span = Span.subtract(*RHSC); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 554 | CandidateVal = RHSVal; |
| 555 | } |
| 556 | |
| 557 | // If this is an and/!= check, then we are looking to build the set of |
| 558 | // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into |
| 559 | // x != 0 && x != 1. |
| 560 | if (!isEQ) |
| 561 | Span = Span.inverse(); |
| 562 | |
| 563 | // If there are a ton of values, we don't want to make a ginormous switch. |
| 564 | if (Span.getSetSize().ugt(8) || Span.isEmptySet()) { |
| 565 | return false; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 566 | } |
| 567 | |
| 568 | // If we already have a value for the switch, it has to match! |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 569 | if (!setValueOnce(CandidateVal)) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 570 | return false; |
| 571 | |
| 572 | // Add all values from the range to the set |
| 573 | for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) |
| 574 | Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 575 | |
| 576 | UsedICmps++; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 577 | return true; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 578 | } |
| 579 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 580 | /// Given a potentially 'or'd or 'and'd together collection of icmp |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 581 | /// eq/ne/lt/gt instructions that compare a value against a constant, extract |
| 582 | /// the value being compared, and stick the list constants into the Vals |
| 583 | /// vector. |
| 584 | /// One "Extra" case is allowed to differ from the other. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 585 | void gather(Value *V) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 586 | Instruction *I = dyn_cast<Instruction>(V); |
| 587 | bool isEQ = (I->getOpcode() == Instruction::Or); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 588 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 589 | // Keep a stack (SmallVector for efficiency) for depth-first traversal |
| 590 | SmallVector<Value *, 8> DFT; |
Gerolf Hoflehner | 2432bd0 | 2016-02-03 23:54:25 +0000 | [diff] [blame] | 591 | SmallPtrSet<Value *, 8> Visited; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 592 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 593 | // Initialize |
Gerolf Hoflehner | 2432bd0 | 2016-02-03 23:54:25 +0000 | [diff] [blame] | 594 | Visited.insert(V); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 595 | DFT.push_back(V); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 596 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 597 | while (!DFT.empty()) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 598 | V = DFT.pop_back_val(); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 599 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 600 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 601 | // If it is a || (or && depending on isEQ), process the operands. |
| 602 | if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { |
Gerolf Hoflehner | 2432bd0 | 2016-02-03 23:54:25 +0000 | [diff] [blame] | 603 | if (Visited.insert(I->getOperand(1)).second) |
| 604 | DFT.push_back(I->getOperand(1)); |
| 605 | if (Visited.insert(I->getOperand(0)).second) |
| 606 | DFT.push_back(I->getOperand(0)); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 607 | continue; |
| 608 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 609 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 610 | // Try to match the current instruction |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 611 | if (matchInstruction(I, isEQ)) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 612 | // Match succeed, continue the loop |
| 613 | continue; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 614 | } |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 615 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 616 | // One element of the sequence of || (or &&) could not be match as a |
| 617 | // comparison against the same value as the others. |
| 618 | // We allow only one "Extra" case to be checked before the switch |
| 619 | if (!Extra) { |
| 620 | Extra = V; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 621 | continue; |
| 622 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 623 | // Failed to parse a proper sequence, abort now |
| 624 | CompValue = nullptr; |
| 625 | break; |
Chris Lattner | 5a177e6 | 2010-12-13 04:26:26 +0000 | [diff] [blame] | 626 | } |
Anton Korobeynikov | 1bfd121 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 627 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 628 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 629 | } |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 630 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 631 | static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 632 | Instruction *Cond = nullptr; |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 633 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 634 | Cond = dyn_cast<Instruction>(SI->getCondition()); |
| 635 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 636 | if (BI->isConditional()) |
| 637 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 638 | } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { |
| 639 | Cond = dyn_cast<Instruction>(IBI->getAddress()); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 640 | } |
| 641 | |
| 642 | TI->eraseFromParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 643 | if (Cond) |
| 644 | RecursivelyDeleteTriviallyDeadInstructions(Cond); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 645 | } |
| 646 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 647 | /// Return true if the specified terminator checks |
Chris Lattner | 8e84c12 | 2008-11-27 23:25:44 +0000 | [diff] [blame] | 648 | /// to see if a value is equal to constant integer value. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 649 | Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 650 | Value *CV = nullptr; |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 651 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 652 | // Do not permit merging of large switch instructions into their |
| 653 | // predecessors unless there is only one predecessor. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 654 | if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()), |
| 655 | pred_end(SI->getParent())) <= |
| 656 | 128) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 657 | CV = SI->getCondition(); |
| 658 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 659 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 660 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 661 | if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 662 | CV = ICI->getOperand(0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 663 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 664 | |
| 665 | // Unwrap any lossless ptrtoint cast. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 666 | if (CV) { |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 667 | if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { |
| 668 | Value *Ptr = PTII->getPointerOperand(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 669 | if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 670 | CV = Ptr; |
| 671 | } |
| 672 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 673 | return CV; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 674 | } |
| 675 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 676 | /// Given a value comparison instruction, |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 677 | /// decode all of the 'cases' that it represents and return the 'default' block. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 678 | BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases( |
| 679 | TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 680 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 681 | Cases.reserve(SI->getNumCases()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 682 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; |
| 683 | ++i) |
| 684 | Cases.push_back( |
| 685 | ValueEqualityComparisonCase(i.getCaseValue(), i.getCaseSuccessor())); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 686 | return SI->getDefaultDest(); |
| 687 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 688 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 689 | BranchInst *BI = cast<BranchInst>(TI); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 690 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 691 | BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 692 | Cases.push_back(ValueEqualityComparisonCase( |
| 693 | GetConstantInt(ICI->getOperand(1), DL), Succ)); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 694 | return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 695 | } |
| 696 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 697 | /// Given a vector of bb/value pairs, remove any entries |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 698 | /// in the list that match the specified block. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 699 | static void |
| 700 | EliminateBlockCases(BasicBlock *BB, |
| 701 | std::vector<ValueEqualityComparisonCase> &Cases) { |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 702 | Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 703 | } |
| 704 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 705 | /// Return true if there are any keys in C1 that exist in C2 as well. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 706 | static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, |
| 707 | std::vector<ValueEqualityComparisonCase> &C2) { |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 708 | std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; |
| 709 | |
| 710 | // Make V1 be smaller than V2. |
| 711 | if (V1->size() > V2->size()) |
| 712 | std::swap(V1, V2); |
| 713 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 714 | if (V1->size() == 0) |
| 715 | return false; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 716 | if (V1->size() == 1) { |
| 717 | // Just scan V2. |
| 718 | ConstantInt *TheVal = (*V1)[0].Value; |
| 719 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 720 | if (TheVal == (*V2)[i].Value) |
| 721 | return true; |
| 722 | } |
| 723 | |
| 724 | // Otherwise, just sort both lists and compare element by element. |
| 725 | array_pod_sort(V1->begin(), V1->end()); |
| 726 | array_pod_sort(V2->begin(), V2->end()); |
| 727 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 728 | while (i1 != e1 && i2 != e2) { |
| 729 | if ((*V1)[i1].Value == (*V2)[i2].Value) |
| 730 | return true; |
| 731 | if ((*V1)[i1].Value < (*V2)[i2].Value) |
| 732 | ++i1; |
| 733 | else |
| 734 | ++i2; |
| 735 | } |
| 736 | return false; |
| 737 | } |
| 738 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 739 | /// If TI is known to be a terminator instruction and its block is known to |
| 740 | /// only have a single predecessor block, check to see if that predecessor is |
| 741 | /// also a value comparison with the same value, and if that comparison |
| 742 | /// determines the outcome of this comparison. If so, simplify TI. This does a |
| 743 | /// very limited form of jump threading. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 744 | bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor( |
| 745 | TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) { |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 746 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 747 | if (!PredVal) |
| 748 | return false; // Not a value comparison in predecessor. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 749 | |
| 750 | Value *ThisVal = isValueEqualityComparison(TI); |
| 751 | assert(ThisVal && "This isn't a value comparison!!"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 752 | if (ThisVal != PredVal) |
| 753 | return false; // Different predicates. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 754 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 755 | // TODO: Preserve branch weight metadata, similarly to how |
| 756 | // FoldValueComparisonIntoPredecessors preserves it. |
| 757 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 758 | // Find out information about when control will move from Pred to TI's block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 759 | std::vector<ValueEqualityComparisonCase> PredCases; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 760 | BasicBlock *PredDef = |
| 761 | GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases); |
| 762 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 763 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 764 | // Find information about how control leaves this block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 765 | std::vector<ValueEqualityComparisonCase> ThisCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 766 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 767 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 768 | |
| 769 | // If TI's block is the default block from Pred's comparison, potentially |
| 770 | // simplify TI based on this knowledge. |
| 771 | if (PredDef == TI->getParent()) { |
| 772 | // If we are here, we know that the value is none of those cases listed in |
| 773 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 774 | // can simplify TI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 775 | if (!ValuesOverlap(PredCases, ThisCases)) |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 776 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 777 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 778 | if (isa<BranchInst>(TI)) { |
| 779 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 780 | // uncond br. |
| 781 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 782 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 783 | Instruction *NI = Builder.CreateBr(ThisDef); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 784 | (void)NI; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 785 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 786 | // Remove PHI node entries for the dead edge. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 787 | ThisCases[0].Dest->removePredecessor(TI->getParent()); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 788 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 789 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 790 | << "Through successor TI: " << *TI << "Leaving: " << *NI |
| 791 | << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 792 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 793 | EraseTerminatorInstAndDCECond(TI); |
| 794 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 795 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 796 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 797 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 798 | // Okay, TI has cases that are statically dead, prune them away. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 799 | SmallPtrSet<Constant *, 16> DeadCases; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 800 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 801 | DeadCases.insert(PredCases[i].Value); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 802 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 803 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 804 | << "Through successor TI: " << *TI); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 805 | |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 806 | // Collect branch weights into a vector. |
| 807 | SmallVector<uint32_t, 8> Weights; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 808 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 809 | bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); |
| 810 | if (HasWeight) |
| 811 | for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| 812 | ++MD_i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 813 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 814 | Weights.push_back(CI->getValue().getZExtValue()); |
| 815 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 816 | for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { |
| 817 | --i; |
| 818 | if (DeadCases.count(i.getCaseValue())) { |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 819 | if (HasWeight) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 820 | std::swap(Weights[i.getCaseIndex() + 1], Weights.back()); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 821 | Weights.pop_back(); |
| 822 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 823 | i.getCaseSuccessor()->removePredecessor(TI->getParent()); |
| 824 | SI->removeCase(i); |
| 825 | } |
| 826 | } |
Manman Ren | 97c1876 | 2012-10-11 22:28:34 +0000 | [diff] [blame] | 827 | if (HasWeight && Weights.size() >= 2) |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 828 | SI->setMetadata(LLVMContext::MD_prof, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 829 | MDBuilder(SI->getParent()->getContext()) |
| 830 | .createBranchWeights(Weights)); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 831 | |
| 832 | DEBUG(dbgs() << "Leaving: " << *TI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 833 | return true; |
| 834 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 835 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 836 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 837 | // which value (or set of values) this is. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 838 | ConstantInt *TIV = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 839 | BasicBlock *TIBB = TI->getParent(); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 840 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 841 | if (PredCases[i].Dest == TIBB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 842 | if (TIV) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 843 | return false; // Cannot handle multiple values coming to this block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 844 | TIV = PredCases[i].Value; |
| 845 | } |
| 846 | assert(TIV && "No edge from pred to succ?"); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 847 | |
| 848 | // Okay, we found the one constant that our value can be if we get into TI's |
| 849 | // BB. Find out which successor will unconditionally be branched to. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 850 | BasicBlock *TheRealDest = nullptr; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 851 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 852 | if (ThisCases[i].Value == TIV) { |
| 853 | TheRealDest = ThisCases[i].Dest; |
| 854 | break; |
| 855 | } |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 856 | |
| 857 | // If not handled by any explicit cases, it is handled by the default case. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 858 | if (!TheRealDest) |
| 859 | TheRealDest = ThisDef; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 860 | |
| 861 | // Remove PHI node entries for dead edges. |
| 862 | BasicBlock *CheckEdge = TheRealDest; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 863 | for (BasicBlock *Succ : successors(TIBB)) |
| 864 | if (Succ != CheckEdge) |
| 865 | Succ->removePredecessor(TIBB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 866 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 867 | CheckEdge = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 868 | |
| 869 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 870 | Instruction *NI = Builder.CreateBr(TheRealDest); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 871 | (void)NI; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 872 | |
| 873 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 874 | << "Through successor TI: " << *TI << "Leaving: " << *NI |
| 875 | << "\n"); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 876 | |
| 877 | EraseTerminatorInstAndDCECond(TI); |
| 878 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 879 | } |
| 880 | |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 881 | namespace { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 882 | /// This class implements a stable ordering of constant |
| 883 | /// integers that does not depend on their address. This is important for |
| 884 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 885 | struct ConstantIntOrdering { |
| 886 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| 887 | return LHS->getValue().ult(RHS->getValue()); |
| 888 | } |
| 889 | }; |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 890 | } |
Dale Johannesen | 5a41b2d | 2009-03-12 01:00:26 +0000 | [diff] [blame] | 891 | |
Benjamin Kramer | 8817cca | 2013-09-22 14:09:50 +0000 | [diff] [blame] | 892 | static int ConstantIntSortPredicate(ConstantInt *const *P1, |
| 893 | ConstantInt *const *P2) { |
| 894 | const ConstantInt *LHS = *P1; |
| 895 | const ConstantInt *RHS = *P2; |
Benjamin Kramer | 7d537ae | 2016-02-20 10:40:42 +0000 | [diff] [blame] | 896 | if (LHS == RHS) |
Chris Lattner | e893e26 | 2010-12-15 04:52:41 +0000 | [diff] [blame] | 897 | return 0; |
Benjamin Kramer | 7d537ae | 2016-02-20 10:40:42 +0000 | [diff] [blame] | 898 | return LHS->getValue().ult(RHS->getValue()) ? 1 : -1; |
Chris Lattner | 7c8e604 | 2010-12-13 02:00:58 +0000 | [diff] [blame] | 899 | } |
| 900 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 901 | static inline bool HasBranchWeights(const Instruction *I) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 902 | MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 903 | if (ProfMD && ProfMD->getOperand(0)) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 904 | if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 905 | return MDS->getString().equals("branch_weights"); |
| 906 | |
| 907 | return false; |
| 908 | } |
| 909 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 910 | /// Get Weights of a given TerminatorInst, the default weight is at the front |
| 911 | /// of the vector. If TI is a conditional eq, we need to swap the branch-weight |
| 912 | /// metadata. |
| 913 | static void GetBranchWeights(TerminatorInst *TI, |
| 914 | SmallVectorImpl<uint64_t> &Weights) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 915 | MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 916 | assert(MD); |
| 917 | for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 918 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 919 | Weights.push_back(CI->getValue().getZExtValue()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 920 | } |
| 921 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 922 | // If TI is a conditional eq, the default case is the false case, |
| 923 | // and the corresponding branch-weight data is at index 2. We swap the |
| 924 | // default weight to be the first entry. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 925 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 926 | assert(Weights.size() == 2); |
| 927 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| 928 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 929 | std::swap(Weights.front(), Weights.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 930 | } |
| 931 | } |
| 932 | |
Sanjay Patel | 84a0bf6 | 2016-05-06 17:51:37 +0000 | [diff] [blame] | 933 | /// Keep halving the weights until all can fit in uint32_t. |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 934 | static void FitWeights(MutableArrayRef<uint64_t> Weights) { |
Benjamin Kramer | 79da941 | 2014-03-09 14:42:55 +0000 | [diff] [blame] | 935 | uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); |
| 936 | if (Max > UINT_MAX) { |
| 937 | unsigned Offset = 32 - countLeadingZeros(Max); |
| 938 | for (uint64_t &I : Weights) |
| 939 | I >>= Offset; |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 940 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 941 | } |
| 942 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 943 | /// The specified terminator is a value equality comparison instruction |
| 944 | /// (either a switch or a branch on "X == c"). |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 945 | /// See if any of the predecessors of the terminator block are value comparisons |
| 946 | /// on the same value. If so, and if safe to do so, fold them together. |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 947 | bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 948 | IRBuilder<> &Builder) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 949 | BasicBlock *BB = TI->getParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 950 | Value *CV = isValueEqualityComparison(TI); // CondVal |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 951 | assert(CV && "Not a comparison?"); |
| 952 | bool Changed = false; |
| 953 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 954 | SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 955 | while (!Preds.empty()) { |
Dan Gohman | 9a6fef0 | 2009-05-06 17:22:41 +0000 | [diff] [blame] | 956 | BasicBlock *Pred = Preds.pop_back_val(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 957 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 958 | // See if the predecessor is a comparison with the same value. |
| 959 | TerminatorInst *PTI = Pred->getTerminator(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 960 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 961 | |
James Molloy | 8e69b03 | 2016-08-31 10:46:39 +0000 | [diff] [blame] | 962 | if (PCV == CV && TI != PTI) { |
| 963 | std::vector<BasicBlock*> FailBlocks; |
| 964 | if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) { |
| 965 | for (auto *Succ : FailBlocks) { |
| 966 | std::vector<BasicBlock*> Blocks = { TI->getParent() }; |
| 967 | if (!SplitBlockPredecessors(Succ, Blocks, ".fold.split")) |
| 968 | return false; |
| 969 | } |
| 970 | } |
| 971 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 972 | // Figure out which 'cases' to copy from SI to PSI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 973 | std::vector<ValueEqualityComparisonCase> BBCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 974 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 975 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 976 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 977 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 978 | |
| 979 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 980 | // PredCases and PredDefault with the new switch cases we would like to |
| 981 | // build. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 982 | SmallVector<BasicBlock *, 8> NewSuccessors; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 983 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 984 | // Update the branch weight metadata along the way |
| 985 | SmallVector<uint64_t, 8> Weights; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 986 | bool PredHasWeights = HasBranchWeights(PTI); |
| 987 | bool SuccHasWeights = HasBranchWeights(TI); |
| 988 | |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 989 | if (PredHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 990 | GetBranchWeights(PTI, Weights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 991 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 992 | if (Weights.size() != 1 + PredCases.size()) |
| 993 | PredHasWeights = SuccHasWeights = false; |
| 994 | } else if (SuccHasWeights) |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 995 | // If there are no predecessor weights but there are successor weights, |
| 996 | // populate Weights with 1, which will later be scaled to the sum of |
| 997 | // successor's weights |
| 998 | Weights.assign(1 + PredCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 999 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1000 | SmallVector<uint64_t, 8> SuccWeights; |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 1001 | if (SuccHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1002 | GetBranchWeights(TI, SuccWeights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 1003 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 1004 | if (SuccWeights.size() != 1 + BBCases.size()) |
| 1005 | PredHasWeights = SuccHasWeights = false; |
| 1006 | } else if (PredHasWeights) |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1007 | SuccWeights.assign(1 + BBCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1008 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1009 | if (PredDefault == BB) { |
| 1010 | // If this is the default destination from PTI, only the edges in TI |
| 1011 | // that don't occur in PTI, or that branch to BB will be activated. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1012 | std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1013 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 1014 | if (PredCases[i].Dest != BB) |
| 1015 | PTIHandled.insert(PredCases[i].Value); |
| 1016 | else { |
| 1017 | // The default destination is BB, we don't need explicit targets. |
| 1018 | std::swap(PredCases[i], PredCases.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1019 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1020 | if (PredHasWeights || SuccHasWeights) { |
| 1021 | // Increase weight for the default case. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1022 | Weights[0] += Weights[i + 1]; |
| 1023 | std::swap(Weights[i + 1], Weights.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1024 | Weights.pop_back(); |
| 1025 | } |
| 1026 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1027 | PredCases.pop_back(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1028 | --i; |
| 1029 | --e; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1030 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1031 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1032 | // Reconstruct the new switch statement we will be building. |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1033 | if (PredDefault != BBDefault) { |
| 1034 | PredDefault->removePredecessor(Pred); |
| 1035 | PredDefault = BBDefault; |
| 1036 | NewSuccessors.push_back(BBDefault); |
| 1037 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1038 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1039 | unsigned CasesFromPred = Weights.size(); |
| 1040 | uint64_t ValidTotalSuccWeight = 0; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1041 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 1042 | if (!PTIHandled.count(BBCases[i].Value) && |
| 1043 | BBCases[i].Dest != BBDefault) { |
| 1044 | PredCases.push_back(BBCases[i]); |
| 1045 | NewSuccessors.push_back(BBCases[i].Dest); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1046 | if (SuccHasWeights || PredHasWeights) { |
| 1047 | // The default weight is at index 0, so weight for the ith case |
| 1048 | // should be at index i+1. Scale the cases from successor by |
| 1049 | // PredDefaultWeight (Weights[0]). |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1050 | Weights.push_back(Weights[0] * SuccWeights[i + 1]); |
| 1051 | ValidTotalSuccWeight += SuccWeights[i + 1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1052 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1053 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1054 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 1055 | if (SuccHasWeights || PredHasWeights) { |
| 1056 | ValidTotalSuccWeight += SuccWeights[0]; |
| 1057 | // Scale the cases from predecessor by ValidTotalSuccWeight. |
| 1058 | for (unsigned i = 1; i < CasesFromPred; ++i) |
| 1059 | Weights[i] *= ValidTotalSuccWeight; |
| 1060 | // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). |
| 1061 | Weights[0] *= SuccWeights[0]; |
| 1062 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1063 | } else { |
| 1064 | // If this is not the default destination from PSI, only the edges |
| 1065 | // in SI that occur in PSI with a destination of BB will be |
| 1066 | // activated. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1067 | std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; |
| 1068 | std::map<ConstantInt *, uint64_t> WeightsForHandled; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1069 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 1070 | if (PredCases[i].Dest == BB) { |
| 1071 | PTIHandled.insert(PredCases[i].Value); |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 1072 | |
| 1073 | if (PredHasWeights || SuccHasWeights) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1074 | WeightsForHandled[PredCases[i].Value] = Weights[i + 1]; |
| 1075 | std::swap(Weights[i + 1], Weights.back()); |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 1076 | Weights.pop_back(); |
| 1077 | } |
| 1078 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1079 | std::swap(PredCases[i], PredCases.back()); |
| 1080 | PredCases.pop_back(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1081 | --i; |
| 1082 | --e; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1083 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1084 | |
| 1085 | // Okay, now we know which constants were sent to BB from the |
| 1086 | // predecessor. Figure out where they will all go now. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1087 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 1088 | if (PTIHandled.count(BBCases[i].Value)) { |
| 1089 | // If this is one we are capable of getting... |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 1090 | if (PredHasWeights || SuccHasWeights) |
| 1091 | Weights.push_back(WeightsForHandled[BBCases[i].Value]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1092 | PredCases.push_back(BBCases[i]); |
| 1093 | NewSuccessors.push_back(BBCases[i].Dest); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1094 | PTIHandled.erase( |
| 1095 | BBCases[i].Value); // This constant is taken care of |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1096 | } |
| 1097 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1098 | // If there are any constants vectored to BB that TI doesn't handle, |
| 1099 | // they must go to the default destination of TI. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1100 | for (ConstantInt *I : PTIHandled) { |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1101 | if (PredHasWeights || SuccHasWeights) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1102 | Weights.push_back(WeightsForHandled[I]); |
| 1103 | PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1104 | NewSuccessors.push_back(BBDefault); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1105 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1106 | } |
| 1107 | |
| 1108 | // Okay, at this point, we know which new successor Pred will get. Make |
| 1109 | // sure we update the number of entries in the PHI nodes for these |
| 1110 | // successors. |
Sanjay Patel | f4b34b7 | 2015-09-10 16:25:38 +0000 | [diff] [blame] | 1111 | for (BasicBlock *NewSuccessor : NewSuccessors) |
| 1112 | AddPredecessorToBlock(NewSuccessor, Pred, BB); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1113 | |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 1114 | Builder.SetInsertPoint(PTI); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 1115 | // Convert pointer to int before we switch. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 1116 | if (CV->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1117 | CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 1118 | "magicptr"); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 1119 | } |
| 1120 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1121 | // Now that the successors are updated, create the new Switch instruction. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1122 | SwitchInst *NewSI = |
| 1123 | Builder.CreateSwitch(CV, PredDefault, PredCases.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 1124 | NewSI->setDebugLoc(PTI->getDebugLoc()); |
Sanjay Patel | 5e7bd91 | 2015-09-10 16:15:21 +0000 | [diff] [blame] | 1125 | for (ValueEqualityComparisonCase &V : PredCases) |
| 1126 | NewSI->addCase(V.Value, V.Dest); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1127 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1128 | if (PredHasWeights || SuccHasWeights) { |
| 1129 | // Halve the weights if any of them cannot fit in an uint32_t |
| 1130 | FitWeights(Weights); |
| 1131 | |
| 1132 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 1133 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1134 | NewSI->setMetadata( |
| 1135 | LLVMContext::MD_prof, |
| 1136 | MDBuilder(BB->getContext()).createBranchWeights(MDWeights)); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1137 | } |
| 1138 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1139 | EraseTerminatorInstAndDCECond(PTI); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1140 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1141 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 1142 | // have an infinite loop case. If so, add an infinitely looping block |
| 1143 | // to handle the case to preserve the behavior of the code. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1144 | BasicBlock *InfLoopBlock = nullptr; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1145 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 1146 | if (NewSI->getSuccessor(i) == BB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1147 | if (!InfLoopBlock) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 1148 | // Insert it at the end of the function, because it's either code, |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1149 | // or it won't matter if it's hot. :) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1150 | InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop", |
| 1151 | BB->getParent()); |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1152 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1153 | } |
| 1154 | NewSI->setSuccessor(i, InfLoopBlock); |
| 1155 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1156 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1157 | Changed = true; |
| 1158 | } |
| 1159 | } |
| 1160 | return Changed; |
| 1161 | } |
| 1162 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1163 | // If we would need to insert a select that uses the value of this invoke |
| 1164 | // (comments in HoistThenElseCodeToIf explain why we would need to do this), we |
| 1165 | // can't hoist the invoke, as there is nowhere to put the select in this case. |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1166 | static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, |
| 1167 | Instruction *I1, Instruction *I2) { |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1168 | for (BasicBlock *Succ : successors(BB1)) { |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1169 | PHINode *PN; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1170 | for (BasicBlock::iterator BBI = Succ->begin(); |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1171 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1172 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1173 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1174 | if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) { |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1175 | return false; |
| 1176 | } |
| 1177 | } |
| 1178 | } |
| 1179 | return true; |
| 1180 | } |
| 1181 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1182 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); |
| 1183 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1184 | /// Given a conditional branch that goes to BB1 and BB2, hoist any common code |
| 1185 | /// in the two blocks up into the branch block. The caller of this function |
| 1186 | /// guarantees that BI's block dominates BB1 and BB2. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1187 | static bool HoistThenElseCodeToIf(BranchInst *BI, |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1188 | const TargetTransformInfo &TTI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1189 | // This does very trivial matching, with limited scanning, to find identical |
| 1190 | // instructions in the two blocks. In particular, we don't want to get into |
| 1191 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 1192 | // such, we currently just scan for obviously identical instructions in an |
| 1193 | // identical order. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1194 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 1195 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1196 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1197 | BasicBlock::iterator BB1_Itr = BB1->begin(); |
| 1198 | BasicBlock::iterator BB2_Itr = BB2->begin(); |
| 1199 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1200 | Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1201 | // Skip debug info if it is not identical. |
| 1202 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1203 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1204 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1205 | while (isa<DbgInfoIntrinsic>(I1)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1206 | I1 = &*BB1_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1207 | while (isa<DbgInfoIntrinsic>(I2)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1208 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1209 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1210 | if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1211 | (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1212 | return false; |
| 1213 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1214 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1215 | |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1216 | bool Changed = false; |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1217 | do { |
| 1218 | // If we are hoisting the terminator instruction, don't move one (making a |
| 1219 | // broken BB), instead clone it, and remove BI. |
| 1220 | if (isa<TerminatorInst>(I1)) |
| 1221 | goto HoistTerminator; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1222 | |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1223 | if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) |
| 1224 | return Changed; |
| 1225 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1226 | // For a normal instruction, we just move one to right before the branch, |
| 1227 | // then replace all uses of the other with the first. Finally, we remove |
| 1228 | // the now redundant second instruction. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1229 | BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1230 | if (!I2->use_empty()) |
| 1231 | I2->replaceAllUsesWith(I1); |
Dan Gohman | c8a27f2 | 2009-08-25 22:11:20 +0000 | [diff] [blame] | 1232 | I1->intersectOptionalDataWith(I2); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1233 | unsigned KnownIDs[] = {LLVMContext::MD_tbaa, |
| 1234 | LLVMContext::MD_range, |
| 1235 | LLVMContext::MD_fpmath, |
| 1236 | LLVMContext::MD_invariant_load, |
| 1237 | LLVMContext::MD_nonnull, |
| 1238 | LLVMContext::MD_invariant_group, |
| 1239 | LLVMContext::MD_align, |
| 1240 | LLVMContext::MD_dereferenceable, |
| 1241 | LLVMContext::MD_dereferenceable_or_null, |
| 1242 | LLVMContext::MD_mem_parallel_loop_access}; |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1243 | combineMetadata(I1, I2, KnownIDs); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1244 | I2->eraseFromParent(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1245 | Changed = true; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1246 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1247 | I1 = &*BB1_Itr++; |
| 1248 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1249 | // Skip debug info if it is not identical. |
| 1250 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1251 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1252 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1253 | while (isa<DbgInfoIntrinsic>(I1)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1254 | I1 = &*BB1_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1255 | while (isa<DbgInfoIntrinsic>(I2)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1256 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1257 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1258 | } while (I1->isIdenticalToWhenDefined(I2)); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1259 | |
| 1260 | return true; |
| 1261 | |
| 1262 | HoistTerminator: |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1263 | // It may not be possible to hoist an invoke. |
| 1264 | if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1265 | return Changed; |
| 1266 | |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1267 | for (BasicBlock *Succ : successors(BB1)) { |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1268 | PHINode *PN; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1269 | for (BasicBlock::iterator BBI = Succ->begin(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1270 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1271 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1272 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1273 | if (BB1V == BB2V) |
| 1274 | continue; |
| 1275 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1276 | // Check for passingValueIsAlwaysUndefined here because we would rather |
| 1277 | // eliminate undefined control flow then converting it to a select. |
| 1278 | if (passingValueIsAlwaysUndefined(BB1V, PN) || |
| 1279 | passingValueIsAlwaysUndefined(BB2V, PN)) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1280 | return Changed; |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1281 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1282 | if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1283 | return Changed; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1284 | if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1285 | return Changed; |
| 1286 | } |
| 1287 | } |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1288 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1289 | // Okay, it is safe to hoist the terminator. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 1290 | Instruction *NT = I1->clone(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1291 | BIParent->getInstList().insert(BI->getIterator(), NT); |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1292 | if (!NT->getType()->isVoidTy()) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1293 | I1->replaceAllUsesWith(NT); |
| 1294 | I2->replaceAllUsesWith(NT); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1295 | NT->takeName(I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1296 | } |
| 1297 | |
Mehdi Amini | ba9fba8 | 2016-03-13 21:05:13 +0000 | [diff] [blame] | 1298 | IRBuilder<NoFolder> Builder(NT); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1299 | // Hoisting one of the terminators from our successor is a great thing. |
| 1300 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 1301 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 1302 | // nodes, so we insert select instruction to compute the final result. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1303 | std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1304 | for (BasicBlock *Succ : successors(BB1)) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1305 | PHINode *PN; |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1306 | for (BasicBlock::iterator BBI = Succ->begin(); |
Chris Lattner | 0194457 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 1307 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1308 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1309 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1310 | if (BB1V == BB2V) |
| 1311 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1312 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1313 | // These values do not agree. Insert a select instruction before NT |
| 1314 | // that determines the right value. |
| 1315 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1316 | if (!SI) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1317 | SI = cast<SelectInst>( |
| 1318 | Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, |
| 1319 | BB1V->getName() + "." + BB2V->getName(), BI)); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1320 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1321 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 1322 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 1323 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 1324 | PN->setIncomingValue(i, SI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | // Update any PHI nodes in our new successors. |
Sanjay Patel | 5781d84 | 2016-03-12 16:52:17 +0000 | [diff] [blame] | 1329 | for (BasicBlock *Succ : successors(BB1)) |
| 1330 | AddPredecessorToBlock(Succ, BIParent, BB1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1331 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1332 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1333 | return true; |
| 1334 | } |
| 1335 | |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1336 | // Is it legal to place a variable in operand \c OpIdx of \c I? |
| 1337 | // FIXME: This should be promoted to Instruction. |
| 1338 | static bool canReplaceOperandWithVariable(const Instruction *I, |
| 1339 | unsigned OpIdx) { |
| 1340 | // Early exit. |
| 1341 | if (!isa<Constant>(I->getOperand(OpIdx))) |
| 1342 | return true; |
| 1343 | |
| 1344 | switch (I->getOpcode()) { |
| 1345 | default: |
| 1346 | return true; |
| 1347 | case Instruction::Call: |
| 1348 | case Instruction::Invoke: |
| 1349 | // FIXME: many arithmetic intrinsics have no issue taking a |
| 1350 | // variable, however it's hard to distingish these from |
| 1351 | // specials such as @llvm.frameaddress that require a constant. |
| 1352 | return !isa<IntrinsicInst>(I); |
| 1353 | case Instruction::ShuffleVector: |
| 1354 | // Shufflevector masks are constant. |
| 1355 | return OpIdx != 2; |
| 1356 | case Instruction::ExtractValue: |
| 1357 | case Instruction::InsertValue: |
| 1358 | // All operands apart from the first are constant. |
| 1359 | return OpIdx == 0; |
| 1360 | case Instruction::Alloca: |
| 1361 | return false; |
| 1362 | case Instruction::GetElementPtr: |
| 1363 | if (OpIdx == 0) |
| 1364 | return true; |
| 1365 | gep_type_iterator It = std::next(gep_type_begin(I), OpIdx - 1); |
| 1366 | return !It->isStructTy(); |
| 1367 | } |
| 1368 | } |
| 1369 | |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1370 | // All instructions in Insts belong to different blocks that all unconditionally |
| 1371 | // branch to a common successor. Analyze each instruction and return true if it |
| 1372 | // would be possible to sink them into their successor, creating one common |
| 1373 | // instruction instead. For every value that would be required to be provided by |
| 1374 | // PHI node (because an operand varies in each input block), add to PHIOperands. |
| 1375 | static bool canSinkInstructions( |
| 1376 | ArrayRef<Instruction *> Insts, |
| 1377 | DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) { |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1378 | // Prune out obviously bad instructions to move. Any non-store instruction |
| 1379 | // must have exactly one use, and we check later that use is by a single, |
| 1380 | // common PHI instruction in the successor. |
| 1381 | for (auto *I : Insts) { |
| 1382 | // These instructions may change or break semantics if moved. |
| 1383 | if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || |
| 1384 | I->getType()->isTokenTy()) |
| 1385 | return false; |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1386 | // Everything must have only one use too, apart from stores which |
| 1387 | // have no uses. |
| 1388 | if (!isa<StoreInst>(I) && !I->hasOneUse()) |
| 1389 | return false; |
| 1390 | } |
| 1391 | |
| 1392 | const Instruction *I0 = Insts.front(); |
| 1393 | for (auto *I : Insts) |
| 1394 | if (!I->isSameOperationAs(I0)) |
| 1395 | return false; |
| 1396 | |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1397 | // All instructions in Insts are known to be the same opcode. If they aren't |
| 1398 | // stores, check the only user of each is a PHI or in the same block as the |
| 1399 | // instruction, because if a user is in the same block as an instruction |
| 1400 | // we're contemplating sinking, it must already be determined to be sinkable. |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1401 | if (!isa<StoreInst>(I0)) { |
| 1402 | auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1403 | if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool { |
| 1404 | auto *U = cast<Instruction>(*I->user_begin()); |
| 1405 | return U == PNUse || U->getParent() == I->getParent(); |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1406 | })) |
| 1407 | return false; |
| 1408 | } |
| 1409 | |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1410 | for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) { |
| 1411 | if (I0->getOperand(OI)->getType()->isTokenTy()) |
| 1412 | // Don't touch any operand of token type. |
| 1413 | return false; |
| 1414 | auto SameAsI0 = [&I0, OI](const Instruction *I) { |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1415 | assert(I->getNumOperands() == I0->getNumOperands()); |
| 1416 | return I->getOperand(OI) == I0->getOperand(OI); |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1417 | }; |
| 1418 | if (!all_of(Insts, SameAsI0)) { |
| 1419 | if (!canReplaceOperandWithVariable(I0, OI)) |
| 1420 | // We can't create a PHI from this GEP. |
| 1421 | return false; |
James Molloy | 923e98c | 2016-08-31 10:46:16 +0000 | [diff] [blame] | 1422 | // Don't create indirect calls! The called value is the final operand. |
| 1423 | if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) { |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1424 | // FIXME: if the call was *already* indirect, we should do this. |
| 1425 | return false; |
James Molloy | 923e98c | 2016-08-31 10:46:16 +0000 | [diff] [blame] | 1426 | } |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1427 | for (auto *I : Insts) |
| 1428 | PHIOperands[I].push_back(I->getOperand(OI)); |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1429 | } |
| 1430 | } |
| 1431 | return true; |
| 1432 | } |
| 1433 | |
| 1434 | // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last |
| 1435 | // instruction of every block in Blocks to their common successor, commoning |
| 1436 | // into one instruction. |
James Molloy | 8a66a39 | 2016-08-31 13:16:30 +0000 | [diff] [blame] | 1437 | static void sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) { |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1438 | auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0); |
| 1439 | |
| 1440 | // canSinkLastInstruction returning true guarantees that every block has at |
| 1441 | // least one non-terminator instruction. |
| 1442 | SmallVector<Instruction*,4> Insts; |
| 1443 | for (auto *BB : Blocks) |
| 1444 | Insts.push_back(BB->getTerminator()->getPrevNode()); |
| 1445 | |
James Molloy | 8a66a39 | 2016-08-31 13:16:30 +0000 | [diff] [blame] | 1446 | // We don't need to do any checking here; canSinkLastInstruction should have |
| 1447 | // done it all for us. |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1448 | Instruction *I0 = Insts.front(); |
| 1449 | SmallVector<Value*, 4> NewOperands; |
| 1450 | for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { |
| 1451 | // This check is different to that in canSinkLastInstruction. There, we |
| 1452 | // cared about the global view once simplifycfg (and instcombine) have |
| 1453 | // completed - it takes into account PHIs that become trivially |
| 1454 | // simplifiable. However here we need a more local view; if an operand |
| 1455 | // differs we create a PHI and rely on instcombine to clean up the very |
| 1456 | // small mess we may make. |
| 1457 | bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) { |
| 1458 | return I->getOperand(O) != I0->getOperand(O); |
| 1459 | }); |
| 1460 | if (!NeedPHI) { |
| 1461 | NewOperands.push_back(I0->getOperand(O)); |
| 1462 | continue; |
| 1463 | } |
| 1464 | |
| 1465 | // Create a new PHI in the successor block and populate it. |
| 1466 | auto *Op = I0->getOperand(O); |
| 1467 | assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); |
| 1468 | auto *PN = PHINode::Create(Op->getType(), Insts.size(), |
| 1469 | Op->getName() + ".sink", &BBEnd->front()); |
| 1470 | for (auto *I : Insts) |
| 1471 | PN->addIncoming(I->getOperand(O), I->getParent()); |
| 1472 | NewOperands.push_back(PN); |
| 1473 | } |
| 1474 | |
| 1475 | // Arbitrarily use I0 as the new "common" instruction; remap its operands |
| 1476 | // and move it to the start of the successor block. |
| 1477 | for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) |
| 1478 | I0->getOperandUse(O).set(NewOperands[O]); |
| 1479 | I0->moveBefore(&*BBEnd->getFirstInsertionPt()); |
| 1480 | |
James Molloy | d13b123 | 2016-08-30 10:56:08 +0000 | [diff] [blame] | 1481 | // Update metadata. |
| 1482 | for (auto *I : Insts) |
| 1483 | if (I != I0) |
| 1484 | combineMetadataForCSE(I0, I); |
| 1485 | |
James Molloy | 5bf2114 | 2016-08-22 19:07:15 +0000 | [diff] [blame] | 1486 | if (!isa<StoreInst>(I0)) { |
| 1487 | // canSinkLastInstruction checked that all instructions were used by |
| 1488 | // one and only one PHI node. Find that now, RAUW it to our common |
| 1489 | // instruction and nuke it. |
| 1490 | assert(I0->hasOneUse()); |
| 1491 | auto *PN = cast<PHINode>(*I0->user_begin()); |
| 1492 | PN->replaceAllUsesWith(I0); |
| 1493 | PN->eraseFromParent(); |
| 1494 | } |
| 1495 | |
| 1496 | // Finally nuke all instructions apart from the common instruction. |
| 1497 | for (auto *I : Insts) |
| 1498 | if (I != I0) |
| 1499 | I->eraseFromParent(); |
| 1500 | } |
| 1501 | |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1502 | namespace { |
| 1503 | // LockstepReverseIterator - Iterates through instructions |
| 1504 | // in a set of blocks in reverse order from the first non-terminator. |
| 1505 | // For example (assume all blocks have size n): |
| 1506 | // LockstepReverseIterator I([B1, B2, B3]); |
| 1507 | // *I-- = [B1[n], B2[n], B3[n]]; |
| 1508 | // *I-- = [B1[n-1], B2[n-1], B3[n-1]]; |
| 1509 | // *I-- = [B1[n-2], B2[n-2], B3[n-2]]; |
| 1510 | // ... |
| 1511 | class LockstepReverseIterator { |
| 1512 | ArrayRef<BasicBlock*> Blocks; |
| 1513 | SmallVector<Instruction*,4> Insts; |
| 1514 | bool Fail; |
| 1515 | public: |
| 1516 | LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : |
| 1517 | Blocks(Blocks) { |
| 1518 | reset(); |
| 1519 | } |
| 1520 | |
| 1521 | void reset() { |
| 1522 | Fail = false; |
| 1523 | Insts.clear(); |
| 1524 | for (auto *BB : Blocks) { |
| 1525 | if (BB->size() <= 1) { |
| 1526 | // Block wasn't big enough |
| 1527 | Fail = true; |
| 1528 | return; |
| 1529 | } |
| 1530 | Insts.push_back(BB->getTerminator()->getPrevNode()); |
| 1531 | } |
| 1532 | } |
| 1533 | |
| 1534 | bool isValid() const { |
| 1535 | return !Fail; |
| 1536 | } |
| 1537 | |
| 1538 | void operator -- () { |
| 1539 | if (Fail) |
| 1540 | return; |
| 1541 | for (auto *&Inst : Insts) { |
| 1542 | if (Inst == &Inst->getParent()->front()) { |
| 1543 | Fail = true; |
| 1544 | return; |
| 1545 | } |
| 1546 | Inst = Inst->getPrevNode(); |
| 1547 | } |
| 1548 | } |
| 1549 | |
| 1550 | ArrayRef<Instruction*> operator * () const { |
| 1551 | return Insts; |
| 1552 | } |
| 1553 | }; |
| 1554 | } |
| 1555 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1556 | /// Given an unconditional branch that goes to BBEnd, |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1557 | /// check whether BBEnd has only two predecessors and the other predecessor |
| 1558 | /// ends with an unconditional branch. If it is true, sink any common code |
| 1559 | /// in the two predecessors to BBEnd. |
| 1560 | static bool SinkThenElseCodeToEnd(BranchInst *BI1) { |
| 1561 | assert(BI1->isUnconditional()); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1562 | BasicBlock *BBEnd = BI1->getSuccessor(0); |
| 1563 | |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1564 | // We currently only support branch targets with two predecessors. |
| 1565 | // FIXME: this is an arbitrary restriction and should be lifted. |
| 1566 | SmallVector<BasicBlock*,4> Blocks; |
| 1567 | for (auto *BB : predecessors(BBEnd)) |
| 1568 | Blocks.push_back(BB); |
| 1569 | if (Blocks.size() != 2 || |
| 1570 | !all_of(Blocks, [](const BasicBlock *BB) { |
| 1571 | auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 1572 | return BI && BI->isUnconditional(); |
| 1573 | })) |
James Molloy | 475f4a7 | 2016-08-22 18:13:12 +0000 | [diff] [blame] | 1574 | return false; |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1575 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1576 | bool Changed = false; |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1577 | |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1578 | // We take a two-step approach to tail sinking. First we scan from the end of |
| 1579 | // each block upwards in lockstep. If the n'th instruction from the end of each |
| 1580 | // block can be sunk, those instructions are added to ValuesToSink and we |
| 1581 | // carry on. If we can sink an instruction but need to PHI-merge some operands |
| 1582 | // (because they're not identical in each instruction) we add these to |
| 1583 | // PHIOperands. |
| 1584 | unsigned ScanIdx = 0; |
| 1585 | SmallPtrSet<Value*,4> InstructionsToSink; |
| 1586 | DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands; |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1587 | LockstepReverseIterator LRI(Blocks); |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1588 | while (LRI.isValid() && |
| 1589 | canSinkInstructions(*LRI, PHIOperands)) { |
James Molloy | 8a66a39 | 2016-08-31 13:16:30 +0000 | [diff] [blame] | 1590 | DEBUG(dbgs() << "SINK: instruction can be sunk: " << (*LRI)[0] << "\n"); |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1591 | InstructionsToSink.insert((*LRI).begin(), (*LRI).end()); |
| 1592 | ++ScanIdx; |
| 1593 | --LRI; |
| 1594 | } |
| 1595 | |
| 1596 | // Now that we've analyzed all potential sinking candidates, perform the |
| 1597 | // actual sink. We iteratively sink the last non-terminator of the source |
| 1598 | // blocks into their common successor unless doing so would require too |
| 1599 | // many PHI instructions to be generated (currently only one PHI is allowed |
| 1600 | // per sunk instruction). |
| 1601 | // |
| 1602 | // We can use InstructionsToSink to discount values needing PHI-merging that will |
| 1603 | // actually be sunk in a later iteration. This allows us to be more |
| 1604 | // aggressive in what we sink. This does allow a false positive where we |
| 1605 | // sink presuming a later value will also be sunk, but stop half way through |
| 1606 | // and never actually sink it which means we produce more PHIs than intended. |
| 1607 | // This is unlikely in practice though. |
| 1608 | for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) { |
| 1609 | DEBUG(dbgs() << "SINK: Sink: " |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1610 | << *Blocks[0]->getTerminator()->getPrevNode() |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1611 | << "\n"); |
| 1612 | // Because we've sunk every instruction in turn, the current instruction to |
| 1613 | // sink is always at index 0. |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1614 | LRI.reset(); |
| 1615 | unsigned NumPHIdValues = 0; |
| 1616 | for (auto *I : *LRI) |
| 1617 | for (auto *V : PHIOperands[I]) |
| 1618 | if (InstructionsToSink.count(V) == 0) |
| 1619 | ++NumPHIdValues; |
| 1620 | DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n"); |
| 1621 | assert((NumPHIdValues % Blocks.size() == 0) && |
| 1622 | "Every operand must either be PHId or not PHId!"); |
James Molloy | 55bd04c | 2016-08-31 10:46:23 +0000 | [diff] [blame] | 1623 | |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1624 | if (NumPHIdValues / Blocks.size() > 1) |
| 1625 | // Too many PHIs would be created. |
| 1626 | break; |
| 1627 | |
| 1628 | sinkLastInstruction(Blocks); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1629 | NumSinkCommons++; |
| 1630 | Changed = true; |
| 1631 | } |
James Molloy | 76c9d42 | 2016-08-31 13:16:45 +0000 | [diff] [blame^] | 1632 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1633 | return Changed; |
| 1634 | } |
| 1635 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1636 | /// \brief Determine if we can hoist sink a sole store instruction out of a |
| 1637 | /// conditional block. |
| 1638 | /// |
| 1639 | /// We are looking for code like the following: |
| 1640 | /// BrBB: |
| 1641 | /// store i32 %add, i32* %arrayidx2 |
| 1642 | /// ... // No other stores or function calls (we could be calling a memory |
| 1643 | /// ... // function). |
| 1644 | /// %cmp = icmp ult %x, %y |
| 1645 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1646 | /// ThenBB: |
| 1647 | /// store i32 %add5, i32* %arrayidx2 |
| 1648 | /// br label EndBB |
| 1649 | /// EndBB: |
| 1650 | /// ... |
| 1651 | /// We are going to transform this into: |
| 1652 | /// BrBB: |
| 1653 | /// store i32 %add, i32* %arrayidx2 |
| 1654 | /// ... // |
| 1655 | /// %cmp = icmp ult %x, %y |
| 1656 | /// %add.add5 = select i1 %cmp, i32 %add, %add5 |
| 1657 | /// store i32 %add.add5, i32* %arrayidx2 |
| 1658 | /// ... |
| 1659 | /// |
| 1660 | /// \return The pointer to the value of the previous store if the store can be |
| 1661 | /// hoisted into the predecessor block. 0 otherwise. |
Benjamin Kramer | ad5c24f | 2013-05-23 16:09:15 +0000 | [diff] [blame] | 1662 | static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, |
| 1663 | BasicBlock *StoreBB, BasicBlock *EndBB) { |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1664 | StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); |
| 1665 | if (!StoreToHoist) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1666 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1667 | |
| 1668 | // Volatile or atomic. |
| 1669 | if (!StoreToHoist->isSimple()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1670 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1671 | |
| 1672 | Value *StorePtr = StoreToHoist->getPointerOperand(); |
| 1673 | |
| 1674 | // Look for a store to the same pointer in BrBB. |
Hans Wennborg | 0c3518e | 2016-05-04 15:40:57 +0000 | [diff] [blame] | 1675 | unsigned MaxNumInstToLookAt = 9; |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 1676 | for (Instruction &CurI : reverse(*BrBB)) { |
| 1677 | if (!MaxNumInstToLookAt) |
| 1678 | break; |
Hans Wennborg | 0c3518e | 2016-05-04 15:40:57 +0000 | [diff] [blame] | 1679 | // Skip debug info. |
| 1680 | if (isa<DbgInfoIntrinsic>(CurI)) |
| 1681 | continue; |
| 1682 | --MaxNumInstToLookAt; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1683 | |
David L Kreitzer | 9667417 | 2016-08-12 21:06:53 +0000 | [diff] [blame] | 1684 | // Could be calling an instruction that affects memory like free(). |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 1685 | if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1686 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1687 | |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 1688 | if (auto *SI = dyn_cast<StoreInst>(&CurI)) { |
| 1689 | // Found the previous store make sure it stores to the same location. |
| 1690 | if (SI->getPointerOperand() == StorePtr) |
| 1691 | // Found the previous store, return its value operand. |
| 1692 | return SI->getValueOperand(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1693 | return nullptr; // Unknown store. |
David Majnemer | d770877 | 2016-06-24 04:05:21 +0000 | [diff] [blame] | 1694 | } |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1695 | } |
| 1696 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1697 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1698 | } |
| 1699 | |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1700 | /// \brief Speculate a conditional basic block flattening the CFG. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1701 | /// |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1702 | /// Note that this is a very risky transform currently. Speculating |
| 1703 | /// instructions like this is most often not desirable. Instead, there is an MI |
| 1704 | /// pass which can do it with full awareness of the resource constraints. |
| 1705 | /// However, some cases are "obvious" and we should do directly. An example of |
| 1706 | /// this is speculating a single, reasonably cheap instruction. |
| 1707 | /// |
| 1708 | /// There is only one distinct advantage to flattening the CFG at the IR level: |
| 1709 | /// it makes very common but simplistic optimizations such as are common in |
| 1710 | /// instcombine and the DAG combiner more powerful by removing CFG edges and |
| 1711 | /// modeling their effects with easier to reason about SSA value graphs. |
| 1712 | /// |
| 1713 | /// |
| 1714 | /// An illustration of this transform is turning this IR: |
| 1715 | /// \code |
| 1716 | /// BB: |
| 1717 | /// %cmp = icmp ult %x, %y |
| 1718 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1719 | /// ThenBB: |
| 1720 | /// %sub = sub %x, %y |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1721 | /// br label BB2 |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1722 | /// EndBB: |
| 1723 | /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] |
| 1724 | /// ... |
| 1725 | /// \endcode |
| 1726 | /// |
| 1727 | /// Into this IR: |
| 1728 | /// \code |
| 1729 | /// BB: |
| 1730 | /// %cmp = icmp ult %x, %y |
| 1731 | /// %sub = sub %x, %y |
| 1732 | /// %cond = select i1 %cmp, 0, %sub |
| 1733 | /// ... |
| 1734 | /// \endcode |
| 1735 | /// |
| 1736 | /// \returns true if the conditional block is removed. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1737 | static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1738 | const TargetTransformInfo &TTI) { |
Chandler Carruth | 1d20c02 | 2013-01-24 08:22:40 +0000 | [diff] [blame] | 1739 | // Be conservative for now. FP select instruction can often be expensive. |
| 1740 | Value *BrCond = BI->getCondition(); |
| 1741 | if (isa<FCmpInst>(BrCond)) |
| 1742 | return false; |
| 1743 | |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1744 | BasicBlock *BB = BI->getParent(); |
| 1745 | BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); |
| 1746 | |
| 1747 | // If ThenBB is actually on the false edge of the conditional branch, remember |
| 1748 | // to swap the select operands later. |
| 1749 | bool Invert = false; |
| 1750 | if (ThenBB != BI->getSuccessor(0)) { |
| 1751 | assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); |
| 1752 | Invert = true; |
| 1753 | } |
| 1754 | assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); |
| 1755 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1756 | // Keep a count of how many times instructions are used within CondBB when |
| 1757 | // they are candidates for sinking into CondBB. Specifically: |
| 1758 | // - They are defined in BB, and |
| 1759 | // - They have no side effects, and |
| 1760 | // - All of their uses are in CondBB. |
| 1761 | SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; |
| 1762 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1763 | unsigned SpeculationCost = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1764 | Value *SpeculatedStoreValue = nullptr; |
| 1765 | StoreInst *SpeculatedStore = nullptr; |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1766 | for (BasicBlock::iterator BBI = ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1767 | BBE = std::prev(ThenBB->end()); |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1768 | BBI != BBE; ++BBI) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1769 | Instruction *I = &*BBI; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1770 | // Skip debug info. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1771 | if (isa<DbgInfoIntrinsic>(I)) |
| 1772 | continue; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1773 | |
Mark Lacey | 274f48b | 2015-04-12 18:18:51 +0000 | [diff] [blame] | 1774 | // Only speculatively execute a single instruction (not counting the |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1775 | // terminator) for now. |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1776 | ++SpeculationCost; |
| 1777 | if (SpeculationCost > 1) |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1778 | return false; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1779 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1780 | // Don't hoist the instruction if it's unsafe or expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1781 | if (!isSafeToSpeculativelyExecute(I) && |
| 1782 | !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( |
| 1783 | I, BB, ThenBB, EndBB)))) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1784 | return false; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1785 | if (!SpeculatedStoreValue && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1786 | ComputeSpeculationCost(I, TTI) > |
| 1787 | PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1788 | return false; |
| 1789 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1790 | // Store the store speculation candidate. |
| 1791 | if (SpeculatedStoreValue) |
| 1792 | SpeculatedStore = cast<StoreInst>(I); |
| 1793 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1794 | // Do not hoist the instruction if any of its operands are defined but not |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1795 | // used in BB. The transformation will prevent the operand from |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1796 | // being sunk into the use block. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1797 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) { |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1798 | Instruction *OpI = dyn_cast<Instruction>(*i); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1799 | if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1800 | continue; // Not a candidate for sinking. |
| 1801 | |
| 1802 | ++SinkCandidateUseCounts[OpI]; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1803 | } |
| 1804 | } |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1805 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1806 | // Consider any sink candidates which are only used in CondBB as costs for |
| 1807 | // speculation. Note, while we iterate over a DenseMap here, we are summing |
| 1808 | // and so iteration order isn't significant. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1809 | for (SmallDenseMap<Instruction *, unsigned, 4>::iterator |
| 1810 | I = SinkCandidateUseCounts.begin(), |
| 1811 | E = SinkCandidateUseCounts.end(); |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1812 | I != E; ++I) |
| 1813 | if (I->first->getNumUses() == I->second) { |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1814 | ++SpeculationCost; |
| 1815 | if (SpeculationCost > 1) |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1816 | return false; |
| 1817 | } |
| 1818 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1819 | // Check that the PHI nodes can be converted to selects. |
| 1820 | bool HaveRewritablePHIs = false; |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1821 | for (BasicBlock::iterator I = EndBB->begin(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1822 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1823 | Value *OrigV = PN->getIncomingValueForBlock(BB); |
| 1824 | Value *ThenV = PN->getIncomingValueForBlock(ThenBB); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1825 | |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1826 | // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1827 | // Skip PHIs which are trivial. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1828 | if (ThenV == OrigV) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1829 | continue; |
| 1830 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1831 | // Don't convert to selects if we could remove undefined behavior instead. |
| 1832 | if (passingValueIsAlwaysUndefined(OrigV, PN) || |
| 1833 | passingValueIsAlwaysUndefined(ThenV, PN)) |
| 1834 | return false; |
| 1835 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1836 | HaveRewritablePHIs = true; |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1837 | ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); |
| 1838 | ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); |
| 1839 | if (!OrigCE && !ThenCE) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1840 | continue; // Known safe and cheap. |
| 1841 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1842 | if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || |
| 1843 | (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1844 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1845 | unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; |
| 1846 | unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1847 | unsigned MaxCost = |
| 1848 | 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1849 | if (OrigCost + ThenCost > MaxCost) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1850 | return false; |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1851 | |
Chandler Carruth | 01bffaa | 2013-01-24 12:05:17 +0000 | [diff] [blame] | 1852 | // Account for the cost of an unfolded ConstantExpr which could end up |
| 1853 | // getting expanded into Instructions. |
| 1854 | // FIXME: This doesn't account for how many operations are combined in the |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1855 | // constant expression. |
| 1856 | ++SpeculationCost; |
| 1857 | if (SpeculationCost > 1) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1858 | return false; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1859 | } |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1860 | |
| 1861 | // If there are no PHIs to process, bail early. This helps ensure idempotence |
| 1862 | // as well. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1863 | if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1864 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1865 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1866 | // If we get here, we can hoist the instruction and if-convert. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1867 | DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1868 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1869 | // Insert a select of the value of the speculated store. |
| 1870 | if (SpeculatedStoreValue) { |
Mehdi Amini | ba9fba8 | 2016-03-13 21:05:13 +0000 | [diff] [blame] | 1871 | IRBuilder<NoFolder> Builder(BI); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1872 | Value *TrueV = SpeculatedStore->getValueOperand(); |
| 1873 | Value *FalseV = SpeculatedStoreValue; |
| 1874 | if (Invert) |
| 1875 | std::swap(TrueV, FalseV); |
Sanjay Patel | 796db35 | 2016-03-26 23:30:50 +0000 | [diff] [blame] | 1876 | Value *S = Builder.CreateSelect( |
| 1877 | BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1878 | SpeculatedStore->setOperand(0, S); |
| 1879 | } |
| 1880 | |
Igor Laevsky | 7310c68 | 2015-11-18 14:50:18 +0000 | [diff] [blame] | 1881 | // Metadata can be dependent on the condition we are hoisting above. |
| 1882 | // Conservatively strip all metadata on the instruction. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1883 | for (auto &I : *ThenBB) |
Igor Laevsky | 7310c68 | 2015-11-18 14:50:18 +0000 | [diff] [blame] | 1884 | I.dropUnknownNonDebugMetadata(); |
| 1885 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1886 | // Hoist the instructions. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1887 | BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), |
| 1888 | ThenBB->begin(), std::prev(ThenBB->end())); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1889 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1890 | // Insert selects and rewrite the PHI operands. |
Mehdi Amini | ba9fba8 | 2016-03-13 21:05:13 +0000 | [diff] [blame] | 1891 | IRBuilder<NoFolder> Builder(BI); |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1892 | for (BasicBlock::iterator I = EndBB->begin(); |
| 1893 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
| 1894 | unsigned OrigI = PN->getBasicBlockIndex(BB); |
| 1895 | unsigned ThenI = PN->getBasicBlockIndex(ThenBB); |
| 1896 | Value *OrigV = PN->getIncomingValue(OrigI); |
| 1897 | Value *ThenV = PN->getIncomingValue(ThenI); |
| 1898 | |
| 1899 | // Skip PHIs which are trivial. |
| 1900 | if (OrigV == ThenV) |
| 1901 | continue; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1902 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1903 | // Create a select whose true value is the speculatively executed value and |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1904 | // false value is the preexisting value. Swap them if the branch |
| 1905 | // destinations were inverted. |
| 1906 | Value *TrueV = ThenV, *FalseV = OrigV; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1907 | if (Invert) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1908 | std::swap(TrueV, FalseV); |
Sanjay Patel | f11ab05 | 2016-04-15 15:32:12 +0000 | [diff] [blame] | 1909 | Value *V = Builder.CreateSelect( |
| 1910 | BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI); |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1911 | PN->setIncomingValue(OrigI, V); |
| 1912 | PN->setIncomingValue(ThenI, V); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1913 | } |
| 1914 | |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1915 | ++NumSpeculations; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1916 | return true; |
| 1917 | } |
| 1918 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1919 | /// Return true if we can thread a branch across this block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1920 | static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| 1921 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1922 | unsigned Size = 0; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1923 | |
Devang Patel | 84fceff | 2009-03-10 18:00:05 +0000 | [diff] [blame] | 1924 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1925 | if (isa<DbgInfoIntrinsic>(BBI)) |
| 1926 | continue; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1927 | if (Size > 10) |
| 1928 | return false; // Don't clone large BB's. |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1929 | ++Size; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1930 | |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1931 | // We can only support instructions that do not define values that are |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1932 | // live outside of the current basic block. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1933 | for (User *U : BBI->users()) { |
| 1934 | Instruction *UI = cast<Instruction>(U); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1935 | if (UI->getParent() != BB || isa<PHINode>(UI)) |
| 1936 | return false; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1937 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1938 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1939 | // Looks ok, continue checking. |
| 1940 | } |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1941 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1942 | return true; |
| 1943 | } |
| 1944 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1945 | /// If we have a conditional branch on a PHI node value that is defined in the |
| 1946 | /// same block as the branch and if any PHI entries are constants, thread edges |
| 1947 | /// corresponding to that entry to be branches to their ultimate destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1948 | static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) { |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1949 | BasicBlock *BB = BI->getParent(); |
| 1950 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
Chris Lattner | 049cb44 | 2005-09-19 23:57:04 +0000 | [diff] [blame] | 1951 | // NOTE: we currently cannot transform this case if the PHI node is used |
| 1952 | // outside of the block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1953 | if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| 1954 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1955 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1956 | // Degenerate case of a single entry PHI. |
| 1957 | if (PN->getNumIncomingValues() == 1) { |
Chris Lattner | dc3f6f2 | 2008-12-03 19:44:02 +0000 | [diff] [blame] | 1958 | FoldSingleEntryPHINodes(PN->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1959 | return true; |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1960 | } |
| 1961 | |
| 1962 | // Now we know that this block has multiple preds and two succs. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1963 | if (!BlockIsSimpleEnoughToThreadThrough(BB)) |
| 1964 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1965 | |
Justin Lebar | db63949 | 2016-02-12 21:01:36 +0000 | [diff] [blame] | 1966 | // Can't fold blocks that contain noduplicate or convergent calls. |
David Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 1967 | if (any_of(*BB, [](const Instruction &I) { |
Justin Lebar | db63949 | 2016-02-12 21:01:36 +0000 | [diff] [blame] | 1968 | const CallInst *CI = dyn_cast<CallInst>(&I); |
| 1969 | return CI && (CI->cannotDuplicate() || CI->isConvergent()); |
| 1970 | })) |
| 1971 | return false; |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1972 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1973 | // Okay, this is a simple enough basic block. See if any phi values are |
| 1974 | // constants. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1975 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1976 | ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1977 | if (!CB || !CB->getType()->isIntegerTy(1)) |
| 1978 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1979 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1980 | // Okay, we now know that all edges from PredBB should be revectored to |
| 1981 | // branch to RealDest. |
| 1982 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 1983 | BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1984 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1985 | if (RealDest == BB) |
| 1986 | continue; // Skip self loops. |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1987 | // Skip if the predecessor's terminator is an indirect branch. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1988 | if (isa<IndirectBrInst>(PredBB->getTerminator())) |
| 1989 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1990 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1991 | // The dest block might have PHI nodes, other predecessors and other |
| 1992 | // difficult cases. Instead of being smart about this, just insert a new |
| 1993 | // block that jumps to the destination block, effectively splitting |
| 1994 | // the edge we are about to create. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 1995 | BasicBlock *EdgeBB = |
| 1996 | BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", |
| 1997 | RealDest->getParent(), RealDest); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1998 | BranchInst::Create(RealDest, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1999 | |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2000 | // Update PHI nodes. |
| 2001 | AddPredecessorToBlock(RealDest, EdgeBB, BB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2002 | |
| 2003 | // BB may have instructions that are being threaded over. Clone these |
| 2004 | // instructions into EdgeBB. We know that there will be no uses of the |
| 2005 | // cloned instructions outside of EdgeBB. |
| 2006 | BasicBlock::iterator InsertPt = EdgeBB->begin(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2007 | DenseMap<Value *, Value *> TranslateMap; // Track translated values. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2008 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| 2009 | if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| 2010 | TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| 2011 | continue; |
| 2012 | } |
| 2013 | // Clone the instruction. |
| 2014 | Instruction *N = BBI->clone(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2015 | if (BBI->hasName()) |
| 2016 | N->setName(BBI->getName() + ".c"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2017 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2018 | // Update operands due to translation. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2019 | for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) { |
| 2020 | DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2021 | if (PI != TranslateMap.end()) |
| 2022 | *i = PI->second; |
| 2023 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2024 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2025 | // Check for trivial simplification. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2026 | if (Value *V = SimplifyInstruction(N, DL)) { |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 2027 | if (!BBI->use_empty()) |
| 2028 | TranslateMap[&*BBI] = V; |
| 2029 | if (!N->mayHaveSideEffects()) { |
| 2030 | delete N; // Instruction folded away, don't need actual inst |
| 2031 | N = nullptr; |
| 2032 | } |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2033 | } else { |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2034 | if (!BBI->use_empty()) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2035 | TranslateMap[&*BBI] = N; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2036 | } |
David Majnemer | b8da3a2 | 2016-06-25 00:04:10 +0000 | [diff] [blame] | 2037 | // Insert the new instruction into its new home. |
| 2038 | if (N) |
| 2039 | EdgeBB->getInstList().insert(InsertPt, N); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2040 | } |
| 2041 | |
| 2042 | // Loop over all of the edges from PredBB to BB, changing them to branch |
| 2043 | // to EdgeBB instead. |
| 2044 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 2045 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 2046 | if (PredBBTI->getSuccessor(i) == BB) { |
| 2047 | BB->removePredecessor(PredBB); |
| 2048 | PredBBTI->setSuccessor(i, EdgeBB); |
| 2049 | } |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 2050 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2051 | // Recurse, simplifying any other constants. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2052 | return FoldCondBranchOnPHI(BI, DL) | true; |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2053 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 2054 | |
| 2055 | return false; |
| 2056 | } |
| 2057 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2058 | /// Given a BB that starts with the specified two-entry PHI node, |
| 2059 | /// see if we can eliminate it. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2060 | static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, |
| 2061 | const DataLayout &DL) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2062 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 2063 | // statement", which has a very simple dominance structure. Basically, we |
| 2064 | // are trying to find the condition that is being branched on, which |
| 2065 | // subsequently causes this merge to happen. We really want control |
| 2066 | // dependence information for this check, but simplifycfg can't keep it up |
| 2067 | // to date, and this catches most of the cases we care about anyway. |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2068 | BasicBlock *BB = PN->getParent(); |
| 2069 | BasicBlock *IfTrue, *IfFalse; |
| 2070 | Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 2071 | if (!IfCond || |
| 2072 | // Don't bother if the branch will be constant folded trivially. |
| 2073 | isa<ConstantInt>(IfCond)) |
| 2074 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2075 | |
Chris Lattner | 95adf8f1 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 2076 | // Okay, we found that we can merge this two-entry phi node into a select. |
| 2077 | // Doing so would require us to fold *all* two entry phi nodes in this block. |
| 2078 | // At some point this becomes non-profitable (particularly if the target |
| 2079 | // doesn't support cmov's). Only do this transformation if there are two or |
| 2080 | // fewer PHI nodes in this block. |
| 2081 | unsigned NumPhis = 0; |
| 2082 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| 2083 | if (NumPhis > 2) |
| 2084 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2085 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2086 | // Loop over the PHI's seeing if we can promote them all to select |
| 2087 | // instructions. While we are at it, keep track of the instructions |
| 2088 | // that need to be moved to the dominating block. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2089 | SmallPtrSet<Instruction *, 4> AggressiveInsts; |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 2090 | unsigned MaxCostVal0 = PHINodeFoldingThreshold, |
| 2091 | MaxCostVal1 = PHINodeFoldingThreshold; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 2092 | MaxCostVal0 *= TargetTransformInfo::TCC_Basic; |
| 2093 | MaxCostVal1 *= TargetTransformInfo::TCC_Basic; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2094 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 2095 | for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { |
| 2096 | PHINode *PN = cast<PHINode>(II++); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2097 | if (Value *V = SimplifyInstruction(PN, DL)) { |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 2098 | PN->replaceAllUsesWith(V); |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 2099 | PN->eraseFromParent(); |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 2100 | continue; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2101 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2102 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 2103 | if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2104 | MaxCostVal0, TTI) || |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 2105 | !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2106 | MaxCostVal1, TTI)) |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 2107 | return false; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2108 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2109 | |
Sylvestre Ledru | 35521e2 | 2012-07-23 08:51:15 +0000 | [diff] [blame] | 2110 | // If we folded the first phi, PN dangles at this point. Refresh it. If |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2111 | // we ran out of PHIs then we simplified them all. |
| 2112 | PN = dyn_cast<PHINode>(BB->begin()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2113 | if (!PN) |
| 2114 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2115 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 2116 | // Don't fold i1 branches on PHIs which contain binary operators. These can |
| 2117 | // often be turned into switches and other things. |
| 2118 | if (PN->getType()->isIntegerTy(1) && |
| 2119 | (isa<BinaryOperator>(PN->getIncomingValue(0)) || |
| 2120 | isa<BinaryOperator>(PN->getIncomingValue(1)) || |
| 2121 | isa<BinaryOperator>(IfCond))) |
| 2122 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2123 | |
Sanjay Patel | 2e00277 | 2016-03-12 18:05:53 +0000 | [diff] [blame] | 2124 | // If all PHI nodes are promotable, check to make sure that all instructions |
| 2125 | // in the predecessor blocks can be promoted as well. If not, we won't be able |
| 2126 | // to get rid of the control flow, so it's not worth promoting to select |
| 2127 | // instructions. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2128 | BasicBlock *DomBlock = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2129 | BasicBlock *IfBlock1 = PN->getIncomingBlock(0); |
| 2130 | BasicBlock *IfBlock2 = PN->getIncomingBlock(1); |
| 2131 | if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2132 | IfBlock1 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2133 | } else { |
| 2134 | DomBlock = *pred_begin(IfBlock1); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2135 | for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I); |
| 2136 | ++I) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2137 | if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2138 | // This is not an aggressive instruction that we can promote. |
Sanjay Patel | 2e00277 | 2016-03-12 18:05:53 +0000 | [diff] [blame] | 2139 | // Because of this, we won't be able to get rid of the control flow, so |
| 2140 | // the xform is not worth it. |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2141 | return false; |
| 2142 | } |
| 2143 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2144 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2145 | if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2146 | IfBlock2 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2147 | } else { |
| 2148 | DomBlock = *pred_begin(IfBlock2); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2149 | for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I); |
| 2150 | ++I) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2151 | if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2152 | // This is not an aggressive instruction that we can promote. |
Sanjay Patel | 2e00277 | 2016-03-12 18:05:53 +0000 | [diff] [blame] | 2153 | // Because of this, we won't be able to get rid of the control flow, so |
| 2154 | // the xform is not worth it. |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2155 | return false; |
| 2156 | } |
| 2157 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2158 | |
Chris Lattner | 9fd838d | 2010-12-14 07:23:10 +0000 | [diff] [blame] | 2159 | DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 2160 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2161 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2162 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 2163 | // do all of the PHI's now. |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 2164 | Instruction *InsertPt = DomBlock->getTerminator(); |
Mehdi Amini | ba9fba8 | 2016-03-13 21:05:13 +0000 | [diff] [blame] | 2165 | IRBuilder<NoFolder> Builder(InsertPt); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2166 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2167 | // Move all 'aggressive' instructions, which are defined in the |
| 2168 | // conditional parts of the if's up to the dominating block. |
David Majnemer | e8fd5f9 | 2016-08-29 17:14:08 +0000 | [diff] [blame] | 2169 | if (IfBlock1) { |
| 2170 | for (auto &I : *IfBlock1) |
| 2171 | I.dropUnknownNonDebugMetadata(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2172 | DomBlock->getInstList().splice(InsertPt->getIterator(), |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2173 | IfBlock1->getInstList(), IfBlock1->begin(), |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2174 | IfBlock1->getTerminator()->getIterator()); |
David Majnemer | e8fd5f9 | 2016-08-29 17:14:08 +0000 | [diff] [blame] | 2175 | } |
| 2176 | if (IfBlock2) { |
| 2177 | for (auto &I : *IfBlock2) |
| 2178 | I.dropUnknownNonDebugMetadata(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2179 | DomBlock->getInstList().splice(InsertPt->getIterator(), |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2180 | IfBlock2->getInstList(), IfBlock2->begin(), |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2181 | IfBlock2->getTerminator()->getIterator()); |
David Majnemer | e8fd5f9 | 2016-08-29 17:14:08 +0000 | [diff] [blame] | 2182 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2183 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2184 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 2185 | // Change the PHI node into a select instruction. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2186 | Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2187 | Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2188 | |
Sanjay Patel | 9e23fed | 2016-03-17 15:30:52 +0000 | [diff] [blame] | 2189 | Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); |
| 2190 | PN->replaceAllUsesWith(Sel); |
| 2191 | Sel->takeName(PN); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2192 | PN->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2193 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2194 | |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 2195 | // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement |
| 2196 | // has been flattened. Change DomBlock to jump directly to our new block to |
| 2197 | // avoid other simplifycfg's kicking in on the diamond. |
| 2198 | TerminatorInst *OldTI = DomBlock->getTerminator(); |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 2199 | Builder.SetInsertPoint(OldTI); |
| 2200 | Builder.CreateBr(BB); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 2201 | OldTI->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 2202 | return true; |
| 2203 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 2204 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2205 | /// If we found a conditional branch that goes to two returning blocks, |
| 2206 | /// try to merge them together into one return, |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2207 | /// introducing a select if the return values disagree. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2208 | static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2209 | IRBuilder<> &Builder) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2210 | assert(BI->isConditional() && "Must be a conditional branch"); |
| 2211 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 2212 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 2213 | ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| 2214 | ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2215 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2216 | // Check to ensure both blocks are empty (just a return) or optionally empty |
| 2217 | // with PHI nodes. If there are other instructions, merging would cause extra |
| 2218 | // computation on one path or the other. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2219 | if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 2220 | return false; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 2221 | if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 2222 | return false; |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2223 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2224 | Builder.SetInsertPoint(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2225 | // Okay, we found a branch that is going to two return nodes. If |
| 2226 | // there is no return value for this function, just change the |
| 2227 | // branch into a return. |
| 2228 | if (FalseRet->getNumOperands() == 0) { |
| 2229 | TrueSucc->removePredecessor(BI->getParent()); |
| 2230 | FalseSucc->removePredecessor(BI->getParent()); |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2231 | Builder.CreateRetVoid(); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 2232 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2233 | return true; |
| 2234 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2235 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2236 | // Otherwise, figure out what the true and false return values are |
| 2237 | // so we can insert a new select instruction. |
| 2238 | Value *TrueValue = TrueRet->getReturnValue(); |
| 2239 | Value *FalseValue = FalseRet->getReturnValue(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2240 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2241 | // Unwrap any PHI nodes in the return blocks. |
| 2242 | if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) |
| 2243 | if (TVPN->getParent() == TrueSucc) |
| 2244 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 2245 | if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) |
| 2246 | if (FVPN->getParent() == FalseSucc) |
| 2247 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2248 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2249 | // In order for this transformation to be safe, we must be able to |
| 2250 | // unconditionally execute both operands to the return. This is |
| 2251 | // normally the case, but we could have a potentially-trapping |
| 2252 | // constant expression that prevents this transformation from being |
| 2253 | // safe. |
| 2254 | if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) |
| 2255 | if (TCV->canTrap()) |
| 2256 | return false; |
| 2257 | if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) |
| 2258 | if (FCV->canTrap()) |
| 2259 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2260 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2261 | // Okay, we collected all the mapped values and checked them for sanity, and |
| 2262 | // defined to really do this transformation. First, update the CFG. |
| 2263 | TrueSucc->removePredecessor(BI->getParent()); |
| 2264 | FalseSucc->removePredecessor(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2265 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2266 | // Insert select instructions where needed. |
| 2267 | Value *BrCond = BI->getCondition(); |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2268 | if (TrueValue) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2269 | // Insert a select if the results differ. |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2270 | if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { |
| 2271 | } else if (isa<UndefValue>(TrueValue)) { |
| 2272 | TrueValue = FalseValue; |
| 2273 | } else { |
Sanjay Patel | facf45a | 2016-04-27 23:14:12 +0000 | [diff] [blame] | 2274 | TrueValue = |
| 2275 | Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2276 | } |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2277 | } |
| 2278 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2279 | Value *RI = |
| 2280 | !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2281 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2282 | (void)RI; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2283 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2284 | DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2285 | << "\n " << *BI << "NewRet = " << *RI |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2286 | << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2287 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 2288 | EraseTerminatorInstAndDCECond(BI); |
| 2289 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2290 | return true; |
| 2291 | } |
| 2292 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2293 | /// Return true if the given instruction is available |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2294 | /// in its predecessor block. If yes, the instruction will be removed. |
Benjamin Kramer | abbfe69 | 2012-07-13 13:25:15 +0000 | [diff] [blame] | 2295 | static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2296 | if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) |
| 2297 | return false; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 2298 | for (Instruction &I : *PB) { |
| 2299 | Instruction *PBI = &I; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2300 | // Check whether Inst and PBI generate the same value. |
| 2301 | if (Inst->isIdenticalTo(PBI)) { |
| 2302 | Inst->replaceAllUsesWith(PBI); |
| 2303 | Inst->eraseFromParent(); |
| 2304 | return true; |
| 2305 | } |
| 2306 | } |
| 2307 | return false; |
| 2308 | } |
Nick Lewycky | 3c3feaf | 2012-01-25 09:43:14 +0000 | [diff] [blame] | 2309 | |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 2310 | /// Return true if either PBI or BI has branch weight available, and store |
| 2311 | /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does |
| 2312 | /// not have branch weight, use 1:1 as its weight. |
| 2313 | static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, |
| 2314 | uint64_t &PredTrueWeight, |
| 2315 | uint64_t &PredFalseWeight, |
| 2316 | uint64_t &SuccTrueWeight, |
| 2317 | uint64_t &SuccFalseWeight) { |
| 2318 | bool PredHasWeights = |
| 2319 | PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); |
| 2320 | bool SuccHasWeights = |
| 2321 | BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); |
| 2322 | if (PredHasWeights || SuccHasWeights) { |
| 2323 | if (!PredHasWeights) |
| 2324 | PredTrueWeight = PredFalseWeight = 1; |
| 2325 | if (!SuccHasWeights) |
| 2326 | SuccTrueWeight = SuccFalseWeight = 1; |
| 2327 | return true; |
| 2328 | } else { |
| 2329 | return false; |
| 2330 | } |
| 2331 | } |
| 2332 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2333 | /// If this basic block is simple enough, and if a predecessor branches to us |
| 2334 | /// and one of our successors, fold the block into the predecessor and use |
| 2335 | /// logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2336 | bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2337 | BasicBlock *BB = BI->getParent(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2338 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2339 | Instruction *Cond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2340 | if (BI->isConditional()) |
| 2341 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 2342 | else { |
| 2343 | // For unconditional branch, check for a simple CFG pattern, where |
| 2344 | // BB has a single predecessor and BB's successor is also its predecessor's |
| 2345 | // successor. If such pattern exisits, check for CSE between BB and its |
| 2346 | // predecessor. |
| 2347 | if (BasicBlock *PB = BB->getSinglePredecessor()) |
| 2348 | if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) |
| 2349 | if (PBI->isConditional() && |
| 2350 | (BI->getSuccessor(0) == PBI->getSuccessor(0) || |
| 2351 | BI->getSuccessor(0) == PBI->getSuccessor(1))) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2352 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2353 | Instruction *Curr = &*I++; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2354 | if (isa<CmpInst>(Curr)) { |
| 2355 | Cond = Curr; |
| 2356 | break; |
| 2357 | } |
| 2358 | // Quit if we can't remove this instruction. |
| 2359 | if (!checkCSEInPredecessor(Curr, PB)) |
| 2360 | return false; |
| 2361 | } |
| 2362 | } |
| 2363 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2364 | if (!Cond) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2365 | return false; |
| 2366 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2367 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2368 | if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || |
| 2369 | Cond->getParent() != BB || !Cond->hasOneUse()) |
Sanjay Patel | 2e00277 | 2016-03-12 18:05:53 +0000 | [diff] [blame] | 2370 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2371 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2372 | // Make sure the instruction after the condition is the cond branch. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2373 | BasicBlock::iterator CondIt = ++Cond->getIterator(); |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2374 | |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2375 | // Ignore dbg intrinsics. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2376 | while (isa<DbgInfoIntrinsic>(CondIt)) |
| 2377 | ++CondIt; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2378 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2379 | if (&*CondIt != BI) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2380 | return false; |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2381 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2382 | // Only allow this transformation if computing the condition doesn't involve |
| 2383 | // too many instructions and these involved instructions can be executed |
| 2384 | // unconditionally. We denote all involved instructions except the condition |
| 2385 | // as "bonus instructions", and only allow this transformation when the |
| 2386 | // number of the bonus instructions does not exceed a certain threshold. |
| 2387 | unsigned NumBonusInsts = 0; |
Duncan P. N. Exon Smith | e9bc579 | 2016-02-21 20:39:50 +0000 | [diff] [blame] | 2388 | for (auto I = BB->begin(); Cond != &*I; ++I) { |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2389 | // Ignore dbg intrinsics. |
| 2390 | if (isa<DbgInfoIntrinsic>(I)) |
| 2391 | continue; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2392 | if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2393 | return false; |
| 2394 | // I has only one use and can be executed unconditionally. |
| 2395 | Instruction *User = dyn_cast<Instruction>(I->user_back()); |
| 2396 | if (User == nullptr || User->getParent() != BB) |
| 2397 | return false; |
| 2398 | // I is used in the same BB. Since BI uses Cond and doesn't have more slots |
| 2399 | // to use any other instruction, User must be an instruction between next(I) |
| 2400 | // and Cond. |
| 2401 | ++NumBonusInsts; |
| 2402 | // Early exits once we reach the limit. |
| 2403 | if (NumBonusInsts > BonusInstThreshold) |
| 2404 | return false; |
| 2405 | } |
| 2406 | |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2407 | // Cond is known to be a compare or binary operator. Check to make sure that |
| 2408 | // neither operand is a potentially-trapping constant expression. |
| 2409 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) |
| 2410 | if (CE->canTrap()) |
| 2411 | return false; |
| 2412 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) |
| 2413 | if (CE->canTrap()) |
| 2414 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2415 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2416 | // Finally, don't infinitely unroll conditional loops. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2417 | BasicBlock *TrueDest = BI->getSuccessor(0); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2418 | BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2419 | if (TrueDest == BB || FalseDest == BB) |
| 2420 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2421 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2422 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 2423 | BasicBlock *PredBlock = *PI; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2424 | BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2425 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2426 | // Check that we have two conditional branches. If there is a PHI node in |
| 2427 | // the common successor, verify that the same value flows in from both |
| 2428 | // blocks. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2429 | SmallVector<PHINode *, 4> PHIs; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2430 | if (!PBI || PBI->isUnconditional() || |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2431 | (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2432 | (!BI->isConditional() && |
| 2433 | !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2434 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2435 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2436 | // Determine if the two branches share a common destination. |
Axel Naumann | 4a12706 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 2437 | Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2438 | bool InvertPredCond = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2439 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2440 | if (BI->isConditional()) { |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2441 | if (PBI->getSuccessor(0) == TrueDest) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2442 | Opc = Instruction::Or; |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2443 | } else if (PBI->getSuccessor(1) == FalseDest) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2444 | Opc = Instruction::And; |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2445 | } else if (PBI->getSuccessor(0) == FalseDest) { |
| 2446 | Opc = Instruction::And; |
| 2447 | InvertPredCond = true; |
| 2448 | } else if (PBI->getSuccessor(1) == TrueDest) { |
| 2449 | Opc = Instruction::Or; |
| 2450 | InvertPredCond = true; |
| 2451 | } else { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2452 | continue; |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2453 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2454 | } else { |
| 2455 | if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) |
| 2456 | continue; |
| 2457 | } |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2458 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2459 | DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2460 | IRBuilder<> Builder(PBI); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2461 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2462 | // If we need to invert the condition in the pred block to match, do so now. |
| 2463 | if (InvertPredCond) { |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2464 | Value *NewCond = PBI->getCondition(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2465 | |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2466 | if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { |
| 2467 | CmpInst *CI = cast<CmpInst>(NewCond); |
| 2468 | CI->setPredicate(CI->getInversePredicate()); |
| 2469 | } else { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2470 | NewCond = |
| 2471 | Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2472 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2473 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2474 | PBI->setCondition(NewCond); |
Nick Lewycky | 8d302df | 2011-12-26 20:54:14 +0000 | [diff] [blame] | 2475 | PBI->swapSuccessors(); |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2476 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2477 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2478 | // If we have bonus instructions, clone them into the predecessor block. |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2479 | // Note that there may be multiple predecessor blocks, so we cannot move |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2480 | // bonus instructions to a predecessor block. |
| 2481 | ValueToValueMapTy VMap; // maps original values to cloned values |
| 2482 | // We already make sure Cond is the last instruction before BI. Therefore, |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2483 | // all instructions before Cond other than DbgInfoIntrinsic are bonus |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2484 | // instructions. |
Duncan P. N. Exon Smith | e9bc579 | 2016-02-21 20:39:50 +0000 | [diff] [blame] | 2485 | for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2486 | if (isa<DbgInfoIntrinsic>(BonusInst)) |
| 2487 | continue; |
| 2488 | Instruction *NewBonusInst = BonusInst->clone(); |
| 2489 | RemapInstruction(NewBonusInst, VMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 2490 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2491 | VMap[&*BonusInst] = NewBonusInst; |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2492 | |
| 2493 | // If we moved a load, we cannot any longer claim any knowledge about |
| 2494 | // its potential value. The previous information might have been valid |
| 2495 | // only given the branch precondition. |
| 2496 | // For an analogous reason, we must also drop all the metadata whose |
| 2497 | // semantics we don't understand. |
Adrian Prantl | cbdfdb7 | 2015-08-20 22:00:30 +0000 | [diff] [blame] | 2498 | NewBonusInst->dropUnknownNonDebugMetadata(); |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2499 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2500 | PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); |
| 2501 | NewBonusInst->takeName(&*BonusInst); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2502 | BonusInst->setName(BonusInst->getName() + ".old"); |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2503 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2504 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2505 | // Clone Cond into the predecessor basic block, and or/and the |
| 2506 | // two conditions together. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 2507 | Instruction *New = Cond->clone(); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2508 | RemapInstruction(New, VMap, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 2509 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2510 | PredBlock->getInstList().insert(PBI->getIterator(), New); |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2511 | New->takeName(Cond); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2512 | Cond->setName(New->getName() + ".old"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2513 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2514 | if (BI->isConditional()) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2515 | Instruction *NewCond = cast<Instruction>( |
| 2516 | Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2517 | PBI->setCondition(NewCond); |
| 2518 | |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2519 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 2520 | bool HasWeights = |
| 2521 | extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, |
| 2522 | SuccTrueWeight, SuccFalseWeight); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2523 | SmallVector<uint64_t, 8> NewWeights; |
| 2524 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2525 | if (PBI->getSuccessor(0) == BB) { |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 2526 | if (HasWeights) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2527 | // PBI: br i1 %x, BB, FalseDest |
| 2528 | // BI: br i1 %y, TrueDest, FalseDest |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2529 | // TrueWeight is TrueWeight for PBI * TrueWeight for BI. |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2530 | NewWeights.push_back(PredTrueWeight * SuccTrueWeight); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2531 | // FalseWeight is FalseWeight for PBI * TotalWeight for BI + |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2532 | // TrueWeight for PBI * FalseWeight for BI. |
| 2533 | // We assume that total weights of a BranchInst can fit into 32 bits. |
| 2534 | // Therefore, we will not have overflow using 64-bit arithmetic. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2535 | NewWeights.push_back(PredFalseWeight * |
| 2536 | (SuccFalseWeight + SuccTrueWeight) + |
| 2537 | PredTrueWeight * SuccFalseWeight); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2538 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2539 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
| 2540 | PBI->setSuccessor(0, TrueDest); |
| 2541 | } |
| 2542 | if (PBI->getSuccessor(1) == BB) { |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 2543 | if (HasWeights) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2544 | // PBI: br i1 %x, TrueDest, BB |
| 2545 | // BI: br i1 %y, TrueDest, FalseDest |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2546 | // TrueWeight is TrueWeight for PBI * TotalWeight for BI + |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2547 | // FalseWeight for PBI * TrueWeight for BI. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2548 | NewWeights.push_back(PredTrueWeight * |
| 2549 | (SuccFalseWeight + SuccTrueWeight) + |
| 2550 | PredFalseWeight * SuccTrueWeight); |
| 2551 | // FalseWeight is FalseWeight for PBI * FalseWeight for BI. |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2552 | NewWeights.push_back(PredFalseWeight * SuccFalseWeight); |
| 2553 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2554 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
| 2555 | PBI->setSuccessor(1, FalseDest); |
| 2556 | } |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2557 | if (NewWeights.size() == 2) { |
| 2558 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2559 | FitWeights(NewWeights); |
| 2560 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2561 | SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), |
| 2562 | NewWeights.end()); |
| 2563 | PBI->setMetadata( |
| 2564 | LLVMContext::MD_prof, |
| 2565 | MDBuilder(BI->getContext()).createBranchWeights(MDWeights)); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2566 | } else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2567 | PBI->setMetadata(LLVMContext::MD_prof, nullptr); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2568 | } else { |
| 2569 | // Update PHI nodes in the common successors. |
| 2570 | for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 2571 | ConstantInt *PBI_C = cast<ConstantInt>( |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2572 | PHIs[i]->getIncomingValueForBlock(PBI->getParent())); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2573 | assert(PBI_C->getType()->isIntegerTy(1)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2574 | Instruction *MergedCond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2575 | if (PBI->getSuccessor(0) == TrueDest) { |
| 2576 | // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) |
| 2577 | // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) |
| 2578 | // is false: !PBI_Cond and BI_Value |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2579 | Instruction *NotCond = cast<Instruction>( |
| 2580 | Builder.CreateNot(PBI->getCondition(), "not.cond")); |
| 2581 | MergedCond = cast<Instruction>( |
| 2582 | Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2583 | if (PBI_C->isOne()) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2584 | MergedCond = cast<Instruction>(Builder.CreateBinOp( |
| 2585 | Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2586 | } else { |
| 2587 | // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) |
| 2588 | // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) |
| 2589 | // is false: PBI_Cond and BI_Value |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2590 | MergedCond = cast<Instruction>(Builder.CreateBinOp( |
| 2591 | Instruction::And, PBI->getCondition(), New, "and.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2592 | if (PBI_C->isOne()) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2593 | Instruction *NotCond = cast<Instruction>( |
| 2594 | Builder.CreateNot(PBI->getCondition(), "not.cond")); |
| 2595 | MergedCond = cast<Instruction>(Builder.CreateBinOp( |
| 2596 | Instruction::Or, NotCond, MergedCond, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2597 | } |
| 2598 | } |
| 2599 | // Update PHI Node. |
| 2600 | PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), |
| 2601 | MergedCond); |
| 2602 | } |
| 2603 | // Change PBI from Conditional to Unconditional. |
| 2604 | BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); |
| 2605 | EraseTerminatorInstAndDCECond(PBI); |
| 2606 | PBI = New_PBI; |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2607 | } |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2608 | |
Nick Lewycky | c554a9b | 2011-12-27 04:31:52 +0000 | [diff] [blame] | 2609 | // TODO: If BB is reachable from all paths through PredBlock, then we |
| 2610 | // could replace PBI's branch probabilities with BI's. |
| 2611 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2612 | // Copy any debug value intrinsics into the end of PredBlock. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 2613 | for (Instruction &I : *BB) |
| 2614 | if (isa<DbgInfoIntrinsic>(I)) |
| 2615 | I.clone()->insertBefore(PBI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2616 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2617 | return true; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2618 | } |
| 2619 | return false; |
| 2620 | } |
| 2621 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2622 | // If there is only one store in BB1 and BB2, return it, otherwise return |
| 2623 | // nullptr. |
| 2624 | static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { |
| 2625 | StoreInst *S = nullptr; |
| 2626 | for (auto *BB : {BB1, BB2}) { |
| 2627 | if (!BB) |
| 2628 | continue; |
| 2629 | for (auto &I : *BB) |
| 2630 | if (auto *SI = dyn_cast<StoreInst>(&I)) { |
| 2631 | if (S) |
| 2632 | // Multiple stores seen. |
| 2633 | return nullptr; |
| 2634 | else |
| 2635 | S = SI; |
| 2636 | } |
| 2637 | } |
| 2638 | return S; |
| 2639 | } |
| 2640 | |
| 2641 | static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, |
| 2642 | Value *AlternativeV = nullptr) { |
| 2643 | // PHI is going to be a PHI node that allows the value V that is defined in |
| 2644 | // BB to be referenced in BB's only successor. |
| 2645 | // |
| 2646 | // If AlternativeV is nullptr, the only value we care about in PHI is V. It |
| 2647 | // doesn't matter to us what the other operand is (it'll never get used). We |
| 2648 | // could just create a new PHI with an undef incoming value, but that could |
| 2649 | // increase register pressure if EarlyCSE/InstCombine can't fold it with some |
| 2650 | // other PHI. So here we directly look for some PHI in BB's successor with V |
| 2651 | // as an incoming operand. If we find one, we use it, else we create a new |
| 2652 | // one. |
| 2653 | // |
| 2654 | // If AlternativeV is not nullptr, we care about both incoming values in PHI. |
| 2655 | // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] |
| 2656 | // where OtherBB is the single other predecessor of BB's only successor. |
| 2657 | PHINode *PHI = nullptr; |
| 2658 | BasicBlock *Succ = BB->getSingleSuccessor(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2659 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2660 | for (auto I = Succ->begin(); isa<PHINode>(I); ++I) |
| 2661 | if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { |
| 2662 | PHI = cast<PHINode>(I); |
| 2663 | if (!AlternativeV) |
| 2664 | break; |
| 2665 | |
| 2666 | assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2); |
| 2667 | auto PredI = pred_begin(Succ); |
| 2668 | BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; |
| 2669 | if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) |
| 2670 | break; |
| 2671 | PHI = nullptr; |
| 2672 | } |
| 2673 | if (PHI) |
| 2674 | return PHI; |
| 2675 | |
James Molloy | 3d21dcf | 2015-12-16 14:12:44 +0000 | [diff] [blame] | 2676 | // If V is not an instruction defined in BB, just return it. |
| 2677 | if (!AlternativeV && |
| 2678 | (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) |
| 2679 | return V; |
| 2680 | |
Duncan P. N. Exon Smith | 83c4b68 | 2015-11-07 00:01:16 +0000 | [diff] [blame] | 2681 | PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2682 | PHI->addIncoming(V, BB); |
| 2683 | for (BasicBlock *PredBB : predecessors(Succ)) |
| 2684 | if (PredBB != BB) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2685 | PHI->addIncoming( |
| 2686 | AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2687 | return PHI; |
| 2688 | } |
| 2689 | |
| 2690 | static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, |
| 2691 | BasicBlock *QTB, BasicBlock *QFB, |
| 2692 | BasicBlock *PostBB, Value *Address, |
| 2693 | bool InvertPCond, bool InvertQCond) { |
| 2694 | auto IsaBitcastOfPointerType = [](const Instruction &I) { |
| 2695 | return Operator::getOpcode(&I) == Instruction::BitCast && |
| 2696 | I.getType()->isPointerTy(); |
| 2697 | }; |
| 2698 | |
| 2699 | // If we're not in aggressive mode, we only optimize if we have some |
| 2700 | // confidence that by optimizing we'll allow P and/or Q to be if-converted. |
| 2701 | auto IsWorthwhile = [&](BasicBlock *BB) { |
| 2702 | if (!BB) |
| 2703 | return true; |
| 2704 | // Heuristic: if the block can be if-converted/phi-folded and the |
| 2705 | // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to |
| 2706 | // thread this store. |
James Molloy | 9e959ac | 2015-11-05 08:40:19 +0000 | [diff] [blame] | 2707 | unsigned N = 0; |
| 2708 | for (auto &I : *BB) { |
| 2709 | // Cheap instructions viable for folding. |
| 2710 | if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) || |
| 2711 | isa<StoreInst>(I)) |
| 2712 | ++N; |
| 2713 | // Free instructions. |
| 2714 | else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) || |
| 2715 | IsaBitcastOfPointerType(I)) |
| 2716 | continue; |
| 2717 | else |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2718 | return false; |
James Molloy | 9e959ac | 2015-11-05 08:40:19 +0000 | [diff] [blame] | 2719 | } |
| 2720 | return N <= PHINodeFoldingThreshold; |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2721 | }; |
| 2722 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2723 | if (!MergeCondStoresAggressively && |
| 2724 | (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) || |
| 2725 | !IsWorthwhile(QFB))) |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2726 | return false; |
| 2727 | |
| 2728 | // For every pointer, there must be exactly two stores, one coming from |
| 2729 | // PTB or PFB, and the other from QTB or QFB. We don't support more than one |
| 2730 | // store (to any address) in PTB,PFB or QTB,QFB. |
| 2731 | // FIXME: We could relax this restriction with a bit more work and performance |
| 2732 | // testing. |
| 2733 | StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); |
| 2734 | StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); |
| 2735 | if (!PStore || !QStore) |
| 2736 | return false; |
| 2737 | |
| 2738 | // Now check the stores are compatible. |
| 2739 | if (!QStore->isUnordered() || !PStore->isUnordered()) |
| 2740 | return false; |
| 2741 | |
| 2742 | // Check that sinking the store won't cause program behavior changes. Sinking |
| 2743 | // the store out of the Q blocks won't change any behavior as we're sinking |
| 2744 | // from a block to its unconditional successor. But we're moving a store from |
| 2745 | // the P blocks down through the middle block (QBI) and past both QFB and QTB. |
| 2746 | // So we need to check that there are no aliasing loads or stores in |
| 2747 | // QBI, QTB and QFB. We also need to check there are no conflicting memory |
| 2748 | // operations between PStore and the end of its parent block. |
| 2749 | // |
| 2750 | // The ideal way to do this is to query AliasAnalysis, but we don't |
| 2751 | // preserve AA currently so that is dangerous. Be super safe and just |
| 2752 | // check there are no other memory operations at all. |
| 2753 | for (auto &I : *QFB->getSinglePredecessor()) |
| 2754 | if (I.mayReadOrWriteMemory()) |
| 2755 | return false; |
| 2756 | for (auto &I : *QFB) |
| 2757 | if (&I != QStore && I.mayReadOrWriteMemory()) |
| 2758 | return false; |
| 2759 | if (QTB) |
| 2760 | for (auto &I : *QTB) |
| 2761 | if (&I != QStore && I.mayReadOrWriteMemory()) |
| 2762 | return false; |
| 2763 | for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); |
| 2764 | I != E; ++I) |
| 2765 | if (&*I != PStore && I->mayReadOrWriteMemory()) |
| 2766 | return false; |
| 2767 | |
| 2768 | // OK, we're going to sink the stores to PostBB. The store has to be |
| 2769 | // conditional though, so first create the predicate. |
| 2770 | Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) |
| 2771 | ->getCondition(); |
| 2772 | Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) |
| 2773 | ->getCondition(); |
| 2774 | |
| 2775 | Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), |
| 2776 | PStore->getParent()); |
| 2777 | Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), |
| 2778 | QStore->getParent(), PPHI); |
| 2779 | |
Duncan P. N. Exon Smith | 83c4b68 | 2015-11-07 00:01:16 +0000 | [diff] [blame] | 2780 | IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); |
| 2781 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2782 | Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); |
| 2783 | Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); |
| 2784 | |
| 2785 | if (InvertPCond) |
| 2786 | PPred = QB.CreateNot(PPred); |
| 2787 | if (InvertQCond) |
| 2788 | QPred = QB.CreateNot(QPred); |
| 2789 | Value *CombinedPred = QB.CreateOr(PPred, QPred); |
| 2790 | |
Duncan P. N. Exon Smith | 83c4b68 | 2015-11-07 00:01:16 +0000 | [diff] [blame] | 2791 | auto *T = |
| 2792 | SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2793 | QB.SetInsertPoint(T); |
| 2794 | StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); |
| 2795 | AAMDNodes AAMD; |
| 2796 | PStore->getAAMetadata(AAMD, /*Merge=*/false); |
| 2797 | PStore->getAAMetadata(AAMD, /*Merge=*/true); |
| 2798 | SI->setAAMetadata(AAMD); |
| 2799 | |
| 2800 | QStore->eraseFromParent(); |
| 2801 | PStore->eraseFromParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2802 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2803 | return true; |
| 2804 | } |
| 2805 | |
| 2806 | static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) { |
| 2807 | // The intention here is to find diamonds or triangles (see below) where each |
| 2808 | // conditional block contains a store to the same address. Both of these |
| 2809 | // stores are conditional, so they can't be unconditionally sunk. But it may |
| 2810 | // be profitable to speculatively sink the stores into one merged store at the |
| 2811 | // end, and predicate the merged store on the union of the two conditions of |
| 2812 | // PBI and QBI. |
| 2813 | // |
| 2814 | // This can reduce the number of stores executed if both of the conditions are |
| 2815 | // true, and can allow the blocks to become small enough to be if-converted. |
| 2816 | // This optimization will also chain, so that ladders of test-and-set |
| 2817 | // sequences can be if-converted away. |
| 2818 | // |
| 2819 | // We only deal with simple diamonds or triangles: |
| 2820 | // |
| 2821 | // PBI or PBI or a combination of the two |
| 2822 | // / \ | \ |
| 2823 | // PTB PFB | PFB |
| 2824 | // \ / | / |
| 2825 | // QBI QBI |
| 2826 | // / \ | \ |
| 2827 | // QTB QFB | QFB |
| 2828 | // \ / | / |
| 2829 | // PostBB PostBB |
| 2830 | // |
| 2831 | // We model triangles as a type of diamond with a nullptr "true" block. |
| 2832 | // Triangles are canonicalized so that the fallthrough edge is represented by |
| 2833 | // a true condition, as in the diagram above. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2834 | // |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2835 | BasicBlock *PTB = PBI->getSuccessor(0); |
| 2836 | BasicBlock *PFB = PBI->getSuccessor(1); |
| 2837 | BasicBlock *QTB = QBI->getSuccessor(0); |
| 2838 | BasicBlock *QFB = QBI->getSuccessor(1); |
| 2839 | BasicBlock *PostBB = QFB->getSingleSuccessor(); |
| 2840 | |
| 2841 | bool InvertPCond = false, InvertQCond = false; |
| 2842 | // Canonicalize fallthroughs to the true branches. |
| 2843 | if (PFB == QBI->getParent()) { |
| 2844 | std::swap(PFB, PTB); |
| 2845 | InvertPCond = true; |
| 2846 | } |
| 2847 | if (QFB == PostBB) { |
| 2848 | std::swap(QFB, QTB); |
| 2849 | InvertQCond = true; |
| 2850 | } |
| 2851 | |
| 2852 | // From this point on we can assume PTB or QTB may be fallthroughs but PFB |
| 2853 | // and QFB may not. Model fallthroughs as a nullptr block. |
| 2854 | if (PTB == QBI->getParent()) |
| 2855 | PTB = nullptr; |
| 2856 | if (QTB == PostBB) |
| 2857 | QTB = nullptr; |
| 2858 | |
| 2859 | // Legality bailouts. We must have at least the non-fallthrough blocks and |
| 2860 | // the post-dominating block, and the non-fallthroughs must only have one |
| 2861 | // predecessor. |
| 2862 | auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2863 | return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2864 | }; |
| 2865 | if (!PostBB || |
| 2866 | !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || |
| 2867 | !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) |
| 2868 | return false; |
| 2869 | if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || |
| 2870 | (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) |
| 2871 | return false; |
| 2872 | if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2) |
| 2873 | return false; |
| 2874 | |
| 2875 | // OK, this is a sequence of two diamonds or triangles. |
| 2876 | // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2877 | SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2878 | for (auto *BB : {PTB, PFB}) { |
| 2879 | if (!BB) |
| 2880 | continue; |
| 2881 | for (auto &I : *BB) |
| 2882 | if (StoreInst *SI = dyn_cast<StoreInst>(&I)) |
| 2883 | PStoreAddresses.insert(SI->getPointerOperand()); |
| 2884 | } |
| 2885 | for (auto *BB : {QTB, QFB}) { |
| 2886 | if (!BB) |
| 2887 | continue; |
| 2888 | for (auto &I : *BB) |
| 2889 | if (StoreInst *SI = dyn_cast<StoreInst>(&I)) |
| 2890 | QStoreAddresses.insert(SI->getPointerOperand()); |
| 2891 | } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2892 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2893 | set_intersect(PStoreAddresses, QStoreAddresses); |
| 2894 | // set_intersect mutates PStoreAddresses in place. Rename it here to make it |
| 2895 | // clear what it contains. |
| 2896 | auto &CommonAddresses = PStoreAddresses; |
| 2897 | |
| 2898 | bool Changed = false; |
| 2899 | for (auto *Address : CommonAddresses) |
| 2900 | Changed |= mergeConditionalStoreToAddress( |
| 2901 | PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond); |
| 2902 | return Changed; |
| 2903 | } |
| 2904 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2905 | /// If we have a conditional branch as a predecessor of another block, |
| 2906 | /// this function tries to simplify it. We know |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2907 | /// that PBI and BI are both conditional branches, and BI is in one of the |
| 2908 | /// successor blocks of PBI - PBI branches to BI. |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 2909 | static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, |
| 2910 | const DataLayout &DL) { |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2911 | assert(PBI->isConditional() && BI->isConditional()); |
| 2912 | BasicBlock *BB = BI->getParent(); |
Dan Gohman | 5476cfd | 2009-08-12 16:23:25 +0000 | [diff] [blame] | 2913 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2914 | // If this block ends with a branch instruction, and if there is a |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2915 | // predecessor that ends on a branch of the same condition, make |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2916 | // this conditional branch redundant. |
| 2917 | if (PBI->getCondition() == BI->getCondition() && |
| 2918 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2919 | // Okay, the outcome of this conditional branch is statically |
| 2920 | // knowable. If this block had a single pred, handle specially. |
| 2921 | if (BB->getSinglePredecessor()) { |
| 2922 | // Turn this into a branch on constant. |
| 2923 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2924 | BI->setCondition( |
| 2925 | ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); |
| 2926 | return true; // Nuke the branch on constant. |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2927 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2928 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2929 | // Otherwise, if there are multiple predecessors, insert a PHI that merges |
| 2930 | // in the constant and simplify the block result. Subsequent passes of |
| 2931 | // simplifycfg will thread the block. |
| 2932 | if (BlockIsSimpleEnoughToThreadThrough(BB)) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2933 | pred_iterator PB = pred_begin(BB), PE = pred_end(BB); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2934 | PHINode *NewPN = PHINode::Create( |
| 2935 | Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), |
| 2936 | BI->getCondition()->getName() + ".pr", &BB->front()); |
Chris Lattner | 5eed372 | 2008-07-13 21:55:46 +0000 | [diff] [blame] | 2937 | // Okay, we're going to insert the PHI node. Since PBI is not the only |
| 2938 | // predecessor, compute the PHI'd conditional value for all of the preds. |
| 2939 | // Any predecessor where the condition is not computable we keep symbolic. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2940 | for (pred_iterator PI = PB; PI != PE; ++PI) { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2941 | BasicBlock *P = *PI; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2942 | if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && |
| 2943 | PBI->isConditional() && PBI->getCondition() == BI->getCondition() && |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2944 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2945 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 2946 | NewPN->addIncoming( |
| 2947 | ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), |
| 2948 | P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2949 | } else { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2950 | NewPN->addIncoming(BI->getCondition(), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2951 | } |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2952 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2953 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2954 | BI->setCondition(NewPN); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2955 | return true; |
| 2956 | } |
| 2957 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2958 | |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 2959 | if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) |
| 2960 | if (CE->canTrap()) |
| 2961 | return false; |
| 2962 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2963 | // If both branches are conditional and both contain stores to the same |
| 2964 | // address, remove the stores from the conditionals and create a conditional |
| 2965 | // merged store at the end. |
| 2966 | if (MergeCondStores && mergeConditionalStores(PBI, BI)) |
| 2967 | return true; |
| 2968 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2969 | // If this is a conditional branch in an empty block, and if any |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2970 | // predecessors are a conditional branch to one of our destinations, |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2971 | // fold the conditions into logical ops and one cond br. |
Zhou Sheng | 264e46e | 2009-02-26 06:56:37 +0000 | [diff] [blame] | 2972 | BasicBlock::iterator BBI = BB->begin(); |
| 2973 | // Ignore dbg intrinsics. |
| 2974 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 2975 | ++BBI; |
| 2976 | if (&*BBI != BI) |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2977 | return false; |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2978 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2979 | int PBIOp, BIOp; |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2980 | if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { |
| 2981 | PBIOp = 0; |
| 2982 | BIOp = 0; |
| 2983 | } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { |
| 2984 | PBIOp = 0; |
| 2985 | BIOp = 1; |
| 2986 | } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { |
| 2987 | PBIOp = 1; |
| 2988 | BIOp = 0; |
| 2989 | } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { |
| 2990 | PBIOp = 1; |
| 2991 | BIOp = 1; |
| 2992 | } else { |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2993 | return false; |
Richard Trieu | 7a08381 | 2016-02-18 22:09:30 +0000 | [diff] [blame] | 2994 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2995 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2996 | // Check to make sure that the other destination of this branch |
| 2997 | // isn't BB itself. If so, this is an infinite loop that will |
| 2998 | // keep getting unwound. |
| 2999 | if (PBI->getSuccessor(PBIOp) == BB) |
| 3000 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3001 | |
| 3002 | // Do not perform this transformation if it would require |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3003 | // insertion of a large number of select instructions. For targets |
| 3004 | // without predication/cmovs, this is a big pessimization. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3005 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 3006 | // Also do not perform this transformation if any phi node in the common |
| 3007 | // destination block can trap when reached by BB or PBB (PR17073). In that |
| 3008 | // case, it would be unsafe to hoist the operation into a select instruction. |
| 3009 | |
| 3010 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3011 | unsigned NumPhis = 0; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3012 | for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); |
| 3013 | ++II, ++NumPhis) { |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3014 | if (NumPhis > 2) // Disable this xform. |
| 3015 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3016 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 3017 | PHINode *PN = cast<PHINode>(II); |
| 3018 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 3019 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) |
| 3020 | if (CE->canTrap()) |
| 3021 | return false; |
| 3022 | |
| 3023 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 3024 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 3025 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) |
| 3026 | if (CE->canTrap()) |
| 3027 | return false; |
| 3028 | } |
| 3029 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3030 | // Finally, if everything is ok, fold the branches to logical ops. |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 3031 | BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3032 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 3033 | DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 3034 | << "AND: " << *BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3035 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 3036 | // If OtherDest *is* BB, then BB is a basic block with a single conditional |
| 3037 | // branch in it, where one edge (OtherDest) goes back to itself but the other |
| 3038 | // exits. We don't *know* that the program avoids the infinite loop |
| 3039 | // (even though that seems likely). If we do this xform naively, we'll end up |
| 3040 | // recursively unpeeling the loop. Since we know that (after the xform is |
| 3041 | // done) that the block *is* infinite if reached, we just make it an obviously |
| 3042 | // infinite loop with no cond branch. |
| 3043 | if (OtherDest == BB) { |
| 3044 | // Insert it at the end of the function, because it's either code, |
| 3045 | // or it won't matter if it's hot. :) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3046 | BasicBlock *InfLoopBlock = |
| 3047 | BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 3048 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
| 3049 | OtherDest = InfLoopBlock; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3050 | } |
| 3051 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 3052 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 3053 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3054 | // BI may have other predecessors. Because of this, we leave |
| 3055 | // it alone, but modify PBI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3056 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3057 | // Make sure we get to CommonDest on True&True directions. |
| 3058 | Value *PBICond = PBI->getCondition(); |
Mehdi Amini | ba9fba8 | 2016-03-13 21:05:13 +0000 | [diff] [blame] | 3059 | IRBuilder<NoFolder> Builder(PBI); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3060 | if (PBIOp) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3061 | PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 3062 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3063 | Value *BICond = BI->getCondition(); |
| 3064 | if (BIOp) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3065 | BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 3066 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3067 | // Merge the conditions. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 3068 | Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3069 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3070 | // Modify PBI to branch on the new condition to the new dests. |
| 3071 | PBI->setCondition(Cond); |
| 3072 | PBI->setSuccessor(0, CommonDest); |
| 3073 | PBI->setSuccessor(1, OtherDest); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3074 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 3075 | // Update branch weight for PBI. |
| 3076 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Dehao Chen | b76e5d9 | 2016-05-10 23:07:19 +0000 | [diff] [blame] | 3077 | uint64_t PredCommon, PredOther, SuccCommon, SuccOther; |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 3078 | bool HasWeights = |
| 3079 | extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, |
| 3080 | SuccTrueWeight, SuccFalseWeight); |
Dehao Chen | b76e5d9 | 2016-05-10 23:07:19 +0000 | [diff] [blame] | 3081 | if (HasWeights) { |
Dehao Chen | b76e5d9 | 2016-05-10 23:07:19 +0000 | [diff] [blame] | 3082 | PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; |
| 3083 | PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; |
| 3084 | SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; |
| 3085 | SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 3086 | // The weight to CommonDest should be PredCommon * SuccTotal + |
| 3087 | // PredOther * SuccCommon. |
| 3088 | // The weight to OtherDest should be PredOther * SuccOther. |
Benjamin Kramer | ea68a94 | 2015-02-19 15:26:17 +0000 | [diff] [blame] | 3089 | uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + |
| 3090 | PredOther * SuccCommon, |
| 3091 | PredOther * SuccOther}; |
Sanjay Patel | 84a0bf6 | 2016-05-06 17:51:37 +0000 | [diff] [blame] | 3092 | // Halve the weights if any of them cannot fit in an uint32_t |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 3093 | FitWeights(NewWeights); |
| 3094 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 3095 | PBI->setMetadata(LLVMContext::MD_prof, |
Sanjay Patel | 84a0bf6 | 2016-05-06 17:51:37 +0000 | [diff] [blame] | 3096 | MDBuilder(BI->getContext()) |
| 3097 | .createBranchWeights(NewWeights[0], NewWeights[1])); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 3098 | } |
| 3099 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3100 | // OtherDest may have phi nodes. If so, add an entry from PBI's |
| 3101 | // block that are identical to the entries for BI's block. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 3102 | AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3103 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3104 | // We know that the CommonDest already had an edge from PBI to |
| 3105 | // it. If it has PHIs though, the PHIs may have different |
| 3106 | // entries for BB and PBI's BB. If so, insert a select to make |
| 3107 | // them agree. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 3108 | PHINode *PN; |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3109 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 3110 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 3111 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 3112 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 3113 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 3114 | if (BIV != PBIV) { |
| 3115 | // Insert a select in PBI to pick the right value. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3116 | SelectInst *NV = cast<SelectInst>( |
| 3117 | Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3118 | PN->setIncomingValue(PBBIdx, NV); |
Sanjay Patel | 1cb6241 | 2016-05-06 18:07:46 +0000 | [diff] [blame] | 3119 | // Although the select has the same condition as PBI, the original branch |
| 3120 | // weights for PBI do not apply to the new select because the select's |
| 3121 | // 'logical' edges are incoming edges of the phi that is eliminated, not |
| 3122 | // the outgoing edges of PBI. |
Dehao Chen | f16376b | 2016-05-18 22:41:03 +0000 | [diff] [blame] | 3123 | if (HasWeights) { |
Sanjay Patel | 1cb6241 | 2016-05-06 18:07:46 +0000 | [diff] [blame] | 3124 | uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; |
| 3125 | uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; |
| 3126 | uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; |
| 3127 | uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; |
| 3128 | // The weight to PredCommonDest should be PredCommon * SuccTotal. |
| 3129 | // The weight to PredOtherDest should be PredOther * SuccCommon. |
| 3130 | uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), |
| 3131 | PredOther * SuccCommon}; |
| 3132 | |
| 3133 | FitWeights(NewWeights); |
| 3134 | |
| 3135 | NV->setMetadata(LLVMContext::MD_prof, |
| 3136 | MDBuilder(BI->getContext()) |
| 3137 | .createBranchWeights(NewWeights[0], NewWeights[1])); |
| 3138 | } |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 3139 | } |
| 3140 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3141 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 3142 | DEBUG(dbgs() << "INTO: " << *PBI->getParent()); |
| 3143 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3144 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 3145 | // This basic block is probably dead. We know it has at least |
| 3146 | // one fewer predecessor. |
| 3147 | return true; |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 3148 | } |
| 3149 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3150 | // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is |
| 3151 | // true or to FalseBB if Cond is false. |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3152 | // Takes care of updating the successors and removing the old terminator. |
| 3153 | // Also makes sure not to introduce new successors by assuming that edges to |
| 3154 | // non-successor TrueBBs and FalseBBs aren't reachable. |
| 3155 | static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3156 | BasicBlock *TrueBB, BasicBlock *FalseBB, |
| 3157 | uint32_t TrueWeight, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3158 | uint32_t FalseWeight) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3159 | // Remove any superfluous successor edges from the CFG. |
| 3160 | // First, figure out which successors to preserve. |
| 3161 | // If TrueBB and FalseBB are equal, only try to preserve one copy of that |
| 3162 | // successor. |
| 3163 | BasicBlock *KeepEdge1 = TrueBB; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3164 | BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3165 | |
| 3166 | // Then remove the rest. |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 3167 | for (BasicBlock *Succ : OldTerm->successors()) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3168 | // Make sure only to keep exactly one copy of each edge. |
| 3169 | if (Succ == KeepEdge1) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3170 | KeepEdge1 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3171 | else if (Succ == KeepEdge2) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3172 | KeepEdge2 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3173 | else |
David Majnemer | dc3b67b | 2015-10-21 18:22:24 +0000 | [diff] [blame] | 3174 | Succ->removePredecessor(OldTerm->getParent(), |
| 3175 | /*DontDeleteUselessPHIs=*/true); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3176 | } |
| 3177 | |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 3178 | IRBuilder<> Builder(OldTerm); |
| 3179 | Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); |
| 3180 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3181 | // Insert an appropriate new terminator. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3182 | if (!KeepEdge1 && !KeepEdge2) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3183 | if (TrueBB == FalseBB) |
| 3184 | // We were only looking for one successor, and it was present. |
| 3185 | // Create an unconditional branch to it. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 3186 | Builder.CreateBr(TrueBB); |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3187 | else { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3188 | // We found both of the successors we were looking for. |
| 3189 | // Create a conditional branch sharing the condition of the select. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3190 | BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); |
| 3191 | if (TrueWeight != FalseWeight) |
| 3192 | NewBI->setMetadata(LLVMContext::MD_prof, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3193 | MDBuilder(OldTerm->getContext()) |
| 3194 | .createBranchWeights(TrueWeight, FalseWeight)); |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3195 | } |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3196 | } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { |
| 3197 | // Neither of the selected blocks were successors, so this |
| 3198 | // terminator must be unreachable. |
| 3199 | new UnreachableInst(OldTerm->getContext(), OldTerm); |
| 3200 | } else { |
| 3201 | // One of the selected values was a successor, but the other wasn't. |
| 3202 | // Insert an unconditional branch to the one that was found; |
| 3203 | // the edge to the one that wasn't must be unreachable. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3204 | if (!KeepEdge1) |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3205 | // Only TrueBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 3206 | Builder.CreateBr(TrueBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3207 | else |
| 3208 | // Only FalseBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 3209 | Builder.CreateBr(FalseBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3210 | } |
| 3211 | |
| 3212 | EraseTerminatorInstAndDCECond(OldTerm); |
| 3213 | return true; |
| 3214 | } |
| 3215 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3216 | // Replaces |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 3217 | // (switch (select cond, X, Y)) on constant X, Y |
| 3218 | // with a branch - conditional if X and Y lead to distinct BBs, |
| 3219 | // unconditional otherwise. |
| 3220 | static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { |
| 3221 | // Check for constant integer values in the select. |
| 3222 | ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); |
| 3223 | ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); |
| 3224 | if (!TrueVal || !FalseVal) |
| 3225 | return false; |
| 3226 | |
| 3227 | // Find the relevant condition and destinations. |
| 3228 | Value *Condition = Select->getCondition(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3229 | BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); |
| 3230 | BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 3231 | |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3232 | // Get weight for TrueBB and FalseBB. |
| 3233 | uint32_t TrueWeight = 0, FalseWeight = 0; |
| 3234 | SmallVector<uint64_t, 8> Weights; |
| 3235 | bool HasWeights = HasBranchWeights(SI); |
| 3236 | if (HasWeights) { |
| 3237 | GetBranchWeights(SI, Weights); |
| 3238 | if (Weights.size() == 1 + SI->getNumCases()) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3239 | TrueWeight = |
| 3240 | (uint32_t)Weights[SI->findCaseValue(TrueVal).getSuccessorIndex()]; |
| 3241 | FalseWeight = |
| 3242 | (uint32_t)Weights[SI->findCaseValue(FalseVal).getSuccessorIndex()]; |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 3243 | } |
| 3244 | } |
| 3245 | |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 3246 | // Perform the actual simplification. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3247 | return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, |
| 3248 | FalseWeight); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 3249 | } |
| 3250 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3251 | // Replaces |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 3252 | // (indirectbr (select cond, blockaddress(@fn, BlockA), |
| 3253 | // blockaddress(@fn, BlockB))) |
| 3254 | // with |
| 3255 | // (br cond, BlockA, BlockB). |
| 3256 | static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { |
| 3257 | // Check that both operands of the select are block addresses. |
| 3258 | BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); |
| 3259 | BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); |
| 3260 | if (!TBA || !FBA) |
| 3261 | return false; |
| 3262 | |
| 3263 | // Extract the actual blocks. |
| 3264 | BasicBlock *TrueBB = TBA->getBasicBlock(); |
| 3265 | BasicBlock *FalseBB = FBA->getBasicBlock(); |
| 3266 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 3267 | // Perform the actual simplification. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3268 | return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, |
| 3269 | 0); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 3270 | } |
| 3271 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3272 | /// This is called when we find an icmp instruction |
| 3273 | /// (a seteq/setne with a constant) as the only instruction in a |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3274 | /// block that ends with an uncond branch. We are looking for a very specific |
| 3275 | /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In |
| 3276 | /// this case, we merge the first two "or's of icmp" into a switch, but then the |
| 3277 | /// default value goes to an uncond block with a seteq in it, we get something |
| 3278 | /// like: |
| 3279 | /// |
| 3280 | /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] |
| 3281 | /// DEFAULT: |
| 3282 | /// %tmp = icmp eq i8 %A, 92 |
| 3283 | /// br label %end |
| 3284 | /// end: |
| 3285 | /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3286 | /// |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3287 | /// We prefer to split the edge to 'end' so that there is a true/false entry to |
| 3288 | /// the PHI, merging the third icmp into the switch. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 3289 | static bool TryToSimplifyUncondBranchWithICmpInIt( |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3290 | ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, |
| 3291 | const TargetTransformInfo &TTI, unsigned BonusInstThreshold, |
| 3292 | AssumptionCache *AC) { |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3293 | BasicBlock *BB = ICI->getParent(); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 3294 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3295 | // If the block has any PHIs in it or the icmp has multiple uses, it is too |
| 3296 | // complex. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3297 | if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) |
| 3298 | return false; |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3299 | |
| 3300 | Value *V = ICI->getOperand(0); |
| 3301 | ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3302 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3303 | // The pattern we're looking for is where our only predecessor is a switch on |
| 3304 | // 'V' and this block is the default case for the switch. In this case we can |
| 3305 | // fold the compared value into the switch to simplify things. |
| 3306 | BasicBlock *Pred = BB->getSinglePredecessor(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3307 | if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) |
| 3308 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3309 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3310 | SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); |
| 3311 | if (SI->getCondition() != V) |
| 3312 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3313 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3314 | // If BB is reachable on a non-default case, then we simply know the value of |
| 3315 | // V in this block. Substitute it and constant fold the icmp instruction |
| 3316 | // away. |
| 3317 | if (SI->getDefaultDest() != BB) { |
| 3318 | ConstantInt *VVal = SI->findCaseDest(BB); |
| 3319 | assert(VVal && "Should have a unique destination value"); |
| 3320 | ICI->setOperand(0, VVal); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3321 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3322 | if (Value *V = SimplifyInstruction(ICI, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3323 | ICI->replaceAllUsesWith(V); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3324 | ICI->eraseFromParent(); |
| 3325 | } |
| 3326 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3327 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3328 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3329 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3330 | // Ok, the block is reachable from the default dest. If the constant we're |
| 3331 | // comparing exists in one of the other edges, then we can constant fold ICI |
| 3332 | // and zap it. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3333 | if (SI->findCaseValue(Cst) != SI->case_default()) { |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3334 | Value *V; |
| 3335 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 3336 | V = ConstantInt::getFalse(BB->getContext()); |
| 3337 | else |
| 3338 | V = ConstantInt::getTrue(BB->getContext()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3339 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3340 | ICI->replaceAllUsesWith(V); |
| 3341 | ICI->eraseFromParent(); |
| 3342 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3343 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3344 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3345 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3346 | // The use of the icmp has to be in the 'end' block, by the only PHI node in |
| 3347 | // the block. |
| 3348 | BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3349 | PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3350 | if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3351 | isa<PHINode>(++BasicBlock::iterator(PHIUse))) |
| 3352 | return false; |
| 3353 | |
| 3354 | // If the icmp is a SETEQ, then the default dest gets false, the new edge gets |
| 3355 | // true in the PHI. |
| 3356 | Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3357 | Constant *NewCst = ConstantInt::getFalse(BB->getContext()); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3358 | |
| 3359 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 3360 | std::swap(DefaultCst, NewCst); |
| 3361 | |
| 3362 | // Replace ICI (which is used by the PHI for the default value) with true or |
| 3363 | // false depending on if it is EQ or NE. |
| 3364 | ICI->replaceAllUsesWith(DefaultCst); |
| 3365 | ICI->eraseFromParent(); |
| 3366 | |
| 3367 | // Okay, the switch goes to this block on a default value. Add an edge from |
| 3368 | // the switch to the merge point on the compared value. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3369 | BasicBlock *NewBB = |
| 3370 | BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 3371 | SmallVector<uint64_t, 8> Weights; |
| 3372 | bool HasWeights = HasBranchWeights(SI); |
| 3373 | if (HasWeights) { |
| 3374 | GetBranchWeights(SI, Weights); |
| 3375 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 3376 | // Split weight for default case to case for "Cst". |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3377 | Weights[0] = (Weights[0] + 1) >> 1; |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 3378 | Weights.push_back(Weights[0]); |
| 3379 | |
| 3380 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3381 | SI->setMetadata( |
| 3382 | LLVMContext::MD_prof, |
| 3383 | MDBuilder(SI->getContext()).createBranchWeights(MDWeights)); |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 3384 | } |
| 3385 | } |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3386 | SI->addCase(Cst, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3387 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3388 | // NewBB branches to the phi block, add the uncond branch and the phi entry. |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 3389 | Builder.SetInsertPoint(NewBB); |
| 3390 | Builder.SetCurrentDebugLocation(SI->getDebugLoc()); |
| 3391 | Builder.CreateBr(SuccBlock); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3392 | PHIUse->addIncoming(NewCst, NewBB); |
| 3393 | return true; |
| 3394 | } |
| 3395 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3396 | /// The specified branch is a conditional branch. |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3397 | /// Check to see if it is branching on an or/and chain of icmp instructions, and |
| 3398 | /// fold it into a switch instruction if so. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3399 | static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, |
| 3400 | const DataLayout &DL) { |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3401 | Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3402 | if (!Cond) |
| 3403 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3404 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3405 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 3406 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 3407 | // 'setne's and'ed together, collect them. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3408 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 3409 | // Try to gather values from a chain of and/or to be turned into a switch |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 3410 | ConstantComparesGatherer ConstantCompare(Cond, DL); |
| 3411 | // Unpack the result |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3412 | SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 3413 | Value *CompVal = ConstantCompare.CompValue; |
| 3414 | unsigned UsedICmps = ConstantCompare.UsedICmps; |
| 3415 | Value *ExtraCase = ConstantCompare.Extra; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3416 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3417 | // If we didn't have a multiply compared value, fail. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3418 | if (!CompVal) |
| 3419 | return false; |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3420 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 3421 | // Avoid turning single icmps into a switch. |
| 3422 | if (UsedICmps <= 1) |
| 3423 | return false; |
| 3424 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 3425 | bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); |
| 3426 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3427 | // There might be duplicate constants in the list, which the switch |
| 3428 | // instruction can't handle, remove them now. |
| 3429 | array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); |
| 3430 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3431 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3432 | // If Extra was used, we require at least two switch values to do the |
Sanjay Patel | 5966145 | 2015-09-10 15:14:34 +0000 | [diff] [blame] | 3433 | // transformation. A switch with one value is just a conditional branch. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3434 | if (ExtraCase && Values.size() < 2) |
| 3435 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3436 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 3437 | // TODO: Preserve branch weight metadata, similarly to how |
| 3438 | // FoldValueComparisonIntoPredecessors preserves it. |
| 3439 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3440 | // Figure out which block is which destination. |
| 3441 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3442 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 3443 | if (!TrueWhenEqual) |
| 3444 | std::swap(DefaultBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3445 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3446 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3447 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3448 | DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3449 | << " cases into SWITCH. BB is:\n" |
| 3450 | << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3451 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3452 | // If there are any extra values that couldn't be folded into the switch |
| 3453 | // then we evaluate them with an explicit branch first. Split the block |
| 3454 | // right before the condbr to handle it. |
| 3455 | if (ExtraCase) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3456 | BasicBlock *NewBB = |
| 3457 | BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3458 | // Remove the uncond branch added to the old block. |
| 3459 | TerminatorInst *OldTI = BB->getTerminator(); |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3460 | Builder.SetInsertPoint(OldTI); |
| 3461 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 3462 | if (TrueWhenEqual) |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3463 | Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 3464 | else |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3465 | Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3466 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3467 | OldTI->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3468 | |
Chris Lattner | cb570f8 | 2010-12-13 05:34:18 +0000 | [diff] [blame] | 3469 | // If there are PHI nodes in EdgeBB, then we need to add a new entry to them |
| 3470 | // for the edge we just added. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 3471 | AddPredecessorToBlock(EdgeBB, BB, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3472 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3473 | DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3474 | << "\nEXTRABB = " << *BB); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3475 | BB = NewBB; |
| 3476 | } |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3477 | |
| 3478 | Builder.SetInsertPoint(BI); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3479 | // Convert pointer to int before we switch. |
| 3480 | if (CompVal->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3481 | CompVal = Builder.CreatePtrToInt( |
| 3482 | CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3483 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3484 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3485 | // Create the new switch instruction now. |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3486 | SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 3487 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3488 | // Add all of the 'cases' to the switch instruction. |
| 3489 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 3490 | New->addCase(Values[i], EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3491 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3492 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 3493 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 3494 | // the number of edges added. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3495 | for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3496 | PHINode *PN = cast<PHINode>(BBI); |
| 3497 | Value *InVal = PN->getIncomingValueForBlock(BB); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3498 | for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3499 | PN->addIncoming(InVal, BB); |
| 3500 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3501 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3502 | // Erase the old branch instruction. |
| 3503 | EraseTerminatorInstAndDCECond(BI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3504 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3505 | DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3506 | return true; |
| 3507 | } |
| 3508 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3509 | bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3510 | if (isa<PHINode>(RI->getValue())) |
| 3511 | return SimplifyCommonResume(RI); |
| 3512 | else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && |
| 3513 | RI->getValue() == RI->getParent()->getFirstNonPHI()) |
| 3514 | // The resume must unwind the exception that caused control to branch here. |
| 3515 | return SimplifySingleResume(RI); |
Chen Li | 509ff21 | 2016-01-11 19:20:53 +0000 | [diff] [blame] | 3516 | |
| 3517 | return false; |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3518 | } |
| 3519 | |
| 3520 | // Simplify resume that is shared by several landing pads (phi of landing pad). |
| 3521 | bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) { |
| 3522 | BasicBlock *BB = RI->getParent(); |
| 3523 | |
| 3524 | // Check that there are no other instructions except for debug intrinsics |
| 3525 | // between the phi of landing pads (RI->getValue()) and resume instruction. |
| 3526 | BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(), |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3527 | E = RI->getIterator(); |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3528 | while (++I != E) |
| 3529 | if (!isa<DbgInfoIntrinsic>(I)) |
| 3530 | return false; |
| 3531 | |
| 3532 | SmallSet<BasicBlock *, 4> TrivialUnwindBlocks; |
| 3533 | auto *PhiLPInst = cast<PHINode>(RI->getValue()); |
| 3534 | |
| 3535 | // Check incoming blocks to see if any of them are trivial. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3536 | for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; |
| 3537 | Idx++) { |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3538 | auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); |
| 3539 | auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); |
| 3540 | |
| 3541 | // If the block has other successors, we can not delete it because |
| 3542 | // it has other dependents. |
| 3543 | if (IncomingBB->getUniqueSuccessor() != BB) |
| 3544 | continue; |
| 3545 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3546 | auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3547 | // Not the landing pad that caused the control to branch here. |
| 3548 | if (IncomingValue != LandingPad) |
| 3549 | continue; |
| 3550 | |
| 3551 | bool isTrivial = true; |
| 3552 | |
| 3553 | I = IncomingBB->getFirstNonPHI()->getIterator(); |
| 3554 | E = IncomingBB->getTerminator()->getIterator(); |
| 3555 | while (++I != E) |
| 3556 | if (!isa<DbgInfoIntrinsic>(I)) { |
| 3557 | isTrivial = false; |
| 3558 | break; |
| 3559 | } |
| 3560 | |
| 3561 | if (isTrivial) |
| 3562 | TrivialUnwindBlocks.insert(IncomingBB); |
| 3563 | } |
| 3564 | |
| 3565 | // If no trivial unwind blocks, don't do any simplifications. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3566 | if (TrivialUnwindBlocks.empty()) |
| 3567 | return false; |
Chen Li | 1689c2f | 2016-01-10 05:48:01 +0000 | [diff] [blame] | 3568 | |
| 3569 | // Turn all invokes that unwind here into calls. |
| 3570 | for (auto *TrivialBB : TrivialUnwindBlocks) { |
| 3571 | // Blocks that will be simplified should be removed from the phi node. |
| 3572 | // Note there could be multiple edges to the resume block, and we need |
| 3573 | // to remove them all. |
| 3574 | while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) |
| 3575 | BB->removePredecessor(TrivialBB, true); |
| 3576 | |
| 3577 | for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); |
| 3578 | PI != PE;) { |
| 3579 | BasicBlock *Pred = *PI++; |
| 3580 | removeUnwindEdge(Pred); |
| 3581 | } |
| 3582 | |
| 3583 | // In each SimplifyCFG run, only the current processed block can be erased. |
| 3584 | // Otherwise, it will break the iteration of SimplifyCFG pass. So instead |
| 3585 | // of erasing TrivialBB, we only remove the branch to the common resume |
| 3586 | // block so that we can later erase the resume block since it has no |
| 3587 | // predecessors. |
| 3588 | TrivialBB->getTerminator()->eraseFromParent(); |
| 3589 | new UnreachableInst(RI->getContext(), TrivialBB); |
| 3590 | } |
| 3591 | |
| 3592 | // Delete the resume block if all its predecessors have been removed. |
| 3593 | if (pred_empty(BB)) |
| 3594 | BB->eraseFromParent(); |
| 3595 | |
| 3596 | return !TrivialUnwindBlocks.empty(); |
| 3597 | } |
| 3598 | |
| 3599 | // Simplify resume that is only used by a single (non-phi) landing pad. |
| 3600 | bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) { |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3601 | BasicBlock *BB = RI->getParent(); |
| 3602 | LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3603 | assert(RI->getValue() == LPInst && |
| 3604 | "Resume must unwind the exception that caused control to here"); |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3605 | |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3606 | // Check that there are no other instructions except for debug intrinsics. |
| 3607 | BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator(); |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3608 | while (++I != E) |
| 3609 | if (!isa<DbgInfoIntrinsic>(I)) |
| 3610 | return false; |
| 3611 | |
Chen Li | c6e2878 | 2015-10-22 20:48:38 +0000 | [diff] [blame] | 3612 | // Turn all invokes that unwind here into calls and delete the basic block. |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3613 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 3614 | BasicBlock *Pred = *PI++; |
| 3615 | removeUnwindEdge(Pred); |
Chen Li | c6e2878 | 2015-10-22 20:48:38 +0000 | [diff] [blame] | 3616 | } |
| 3617 | |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3618 | // The landingpad is now unreachable. Zap it. |
| 3619 | BB->eraseFromParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3620 | if (LoopHeaders) |
| 3621 | LoopHeaders->erase(BB); |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3622 | return true; |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3623 | } |
| 3624 | |
David Majnemer | 1efa23d | 2016-02-20 01:07:45 +0000 | [diff] [blame] | 3625 | static bool removeEmptyCleanup(CleanupReturnInst *RI) { |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3626 | // If this is a trivial cleanup pad that executes no instructions, it can be |
| 3627 | // eliminated. If the cleanup pad continues to the caller, any predecessor |
| 3628 | // that is an EH pad will be updated to continue to the caller and any |
| 3629 | // predecessor that terminates with an invoke instruction will have its invoke |
| 3630 | // instruction converted to a call instruction. If the cleanup pad being |
| 3631 | // simplified does not continue to the caller, each predecessor will be |
| 3632 | // updated to continue to the unwind destination of the cleanup pad being |
| 3633 | // simplified. |
| 3634 | BasicBlock *BB = RI->getParent(); |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3635 | CleanupPadInst *CPInst = RI->getCleanupPad(); |
| 3636 | if (CPInst->getParent() != BB) |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3637 | // This isn't an empty cleanup. |
| 3638 | return false; |
| 3639 | |
David Majnemer | 2482e1c | 2016-06-04 23:50:03 +0000 | [diff] [blame] | 3640 | // We cannot kill the pad if it has multiple uses. This typically arises |
| 3641 | // from unreachable basic blocks. |
| 3642 | if (!CPInst->hasOneUse()) |
| 3643 | return false; |
| 3644 | |
David Majnemer | 9f92f4c | 2016-05-21 05:12:32 +0000 | [diff] [blame] | 3645 | // Check that there are no other instructions except for benign intrinsics. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3646 | BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator(); |
David Majnemer | 9f92f4c | 2016-05-21 05:12:32 +0000 | [diff] [blame] | 3647 | while (++I != E) { |
| 3648 | auto *II = dyn_cast<IntrinsicInst>(I); |
| 3649 | if (!II) |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3650 | return false; |
| 3651 | |
David Majnemer | 9f92f4c | 2016-05-21 05:12:32 +0000 | [diff] [blame] | 3652 | Intrinsic::ID IntrinsicID = II->getIntrinsicID(); |
| 3653 | switch (IntrinsicID) { |
| 3654 | case Intrinsic::dbg_declare: |
| 3655 | case Intrinsic::dbg_value: |
| 3656 | case Intrinsic::lifetime_end: |
| 3657 | break; |
| 3658 | default: |
| 3659 | return false; |
| 3660 | } |
| 3661 | } |
| 3662 | |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3663 | // If the cleanup return we are simplifying unwinds to the caller, this will |
| 3664 | // set UnwindDest to nullptr. |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3665 | BasicBlock *UnwindDest = RI->getUnwindDest(); |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3666 | Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3667 | |
| 3668 | // We're about to remove BB from the control flow. Before we do, sink any |
| 3669 | // PHINodes into the unwind destination. Doing this before changing the |
| 3670 | // control flow avoids some potentially slow checks, since we can currently |
| 3671 | // be certain that UnwindDest and BB have no common predecessors (since they |
| 3672 | // are both EH pads). |
| 3673 | if (UnwindDest) { |
| 3674 | // First, go through the PHI nodes in UnwindDest and update any nodes that |
| 3675 | // reference the block we are removing |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3676 | for (BasicBlock::iterator I = UnwindDest->begin(), |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3677 | IE = DestEHPad->getIterator(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3678 | I != IE; ++I) { |
| 3679 | PHINode *DestPN = cast<PHINode>(I); |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 3680 | |
Andrew Kaylor | 2a9a6d8 | 2015-09-05 01:00:51 +0000 | [diff] [blame] | 3681 | int Idx = DestPN->getBasicBlockIndex(BB); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3682 | // Since BB unwinds to UnwindDest, it has to be in the PHI node. |
Craig Topper | 02a55d7 | 2015-09-05 04:49:44 +0000 | [diff] [blame] | 3683 | assert(Idx != -1); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3684 | // This PHI node has an incoming value that corresponds to a control |
| 3685 | // path through the cleanup pad we are removing. If the incoming |
| 3686 | // value is in the cleanup pad, it must be a PHINode (because we |
| 3687 | // verified above that the block is otherwise empty). Otherwise, the |
| 3688 | // value is either a constant or a value that dominates the cleanup |
| 3689 | // pad being removed. |
| 3690 | // |
| 3691 | // Because BB and UnwindDest are both EH pads, all of their |
| 3692 | // predecessors must unwind to these blocks, and since no instruction |
| 3693 | // can have multiple unwind destinations, there will be no overlap in |
| 3694 | // incoming blocks between SrcPN and DestPN. |
| 3695 | Value *SrcVal = DestPN->getIncomingValue(Idx); |
| 3696 | PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); |
| 3697 | |
| 3698 | // Remove the entry for the block we are deleting. |
| 3699 | DestPN->removeIncomingValue(Idx, false); |
| 3700 | |
| 3701 | if (SrcPN && SrcPN->getParent() == BB) { |
| 3702 | // If the incoming value was a PHI node in the cleanup pad we are |
| 3703 | // removing, we need to merge that PHI node's incoming values into |
| 3704 | // DestPN. |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 3705 | for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3706 | SrcIdx != SrcE; ++SrcIdx) { |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3707 | DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), |
| 3708 | SrcPN->getIncomingBlock(SrcIdx)); |
| 3709 | } |
| 3710 | } else { |
| 3711 | // Otherwise, the incoming value came from above BB and |
| 3712 | // so we can just reuse it. We must associate all of BB's |
| 3713 | // predecessors with this value. |
| 3714 | for (auto *pred : predecessors(BB)) { |
| 3715 | DestPN->addIncoming(SrcVal, pred); |
| 3716 | } |
| 3717 | } |
| 3718 | } |
| 3719 | |
| 3720 | // Sink any remaining PHI nodes directly into UnwindDest. |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3721 | Instruction *InsertPt = DestEHPad; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3722 | for (BasicBlock::iterator I = BB->begin(), |
| 3723 | IE = BB->getFirstNonPHI()->getIterator(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3724 | I != IE;) { |
| 3725 | // The iterator must be incremented here because the instructions are |
| 3726 | // being moved to another block. |
| 3727 | PHINode *PN = cast<PHINode>(I++); |
| 3728 | if (PN->use_empty()) |
| 3729 | // If the PHI node has no uses, just leave it. It will be erased |
| 3730 | // when we erase BB below. |
| 3731 | continue; |
| 3732 | |
| 3733 | // Otherwise, sink this PHI node into UnwindDest. |
| 3734 | // Any predecessors to UnwindDest which are not already represented |
| 3735 | // must be back edges which inherit the value from the path through |
| 3736 | // BB. In this case, the PHI value must reference itself. |
| 3737 | for (auto *pred : predecessors(UnwindDest)) |
| 3738 | if (pred != BB) |
| 3739 | PN->addIncoming(PN, pred); |
| 3740 | PN->moveBefore(InsertPt); |
| 3741 | } |
| 3742 | } |
| 3743 | |
| 3744 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 3745 | // The iterator must be updated here because we are removing this pred. |
| 3746 | BasicBlock *PredBB = *PI++; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3747 | if (UnwindDest == nullptr) { |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3748 | removeUnwindEdge(PredBB); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3749 | } else { |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3750 | TerminatorInst *TI = PredBB->getTerminator(); |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3751 | TI->replaceUsesOfWith(BB, UnwindDest); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3752 | } |
| 3753 | } |
| 3754 | |
| 3755 | // The cleanup pad is now unreachable. Zap it. |
| 3756 | BB->eraseFromParent(); |
| 3757 | return true; |
| 3758 | } |
| 3759 | |
David Majnemer | 1efa23d | 2016-02-20 01:07:45 +0000 | [diff] [blame] | 3760 | // Try to merge two cleanuppads together. |
| 3761 | static bool mergeCleanupPad(CleanupReturnInst *RI) { |
| 3762 | // Skip any cleanuprets which unwind to caller, there is nothing to merge |
| 3763 | // with. |
| 3764 | BasicBlock *UnwindDest = RI->getUnwindDest(); |
| 3765 | if (!UnwindDest) |
| 3766 | return false; |
| 3767 | |
| 3768 | // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't |
| 3769 | // be safe to merge without code duplication. |
| 3770 | if (UnwindDest->getSinglePredecessor() != RI->getParent()) |
| 3771 | return false; |
| 3772 | |
| 3773 | // Verify that our cleanuppad's unwind destination is another cleanuppad. |
| 3774 | auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); |
| 3775 | if (!SuccessorCleanupPad) |
| 3776 | return false; |
| 3777 | |
| 3778 | CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); |
| 3779 | // Replace any uses of the successor cleanupad with the predecessor pad |
| 3780 | // The only cleanuppad uses should be this cleanupret, it's cleanupret and |
| 3781 | // funclet bundle operands. |
| 3782 | SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); |
| 3783 | // Remove the old cleanuppad. |
| 3784 | SuccessorCleanupPad->eraseFromParent(); |
| 3785 | // Now, we simply replace the cleanupret with a branch to the unwind |
| 3786 | // destination. |
| 3787 | BranchInst::Create(UnwindDest, RI->getParent()); |
| 3788 | RI->eraseFromParent(); |
| 3789 | |
| 3790 | return true; |
| 3791 | } |
| 3792 | |
| 3793 | bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { |
David Majnemer | ee0cbbb | 2016-02-24 17:30:48 +0000 | [diff] [blame] | 3794 | // It is possible to transiantly have an undef cleanuppad operand because we |
| 3795 | // have deleted some, but not all, dead blocks. |
| 3796 | // Eventually, this block will be deleted. |
| 3797 | if (isa<UndefValue>(RI->getOperand(0))) |
| 3798 | return false; |
| 3799 | |
David Majnemer | 9f92f4c | 2016-05-21 05:12:32 +0000 | [diff] [blame] | 3800 | if (mergeCleanupPad(RI)) |
David Majnemer | 1efa23d | 2016-02-20 01:07:45 +0000 | [diff] [blame] | 3801 | return true; |
| 3802 | |
David Majnemer | 9f92f4c | 2016-05-21 05:12:32 +0000 | [diff] [blame] | 3803 | if (removeEmptyCleanup(RI)) |
David Majnemer | 1efa23d | 2016-02-20 01:07:45 +0000 | [diff] [blame] | 3804 | return true; |
| 3805 | |
| 3806 | return false; |
| 3807 | } |
| 3808 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3809 | bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3810 | BasicBlock *BB = RI->getParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3811 | if (!BB->getFirstNonPHIOrDbg()->isTerminator()) |
| 3812 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3813 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3814 | // Find predecessors that end with branches. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3815 | SmallVector<BasicBlock *, 8> UncondBranchPreds; |
| 3816 | SmallVector<BranchInst *, 8> CondBranchPreds; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 3817 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 3818 | BasicBlock *P = *PI; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3819 | TerminatorInst *PTI = P->getTerminator(); |
| 3820 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { |
| 3821 | if (BI->isUnconditional()) |
| 3822 | UncondBranchPreds.push_back(P); |
| 3823 | else |
| 3824 | CondBranchPreds.push_back(BI); |
| 3825 | } |
| 3826 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3827 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3828 | // If we found some, do the transformation! |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3829 | if (!UncondBranchPreds.empty() && DupRet) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3830 | while (!UncondBranchPreds.empty()) { |
| 3831 | BasicBlock *Pred = UncondBranchPreds.pop_back_val(); |
| 3832 | DEBUG(dbgs() << "FOLDING: " << *BB |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3833 | << "INTO UNCOND BRANCH PRED: " << *Pred); |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3834 | (void)FoldReturnIntoUncondBranch(RI, BB, Pred); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3835 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3836 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3837 | // If we eliminated all predecessors of the block, delete the block now. |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 3838 | if (pred_empty(BB)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3839 | // We know there are no successors, so just nuke the block. |
| 3840 | BB->eraseFromParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3841 | if (LoopHeaders) |
| 3842 | LoopHeaders->erase(BB); |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 3843 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3844 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3845 | return true; |
| 3846 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3847 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3848 | // Check out all of the conditional branches going to this return |
| 3849 | // instruction. If any of them just select between returns, change the |
| 3850 | // branch itself into a select/return pair. |
| 3851 | while (!CondBranchPreds.empty()) { |
| 3852 | BranchInst *BI = CondBranchPreds.pop_back_val(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3853 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3854 | // Check to see if the non-BB successor is also a return block. |
| 3855 | if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && |
| 3856 | isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3857 | SimplifyCondBranchToTwoReturns(BI, Builder)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3858 | return true; |
| 3859 | } |
| 3860 | return false; |
| 3861 | } |
| 3862 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3863 | bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { |
| 3864 | BasicBlock *BB = UI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3865 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3866 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3867 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3868 | // If there are any instructions immediately before the unreachable that can |
| 3869 | // be removed, do so. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3870 | while (UI->getIterator() != BB->begin()) { |
| 3871 | BasicBlock::iterator BBI = UI->getIterator(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3872 | --BBI; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3873 | // Do not delete instructions that can have side effects which might cause |
| 3874 | // the unreachable to not be reachable; specifically, calls and volatile |
| 3875 | // operations may have this effect. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3876 | if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) |
| 3877 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3878 | |
| 3879 | if (BBI->mayHaveSideEffects()) { |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3880 | if (auto *SI = dyn_cast<StoreInst>(BBI)) { |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3881 | if (SI->isVolatile()) |
| 3882 | break; |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3883 | } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3884 | if (LI->isVolatile()) |
| 3885 | break; |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3886 | } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3887 | if (RMWI->isVolatile()) |
| 3888 | break; |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3889 | } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3890 | if (CXI->isVolatile()) |
| 3891 | break; |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3892 | } else if (isa<CatchPadInst>(BBI)) { |
| 3893 | // A catchpad may invoke exception object constructors and such, which |
| 3894 | // in some languages can be arbitrary code, so be conservative by |
| 3895 | // default. |
| 3896 | // For CoreCLR, it just involves a type test, so can be removed. |
| 3897 | if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != |
| 3898 | EHPersonality::CoreCLR) |
| 3899 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3900 | } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && |
| 3901 | !isa<LandingPadInst>(BBI)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3902 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3903 | } |
Bill Wendling | 55d875f | 2011-08-16 20:41:17 +0000 | [diff] [blame] | 3904 | // Note that deleting LandingPad's here is in fact okay, although it |
| 3905 | // involves a bit of subtle reasoning. If this inst is a LandingPad, |
| 3906 | // all the predecessors of this block will be the unwind edges of Invokes, |
| 3907 | // and we can therefore guarantee this block will be erased. |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3908 | } |
| 3909 | |
Eli Friedman | aac35b3 | 2011-03-09 00:48:33 +0000 | [diff] [blame] | 3910 | // Delete this instruction (any uses are guaranteed to be dead) |
| 3911 | if (!BBI->use_empty()) |
| 3912 | BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3913 | BBI->eraseFromParent(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3914 | Changed = true; |
| 3915 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3916 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3917 | // If the unreachable instruction is the first in the block, take a gander |
| 3918 | // at all of the predecessors of this instruction, and simplify them. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3919 | if (&BB->front() != UI) |
| 3920 | return Changed; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3921 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3922 | SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3923 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 3924 | TerminatorInst *TI = Preds[i]->getTerminator(); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3925 | IRBuilder<> Builder(TI); |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3926 | if (auto *BI = dyn_cast<BranchInst>(TI)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3927 | if (BI->isUnconditional()) { |
| 3928 | if (BI->getSuccessor(0) == BB) { |
| 3929 | new UnreachableInst(TI->getContext(), TI); |
| 3930 | TI->eraseFromParent(); |
| 3931 | Changed = true; |
| 3932 | } |
| 3933 | } else { |
| 3934 | if (BI->getSuccessor(0) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3935 | Builder.CreateBr(BI->getSuccessor(1)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3936 | EraseTerminatorInstAndDCECond(BI); |
| 3937 | } else if (BI->getSuccessor(1) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3938 | Builder.CreateBr(BI->getSuccessor(0)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3939 | EraseTerminatorInstAndDCECond(BI); |
| 3940 | Changed = true; |
| 3941 | } |
| 3942 | } |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3943 | } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3944 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; |
| 3945 | ++i) |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3946 | if (i.getCaseSuccessor() == BB) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3947 | BB->removePredecessor(SI->getParent()); |
| 3948 | SI->removeCase(i); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3949 | --i; |
| 3950 | --e; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3951 | Changed = true; |
| 3952 | } |
Joseph Tremoulet | 0d80888 | 2016-01-05 02:37:41 +0000 | [diff] [blame] | 3953 | } else if (auto *II = dyn_cast<InvokeInst>(TI)) { |
| 3954 | if (II->getUnwindDest() == BB) { |
| 3955 | removeUnwindEdge(TI->getParent()); |
| 3956 | Changed = true; |
| 3957 | } |
| 3958 | } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { |
| 3959 | if (CSI->getUnwindDest() == BB) { |
| 3960 | removeUnwindEdge(TI->getParent()); |
| 3961 | Changed = true; |
| 3962 | continue; |
| 3963 | } |
| 3964 | |
| 3965 | for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), |
| 3966 | E = CSI->handler_end(); |
| 3967 | I != E; ++I) { |
| 3968 | if (*I == BB) { |
| 3969 | CSI->removeHandler(I); |
| 3970 | --I; |
| 3971 | --E; |
| 3972 | Changed = true; |
| 3973 | } |
| 3974 | } |
| 3975 | if (CSI->getNumHandlers() == 0) { |
| 3976 | BasicBlock *CatchSwitchBB = CSI->getParent(); |
| 3977 | if (CSI->hasUnwindDest()) { |
| 3978 | // Redirect preds to the unwind dest |
| 3979 | CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest()); |
| 3980 | } else { |
| 3981 | // Rewrite all preds to unwind to caller (or from invoke to call). |
| 3982 | SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB)); |
| 3983 | for (BasicBlock *EHPred : EHPreds) |
| 3984 | removeUnwindEdge(EHPred); |
| 3985 | } |
| 3986 | // The catchswitch is no longer reachable. |
| 3987 | new UnreachableInst(CSI->getContext(), CSI); |
| 3988 | CSI->eraseFromParent(); |
| 3989 | Changed = true; |
| 3990 | } |
David Majnemer | 8a1c45d | 2015-12-12 05:38:55 +0000 | [diff] [blame] | 3991 | } else if (isa<CleanupReturnInst>(TI)) { |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3992 | new UnreachableInst(TI->getContext(), TI); |
| 3993 | TI->eraseFromParent(); |
| 3994 | Changed = true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3995 | } |
| 3996 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3997 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3998 | // If this block is now dead, remove it. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 3999 | if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4000 | // We know there are no successors, so just nuke the block. |
| 4001 | BB->eraseFromParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4002 | if (LoopHeaders) |
| 4003 | LoopHeaders->erase(BB); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4004 | return true; |
| 4005 | } |
| 4006 | |
| 4007 | return Changed; |
| 4008 | } |
| 4009 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4010 | static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { |
| 4011 | assert(Cases.size() >= 1); |
| 4012 | |
| 4013 | array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); |
| 4014 | for (size_t I = 1, E = Cases.size(); I != E; ++I) { |
| 4015 | if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) |
| 4016 | return false; |
| 4017 | } |
| 4018 | return true; |
| 4019 | } |
| 4020 | |
| 4021 | /// Turn a switch with two reachable destinations into an integer range |
| 4022 | /// comparison and branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4023 | static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 4024 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4025 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4026 | bool HasDefault = |
| 4027 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 4028 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4029 | // Partition the cases into two sets with different destinations. |
| 4030 | BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; |
| 4031 | BasicBlock *DestB = nullptr; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4032 | SmallVector<ConstantInt *, 16> CasesA; |
| 4033 | SmallVector<ConstantInt *, 16> CasesB; |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4034 | |
| 4035 | for (SwitchInst::CaseIt I : SI->cases()) { |
| 4036 | BasicBlock *Dest = I.getCaseSuccessor(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4037 | if (!DestA) |
| 4038 | DestA = Dest; |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4039 | if (Dest == DestA) { |
| 4040 | CasesA.push_back(I.getCaseValue()); |
| 4041 | continue; |
| 4042 | } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4043 | if (!DestB) |
| 4044 | DestB = Dest; |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4045 | if (Dest == DestB) { |
| 4046 | CasesB.push_back(I.getCaseValue()); |
| 4047 | continue; |
| 4048 | } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4049 | return false; // More than two destinations. |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 4050 | } |
| 4051 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4052 | assert(DestA && DestB && |
| 4053 | "Single-destination switch should have been folded."); |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4054 | assert(DestA != DestB); |
| 4055 | assert(DestB != SI->getDefaultDest()); |
| 4056 | assert(!CasesB.empty() && "There must be non-default cases."); |
| 4057 | assert(!CasesA.empty() || HasDefault); |
| 4058 | |
| 4059 | // Figure out if one of the sets of cases form a contiguous range. |
| 4060 | SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; |
| 4061 | BasicBlock *ContiguousDest = nullptr; |
| 4062 | BasicBlock *OtherDest = nullptr; |
| 4063 | if (!CasesA.empty() && CasesAreContiguous(CasesA)) { |
| 4064 | ContiguousCases = &CasesA; |
| 4065 | ContiguousDest = DestA; |
| 4066 | OtherDest = DestB; |
| 4067 | } else if (CasesAreContiguous(CasesB)) { |
| 4068 | ContiguousCases = &CasesB; |
| 4069 | ContiguousDest = DestB; |
| 4070 | OtherDest = DestA; |
| 4071 | } else |
| 4072 | return false; |
| 4073 | |
| 4074 | // Start building the compare and branch. |
| 4075 | |
| 4076 | Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4077 | Constant *NumCases = |
| 4078 | ConstantInt::get(Offset->getType(), ContiguousCases->size()); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4079 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 4080 | Value *Sub = SI->getCondition(); |
| 4081 | if (!Offset->isNullValue()) |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4082 | Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); |
| 4083 | |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 4084 | Value *Cmp; |
| 4085 | // If NumCases overflowed, then all possible values jump to the successor. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4086 | if (NumCases->isNullValue() && !ContiguousCases->empty()) |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 4087 | Cmp = ConstantInt::getTrue(SI->getContext()); |
| 4088 | else |
| 4089 | Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4090 | BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4091 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4092 | // Update weight for the newly-created conditional branch. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4093 | if (HasBranchWeights(SI)) { |
| 4094 | SmallVector<uint64_t, 8> Weights; |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4095 | GetBranchWeights(SI, Weights); |
| 4096 | if (Weights.size() == 1 + SI->getNumCases()) { |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4097 | uint64_t TrueWeight = 0; |
| 4098 | uint64_t FalseWeight = 0; |
| 4099 | for (size_t I = 0, E = Weights.size(); I != E; ++I) { |
| 4100 | if (SI->getSuccessor(I) == ContiguousDest) |
| 4101 | TrueWeight += Weights[I]; |
| 4102 | else |
| 4103 | FalseWeight += Weights[I]; |
| 4104 | } |
| 4105 | while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { |
| 4106 | TrueWeight /= 2; |
| 4107 | FalseWeight /= 2; |
| 4108 | } |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4109 | NewBI->setMetadata(LLVMContext::MD_prof, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4110 | MDBuilder(SI->getContext()) |
| 4111 | .createBranchWeights((uint32_t)TrueWeight, |
| 4112 | (uint32_t)FalseWeight)); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4113 | } |
| 4114 | } |
| 4115 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4116 | // Prune obsolete incoming values off the successors' PHI nodes. |
| 4117 | for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 4118 | unsigned PreviousEdges = ContiguousCases->size(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4119 | if (ContiguousDest == SI->getDefaultDest()) |
| 4120 | ++PreviousEdges; |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4121 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4122 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 4123 | } |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4124 | for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 4125 | unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4126 | if (OtherDest == SI->getDefaultDest()) |
| 4127 | ++PreviousEdges; |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 4128 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
| 4129 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 4130 | } |
| 4131 | |
| 4132 | // Drop the switch. |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4133 | SI->eraseFromParent(); |
| 4134 | |
| 4135 | return true; |
| 4136 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4137 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4138 | /// Compute masked bits for the condition of a switch |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4139 | /// and use it to remove dead cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4140 | static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, |
| 4141 | const DataLayout &DL) { |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4142 | Value *Cond = SI->getCondition(); |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 4143 | unsigned Bits = Cond->getType()->getIntegerBitWidth(); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4144 | APInt KnownZero(Bits, 0), KnownOne(Bits, 0); |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4145 | computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4146 | |
Sanjay Patel | 75892a1 | 2016-05-20 14:53:09 +0000 | [diff] [blame] | 4147 | // We can also eliminate cases by determining that their values are outside of |
| 4148 | // the limited range of the condition based on how many significant (non-sign) |
| 4149 | // bits are in the condition value. |
| 4150 | unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; |
| 4151 | unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; |
| 4152 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4153 | // Gather dead cases. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4154 | SmallVector<ConstantInt *, 8> DeadCases; |
Sanjay Patel | 5d5134f | 2016-05-13 20:24:53 +0000 | [diff] [blame] | 4155 | for (auto &Case : SI->cases()) { |
Sanjay Patel | 75892a1 | 2016-05-20 14:53:09 +0000 | [diff] [blame] | 4156 | APInt CaseVal = Case.getCaseValue()->getValue(); |
| 4157 | if ((CaseVal & KnownZero) != 0 || (CaseVal & KnownOne) != KnownOne || |
| 4158 | (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { |
Sanjay Patel | 5d5134f | 2016-05-13 20:24:53 +0000 | [diff] [blame] | 4159 | DeadCases.push_back(Case.getCaseValue()); |
Sanjay Patel | 75892a1 | 2016-05-20 14:53:09 +0000 | [diff] [blame] | 4160 | DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n"); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4161 | } |
| 4162 | } |
| 4163 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4164 | // If we can prove that the cases must cover all possible values, the |
| 4165 | // default destination becomes dead and we can remove it. If we know some |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 4166 | // of the bits in the value, we can use that to more precisely compute the |
| 4167 | // number of possible unique case values. |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 4168 | bool HasDefault = |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4169 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
| 4170 | const unsigned NumUnknownBits = |
| 4171 | Bits - (KnownZero.Or(KnownOne)).countPopulation(); |
Filipe Cabecinhas | 48b090a | 2015-09-10 22:34:39 +0000 | [diff] [blame] | 4172 | assert(NumUnknownBits <= Bits); |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 4173 | if (HasDefault && DeadCases.empty() && |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4174 | NumUnknownBits < 64 /* avoid overflow */ && |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 4175 | SI->getNumCases() == (1ULL << NumUnknownBits)) { |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 4176 | DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4177 | BasicBlock *NewDefault = |
| 4178 | SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), ""); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 4179 | SI->setDefaultDest(&*NewDefault); |
| 4180 | SplitBlock(&*NewDefault, &NewDefault->front()); |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 4181 | auto *OldTI = NewDefault->getTerminator(); |
| 4182 | new UnreachableInst(SI->getContext(), OldTI); |
| 4183 | EraseTerminatorInstAndDCECond(OldTI); |
| 4184 | return true; |
| 4185 | } |
| 4186 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4187 | SmallVector<uint64_t, 8> Weights; |
| 4188 | bool HasWeight = HasBranchWeights(SI); |
| 4189 | if (HasWeight) { |
| 4190 | GetBranchWeights(SI, Weights); |
| 4191 | HasWeight = (Weights.size() == 1 + SI->getNumCases()); |
| 4192 | } |
| 4193 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4194 | // Remove dead cases from the switch. |
Sanjay Patel | 5d5134f | 2016-05-13 20:24:53 +0000 | [diff] [blame] | 4195 | for (ConstantInt *DeadCase : DeadCases) { |
| 4196 | SwitchInst::CaseIt Case = SI->findCaseValue(DeadCase); |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 4197 | assert(Case != SI->case_default() && |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 4198 | "Case was not found. Probably mistake in DeadCases forming."); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4199 | if (HasWeight) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4200 | std::swap(Weights[Case.getCaseIndex() + 1], Weights.back()); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4201 | Weights.pop_back(); |
| 4202 | } |
| 4203 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4204 | // Prune unused values from PHI nodes. |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 4205 | Case.getCaseSuccessor()->removePredecessor(SI->getParent()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4206 | SI->removeCase(Case); |
| 4207 | } |
Justin Bogner | 0ba3f21 | 2013-12-20 08:21:30 +0000 | [diff] [blame] | 4208 | if (HasWeight && Weights.size() >= 2) { |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4209 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 4210 | SI->setMetadata(LLVMContext::MD_prof, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4211 | MDBuilder(SI->getParent()->getContext()) |
| 4212 | .createBranchWeights(MDWeights)); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 4213 | } |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4214 | |
| 4215 | return !DeadCases.empty(); |
| 4216 | } |
| 4217 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4218 | /// If BB would be eligible for simplification by |
| 4219 | /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4220 | /// by an unconditional branch), look at the phi node for BB in the successor |
| 4221 | /// block and see if the incoming value is equal to CaseValue. If so, return |
| 4222 | /// the phi node, and set PhiIndex to BB's index in the phi node. |
| 4223 | static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4224 | BasicBlock *BB, int *PhiIndex) { |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4225 | if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4226 | return nullptr; // BB must be empty to be a candidate for simplification. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4227 | if (!BB->getSinglePredecessor()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4228 | return nullptr; // BB must be dominated by the switch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4229 | |
| 4230 | BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); |
| 4231 | if (!Branch || !Branch->isUnconditional()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4232 | return nullptr; // Terminator must be unconditional branch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4233 | |
| 4234 | BasicBlock *Succ = Branch->getSuccessor(0); |
| 4235 | |
| 4236 | BasicBlock::iterator I = Succ->begin(); |
| 4237 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 4238 | int Idx = PHI->getBasicBlockIndex(BB); |
| 4239 | assert(Idx >= 0 && "PHI has no entry for predecessor?"); |
| 4240 | |
| 4241 | Value *InValue = PHI->getIncomingValue(Idx); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4242 | if (InValue != CaseValue) |
| 4243 | continue; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4244 | |
| 4245 | *PhiIndex = Idx; |
| 4246 | return PHI; |
| 4247 | } |
| 4248 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4249 | return nullptr; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4250 | } |
| 4251 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4252 | /// Try to forward the condition of a switch instruction to a phi node |
| 4253 | /// dominated by the switch, if that would mean that some of the destination |
| 4254 | /// blocks of the switch can be folded away. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4255 | /// Returns true if a change is made. |
| 4256 | static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4257 | typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4258 | ForwardingNodesMap ForwardingNodes; |
| 4259 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4260 | for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; |
| 4261 | ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 4262 | ConstantInt *CaseValue = I.getCaseValue(); |
| 4263 | BasicBlock *CaseDest = I.getCaseSuccessor(); |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4264 | |
| 4265 | int PhiIndex; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4266 | PHINode *PHI = |
| 4267 | FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex); |
| 4268 | if (!PHI) |
| 4269 | continue; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4270 | |
| 4271 | ForwardingNodes[PHI].push_back(PhiIndex); |
| 4272 | } |
| 4273 | |
| 4274 | bool Changed = false; |
| 4275 | |
| 4276 | for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4277 | E = ForwardingNodes.end(); |
| 4278 | I != E; ++I) { |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4279 | PHINode *Phi = I->first; |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 4280 | SmallVectorImpl<int> &Indexes = I->second; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4281 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4282 | if (Indexes.size() < 2) |
| 4283 | continue; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4284 | |
| 4285 | for (size_t I = 0, E = Indexes.size(); I != E; ++I) |
| 4286 | Phi->setIncomingValue(Indexes[I], SI->getCondition()); |
| 4287 | Changed = true; |
| 4288 | } |
| 4289 | |
| 4290 | return Changed; |
| 4291 | } |
| 4292 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4293 | /// Return true if the backend will be able to handle |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4294 | /// initializing an array of constants like C. |
Hans Wennborg | 08238ad | 2012-09-07 08:22:57 +0000 | [diff] [blame] | 4295 | static bool ValidLookupTableConstant(Constant *C) { |
Hans Wennborg | 4dc8951 | 2014-06-20 00:38:12 +0000 | [diff] [blame] | 4296 | if (C->isThreadDependent()) |
| 4297 | return false; |
| 4298 | if (C->isDLLImportDependent()) |
| 4299 | return false; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4300 | |
Hans Wennborg | b03ebfb | 2014-06-26 00:30:52 +0000 | [diff] [blame] | 4301 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) |
| 4302 | return CE->isGEPWithNoNotionalOverIndexing(); |
| 4303 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4304 | return isa<ConstantFP>(C) || isa<ConstantInt>(C) || |
| 4305 | isa<ConstantPointerNull>(C) || isa<GlobalValue>(C) || |
| 4306 | isa<UndefValue>(C); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4307 | } |
| 4308 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4309 | /// If V is a Constant, return it. Otherwise, try to look up |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 4310 | /// its constant value in ConstantPool, returning 0 if it's not there. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4311 | static Constant * |
| 4312 | LookupConstant(Value *V, |
| 4313 | const SmallDenseMap<Value *, Constant *> &ConstantPool) { |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 4314 | if (Constant *C = dyn_cast<Constant>(V)) |
| 4315 | return C; |
| 4316 | return ConstantPool.lookup(V); |
| 4317 | } |
| 4318 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4319 | /// Try to fold instruction I into a constant. This works for |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4320 | /// simple instructions such as binary operations where both operands are |
| 4321 | /// constant or can be replaced by constants from the ConstantPool. Returns the |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 4322 | /// resulting constant on success, 0 otherwise. |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 4323 | static Constant * |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4324 | ConstantFold(Instruction *I, const DataLayout &DL, |
| 4325 | const SmallDenseMap<Value *, Constant *> &ConstantPool) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4326 | if (SelectInst *Select = dyn_cast<SelectInst>(I)) { |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 4327 | Constant *A = LookupConstant(Select->getCondition(), ConstantPool); |
| 4328 | if (!A) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4329 | return nullptr; |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 4330 | if (A->isAllOnesValue()) |
| 4331 | return LookupConstant(Select->getTrueValue(), ConstantPool); |
| 4332 | if (A->isNullValue()) |
| 4333 | return LookupConstant(Select->getFalseValue(), ConstantPool); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4334 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4335 | } |
| 4336 | |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 4337 | SmallVector<Constant *, 4> COps; |
| 4338 | for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { |
| 4339 | if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) |
| 4340 | COps.push_back(A); |
| 4341 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4342 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4343 | } |
| 4344 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4345 | if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 4346 | return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], |
| 4347 | COps[1], DL); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4348 | } |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 4349 | |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 4350 | return ConstantFoldInstOperands(I, COps, DL); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4351 | } |
| 4352 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4353 | /// Try to determine the resulting constant values in phi nodes |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4354 | /// at the common destination basic block, *CommonDest, for one of the case |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 4355 | /// destionations CaseDest corresponding to value CaseVal (0 for the default |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4356 | /// case), of a switch instruction SI. |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 4357 | static bool |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4358 | GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 4359 | BasicBlock **CommonDest, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4360 | SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, |
| 4361 | const DataLayout &DL) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4362 | // The block from which we enter the common destination. |
| 4363 | BasicBlock *Pred = SI->getParent(); |
| 4364 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4365 | // If CaseDest is empty except for some side-effect free instructions through |
| 4366 | // which we can constant-propagate the CaseVal, continue to its successor. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4367 | SmallDenseMap<Value *, Constant *> ConstantPool; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4368 | ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); |
| 4369 | for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; |
| 4370 | ++I) { |
| 4371 | if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { |
| 4372 | // If the terminator is a simple branch, continue to the next block. |
| 4373 | if (T->getNumSuccessors() != 1) |
| 4374 | return false; |
| 4375 | Pred = CaseDest; |
| 4376 | CaseDest = T->getSuccessor(0); |
| 4377 | } else if (isa<DbgInfoIntrinsic>(I)) { |
| 4378 | // Skip debug intrinsic. |
| 4379 | continue; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 4380 | } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4381 | // Instruction is side-effect free and constant. |
Hans Wennborg | dcc6e5b | 2015-01-09 22:13:31 +0000 | [diff] [blame] | 4382 | |
| 4383 | // If the instruction has uses outside this block or a phi node slot for |
| 4384 | // the block, it is not safe to bypass the instruction since it would then |
| 4385 | // no longer dominate all its uses. |
| 4386 | for (auto &Use : I->uses()) { |
| 4387 | User *User = Use.getUser(); |
| 4388 | if (Instruction *I = dyn_cast<Instruction>(User)) |
| 4389 | if (I->getParent() == CaseDest) |
| 4390 | continue; |
| 4391 | if (PHINode *Phi = dyn_cast<PHINode>(User)) |
| 4392 | if (Phi->getIncomingBlock(Use) == CaseDest) |
| 4393 | continue; |
| 4394 | return false; |
| 4395 | } |
| 4396 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 4397 | ConstantPool.insert(std::make_pair(&*I, C)); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4398 | } else { |
| 4399 | break; |
| 4400 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4401 | } |
| 4402 | |
| 4403 | // If we did not have a CommonDest before, use the current one. |
| 4404 | if (!*CommonDest) |
| 4405 | *CommonDest = CaseDest; |
| 4406 | // If the destination isn't the common one, abort. |
| 4407 | if (CaseDest != *CommonDest) |
| 4408 | return false; |
| 4409 | |
| 4410 | // Get the values for this case from phi nodes in the destination block. |
| 4411 | BasicBlock::iterator I = (*CommonDest)->begin(); |
| 4412 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 4413 | int Idx = PHI->getBasicBlockIndex(Pred); |
| 4414 | if (Idx == -1) |
| 4415 | continue; |
| 4416 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4417 | Constant *ConstVal = |
| 4418 | LookupConstant(PHI->getIncomingValue(Idx), ConstantPool); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4419 | if (!ConstVal) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4420 | return false; |
| 4421 | |
| 4422 | // Be conservative about which kinds of constants we support. |
| 4423 | if (!ValidLookupTableConstant(ConstVal)) |
| 4424 | return false; |
| 4425 | |
| 4426 | Res.push_back(std::make_pair(PHI, ConstVal)); |
| 4427 | } |
| 4428 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4429 | return Res.size() > 0; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4430 | } |
| 4431 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4432 | // Helper function used to add CaseVal to the list of cases that generate |
| 4433 | // Result. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4434 | static void MapCaseToResult(ConstantInt *CaseVal, |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4435 | SwitchCaseResultVectorTy &UniqueResults, |
| 4436 | Constant *Result) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4437 | for (auto &I : UniqueResults) { |
| 4438 | if (I.first == Result) { |
| 4439 | I.second.push_back(CaseVal); |
| 4440 | return; |
| 4441 | } |
| 4442 | } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4443 | UniqueResults.push_back( |
| 4444 | std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4445 | } |
| 4446 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4447 | // Helper function that initializes a map containing |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4448 | // results for the PHI node of the common destination block for a switch |
| 4449 | // instruction. Returns false if multiple PHI nodes have been found or if |
| 4450 | // there is not a common destination block for the switch. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4451 | static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, |
| 4452 | BasicBlock *&CommonDest, |
| 4453 | SwitchCaseResultVectorTy &UniqueResults, |
| 4454 | Constant *&DefaultResult, |
| 4455 | const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4456 | for (auto &I : SI->cases()) { |
| 4457 | ConstantInt *CaseVal = I.getCaseValue(); |
| 4458 | |
| 4459 | // Resulting value at phi nodes for this case value. |
| 4460 | SwitchCaseResultsTy Results; |
| 4461 | if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, |
| 4462 | DL)) |
| 4463 | return false; |
| 4464 | |
| 4465 | // Only one value per case is permitted |
| 4466 | if (Results.size() > 1) |
| 4467 | return false; |
| 4468 | MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); |
| 4469 | |
| 4470 | // Check the PHI consistency. |
| 4471 | if (!PHI) |
| 4472 | PHI = Results[0].first; |
| 4473 | else if (PHI != Results[0].first) |
| 4474 | return false; |
| 4475 | } |
| 4476 | // Find the default result value. |
| 4477 | SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; |
| 4478 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
| 4479 | GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, |
| 4480 | DL); |
| 4481 | // If the default value is not found abort unless the default destination |
| 4482 | // is unreachable. |
| 4483 | DefaultResult = |
| 4484 | DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; |
| 4485 | if ((!DefaultResult && |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4486 | !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4487 | return false; |
| 4488 | |
| 4489 | return true; |
| 4490 | } |
| 4491 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4492 | // Helper function that checks if it is possible to transform a switch with only |
| 4493 | // two cases (or two cases + default) that produces a result into a select. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4494 | // Example: |
| 4495 | // switch (a) { |
| 4496 | // case 10: %0 = icmp eq i32 %a, 10 |
| 4497 | // return 10; %1 = select i1 %0, i32 10, i32 4 |
| 4498 | // case 20: ----> %2 = icmp eq i32 %a, 20 |
| 4499 | // return 2; %3 = select i1 %2, i32 2, i32 %1 |
| 4500 | // default: |
| 4501 | // return 4; |
| 4502 | // } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4503 | static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, |
| 4504 | Constant *DefaultResult, Value *Condition, |
| 4505 | IRBuilder<> &Builder) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4506 | assert(ResultVector.size() == 2 && |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4507 | "We should have exactly two unique results at this point"); |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4508 | // If we are selecting between only two cases transform into a simple |
| 4509 | // select or a two-way select if default is possible. |
| 4510 | if (ResultVector[0].second.size() == 1 && |
| 4511 | ResultVector[1].second.size() == 1) { |
| 4512 | ConstantInt *const FirstCase = ResultVector[0].second[0]; |
| 4513 | ConstantInt *const SecondCase = ResultVector[1].second[0]; |
| 4514 | |
| 4515 | bool DefaultCanTrigger = DefaultResult; |
| 4516 | Value *SelectValue = ResultVector[1].first; |
| 4517 | if (DefaultCanTrigger) { |
| 4518 | Value *const ValueCompare = |
| 4519 | Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); |
| 4520 | SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, |
| 4521 | DefaultResult, "switch.select"); |
| 4522 | } |
| 4523 | Value *const ValueCompare = |
| 4524 | Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4525 | return Builder.CreateSelect(ValueCompare, ResultVector[0].first, |
| 4526 | SelectValue, "switch.select"); |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4527 | } |
| 4528 | |
| 4529 | return nullptr; |
| 4530 | } |
| 4531 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4532 | // Helper function to cleanup a switch instruction that has been converted into |
| 4533 | // a select, fixing up PHI nodes and basic blocks. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4534 | static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, |
| 4535 | Value *SelectValue, |
| 4536 | IRBuilder<> &Builder) { |
| 4537 | BasicBlock *SelectBB = SI->getParent(); |
| 4538 | while (PHI->getBasicBlockIndex(SelectBB) >= 0) |
| 4539 | PHI->removeIncomingValue(SelectBB); |
| 4540 | PHI->addIncoming(SelectValue, SelectBB); |
| 4541 | |
| 4542 | Builder.CreateBr(PHI->getParent()); |
| 4543 | |
| 4544 | // Remove the switch. |
| 4545 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
| 4546 | BasicBlock *Succ = SI->getSuccessor(i); |
| 4547 | |
| 4548 | if (Succ == PHI->getParent()) |
| 4549 | continue; |
| 4550 | Succ->removePredecessor(SelectBB); |
| 4551 | } |
| 4552 | SI->eraseFromParent(); |
| 4553 | } |
| 4554 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4555 | /// If the switch is only used to initialize one or more |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4556 | /// phi nodes in a common successor block with only two different |
| 4557 | /// constant values, replace the switch with select. |
| 4558 | static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4559 | AssumptionCache *AC, const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4560 | Value *const Cond = SI->getCondition(); |
| 4561 | PHINode *PHI = nullptr; |
| 4562 | BasicBlock *CommonDest = nullptr; |
| 4563 | Constant *DefaultResult; |
| 4564 | SwitchCaseResultVectorTy UniqueResults; |
| 4565 | // Collect all the cases that will deliver the same value from the switch. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4566 | if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, |
| 4567 | DL)) |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4568 | return false; |
| 4569 | // Selects choose between maximum two values. |
| 4570 | if (UniqueResults.size() != 2) |
| 4571 | return false; |
| 4572 | assert(PHI != nullptr && "PHI for value select not found"); |
| 4573 | |
| 4574 | Builder.SetInsertPoint(SI); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4575 | Value *SelectValue = |
| 4576 | ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4577 | if (SelectValue) { |
| 4578 | RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); |
| 4579 | return true; |
| 4580 | } |
| 4581 | // The switch couldn't be converted into a select. |
| 4582 | return false; |
| 4583 | } |
| 4584 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4585 | namespace { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4586 | /// This class represents a lookup table that can be used to replace a switch. |
| 4587 | class SwitchLookupTable { |
| 4588 | public: |
| 4589 | /// Create a lookup table to use as a switch replacement with the contents |
| 4590 | /// of Values, using DefaultValue to fill any holes in the table. |
| 4591 | SwitchLookupTable( |
| 4592 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 4593 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 4594 | Constant *DefaultValue, const DataLayout &DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4595 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4596 | /// Build instructions with Builder to retrieve the value at |
| 4597 | /// the position given by Index in the lookup table. |
| 4598 | Value *BuildLookup(Value *Index, IRBuilder<> &Builder); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4599 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4600 | /// Return true if a table with TableSize elements of |
| 4601 | /// type ElementType would fit in a target-legal register. |
| 4602 | static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, |
| 4603 | Type *ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4604 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4605 | private: |
| 4606 | // Depending on the contents of the table, it can be represented in |
| 4607 | // different ways. |
| 4608 | enum { |
| 4609 | // For tables where each element contains the same value, we just have to |
| 4610 | // store that single value and return it for each lookup. |
| 4611 | SingleValueKind, |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4612 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4613 | // For tables where there is a linear relationship between table index |
| 4614 | // and values. We calculate the result with a simple multiplication |
| 4615 | // and addition instead of a table lookup. |
| 4616 | LinearMapKind, |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4617 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4618 | // For small tables with integer elements, we can pack them into a bitmap |
| 4619 | // that fits into a target-legal register. Values are retrieved by |
| 4620 | // shift and mask operations. |
| 4621 | BitMapKind, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4622 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4623 | // The table is stored as an array of values. Values are retrieved by load |
| 4624 | // instructions from the table. |
| 4625 | ArrayKind |
| 4626 | } Kind; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4627 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4628 | // For SingleValueKind, this is the single value. |
| 4629 | Constant *SingleValue; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4630 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4631 | // For BitMapKind, this is the bitmap. |
| 4632 | ConstantInt *BitMap; |
| 4633 | IntegerType *BitMapElementTy; |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4634 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4635 | // For LinearMapKind, these are the constants used to derive the value. |
| 4636 | ConstantInt *LinearOffset; |
| 4637 | ConstantInt *LinearMultiplier; |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4638 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4639 | // For ArrayKind, this is the array. |
| 4640 | GlobalVariable *Array; |
| 4641 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 4642 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4643 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4644 | SwitchLookupTable::SwitchLookupTable( |
| 4645 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 4646 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 4647 | Constant *DefaultValue, const DataLayout &DL) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4648 | : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4649 | LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 4650 | assert(Values.size() && "Can't build lookup table without values!"); |
| 4651 | assert(TableSize >= Values.size() && "Can't fit values in table!"); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4652 | |
| 4653 | // If all values in the table are equal, this is that value. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4654 | SingleValue = Values.begin()->second; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4655 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4656 | Type *ValueType = Values.begin()->second->getType(); |
| 4657 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4658 | // Build up the table contents. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4659 | SmallVector<Constant *, 64> TableContents(TableSize); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4660 | for (size_t I = 0, E = Values.size(); I != E; ++I) { |
| 4661 | ConstantInt *CaseVal = Values[I].first; |
| 4662 | Constant *CaseRes = Values[I].second; |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4663 | assert(CaseRes->getType() == ValueType); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4664 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4665 | uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4666 | TableContents[Idx] = CaseRes; |
| 4667 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4668 | if (CaseRes != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4669 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4670 | } |
| 4671 | |
| 4672 | // Fill in any holes in the table with the default result. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4673 | if (Values.size() < TableSize) { |
Marcello Maggioni | 89c05ad | 2014-07-03 08:29:06 +0000 | [diff] [blame] | 4674 | assert(DefaultValue && |
| 4675 | "Need a default value to fill the lookup table holes."); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4676 | assert(DefaultValue->getType() == ValueType); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4677 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 4678 | if (!TableContents[I]) |
| 4679 | TableContents[I] = DefaultValue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4680 | } |
| 4681 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4682 | if (DefaultValue != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4683 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4684 | } |
| 4685 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4686 | // If each element in the table contains the same value, we only need to store |
| 4687 | // that single value. |
| 4688 | if (SingleValue) { |
| 4689 | Kind = SingleValueKind; |
| 4690 | return; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4691 | } |
| 4692 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4693 | // Check if we can derive the value with a linear transformation from the |
| 4694 | // table index. |
| 4695 | if (isa<IntegerType>(ValueType)) { |
| 4696 | bool LinearMappingPossible = true; |
| 4697 | APInt PrevVal; |
| 4698 | APInt DistToPrev; |
| 4699 | assert(TableSize >= 2 && "Should be a SingleValue table."); |
| 4700 | // Check if there is the same distance between two consecutive values. |
| 4701 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 4702 | ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); |
| 4703 | if (!ConstVal) { |
| 4704 | // This is an undef. We could deal with it, but undefs in lookup tables |
| 4705 | // are very seldom. It's probably not worth the additional complexity. |
| 4706 | LinearMappingPossible = false; |
| 4707 | break; |
| 4708 | } |
| 4709 | APInt Val = ConstVal->getValue(); |
| 4710 | if (I != 0) { |
| 4711 | APInt Dist = Val - PrevVal; |
| 4712 | if (I == 1) { |
| 4713 | DistToPrev = Dist; |
| 4714 | } else if (Dist != DistToPrev) { |
| 4715 | LinearMappingPossible = false; |
| 4716 | break; |
| 4717 | } |
| 4718 | } |
| 4719 | PrevVal = Val; |
| 4720 | } |
| 4721 | if (LinearMappingPossible) { |
| 4722 | LinearOffset = cast<ConstantInt>(TableContents[0]); |
| 4723 | LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); |
| 4724 | Kind = LinearMapKind; |
| 4725 | ++NumLinearMaps; |
| 4726 | return; |
| 4727 | } |
| 4728 | } |
| 4729 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4730 | // If the type is integer and the table fits in a register, build a bitmap. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4731 | if (WouldFitInRegister(DL, TableSize, ValueType)) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4732 | IntegerType *IT = cast<IntegerType>(ValueType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4733 | APInt TableInt(TableSize * IT->getBitWidth(), 0); |
| 4734 | for (uint64_t I = TableSize; I > 0; --I) { |
| 4735 | TableInt <<= IT->getBitWidth(); |
Benjamin Kramer | 9fc3dc7 | 2012-10-01 11:31:48 +0000 | [diff] [blame] | 4736 | // Insert values into the bitmap. Undef values are set to zero. |
| 4737 | if (!isa<UndefValue>(TableContents[I - 1])) { |
| 4738 | ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); |
| 4739 | TableInt |= Val->getValue().zext(TableInt.getBitWidth()); |
| 4740 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4741 | } |
| 4742 | BitMap = ConstantInt::get(M.getContext(), TableInt); |
| 4743 | BitMapElementTy = IT; |
| 4744 | Kind = BitMapKind; |
| 4745 | ++NumBitMaps; |
| 4746 | return; |
| 4747 | } |
| 4748 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4749 | // Store the table in an array. |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4750 | ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4751 | Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); |
| 4752 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4753 | Array = new GlobalVariable(M, ArrayTy, /*constant=*/true, |
| 4754 | GlobalVariable::PrivateLinkage, Initializer, |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4755 | "switch.table"); |
Peter Collingbourne | 96efdd6 | 2016-06-14 21:01:22 +0000 | [diff] [blame] | 4756 | Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4757 | Kind = ArrayKind; |
| 4758 | } |
| 4759 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4760 | Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4761 | switch (Kind) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4762 | case SingleValueKind: |
| 4763 | return SingleValue; |
| 4764 | case LinearMapKind: { |
| 4765 | // Derive the result value from the input value. |
| 4766 | Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), |
| 4767 | false, "switch.idx.cast"); |
| 4768 | if (!LinearMultiplier->isOne()) |
| 4769 | Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); |
| 4770 | if (!LinearOffset->isZero()) |
| 4771 | Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); |
| 4772 | return Result; |
| 4773 | } |
| 4774 | case BitMapKind: { |
| 4775 | // Type of the bitmap (e.g. i59). |
| 4776 | IntegerType *MapTy = BitMap->getType(); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4777 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4778 | // Cast Index to the same type as the bitmap. |
| 4779 | // Note: The Index is <= the number of elements in the table, so |
| 4780 | // truncating it to the width of the bitmask is safe. |
| 4781 | Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4782 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4783 | // Multiply the shift amount by the element width. |
| 4784 | ShiftAmt = Builder.CreateMul( |
| 4785 | ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), |
| 4786 | "switch.shiftamt"); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4787 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4788 | // Shift down. |
| 4789 | Value *DownShifted = |
| 4790 | Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); |
| 4791 | // Mask off. |
| 4792 | return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); |
| 4793 | } |
| 4794 | case ArrayKind: { |
| 4795 | // Make sure the table index will not overflow when treated as signed. |
| 4796 | IntegerType *IT = cast<IntegerType>(Index->getType()); |
| 4797 | uint64_t TableSize = |
| 4798 | Array->getInitializer()->getType()->getArrayNumElements(); |
| 4799 | if (TableSize > (1ULL << (IT->getBitWidth() - 1))) |
| 4800 | Index = Builder.CreateZExt( |
| 4801 | Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), |
| 4802 | "switch.tableidx.zext"); |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4803 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4804 | Value *GEPIndices[] = {Builder.getInt32(0), Index}; |
| 4805 | Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, |
| 4806 | GEPIndices, "switch.gep"); |
| 4807 | return Builder.CreateLoad(GEP, "switch.load"); |
| 4808 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4809 | } |
| 4810 | llvm_unreachable("Unknown lookup table kind!"); |
| 4811 | } |
| 4812 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4813 | bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4814 | uint64_t TableSize, |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 4815 | Type *ElementType) { |
| 4816 | auto *IT = dyn_cast<IntegerType>(ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4817 | if (!IT) |
| 4818 | return false; |
| 4819 | // FIXME: If the type is wider than it needs to be, e.g. i8 but all values |
| 4820 | // are <= 15, we could try to narrow the type. |
Benjamin Kramer | c2081d1 | 2012-09-27 18:29:58 +0000 | [diff] [blame] | 4821 | |
| 4822 | // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4823 | if (TableSize >= UINT_MAX / IT->getBitWidth()) |
Benjamin Kramer | c2081d1 | 2012-09-27 18:29:58 +0000 | [diff] [blame] | 4824 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4825 | return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4826 | } |
| 4827 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4828 | /// Determine whether a lookup table should be built for this switch, based on |
| 4829 | /// the number of cases, size of the table, and the types of the results. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4830 | static bool |
| 4831 | ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, |
| 4832 | const TargetTransformInfo &TTI, const DataLayout &DL, |
| 4833 | const SmallDenseMap<PHINode *, Type *> &ResultTypes) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 4834 | if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) |
| 4835 | return false; // TableSize overflowed, or mul below might overflow. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4836 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4837 | bool AllTablesFitInRegister = true; |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4838 | bool HasIllegalType = false; |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4839 | for (const auto &I : ResultTypes) { |
| 4840 | Type *Ty = I.second; |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4841 | |
| 4842 | // Saturate this flag to true. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4843 | HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4844 | |
| 4845 | // Saturate this flag to false. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4846 | AllTablesFitInRegister = |
| 4847 | AllTablesFitInRegister && |
| 4848 | SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4849 | |
| 4850 | // If both flags saturate, we're done. NOTE: This *only* works with |
| 4851 | // saturating flags, and all flags have to saturate first due to the |
| 4852 | // non-deterministic behavior of iterating over a dense map. |
| 4853 | if (HasIllegalType && !AllTablesFitInRegister) |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4854 | break; |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4855 | } |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4856 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4857 | // If each table would fit in a register, we should build it anyway. |
| 4858 | if (AllTablesFitInRegister) |
| 4859 | return true; |
| 4860 | |
| 4861 | // Don't build a table that doesn't fit in-register if it has illegal types. |
| 4862 | if (HasIllegalType) |
| 4863 | return false; |
| 4864 | |
| 4865 | // The table density should be at least 40%. This is the same criterion as for |
| 4866 | // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. |
| 4867 | // FIXME: Find the best cut-off. |
| 4868 | return SI->getNumCases() * 10 >= TableSize * 4; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4869 | } |
| 4870 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4871 | /// Try to reuse the switch table index compare. Following pattern: |
| 4872 | /// \code |
| 4873 | /// if (idx < tablesize) |
| 4874 | /// r = table[idx]; // table does not contain default_value |
| 4875 | /// else |
| 4876 | /// r = default_value; |
| 4877 | /// if (r != default_value) |
| 4878 | /// ... |
| 4879 | /// \endcode |
| 4880 | /// Is optimized to: |
| 4881 | /// \code |
| 4882 | /// cond = idx < tablesize; |
| 4883 | /// if (cond) |
| 4884 | /// r = table[idx]; |
| 4885 | /// else |
| 4886 | /// r = default_value; |
| 4887 | /// if (cond) |
| 4888 | /// ... |
| 4889 | /// \endcode |
| 4890 | /// Jump threading will then eliminate the second if(cond). |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4891 | static void reuseTableCompare( |
| 4892 | User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, |
| 4893 | Constant *DefaultValue, |
| 4894 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4895 | |
| 4896 | ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); |
| 4897 | if (!CmpInst) |
| 4898 | return; |
| 4899 | |
| 4900 | // We require that the compare is in the same block as the phi so that jump |
| 4901 | // threading can do its work afterwards. |
| 4902 | if (CmpInst->getParent() != PhiBlock) |
| 4903 | return; |
| 4904 | |
| 4905 | Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); |
| 4906 | if (!CmpOp1) |
| 4907 | return; |
| 4908 | |
| 4909 | Value *RangeCmp = RangeCheckBranch->getCondition(); |
| 4910 | Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); |
| 4911 | Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); |
| 4912 | |
| 4913 | // Check if the compare with the default value is constant true or false. |
| 4914 | Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4915 | DefaultValue, CmpOp1, true); |
| 4916 | if (DefaultConst != TrueConst && DefaultConst != FalseConst) |
| 4917 | return; |
| 4918 | |
| 4919 | // Check if the compare with the case values is distinct from the default |
| 4920 | // compare result. |
| 4921 | for (auto ValuePair : Values) { |
| 4922 | Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4923 | ValuePair.second, CmpOp1, true); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4924 | if (!CaseConst || CaseConst == DefaultConst) |
| 4925 | return; |
| 4926 | assert((CaseConst == TrueConst || CaseConst == FalseConst) && |
| 4927 | "Expect true or false as compare result."); |
| 4928 | } |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4929 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4930 | // Check if the branch instruction dominates the phi node. It's a simple |
| 4931 | // dominance check, but sufficient for our needs. |
| 4932 | // Although this check is invariant in the calling loops, it's better to do it |
| 4933 | // at this late stage. Practically we do it at most once for a switch. |
| 4934 | BasicBlock *BranchBlock = RangeCheckBranch->getParent(); |
| 4935 | for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { |
| 4936 | BasicBlock *Pred = *PI; |
| 4937 | if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) |
| 4938 | return; |
| 4939 | } |
| 4940 | |
| 4941 | if (DefaultConst == FalseConst) { |
| 4942 | // The compare yields the same result. We can replace it. |
| 4943 | CmpInst->replaceAllUsesWith(RangeCmp); |
| 4944 | ++NumTableCmpReuses; |
| 4945 | } else { |
| 4946 | // The compare yields the same result, just inverted. We can replace it. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4947 | Value *InvertedTableCmp = BinaryOperator::CreateXor( |
| 4948 | RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", |
| 4949 | RangeCheckBranch); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4950 | CmpInst->replaceAllUsesWith(InvertedTableCmp); |
| 4951 | ++NumTableCmpReuses; |
| 4952 | } |
| 4953 | } |
| 4954 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4955 | /// If the switch is only used to initialize one or more phi nodes in a common |
| 4956 | /// successor block with different constant values, replace the switch with |
| 4957 | /// lookup tables. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4958 | static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, |
| 4959 | const DataLayout &DL, |
| 4960 | const TargetTransformInfo &TTI) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4961 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4962 | |
Hans Wennborg | c3c8d95 | 2012-11-07 21:35:12 +0000 | [diff] [blame] | 4963 | // Only build lookup table when we have a target that supports it. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4964 | if (!TTI.shouldBuildLookupTables()) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4965 | return false; |
| 4966 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4967 | // FIXME: If the switch is too sparse for a lookup table, perhaps we could |
| 4968 | // split off a dense part and build a lookup table for that. |
| 4969 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4970 | // FIXME: This creates arrays of GEPs to constant strings, which means each |
| 4971 | // GEP needs a runtime relocation in PIC code. We should just build one big |
| 4972 | // string and lookup indices into that. |
| 4973 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4974 | // Ignore switches with less than three cases. Lookup tables will not make |
| 4975 | // them |
Hans Wennborg | 4744ac1 | 2014-01-15 05:00:27 +0000 | [diff] [blame] | 4976 | // faster, so we don't analyze them. |
| 4977 | if (SI->getNumCases() < 3) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4978 | return false; |
| 4979 | |
| 4980 | // Figure out the corresponding result for each case value and phi node in the |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 4981 | // common destination, as well as the min and max case values. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4982 | assert(SI->case_begin() != SI->case_end()); |
| 4983 | SwitchInst::CaseIt CI = SI->case_begin(); |
| 4984 | ConstantInt *MinCaseVal = CI.getCaseValue(); |
| 4985 | ConstantInt *MaxCaseVal = CI.getCaseValue(); |
| 4986 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4987 | BasicBlock *CommonDest = nullptr; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 4988 | typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy; |
| 4989 | SmallDenseMap<PHINode *, ResultListTy> ResultLists; |
| 4990 | SmallDenseMap<PHINode *, Constant *> DefaultResults; |
| 4991 | SmallDenseMap<PHINode *, Type *> ResultTypes; |
| 4992 | SmallVector<PHINode *, 4> PHIs; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4993 | |
| 4994 | for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { |
| 4995 | ConstantInt *CaseVal = CI.getCaseValue(); |
| 4996 | if (CaseVal->getValue().slt(MinCaseVal->getValue())) |
| 4997 | MinCaseVal = CaseVal; |
| 4998 | if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) |
| 4999 | MaxCaseVal = CaseVal; |
| 5000 | |
| 5001 | // Resulting value at phi nodes for this case value. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5002 | typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5003 | ResultsTy Results; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 5004 | if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 5005 | Results, DL)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5006 | return false; |
| 5007 | |
| 5008 | // Append the result from this case to the list for each phi. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 5009 | for (const auto &I : Results) { |
| 5010 | PHINode *PHI = I.first; |
| 5011 | Constant *Value = I.second; |
| 5012 | if (!ResultLists.count(PHI)) |
| 5013 | PHIs.push_back(PHI); |
| 5014 | ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5015 | } |
| 5016 | } |
| 5017 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 5018 | // Keep track of the result types. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 5019 | for (PHINode *PHI : PHIs) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 5020 | ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); |
| 5021 | } |
| 5022 | |
| 5023 | uint64_t NumResults = ResultLists[PHIs[0]].size(); |
| 5024 | APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); |
| 5025 | uint64_t TableSize = RangeSpread.getLimitedValue() + 1; |
| 5026 | bool TableHasHoles = (NumResults < TableSize); |
| 5027 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5028 | // If the table has holes, we need a constant result for the default case |
| 5029 | // or a bitmask that fits in a register. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5030 | SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 5031 | bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(), |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5032 | &CommonDest, DefaultResultsList, DL); |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 5033 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5034 | bool NeedMask = (TableHasHoles && !HasDefaultResults); |
| 5035 | if (NeedMask) { |
| 5036 | // As an extra penalty for the validity test we require more cases. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5037 | if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5038 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5039 | if (!DL.fitsInLegalInteger(TableSize)) |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5040 | return false; |
| 5041 | } |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 5042 | |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 5043 | for (const auto &I : DefaultResultsList) { |
| 5044 | PHINode *PHI = I.first; |
| 5045 | Constant *Result = I.second; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 5046 | DefaultResults[PHI] = Result; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5047 | } |
| 5048 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 5049 | if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5050 | return false; |
| 5051 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5052 | // Create the BB that does the lookups. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 5053 | Module &Mod = *CommonDest->getParent()->getParent(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5054 | BasicBlock *LookupBB = BasicBlock::Create( |
| 5055 | Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5056 | |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5057 | // Compute the table index value. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5058 | Builder.SetInsertPoint(SI); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5059 | Value *TableIndex = |
| 5060 | Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx"); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5061 | |
| 5062 | // Compute the maximum table size representable by the integer type we are |
| 5063 | // switching upon. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 5064 | unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 5065 | uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5066 | assert(MaxTableSize >= TableSize && |
| 5067 | "It is impossible for a switch to have more entries than the max " |
| 5068 | "representable value of its input integer type's size."); |
| 5069 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 5070 | // If the default destination is unreachable, or if the lookup table covers |
| 5071 | // all values of the conditional variable, branch directly to the lookup table |
| 5072 | // BB. Otherwise, check that the condition is within the case range. |
| 5073 | const bool DefaultIsReachable = |
| 5074 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
| 5075 | const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 5076 | BranchInst *RangeCheckBranch = nullptr; |
| 5077 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 5078 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5079 | Builder.CreateBr(LookupBB); |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 5080 | // Note: We call removeProdecessor later since we need to be able to get the |
| 5081 | // PHI value for the default case in case we're using a bit mask. |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5082 | } else { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5083 | Value *Cmp = Builder.CreateICmpULT( |
| 5084 | TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); |
| 5085 | RangeCheckBranch = |
| 5086 | Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5087 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5088 | |
| 5089 | // Populate the BB that does the lookups. |
| 5090 | Builder.SetInsertPoint(LookupBB); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5091 | |
| 5092 | if (NeedMask) { |
| 5093 | // Before doing the lookup we do the hole check. |
| 5094 | // The LookupBB is therefore re-purposed to do the hole check |
| 5095 | // and we create a new LookupBB. |
| 5096 | BasicBlock *MaskBB = LookupBB; |
| 5097 | MaskBB->setName("switch.hole_check"); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5098 | LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", |
| 5099 | CommonDest->getParent(), CommonDest); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5100 | |
Juergen Ributzka | c9591e9 | 2014-11-17 19:39:56 +0000 | [diff] [blame] | 5101 | // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid |
| 5102 | // unnecessary illegal types. |
| 5103 | uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); |
| 5104 | APInt MaskInt(TableSizePowOf2, 0); |
| 5105 | APInt One(TableSizePowOf2, 1); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5106 | // Build bitmask; fill in a 1 bit for every case. |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5107 | const ResultListTy &ResultList = ResultLists[PHIs[0]]; |
| 5108 | for (size_t I = 0, E = ResultList.size(); I != E; ++I) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5109 | uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) |
| 5110 | .getLimitedValue(); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5111 | MaskInt |= One << Idx; |
| 5112 | } |
| 5113 | ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); |
| 5114 | |
| 5115 | // Get the TableIndex'th bit of the bitmask. |
| 5116 | // If this bit is 0 (meaning hole) jump to the default destination, |
| 5117 | // else continue with table lookup. |
| 5118 | IntegerType *MapTy = TableMask->getType(); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5119 | Value *MaskIndex = |
| 5120 | Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); |
| 5121 | Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); |
| 5122 | Value *LoBit = Builder.CreateTrunc( |
| 5123 | Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5124 | Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); |
| 5125 | |
| 5126 | Builder.SetInsertPoint(LookupBB); |
| 5127 | AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); |
| 5128 | } |
| 5129 | |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 5130 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
| 5131 | // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, |
| 5132 | // do not delete PHINodes here. |
| 5133 | SI->getDefaultDest()->removePredecessor(SI->getParent(), |
| 5134 | /*DontDeleteUselessPHIs=*/true); |
| 5135 | } |
| 5136 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5137 | bool ReturnedEarly = false; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 5138 | for (size_t I = 0, E = PHIs.size(); I != E; ++I) { |
| 5139 | PHINode *PHI = PHIs[I]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 5140 | const ResultListTy &ResultList = ResultLists[PHI]; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5141 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5142 | // If using a bitmask, use any value to fill the lookup table holes. |
| 5143 | Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 5144 | SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 5145 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 5146 | Value *Result = Table.BuildLookup(TableIndex, Builder); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5147 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 5148 | // If the result is used to return immediately from the function, we want to |
| 5149 | // do that right here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5150 | if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && |
| 5151 | PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 5152 | Builder.CreateRet(Result); |
| 5153 | ReturnedEarly = true; |
| 5154 | break; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5155 | } |
| 5156 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 5157 | // Do a small peephole optimization: re-use the switch table compare if |
| 5158 | // possible. |
| 5159 | if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { |
| 5160 | BasicBlock *PhiBlock = PHI->getParent(); |
| 5161 | // Search for compare instructions which use the phi. |
| 5162 | for (auto *User : PHI->users()) { |
| 5163 | reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); |
| 5164 | } |
| 5165 | } |
| 5166 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 5167 | PHI->addIncoming(Result, LookupBB); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5168 | } |
| 5169 | |
| 5170 | if (!ReturnedEarly) |
| 5171 | Builder.CreateBr(CommonDest); |
| 5172 | |
| 5173 | // Remove the switch. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 5174 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5175 | BasicBlock *Succ = SI->getSuccessor(i); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5176 | |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 5177 | if (Succ == SI->getDefaultDest()) |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 5178 | continue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5179 | Succ->removePredecessor(SI->getParent()); |
| 5180 | } |
| 5181 | SI->eraseFromParent(); |
| 5182 | |
| 5183 | ++NumLookupTables; |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 5184 | if (NeedMask) |
| 5185 | ++NumLookupTablesHoles; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5186 | return true; |
| 5187 | } |
| 5188 | |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5189 | static bool isSwitchDense(ArrayRef<int64_t> Values) { |
| 5190 | // See also SelectionDAGBuilder::isDense(), which this function was based on. |
| 5191 | uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); |
| 5192 | uint64_t Range = Diff + 1; |
| 5193 | uint64_t NumCases = Values.size(); |
| 5194 | // 40% is the default density for building a jump table in optsize/minsize mode. |
| 5195 | uint64_t MinDensity = 40; |
Junmo Park | db8f6ee | 2016-08-02 04:38:27 +0000 | [diff] [blame] | 5196 | |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5197 | return NumCases * 100 >= Range * MinDensity; |
| 5198 | } |
| 5199 | |
| 5200 | // Try and transform a switch that has "holes" in it to a contiguous sequence |
| 5201 | // of cases. |
| 5202 | // |
| 5203 | // A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be |
| 5204 | // range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. |
| 5205 | // |
| 5206 | // This converts a sparse switch into a dense switch which allows better |
| 5207 | // lowering and could also allow transforming into a lookup table. |
| 5208 | static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, |
| 5209 | const DataLayout &DL, |
| 5210 | const TargetTransformInfo &TTI) { |
| 5211 | auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); |
| 5212 | if (CondTy->getIntegerBitWidth() > 64 || |
| 5213 | !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) |
| 5214 | return false; |
| 5215 | // Only bother with this optimization if there are more than 3 switch cases; |
| 5216 | // SDAG will only bother creating jump tables for 4 or more cases. |
| 5217 | if (SI->getNumCases() < 4) |
| 5218 | return false; |
| 5219 | |
| 5220 | // This transform is agnostic to the signedness of the input or case values. We |
| 5221 | // can treat the case values as signed or unsigned. We can optimize more common |
| 5222 | // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values |
| 5223 | // as signed. |
| 5224 | SmallVector<int64_t,4> Values; |
| 5225 | for (auto &C : SI->cases()) |
| 5226 | Values.push_back(C.getCaseValue()->getValue().getSExtValue()); |
| 5227 | std::sort(Values.begin(), Values.end()); |
| 5228 | |
| 5229 | // If the switch is already dense, there's nothing useful to do here. |
| 5230 | if (isSwitchDense(Values)) |
| 5231 | return false; |
| 5232 | |
| 5233 | // First, transform the values such that they start at zero and ascend. |
| 5234 | int64_t Base = Values[0]; |
| 5235 | for (auto &V : Values) |
| 5236 | V -= Base; |
| 5237 | |
| 5238 | // Now we have signed numbers that have been shifted so that, given enough |
| 5239 | // precision, there are no negative values. Since the rest of the transform |
| 5240 | // is bitwise only, we switch now to an unsigned representation. |
| 5241 | uint64_t GCD = 0; |
| 5242 | for (auto &V : Values) |
| 5243 | GCD = llvm::GreatestCommonDivisor64(GCD, (uint64_t)V); |
| 5244 | |
| 5245 | // This transform can be done speculatively because it is so cheap - it results |
| 5246 | // in a single rotate operation being inserted. This can only happen if the |
| 5247 | // factor extracted is a power of 2. |
| 5248 | // FIXME: If the GCD is an odd number we can multiply by the multiplicative |
| 5249 | // inverse of GCD and then perform this transform. |
| 5250 | // FIXME: It's possible that optimizing a switch on powers of two might also |
| 5251 | // be beneficial - flag values are often powers of two and we could use a CLZ |
| 5252 | // as the key function. |
| 5253 | if (GCD <= 1 || !llvm::isPowerOf2_64(GCD)) |
| 5254 | // No common divisor found or too expensive to compute key function. |
| 5255 | return false; |
| 5256 | |
| 5257 | unsigned Shift = llvm::Log2_64(GCD); |
| 5258 | for (auto &V : Values) |
| 5259 | V = (int64_t)((uint64_t)V >> Shift); |
| 5260 | |
| 5261 | if (!isSwitchDense(Values)) |
| 5262 | // Transform didn't create a dense switch. |
| 5263 | return false; |
| 5264 | |
| 5265 | // The obvious transform is to shift the switch condition right and emit a |
| 5266 | // check that the condition actually cleanly divided by GCD, i.e. |
| 5267 | // C & (1 << Shift - 1) == 0 |
| 5268 | // inserting a new CFG edge to handle the case where it didn't divide cleanly. |
| 5269 | // |
| 5270 | // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the |
| 5271 | // shift and puts the shifted-off bits in the uppermost bits. If any of these |
| 5272 | // are nonzero then the switch condition will be very large and will hit the |
| 5273 | // default case. |
Junmo Park | db8f6ee | 2016-08-02 04:38:27 +0000 | [diff] [blame] | 5274 | |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5275 | auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); |
| 5276 | Builder.SetInsertPoint(SI); |
| 5277 | auto *ShiftC = ConstantInt::get(Ty, Shift); |
| 5278 | auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); |
Benjamin Kramer | aa160c2 | 2016-08-05 14:55:02 +0000 | [diff] [blame] | 5279 | auto *LShr = Builder.CreateLShr(Sub, ShiftC); |
| 5280 | auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); |
| 5281 | auto *Rot = Builder.CreateOr(LShr, Shl); |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5282 | SI->replaceUsesOfWith(SI->getCondition(), Rot); |
| 5283 | |
James Molloy | bade86c | 2016-08-01 09:34:48 +0000 | [diff] [blame] | 5284 | for (SwitchInst::CaseIt C = SI->case_begin(), E = SI->case_end(); C != E; |
| 5285 | ++C) { |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5286 | auto *Orig = C.getCaseValue(); |
| 5287 | auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); |
James Molloy | bade86c | 2016-08-01 09:34:48 +0000 | [diff] [blame] | 5288 | C.setValue( |
| 5289 | cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5290 | } |
| 5291 | return true; |
| 5292 | } |
| 5293 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5294 | bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5295 | BasicBlock *BB = SI->getParent(); |
| 5296 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 5297 | if (isValueEqualityComparison(SI)) { |
| 5298 | // If we only have one predecessor, and if it is a branch on this value, |
| 5299 | // see if that predecessor totally determines the outcome of this switch. |
| 5300 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 5301 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5302 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 5303 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 5304 | Value *Cond = SI->getCondition(); |
| 5305 | if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) |
| 5306 | if (SimplifySwitchOnSelect(SI, Select)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5307 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 5308 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 5309 | // If the block only contains the switch, see if we can fold the block |
| 5310 | // away into any preds. |
| 5311 | BasicBlock::iterator BBI = BB->begin(); |
| 5312 | // Ignore dbg intrinsics. |
| 5313 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 5314 | ++BBI; |
| 5315 | if (SI == &*BBI) |
| 5316 | if (FoldValueComparisonIntoPredecessors(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5317 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 5318 | } |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 5319 | |
| 5320 | // Try to transform the switch into an icmp and a branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5321 | if (TurnSwitchRangeIntoICmp(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5322 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 5323 | |
| 5324 | // Remove unreachable cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5325 | if (EliminateDeadSwitchCases(SI, AC, DL)) |
| 5326 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 5327 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5328 | if (SwitchToSelect(SI, Builder, AC, DL)) |
| 5329 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 5330 | |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 5331 | if (ForwardSwitchConditionToPHI(SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5332 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 5333 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5334 | if (SwitchToLookupTable(SI, Builder, DL, TTI)) |
| 5335 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 5336 | |
James Molloy | b2e436d | 2016-08-01 07:45:11 +0000 | [diff] [blame] | 5337 | if (ReduceSwitchRange(SI, Builder, DL, TTI)) |
| 5338 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
| 5339 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5340 | return false; |
| 5341 | } |
| 5342 | |
| 5343 | bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { |
| 5344 | BasicBlock *BB = IBI->getParent(); |
| 5345 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5346 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5347 | // Eliminate redundant destinations. |
| 5348 | SmallPtrSet<Value *, 8> Succs; |
| 5349 | for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { |
| 5350 | BasicBlock *Dest = IBI->getDestination(i); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5351 | if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5352 | Dest->removePredecessor(BB); |
| 5353 | IBI->removeDestination(i); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5354 | --i; |
| 5355 | --e; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5356 | Changed = true; |
| 5357 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5358 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5359 | |
| 5360 | if (IBI->getNumDestinations() == 0) { |
| 5361 | // If the indirectbr has no successors, change it to unreachable. |
| 5362 | new UnreachableInst(IBI->getContext(), IBI); |
| 5363 | EraseTerminatorInstAndDCECond(IBI); |
| 5364 | return true; |
| 5365 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5366 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5367 | if (IBI->getNumDestinations() == 1) { |
| 5368 | // If the indirectbr has one successor, change it to a direct branch. |
| 5369 | BranchInst::Create(IBI->getDestination(0), IBI); |
| 5370 | EraseTerminatorInstAndDCECond(IBI); |
| 5371 | return true; |
| 5372 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5373 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5374 | if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { |
| 5375 | if (SimplifyIndirectBrOnSelect(IBI, SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5376 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5377 | } |
| 5378 | return Changed; |
| 5379 | } |
| 5380 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5381 | /// Given an block with only a single landing pad and a unconditional branch |
| 5382 | /// try to find another basic block which this one can be merged with. This |
| 5383 | /// handles cases where we have multiple invokes with unique landing pads, but |
| 5384 | /// a shared handler. |
| 5385 | /// |
| 5386 | /// We specifically choose to not worry about merging non-empty blocks |
| 5387 | /// here. That is a PRE/scheduling problem and is best solved elsewhere. In |
| 5388 | /// practice, the optimizer produces empty landing pad blocks quite frequently |
| 5389 | /// when dealing with exception dense code. (see: instcombine, gvn, if-else |
| 5390 | /// sinking in this file) |
| 5391 | /// |
| 5392 | /// This is primarily a code size optimization. We need to avoid performing |
| 5393 | /// any transform which might inhibit optimization (such as our ability to |
| 5394 | /// specialize a particular handler via tail commoning). We do this by not |
| 5395 | /// merging any blocks which require us to introduce a phi. Since the same |
| 5396 | /// values are flowing through both blocks, we don't loose any ability to |
| 5397 | /// specialize. If anything, we make such specialization more likely. |
| 5398 | /// |
| 5399 | /// TODO - This transformation could remove entries from a phi in the target |
| 5400 | /// block when the inputs in the phi are the same for the two blocks being |
| 5401 | /// merged. In some cases, this could result in removal of the PHI entirely. |
| 5402 | static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, |
| 5403 | BasicBlock *BB) { |
| 5404 | auto Succ = BB->getUniqueSuccessor(); |
| 5405 | assert(Succ); |
| 5406 | // If there's a phi in the successor block, we'd likely have to introduce |
| 5407 | // a phi into the merged landing pad block. |
| 5408 | if (isa<PHINode>(*Succ->begin())) |
| 5409 | return false; |
| 5410 | |
| 5411 | for (BasicBlock *OtherPred : predecessors(Succ)) { |
| 5412 | if (BB == OtherPred) |
| 5413 | continue; |
| 5414 | BasicBlock::iterator I = OtherPred->begin(); |
| 5415 | LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); |
| 5416 | if (!LPad2 || !LPad2->isIdenticalTo(LPad)) |
| 5417 | continue; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5418 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) { |
| 5419 | } |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5420 | BranchInst *BI2 = dyn_cast<BranchInst>(I); |
| 5421 | if (!BI2 || !BI2->isIdenticalTo(BI)) |
| 5422 | continue; |
| 5423 | |
David Majnemer | 1efa23d | 2016-02-20 01:07:45 +0000 | [diff] [blame] | 5424 | // We've found an identical block. Update our predecessors to take that |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5425 | // path instead and make ourselves dead. |
| 5426 | SmallSet<BasicBlock *, 16> Preds; |
| 5427 | Preds.insert(pred_begin(BB), pred_end(BB)); |
| 5428 | for (BasicBlock *Pred : Preds) { |
| 5429 | InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5430 | assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && |
| 5431 | "unexpected successor"); |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5432 | II->setUnwindDest(OtherPred); |
| 5433 | } |
| 5434 | |
| 5435 | // The debug info in OtherPred doesn't cover the merged control flow that |
| 5436 | // used to go through BB. We need to delete it or update it. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5437 | for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { |
| 5438 | Instruction &Inst = *I; |
| 5439 | I++; |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5440 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 5441 | Inst.eraseFromParent(); |
| 5442 | } |
| 5443 | |
| 5444 | SmallSet<BasicBlock *, 16> Succs; |
| 5445 | Succs.insert(succ_begin(BB), succ_end(BB)); |
| 5446 | for (BasicBlock *Succ : Succs) { |
| 5447 | Succ->removePredecessor(BB); |
| 5448 | } |
| 5449 | |
| 5450 | IRBuilder<> Builder(BI); |
| 5451 | Builder.CreateUnreachable(); |
| 5452 | BI->eraseFromParent(); |
| 5453 | return true; |
| 5454 | } |
| 5455 | return false; |
| 5456 | } |
| 5457 | |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5458 | bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, |
| 5459 | IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5460 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5461 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 5462 | if (SinkCommon && SinkThenElseCodeToEnd(BI)) |
| 5463 | return true; |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 5464 | |
| 5465 | // If the Terminator is the only non-phi instruction, simplify the block. |
| 5466 | // if LoopHeader is provided, check if the block is a loop header |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 5467 | // (This is for early invocations before loop simplify and vectorization |
| 5468 | // to keep canonical loop forms for nested loops. |
| 5469 | // These blocks can be eliminated when the pass is invoked later |
| 5470 | // in the back-end.) |
Reid Kleckner | bca59d2 | 2016-05-02 19:43:22 +0000 | [diff] [blame] | 5471 | BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5472 | if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && |
Hans Wennborg | e913489 | 2016-04-11 20:35:01 +0000 | [diff] [blame] | 5473 | (!LoopHeaders || !LoopHeaders->count(BB)) && |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5474 | TryToSimplifyUncondBranchFromEmptyBlock(BB)) |
| 5475 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5476 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5477 | // If the only instruction in the block is a seteq/setne comparison |
| 5478 | // against a constant, try to simplify the block. |
| 5479 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) |
| 5480 | if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { |
| 5481 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) |
| 5482 | ; |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 5483 | if (I->isTerminator() && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5484 | TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, |
| 5485 | BonusInstThreshold, AC)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5486 | return true; |
| 5487 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5488 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5489 | // See if we can merge an empty landing pad block with another which is |
| 5490 | // equivalent. |
| 5491 | if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5492 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) { |
| 5493 | } |
| 5494 | if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB)) |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 5495 | return true; |
| 5496 | } |
| 5497 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 5498 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 5499 | // branches to us and our successor, fold the comparison into the |
| 5500 | // predecessor and use logical operations to update the incoming value |
| 5501 | // for PHI nodes in common successor. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5502 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 5503 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5504 | return false; |
| 5505 | } |
| 5506 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 5507 | static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { |
| 5508 | BasicBlock *PredPred = nullptr; |
| 5509 | for (auto *P : predecessors(BB)) { |
| 5510 | BasicBlock *PPred = P->getSinglePredecessor(); |
| 5511 | if (!PPred || (PredPred && PredPred != PPred)) |
| 5512 | return nullptr; |
| 5513 | PredPred = PPred; |
| 5514 | } |
| 5515 | return PredPred; |
| 5516 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5517 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5518 | bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5519 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5520 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5521 | // Conditional branch |
| 5522 | if (isValueEqualityComparison(BI)) { |
| 5523 | // If we only have one predecessor, and if it is a branch on this value, |
| 5524 | // see if that predecessor totally determines the outcome of this |
| 5525 | // switch. |
| 5526 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5527 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5528 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5529 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5530 | // This block must be empty, except for the setcond inst, if it exists. |
| 5531 | // Ignore dbg intrinsics. |
| 5532 | BasicBlock::iterator I = BB->begin(); |
| 5533 | // Ignore dbg intrinsics. |
| 5534 | while (isa<DbgInfoIntrinsic>(I)) |
| 5535 | ++I; |
| 5536 | if (&*I == BI) { |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 5537 | if (FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5538 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5539 | } else if (&*I == cast<Instruction>(BI->getCondition())) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5540 | ++I; |
| 5541 | // Ignore dbg intrinsics. |
| 5542 | while (isa<DbgInfoIntrinsic>(I)) |
| 5543 | ++I; |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 5544 | if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5545 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5546 | } |
| 5547 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5548 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5549 | // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5550 | if (SimplifyBranchOnICmpChain(BI, Builder, DL)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5551 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5552 | |
Chad Rosier | 4ab37c0 | 2016-05-06 14:25:14 +0000 | [diff] [blame] | 5553 | // If this basic block has a single dominating predecessor block and the |
| 5554 | // dominating block's condition implies BI's condition, we know the direction |
| 5555 | // of the BI branch. |
| 5556 | if (BasicBlock *Dom = BB->getSinglePredecessor()) { |
| 5557 | auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator()); |
| 5558 | if (PBI && PBI->isConditional() && |
| 5559 | PBI->getSuccessor(0) != PBI->getSuccessor(1) && |
| 5560 | (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) { |
| 5561 | bool CondIsFalse = PBI->getSuccessor(1) == BB; |
| 5562 | Optional<bool> Implication = isImpliedCondition( |
| 5563 | PBI->getCondition(), BI->getCondition(), DL, CondIsFalse); |
| 5564 | if (Implication) { |
| 5565 | // Turn this into a branch on constant. |
| 5566 | auto *OldCond = BI->getCondition(); |
| 5567 | ConstantInt *CI = *Implication |
| 5568 | ? ConstantInt::getTrue(BB->getContext()) |
| 5569 | : ConstantInt::getFalse(BB->getContext()); |
| 5570 | BI->setCondition(CI); |
| 5571 | RecursivelyDeleteTriviallyDeadInstructions(OldCond); |
| 5572 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
| 5573 | } |
| 5574 | } |
| 5575 | } |
| 5576 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 5577 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 5578 | // branches to us and one of our successors, fold the comparison into the |
| 5579 | // predecessor and use logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5580 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 5581 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5582 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5583 | // We have a conditional branch to two blocks that are only reachable |
| 5584 | // from BI. We know that the condbr dominates the two blocks, so see if |
| 5585 | // there is any identical code in the "then" and "else" blocks. If so, we |
| 5586 | // can hoist it up to the branching block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 5587 | if (BI->getSuccessor(0)->getSinglePredecessor()) { |
| 5588 | if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5589 | if (HoistThenElseCodeToIf(BI, TTI)) |
| 5590 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5591 | } else { |
| 5592 | // If Successor #1 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 5593 | // execute Successor #0 if it branches to Successor #1. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5594 | TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); |
| 5595 | if (Succ0TI->getNumSuccessors() == 1 && |
| 5596 | Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5597 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) |
| 5598 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5599 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 5600 | } else if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5601 | // If Successor #0 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 5602 | // execute Successor #1 if it branches to Successor #0. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5603 | TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); |
| 5604 | if (Succ1TI->getNumSuccessors() == 1 && |
| 5605 | Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5606 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) |
| 5607 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5608 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5609 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5610 | // If this is a branch on a phi node in the current block, thread control |
| 5611 | // through this block if any PHI node entries are constants. |
| 5612 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 5613 | if (PN->getParent() == BI->getParent()) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 5614 | if (FoldCondBranchOnPHI(BI, DL)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5615 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5616 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5617 | // Scan predecessor blocks for conditional branches. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 5618 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 5619 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5620 | if (PBI != BI && PBI->isConditional()) |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 5621 | if (SimplifyCondBranchToCondBranch(PBI, BI, DL)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5622 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5623 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 5624 | // Look for diamond patterns. |
| 5625 | if (MergeCondStores) |
| 5626 | if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) |
| 5627 | if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) |
| 5628 | if (PBI != BI && PBI->isConditional()) |
| 5629 | if (mergeConditionalStores(PBI, BI)) |
| 5630 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5631 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5632 | return false; |
| 5633 | } |
| 5634 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5635 | /// Check if passing a value to an instruction will cause undefined behavior. |
| 5636 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { |
| 5637 | Constant *C = dyn_cast<Constant>(V); |
| 5638 | if (!C) |
| 5639 | return false; |
| 5640 | |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 5641 | if (I->use_empty()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5642 | return false; |
| 5643 | |
David Majnemer | 1fea77c | 2016-06-25 07:37:27 +0000 | [diff] [blame] | 5644 | if (C->isNullValue() || isa<UndefValue>(C)) { |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 5645 | // Only look at the first use, avoid hurting compile time with long uselists |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5646 | User *Use = *I->user_begin(); |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5647 | |
| 5648 | // Now make sure that there are no instructions in between that can alter |
| 5649 | // control flow (eg. calls) |
Duncan P. N. Exon Smith | 0a12729f | 2016-08-16 23:57:56 +0000 | [diff] [blame] | 5650 | for (BasicBlock::iterator |
| 5651 | i = ++BasicBlock::iterator(I), |
| 5652 | UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); |
| 5653 | i != UI; ++i) |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5654 | if (i == I->getParent()->end() || i->mayHaveSideEffects()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5655 | return false; |
| 5656 | |
| 5657 | // Look through GEPs. A load from a GEP derived from NULL is still undefined |
| 5658 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) |
| 5659 | if (GEP->getPointerOperand() == I) |
| 5660 | return passingValueIsAlwaysUndefined(V, GEP); |
| 5661 | |
| 5662 | // Look through bitcasts. |
| 5663 | if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) |
| 5664 | return passingValueIsAlwaysUndefined(V, BC); |
| 5665 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5666 | // Load from null is undefined. |
| 5667 | if (LoadInst *LI = dyn_cast<LoadInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 5668 | if (!LI->isVolatile()) |
| 5669 | return LI->getPointerAddressSpace() == 0; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5670 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5671 | // Store to null is undefined. |
| 5672 | if (StoreInst *SI = dyn_cast<StoreInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 5673 | if (!SI->isVolatile()) |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5674 | return SI->getPointerAddressSpace() == 0 && |
| 5675 | SI->getPointerOperand() == I; |
David Majnemer | 1fea77c | 2016-06-25 07:37:27 +0000 | [diff] [blame] | 5676 | |
| 5677 | // A call to null is undefined. |
| 5678 | if (auto CS = CallSite(Use)) |
| 5679 | return CS.getCalledValue() == I; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5680 | } |
| 5681 | return false; |
| 5682 | } |
| 5683 | |
| 5684 | /// If BB has an incoming value that will always trigger undefined behavior |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 5685 | /// (eg. null pointer dereference), remove the branch leading here. |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5686 | static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { |
| 5687 | for (BasicBlock::iterator i = BB->begin(); |
| 5688 | PHINode *PHI = dyn_cast<PHINode>(i); ++i) |
| 5689 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
| 5690 | if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { |
| 5691 | TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); |
| 5692 | IRBuilder<> Builder(T); |
| 5693 | if (BranchInst *BI = dyn_cast<BranchInst>(T)) { |
| 5694 | BB->removePredecessor(PHI->getIncomingBlock(i)); |
| 5695 | // Turn uncoditional branches into unreachables and remove the dead |
| 5696 | // destination from conditional branches. |
| 5697 | if (BI->isUnconditional()) |
| 5698 | Builder.CreateUnreachable(); |
| 5699 | else |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5700 | Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) |
| 5701 | : BI->getSuccessor(0)); |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5702 | BI->eraseFromParent(); |
| 5703 | return true; |
| 5704 | } |
| 5705 | // TODO: SwitchInst. |
| 5706 | } |
| 5707 | |
| 5708 | return false; |
| 5709 | } |
| 5710 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5711 | bool SimplifyCFGOpt::run(BasicBlock *BB) { |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 5712 | bool Changed = false; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5713 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 5714 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5715 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5716 | |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 5717 | // Remove basic blocks that have no predecessors (except the entry block)... |
| 5718 | // or that just have themself as a predecessor. These are unreachable. |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5719 | if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 5720 | BB->getSinglePredecessor() == BB) { |
David Majnemer | ee0cbbb | 2016-02-24 17:30:48 +0000 | [diff] [blame] | 5721 | DEBUG(dbgs() << "Removing BB: \n" << *BB); |
| 5722 | DeleteDeadBlock(BB); |
| 5723 | return true; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5724 | } |
| 5725 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5726 | // Check to see if we can constant propagate this terminator instruction |
| 5727 | // away... |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 5728 | Changed |= ConstantFoldTerminator(BB, true); |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5729 | |
Dan Gohman | 1a95106 | 2009-10-30 22:39:04 +0000 | [diff] [blame] | 5730 | // Check for and eliminate duplicate PHI nodes in this block. |
| 5731 | Changed |= EliminateDuplicatePHINodes(BB); |
| 5732 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5733 | // Check for and remove branches that will always cause undefined behavior. |
| 5734 | Changed |= removeUndefIntroducingPredecessor(BB); |
| 5735 | |
Chris Lattner | 2e3832d | 2010-12-13 05:10:48 +0000 | [diff] [blame] | 5736 | // Merge basic blocks into their predecessor if there is only one distinct |
| 5737 | // pred, and if there is only one distinct successor of the predecessor, and |
| 5738 | // if there are no PHI nodes. |
| 5739 | // |
| 5740 | if (MergeBlockIntoPredecessor(BB)) |
| 5741 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5742 | |
Devang Patel | 15ad676 | 2011-05-18 18:01:27 +0000 | [diff] [blame] | 5743 | IRBuilder<> Builder(BB); |
| 5744 | |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 5745 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 5746 | // eliminate it, do so now. |
| 5747 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 5748 | if (PN->getNumIncomingValues() == 2) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5749 | Changed |= FoldTwoEntryPHINode(PN, TTI, DL); |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 5750 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5751 | Builder.SetInsertPoint(BB->getTerminator()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5752 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5753 | if (BI->isUnconditional()) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5754 | if (SimplifyUncondBranch(BI, Builder)) |
| 5755 | return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5756 | } else { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5757 | if (SimplifyCondBranch(BI, Builder)) |
| 5758 | return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5759 | } |
| 5760 | } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5761 | if (SimplifyReturn(RI, Builder)) |
| 5762 | return true; |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 5763 | } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5764 | if (SimplifyResume(RI, Builder)) |
| 5765 | return true; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 5766 | } else if (CleanupReturnInst *RI = |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5767 | dyn_cast<CleanupReturnInst>(BB->getTerminator())) { |
| 5768 | if (SimplifyCleanupReturn(RI)) |
| 5769 | return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5770 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5771 | if (SimplifySwitch(SI, Builder)) |
| 5772 | return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5773 | } else if (UnreachableInst *UI = |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5774 | dyn_cast<UnreachableInst>(BB->getTerminator())) { |
| 5775 | if (SimplifyUnreachable(UI)) |
| 5776 | return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5777 | } else if (IndirectBrInst *IBI = |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5778 | dyn_cast<IndirectBrInst>(BB->getTerminator())) { |
| 5779 | if (SimplifyIndirectBr(IBI)) |
| 5780 | return true; |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 5781 | } |
| 5782 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5783 | return Changed; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5784 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5785 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 5786 | /// This function is used to do simplification of a CFG. |
| 5787 | /// For example, it adjusts branches to branches to eliminate the extra hop, |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5788 | /// eliminates unreachable basic blocks, and does other "peephole" optimization |
| 5789 | /// of the CFG. It returns true if a modification was made. |
| 5790 | /// |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 5791 | bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, |
Hyojin Sung | 4673f10 | 2016-03-29 04:08:57 +0000 | [diff] [blame] | 5792 | unsigned BonusInstThreshold, AssumptionCache *AC, |
| 5793 | SmallPtrSetImpl<BasicBlock *> *LoopHeaders) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5794 | return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), |
Dehao Chen | f6c0083 | 2016-05-18 19:44:21 +0000 | [diff] [blame] | 5795 | BonusInstThreshold, AC, LoopHeaders) |
| 5796 | .run(BB); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5797 | } |