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 | |
| 14 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/DenseMap.h" |
| 16 | #include "llvm/ADT/STLExtras.h" |
| 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" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 25 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 26 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Constants.h" |
| 28 | #include "llvm/IR/DataLayout.h" |
| 29 | #include "llvm/IR/DerivedTypes.h" |
| 30 | #include "llvm/IR/GlobalVariable.h" |
| 31 | #include "llvm/IR/IRBuilder.h" |
| 32 | #include "llvm/IR/Instructions.h" |
| 33 | #include "llvm/IR/IntrinsicInst.h" |
| 34 | #include "llvm/IR/LLVMContext.h" |
| 35 | #include "llvm/IR/MDBuilder.h" |
| 36 | #include "llvm/IR/Metadata.h" |
| 37 | #include "llvm/IR/Module.h" |
Chandler Carruth | 64396b0 | 2014-03-04 12:05:47 +0000 | [diff] [blame] | 38 | #include "llvm/IR/NoFolder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 40 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 41 | #include "llvm/IR/Type.h" |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 42 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 43 | #include "llvm/Support/Debug.h" |
| 44 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/Local.h" |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 48 | #include <algorithm> |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 49 | #include <map> |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 50 | #include <set> |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 51 | using namespace llvm; |
Benjamin Kramer | 3717222 | 2013-07-04 14:22:02 +0000 | [diff] [blame] | 52 | using namespace PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 53 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 54 | #define DEBUG_TYPE "simplifycfg" |
| 55 | |
James Molloy | 1b6207e | 2015-02-13 10:48:30 +0000 | [diff] [blame] | 56 | // Chosen as 2 so as to be cheap, but still to have enough power to fold |
| 57 | // a select, so the "clamp" idiom (of a min followed by a max) will be caught. |
| 58 | // To catch this, we need to fold a compare and a select, hence '2' being the |
| 59 | // minimum reasonable default. |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 60 | static cl::opt<unsigned> |
James Molloy | 1b6207e | 2015-02-13 10:48:30 +0000 | [diff] [blame] | 61 | PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), |
| 62 | cl::desc("Control the amount of phi node folding to perform (default = 2)")); |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 63 | |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 64 | static cl::opt<bool> |
| 65 | DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), |
| 66 | cl::desc("Duplicate return instructions into unconditional branches")); |
| 67 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 68 | static cl::opt<bool> |
| 69 | SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), |
| 70 | cl::desc("Sink common instructions down to the end block")); |
| 71 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 72 | static cl::opt<bool> HoistCondStores( |
| 73 | "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), |
| 74 | cl::desc("Hoist conditional stores if an unconditional store precedes")); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 75 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 76 | STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 77 | STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 78 | STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables"); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 79 | STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)"); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 80 | STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 81 | STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 82 | STATISTIC(NumSpeculations, "Number of speculative executed instructions"); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 83 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 84 | namespace { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 85 | // The first field contains the value that the switch produces when a certain |
| 86 | // case group is selected, and the second field is a vector containing the cases |
| 87 | // composing the case group. |
| 88 | typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2> |
| 89 | SwitchCaseResultVectorTy; |
| 90 | // The first field contains the phi node that generates a result of the switch |
| 91 | // and the second field contains the value generated for a certain case in the switch |
| 92 | // for that PHI. |
| 93 | typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy; |
| 94 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 95 | /// ValueEqualityComparisonCase - Represents a case of a switch. |
| 96 | struct ValueEqualityComparisonCase { |
| 97 | ConstantInt *Value; |
| 98 | BasicBlock *Dest; |
| 99 | |
| 100 | ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) |
| 101 | : Value(Value), Dest(Dest) {} |
| 102 | |
| 103 | bool operator<(ValueEqualityComparisonCase RHS) const { |
| 104 | // Comparing pointers is ok as we only rely on the order for uniquing. |
| 105 | return Value < RHS.Value; |
| 106 | } |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 107 | |
| 108 | bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 109 | }; |
| 110 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 111 | class SimplifyCFGOpt { |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 112 | const TargetTransformInfo &TTI; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 113 | const DataLayout &DL; |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 114 | unsigned BonusInstThreshold; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 115 | AssumptionCache *AC; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 116 | Value *isValueEqualityComparison(TerminatorInst *TI); |
| 117 | BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 118 | std::vector<ValueEqualityComparisonCase> &Cases); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 119 | bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 120 | BasicBlock *Pred, |
| 121 | IRBuilder<> &Builder); |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 122 | bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 123 | IRBuilder<> &Builder); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 124 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 125 | bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 126 | bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 127 | bool SimplifyCleanupReturn(CleanupReturnInst *RI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 128 | bool SimplifyUnreachable(UnreachableInst *UI); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 129 | bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 130 | bool SimplifyIndirectBr(IndirectBrInst *IBI); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 131 | bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 132 | bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 133 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 134 | public: |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 135 | SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, |
| 136 | unsigned BonusInstThreshold, AssumptionCache *AC) |
| 137 | : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {} |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 138 | bool run(BasicBlock *BB); |
| 139 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 140 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 141 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 142 | /// Return true if it is safe to merge these two |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 143 | /// terminator instructions together. |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 144 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { |
| 145 | if (SI1 == SI2) return false; // Can't merge with self! |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 146 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 147 | // It is not safe to merge these two switch instructions if they have a common |
| 148 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 149 | // conflicting incoming values from the two switch blocks. |
| 150 | BasicBlock *SI1BB = SI1->getParent(); |
| 151 | BasicBlock *SI2BB = SI2->getParent(); |
Chris Lattner | b7b7514 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 152 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 153 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 154 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 155 | if (SI1Succs.count(*I)) |
| 156 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 157 | isa<PHINode>(BBI); ++BBI) { |
| 158 | PHINode *PN = cast<PHINode>(BBI); |
| 159 | if (PN->getIncomingValueForBlock(SI1BB) != |
| 160 | PN->getIncomingValueForBlock(SI2BB)) |
| 161 | return false; |
| 162 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 163 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 164 | return true; |
| 165 | } |
| 166 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 167 | /// Return true if it is safe and profitable to merge these two terminator |
| 168 | /// instructions together, where SI1 is an unconditional branch. PhiNodes will |
| 169 | /// store all PHI nodes in common successors. |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 170 | static bool isProfitableToFoldUnconditional(BranchInst *SI1, |
| 171 | BranchInst *SI2, |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 172 | Instruction *Cond, |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 173 | SmallVectorImpl<PHINode*> &PhiNodes) { |
| 174 | if (SI1 == SI2) return false; // Can't merge with self! |
| 175 | assert(SI1->isUnconditional() && SI2->isConditional()); |
| 176 | |
| 177 | // 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] | 178 | // common successors: |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 179 | // 1> We have a constant incoming value for the conditional branch; |
| 180 | // 2> We have "Cond" as the incoming value for the unconditional branch; |
| 181 | // 3> SI2->getCondition() and Cond have same operands. |
| 182 | CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); |
| 183 | if (!Ci2) return false; |
| 184 | if (!(Cond->getOperand(0) == Ci2->getOperand(0) && |
| 185 | Cond->getOperand(1) == Ci2->getOperand(1)) && |
| 186 | !(Cond->getOperand(0) == Ci2->getOperand(1) && |
| 187 | Cond->getOperand(1) == Ci2->getOperand(0))) |
| 188 | return false; |
| 189 | |
| 190 | BasicBlock *SI1BB = SI1->getParent(); |
| 191 | BasicBlock *SI2BB = SI2->getParent(); |
| 192 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 193 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 194 | if (SI1Succs.count(*I)) |
| 195 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 196 | isa<PHINode>(BBI); ++BBI) { |
| 197 | PHINode *PN = cast<PHINode>(BBI); |
| 198 | if (PN->getIncomingValueForBlock(SI1BB) != Cond || |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 199 | !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 200 | return false; |
| 201 | PhiNodes.push_back(PN); |
| 202 | } |
| 203 | return true; |
| 204 | } |
| 205 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 206 | /// Update PHI nodes in Succ to indicate that there will now be entries in it |
| 207 | /// from the 'NewPred' block. The values that will be flowing into the PHI nodes |
| 208 | /// will be the same as those coming in from ExistPred, an existing predecessor |
| 209 | /// of Succ. |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 210 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 211 | BasicBlock *ExistPred) { |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 212 | if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 213 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 214 | PHINode *PN; |
| 215 | for (BasicBlock::iterator I = Succ->begin(); |
| 216 | (PN = dyn_cast<PHINode>(I)); ++I) |
| 217 | PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 218 | } |
| 219 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 220 | /// Compute an abstract "cost" of speculating the given instruction, |
| 221 | /// which is assumed to be safe to speculate. TCC_Free means cheap, |
| 222 | /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 223 | /// expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 224 | static unsigned ComputeSpeculationCost(const User *I, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 225 | const TargetTransformInfo &TTI) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 226 | assert(isSafeToSpeculativelyExecute(I) && |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 227 | "Instruction is not safe to speculatively execute!"); |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 228 | return TTI.getUserCost(I); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 229 | } |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 230 | /// If we have a merge point of an "if condition" as accepted above, |
| 231 | /// return true if the specified value dominates the block. We |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 232 | /// don't handle the true generality of domination here, just a special case |
| 233 | /// which works well enough for us. |
| 234 | /// |
| 235 | /// 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] | 236 | /// see if V (which must be an instruction) and its recursive operands |
| 237 | /// that do not dominate BB have a combined cost lower than CostRemaining and |
| 238 | /// are non-trapping. If both are true, the instruction is inserted into the |
| 239 | /// set and true is returned. |
| 240 | /// |
| 241 | /// The cost for most non-trapping instructions is defined as 1 except for |
| 242 | /// Select whose cost is 2. |
| 243 | /// |
| 244 | /// After this function returns, CostRemaining is decreased by the cost of |
| 245 | /// V plus its non-dominating operands. If that cost is greater than |
| 246 | /// CostRemaining, false is returned and CostRemaining is undefined. |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 247 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 248 | SmallPtrSetImpl<Instruction*> *AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 249 | unsigned &CostRemaining, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 250 | const TargetTransformInfo &TTI) { |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 251 | Instruction *I = dyn_cast<Instruction>(V); |
Chris Lattner | b8b1159 | 2006-10-20 00:42:07 +0000 | [diff] [blame] | 252 | if (!I) { |
| 253 | // Non-instructions all dominate instructions, but not all constantexprs |
| 254 | // can be executed unconditionally. |
| 255 | if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| 256 | if (C->canTrap()) |
| 257 | return false; |
| 258 | return true; |
| 259 | } |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 260 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 261 | |
Chris Lattner | 0ce80cd | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 262 | // 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] | 263 | // the bottom of this block. |
| 264 | if (PBB == BB) return false; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 265 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 266 | // If this instruction is defined in a block that contains an unconditional |
| 267 | // 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] | 268 | // statement". If not, it definitely dominates the region. |
| 269 | BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 270 | if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 271 | return true; |
Eli Friedman | b8f6a4f | 2009-07-17 04:28:42 +0000 | [diff] [blame] | 272 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 273 | // If we aren't allowing aggressive promotion anymore, then don't consider |
| 274 | // instructions in the 'if region'. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 275 | if (!AggressiveInsts) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 276 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 277 | // If we have seen this instruction before, don't count it again. |
| 278 | if (AggressiveInsts->count(I)) return true; |
| 279 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 280 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 281 | // see if it's a cheap instruction to unconditionally compute, and if it |
| 282 | // 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] | 283 | if (!isSafeToSpeculativelyExecute(I)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 284 | return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 285 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 286 | unsigned Cost = ComputeSpeculationCost(I, TTI); |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 287 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 288 | if (Cost > CostRemaining) |
| 289 | return false; |
| 290 | |
| 291 | CostRemaining -= Cost; |
| 292 | |
| 293 | // Okay, we can only really hoist these out if their operands do |
| 294 | // not take us over the cost threshold. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 295 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 296 | if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 297 | return false; |
| 298 | // Okay, it's safe to do this! Remember this instruction. |
| 299 | AggressiveInsts->insert(I); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 300 | return true; |
| 301 | } |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 302 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 303 | /// Extract ConstantInt from value, looking through IntToPtr |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 304 | /// and PointerNullValue. Return NULL if value is not a constant int. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 305 | static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 306 | // Normal constant int. |
| 307 | ConstantInt *CI = dyn_cast<ConstantInt>(V); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 308 | if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 309 | return CI; |
| 310 | |
| 311 | // This is some kind of pointer constant. Turn it into a pointer-sized |
| 312 | // ConstantInt if possible. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 313 | IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 314 | |
| 315 | // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). |
| 316 | if (isa<ConstantPointerNull>(V)) |
| 317 | return ConstantInt::get(PtrTy, 0); |
| 318 | |
| 319 | // IntToPtr const int. |
| 320 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 321 | if (CE->getOpcode() == Instruction::IntToPtr) |
| 322 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { |
| 323 | // The constant is very likely to have the right type already. |
| 324 | if (CI->getType() == PtrTy) |
| 325 | return CI; |
| 326 | else |
| 327 | return cast<ConstantInt> |
| 328 | (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); |
| 329 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 330 | return nullptr; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 331 | } |
| 332 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 333 | namespace { |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 334 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 335 | /// Given a chain of or (||) or and (&&) comparison of a value against a |
| 336 | /// constant, this will try to recover the information required for a switch |
| 337 | /// structure. |
| 338 | /// It will depth-first traverse the chain of comparison, seeking for patterns |
| 339 | /// like %a == 12 or %a < 4 and combine them to produce a set of integer |
| 340 | /// representing the different cases for the switch. |
| 341 | /// Note that if the chain is composed of '||' it will build the set of elements |
| 342 | /// that matches the comparisons (i.e. any of this value validate the chain) |
| 343 | /// while for a chain of '&&' it will build the set elements that make the test |
| 344 | /// fail. |
| 345 | struct ConstantComparesGatherer { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 346 | const DataLayout &DL; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 347 | Value *CompValue; /// Value found for the switch comparison |
| 348 | Value *Extra; /// Extra clause to be checked before the switch |
| 349 | SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch |
| 350 | unsigned UsedICmps; /// Number of comparisons matched in the and/or chain |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 351 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 352 | /// Construct and compute the result for the comparison instruction Cond |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 353 | ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) |
| 354 | : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) { |
| 355 | gather(Cond); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 356 | } |
| 357 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 358 | /// Prevent copy |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 359 | ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 360 | ConstantComparesGatherer & |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 361 | operator=(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 362 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 363 | private: |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 364 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 365 | /// Try to set the current value used for the comparison, it succeeds only if |
| 366 | /// it wasn't set before or if the new value is the same as the old one |
| 367 | bool setValueOnce(Value *NewVal) { |
| 368 | if(CompValue && CompValue != NewVal) return false; |
| 369 | CompValue = NewVal; |
| 370 | return (CompValue != nullptr); |
| 371 | } |
| 372 | |
| 373 | /// Try to match Instruction "I" as a comparison against a constant and |
| 374 | /// populates the array Vals with the set of values that match (or do not |
| 375 | /// match depending on isEQ). |
| 376 | /// Return false on failure. On success, the Value the comparison matched |
| 377 | /// against is placed in CompValue. |
| 378 | /// If CompValue is already set, the function is expected to fail if a match |
| 379 | /// is found but the value compared to is different. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 380 | bool matchInstruction(Instruction *I, bool isEQ) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 381 | // If this is an icmp against a constant, handle this as one of the cases. |
| 382 | ICmpInst *ICI; |
| 383 | ConstantInt *C; |
| 384 | if (!((ICI = dyn_cast<ICmpInst>(I)) && |
| 385 | (C = GetConstantInt(I->getOperand(1), DL)))) { |
| 386 | return false; |
| 387 | } |
| 388 | |
| 389 | Value *RHSVal; |
| 390 | ConstantInt *RHSC; |
| 391 | |
| 392 | // Pattern match a special case |
| 393 | // (x & ~2^x) == y --> x == y || x == y|2^x |
| 394 | // This undoes a transformation done by instcombine to fuse 2 compares. |
| 395 | if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) { |
| 396 | if (match(ICI->getOperand(0), |
| 397 | m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 398 | APInt Not = ~RHSC->getValue(); |
| 399 | if (Not.isPowerOf2()) { |
| 400 | // If we already have a value for the switch, it has to match! |
| 401 | if(!setValueOnce(RHSVal)) |
| 402 | return false; |
| 403 | |
| 404 | Vals.push_back(C); |
| 405 | Vals.push_back(ConstantInt::get(C->getContext(), |
| 406 | C->getValue() | Not)); |
| 407 | UsedICmps++; |
| 408 | return true; |
| 409 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 410 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 411 | |
| 412 | // If we already have a value for the switch, it has to match! |
| 413 | if(!setValueOnce(ICI->getOperand(0))) |
| 414 | return false; |
| 415 | |
| 416 | UsedICmps++; |
| 417 | Vals.push_back(C); |
| 418 | return ICI->getOperand(0); |
| 419 | } |
| 420 | |
| 421 | // 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] | 422 | ConstantRange Span = ConstantRange::makeAllowedICmpRegion( |
| 423 | ICI->getPredicate(), C->getValue()); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 424 | |
| 425 | // Shift the range if the compare is fed by an add. This is the range |
| 426 | // compare idiom as emitted by instcombine. |
| 427 | Value *CandidateVal = I->getOperand(0); |
| 428 | if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 429 | Span = Span.subtract(RHSC->getValue()); |
| 430 | CandidateVal = RHSVal; |
| 431 | } |
| 432 | |
| 433 | // If this is an and/!= check, then we are looking to build the set of |
| 434 | // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into |
| 435 | // x != 0 && x != 1. |
| 436 | if (!isEQ) |
| 437 | Span = Span.inverse(); |
| 438 | |
| 439 | // If there are a ton of values, we don't want to make a ginormous switch. |
| 440 | if (Span.getSetSize().ugt(8) || Span.isEmptySet()) { |
| 441 | return false; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 442 | } |
| 443 | |
| 444 | // If we already have a value for the switch, it has to match! |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 445 | if(!setValueOnce(CandidateVal)) |
| 446 | return false; |
| 447 | |
| 448 | // Add all values from the range to the set |
| 449 | for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) |
| 450 | Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 451 | |
| 452 | UsedICmps++; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 453 | return true; |
| 454 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 455 | } |
| 456 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 457 | /// Given a potentially 'or'd or 'and'd together collection of icmp |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 458 | /// eq/ne/lt/gt instructions that compare a value against a constant, extract |
| 459 | /// the value being compared, and stick the list constants into the Vals |
| 460 | /// vector. |
| 461 | /// One "Extra" case is allowed to differ from the other. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 462 | void gather(Value *V) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 463 | Instruction *I = dyn_cast<Instruction>(V); |
| 464 | bool isEQ = (I->getOpcode() == Instruction::Or); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 465 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 466 | // Keep a stack (SmallVector for efficiency) for depth-first traversal |
| 467 | SmallVector<Value *, 8> DFT; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 468 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 469 | // Initialize |
| 470 | DFT.push_back(V); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 471 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 472 | while(!DFT.empty()) { |
| 473 | V = DFT.pop_back_val(); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 474 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 475 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 476 | // If it is a || (or && depending on isEQ), process the operands. |
| 477 | if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { |
| 478 | DFT.push_back(I->getOperand(1)); |
| 479 | DFT.push_back(I->getOperand(0)); |
| 480 | continue; |
| 481 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 482 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 483 | // Try to match the current instruction |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 484 | if (matchInstruction(I, isEQ)) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 485 | // Match succeed, continue the loop |
| 486 | continue; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 487 | } |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 488 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 489 | // One element of the sequence of || (or &&) could not be match as a |
| 490 | // comparison against the same value as the others. |
| 491 | // We allow only one "Extra" case to be checked before the switch |
| 492 | if (!Extra) { |
| 493 | Extra = V; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 494 | continue; |
| 495 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 496 | // Failed to parse a proper sequence, abort now |
| 497 | CompValue = nullptr; |
| 498 | break; |
Chris Lattner | 5a177e6 | 2010-12-13 04:26:26 +0000 | [diff] [blame] | 499 | } |
Anton Korobeynikov | 1bfd121 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 500 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 501 | }; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 502 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 503 | } |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 504 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 505 | static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 506 | Instruction *Cond = nullptr; |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 507 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 508 | Cond = dyn_cast<Instruction>(SI->getCondition()); |
| 509 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 510 | if (BI->isConditional()) |
| 511 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 512 | } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { |
| 513 | Cond = dyn_cast<Instruction>(IBI->getAddress()); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 514 | } |
| 515 | |
| 516 | TI->eraseFromParent(); |
| 517 | if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond); |
| 518 | } |
| 519 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 520 | /// Return true if the specified terminator checks |
Chris Lattner | 8e84c12 | 2008-11-27 23:25:44 +0000 | [diff] [blame] | 521 | /// to see if a value is equal to constant integer value. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 522 | Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 523 | Value *CV = nullptr; |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 524 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 525 | // Do not permit merging of large switch instructions into their |
| 526 | // predecessors unless there is only one predecessor. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 527 | if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()), |
| 528 | pred_end(SI->getParent())) <= 128) |
| 529 | CV = SI->getCondition(); |
| 530 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 531 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 532 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 533 | if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 534 | CV = ICI->getOperand(0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 535 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 536 | |
| 537 | // Unwrap any lossless ptrtoint cast. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 538 | if (CV) { |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 539 | if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { |
| 540 | Value *Ptr = PTII->getPointerOperand(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 541 | if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 542 | CV = Ptr; |
| 543 | } |
| 544 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 545 | return CV; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 546 | } |
| 547 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 548 | /// Given a value comparison instruction, |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 549 | /// decode all of the 'cases' that it represents and return the 'default' block. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 550 | BasicBlock *SimplifyCFGOpt:: |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 551 | GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 552 | std::vector<ValueEqualityComparisonCase> |
| 553 | &Cases) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 554 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 555 | Cases.reserve(SI->getNumCases()); |
| 556 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) |
| 557 | Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(), |
| 558 | i.getCaseSuccessor())); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 559 | return SI->getDefaultDest(); |
| 560 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 561 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 562 | BranchInst *BI = cast<BranchInst>(TI); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 563 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 564 | BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); |
| 565 | Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1), |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 566 | DL), |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 567 | Succ)); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 568 | return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 569 | } |
| 570 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 571 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 572 | /// Given a vector of bb/value pairs, remove any entries |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 573 | /// in the list that match the specified block. |
| 574 | static void EliminateBlockCases(BasicBlock *BB, |
| 575 | std::vector<ValueEqualityComparisonCase> &Cases) { |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 576 | Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 577 | } |
| 578 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 579 | /// Return true if there are any keys in C1 that exist in C2 as well. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 580 | static bool |
| 581 | ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, |
| 582 | std::vector<ValueEqualityComparisonCase > &C2) { |
| 583 | std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; |
| 584 | |
| 585 | // Make V1 be smaller than V2. |
| 586 | if (V1->size() > V2->size()) |
| 587 | std::swap(V1, V2); |
| 588 | |
| 589 | if (V1->size() == 0) return false; |
| 590 | if (V1->size() == 1) { |
| 591 | // Just scan V2. |
| 592 | ConstantInt *TheVal = (*V1)[0].Value; |
| 593 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 594 | if (TheVal == (*V2)[i].Value) |
| 595 | return true; |
| 596 | } |
| 597 | |
| 598 | // Otherwise, just sort both lists and compare element by element. |
| 599 | array_pod_sort(V1->begin(), V1->end()); |
| 600 | array_pod_sort(V2->begin(), V2->end()); |
| 601 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 602 | while (i1 != e1 && i2 != e2) { |
| 603 | if ((*V1)[i1].Value == (*V2)[i2].Value) |
| 604 | return true; |
| 605 | if ((*V1)[i1].Value < (*V2)[i2].Value) |
| 606 | ++i1; |
| 607 | else |
| 608 | ++i2; |
| 609 | } |
| 610 | return false; |
| 611 | } |
| 612 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 613 | /// If TI is known to be a terminator instruction and its block is known to |
| 614 | /// only have a single predecessor block, check to see if that predecessor is |
| 615 | /// also a value comparison with the same value, and if that comparison |
| 616 | /// determines the outcome of this comparison. If so, simplify TI. This does a |
| 617 | /// very limited form of jump threading. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 618 | bool SimplifyCFGOpt:: |
| 619 | SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 620 | BasicBlock *Pred, |
| 621 | IRBuilder<> &Builder) { |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 622 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| 623 | if (!PredVal) return false; // Not a value comparison in predecessor. |
| 624 | |
| 625 | Value *ThisVal = isValueEqualityComparison(TI); |
| 626 | assert(ThisVal && "This isn't a value comparison!!"); |
| 627 | if (ThisVal != PredVal) return false; // Different predicates. |
| 628 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 629 | // TODO: Preserve branch weight metadata, similarly to how |
| 630 | // FoldValueComparisonIntoPredecessors preserves it. |
| 631 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 632 | // 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] | 633 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 634 | BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), |
| 635 | PredCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 636 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 637 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 638 | // Find information about how control leaves this block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 639 | std::vector<ValueEqualityComparisonCase> ThisCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 640 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 641 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 642 | |
| 643 | // If TI's block is the default block from Pred's comparison, potentially |
| 644 | // simplify TI based on this knowledge. |
| 645 | if (PredDef == TI->getParent()) { |
| 646 | // If we are here, we know that the value is none of those cases listed in |
| 647 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 648 | // can simplify TI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 649 | if (!ValuesOverlap(PredCases, ThisCases)) |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 650 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 651 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 652 | if (isa<BranchInst>(TI)) { |
| 653 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 654 | // uncond br. |
| 655 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 656 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 657 | Instruction *NI = Builder.CreateBr(ThisDef); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 658 | (void) NI; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 659 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 660 | // Remove PHI node entries for the dead edge. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 661 | ThisCases[0].Dest->removePredecessor(TI->getParent()); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 662 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 663 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 664 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 665 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 666 | EraseTerminatorInstAndDCECond(TI); |
| 667 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 668 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 669 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 670 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 671 | // Okay, TI has cases that are statically dead, prune them away. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 672 | SmallPtrSet<Constant*, 16> DeadCases; |
| 673 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 674 | DeadCases.insert(PredCases[i].Value); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 675 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 676 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 677 | << "Through successor TI: " << *TI); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 678 | |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 679 | // Collect branch weights into a vector. |
| 680 | SmallVector<uint32_t, 8> Weights; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 681 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 682 | bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); |
| 683 | if (HasWeight) |
| 684 | for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| 685 | ++MD_i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 686 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 687 | Weights.push_back(CI->getValue().getZExtValue()); |
| 688 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 689 | for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { |
| 690 | --i; |
| 691 | if (DeadCases.count(i.getCaseValue())) { |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 692 | if (HasWeight) { |
| 693 | std::swap(Weights[i.getCaseIndex()+1], Weights.back()); |
| 694 | Weights.pop_back(); |
| 695 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 696 | i.getCaseSuccessor()->removePredecessor(TI->getParent()); |
| 697 | SI->removeCase(i); |
| 698 | } |
| 699 | } |
Manman Ren | 97c1876 | 2012-10-11 22:28:34 +0000 | [diff] [blame] | 700 | if (HasWeight && Weights.size() >= 2) |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 701 | SI->setMetadata(LLVMContext::MD_prof, |
| 702 | MDBuilder(SI->getParent()->getContext()). |
| 703 | createBranchWeights(Weights)); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 704 | |
| 705 | DEBUG(dbgs() << "Leaving: " << *TI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 706 | return true; |
| 707 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 708 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 709 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 710 | // which value (or set of values) this is. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 711 | ConstantInt *TIV = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 712 | BasicBlock *TIBB = TI->getParent(); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 713 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 714 | if (PredCases[i].Dest == TIBB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 715 | if (TIV) |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 716 | return false; // Cannot handle multiple values coming to this block. |
| 717 | TIV = PredCases[i].Value; |
| 718 | } |
| 719 | assert(TIV && "No edge from pred to succ?"); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 720 | |
| 721 | // Okay, we found the one constant that our value can be if we get into TI's |
| 722 | // BB. Find out which successor will unconditionally be branched to. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 723 | BasicBlock *TheRealDest = nullptr; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 724 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 725 | if (ThisCases[i].Value == TIV) { |
| 726 | TheRealDest = ThisCases[i].Dest; |
| 727 | break; |
| 728 | } |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 729 | |
| 730 | // If not handled by any explicit cases, it is handled by the default case. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 731 | if (!TheRealDest) TheRealDest = ThisDef; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 732 | |
| 733 | // Remove PHI node entries for dead edges. |
| 734 | BasicBlock *CheckEdge = TheRealDest; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 735 | for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) |
| 736 | if (*SI != CheckEdge) |
| 737 | (*SI)->removePredecessor(TIBB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 738 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 739 | CheckEdge = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 740 | |
| 741 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 742 | Instruction *NI = Builder.CreateBr(TheRealDest); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 743 | (void) NI; |
| 744 | |
| 745 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 746 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
| 747 | |
| 748 | EraseTerminatorInstAndDCECond(TI); |
| 749 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 750 | } |
| 751 | |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 752 | namespace { |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 753 | /// This class implements a stable ordering of constant |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 754 | /// integers that does not depend on their address. This is important for |
| 755 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 756 | struct ConstantIntOrdering { |
| 757 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| 758 | return LHS->getValue().ult(RHS->getValue()); |
| 759 | } |
| 760 | }; |
| 761 | } |
Dale Johannesen | 5a41b2d | 2009-03-12 01:00:26 +0000 | [diff] [blame] | 762 | |
Benjamin Kramer | 8817cca | 2013-09-22 14:09:50 +0000 | [diff] [blame] | 763 | static int ConstantIntSortPredicate(ConstantInt *const *P1, |
| 764 | ConstantInt *const *P2) { |
| 765 | const ConstantInt *LHS = *P1; |
| 766 | const ConstantInt *RHS = *P2; |
Chris Lattner | e893e26 | 2010-12-15 04:52:41 +0000 | [diff] [blame] | 767 | if (LHS->getValue().ult(RHS->getValue())) |
| 768 | return 1; |
| 769 | if (LHS->getValue() == RHS->getValue()) |
| 770 | return 0; |
| 771 | return -1; |
Chris Lattner | 7c8e604 | 2010-12-13 02:00:58 +0000 | [diff] [blame] | 772 | } |
| 773 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 774 | static inline bool HasBranchWeights(const Instruction* I) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 775 | MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 776 | if (ProfMD && ProfMD->getOperand(0)) |
| 777 | if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) |
| 778 | return MDS->getString().equals("branch_weights"); |
| 779 | |
| 780 | return false; |
| 781 | } |
| 782 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 783 | /// Get Weights of a given TerminatorInst, the default weight is at the front |
| 784 | /// of the vector. If TI is a conditional eq, we need to swap the branch-weight |
| 785 | /// metadata. |
| 786 | static void GetBranchWeights(TerminatorInst *TI, |
| 787 | SmallVectorImpl<uint64_t> &Weights) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 788 | MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 789 | assert(MD); |
| 790 | 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] | 791 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 792 | Weights.push_back(CI->getValue().getZExtValue()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 793 | } |
| 794 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 795 | // If TI is a conditional eq, the default case is the false case, |
| 796 | // and the corresponding branch-weight data is at index 2. We swap the |
| 797 | // default weight to be the first entry. |
| 798 | if (BranchInst* BI = dyn_cast<BranchInst>(TI)) { |
| 799 | assert(Weights.size() == 2); |
| 800 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| 801 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 802 | std::swap(Weights.front(), Weights.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 803 | } |
| 804 | } |
| 805 | |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 806 | /// Keep halving the weights until all can fit in uint32_t. |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 807 | static void FitWeights(MutableArrayRef<uint64_t> Weights) { |
Benjamin Kramer | 79da941 | 2014-03-09 14:42:55 +0000 | [diff] [blame] | 808 | uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); |
| 809 | if (Max > UINT_MAX) { |
| 810 | unsigned Offset = 32 - countLeadingZeros(Max); |
| 811 | for (uint64_t &I : Weights) |
| 812 | I >>= Offset; |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 813 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 814 | } |
| 815 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 816 | /// The specified terminator is a value equality comparison instruction |
| 817 | /// (either a switch or a branch on "X == c"). |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 818 | /// See if any of the predecessors of the terminator block are value comparisons |
| 819 | /// 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] | 820 | bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 821 | IRBuilder<> &Builder) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 822 | BasicBlock *BB = TI->getParent(); |
| 823 | Value *CV = isValueEqualityComparison(TI); // CondVal |
| 824 | assert(CV && "Not a comparison?"); |
| 825 | bool Changed = false; |
| 826 | |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 827 | SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 828 | while (!Preds.empty()) { |
Dan Gohman | 9a6fef0 | 2009-05-06 17:22:41 +0000 | [diff] [blame] | 829 | BasicBlock *Pred = Preds.pop_back_val(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 830 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 831 | // See if the predecessor is a comparison with the same value. |
| 832 | TerminatorInst *PTI = Pred->getTerminator(); |
| 833 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| 834 | |
| 835 | if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { |
| 836 | // Figure out which 'cases' to copy from SI to PSI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 837 | std::vector<ValueEqualityComparisonCase> BBCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 838 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 839 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 840 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 841 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 842 | |
| 843 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 844 | // PredCases and PredDefault with the new switch cases we would like to |
| 845 | // build. |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 846 | SmallVector<BasicBlock*, 8> NewSuccessors; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 847 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 848 | // Update the branch weight metadata along the way |
| 849 | SmallVector<uint64_t, 8> Weights; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 850 | bool PredHasWeights = HasBranchWeights(PTI); |
| 851 | bool SuccHasWeights = HasBranchWeights(TI); |
| 852 | |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 853 | if (PredHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 854 | GetBranchWeights(PTI, Weights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 855 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 856 | if (Weights.size() != 1 + PredCases.size()) |
| 857 | PredHasWeights = SuccHasWeights = false; |
| 858 | } else if (SuccHasWeights) |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 859 | // If there are no predecessor weights but there are successor weights, |
| 860 | // populate Weights with 1, which will later be scaled to the sum of |
| 861 | // successor's weights |
| 862 | Weights.assign(1 + PredCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 863 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 864 | SmallVector<uint64_t, 8> SuccWeights; |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 865 | if (SuccHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 866 | GetBranchWeights(TI, SuccWeights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 867 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 868 | if (SuccWeights.size() != 1 + BBCases.size()) |
| 869 | PredHasWeights = SuccHasWeights = false; |
| 870 | } else if (PredHasWeights) |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 871 | SuccWeights.assign(1 + BBCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 872 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 873 | if (PredDefault == BB) { |
| 874 | // If this is the default destination from PTI, only the edges in TI |
| 875 | // that don't occur in PTI, or that branch to BB will be activated. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 876 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
| 877 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 878 | if (PredCases[i].Dest != BB) |
| 879 | PTIHandled.insert(PredCases[i].Value); |
| 880 | else { |
| 881 | // The default destination is BB, we don't need explicit targets. |
| 882 | std::swap(PredCases[i], PredCases.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 883 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 884 | if (PredHasWeights || SuccHasWeights) { |
| 885 | // Increase weight for the default case. |
| 886 | Weights[0] += Weights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 887 | std::swap(Weights[i+1], Weights.back()); |
| 888 | Weights.pop_back(); |
| 889 | } |
| 890 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 891 | PredCases.pop_back(); |
| 892 | --i; --e; |
| 893 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 894 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 895 | // Reconstruct the new switch statement we will be building. |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 896 | if (PredDefault != BBDefault) { |
| 897 | PredDefault->removePredecessor(Pred); |
| 898 | PredDefault = BBDefault; |
| 899 | NewSuccessors.push_back(BBDefault); |
| 900 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 901 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 902 | unsigned CasesFromPred = Weights.size(); |
| 903 | uint64_t ValidTotalSuccWeight = 0; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 904 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 905 | if (!PTIHandled.count(BBCases[i].Value) && |
| 906 | BBCases[i].Dest != BBDefault) { |
| 907 | PredCases.push_back(BBCases[i]); |
| 908 | NewSuccessors.push_back(BBCases[i].Dest); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 909 | if (SuccHasWeights || PredHasWeights) { |
| 910 | // The default weight is at index 0, so weight for the ith case |
| 911 | // should be at index i+1. Scale the cases from successor by |
| 912 | // PredDefaultWeight (Weights[0]). |
| 913 | Weights.push_back(Weights[0] * SuccWeights[i+1]); |
| 914 | ValidTotalSuccWeight += SuccWeights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 915 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 916 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 917 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 918 | if (SuccHasWeights || PredHasWeights) { |
| 919 | ValidTotalSuccWeight += SuccWeights[0]; |
| 920 | // Scale the cases from predecessor by ValidTotalSuccWeight. |
| 921 | for (unsigned i = 1; i < CasesFromPred; ++i) |
| 922 | Weights[i] *= ValidTotalSuccWeight; |
| 923 | // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). |
| 924 | Weights[0] *= SuccWeights[0]; |
| 925 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 926 | } else { |
| 927 | // If this is not the default destination from PSI, only the edges |
| 928 | // in SI that occur in PSI with a destination of BB will be |
| 929 | // activated. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 930 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 931 | std::map<ConstantInt*, uint64_t> WeightsForHandled; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 932 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 933 | if (PredCases[i].Dest == BB) { |
| 934 | PTIHandled.insert(PredCases[i].Value); |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 935 | |
| 936 | if (PredHasWeights || SuccHasWeights) { |
| 937 | WeightsForHandled[PredCases[i].Value] = Weights[i+1]; |
| 938 | std::swap(Weights[i+1], Weights.back()); |
| 939 | Weights.pop_back(); |
| 940 | } |
| 941 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 942 | std::swap(PredCases[i], PredCases.back()); |
| 943 | PredCases.pop_back(); |
| 944 | --i; --e; |
| 945 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 946 | |
| 947 | // Okay, now we know which constants were sent to BB from the |
| 948 | // predecessor. Figure out where they will all go now. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 949 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 950 | if (PTIHandled.count(BBCases[i].Value)) { |
| 951 | // If this is one we are capable of getting... |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 952 | if (PredHasWeights || SuccHasWeights) |
| 953 | Weights.push_back(WeightsForHandled[BBCases[i].Value]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 954 | PredCases.push_back(BBCases[i]); |
| 955 | NewSuccessors.push_back(BBCases[i].Dest); |
| 956 | PTIHandled.erase(BBCases[i].Value);// This constant is taken care of |
| 957 | } |
| 958 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 959 | // If there are any constants vectored to BB that TI doesn't handle, |
| 960 | // they must go to the default destination of TI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 961 | for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 962 | PTIHandled.begin(), |
| 963 | E = PTIHandled.end(); I != E; ++I) { |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 964 | if (PredHasWeights || SuccHasWeights) |
| 965 | Weights.push_back(WeightsForHandled[*I]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 966 | PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 967 | NewSuccessors.push_back(BBDefault); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 968 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 969 | } |
| 970 | |
| 971 | // Okay, at this point, we know which new successor Pred will get. Make |
| 972 | // sure we update the number of entries in the PHI nodes for these |
| 973 | // successors. |
| 974 | for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) |
| 975 | AddPredecessorToBlock(NewSuccessors[i], Pred, BB); |
| 976 | |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 977 | Builder.SetInsertPoint(PTI); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 978 | // Convert pointer to int before we switch. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 979 | if (CV->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 980 | CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 981 | "magicptr"); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 982 | } |
| 983 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 984 | // Now that the successors are updated, create the new Switch instruction. |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 985 | SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, |
| 986 | PredCases.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 987 | NewSI->setDebugLoc(PTI->getDebugLoc()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 988 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 989 | NewSI->addCase(PredCases[i].Value, PredCases[i].Dest); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 990 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 991 | if (PredHasWeights || SuccHasWeights) { |
| 992 | // Halve the weights if any of them cannot fit in an uint32_t |
| 993 | FitWeights(Weights); |
| 994 | |
| 995 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 996 | |
| 997 | NewSI->setMetadata(LLVMContext::MD_prof, |
| 998 | MDBuilder(BB->getContext()). |
| 999 | createBranchWeights(MDWeights)); |
| 1000 | } |
| 1001 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1002 | EraseTerminatorInstAndDCECond(PTI); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1003 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1004 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 1005 | // have an infinite loop case. If so, add an infinitely looping block |
| 1006 | // to handle the case to preserve the behavior of the code. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1007 | BasicBlock *InfLoopBlock = nullptr; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1008 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 1009 | if (NewSI->getSuccessor(i) == BB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1010 | if (!InfLoopBlock) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 1011 | // 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] | 1012 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1013 | InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 1014 | "infloop", BB->getParent()); |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1015 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1016 | } |
| 1017 | NewSI->setSuccessor(i, InfLoopBlock); |
| 1018 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1019 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1020 | Changed = true; |
| 1021 | } |
| 1022 | } |
| 1023 | return Changed; |
| 1024 | } |
| 1025 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1026 | // If we would need to insert a select that uses the value of this invoke |
| 1027 | // (comments in HoistThenElseCodeToIf explain why we would need to do this), we |
| 1028 | // 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] | 1029 | static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, |
| 1030 | Instruction *I1, Instruction *I2) { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1031 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1032 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1033 | for (BasicBlock::iterator BBI = SI->begin(); |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1034 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1035 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1036 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1037 | if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) { |
| 1038 | return false; |
| 1039 | } |
| 1040 | } |
| 1041 | } |
| 1042 | return true; |
| 1043 | } |
| 1044 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1045 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); |
| 1046 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1047 | /// Given a conditional branch that goes to BB1 and BB2, hoist any common code |
| 1048 | /// in the two blocks up into the branch block. The caller of this function |
| 1049 | /// guarantees that BI's block dominates BB1 and BB2. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1050 | static bool HoistThenElseCodeToIf(BranchInst *BI, |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1051 | const TargetTransformInfo &TTI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1052 | // This does very trivial matching, with limited scanning, to find identical |
| 1053 | // instructions in the two blocks. In particular, we don't want to get into |
| 1054 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 1055 | // such, we currently just scan for obviously identical instructions in an |
| 1056 | // identical order. |
| 1057 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 1058 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| 1059 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1060 | BasicBlock::iterator BB1_Itr = BB1->begin(); |
| 1061 | BasicBlock::iterator BB2_Itr = BB2->begin(); |
| 1062 | |
| 1063 | Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1064 | // Skip debug info if it is not identical. |
| 1065 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1066 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1067 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1068 | while (isa<DbgInfoIntrinsic>(I1)) |
| 1069 | I1 = BB1_Itr++; |
| 1070 | while (isa<DbgInfoIntrinsic>(I2)) |
| 1071 | I2 = BB2_Itr++; |
| 1072 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1073 | if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1074 | (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1075 | return false; |
| 1076 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1077 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1078 | |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1079 | bool Changed = false; |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1080 | do { |
| 1081 | // If we are hoisting the terminator instruction, don't move one (making a |
| 1082 | // broken BB), instead clone it, and remove BI. |
| 1083 | if (isa<TerminatorInst>(I1)) |
| 1084 | goto HoistTerminator; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1085 | |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1086 | if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) |
| 1087 | return Changed; |
| 1088 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1089 | // For a normal instruction, we just move one to right before the branch, |
| 1090 | // then replace all uses of the other with the first. Finally, we remove |
| 1091 | // the now redundant second instruction. |
| 1092 | BIParent->getInstList().splice(BI, BB1->getInstList(), I1); |
| 1093 | if (!I2->use_empty()) |
| 1094 | I2->replaceAllUsesWith(I1); |
Dan Gohman | c8a27f2 | 2009-08-25 22:11:20 +0000 | [diff] [blame] | 1095 | I1->intersectOptionalDataWith(I2); |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1096 | unsigned KnownIDs[] = { |
| 1097 | LLVMContext::MD_tbaa, |
| 1098 | LLVMContext::MD_range, |
| 1099 | LLVMContext::MD_fpmath, |
Philip Reames | d92c2a7 | 2014-10-22 16:37:13 +0000 | [diff] [blame] | 1100 | LLVMContext::MD_invariant_load, |
| 1101 | LLVMContext::MD_nonnull |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1102 | }; |
| 1103 | combineMetadata(I1, I2, KnownIDs); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1104 | I2->eraseFromParent(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1105 | Changed = true; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1106 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1107 | I1 = BB1_Itr++; |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1108 | I2 = BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1109 | // Skip debug info if it is not identical. |
| 1110 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1111 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1112 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1113 | while (isa<DbgInfoIntrinsic>(I1)) |
| 1114 | I1 = BB1_Itr++; |
| 1115 | while (isa<DbgInfoIntrinsic>(I2)) |
| 1116 | I2 = BB2_Itr++; |
| 1117 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1118 | } while (I1->isIdenticalToWhenDefined(I2)); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1119 | |
| 1120 | return true; |
| 1121 | |
| 1122 | HoistTerminator: |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1123 | // It may not be possible to hoist an invoke. |
| 1124 | if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1125 | return Changed; |
| 1126 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1127 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1128 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1129 | for (BasicBlock::iterator BBI = SI->begin(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1130 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1131 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1132 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1133 | if (BB1V == BB2V) |
| 1134 | continue; |
| 1135 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1136 | // Check for passingValueIsAlwaysUndefined here because we would rather |
| 1137 | // eliminate undefined control flow then converting it to a select. |
| 1138 | if (passingValueIsAlwaysUndefined(BB1V, PN) || |
| 1139 | passingValueIsAlwaysUndefined(BB2V, PN)) |
| 1140 | return Changed; |
| 1141 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1142 | if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1143 | return Changed; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1144 | if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1145 | return Changed; |
| 1146 | } |
| 1147 | } |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1148 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1149 | // Okay, it is safe to hoist the terminator. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 1150 | Instruction *NT = I1->clone(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1151 | BIParent->getInstList().insert(BI, NT); |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1152 | if (!NT->getType()->isVoidTy()) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1153 | I1->replaceAllUsesWith(NT); |
| 1154 | I2->replaceAllUsesWith(NT); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1155 | NT->takeName(I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1156 | } |
| 1157 | |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1158 | IRBuilder<true, NoFolder> Builder(NT); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1159 | // Hoisting one of the terminators from our successor is a great thing. |
| 1160 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 1161 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 1162 | // nodes, so we insert select instruction to compute the final result. |
| 1163 | std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1164 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1165 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1166 | for (BasicBlock::iterator BBI = SI->begin(); |
Chris Lattner | 0194457 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 1167 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1168 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1169 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1170 | if (BB1V == BB2V) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1171 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1172 | // These values do not agree. Insert a select instruction before NT |
| 1173 | // that determines the right value. |
| 1174 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1175 | if (!SI) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1176 | SI = cast<SelectInst> |
| 1177 | (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, |
| 1178 | BB1V->getName()+"."+BB2V->getName())); |
| 1179 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1180 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 1181 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 1182 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 1183 | PN->setIncomingValue(i, SI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1184 | } |
| 1185 | } |
| 1186 | |
| 1187 | // Update any PHI nodes in our new successors. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1188 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) |
| 1189 | AddPredecessorToBlock(*SI, BIParent, BB1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1190 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1191 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1192 | return true; |
| 1193 | } |
| 1194 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1195 | /// Given an unconditional branch that goes to BBEnd, |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1196 | /// check whether BBEnd has only two predecessors and the other predecessor |
| 1197 | /// ends with an unconditional branch. If it is true, sink any common code |
| 1198 | /// in the two predecessors to BBEnd. |
| 1199 | static bool SinkThenElseCodeToEnd(BranchInst *BI1) { |
| 1200 | assert(BI1->isUnconditional()); |
| 1201 | BasicBlock *BB1 = BI1->getParent(); |
| 1202 | BasicBlock *BBEnd = BI1->getSuccessor(0); |
| 1203 | |
| 1204 | // Check that BBEnd has two predecessors and the other predecessor ends with |
| 1205 | // an unconditional branch. |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1206 | pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd); |
| 1207 | BasicBlock *Pred0 = *PI++; |
| 1208 | if (PI == PE) // Only one predecessor. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1209 | return false; |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1210 | BasicBlock *Pred1 = *PI++; |
| 1211 | if (PI != PE) // More than two predecessors. |
| 1212 | return false; |
| 1213 | BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1214 | BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator()); |
| 1215 | if (!BI2 || !BI2->isUnconditional()) |
| 1216 | return false; |
| 1217 | |
| 1218 | // Gather the PHI nodes in BBEnd. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1219 | SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1220 | Instruction *FirstNonPhiInBBEnd = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1221 | for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) { |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1222 | if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 1223 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1224 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1225 | JointValueMap[std::make_pair(BB1V, BB2V)] = PN; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1226 | } else { |
| 1227 | FirstNonPhiInBBEnd = &*I; |
| 1228 | break; |
| 1229 | } |
| 1230 | } |
| 1231 | if (!FirstNonPhiInBBEnd) |
| 1232 | return false; |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1233 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1234 | // This does very trivial matching, with limited scanning, to find identical |
| 1235 | // instructions in the two blocks. We scan backward for obviously identical |
| 1236 | // instructions in an identical order. |
| 1237 | BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(), |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1238 | RE1 = BB1->getInstList().rend(), |
| 1239 | RI2 = BB2->getInstList().rbegin(), |
| 1240 | RE2 = BB2->getInstList().rend(); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1241 | // Skip debug info. |
| 1242 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1243 | if (RI1 == RE1) |
| 1244 | return false; |
| 1245 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1246 | if (RI2 == RE2) |
| 1247 | return false; |
| 1248 | // Skip the unconditional branches. |
| 1249 | ++RI1; |
| 1250 | ++RI2; |
| 1251 | |
| 1252 | bool Changed = false; |
| 1253 | while (RI1 != RE1 && RI2 != RE2) { |
| 1254 | // Skip debug info. |
| 1255 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1256 | if (RI1 == RE1) |
| 1257 | return Changed; |
| 1258 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1259 | if (RI2 == RE2) |
| 1260 | return Changed; |
| 1261 | |
| 1262 | Instruction *I1 = &*RI1, *I2 = &*RI2; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1263 | auto InstPair = std::make_pair(I1, I2); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1264 | // I1 and I2 should have a single use in the same PHI node, and they |
| 1265 | // perform the same operation. |
| 1266 | // Cannot move control-flow-involving, volatile loads, vaarg, etc. |
| 1267 | if (isa<PHINode>(I1) || isa<PHINode>(I2) || |
| 1268 | isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) || |
David Majnemer | ba275f9 | 2015-08-19 19:54:02 +0000 | [diff] [blame] | 1269 | I1->isEHPad() || I2->isEHPad() || |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1270 | isa<AllocaInst>(I1) || isa<AllocaInst>(I2) || |
| 1271 | I1->mayHaveSideEffects() || I2->mayHaveSideEffects() || |
| 1272 | I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() || |
| 1273 | !I1->hasOneUse() || !I2->hasOneUse() || |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1274 | !JointValueMap.count(InstPair)) |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1275 | return Changed; |
| 1276 | |
| 1277 | // Check whether we should swap the operands of ICmpInst. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1278 | // TODO: Add support of communativity. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1279 | ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2); |
| 1280 | bool SwapOpnds = false; |
| 1281 | if (ICmp1 && ICmp2 && |
| 1282 | ICmp1->getOperand(0) != ICmp2->getOperand(0) && |
| 1283 | ICmp1->getOperand(1) != ICmp2->getOperand(1) && |
| 1284 | (ICmp1->getOperand(0) == ICmp2->getOperand(1) || |
| 1285 | ICmp1->getOperand(1) == ICmp2->getOperand(0))) { |
| 1286 | ICmp2->swapOperands(); |
| 1287 | SwapOpnds = true; |
| 1288 | } |
| 1289 | if (!I1->isSameOperationAs(I2)) { |
| 1290 | if (SwapOpnds) |
| 1291 | ICmp2->swapOperands(); |
| 1292 | return Changed; |
| 1293 | } |
| 1294 | |
| 1295 | // The operands should be either the same or they need to be generated |
| 1296 | // with a PHI node after sinking. We only handle the case where there is |
| 1297 | // a single pair of different operands. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1298 | Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1299 | unsigned Op1Idx = ~0U; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1300 | for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) { |
| 1301 | if (I1->getOperand(I) == I2->getOperand(I)) |
| 1302 | continue; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1303 | // Early exit if we have more-than one pair of different operands or if |
| 1304 | // we need a PHI node to replace a constant. |
| 1305 | if (Op1Idx != ~0U || |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1306 | isa<Constant>(I1->getOperand(I)) || |
| 1307 | isa<Constant>(I2->getOperand(I))) { |
| 1308 | // If we can't sink the instructions, undo the swapping. |
| 1309 | if (SwapOpnds) |
| 1310 | ICmp2->swapOperands(); |
| 1311 | return Changed; |
| 1312 | } |
| 1313 | DifferentOp1 = I1->getOperand(I); |
| 1314 | Op1Idx = I; |
| 1315 | DifferentOp2 = I2->getOperand(I); |
| 1316 | } |
| 1317 | |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1318 | DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n"); |
| 1319 | DEBUG(dbgs() << " " << *I2 << "\n"); |
| 1320 | |
| 1321 | // We insert the pair of different operands to JointValueMap and |
| 1322 | // remove (I1, I2) from JointValueMap. |
| 1323 | if (Op1Idx != ~0U) { |
| 1324 | auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)]; |
| 1325 | if (!NewPN) { |
| 1326 | NewPN = |
| 1327 | PHINode::Create(DifferentOp1->getType(), 2, |
| 1328 | DifferentOp1->getName() + ".sink", BBEnd->begin()); |
| 1329 | NewPN->addIncoming(DifferentOp1, BB1); |
| 1330 | NewPN->addIncoming(DifferentOp2, BB2); |
| 1331 | DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";); |
| 1332 | } |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1333 | // I1 should use NewPN instead of DifferentOp1. |
| 1334 | I1->setOperand(Op1Idx, NewPN); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1335 | } |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1336 | PHINode *OldPN = JointValueMap[InstPair]; |
| 1337 | JointValueMap.erase(InstPair); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1338 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1339 | // We need to update RE1 and RE2 if we are going to sink the first |
| 1340 | // instruction in the basic block down. |
| 1341 | bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin()); |
| 1342 | // Sink the instruction. |
| 1343 | BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1); |
| 1344 | if (!OldPN->use_empty()) |
| 1345 | OldPN->replaceAllUsesWith(I1); |
| 1346 | OldPN->eraseFromParent(); |
| 1347 | |
| 1348 | if (!I2->use_empty()) |
| 1349 | I2->replaceAllUsesWith(I1); |
| 1350 | I1->intersectOptionalDataWith(I2); |
Philip Reames | d92c2a7 | 2014-10-22 16:37:13 +0000 | [diff] [blame] | 1351 | // TODO: Use combineMetadata here to preserve what metadata we can |
| 1352 | // (analogous to the hoisting case above). |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1353 | I2->eraseFromParent(); |
| 1354 | |
| 1355 | if (UpdateRE1) |
| 1356 | RE1 = BB1->getInstList().rend(); |
| 1357 | if (UpdateRE2) |
| 1358 | RE2 = BB2->getInstList().rend(); |
| 1359 | FirstNonPhiInBBEnd = I1; |
| 1360 | NumSinkCommons++; |
| 1361 | Changed = true; |
| 1362 | } |
| 1363 | return Changed; |
| 1364 | } |
| 1365 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1366 | /// \brief Determine if we can hoist sink a sole store instruction out of a |
| 1367 | /// conditional block. |
| 1368 | /// |
| 1369 | /// We are looking for code like the following: |
| 1370 | /// BrBB: |
| 1371 | /// store i32 %add, i32* %arrayidx2 |
| 1372 | /// ... // No other stores or function calls (we could be calling a memory |
| 1373 | /// ... // function). |
| 1374 | /// %cmp = icmp ult %x, %y |
| 1375 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1376 | /// ThenBB: |
| 1377 | /// store i32 %add5, i32* %arrayidx2 |
| 1378 | /// br label EndBB |
| 1379 | /// EndBB: |
| 1380 | /// ... |
| 1381 | /// We are going to transform this into: |
| 1382 | /// BrBB: |
| 1383 | /// store i32 %add, i32* %arrayidx2 |
| 1384 | /// ... // |
| 1385 | /// %cmp = icmp ult %x, %y |
| 1386 | /// %add.add5 = select i1 %cmp, i32 %add, %add5 |
| 1387 | /// store i32 %add.add5, i32* %arrayidx2 |
| 1388 | /// ... |
| 1389 | /// |
| 1390 | /// \return The pointer to the value of the previous store if the store can be |
| 1391 | /// hoisted into the predecessor block. 0 otherwise. |
Benjamin Kramer | ad5c24f | 2013-05-23 16:09:15 +0000 | [diff] [blame] | 1392 | static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, |
| 1393 | BasicBlock *StoreBB, BasicBlock *EndBB) { |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1394 | StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); |
| 1395 | if (!StoreToHoist) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1396 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1397 | |
| 1398 | // Volatile or atomic. |
| 1399 | if (!StoreToHoist->isSimple()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1400 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1401 | |
| 1402 | Value *StorePtr = StoreToHoist->getPointerOperand(); |
| 1403 | |
| 1404 | // Look for a store to the same pointer in BrBB. |
| 1405 | unsigned MaxNumInstToLookAt = 10; |
| 1406 | for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), |
| 1407 | RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) { |
| 1408 | Instruction *CurI = &*RI; |
| 1409 | |
| 1410 | // Could be calling an instruction that effects memory like free(). |
| 1411 | if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1412 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1413 | |
| 1414 | StoreInst *SI = dyn_cast<StoreInst>(CurI); |
| 1415 | // Found the previous store make sure it stores to the same location. |
| 1416 | if (SI && SI->getPointerOperand() == StorePtr) |
| 1417 | // Found the previous store, return its value operand. |
| 1418 | return SI->getValueOperand(); |
| 1419 | else if (SI) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1420 | return nullptr; // Unknown store. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1421 | } |
| 1422 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1423 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1424 | } |
| 1425 | |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1426 | /// \brief Speculate a conditional basic block flattening the CFG. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1427 | /// |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1428 | /// Note that this is a very risky transform currently. Speculating |
| 1429 | /// instructions like this is most often not desirable. Instead, there is an MI |
| 1430 | /// pass which can do it with full awareness of the resource constraints. |
| 1431 | /// However, some cases are "obvious" and we should do directly. An example of |
| 1432 | /// this is speculating a single, reasonably cheap instruction. |
| 1433 | /// |
| 1434 | /// There is only one distinct advantage to flattening the CFG at the IR level: |
| 1435 | /// it makes very common but simplistic optimizations such as are common in |
| 1436 | /// instcombine and the DAG combiner more powerful by removing CFG edges and |
| 1437 | /// modeling their effects with easier to reason about SSA value graphs. |
| 1438 | /// |
| 1439 | /// |
| 1440 | /// An illustration of this transform is turning this IR: |
| 1441 | /// \code |
| 1442 | /// BB: |
| 1443 | /// %cmp = icmp ult %x, %y |
| 1444 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1445 | /// ThenBB: |
| 1446 | /// %sub = sub %x, %y |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1447 | /// br label BB2 |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1448 | /// EndBB: |
| 1449 | /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] |
| 1450 | /// ... |
| 1451 | /// \endcode |
| 1452 | /// |
| 1453 | /// Into this IR: |
| 1454 | /// \code |
| 1455 | /// BB: |
| 1456 | /// %cmp = icmp ult %x, %y |
| 1457 | /// %sub = sub %x, %y |
| 1458 | /// %cond = select i1 %cmp, 0, %sub |
| 1459 | /// ... |
| 1460 | /// \endcode |
| 1461 | /// |
| 1462 | /// \returns true if the conditional block is removed. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1463 | static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1464 | const TargetTransformInfo &TTI) { |
Chandler Carruth | 1d20c02 | 2013-01-24 08:22:40 +0000 | [diff] [blame] | 1465 | // Be conservative for now. FP select instruction can often be expensive. |
| 1466 | Value *BrCond = BI->getCondition(); |
| 1467 | if (isa<FCmpInst>(BrCond)) |
| 1468 | return false; |
| 1469 | |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1470 | BasicBlock *BB = BI->getParent(); |
| 1471 | BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); |
| 1472 | |
| 1473 | // If ThenBB is actually on the false edge of the conditional branch, remember |
| 1474 | // to swap the select operands later. |
| 1475 | bool Invert = false; |
| 1476 | if (ThenBB != BI->getSuccessor(0)) { |
| 1477 | assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); |
| 1478 | Invert = true; |
| 1479 | } |
| 1480 | assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); |
| 1481 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1482 | // Keep a count of how many times instructions are used within CondBB when |
| 1483 | // they are candidates for sinking into CondBB. Specifically: |
| 1484 | // - They are defined in BB, and |
| 1485 | // - They have no side effects, and |
| 1486 | // - All of their uses are in CondBB. |
| 1487 | SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; |
| 1488 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1489 | unsigned SpeculationCost = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1490 | Value *SpeculatedStoreValue = nullptr; |
| 1491 | StoreInst *SpeculatedStore = nullptr; |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1492 | for (BasicBlock::iterator BBI = ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1493 | BBE = std::prev(ThenBB->end()); |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1494 | BBI != BBE; ++BBI) { |
| 1495 | Instruction *I = BBI; |
| 1496 | // Skip debug info. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1497 | if (isa<DbgInfoIntrinsic>(I)) |
| 1498 | continue; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1499 | |
Mark Lacey | 274f48b | 2015-04-12 18:18:51 +0000 | [diff] [blame] | 1500 | // Only speculatively execute a single instruction (not counting the |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1501 | // terminator) for now. |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1502 | ++SpeculationCost; |
| 1503 | if (SpeculationCost > 1) |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1504 | return false; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1505 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1506 | // Don't hoist the instruction if it's unsafe or expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1507 | if (!isSafeToSpeculativelyExecute(I) && |
| 1508 | !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( |
| 1509 | I, BB, ThenBB, EndBB)))) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1510 | return false; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1511 | if (!SpeculatedStoreValue && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1512 | ComputeSpeculationCost(I, TTI) > |
| 1513 | PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1514 | return false; |
| 1515 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1516 | // Store the store speculation candidate. |
| 1517 | if (SpeculatedStoreValue) |
| 1518 | SpeculatedStore = cast<StoreInst>(I); |
| 1519 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1520 | // 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] | 1521 | // used in BB. The transformation will prevent the operand from |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1522 | // being sunk into the use block. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1523 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1524 | i != e; ++i) { |
| 1525 | Instruction *OpI = dyn_cast<Instruction>(*i); |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1526 | if (!OpI || OpI->getParent() != BB || |
| 1527 | OpI->mayHaveSideEffects()) |
| 1528 | continue; // Not a candidate for sinking. |
| 1529 | |
| 1530 | ++SinkCandidateUseCounts[OpI]; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1531 | } |
| 1532 | } |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1533 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1534 | // Consider any sink candidates which are only used in CondBB as costs for |
| 1535 | // speculation. Note, while we iterate over a DenseMap here, we are summing |
| 1536 | // and so iteration order isn't significant. |
| 1537 | for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I = |
| 1538 | SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end(); |
| 1539 | I != E; ++I) |
| 1540 | if (I->first->getNumUses() == I->second) { |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1541 | ++SpeculationCost; |
| 1542 | if (SpeculationCost > 1) |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1543 | return false; |
| 1544 | } |
| 1545 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1546 | // Check that the PHI nodes can be converted to selects. |
| 1547 | bool HaveRewritablePHIs = false; |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1548 | for (BasicBlock::iterator I = EndBB->begin(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1549 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1550 | Value *OrigV = PN->getIncomingValueForBlock(BB); |
| 1551 | Value *ThenV = PN->getIncomingValueForBlock(ThenBB); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1552 | |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1553 | // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1554 | // Skip PHIs which are trivial. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1555 | if (ThenV == OrigV) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1556 | continue; |
| 1557 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1558 | // Don't convert to selects if we could remove undefined behavior instead. |
| 1559 | if (passingValueIsAlwaysUndefined(OrigV, PN) || |
| 1560 | passingValueIsAlwaysUndefined(ThenV, PN)) |
| 1561 | return false; |
| 1562 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1563 | HaveRewritablePHIs = true; |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1564 | ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); |
| 1565 | ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); |
| 1566 | if (!OrigCE && !ThenCE) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1567 | continue; // Known safe and cheap. |
| 1568 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1569 | if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || |
| 1570 | (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1571 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1572 | unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; |
| 1573 | unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1574 | unsigned MaxCost = 2 * PHINodeFoldingThreshold * |
| 1575 | TargetTransformInfo::TCC_Basic; |
| 1576 | if (OrigCost + ThenCost > MaxCost) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1577 | return false; |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1578 | |
Chandler Carruth | 01bffaa | 2013-01-24 12:05:17 +0000 | [diff] [blame] | 1579 | // Account for the cost of an unfolded ConstantExpr which could end up |
| 1580 | // getting expanded into Instructions. |
| 1581 | // 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] | 1582 | // constant expression. |
| 1583 | ++SpeculationCost; |
| 1584 | if (SpeculationCost > 1) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1585 | return false; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1586 | } |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1587 | |
| 1588 | // If there are no PHIs to process, bail early. This helps ensure idempotence |
| 1589 | // as well. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1590 | if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1591 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1592 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1593 | // If we get here, we can hoist the instruction and if-convert. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1594 | DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1595 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1596 | // Insert a select of the value of the speculated store. |
| 1597 | if (SpeculatedStoreValue) { |
| 1598 | IRBuilder<true, NoFolder> Builder(BI); |
| 1599 | Value *TrueV = SpeculatedStore->getValueOperand(); |
| 1600 | Value *FalseV = SpeculatedStoreValue; |
| 1601 | if (Invert) |
| 1602 | std::swap(TrueV, FalseV); |
| 1603 | Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() + |
| 1604 | "." + FalseV->getName()); |
| 1605 | SpeculatedStore->setOperand(0, S); |
| 1606 | } |
| 1607 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1608 | // Hoist the instructions. |
| 1609 | BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1610 | std::prev(ThenBB->end())); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1611 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1612 | // Insert selects and rewrite the PHI operands. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1613 | IRBuilder<true, NoFolder> Builder(BI); |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1614 | for (BasicBlock::iterator I = EndBB->begin(); |
| 1615 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
| 1616 | unsigned OrigI = PN->getBasicBlockIndex(BB); |
| 1617 | unsigned ThenI = PN->getBasicBlockIndex(ThenBB); |
| 1618 | Value *OrigV = PN->getIncomingValue(OrigI); |
| 1619 | Value *ThenV = PN->getIncomingValue(ThenI); |
| 1620 | |
| 1621 | // Skip PHIs which are trivial. |
| 1622 | if (OrigV == ThenV) |
| 1623 | continue; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1624 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1625 | // Create a select whose true value is the speculatively executed value and |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1626 | // false value is the preexisting value. Swap them if the branch |
| 1627 | // destinations were inverted. |
| 1628 | Value *TrueV = ThenV, *FalseV = OrigV; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1629 | if (Invert) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1630 | std::swap(TrueV, FalseV); |
| 1631 | Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, |
| 1632 | TrueV->getName() + "." + FalseV->getName()); |
| 1633 | PN->setIncomingValue(OrigI, V); |
| 1634 | PN->setIncomingValue(ThenI, V); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1635 | } |
| 1636 | |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1637 | ++NumSpeculations; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1638 | return true; |
| 1639 | } |
| 1640 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1641 | /// \returns True if this block contains a CallInst with the NoDuplicate |
| 1642 | /// attribute. |
| 1643 | static bool HasNoDuplicateCall(const BasicBlock *BB) { |
| 1644 | for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 1645 | const CallInst *CI = dyn_cast<CallInst>(I); |
| 1646 | if (!CI) |
| 1647 | continue; |
| 1648 | if (CI->cannotDuplicate()) |
| 1649 | return true; |
| 1650 | } |
| 1651 | return false; |
| 1652 | } |
| 1653 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1654 | /// Return true if we can thread a branch across this block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1655 | static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| 1656 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1657 | unsigned Size = 0; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1658 | |
Devang Patel | 84fceff | 2009-03-10 18:00:05 +0000 | [diff] [blame] | 1659 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1660 | if (isa<DbgInfoIntrinsic>(BBI)) |
| 1661 | continue; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1662 | if (Size > 10) return false; // Don't clone large BB's. |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1663 | ++Size; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1664 | |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1665 | // We can only support instructions that do not define values that are |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1666 | // live outside of the current basic block. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1667 | for (User *U : BBI->users()) { |
| 1668 | Instruction *UI = cast<Instruction>(U); |
| 1669 | if (UI->getParent() != BB || isa<PHINode>(UI)) return false; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1670 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1671 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1672 | // Looks ok, continue checking. |
| 1673 | } |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1674 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1675 | return true; |
| 1676 | } |
| 1677 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1678 | /// If we have a conditional branch on a PHI node value that is defined in the |
| 1679 | /// same block as the branch and if any PHI entries are constants, thread edges |
| 1680 | /// corresponding to that entry to be branches to their ultimate destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1681 | static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) { |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1682 | BasicBlock *BB = BI->getParent(); |
| 1683 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
Chris Lattner | 049cb44 | 2005-09-19 23:57:04 +0000 | [diff] [blame] | 1684 | // NOTE: we currently cannot transform this case if the PHI node is used |
| 1685 | // outside of the block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1686 | if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| 1687 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1688 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1689 | // Degenerate case of a single entry PHI. |
| 1690 | if (PN->getNumIncomingValues() == 1) { |
Chris Lattner | dc3f6f2 | 2008-12-03 19:44:02 +0000 | [diff] [blame] | 1691 | FoldSingleEntryPHINodes(PN->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1692 | return true; |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1693 | } |
| 1694 | |
| 1695 | // Now we know that this block has multiple preds and two succs. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1696 | if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1697 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1698 | if (HasNoDuplicateCall(BB)) return false; |
| 1699 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1700 | // Okay, this is a simple enough basic block. See if any phi values are |
| 1701 | // constants. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1702 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1703 | ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1704 | if (!CB || !CB->getType()->isIntegerTy(1)) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1705 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1706 | // Okay, we now know that all edges from PredBB should be revectored to |
| 1707 | // branch to RealDest. |
| 1708 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 1709 | BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1710 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1711 | if (RealDest == BB) continue; // Skip self loops. |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1712 | // Skip if the predecessor's terminator is an indirect branch. |
| 1713 | if (isa<IndirectBrInst>(PredBB->getTerminator())) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1714 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1715 | // The dest block might have PHI nodes, other predecessors and other |
| 1716 | // difficult cases. Instead of being smart about this, just insert a new |
| 1717 | // block that jumps to the destination block, effectively splitting |
| 1718 | // the edge we are about to create. |
| 1719 | BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(), |
| 1720 | RealDest->getName()+".critedge", |
| 1721 | RealDest->getParent(), RealDest); |
| 1722 | BranchInst::Create(RealDest, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1723 | |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 1724 | // Update PHI nodes. |
| 1725 | AddPredecessorToBlock(RealDest, EdgeBB, BB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1726 | |
| 1727 | // BB may have instructions that are being threaded over. Clone these |
| 1728 | // instructions into EdgeBB. We know that there will be no uses of the |
| 1729 | // cloned instructions outside of EdgeBB. |
| 1730 | BasicBlock::iterator InsertPt = EdgeBB->begin(); |
| 1731 | DenseMap<Value*, Value*> TranslateMap; // Track translated values. |
| 1732 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| 1733 | if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| 1734 | TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| 1735 | continue; |
| 1736 | } |
| 1737 | // Clone the instruction. |
| 1738 | Instruction *N = BBI->clone(); |
| 1739 | if (BBI->hasName()) N->setName(BBI->getName()+".c"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1740 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1741 | // Update operands due to translation. |
| 1742 | for (User::op_iterator i = N->op_begin(), e = N->op_end(); |
| 1743 | i != e; ++i) { |
| 1744 | DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i); |
| 1745 | if (PI != TranslateMap.end()) |
| 1746 | *i = PI->second; |
| 1747 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1748 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1749 | // Check for trivial simplification. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1750 | if (Value *V = SimplifyInstruction(N, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1751 | TranslateMap[BBI] = V; |
| 1752 | delete N; // Instruction folded away, don't need actual inst |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1753 | } else { |
| 1754 | // Insert the new instruction into its new home. |
| 1755 | EdgeBB->getInstList().insert(InsertPt, N); |
| 1756 | if (!BBI->use_empty()) |
| 1757 | TranslateMap[BBI] = N; |
| 1758 | } |
| 1759 | } |
| 1760 | |
| 1761 | // Loop over all of the edges from PredBB to BB, changing them to branch |
| 1762 | // to EdgeBB instead. |
| 1763 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 1764 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 1765 | if (PredBBTI->getSuccessor(i) == BB) { |
| 1766 | BB->removePredecessor(PredBB); |
| 1767 | PredBBTI->setSuccessor(i, EdgeBB); |
| 1768 | } |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1769 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1770 | // Recurse, simplifying any other constants. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1771 | return FoldCondBranchOnPHI(BI, DL) | true; |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1772 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1773 | |
| 1774 | return false; |
| 1775 | } |
| 1776 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1777 | /// Given a BB that starts with the specified two-entry PHI node, |
| 1778 | /// see if we can eliminate it. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1779 | static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, |
| 1780 | const DataLayout &DL) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1781 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 1782 | // statement", which has a very simple dominance structure. Basically, we |
| 1783 | // are trying to find the condition that is being branched on, which |
| 1784 | // subsequently causes this merge to happen. We really want control |
| 1785 | // dependence information for this check, but simplifycfg can't keep it up |
| 1786 | // 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] | 1787 | BasicBlock *BB = PN->getParent(); |
| 1788 | BasicBlock *IfTrue, *IfFalse; |
| 1789 | Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1790 | if (!IfCond || |
| 1791 | // Don't bother if the branch will be constant folded trivially. |
| 1792 | isa<ConstantInt>(IfCond)) |
| 1793 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1794 | |
Chris Lattner | 95adf8f1 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 1795 | // Okay, we found that we can merge this two-entry phi node into a select. |
| 1796 | // Doing so would require us to fold *all* two entry phi nodes in this block. |
| 1797 | // At some point this becomes non-profitable (particularly if the target |
| 1798 | // doesn't support cmov's). Only do this transformation if there are two or |
| 1799 | // fewer PHI nodes in this block. |
| 1800 | unsigned NumPhis = 0; |
| 1801 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| 1802 | if (NumPhis > 2) |
| 1803 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1804 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1805 | // Loop over the PHI's seeing if we can promote them all to select |
| 1806 | // instructions. While we are at it, keep track of the instructions |
| 1807 | // that need to be moved to the dominating block. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1808 | SmallPtrSet<Instruction*, 4> AggressiveInsts; |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 1809 | unsigned MaxCostVal0 = PHINodeFoldingThreshold, |
| 1810 | MaxCostVal1 = PHINodeFoldingThreshold; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1811 | MaxCostVal0 *= TargetTransformInfo::TCC_Basic; |
| 1812 | MaxCostVal1 *= TargetTransformInfo::TCC_Basic; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1813 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1814 | for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { |
| 1815 | PHINode *PN = cast<PHINode>(II++); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1816 | if (Value *V = SimplifyInstruction(PN, DL)) { |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1817 | PN->replaceAllUsesWith(V); |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1818 | PN->eraseFromParent(); |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1819 | continue; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1820 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1821 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1822 | if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1823 | MaxCostVal0, TTI) || |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1824 | !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1825 | MaxCostVal1, TTI)) |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1826 | return false; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1827 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1828 | |
Sylvestre Ledru | 35521e2 | 2012-07-23 08:51:15 +0000 | [diff] [blame] | 1829 | // 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] | 1830 | // we ran out of PHIs then we simplified them all. |
| 1831 | PN = dyn_cast<PHINode>(BB->begin()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1832 | if (!PN) return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1833 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1834 | // Don't fold i1 branches on PHIs which contain binary operators. These can |
| 1835 | // often be turned into switches and other things. |
| 1836 | if (PN->getType()->isIntegerTy(1) && |
| 1837 | (isa<BinaryOperator>(PN->getIncomingValue(0)) || |
| 1838 | isa<BinaryOperator>(PN->getIncomingValue(1)) || |
| 1839 | isa<BinaryOperator>(IfCond))) |
| 1840 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1841 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1842 | // If we all PHI nodes are promotable, check to make sure that all |
| 1843 | // instructions in the predecessor blocks can be promoted as well. If |
| 1844 | // not, we won't be able to get rid of the control flow, so it's not |
| 1845 | // worth promoting to select instructions. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1846 | BasicBlock *DomBlock = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1847 | BasicBlock *IfBlock1 = PN->getIncomingBlock(0); |
| 1848 | BasicBlock *IfBlock2 = PN->getIncomingBlock(1); |
| 1849 | if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1850 | IfBlock1 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1851 | } else { |
| 1852 | DomBlock = *pred_begin(IfBlock1); |
| 1853 | for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I) |
Devang Patel | 2032cad | 2009-02-03 22:12:02 +0000 | [diff] [blame] | 1854 | if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1855 | // This is not an aggressive instruction that we can promote. |
| 1856 | // Because of this, we won't be able to get rid of the control |
| 1857 | // flow, so the xform is not worth it. |
| 1858 | return false; |
| 1859 | } |
| 1860 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1861 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1862 | if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1863 | IfBlock2 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1864 | } else { |
| 1865 | DomBlock = *pred_begin(IfBlock2); |
| 1866 | for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I) |
Devang Patel | 2032cad | 2009-02-03 22:12:02 +0000 | [diff] [blame] | 1867 | if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1868 | // This is not an aggressive instruction that we can promote. |
| 1869 | // Because of this, we won't be able to get rid of the control |
| 1870 | // flow, so the xform is not worth it. |
| 1871 | return false; |
| 1872 | } |
| 1873 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1874 | |
Chris Lattner | 9fd838d | 2010-12-14 07:23:10 +0000 | [diff] [blame] | 1875 | DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1876 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1877 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1878 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 1879 | // do all of the PHI's now. |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1880 | Instruction *InsertPt = DomBlock->getTerminator(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1881 | IRBuilder<true, NoFolder> Builder(InsertPt); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1882 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1883 | // Move all 'aggressive' instructions, which are defined in the |
| 1884 | // conditional parts of the if's up to the dominating block. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1885 | if (IfBlock1) |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1886 | DomBlock->getInstList().splice(InsertPt, |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1887 | IfBlock1->getInstList(), IfBlock1->begin(), |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1888 | IfBlock1->getTerminator()); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1889 | if (IfBlock2) |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1890 | DomBlock->getInstList().splice(InsertPt, |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1891 | IfBlock2->getInstList(), IfBlock2->begin(), |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1892 | IfBlock2->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1893 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1894 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 1895 | // Change the PHI node into a select instruction. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1896 | Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| 1897 | Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1898 | |
| 1899 | SelectInst *NV = |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1900 | cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, "")); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1901 | PN->replaceAllUsesWith(NV); |
| 1902 | NV->takeName(PN); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1903 | PN->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1904 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1905 | |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1906 | // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement |
| 1907 | // has been flattened. Change DomBlock to jump directly to our new block to |
| 1908 | // avoid other simplifycfg's kicking in on the diamond. |
| 1909 | TerminatorInst *OldTI = DomBlock->getTerminator(); |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1910 | Builder.SetInsertPoint(OldTI); |
| 1911 | Builder.CreateBr(BB); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1912 | OldTI->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1913 | return true; |
| 1914 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1915 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1916 | /// If we found a conditional branch that goes to two returning blocks, |
| 1917 | /// try to merge them together into one return, |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1918 | /// introducing a select if the return values disagree. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1919 | static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1920 | IRBuilder<> &Builder) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1921 | assert(BI->isConditional() && "Must be a conditional branch"); |
| 1922 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1923 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1924 | ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| 1925 | ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1926 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1927 | // Check to ensure both blocks are empty (just a return) or optionally empty |
| 1928 | // with PHI nodes. If there are other instructions, merging would cause extra |
| 1929 | // computation on one path or the other. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1930 | if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1931 | return false; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1932 | if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1933 | return false; |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1934 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1935 | Builder.SetInsertPoint(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1936 | // Okay, we found a branch that is going to two return nodes. If |
| 1937 | // there is no return value for this function, just change the |
| 1938 | // branch into a return. |
| 1939 | if (FalseRet->getNumOperands() == 0) { |
| 1940 | TrueSucc->removePredecessor(BI->getParent()); |
| 1941 | FalseSucc->removePredecessor(BI->getParent()); |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1942 | Builder.CreateRetVoid(); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1943 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1944 | return true; |
| 1945 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1946 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1947 | // Otherwise, figure out what the true and false return values are |
| 1948 | // so we can insert a new select instruction. |
| 1949 | Value *TrueValue = TrueRet->getReturnValue(); |
| 1950 | Value *FalseValue = FalseRet->getReturnValue(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1951 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1952 | // Unwrap any PHI nodes in the return blocks. |
| 1953 | if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) |
| 1954 | if (TVPN->getParent() == TrueSucc) |
| 1955 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 1956 | if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) |
| 1957 | if (FVPN->getParent() == FalseSucc) |
| 1958 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1959 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1960 | // In order for this transformation to be safe, we must be able to |
| 1961 | // unconditionally execute both operands to the return. This is |
| 1962 | // normally the case, but we could have a potentially-trapping |
| 1963 | // constant expression that prevents this transformation from being |
| 1964 | // safe. |
| 1965 | if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) |
| 1966 | if (TCV->canTrap()) |
| 1967 | return false; |
| 1968 | if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) |
| 1969 | if (FCV->canTrap()) |
| 1970 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1971 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1972 | // Okay, we collected all the mapped values and checked them for sanity, and |
| 1973 | // defined to really do this transformation. First, update the CFG. |
| 1974 | TrueSucc->removePredecessor(BI->getParent()); |
| 1975 | FalseSucc->removePredecessor(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1976 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1977 | // Insert select instructions where needed. |
| 1978 | Value *BrCond = BI->getCondition(); |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1979 | if (TrueValue) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1980 | // Insert a select if the results differ. |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1981 | if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { |
| 1982 | } else if (isa<UndefValue>(TrueValue)) { |
| 1983 | TrueValue = FalseValue; |
| 1984 | } else { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1985 | TrueValue = Builder.CreateSelect(BrCond, TrueValue, |
| 1986 | FalseValue, "retval"); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1987 | } |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1988 | } |
| 1989 | |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1990 | Value *RI = !TrueValue ? |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1991 | Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); |
| 1992 | |
Daniel Dunbar | 5e0a58b | 2009-08-23 10:29:55 +0000 | [diff] [blame] | 1993 | (void) RI; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1994 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 1995 | DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 1996 | << "\n " << *BI << "NewRet = " << *RI |
| 1997 | << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1998 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1999 | EraseTerminatorInstAndDCECond(BI); |
| 2000 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2001 | return true; |
| 2002 | } |
| 2003 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2004 | /// Given a conditional BranchInstruction, retrieve the probabilities of the |
| 2005 | /// branch taking each edge. Fills in the two APInt parameters and returns true, |
| 2006 | /// or returns false if no or invalid metadata was found. |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2007 | static bool ExtractBranchMetadata(BranchInst *BI, |
| 2008 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 2009 | assert(BI->isConditional() && |
| 2010 | "Looking for probabilities on unconditional branch?"); |
| 2011 | MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 2012 | if (!ProfileData || ProfileData->getNumOperands() != 3) return false; |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 2013 | ConstantInt *CITrue = |
| 2014 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 2015 | ConstantInt *CIFalse = |
| 2016 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2017 | if (!CITrue || !CIFalse) return false; |
| 2018 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 2019 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 2020 | return true; |
| 2021 | } |
| 2022 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2023 | /// Return true if the given instruction is available |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2024 | /// in its predecessor block. If yes, the instruction will be removed. |
Benjamin Kramer | abbfe69 | 2012-07-13 13:25:15 +0000 | [diff] [blame] | 2025 | static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2026 | if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) |
| 2027 | return false; |
| 2028 | for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) { |
| 2029 | Instruction *PBI = &*I; |
| 2030 | // Check whether Inst and PBI generate the same value. |
| 2031 | if (Inst->isIdenticalTo(PBI)) { |
| 2032 | Inst->replaceAllUsesWith(PBI); |
| 2033 | Inst->eraseFromParent(); |
| 2034 | return true; |
| 2035 | } |
| 2036 | } |
| 2037 | return false; |
| 2038 | } |
Nick Lewycky | 3c3feaf | 2012-01-25 09:43:14 +0000 | [diff] [blame] | 2039 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2040 | /// If this basic block is simple enough, and if a predecessor branches to us |
| 2041 | /// and one of our successors, fold the block into the predecessor and use |
| 2042 | /// logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2043 | bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2044 | BasicBlock *BB = BI->getParent(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2045 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2046 | Instruction *Cond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2047 | if (BI->isConditional()) |
| 2048 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 2049 | else { |
| 2050 | // For unconditional branch, check for a simple CFG pattern, where |
| 2051 | // BB has a single predecessor and BB's successor is also its predecessor's |
| 2052 | // successor. If such pattern exisits, check for CSE between BB and its |
| 2053 | // predecessor. |
| 2054 | if (BasicBlock *PB = BB->getSinglePredecessor()) |
| 2055 | if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) |
| 2056 | if (PBI->isConditional() && |
| 2057 | (BI->getSuccessor(0) == PBI->getSuccessor(0) || |
| 2058 | BI->getSuccessor(0) == PBI->getSuccessor(1))) { |
| 2059 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); |
| 2060 | I != E; ) { |
| 2061 | Instruction *Curr = I++; |
| 2062 | if (isa<CmpInst>(Curr)) { |
| 2063 | Cond = Curr; |
| 2064 | break; |
| 2065 | } |
| 2066 | // Quit if we can't remove this instruction. |
| 2067 | if (!checkCSEInPredecessor(Curr, PB)) |
| 2068 | return false; |
| 2069 | } |
| 2070 | } |
| 2071 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2072 | if (!Cond) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2073 | return false; |
| 2074 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2075 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2076 | if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || |
| 2077 | Cond->getParent() != BB || !Cond->hasOneUse()) |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2078 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2079 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2080 | // Make sure the instruction after the condition is the cond branch. |
| 2081 | BasicBlock::iterator CondIt = Cond; ++CondIt; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2082 | |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2083 | // Ignore dbg intrinsics. |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2084 | while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2085 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2086 | if (&*CondIt != BI) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2087 | return false; |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2088 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2089 | // Only allow this transformation if computing the condition doesn't involve |
| 2090 | // too many instructions and these involved instructions can be executed |
| 2091 | // unconditionally. We denote all involved instructions except the condition |
| 2092 | // as "bonus instructions", and only allow this transformation when the |
| 2093 | // number of the bonus instructions does not exceed a certain threshold. |
| 2094 | unsigned NumBonusInsts = 0; |
| 2095 | for (auto I = BB->begin(); Cond != I; ++I) { |
| 2096 | // Ignore dbg intrinsics. |
| 2097 | if (isa<DbgInfoIntrinsic>(I)) |
| 2098 | continue; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2099 | if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I)) |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2100 | return false; |
| 2101 | // I has only one use and can be executed unconditionally. |
| 2102 | Instruction *User = dyn_cast<Instruction>(I->user_back()); |
| 2103 | if (User == nullptr || User->getParent() != BB) |
| 2104 | return false; |
| 2105 | // I is used in the same BB. Since BI uses Cond and doesn't have more slots |
| 2106 | // to use any other instruction, User must be an instruction between next(I) |
| 2107 | // and Cond. |
| 2108 | ++NumBonusInsts; |
| 2109 | // Early exits once we reach the limit. |
| 2110 | if (NumBonusInsts > BonusInstThreshold) |
| 2111 | return false; |
| 2112 | } |
| 2113 | |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2114 | // Cond is known to be a compare or binary operator. Check to make sure that |
| 2115 | // neither operand is a potentially-trapping constant expression. |
| 2116 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) |
| 2117 | if (CE->canTrap()) |
| 2118 | return false; |
| 2119 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) |
| 2120 | if (CE->canTrap()) |
| 2121 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2122 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2123 | // Finally, don't infinitely unroll conditional loops. |
| 2124 | BasicBlock *TrueDest = BI->getSuccessor(0); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2125 | BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2126 | if (TrueDest == BB || FalseDest == BB) |
| 2127 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2128 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2129 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 2130 | BasicBlock *PredBlock = *PI; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2131 | BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2132 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2133 | // Check that we have two conditional branches. If there is a PHI node in |
| 2134 | // the common successor, verify that the same value flows in from both |
| 2135 | // blocks. |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2136 | SmallVector<PHINode*, 4> PHIs; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2137 | if (!PBI || PBI->isUnconditional() || |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2138 | (BI->isConditional() && |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2139 | !SafeToMergeTerminators(BI, PBI)) || |
| 2140 | (!BI->isConditional() && |
| 2141 | !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2142 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2143 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2144 | // Determine if the two branches share a common destination. |
Axel Naumann | 4a12706 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 2145 | Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2146 | bool InvertPredCond = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2147 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2148 | if (BI->isConditional()) { |
| 2149 | if (PBI->getSuccessor(0) == TrueDest) |
| 2150 | Opc = Instruction::Or; |
| 2151 | else if (PBI->getSuccessor(1) == FalseDest) |
| 2152 | Opc = Instruction::And; |
| 2153 | else if (PBI->getSuccessor(0) == FalseDest) |
| 2154 | Opc = Instruction::And, InvertPredCond = true; |
| 2155 | else if (PBI->getSuccessor(1) == TrueDest) |
| 2156 | Opc = Instruction::Or, InvertPredCond = true; |
| 2157 | else |
| 2158 | continue; |
| 2159 | } else { |
| 2160 | if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) |
| 2161 | continue; |
| 2162 | } |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2163 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2164 | DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2165 | IRBuilder<> Builder(PBI); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2166 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2167 | // If we need to invert the condition in the pred block to match, do so now. |
| 2168 | if (InvertPredCond) { |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2169 | Value *NewCond = PBI->getCondition(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2170 | |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2171 | if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { |
| 2172 | CmpInst *CI = cast<CmpInst>(NewCond); |
| 2173 | CI->setPredicate(CI->getInversePredicate()); |
| 2174 | } else { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2175 | NewCond = Builder.CreateNot(NewCond, |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2176 | PBI->getCondition()->getName()+".not"); |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2177 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2178 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2179 | PBI->setCondition(NewCond); |
Nick Lewycky | 8d302df | 2011-12-26 20:54:14 +0000 | [diff] [blame] | 2180 | PBI->swapSuccessors(); |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2181 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2182 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2183 | // If we have bonus instructions, clone them into the predecessor block. |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2184 | // Note that there may be multiple predecessor blocks, so we cannot move |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2185 | // bonus instructions to a predecessor block. |
| 2186 | ValueToValueMapTy VMap; // maps original values to cloned values |
| 2187 | // We already make sure Cond is the last instruction before BI. Therefore, |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2188 | // all instructions before Cond other than DbgInfoIntrinsic are bonus |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2189 | // instructions. |
| 2190 | for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) { |
| 2191 | if (isa<DbgInfoIntrinsic>(BonusInst)) |
| 2192 | continue; |
| 2193 | Instruction *NewBonusInst = BonusInst->clone(); |
| 2194 | RemapInstruction(NewBonusInst, VMap, |
| 2195 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
| 2196 | VMap[BonusInst] = NewBonusInst; |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2197 | |
| 2198 | // If we moved a load, we cannot any longer claim any knowledge about |
| 2199 | // its potential value. The previous information might have been valid |
| 2200 | // only given the branch precondition. |
| 2201 | // For an analogous reason, we must also drop all the metadata whose |
| 2202 | // semantics we don't understand. |
Adrian Prantl | cbdfdb7 | 2015-08-20 22:00:30 +0000 | [diff] [blame] | 2203 | NewBonusInst->dropUnknownNonDebugMetadata(); |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2204 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2205 | PredBlock->getInstList().insert(PBI, NewBonusInst); |
| 2206 | NewBonusInst->takeName(BonusInst); |
| 2207 | BonusInst->setName(BonusInst->getName() + ".old"); |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2208 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2209 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2210 | // Clone Cond into the predecessor basic block, and or/and the |
| 2211 | // two conditions together. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 2212 | Instruction *New = Cond->clone(); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2213 | RemapInstruction(New, VMap, |
| 2214 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2215 | PredBlock->getInstList().insert(PBI, New); |
| 2216 | New->takeName(Cond); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2217 | Cond->setName(New->getName() + ".old"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2218 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2219 | if (BI->isConditional()) { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2220 | Instruction *NewCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2221 | cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(), |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2222 | New, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2223 | PBI->setCondition(NewCond); |
| 2224 | |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2225 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2226 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2227 | PredFalseWeight); |
| 2228 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2229 | SuccFalseWeight); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2230 | SmallVector<uint64_t, 8> NewWeights; |
| 2231 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2232 | if (PBI->getSuccessor(0) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2233 | if (PredHasWeights && SuccHasWeights) { |
| 2234 | // PBI: br i1 %x, BB, FalseDest |
| 2235 | // BI: br i1 %y, TrueDest, FalseDest |
| 2236 | //TrueWeight is TrueWeight for PBI * TrueWeight for BI. |
| 2237 | NewWeights.push_back(PredTrueWeight * SuccTrueWeight); |
| 2238 | //FalseWeight is FalseWeight for PBI * TotalWeight for BI + |
| 2239 | // TrueWeight for PBI * FalseWeight for BI. |
| 2240 | // We assume that total weights of a BranchInst can fit into 32 bits. |
| 2241 | // Therefore, we will not have overflow using 64-bit arithmetic. |
| 2242 | NewWeights.push_back(PredFalseWeight * (SuccFalseWeight + |
| 2243 | SuccTrueWeight) + PredTrueWeight * SuccFalseWeight); |
| 2244 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2245 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
| 2246 | PBI->setSuccessor(0, TrueDest); |
| 2247 | } |
| 2248 | if (PBI->getSuccessor(1) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2249 | if (PredHasWeights && SuccHasWeights) { |
| 2250 | // PBI: br i1 %x, TrueDest, BB |
| 2251 | // BI: br i1 %y, TrueDest, FalseDest |
| 2252 | //TrueWeight is TrueWeight for PBI * TotalWeight for BI + |
| 2253 | // FalseWeight for PBI * TrueWeight for BI. |
| 2254 | NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + |
| 2255 | SuccTrueWeight) + PredFalseWeight * SuccTrueWeight); |
| 2256 | //FalseWeight is FalseWeight for PBI * FalseWeight for BI. |
| 2257 | NewWeights.push_back(PredFalseWeight * SuccFalseWeight); |
| 2258 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2259 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
| 2260 | PBI->setSuccessor(1, FalseDest); |
| 2261 | } |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2262 | if (NewWeights.size() == 2) { |
| 2263 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2264 | FitWeights(NewWeights); |
| 2265 | |
| 2266 | SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end()); |
| 2267 | PBI->setMetadata(LLVMContext::MD_prof, |
| 2268 | MDBuilder(BI->getContext()). |
| 2269 | createBranchWeights(MDWeights)); |
| 2270 | } else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2271 | PBI->setMetadata(LLVMContext::MD_prof, nullptr); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2272 | } else { |
| 2273 | // Update PHI nodes in the common successors. |
| 2274 | for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 2275 | ConstantInt *PBI_C = cast<ConstantInt>( |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2276 | PHIs[i]->getIncomingValueForBlock(PBI->getParent())); |
| 2277 | assert(PBI_C->getType()->isIntegerTy(1)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2278 | Instruction *MergedCond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2279 | if (PBI->getSuccessor(0) == TrueDest) { |
| 2280 | // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) |
| 2281 | // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) |
| 2282 | // is false: !PBI_Cond and BI_Value |
| 2283 | Instruction *NotCond = |
| 2284 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2285 | "not.cond")); |
| 2286 | MergedCond = |
| 2287 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2288 | NotCond, New, |
| 2289 | "and.cond")); |
| 2290 | if (PBI_C->isOne()) |
| 2291 | MergedCond = |
| 2292 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2293 | PBI->getCondition(), MergedCond, |
| 2294 | "or.cond")); |
| 2295 | } else { |
| 2296 | // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) |
| 2297 | // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) |
| 2298 | // is false: PBI_Cond and BI_Value |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2299 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2300 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2301 | PBI->getCondition(), New, |
| 2302 | "and.cond")); |
| 2303 | if (PBI_C->isOne()) { |
| 2304 | Instruction *NotCond = |
| 2305 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2306 | "not.cond")); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2307 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2308 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2309 | NotCond, MergedCond, |
| 2310 | "or.cond")); |
| 2311 | } |
| 2312 | } |
| 2313 | // Update PHI Node. |
| 2314 | PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), |
| 2315 | MergedCond); |
| 2316 | } |
| 2317 | // Change PBI from Conditional to Unconditional. |
| 2318 | BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); |
| 2319 | EraseTerminatorInstAndDCECond(PBI); |
| 2320 | PBI = New_PBI; |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2321 | } |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2322 | |
Nick Lewycky | c554a9b | 2011-12-27 04:31:52 +0000 | [diff] [blame] | 2323 | // TODO: If BB is reachable from all paths through PredBlock, then we |
| 2324 | // could replace PBI's branch probabilities with BI's. |
| 2325 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2326 | // Copy any debug value intrinsics into the end of PredBlock. |
| 2327 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 2328 | if (isa<DbgInfoIntrinsic>(*I)) |
| 2329 | I->clone()->insertBefore(PBI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2330 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2331 | return true; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2332 | } |
| 2333 | return false; |
| 2334 | } |
| 2335 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2336 | /// If we have a conditional branch as a predecessor of another block, |
| 2337 | /// this function tries to simplify it. We know |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2338 | /// that PBI and BI are both conditional branches, and BI is in one of the |
| 2339 | /// successor blocks of PBI - PBI branches to BI. |
| 2340 | static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { |
| 2341 | assert(PBI->isConditional() && BI->isConditional()); |
| 2342 | BasicBlock *BB = BI->getParent(); |
Dan Gohman | 5476cfd | 2009-08-12 16:23:25 +0000 | [diff] [blame] | 2343 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2344 | // 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] | 2345 | // predecessor that ends on a branch of the same condition, make |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2346 | // this conditional branch redundant. |
| 2347 | if (PBI->getCondition() == BI->getCondition() && |
| 2348 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2349 | // Okay, the outcome of this conditional branch is statically |
| 2350 | // knowable. If this block had a single pred, handle specially. |
| 2351 | if (BB->getSinglePredecessor()) { |
| 2352 | // Turn this into a branch on constant. |
| 2353 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2354 | BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2355 | CondIsTrue)); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2356 | return true; // Nuke the branch on constant. |
| 2357 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2358 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2359 | // Otherwise, if there are multiple predecessors, insert a PHI that merges |
| 2360 | // in the constant and simplify the block result. Subsequent passes of |
| 2361 | // simplifycfg will thread the block. |
| 2362 | if (BlockIsSimpleEnoughToThreadThrough(BB)) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2363 | pred_iterator PB = pred_begin(BB), PE = pred_end(BB); |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2364 | PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()), |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 2365 | std::distance(PB, PE), |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2366 | BI->getCondition()->getName() + ".pr", |
| 2367 | BB->begin()); |
Chris Lattner | 5eed372 | 2008-07-13 21:55:46 +0000 | [diff] [blame] | 2368 | // Okay, we're going to insert the PHI node. Since PBI is not the only |
| 2369 | // predecessor, compute the PHI'd conditional value for all of the preds. |
| 2370 | // Any predecessor where the condition is not computable we keep symbolic. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2371 | for (pred_iterator PI = PB; PI != PE; ++PI) { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2372 | BasicBlock *P = *PI; |
| 2373 | if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2374 | PBI != BI && PBI->isConditional() && |
| 2375 | PBI->getCondition() == BI->getCondition() && |
| 2376 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2377 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2378 | NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2379 | CondIsTrue), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2380 | } else { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2381 | NewPN->addIncoming(BI->getCondition(), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2382 | } |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2383 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2384 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2385 | BI->setCondition(NewPN); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2386 | return true; |
| 2387 | } |
| 2388 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2389 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2390 | // 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] | 2391 | // predecessors are a conditional branch to one of our destinations, |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2392 | // fold the conditions into logical ops and one cond br. |
Zhou Sheng | 264e46e | 2009-02-26 06:56:37 +0000 | [diff] [blame] | 2393 | BasicBlock::iterator BBI = BB->begin(); |
| 2394 | // Ignore dbg intrinsics. |
| 2395 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 2396 | ++BBI; |
| 2397 | if (&*BBI != BI) |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2398 | return false; |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2399 | |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2400 | |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2401 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition())) |
| 2402 | if (CE->canTrap()) |
| 2403 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2404 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2405 | int PBIOp, BIOp; |
| 2406 | if (PBI->getSuccessor(0) == BI->getSuccessor(0)) |
| 2407 | PBIOp = BIOp = 0; |
| 2408 | else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) |
| 2409 | PBIOp = 0, BIOp = 1; |
| 2410 | else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) |
| 2411 | PBIOp = 1, BIOp = 0; |
| 2412 | else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) |
| 2413 | PBIOp = BIOp = 1; |
| 2414 | else |
| 2415 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2416 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2417 | // Check to make sure that the other destination of this branch |
| 2418 | // isn't BB itself. If so, this is an infinite loop that will |
| 2419 | // keep getting unwound. |
| 2420 | if (PBI->getSuccessor(PBIOp) == BB) |
| 2421 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2422 | |
| 2423 | // Do not perform this transformation if it would require |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2424 | // insertion of a large number of select instructions. For targets |
| 2425 | // without predication/cmovs, this is a big pessimization. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2426 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2427 | // Also do not perform this transformation if any phi node in the common |
| 2428 | // destination block can trap when reached by BB or PBB (PR17073). In that |
| 2429 | // case, it would be unsafe to hoist the operation into a select instruction. |
| 2430 | |
| 2431 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2432 | unsigned NumPhis = 0; |
| 2433 | for (BasicBlock::iterator II = CommonDest->begin(); |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2434 | isa<PHINode>(II); ++II, ++NumPhis) { |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2435 | if (NumPhis > 2) // Disable this xform. |
| 2436 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2437 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2438 | PHINode *PN = cast<PHINode>(II); |
| 2439 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2440 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) |
| 2441 | if (CE->canTrap()) |
| 2442 | return false; |
| 2443 | |
| 2444 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2445 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2446 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) |
| 2447 | if (CE->canTrap()) |
| 2448 | return false; |
| 2449 | } |
| 2450 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2451 | // Finally, if everything is ok, fold the branches to logical ops. |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2452 | BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2453 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2454 | DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2455 | << "AND: " << *BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2456 | |
| 2457 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2458 | // If OtherDest *is* BB, then BB is a basic block with a single conditional |
| 2459 | // branch in it, where one edge (OtherDest) goes back to itself but the other |
| 2460 | // exits. We don't *know* that the program avoids the infinite loop |
| 2461 | // (even though that seems likely). If we do this xform naively, we'll end up |
| 2462 | // recursively unpeeling the loop. Since we know that (after the xform is |
| 2463 | // done) that the block *is* infinite if reached, we just make it an obviously |
| 2464 | // infinite loop with no cond branch. |
| 2465 | if (OtherDest == BB) { |
| 2466 | // Insert it at the end of the function, because it's either code, |
| 2467 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2468 | BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 2469 | "infloop", BB->getParent()); |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2470 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
| 2471 | OtherDest = InfLoopBlock; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2472 | } |
| 2473 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2474 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2475 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2476 | // BI may have other predecessors. Because of this, we leave |
| 2477 | // it alone, but modify PBI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2478 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2479 | // Make sure we get to CommonDest on True&True directions. |
| 2480 | Value *PBICond = PBI->getCondition(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2481 | IRBuilder<true, NoFolder> Builder(PBI); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2482 | if (PBIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2483 | PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not"); |
| 2484 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2485 | Value *BICond = BI->getCondition(); |
| 2486 | if (BIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2487 | BICond = Builder.CreateNot(BICond, BICond->getName()+".not"); |
| 2488 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2489 | // Merge the conditions. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2490 | Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2491 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2492 | // Modify PBI to branch on the new condition to the new dests. |
| 2493 | PBI->setCondition(Cond); |
| 2494 | PBI->setSuccessor(0, CommonDest); |
| 2495 | PBI->setSuccessor(1, OtherDest); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2496 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2497 | // Update branch weight for PBI. |
| 2498 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2499 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2500 | PredFalseWeight); |
| 2501 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2502 | SuccFalseWeight); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2503 | if (PredHasWeights && SuccHasWeights) { |
| 2504 | uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; |
| 2505 | uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight; |
| 2506 | uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; |
| 2507 | uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; |
| 2508 | // The weight to CommonDest should be PredCommon * SuccTotal + |
| 2509 | // PredOther * SuccCommon. |
| 2510 | // The weight to OtherDest should be PredOther * SuccOther. |
Benjamin Kramer | ea68a94 | 2015-02-19 15:26:17 +0000 | [diff] [blame] | 2511 | uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + |
| 2512 | PredOther * SuccCommon, |
| 2513 | PredOther * SuccOther}; |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2514 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2515 | FitWeights(NewWeights); |
| 2516 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2517 | PBI->setMetadata(LLVMContext::MD_prof, |
Benjamin Kramer | ea68a94 | 2015-02-19 15:26:17 +0000 | [diff] [blame] | 2518 | MDBuilder(BI->getContext()) |
| 2519 | .createBranchWeights(NewWeights[0], NewWeights[1])); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2520 | } |
| 2521 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2522 | // OtherDest may have phi nodes. If so, add an entry from PBI's |
| 2523 | // block that are identical to the entries for BI's block. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2524 | AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2525 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2526 | // We know that the CommonDest already had an edge from PBI to |
| 2527 | // it. If it has PHIs though, the PHIs may have different |
| 2528 | // entries for BB and PBI's BB. If so, insert a select to make |
| 2529 | // them agree. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2530 | PHINode *PN; |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2531 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 2532 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 2533 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2534 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2535 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2536 | if (BIV != PBIV) { |
| 2537 | // Insert a select in PBI to pick the right value. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2538 | Value *NV = cast<SelectInst> |
| 2539 | (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux")); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2540 | PN->setIncomingValue(PBBIdx, NV); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2541 | } |
| 2542 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2543 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2544 | DEBUG(dbgs() << "INTO: " << *PBI->getParent()); |
| 2545 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2546 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2547 | // This basic block is probably dead. We know it has at least |
| 2548 | // one fewer predecessor. |
| 2549 | return true; |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2550 | } |
| 2551 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2552 | // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is |
| 2553 | // true or to FalseBB if Cond is false. |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2554 | // Takes care of updating the successors and removing the old terminator. |
| 2555 | // Also makes sure not to introduce new successors by assuming that edges to |
| 2556 | // non-successor TrueBBs and FalseBBs aren't reachable. |
| 2557 | static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2558 | BasicBlock *TrueBB, BasicBlock *FalseBB, |
| 2559 | uint32_t TrueWeight, |
| 2560 | uint32_t FalseWeight){ |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2561 | // Remove any superfluous successor edges from the CFG. |
| 2562 | // First, figure out which successors to preserve. |
| 2563 | // If TrueBB and FalseBB are equal, only try to preserve one copy of that |
| 2564 | // successor. |
| 2565 | BasicBlock *KeepEdge1 = TrueBB; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2566 | BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2567 | |
| 2568 | // Then remove the rest. |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 2569 | for (BasicBlock *Succ : OldTerm->successors()) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2570 | // Make sure only to keep exactly one copy of each edge. |
| 2571 | if (Succ == KeepEdge1) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2572 | KeepEdge1 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2573 | else if (Succ == KeepEdge2) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2574 | KeepEdge2 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2575 | else |
| 2576 | Succ->removePredecessor(OldTerm->getParent()); |
| 2577 | } |
| 2578 | |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2579 | IRBuilder<> Builder(OldTerm); |
| 2580 | Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); |
| 2581 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2582 | // Insert an appropriate new terminator. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2583 | if (!KeepEdge1 && !KeepEdge2) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2584 | if (TrueBB == FalseBB) |
| 2585 | // We were only looking for one successor, and it was present. |
| 2586 | // Create an unconditional branch to it. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2587 | Builder.CreateBr(TrueBB); |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2588 | else { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2589 | // We found both of the successors we were looking for. |
| 2590 | // Create a conditional branch sharing the condition of the select. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2591 | BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); |
| 2592 | if (TrueWeight != FalseWeight) |
| 2593 | NewBI->setMetadata(LLVMContext::MD_prof, |
| 2594 | MDBuilder(OldTerm->getContext()). |
| 2595 | createBranchWeights(TrueWeight, FalseWeight)); |
| 2596 | } |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2597 | } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { |
| 2598 | // Neither of the selected blocks were successors, so this |
| 2599 | // terminator must be unreachable. |
| 2600 | new UnreachableInst(OldTerm->getContext(), OldTerm); |
| 2601 | } else { |
| 2602 | // One of the selected values was a successor, but the other wasn't. |
| 2603 | // Insert an unconditional branch to the one that was found; |
| 2604 | // the edge to the one that wasn't must be unreachable. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2605 | if (!KeepEdge1) |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2606 | // Only TrueBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2607 | Builder.CreateBr(TrueBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2608 | else |
| 2609 | // Only FalseBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2610 | Builder.CreateBr(FalseBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2611 | } |
| 2612 | |
| 2613 | EraseTerminatorInstAndDCECond(OldTerm); |
| 2614 | return true; |
| 2615 | } |
| 2616 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2617 | // Replaces |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2618 | // (switch (select cond, X, Y)) on constant X, Y |
| 2619 | // with a branch - conditional if X and Y lead to distinct BBs, |
| 2620 | // unconditional otherwise. |
| 2621 | static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { |
| 2622 | // Check for constant integer values in the select. |
| 2623 | ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); |
| 2624 | ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); |
| 2625 | if (!TrueVal || !FalseVal) |
| 2626 | return false; |
| 2627 | |
| 2628 | // Find the relevant condition and destinations. |
| 2629 | Value *Condition = Select->getCondition(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 2630 | BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); |
| 2631 | BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2632 | |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2633 | // Get weight for TrueBB and FalseBB. |
| 2634 | uint32_t TrueWeight = 0, FalseWeight = 0; |
| 2635 | SmallVector<uint64_t, 8> Weights; |
| 2636 | bool HasWeights = HasBranchWeights(SI); |
| 2637 | if (HasWeights) { |
| 2638 | GetBranchWeights(SI, Weights); |
| 2639 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 2640 | TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal). |
| 2641 | getSuccessorIndex()]; |
| 2642 | FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal). |
| 2643 | getSuccessorIndex()]; |
| 2644 | } |
| 2645 | } |
| 2646 | |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2647 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2648 | return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, |
| 2649 | TrueWeight, FalseWeight); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2650 | } |
| 2651 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2652 | // Replaces |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2653 | // (indirectbr (select cond, blockaddress(@fn, BlockA), |
| 2654 | // blockaddress(@fn, BlockB))) |
| 2655 | // with |
| 2656 | // (br cond, BlockA, BlockB). |
| 2657 | static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { |
| 2658 | // Check that both operands of the select are block addresses. |
| 2659 | BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); |
| 2660 | BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); |
| 2661 | if (!TBA || !FBA) |
| 2662 | return false; |
| 2663 | |
| 2664 | // Extract the actual blocks. |
| 2665 | BasicBlock *TrueBB = TBA->getBasicBlock(); |
| 2666 | BasicBlock *FalseBB = FBA->getBasicBlock(); |
| 2667 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2668 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2669 | return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, |
| 2670 | 0, 0); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2671 | } |
| 2672 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2673 | /// This is called when we find an icmp instruction |
| 2674 | /// (a seteq/setne with a constant) as the only instruction in a |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2675 | /// block that ends with an uncond branch. We are looking for a very specific |
| 2676 | /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In |
| 2677 | /// this case, we merge the first two "or's of icmp" into a switch, but then the |
| 2678 | /// default value goes to an uncond block with a seteq in it, we get something |
| 2679 | /// like: |
| 2680 | /// |
| 2681 | /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] |
| 2682 | /// DEFAULT: |
| 2683 | /// %tmp = icmp eq i8 %A, 92 |
| 2684 | /// br label %end |
| 2685 | /// end: |
| 2686 | /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2687 | /// |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2688 | /// We prefer to split the edge to 'end' so that there is a true/false entry to |
| 2689 | /// the PHI, merging the third icmp into the switch. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 2690 | static bool TryToSimplifyUncondBranchWithICmpInIt( |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2691 | ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, |
| 2692 | const TargetTransformInfo &TTI, unsigned BonusInstThreshold, |
| 2693 | AssumptionCache *AC) { |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2694 | BasicBlock *BB = ICI->getParent(); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 2695 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2696 | // If the block has any PHIs in it or the icmp has multiple uses, it is too |
| 2697 | // complex. |
| 2698 | if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false; |
| 2699 | |
| 2700 | Value *V = ICI->getOperand(0); |
| 2701 | ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2702 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2703 | // The pattern we're looking for is where our only predecessor is a switch on |
| 2704 | // 'V' and this block is the default case for the switch. In this case we can |
| 2705 | // fold the compared value into the switch to simplify things. |
| 2706 | BasicBlock *Pred = BB->getSinglePredecessor(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2707 | if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2708 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2709 | SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); |
| 2710 | if (SI->getCondition() != V) |
| 2711 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2712 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2713 | // If BB is reachable on a non-default case, then we simply know the value of |
| 2714 | // V in this block. Substitute it and constant fold the icmp instruction |
| 2715 | // away. |
| 2716 | if (SI->getDefaultDest() != BB) { |
| 2717 | ConstantInt *VVal = SI->findCaseDest(BB); |
| 2718 | assert(VVal && "Should have a unique destination value"); |
| 2719 | ICI->setOperand(0, VVal); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2720 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2721 | if (Value *V = SimplifyInstruction(ICI, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2722 | ICI->replaceAllUsesWith(V); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2723 | ICI->eraseFromParent(); |
| 2724 | } |
| 2725 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2726 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2727 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2728 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2729 | // Ok, the block is reachable from the default dest. If the constant we're |
| 2730 | // comparing exists in one of the other edges, then we can constant fold ICI |
| 2731 | // and zap it. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 2732 | if (SI->findCaseValue(Cst) != SI->case_default()) { |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2733 | Value *V; |
| 2734 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 2735 | V = ConstantInt::getFalse(BB->getContext()); |
| 2736 | else |
| 2737 | V = ConstantInt::getTrue(BB->getContext()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2738 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2739 | ICI->replaceAllUsesWith(V); |
| 2740 | ICI->eraseFromParent(); |
| 2741 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2742 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2743 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2744 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2745 | // The use of the icmp has to be in the 'end' block, by the only PHI node in |
| 2746 | // the block. |
| 2747 | BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2748 | PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2749 | if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2750 | isa<PHINode>(++BasicBlock::iterator(PHIUse))) |
| 2751 | return false; |
| 2752 | |
| 2753 | // If the icmp is a SETEQ, then the default dest gets false, the new edge gets |
| 2754 | // true in the PHI. |
| 2755 | Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); |
| 2756 | Constant *NewCst = ConstantInt::getFalse(BB->getContext()); |
| 2757 | |
| 2758 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 2759 | std::swap(DefaultCst, NewCst); |
| 2760 | |
| 2761 | // Replace ICI (which is used by the PHI for the default value) with true or |
| 2762 | // false depending on if it is EQ or NE. |
| 2763 | ICI->replaceAllUsesWith(DefaultCst); |
| 2764 | ICI->eraseFromParent(); |
| 2765 | |
| 2766 | // Okay, the switch goes to this block on a default value. Add an edge from |
| 2767 | // the switch to the merge point on the compared value. |
| 2768 | BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge", |
| 2769 | BB->getParent(), BB); |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 2770 | SmallVector<uint64_t, 8> Weights; |
| 2771 | bool HasWeights = HasBranchWeights(SI); |
| 2772 | if (HasWeights) { |
| 2773 | GetBranchWeights(SI, Weights); |
| 2774 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 2775 | // Split weight for default case to case for "Cst". |
| 2776 | Weights[0] = (Weights[0]+1) >> 1; |
| 2777 | Weights.push_back(Weights[0]); |
| 2778 | |
| 2779 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 2780 | SI->setMetadata(LLVMContext::MD_prof, |
| 2781 | MDBuilder(SI->getContext()). |
| 2782 | createBranchWeights(MDWeights)); |
| 2783 | } |
| 2784 | } |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2785 | SI->addCase(Cst, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2786 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2787 | // 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] | 2788 | Builder.SetInsertPoint(NewBB); |
| 2789 | Builder.SetCurrentDebugLocation(SI->getDebugLoc()); |
| 2790 | Builder.CreateBr(SuccBlock); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2791 | PHIUse->addIncoming(NewCst, NewBB); |
| 2792 | return true; |
| 2793 | } |
| 2794 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2795 | /// The specified branch is a conditional branch. |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2796 | /// Check to see if it is branching on an or/and chain of icmp instructions, and |
| 2797 | /// fold it into a switch instruction if so. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2798 | static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, |
| 2799 | const DataLayout &DL) { |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2800 | Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2801 | if (!Cond) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2802 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2803 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 2804 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 2805 | // 'setne's and'ed together, collect them. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2806 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 2807 | // 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] | 2808 | ConstantComparesGatherer ConstantCompare(Cond, DL); |
| 2809 | // Unpack the result |
| 2810 | SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals; |
| 2811 | Value *CompVal = ConstantCompare.CompValue; |
| 2812 | unsigned UsedICmps = ConstantCompare.UsedICmps; |
| 2813 | Value *ExtraCase = ConstantCompare.Extra; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2814 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2815 | // If we didn't have a multiply compared value, fail. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2816 | if (!CompVal) return false; |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2817 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 2818 | // Avoid turning single icmps into a switch. |
| 2819 | if (UsedICmps <= 1) |
| 2820 | return false; |
| 2821 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 2822 | bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); |
| 2823 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2824 | // There might be duplicate constants in the list, which the switch |
| 2825 | // instruction can't handle, remove them now. |
| 2826 | array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); |
| 2827 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2828 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2829 | // If Extra was used, we require at least two switch values to do the |
| 2830 | // transformation. A switch with one value is just an cond branch. |
| 2831 | if (ExtraCase && Values.size() < 2) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2832 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 2833 | // TODO: Preserve branch weight metadata, similarly to how |
| 2834 | // FoldValueComparisonIntoPredecessors preserves it. |
| 2835 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2836 | // Figure out which block is which destination. |
| 2837 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
| 2838 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 2839 | if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2840 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2841 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2842 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2843 | DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2844 | << " cases into SWITCH. BB is:\n" << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2845 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2846 | // If there are any extra values that couldn't be folded into the switch |
| 2847 | // then we evaluate them with an explicit branch first. Split the block |
| 2848 | // right before the condbr to handle it. |
| 2849 | if (ExtraCase) { |
| 2850 | BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test"); |
| 2851 | // Remove the uncond branch added to the old block. |
| 2852 | TerminatorInst *OldTI = BB->getTerminator(); |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2853 | Builder.SetInsertPoint(OldTI); |
| 2854 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2855 | if (TrueWhenEqual) |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2856 | Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2857 | else |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2858 | Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2859 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2860 | OldTI->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2861 | |
Chris Lattner | cb570f8 | 2010-12-13 05:34:18 +0000 | [diff] [blame] | 2862 | // If there are PHI nodes in EdgeBB, then we need to add a new entry to them |
| 2863 | // for the edge we just added. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2864 | AddPredecessorToBlock(EdgeBB, BB, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2865 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2866 | DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase |
| 2867 | << "\nEXTRABB = " << *BB); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2868 | BB = NewBB; |
| 2869 | } |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2870 | |
| 2871 | Builder.SetInsertPoint(BI); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2872 | // Convert pointer to int before we switch. |
| 2873 | if (CompVal->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2874 | CompVal = Builder.CreatePtrToInt( |
| 2875 | CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2876 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2877 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2878 | // Create the new switch instruction now. |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2879 | SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 2880 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2881 | // Add all of the 'cases' to the switch instruction. |
| 2882 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 2883 | New->addCase(Values[i], EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2884 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2885 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 2886 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 2887 | // the number of edges added. |
| 2888 | for (BasicBlock::iterator BBI = EdgeBB->begin(); |
| 2889 | isa<PHINode>(BBI); ++BBI) { |
| 2890 | PHINode *PN = cast<PHINode>(BBI); |
| 2891 | Value *InVal = PN->getIncomingValueForBlock(BB); |
| 2892 | for (unsigned i = 0, e = Values.size()-1; i != e; ++i) |
| 2893 | PN->addIncoming(InVal, BB); |
| 2894 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2895 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2896 | // Erase the old branch instruction. |
| 2897 | EraseTerminatorInstAndDCECond(BI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2898 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2899 | DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2900 | return true; |
| 2901 | } |
| 2902 | |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 2903 | // FIXME: This seems like a pretty common thing to want to do. Consider |
| 2904 | // whether there is a more accessible place to put this. |
| 2905 | static void convertInvokeToCall(InvokeInst *II) { |
| 2906 | SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3); |
| 2907 | // Insert a call instruction before the invoke. |
| 2908 | CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II); |
| 2909 | Call->takeName(II); |
| 2910 | Call->setCallingConv(II->getCallingConv()); |
| 2911 | Call->setAttributes(II->getAttributes()); |
| 2912 | Call->setDebugLoc(II->getDebugLoc()); |
| 2913 | |
| 2914 | // Anything that used the value produced by the invoke instruction now uses |
| 2915 | // the value produced by the call instruction. Note that we do this even |
| 2916 | // for void functions and calls with no uses so that the callgraph edge is |
| 2917 | // updated. |
| 2918 | II->replaceAllUsesWith(Call); |
| 2919 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 2920 | |
| 2921 | // Insert a branch to the normal destination right before the invoke. |
| 2922 | BranchInst::Create(II->getNormalDest(), II); |
| 2923 | |
| 2924 | // Finally, delete the invoke instruction! |
| 2925 | II->eraseFromParent(); |
| 2926 | } |
| 2927 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2928 | bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { |
| 2929 | // If this is a trivial landing pad that just continues unwinding the caught |
| 2930 | // exception then zap the landing pad, turning its invokes into calls. |
| 2931 | BasicBlock *BB = RI->getParent(); |
| 2932 | LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); |
| 2933 | if (RI->getValue() != LPInst) |
| 2934 | // Not a landing pad, or the resume is not unwinding the exception that |
| 2935 | // caused control to branch here. |
| 2936 | return false; |
| 2937 | |
| 2938 | // Check that there are no other instructions except for debug intrinsics. |
| 2939 | BasicBlock::iterator I = LPInst, E = RI; |
| 2940 | while (++I != E) |
| 2941 | if (!isa<DbgInfoIntrinsic>(I)) |
| 2942 | return false; |
| 2943 | |
| 2944 | // Turn all invokes that unwind here into calls and delete the basic block. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2945 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 2946 | InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator()); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 2947 | convertInvokeToCall(II); |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2948 | } |
| 2949 | |
Reid Kleckner | f12b334 | 2015-01-22 19:29:46 +0000 | [diff] [blame] | 2950 | // The landingpad is now unreachable. Zap it. |
| 2951 | BB->eraseFromParent(); |
| 2952 | return true; |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2953 | } |
| 2954 | |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 2955 | bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { |
| 2956 | // If this is a trivial cleanup pad that executes no instructions, it can be |
| 2957 | // eliminated. If the cleanup pad continues to the caller, any predecessor |
| 2958 | // that is an EH pad will be updated to continue to the caller and any |
| 2959 | // predecessor that terminates with an invoke instruction will have its invoke |
| 2960 | // instruction converted to a call instruction. If the cleanup pad being |
| 2961 | // simplified does not continue to the caller, each predecessor will be |
| 2962 | // updated to continue to the unwind destination of the cleanup pad being |
| 2963 | // simplified. |
| 2964 | BasicBlock *BB = RI->getParent(); |
| 2965 | Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI()); |
| 2966 | if (!CPInst) |
| 2967 | // This isn't an empty cleanup. |
| 2968 | return false; |
| 2969 | |
| 2970 | // Check that there are no other instructions except for debug intrinsics. |
| 2971 | BasicBlock::iterator I = CPInst, E = RI; |
| 2972 | while (++I != E) |
| 2973 | if (!isa<DbgInfoIntrinsic>(I)) |
| 2974 | return false; |
| 2975 | |
| 2976 | // If the cleanup return we are simplifying unwinds to the caller, this |
| 2977 | // will set UnwindDest to nullptr. |
| 2978 | BasicBlock *UnwindDest = RI->getUnwindDest(); |
| 2979 | |
| 2980 | // We're about to remove BB from the control flow. Before we do, sink any |
| 2981 | // PHINodes into the unwind destination. Doing this before changing the |
| 2982 | // control flow avoids some potentially slow checks, since we can currently |
| 2983 | // be certain that UnwindDest and BB have no common predecessors (since they |
| 2984 | // are both EH pads). |
| 2985 | if (UnwindDest) { |
| 2986 | // First, go through the PHI nodes in UnwindDest and update any nodes that |
| 2987 | // reference the block we are removing |
| 2988 | for (BasicBlock::iterator I = UnwindDest->begin(), |
| 2989 | IE = UnwindDest->getFirstNonPHI(); |
| 2990 | I != IE; ++I) { |
| 2991 | PHINode *DestPN = cast<PHINode>(I); |
| 2992 | |
Andrew Kaylor | 2a9a6d8 | 2015-09-05 01:00:51 +0000 | [diff] [blame] | 2993 | int Idx = DestPN->getBasicBlockIndex(BB); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 2994 | // 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] | 2995 | assert(Idx != -1); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 2996 | // This PHI node has an incoming value that corresponds to a control |
| 2997 | // path through the cleanup pad we are removing. If the incoming |
| 2998 | // value is in the cleanup pad, it must be a PHINode (because we |
| 2999 | // verified above that the block is otherwise empty). Otherwise, the |
| 3000 | // value is either a constant or a value that dominates the cleanup |
| 3001 | // pad being removed. |
| 3002 | // |
| 3003 | // Because BB and UnwindDest are both EH pads, all of their |
| 3004 | // predecessors must unwind to these blocks, and since no instruction |
| 3005 | // can have multiple unwind destinations, there will be no overlap in |
| 3006 | // incoming blocks between SrcPN and DestPN. |
| 3007 | Value *SrcVal = DestPN->getIncomingValue(Idx); |
| 3008 | PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); |
| 3009 | |
| 3010 | // Remove the entry for the block we are deleting. |
| 3011 | DestPN->removeIncomingValue(Idx, false); |
| 3012 | |
| 3013 | if (SrcPN && SrcPN->getParent() == BB) { |
| 3014 | // If the incoming value was a PHI node in the cleanup pad we are |
| 3015 | // removing, we need to merge that PHI node's incoming values into |
| 3016 | // DestPN. |
| 3017 | for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); |
| 3018 | SrcIdx != SrcE; ++SrcIdx) { |
| 3019 | DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), |
| 3020 | SrcPN->getIncomingBlock(SrcIdx)); |
| 3021 | } |
| 3022 | } else { |
| 3023 | // Otherwise, the incoming value came from above BB and |
| 3024 | // so we can just reuse it. We must associate all of BB's |
| 3025 | // predecessors with this value. |
| 3026 | for (auto *pred : predecessors(BB)) { |
| 3027 | DestPN->addIncoming(SrcVal, pred); |
| 3028 | } |
| 3029 | } |
| 3030 | } |
| 3031 | |
| 3032 | // Sink any remaining PHI nodes directly into UnwindDest. |
| 3033 | Instruction *InsertPt = UnwindDest->getFirstNonPHI(); |
| 3034 | for (BasicBlock::iterator I = BB->begin(), IE = BB->getFirstNonPHI(); |
| 3035 | I != IE;) { |
| 3036 | // The iterator must be incremented here because the instructions are |
| 3037 | // being moved to another block. |
| 3038 | PHINode *PN = cast<PHINode>(I++); |
| 3039 | if (PN->use_empty()) |
| 3040 | // If the PHI node has no uses, just leave it. It will be erased |
| 3041 | // when we erase BB below. |
| 3042 | continue; |
| 3043 | |
| 3044 | // Otherwise, sink this PHI node into UnwindDest. |
| 3045 | // Any predecessors to UnwindDest which are not already represented |
| 3046 | // must be back edges which inherit the value from the path through |
| 3047 | // BB. In this case, the PHI value must reference itself. |
| 3048 | for (auto *pred : predecessors(UnwindDest)) |
| 3049 | if (pred != BB) |
| 3050 | PN->addIncoming(PN, pred); |
| 3051 | PN->moveBefore(InsertPt); |
| 3052 | } |
| 3053 | } |
| 3054 | |
| 3055 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 3056 | // The iterator must be updated here because we are removing this pred. |
| 3057 | BasicBlock *PredBB = *PI++; |
| 3058 | TerminatorInst *TI = PredBB->getTerminator(); |
| 3059 | if (UnwindDest == nullptr) { |
| 3060 | if (auto *II = dyn_cast<InvokeInst>(TI)) { |
| 3061 | // The cleanup return being simplified continues to the caller and this |
| 3062 | // predecessor terminated with an invoke instruction. Convert the |
| 3063 | // invoke to a call. |
| 3064 | // This call updates the predecessor/successor chain. |
| 3065 | convertInvokeToCall(II); |
| 3066 | } else { |
| 3067 | // In the remaining cases the predecessor's terminator unwinds to the |
| 3068 | // block we are removing. We need to create a new instruction that |
| 3069 | // unwinds to the caller. Simply setting the unwind destination to |
| 3070 | // nullptr would leave the objects internal data in an inconsistent |
| 3071 | // state. |
| 3072 | // FIXME: Consider whether it is better to update setUnwindDest to |
| 3073 | // keep things consistent. |
| 3074 | if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { |
| 3075 | auto *NewCRI = CleanupReturnInst::Create(CRI->getCleanupPad(), |
| 3076 | nullptr, CRI); |
| 3077 | NewCRI->takeName(CRI); |
| 3078 | NewCRI->setDebugLoc(CRI->getDebugLoc()); |
| 3079 | CRI->eraseFromParent(); |
| 3080 | } else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI)) { |
| 3081 | auto *NewCEP = CatchEndPadInst::Create(CEP->getContext(), nullptr, |
| 3082 | CEP); |
| 3083 | NewCEP->takeName(CEP); |
| 3084 | NewCEP->setDebugLoc(CEP->getDebugLoc()); |
| 3085 | CEP->eraseFromParent(); |
| 3086 | } else if (auto *TPI = dyn_cast<TerminatePadInst>(TI)) { |
| 3087 | SmallVector<Value *, 3> TerminatePadArgs; |
| 3088 | for (Value *Operand : TPI->arg_operands()) |
| 3089 | TerminatePadArgs.push_back(Operand); |
| 3090 | auto *NewTPI = TerminatePadInst::Create(TPI->getContext(), nullptr, |
| 3091 | TerminatePadArgs, TPI); |
| 3092 | NewTPI->takeName(TPI); |
| 3093 | NewTPI->setDebugLoc(TPI->getDebugLoc()); |
| 3094 | TPI->eraseFromParent(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3095 | } else { |
| 3096 | llvm_unreachable("Unexpected predecessor to cleanup pad."); |
| 3097 | } |
| 3098 | } |
| 3099 | } else { |
| 3100 | // If the predecessor did not terminate with an invoke instruction, it |
| 3101 | // must be some variety of EH pad. |
| 3102 | TerminatorInst *TI = PredBB->getTerminator(); |
| 3103 | // FIXME: Introducing an EH terminator base class would simplify this. |
| 3104 | if (auto *II = dyn_cast<InvokeInst>(TI)) |
| 3105 | II->setUnwindDest(UnwindDest); |
| 3106 | else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) |
| 3107 | CRI->setUnwindDest(UnwindDest); |
| 3108 | else if (auto *CEP = dyn_cast<CatchEndPadInst>(TI)) |
| 3109 | CEP->setUnwindDest(UnwindDest); |
| 3110 | else if (auto *TPI = dyn_cast<TerminatePadInst>(TI)) |
| 3111 | TPI->setUnwindDest(UnwindDest); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3112 | else |
| 3113 | llvm_unreachable("Unexpected predecessor to cleanup pad."); |
| 3114 | } |
| 3115 | } |
| 3116 | |
| 3117 | // The cleanup pad is now unreachable. Zap it. |
| 3118 | BB->eraseFromParent(); |
| 3119 | return true; |
| 3120 | } |
| 3121 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3122 | bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3123 | BasicBlock *BB = RI->getParent(); |
| 3124 | if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3125 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3126 | // Find predecessors that end with branches. |
| 3127 | SmallVector<BasicBlock*, 8> UncondBranchPreds; |
| 3128 | SmallVector<BranchInst*, 8> CondBranchPreds; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 3129 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 3130 | BasicBlock *P = *PI; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3131 | TerminatorInst *PTI = P->getTerminator(); |
| 3132 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { |
| 3133 | if (BI->isUnconditional()) |
| 3134 | UncondBranchPreds.push_back(P); |
| 3135 | else |
| 3136 | CondBranchPreds.push_back(BI); |
| 3137 | } |
| 3138 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3139 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3140 | // If we found some, do the transformation! |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3141 | if (!UncondBranchPreds.empty() && DupRet) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3142 | while (!UncondBranchPreds.empty()) { |
| 3143 | BasicBlock *Pred = UncondBranchPreds.pop_back_val(); |
| 3144 | DEBUG(dbgs() << "FOLDING: " << *BB |
| 3145 | << "INTO UNCOND BRANCH PRED: " << *Pred); |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3146 | (void)FoldReturnIntoUncondBranch(RI, BB, Pred); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3147 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3148 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3149 | // If we eliminated all predecessors of the block, delete the block now. |
Ramkumar Ramachandra | 40c3e03 | 2015-01-13 03:46:47 +0000 | [diff] [blame] | 3150 | if (pred_empty(BB)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3151 | // We know there are no successors, so just nuke the block. |
| 3152 | BB->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3153 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3154 | return true; |
| 3155 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3156 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3157 | // Check out all of the conditional branches going to this return |
| 3158 | // instruction. If any of them just select between returns, change the |
| 3159 | // branch itself into a select/return pair. |
| 3160 | while (!CondBranchPreds.empty()) { |
| 3161 | BranchInst *BI = CondBranchPreds.pop_back_val(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3162 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3163 | // Check to see if the non-BB successor is also a return block. |
| 3164 | if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && |
| 3165 | isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3166 | SimplifyCondBranchToTwoReturns(BI, Builder)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3167 | return true; |
| 3168 | } |
| 3169 | return false; |
| 3170 | } |
| 3171 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3172 | bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { |
| 3173 | BasicBlock *BB = UI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3174 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3175 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3176 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3177 | // If there are any instructions immediately before the unreachable that can |
| 3178 | // be removed, do so. |
| 3179 | while (UI != BB->begin()) { |
| 3180 | BasicBlock::iterator BBI = UI; |
| 3181 | --BBI; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3182 | // Do not delete instructions that can have side effects which might cause |
| 3183 | // the unreachable to not be reachable; specifically, calls and volatile |
| 3184 | // operations may have this effect. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3185 | if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3186 | |
| 3187 | if (BBI->mayHaveSideEffects()) { |
| 3188 | if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { |
| 3189 | if (SI->isVolatile()) |
| 3190 | break; |
| 3191 | } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { |
| 3192 | if (LI->isVolatile()) |
| 3193 | break; |
| 3194 | } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { |
| 3195 | if (RMWI->isVolatile()) |
| 3196 | break; |
| 3197 | } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { |
| 3198 | if (CXI->isVolatile()) |
| 3199 | break; |
| 3200 | } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && |
| 3201 | !isa<LandingPadInst>(BBI)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3202 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3203 | } |
Bill Wendling | 55d875f | 2011-08-16 20:41:17 +0000 | [diff] [blame] | 3204 | // Note that deleting LandingPad's here is in fact okay, although it |
| 3205 | // involves a bit of subtle reasoning. If this inst is a LandingPad, |
| 3206 | // all the predecessors of this block will be the unwind edges of Invokes, |
| 3207 | // and we can therefore guarantee this block will be erased. |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3208 | } |
| 3209 | |
Eli Friedman | aac35b3 | 2011-03-09 00:48:33 +0000 | [diff] [blame] | 3210 | // Delete this instruction (any uses are guaranteed to be dead) |
| 3211 | if (!BBI->use_empty()) |
| 3212 | BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3213 | BBI->eraseFromParent(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3214 | Changed = true; |
| 3215 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3216 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3217 | // If the unreachable instruction is the first in the block, take a gander |
| 3218 | // at all of the predecessors of this instruction, and simplify them. |
| 3219 | if (&BB->front() != UI) return Changed; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3220 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3221 | SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); |
| 3222 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 3223 | TerminatorInst *TI = Preds[i]->getTerminator(); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3224 | IRBuilder<> Builder(TI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3225 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 3226 | if (BI->isUnconditional()) { |
| 3227 | if (BI->getSuccessor(0) == BB) { |
| 3228 | new UnreachableInst(TI->getContext(), TI); |
| 3229 | TI->eraseFromParent(); |
| 3230 | Changed = true; |
| 3231 | } |
| 3232 | } else { |
| 3233 | if (BI->getSuccessor(0) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3234 | Builder.CreateBr(BI->getSuccessor(1)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3235 | EraseTerminatorInstAndDCECond(BI); |
| 3236 | } else if (BI->getSuccessor(1) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3237 | Builder.CreateBr(BI->getSuccessor(0)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3238 | EraseTerminatorInstAndDCECond(BI); |
| 3239 | Changed = true; |
| 3240 | } |
| 3241 | } |
| 3242 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3243 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3244 | i != e; ++i) |
| 3245 | if (i.getCaseSuccessor() == BB) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3246 | BB->removePredecessor(SI->getParent()); |
| 3247 | SI->removeCase(i); |
| 3248 | --i; --e; |
| 3249 | Changed = true; |
| 3250 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3251 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { |
| 3252 | if (II->getUnwindDest() == BB) { |
| 3253 | // Convert the invoke to a call instruction. This would be a good |
| 3254 | // place to note that the call does not throw though. |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3255 | BranchInst *BI = Builder.CreateBr(II->getNormalDest()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3256 | II->removeFromParent(); // Take out of symbol table |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3257 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3258 | // Insert the call now... |
| 3259 | SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3260 | Builder.SetInsertPoint(BI); |
| 3261 | CallInst *CI = Builder.CreateCall(II->getCalledValue(), |
Jay Foad | 5bd375a | 2011-07-15 08:37:34 +0000 | [diff] [blame] | 3262 | Args, II->getName()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3263 | CI->setCallingConv(II->getCallingConv()); |
| 3264 | CI->setAttributes(II->getAttributes()); |
| 3265 | // If the invoke produced a value, the call does now instead. |
| 3266 | II->replaceAllUsesWith(CI); |
| 3267 | delete II; |
| 3268 | Changed = true; |
| 3269 | } |
| 3270 | } |
| 3271 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3272 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3273 | // If this block is now dead, remove it. |
Ramkumar Ramachandra | 40c3e03 | 2015-01-13 03:46:47 +0000 | [diff] [blame] | 3274 | if (pred_empty(BB) && |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3275 | BB != &BB->getParent()->getEntryBlock()) { |
| 3276 | // We know there are no successors, so just nuke the block. |
| 3277 | BB->eraseFromParent(); |
| 3278 | return true; |
| 3279 | } |
| 3280 | |
| 3281 | return Changed; |
| 3282 | } |
| 3283 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3284 | static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { |
| 3285 | assert(Cases.size() >= 1); |
| 3286 | |
| 3287 | array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); |
| 3288 | for (size_t I = 1, E = Cases.size(); I != E; ++I) { |
| 3289 | if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) |
| 3290 | return false; |
| 3291 | } |
| 3292 | return true; |
| 3293 | } |
| 3294 | |
| 3295 | /// Turn a switch with two reachable destinations into an integer range |
| 3296 | /// comparison and branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 3297 | static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3298 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3299 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3300 | bool HasDefault = |
| 3301 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3302 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3303 | // Partition the cases into two sets with different destinations. |
| 3304 | BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; |
| 3305 | BasicBlock *DestB = nullptr; |
| 3306 | SmallVector <ConstantInt *, 16> CasesA; |
| 3307 | SmallVector <ConstantInt *, 16> CasesB; |
| 3308 | |
| 3309 | for (SwitchInst::CaseIt I : SI->cases()) { |
| 3310 | BasicBlock *Dest = I.getCaseSuccessor(); |
| 3311 | if (!DestA) DestA = Dest; |
| 3312 | if (Dest == DestA) { |
| 3313 | CasesA.push_back(I.getCaseValue()); |
| 3314 | continue; |
| 3315 | } |
| 3316 | if (!DestB) DestB = Dest; |
| 3317 | if (Dest == DestB) { |
| 3318 | CasesB.push_back(I.getCaseValue()); |
| 3319 | continue; |
| 3320 | } |
| 3321 | return false; // More than two destinations. |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3322 | } |
| 3323 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3324 | assert(DestA && DestB && "Single-destination switch should have been folded."); |
| 3325 | assert(DestA != DestB); |
| 3326 | assert(DestB != SI->getDefaultDest()); |
| 3327 | assert(!CasesB.empty() && "There must be non-default cases."); |
| 3328 | assert(!CasesA.empty() || HasDefault); |
| 3329 | |
| 3330 | // Figure out if one of the sets of cases form a contiguous range. |
| 3331 | SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; |
| 3332 | BasicBlock *ContiguousDest = nullptr; |
| 3333 | BasicBlock *OtherDest = nullptr; |
| 3334 | if (!CasesA.empty() && CasesAreContiguous(CasesA)) { |
| 3335 | ContiguousCases = &CasesA; |
| 3336 | ContiguousDest = DestA; |
| 3337 | OtherDest = DestB; |
| 3338 | } else if (CasesAreContiguous(CasesB)) { |
| 3339 | ContiguousCases = &CasesB; |
| 3340 | ContiguousDest = DestB; |
| 3341 | OtherDest = DestA; |
| 3342 | } else |
| 3343 | return false; |
| 3344 | |
| 3345 | // Start building the compare and branch. |
| 3346 | |
| 3347 | Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); |
| 3348 | Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size()); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3349 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 3350 | Value *Sub = SI->getCondition(); |
| 3351 | if (!Offset->isNullValue()) |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3352 | Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); |
| 3353 | |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 3354 | Value *Cmp; |
| 3355 | // If NumCases overflowed, then all possible values jump to the successor. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3356 | if (NumCases->isNullValue() && !ContiguousCases->empty()) |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 3357 | Cmp = ConstantInt::getTrue(SI->getContext()); |
| 3358 | else |
| 3359 | Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3360 | BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3361 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3362 | // Update weight for the newly-created conditional branch. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3363 | if (HasBranchWeights(SI)) { |
| 3364 | SmallVector<uint64_t, 8> Weights; |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3365 | GetBranchWeights(SI, Weights); |
| 3366 | if (Weights.size() == 1 + SI->getNumCases()) { |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3367 | uint64_t TrueWeight = 0; |
| 3368 | uint64_t FalseWeight = 0; |
| 3369 | for (size_t I = 0, E = Weights.size(); I != E; ++I) { |
| 3370 | if (SI->getSuccessor(I) == ContiguousDest) |
| 3371 | TrueWeight += Weights[I]; |
| 3372 | else |
| 3373 | FalseWeight += Weights[I]; |
| 3374 | } |
| 3375 | while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { |
| 3376 | TrueWeight /= 2; |
| 3377 | FalseWeight /= 2; |
| 3378 | } |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3379 | NewBI->setMetadata(LLVMContext::MD_prof, |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3380 | MDBuilder(SI->getContext()).createBranchWeights( |
| 3381 | (uint32_t)TrueWeight, (uint32_t)FalseWeight)); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3382 | } |
| 3383 | } |
| 3384 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3385 | // Prune obsolete incoming values off the successors' PHI nodes. |
| 3386 | for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 3387 | unsigned PreviousEdges = ContiguousCases->size(); |
| 3388 | if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges; |
| 3389 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3390 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 3391 | } |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3392 | for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 3393 | unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); |
| 3394 | if (OtherDest == SI->getDefaultDest()) ++PreviousEdges; |
| 3395 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
| 3396 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 3397 | } |
| 3398 | |
| 3399 | // Drop the switch. |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3400 | SI->eraseFromParent(); |
| 3401 | |
| 3402 | return true; |
| 3403 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3404 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3405 | /// Compute masked bits for the condition of a switch |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3406 | /// and use it to remove dead cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3407 | static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, |
| 3408 | const DataLayout &DL) { |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3409 | Value *Cond = SI->getCondition(); |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 3410 | unsigned Bits = Cond->getType()->getIntegerBitWidth(); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3411 | APInt KnownZero(Bits, 0), KnownOne(Bits, 0); |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 3412 | computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3413 | |
| 3414 | // Gather dead cases. |
| 3415 | SmallVector<ConstantInt*, 8> DeadCases; |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3416 | for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3417 | if ((I.getCaseValue()->getValue() & KnownZero) != 0 || |
| 3418 | (I.getCaseValue()->getValue() & KnownOne) != KnownOne) { |
| 3419 | DeadCases.push_back(I.getCaseValue()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3420 | DEBUG(dbgs() << "SimplifyCFG: switch case '" |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3421 | << I.getCaseValue() << "' is dead.\n"); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3422 | } |
| 3423 | } |
| 3424 | |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 3425 | // If we can prove that the cases must cover all possible values, the |
| 3426 | // default destination becomes dead and we can remove it. |
| 3427 | bool HasDefault = |
| 3428 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
| 3429 | if (HasDefault && Bits < 64 /* avoid overflow */ && |
| 3430 | SI->getNumCases() == (1ULL << Bits)) { |
| 3431 | DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); |
| 3432 | BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(), |
| 3433 | SI->getParent(), ""); |
| 3434 | SI->setDefaultDest(NewDefault); |
| 3435 | SplitBlock(NewDefault, NewDefault->begin()); |
| 3436 | auto *OldTI = NewDefault->getTerminator(); |
| 3437 | new UnreachableInst(SI->getContext(), OldTI); |
| 3438 | EraseTerminatorInstAndDCECond(OldTI); |
| 3439 | return true; |
| 3440 | } |
| 3441 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3442 | SmallVector<uint64_t, 8> Weights; |
| 3443 | bool HasWeight = HasBranchWeights(SI); |
| 3444 | if (HasWeight) { |
| 3445 | GetBranchWeights(SI, Weights); |
| 3446 | HasWeight = (Weights.size() == 1 + SI->getNumCases()); |
| 3447 | } |
| 3448 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3449 | // Remove dead cases from the switch. |
| 3450 | for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3451 | SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]); |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3452 | assert(Case != SI->case_default() && |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3453 | "Case was not found. Probably mistake in DeadCases forming."); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3454 | if (HasWeight) { |
| 3455 | std::swap(Weights[Case.getCaseIndex()+1], Weights.back()); |
| 3456 | Weights.pop_back(); |
| 3457 | } |
| 3458 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3459 | // Prune unused values from PHI nodes. |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3460 | Case.getCaseSuccessor()->removePredecessor(SI->getParent()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3461 | SI->removeCase(Case); |
| 3462 | } |
Justin Bogner | 0ba3f21 | 2013-12-20 08:21:30 +0000 | [diff] [blame] | 3463 | if (HasWeight && Weights.size() >= 2) { |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3464 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 3465 | SI->setMetadata(LLVMContext::MD_prof, |
| 3466 | MDBuilder(SI->getParent()->getContext()). |
| 3467 | createBranchWeights(MDWeights)); |
| 3468 | } |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3469 | |
| 3470 | return !DeadCases.empty(); |
| 3471 | } |
| 3472 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3473 | /// If BB would be eligible for simplification by |
| 3474 | /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3475 | /// by an unconditional branch), look at the phi node for BB in the successor |
| 3476 | /// block and see if the incoming value is equal to CaseValue. If so, return |
| 3477 | /// the phi node, and set PhiIndex to BB's index in the phi node. |
| 3478 | static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, |
| 3479 | BasicBlock *BB, |
| 3480 | int *PhiIndex) { |
| 3481 | if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3482 | return nullptr; // BB must be empty to be a candidate for simplification. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3483 | if (!BB->getSinglePredecessor()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3484 | return nullptr; // BB must be dominated by the switch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3485 | |
| 3486 | BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3487 | if (!Branch || !Branch->isUnconditional()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3488 | return nullptr; // Terminator must be unconditional branch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3489 | |
| 3490 | BasicBlock *Succ = Branch->getSuccessor(0); |
| 3491 | |
| 3492 | BasicBlock::iterator I = Succ->begin(); |
| 3493 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3494 | int Idx = PHI->getBasicBlockIndex(BB); |
| 3495 | assert(Idx >= 0 && "PHI has no entry for predecessor?"); |
| 3496 | |
| 3497 | Value *InValue = PHI->getIncomingValue(Idx); |
| 3498 | if (InValue != CaseValue) continue; |
| 3499 | |
| 3500 | *PhiIndex = Idx; |
| 3501 | return PHI; |
| 3502 | } |
| 3503 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3504 | return nullptr; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3505 | } |
| 3506 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3507 | /// Try to forward the condition of a switch instruction to a phi node |
| 3508 | /// dominated by the switch, if that would mean that some of the destination |
| 3509 | /// blocks of the switch can be folded away. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3510 | /// Returns true if a change is made. |
| 3511 | static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { |
| 3512 | typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap; |
| 3513 | ForwardingNodesMap ForwardingNodes; |
| 3514 | |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3515 | for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3516 | ConstantInt *CaseValue = I.getCaseValue(); |
| 3517 | BasicBlock *CaseDest = I.getCaseSuccessor(); |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3518 | |
| 3519 | int PhiIndex; |
| 3520 | PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest, |
| 3521 | &PhiIndex); |
| 3522 | if (!PHI) continue; |
| 3523 | |
| 3524 | ForwardingNodes[PHI].push_back(PhiIndex); |
| 3525 | } |
| 3526 | |
| 3527 | bool Changed = false; |
| 3528 | |
| 3529 | for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), |
| 3530 | E = ForwardingNodes.end(); I != E; ++I) { |
| 3531 | PHINode *Phi = I->first; |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3532 | SmallVectorImpl<int> &Indexes = I->second; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3533 | |
| 3534 | if (Indexes.size() < 2) continue; |
| 3535 | |
| 3536 | for (size_t I = 0, E = Indexes.size(); I != E; ++I) |
| 3537 | Phi->setIncomingValue(Indexes[I], SI->getCondition()); |
| 3538 | Changed = true; |
| 3539 | } |
| 3540 | |
| 3541 | return Changed; |
| 3542 | } |
| 3543 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3544 | /// Return true if the backend will be able to handle |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3545 | /// initializing an array of constants like C. |
Hans Wennborg | 08238ad | 2012-09-07 08:22:57 +0000 | [diff] [blame] | 3546 | static bool ValidLookupTableConstant(Constant *C) { |
Hans Wennborg | 4dc8951 | 2014-06-20 00:38:12 +0000 | [diff] [blame] | 3547 | if (C->isThreadDependent()) |
| 3548 | return false; |
| 3549 | if (C->isDLLImportDependent()) |
| 3550 | return false; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3551 | |
Hans Wennborg | b03ebfb | 2014-06-26 00:30:52 +0000 | [diff] [blame] | 3552 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) |
| 3553 | return CE->isGEPWithNoNotionalOverIndexing(); |
| 3554 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3555 | return isa<ConstantFP>(C) || |
| 3556 | isa<ConstantInt>(C) || |
| 3557 | isa<ConstantPointerNull>(C) || |
| 3558 | isa<GlobalValue>(C) || |
| 3559 | isa<UndefValue>(C); |
| 3560 | } |
| 3561 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3562 | /// If V is a Constant, return it. Otherwise, try to look up |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3563 | /// its constant value in ConstantPool, returning 0 if it's not there. |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3564 | static Constant *LookupConstant(Value *V, |
| 3565 | const SmallDenseMap<Value*, Constant*>& ConstantPool) { |
| 3566 | if (Constant *C = dyn_cast<Constant>(V)) |
| 3567 | return C; |
| 3568 | return ConstantPool.lookup(V); |
| 3569 | } |
| 3570 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3571 | /// Try to fold instruction I into a constant. This works for |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3572 | /// simple instructions such as binary operations where both operands are |
| 3573 | /// constant or can be replaced by constants from the ConstantPool. Returns the |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3574 | /// resulting constant on success, 0 otherwise. |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3575 | static Constant * |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3576 | ConstantFold(Instruction *I, const DataLayout &DL, |
| 3577 | const SmallDenseMap<Value *, Constant *> &ConstantPool) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3578 | if (SelectInst *Select = dyn_cast<SelectInst>(I)) { |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3579 | Constant *A = LookupConstant(Select->getCondition(), ConstantPool); |
| 3580 | if (!A) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3581 | return nullptr; |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3582 | if (A->isAllOnesValue()) |
| 3583 | return LookupConstant(Select->getTrueValue(), ConstantPool); |
| 3584 | if (A->isNullValue()) |
| 3585 | return LookupConstant(Select->getFalseValue(), ConstantPool); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3586 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3587 | } |
| 3588 | |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3589 | SmallVector<Constant *, 4> COps; |
| 3590 | for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { |
| 3591 | if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) |
| 3592 | COps.push_back(A); |
| 3593 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3594 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3595 | } |
| 3596 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3597 | if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3598 | return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], |
| 3599 | COps[1], DL); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3600 | } |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3601 | |
| 3602 | return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3603 | } |
| 3604 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3605 | /// Try to determine the resulting constant values in phi nodes |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3606 | /// at the common destination basic block, *CommonDest, for one of the case |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3607 | /// destionations CaseDest corresponding to value CaseVal (0 for the default |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3608 | /// case), of a switch instruction SI. |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3609 | static bool |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3610 | GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3611 | BasicBlock **CommonDest, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3612 | SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, |
| 3613 | const DataLayout &DL) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3614 | // The block from which we enter the common destination. |
| 3615 | BasicBlock *Pred = SI->getParent(); |
| 3616 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3617 | // If CaseDest is empty except for some side-effect free instructions through |
| 3618 | // which we can constant-propagate the CaseVal, continue to its successor. |
| 3619 | SmallDenseMap<Value*, Constant*> ConstantPool; |
| 3620 | ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); |
| 3621 | for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; |
| 3622 | ++I) { |
| 3623 | if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { |
| 3624 | // If the terminator is a simple branch, continue to the next block. |
| 3625 | if (T->getNumSuccessors() != 1) |
| 3626 | return false; |
| 3627 | Pred = CaseDest; |
| 3628 | CaseDest = T->getSuccessor(0); |
| 3629 | } else if (isa<DbgInfoIntrinsic>(I)) { |
| 3630 | // Skip debug intrinsic. |
| 3631 | continue; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3632 | } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3633 | // Instruction is side-effect free and constant. |
Hans Wennborg | dcc6e5b | 2015-01-09 22:13:31 +0000 | [diff] [blame] | 3634 | |
| 3635 | // If the instruction has uses outside this block or a phi node slot for |
| 3636 | // the block, it is not safe to bypass the instruction since it would then |
| 3637 | // no longer dominate all its uses. |
| 3638 | for (auto &Use : I->uses()) { |
| 3639 | User *User = Use.getUser(); |
| 3640 | if (Instruction *I = dyn_cast<Instruction>(User)) |
| 3641 | if (I->getParent() == CaseDest) |
| 3642 | continue; |
| 3643 | if (PHINode *Phi = dyn_cast<PHINode>(User)) |
| 3644 | if (Phi->getIncomingBlock(Use) == CaseDest) |
| 3645 | continue; |
| 3646 | return false; |
| 3647 | } |
| 3648 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3649 | ConstantPool.insert(std::make_pair(I, C)); |
| 3650 | } else { |
| 3651 | break; |
| 3652 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3653 | } |
| 3654 | |
| 3655 | // If we did not have a CommonDest before, use the current one. |
| 3656 | if (!*CommonDest) |
| 3657 | *CommonDest = CaseDest; |
| 3658 | // If the destination isn't the common one, abort. |
| 3659 | if (CaseDest != *CommonDest) |
| 3660 | return false; |
| 3661 | |
| 3662 | // Get the values for this case from phi nodes in the destination block. |
| 3663 | BasicBlock::iterator I = (*CommonDest)->begin(); |
| 3664 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3665 | int Idx = PHI->getBasicBlockIndex(Pred); |
| 3666 | if (Idx == -1) |
| 3667 | continue; |
| 3668 | |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3669 | Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx), |
| 3670 | ConstantPool); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3671 | if (!ConstVal) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3672 | return false; |
| 3673 | |
| 3674 | // Be conservative about which kinds of constants we support. |
| 3675 | if (!ValidLookupTableConstant(ConstVal)) |
| 3676 | return false; |
| 3677 | |
| 3678 | Res.push_back(std::make_pair(PHI, ConstVal)); |
| 3679 | } |
| 3680 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3681 | return Res.size() > 0; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3682 | } |
| 3683 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3684 | // Helper function used to add CaseVal to the list of cases that generate |
| 3685 | // Result. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3686 | static void MapCaseToResult(ConstantInt *CaseVal, |
| 3687 | SwitchCaseResultVectorTy &UniqueResults, |
| 3688 | Constant *Result) { |
| 3689 | for (auto &I : UniqueResults) { |
| 3690 | if (I.first == Result) { |
| 3691 | I.second.push_back(CaseVal); |
| 3692 | return; |
| 3693 | } |
| 3694 | } |
| 3695 | UniqueResults.push_back(std::make_pair(Result, |
| 3696 | SmallVector<ConstantInt*, 4>(1, CaseVal))); |
| 3697 | } |
| 3698 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3699 | // Helper function that initializes a map containing |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3700 | // results for the PHI node of the common destination block for a switch |
| 3701 | // instruction. Returns false if multiple PHI nodes have been found or if |
| 3702 | // there is not a common destination block for the switch. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3703 | static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, |
| 3704 | BasicBlock *&CommonDest, |
| 3705 | SwitchCaseResultVectorTy &UniqueResults, |
| 3706 | Constant *&DefaultResult, |
| 3707 | const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3708 | for (auto &I : SI->cases()) { |
| 3709 | ConstantInt *CaseVal = I.getCaseValue(); |
| 3710 | |
| 3711 | // Resulting value at phi nodes for this case value. |
| 3712 | SwitchCaseResultsTy Results; |
| 3713 | if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, |
| 3714 | DL)) |
| 3715 | return false; |
| 3716 | |
| 3717 | // Only one value per case is permitted |
| 3718 | if (Results.size() > 1) |
| 3719 | return false; |
| 3720 | MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); |
| 3721 | |
| 3722 | // Check the PHI consistency. |
| 3723 | if (!PHI) |
| 3724 | PHI = Results[0].first; |
| 3725 | else if (PHI != Results[0].first) |
| 3726 | return false; |
| 3727 | } |
| 3728 | // Find the default result value. |
| 3729 | SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; |
| 3730 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
| 3731 | GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, |
| 3732 | DL); |
| 3733 | // If the default value is not found abort unless the default destination |
| 3734 | // is unreachable. |
| 3735 | DefaultResult = |
| 3736 | DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; |
| 3737 | if ((!DefaultResult && |
| 3738 | !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) |
| 3739 | return false; |
| 3740 | |
| 3741 | return true; |
| 3742 | } |
| 3743 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3744 | // Helper function that checks if it is possible to transform a switch with only |
| 3745 | // 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] | 3746 | // Example: |
| 3747 | // switch (a) { |
| 3748 | // case 10: %0 = icmp eq i32 %a, 10 |
| 3749 | // return 10; %1 = select i1 %0, i32 10, i32 4 |
| 3750 | // case 20: ----> %2 = icmp eq i32 %a, 20 |
| 3751 | // return 2; %3 = select i1 %2, i32 2, i32 %1 |
| 3752 | // default: |
| 3753 | // return 4; |
| 3754 | // } |
| 3755 | static Value * |
| 3756 | ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, |
| 3757 | Constant *DefaultResult, Value *Condition, |
| 3758 | IRBuilder<> &Builder) { |
| 3759 | assert(ResultVector.size() == 2 && |
| 3760 | "We should have exactly two unique results at this point"); |
| 3761 | // If we are selecting between only two cases transform into a simple |
| 3762 | // select or a two-way select if default is possible. |
| 3763 | if (ResultVector[0].second.size() == 1 && |
| 3764 | ResultVector[1].second.size() == 1) { |
| 3765 | ConstantInt *const FirstCase = ResultVector[0].second[0]; |
| 3766 | ConstantInt *const SecondCase = ResultVector[1].second[0]; |
| 3767 | |
| 3768 | bool DefaultCanTrigger = DefaultResult; |
| 3769 | Value *SelectValue = ResultVector[1].first; |
| 3770 | if (DefaultCanTrigger) { |
| 3771 | Value *const ValueCompare = |
| 3772 | Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); |
| 3773 | SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, |
| 3774 | DefaultResult, "switch.select"); |
| 3775 | } |
| 3776 | Value *const ValueCompare = |
| 3777 | Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); |
| 3778 | return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue, |
| 3779 | "switch.select"); |
| 3780 | } |
| 3781 | |
| 3782 | return nullptr; |
| 3783 | } |
| 3784 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3785 | // Helper function to cleanup a switch instruction that has been converted into |
| 3786 | // a select, fixing up PHI nodes and basic blocks. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3787 | static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, |
| 3788 | Value *SelectValue, |
| 3789 | IRBuilder<> &Builder) { |
| 3790 | BasicBlock *SelectBB = SI->getParent(); |
| 3791 | while (PHI->getBasicBlockIndex(SelectBB) >= 0) |
| 3792 | PHI->removeIncomingValue(SelectBB); |
| 3793 | PHI->addIncoming(SelectValue, SelectBB); |
| 3794 | |
| 3795 | Builder.CreateBr(PHI->getParent()); |
| 3796 | |
| 3797 | // Remove the switch. |
| 3798 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
| 3799 | BasicBlock *Succ = SI->getSuccessor(i); |
| 3800 | |
| 3801 | if (Succ == PHI->getParent()) |
| 3802 | continue; |
| 3803 | Succ->removePredecessor(SelectBB); |
| 3804 | } |
| 3805 | SI->eraseFromParent(); |
| 3806 | } |
| 3807 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3808 | /// If the switch is only used to initialize one or more |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3809 | /// phi nodes in a common successor block with only two different |
| 3810 | /// constant values, replace the switch with select. |
| 3811 | static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3812 | AssumptionCache *AC, const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3813 | Value *const Cond = SI->getCondition(); |
| 3814 | PHINode *PHI = nullptr; |
| 3815 | BasicBlock *CommonDest = nullptr; |
| 3816 | Constant *DefaultResult; |
| 3817 | SwitchCaseResultVectorTy UniqueResults; |
| 3818 | // 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] | 3819 | if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, |
| 3820 | DL)) |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3821 | return false; |
| 3822 | // Selects choose between maximum two values. |
| 3823 | if (UniqueResults.size() != 2) |
| 3824 | return false; |
| 3825 | assert(PHI != nullptr && "PHI for value select not found"); |
| 3826 | |
| 3827 | Builder.SetInsertPoint(SI); |
| 3828 | Value *SelectValue = ConvertTwoCaseSwitch( |
| 3829 | UniqueResults, |
| 3830 | DefaultResult, Cond, Builder); |
| 3831 | if (SelectValue) { |
| 3832 | RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); |
| 3833 | return true; |
| 3834 | } |
| 3835 | // The switch couldn't be converted into a select. |
| 3836 | return false; |
| 3837 | } |
| 3838 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3839 | namespace { |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3840 | /// This class represents a lookup table that can be used to replace a switch. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3841 | class SwitchLookupTable { |
| 3842 | public: |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3843 | /// Create a lookup table to use as a switch replacement with the contents |
| 3844 | /// of Values, using DefaultValue to fill any holes in the table. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3845 | SwitchLookupTable( |
| 3846 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 3847 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 3848 | Constant *DefaultValue, const DataLayout &DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3849 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3850 | /// Build instructions with Builder to retrieve the value at |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3851 | /// the position given by Index in the lookup table. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 3852 | Value *BuildLookup(Value *Index, IRBuilder<> &Builder); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3853 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3854 | /// Return true if a table with TableSize elements of |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3855 | /// type ElementType would fit in a target-legal register. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3856 | static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 3857 | Type *ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3858 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3859 | private: |
| 3860 | // Depending on the contents of the table, it can be represented in |
| 3861 | // different ways. |
| 3862 | enum { |
| 3863 | // For tables where each element contains the same value, we just have to |
| 3864 | // store that single value and return it for each lookup. |
| 3865 | SingleValueKind, |
| 3866 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3867 | // For tables where there is a linear relationship between table index |
| 3868 | // and values. We calculate the result with a simple multiplication |
| 3869 | // and addition instead of a table lookup. |
| 3870 | LinearMapKind, |
| 3871 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3872 | // For small tables with integer elements, we can pack them into a bitmap |
| 3873 | // that fits into a target-legal register. Values are retrieved by |
| 3874 | // shift and mask operations. |
| 3875 | BitMapKind, |
| 3876 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3877 | // The table is stored as an array of values. Values are retrieved by load |
| 3878 | // instructions from the table. |
| 3879 | ArrayKind |
| 3880 | } Kind; |
| 3881 | |
| 3882 | // For SingleValueKind, this is the single value. |
| 3883 | Constant *SingleValue; |
| 3884 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3885 | // For BitMapKind, this is the bitmap. |
| 3886 | ConstantInt *BitMap; |
| 3887 | IntegerType *BitMapElementTy; |
| 3888 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3889 | // For LinearMapKind, these are the constants used to derive the value. |
| 3890 | ConstantInt *LinearOffset; |
| 3891 | ConstantInt *LinearMultiplier; |
| 3892 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3893 | // For ArrayKind, this is the array. |
| 3894 | GlobalVariable *Array; |
| 3895 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 3896 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3897 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3898 | SwitchLookupTable::SwitchLookupTable( |
| 3899 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 3900 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 3901 | Constant *DefaultValue, const DataLayout &DL) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3902 | : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3903 | LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 3904 | assert(Values.size() && "Can't build lookup table without values!"); |
| 3905 | assert(TableSize >= Values.size() && "Can't fit values in table!"); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3906 | |
| 3907 | // If all values in the table are equal, this is that value. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3908 | SingleValue = Values.begin()->second; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3909 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3910 | Type *ValueType = Values.begin()->second->getType(); |
| 3911 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3912 | // Build up the table contents. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3913 | SmallVector<Constant*, 64> TableContents(TableSize); |
| 3914 | for (size_t I = 0, E = Values.size(); I != E; ++I) { |
| 3915 | ConstantInt *CaseVal = Values[I].first; |
| 3916 | Constant *CaseRes = Values[I].second; |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3917 | assert(CaseRes->getType() == ValueType); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3918 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3919 | uint64_t Idx = (CaseVal->getValue() - Offset->getValue()) |
| 3920 | .getLimitedValue(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3921 | TableContents[Idx] = CaseRes; |
| 3922 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3923 | if (CaseRes != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3924 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3925 | } |
| 3926 | |
| 3927 | // Fill in any holes in the table with the default result. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3928 | if (Values.size() < TableSize) { |
Marcello Maggioni | 89c05ad | 2014-07-03 08:29:06 +0000 | [diff] [blame] | 3929 | assert(DefaultValue && |
| 3930 | "Need a default value to fill the lookup table holes."); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3931 | assert(DefaultValue->getType() == ValueType); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3932 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 3933 | if (!TableContents[I]) |
| 3934 | TableContents[I] = DefaultValue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3935 | } |
| 3936 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3937 | if (DefaultValue != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3938 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3939 | } |
| 3940 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3941 | // If each element in the table contains the same value, we only need to store |
| 3942 | // that single value. |
| 3943 | if (SingleValue) { |
| 3944 | Kind = SingleValueKind; |
| 3945 | return; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3946 | } |
| 3947 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3948 | // Check if we can derive the value with a linear transformation from the |
| 3949 | // table index. |
| 3950 | if (isa<IntegerType>(ValueType)) { |
| 3951 | bool LinearMappingPossible = true; |
| 3952 | APInt PrevVal; |
| 3953 | APInt DistToPrev; |
| 3954 | assert(TableSize >= 2 && "Should be a SingleValue table."); |
| 3955 | // Check if there is the same distance between two consecutive values. |
| 3956 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 3957 | ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); |
| 3958 | if (!ConstVal) { |
| 3959 | // This is an undef. We could deal with it, but undefs in lookup tables |
| 3960 | // are very seldom. It's probably not worth the additional complexity. |
| 3961 | LinearMappingPossible = false; |
| 3962 | break; |
| 3963 | } |
| 3964 | APInt Val = ConstVal->getValue(); |
| 3965 | if (I != 0) { |
| 3966 | APInt Dist = Val - PrevVal; |
| 3967 | if (I == 1) { |
| 3968 | DistToPrev = Dist; |
| 3969 | } else if (Dist != DistToPrev) { |
| 3970 | LinearMappingPossible = false; |
| 3971 | break; |
| 3972 | } |
| 3973 | } |
| 3974 | PrevVal = Val; |
| 3975 | } |
| 3976 | if (LinearMappingPossible) { |
| 3977 | LinearOffset = cast<ConstantInt>(TableContents[0]); |
| 3978 | LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); |
| 3979 | Kind = LinearMapKind; |
| 3980 | ++NumLinearMaps; |
| 3981 | return; |
| 3982 | } |
| 3983 | } |
| 3984 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3985 | // 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] | 3986 | if (WouldFitInRegister(DL, TableSize, ValueType)) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3987 | IntegerType *IT = cast<IntegerType>(ValueType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3988 | APInt TableInt(TableSize * IT->getBitWidth(), 0); |
| 3989 | for (uint64_t I = TableSize; I > 0; --I) { |
| 3990 | TableInt <<= IT->getBitWidth(); |
Benjamin Kramer | 9fc3dc7 | 2012-10-01 11:31:48 +0000 | [diff] [blame] | 3991 | // Insert values into the bitmap. Undef values are set to zero. |
| 3992 | if (!isa<UndefValue>(TableContents[I - 1])) { |
| 3993 | ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); |
| 3994 | TableInt |= Val->getValue().zext(TableInt.getBitWidth()); |
| 3995 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3996 | } |
| 3997 | BitMap = ConstantInt::get(M.getContext(), TableInt); |
| 3998 | BitMapElementTy = IT; |
| 3999 | Kind = BitMapKind; |
| 4000 | ++NumBitMaps; |
| 4001 | return; |
| 4002 | } |
| 4003 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4004 | // Store the table in an array. |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4005 | ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4006 | Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); |
| 4007 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4008 | Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true, |
| 4009 | GlobalVariable::PrivateLinkage, |
| 4010 | Initializer, |
| 4011 | "switch.table"); |
| 4012 | Array->setUnnamedAddr(true); |
| 4013 | Kind = ArrayKind; |
| 4014 | } |
| 4015 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4016 | Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4017 | switch (Kind) { |
| 4018 | case SingleValueKind: |
| 4019 | return SingleValue; |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4020 | case LinearMapKind: { |
| 4021 | // Derive the result value from the input value. |
| 4022 | Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), |
| 4023 | false, "switch.idx.cast"); |
| 4024 | if (!LinearMultiplier->isOne()) |
| 4025 | Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); |
| 4026 | if (!LinearOffset->isZero()) |
| 4027 | Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); |
| 4028 | return Result; |
| 4029 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4030 | case BitMapKind: { |
| 4031 | // Type of the bitmap (e.g. i59). |
| 4032 | IntegerType *MapTy = BitMap->getType(); |
| 4033 | |
| 4034 | // Cast Index to the same type as the bitmap. |
| 4035 | // Note: The Index is <= the number of elements in the table, so |
| 4036 | // truncating it to the width of the bitmask is safe. |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 4037 | Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4038 | |
| 4039 | // Multiply the shift amount by the element width. |
| 4040 | ShiftAmt = Builder.CreateMul(ShiftAmt, |
| 4041 | ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), |
| 4042 | "switch.shiftamt"); |
| 4043 | |
| 4044 | // Shift down. |
| 4045 | Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt, |
| 4046 | "switch.downshift"); |
| 4047 | // Mask off. |
| 4048 | return Builder.CreateTrunc(DownShifted, BitMapElementTy, |
| 4049 | "switch.masked"); |
| 4050 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4051 | case ArrayKind: { |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4052 | // Make sure the table index will not overflow when treated as signed. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4053 | IntegerType *IT = cast<IntegerType>(Index->getType()); |
| 4054 | uint64_t TableSize = Array->getInitializer()->getType() |
| 4055 | ->getArrayNumElements(); |
| 4056 | if (TableSize > (1ULL << (IT->getBitWidth() - 1))) |
| 4057 | Index = Builder.CreateZExt(Index, |
| 4058 | IntegerType::get(IT->getContext(), |
| 4059 | IT->getBitWidth() + 1), |
| 4060 | "switch.tableidx.zext"); |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4061 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4062 | Value *GEPIndices[] = { Builder.getInt32(0), Index }; |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 4063 | Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, |
| 4064 | GEPIndices, "switch.gep"); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4065 | return Builder.CreateLoad(GEP, "switch.load"); |
| 4066 | } |
| 4067 | } |
| 4068 | llvm_unreachable("Unknown lookup table kind!"); |
| 4069 | } |
| 4070 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4071 | bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4072 | uint64_t TableSize, |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 4073 | Type *ElementType) { |
| 4074 | auto *IT = dyn_cast<IntegerType>(ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4075 | if (!IT) |
| 4076 | return false; |
| 4077 | // FIXME: If the type is wider than it needs to be, e.g. i8 but all values |
| 4078 | // are <= 15, we could try to narrow the type. |
Benjamin Kramer | c2081d1 | 2012-09-27 18:29:58 +0000 | [diff] [blame] | 4079 | |
| 4080 | // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. |
| 4081 | if (TableSize >= UINT_MAX/IT->getBitWidth()) |
| 4082 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4083 | return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4084 | } |
| 4085 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4086 | /// Determine whether a lookup table should be built for this switch, based on |
| 4087 | /// 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] | 4088 | static bool |
| 4089 | ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, |
| 4090 | const TargetTransformInfo &TTI, const DataLayout &DL, |
| 4091 | const SmallDenseMap<PHINode *, Type *> &ResultTypes) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 4092 | if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) |
| 4093 | return false; // TableSize overflowed, or mul below might overflow. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4094 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4095 | bool AllTablesFitInRegister = true; |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4096 | bool HasIllegalType = false; |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4097 | for (const auto &I : ResultTypes) { |
| 4098 | Type *Ty = I.second; |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4099 | |
| 4100 | // Saturate this flag to true. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4101 | HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4102 | |
| 4103 | // Saturate this flag to false. |
| 4104 | AllTablesFitInRegister = AllTablesFitInRegister && |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4105 | SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4106 | |
| 4107 | // If both flags saturate, we're done. NOTE: This *only* works with |
| 4108 | // saturating flags, and all flags have to saturate first due to the |
| 4109 | // non-deterministic behavior of iterating over a dense map. |
| 4110 | if (HasIllegalType && !AllTablesFitInRegister) |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4111 | break; |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4112 | } |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4113 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4114 | // If each table would fit in a register, we should build it anyway. |
| 4115 | if (AllTablesFitInRegister) |
| 4116 | return true; |
| 4117 | |
| 4118 | // Don't build a table that doesn't fit in-register if it has illegal types. |
| 4119 | if (HasIllegalType) |
| 4120 | return false; |
| 4121 | |
| 4122 | // The table density should be at least 40%. This is the same criterion as for |
| 4123 | // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. |
| 4124 | // FIXME: Find the best cut-off. |
| 4125 | return SI->getNumCases() * 10 >= TableSize * 4; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4126 | } |
| 4127 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4128 | /// Try to reuse the switch table index compare. Following pattern: |
| 4129 | /// \code |
| 4130 | /// if (idx < tablesize) |
| 4131 | /// r = table[idx]; // table does not contain default_value |
| 4132 | /// else |
| 4133 | /// r = default_value; |
| 4134 | /// if (r != default_value) |
| 4135 | /// ... |
| 4136 | /// \endcode |
| 4137 | /// Is optimized to: |
| 4138 | /// \code |
| 4139 | /// cond = idx < tablesize; |
| 4140 | /// if (cond) |
| 4141 | /// r = table[idx]; |
| 4142 | /// else |
| 4143 | /// r = default_value; |
| 4144 | /// if (cond) |
| 4145 | /// ... |
| 4146 | /// \endcode |
| 4147 | /// Jump threading will then eliminate the second if(cond). |
| 4148 | static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, |
| 4149 | BranchInst *RangeCheckBranch, Constant *DefaultValue, |
| 4150 | const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) { |
| 4151 | |
| 4152 | ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); |
| 4153 | if (!CmpInst) |
| 4154 | return; |
| 4155 | |
| 4156 | // We require that the compare is in the same block as the phi so that jump |
| 4157 | // threading can do its work afterwards. |
| 4158 | if (CmpInst->getParent() != PhiBlock) |
| 4159 | return; |
| 4160 | |
| 4161 | Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); |
| 4162 | if (!CmpOp1) |
| 4163 | return; |
| 4164 | |
| 4165 | Value *RangeCmp = RangeCheckBranch->getCondition(); |
| 4166 | Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); |
| 4167 | Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); |
| 4168 | |
| 4169 | // Check if the compare with the default value is constant true or false. |
| 4170 | Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4171 | DefaultValue, CmpOp1, true); |
| 4172 | if (DefaultConst != TrueConst && DefaultConst != FalseConst) |
| 4173 | return; |
| 4174 | |
| 4175 | // Check if the compare with the case values is distinct from the default |
| 4176 | // compare result. |
| 4177 | for (auto ValuePair : Values) { |
| 4178 | Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4179 | ValuePair.second, CmpOp1, true); |
| 4180 | if (!CaseConst || CaseConst == DefaultConst) |
| 4181 | return; |
| 4182 | assert((CaseConst == TrueConst || CaseConst == FalseConst) && |
| 4183 | "Expect true or false as compare result."); |
| 4184 | } |
| 4185 | |
| 4186 | // Check if the branch instruction dominates the phi node. It's a simple |
| 4187 | // dominance check, but sufficient for our needs. |
| 4188 | // Although this check is invariant in the calling loops, it's better to do it |
| 4189 | // at this late stage. Practically we do it at most once for a switch. |
| 4190 | BasicBlock *BranchBlock = RangeCheckBranch->getParent(); |
| 4191 | for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { |
| 4192 | BasicBlock *Pred = *PI; |
| 4193 | if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) |
| 4194 | return; |
| 4195 | } |
| 4196 | |
| 4197 | if (DefaultConst == FalseConst) { |
| 4198 | // The compare yields the same result. We can replace it. |
| 4199 | CmpInst->replaceAllUsesWith(RangeCmp); |
| 4200 | ++NumTableCmpReuses; |
| 4201 | } else { |
| 4202 | // The compare yields the same result, just inverted. We can replace it. |
| 4203 | Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp, |
| 4204 | ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", |
| 4205 | RangeCheckBranch); |
| 4206 | CmpInst->replaceAllUsesWith(InvertedTableCmp); |
| 4207 | ++NumTableCmpReuses; |
| 4208 | } |
| 4209 | } |
| 4210 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4211 | /// If the switch is only used to initialize one or more phi nodes in a common |
| 4212 | /// successor block with different constant values, replace the switch with |
| 4213 | /// lookup tables. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4214 | static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, |
| 4215 | const DataLayout &DL, |
| 4216 | const TargetTransformInfo &TTI) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4217 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4218 | |
Hans Wennborg | c3c8d95 | 2012-11-07 21:35:12 +0000 | [diff] [blame] | 4219 | // Only build lookup table when we have a target that supports it. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4220 | if (!TTI.shouldBuildLookupTables()) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4221 | return false; |
| 4222 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4223 | // FIXME: If the switch is too sparse for a lookup table, perhaps we could |
| 4224 | // split off a dense part and build a lookup table for that. |
| 4225 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4226 | // FIXME: This creates arrays of GEPs to constant strings, which means each |
| 4227 | // GEP needs a runtime relocation in PIC code. We should just build one big |
| 4228 | // string and lookup indices into that. |
| 4229 | |
Hans Wennborg | 4744ac1 | 2014-01-15 05:00:27 +0000 | [diff] [blame] | 4230 | // Ignore switches with less than three cases. Lookup tables will not make them |
| 4231 | // faster, so we don't analyze them. |
| 4232 | if (SI->getNumCases() < 3) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4233 | return false; |
| 4234 | |
| 4235 | // 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] | 4236 | // common destination, as well as the min and max case values. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4237 | assert(SI->case_begin() != SI->case_end()); |
| 4238 | SwitchInst::CaseIt CI = SI->case_begin(); |
| 4239 | ConstantInt *MinCaseVal = CI.getCaseValue(); |
| 4240 | ConstantInt *MaxCaseVal = CI.getCaseValue(); |
| 4241 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4242 | BasicBlock *CommonDest = nullptr; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4243 | typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4244 | SmallDenseMap<PHINode*, ResultListTy> ResultLists; |
| 4245 | SmallDenseMap<PHINode*, Constant*> DefaultResults; |
| 4246 | SmallDenseMap<PHINode*, Type*> ResultTypes; |
| 4247 | SmallVector<PHINode*, 4> PHIs; |
| 4248 | |
| 4249 | for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { |
| 4250 | ConstantInt *CaseVal = CI.getCaseValue(); |
| 4251 | if (CaseVal->getValue().slt(MinCaseVal->getValue())) |
| 4252 | MinCaseVal = CaseVal; |
| 4253 | if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) |
| 4254 | MaxCaseVal = CaseVal; |
| 4255 | |
| 4256 | // Resulting value at phi nodes for this case value. |
| 4257 | typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy; |
| 4258 | ResultsTy Results; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4259 | if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4260 | Results, DL)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4261 | return false; |
| 4262 | |
| 4263 | // Append the result from this case to the list for each phi. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4264 | for (const auto &I : Results) { |
| 4265 | PHINode *PHI = I.first; |
| 4266 | Constant *Value = I.second; |
| 4267 | if (!ResultLists.count(PHI)) |
| 4268 | PHIs.push_back(PHI); |
| 4269 | ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4270 | } |
| 4271 | } |
| 4272 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4273 | // Keep track of the result types. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4274 | for (PHINode *PHI : PHIs) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4275 | ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); |
| 4276 | } |
| 4277 | |
| 4278 | uint64_t NumResults = ResultLists[PHIs[0]].size(); |
| 4279 | APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); |
| 4280 | uint64_t TableSize = RangeSpread.getLimitedValue() + 1; |
| 4281 | bool TableHasHoles = (NumResults < TableSize); |
| 4282 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4283 | // If the table has holes, we need a constant result for the default case |
| 4284 | // or a bitmask that fits in a register. |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4285 | SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4286 | bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(), |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4287 | &CommonDest, DefaultResultsList, DL); |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4288 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4289 | bool NeedMask = (TableHasHoles && !HasDefaultResults); |
| 4290 | if (NeedMask) { |
| 4291 | // As an extra penalty for the validity test we require more cases. |
| 4292 | if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). |
| 4293 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4294 | if (!DL.fitsInLegalInteger(TableSize)) |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4295 | return false; |
| 4296 | } |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4297 | |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4298 | for (const auto &I : DefaultResultsList) { |
| 4299 | PHINode *PHI = I.first; |
| 4300 | Constant *Result = I.second; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4301 | DefaultResults[PHI] = Result; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4302 | } |
| 4303 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4304 | if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4305 | return false; |
| 4306 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4307 | // Create the BB that does the lookups. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4308 | Module &Mod = *CommonDest->getParent()->getParent(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4309 | BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4310 | "switch.lookup", |
| 4311 | CommonDest->getParent(), |
| 4312 | CommonDest); |
| 4313 | |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4314 | // Compute the table index value. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4315 | Builder.SetInsertPoint(SI); |
| 4316 | Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, |
| 4317 | "switch.tableidx"); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4318 | |
| 4319 | // Compute the maximum table size representable by the integer type we are |
| 4320 | // switching upon. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4321 | unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4322 | uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4323 | assert(MaxTableSize >= TableSize && |
| 4324 | "It is impossible for a switch to have more entries than the max " |
| 4325 | "representable value of its input integer type's size."); |
| 4326 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 4327 | // If the default destination is unreachable, or if the lookup table covers |
| 4328 | // all values of the conditional variable, branch directly to the lookup table |
| 4329 | // BB. Otherwise, check that the condition is within the case range. |
| 4330 | const bool DefaultIsReachable = |
| 4331 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
| 4332 | const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4333 | BranchInst *RangeCheckBranch = nullptr; |
| 4334 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 4335 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4336 | Builder.CreateBr(LookupBB); |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 4337 | // Note: We call removeProdecessor later since we need to be able to get the |
| 4338 | // 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] | 4339 | } else { |
| 4340 | Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get( |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4341 | MinCaseVal->getType(), TableSize)); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4342 | RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4343 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4344 | |
| 4345 | // Populate the BB that does the lookups. |
| 4346 | Builder.SetInsertPoint(LookupBB); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4347 | |
| 4348 | if (NeedMask) { |
| 4349 | // Before doing the lookup we do the hole check. |
| 4350 | // The LookupBB is therefore re-purposed to do the hole check |
| 4351 | // and we create a new LookupBB. |
| 4352 | BasicBlock *MaskBB = LookupBB; |
| 4353 | MaskBB->setName("switch.hole_check"); |
| 4354 | LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4355 | "switch.lookup", |
| 4356 | CommonDest->getParent(), |
| 4357 | CommonDest); |
| 4358 | |
Juergen Ributzka | c9591e9 | 2014-11-17 19:39:56 +0000 | [diff] [blame] | 4359 | // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid |
| 4360 | // unnecessary illegal types. |
| 4361 | uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); |
| 4362 | APInt MaskInt(TableSizePowOf2, 0); |
| 4363 | APInt One(TableSizePowOf2, 1); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4364 | // Build bitmask; fill in a 1 bit for every case. |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4365 | const ResultListTy &ResultList = ResultLists[PHIs[0]]; |
| 4366 | for (size_t I = 0, E = ResultList.size(); I != E; ++I) { |
| 4367 | uint64_t Idx = (ResultList[I].first->getValue() - |
| 4368 | MinCaseVal->getValue()).getLimitedValue(); |
| 4369 | MaskInt |= One << Idx; |
| 4370 | } |
| 4371 | ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); |
| 4372 | |
| 4373 | // Get the TableIndex'th bit of the bitmask. |
| 4374 | // If this bit is 0 (meaning hole) jump to the default destination, |
| 4375 | // else continue with table lookup. |
| 4376 | IntegerType *MapTy = TableMask->getType(); |
| 4377 | Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy, |
| 4378 | "switch.maskindex"); |
| 4379 | Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, |
| 4380 | "switch.shifted"); |
| 4381 | Value *LoBit = Builder.CreateTrunc(Shifted, |
| 4382 | Type::getInt1Ty(Mod.getContext()), |
| 4383 | "switch.lobit"); |
| 4384 | Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); |
| 4385 | |
| 4386 | Builder.SetInsertPoint(LookupBB); |
| 4387 | AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); |
| 4388 | } |
| 4389 | |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 4390 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
| 4391 | // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, |
| 4392 | // do not delete PHINodes here. |
| 4393 | SI->getDefaultDest()->removePredecessor(SI->getParent(), |
| 4394 | /*DontDeleteUselessPHIs=*/true); |
| 4395 | } |
| 4396 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4397 | bool ReturnedEarly = false; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4398 | for (size_t I = 0, E = PHIs.size(); I != E; ++I) { |
| 4399 | PHINode *PHI = PHIs[I]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4400 | const ResultListTy &ResultList = ResultLists[PHI]; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4401 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4402 | // If using a bitmask, use any value to fill the lookup table holes. |
| 4403 | Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4404 | SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4405 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4406 | Value *Result = Table.BuildLookup(TableIndex, Builder); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4407 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4408 | // If the result is used to return immediately from the function, we want to |
| 4409 | // do that right here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4410 | if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && |
| 4411 | PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4412 | Builder.CreateRet(Result); |
| 4413 | ReturnedEarly = true; |
| 4414 | break; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4415 | } |
| 4416 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4417 | // Do a small peephole optimization: re-use the switch table compare if |
| 4418 | // possible. |
| 4419 | if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { |
| 4420 | BasicBlock *PhiBlock = PHI->getParent(); |
| 4421 | // Search for compare instructions which use the phi. |
| 4422 | for (auto *User : PHI->users()) { |
| 4423 | reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); |
| 4424 | } |
| 4425 | } |
| 4426 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4427 | PHI->addIncoming(Result, LookupBB); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4428 | } |
| 4429 | |
| 4430 | if (!ReturnedEarly) |
| 4431 | Builder.CreateBr(CommonDest); |
| 4432 | |
| 4433 | // Remove the switch. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4434 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4435 | BasicBlock *Succ = SI->getSuccessor(i); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4436 | |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4437 | if (Succ == SI->getDefaultDest()) |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4438 | continue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4439 | Succ->removePredecessor(SI->getParent()); |
| 4440 | } |
| 4441 | SI->eraseFromParent(); |
| 4442 | |
| 4443 | ++NumLookupTables; |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4444 | if (NeedMask) |
| 4445 | ++NumLookupTablesHoles; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4446 | return true; |
| 4447 | } |
| 4448 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4449 | bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4450 | BasicBlock *BB = SI->getParent(); |
| 4451 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4452 | if (isValueEqualityComparison(SI)) { |
| 4453 | // If we only have one predecessor, and if it is a branch on this value, |
| 4454 | // see if that predecessor totally determines the outcome of this switch. |
| 4455 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 4456 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4457 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4458 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4459 | Value *Cond = SI->getCondition(); |
| 4460 | if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) |
| 4461 | if (SimplifySwitchOnSelect(SI, Select)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4462 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4463 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4464 | // If the block only contains the switch, see if we can fold the block |
| 4465 | // away into any preds. |
| 4466 | BasicBlock::iterator BBI = BB->begin(); |
| 4467 | // Ignore dbg intrinsics. |
| 4468 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 4469 | ++BBI; |
| 4470 | if (SI == &*BBI) |
| 4471 | if (FoldValueComparisonIntoPredecessors(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4472 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4473 | } |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4474 | |
| 4475 | // Try to transform the switch into an icmp and a branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4476 | if (TurnSwitchRangeIntoICmp(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4477 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4478 | |
| 4479 | // Remove unreachable cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4480 | if (EliminateDeadSwitchCases(SI, AC, DL)) |
| 4481 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4482 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4483 | if (SwitchToSelect(SI, Builder, AC, DL)) |
| 4484 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4485 | |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4486 | if (ForwardSwitchConditionToPHI(SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4487 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4488 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4489 | if (SwitchToLookupTable(SI, Builder, DL, TTI)) |
| 4490 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4491 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4492 | return false; |
| 4493 | } |
| 4494 | |
| 4495 | bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { |
| 4496 | BasicBlock *BB = IBI->getParent(); |
| 4497 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4498 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4499 | // Eliminate redundant destinations. |
| 4500 | SmallPtrSet<Value *, 8> Succs; |
| 4501 | for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { |
| 4502 | BasicBlock *Dest = IBI->getDestination(i); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4503 | if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4504 | Dest->removePredecessor(BB); |
| 4505 | IBI->removeDestination(i); |
| 4506 | --i; --e; |
| 4507 | Changed = true; |
| 4508 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4509 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4510 | |
| 4511 | if (IBI->getNumDestinations() == 0) { |
| 4512 | // If the indirectbr has no successors, change it to unreachable. |
| 4513 | new UnreachableInst(IBI->getContext(), IBI); |
| 4514 | EraseTerminatorInstAndDCECond(IBI); |
| 4515 | return true; |
| 4516 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4517 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4518 | if (IBI->getNumDestinations() == 1) { |
| 4519 | // If the indirectbr has one successor, change it to a direct branch. |
| 4520 | BranchInst::Create(IBI->getDestination(0), IBI); |
| 4521 | EraseTerminatorInstAndDCECond(IBI); |
| 4522 | return true; |
| 4523 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4524 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4525 | if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { |
| 4526 | if (SimplifyIndirectBrOnSelect(IBI, SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4527 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4528 | } |
| 4529 | return Changed; |
| 4530 | } |
| 4531 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 4532 | /// Given an block with only a single landing pad and a unconditional branch |
| 4533 | /// try to find another basic block which this one can be merged with. This |
| 4534 | /// handles cases where we have multiple invokes with unique landing pads, but |
| 4535 | /// a shared handler. |
| 4536 | /// |
| 4537 | /// We specifically choose to not worry about merging non-empty blocks |
| 4538 | /// here. That is a PRE/scheduling problem and is best solved elsewhere. In |
| 4539 | /// practice, the optimizer produces empty landing pad blocks quite frequently |
| 4540 | /// when dealing with exception dense code. (see: instcombine, gvn, if-else |
| 4541 | /// sinking in this file) |
| 4542 | /// |
| 4543 | /// This is primarily a code size optimization. We need to avoid performing |
| 4544 | /// any transform which might inhibit optimization (such as our ability to |
| 4545 | /// specialize a particular handler via tail commoning). We do this by not |
| 4546 | /// merging any blocks which require us to introduce a phi. Since the same |
| 4547 | /// values are flowing through both blocks, we don't loose any ability to |
| 4548 | /// specialize. If anything, we make such specialization more likely. |
| 4549 | /// |
| 4550 | /// TODO - This transformation could remove entries from a phi in the target |
| 4551 | /// block when the inputs in the phi are the same for the two blocks being |
| 4552 | /// merged. In some cases, this could result in removal of the PHI entirely. |
| 4553 | static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, |
| 4554 | BasicBlock *BB) { |
| 4555 | auto Succ = BB->getUniqueSuccessor(); |
| 4556 | assert(Succ); |
| 4557 | // If there's a phi in the successor block, we'd likely have to introduce |
| 4558 | // a phi into the merged landing pad block. |
| 4559 | if (isa<PHINode>(*Succ->begin())) |
| 4560 | return false; |
| 4561 | |
| 4562 | for (BasicBlock *OtherPred : predecessors(Succ)) { |
| 4563 | if (BB == OtherPred) |
| 4564 | continue; |
| 4565 | BasicBlock::iterator I = OtherPred->begin(); |
| 4566 | LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); |
| 4567 | if (!LPad2 || !LPad2->isIdenticalTo(LPad)) |
| 4568 | continue; |
| 4569 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) {} |
| 4570 | BranchInst *BI2 = dyn_cast<BranchInst>(I); |
| 4571 | if (!BI2 || !BI2->isIdenticalTo(BI)) |
| 4572 | continue; |
| 4573 | |
| 4574 | // We've found an identical block. Update our predeccessors to take that |
| 4575 | // path instead and make ourselves dead. |
| 4576 | SmallSet<BasicBlock *, 16> Preds; |
| 4577 | Preds.insert(pred_begin(BB), pred_end(BB)); |
| 4578 | for (BasicBlock *Pred : Preds) { |
| 4579 | InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); |
| 4580 | assert(II->getNormalDest() != BB && |
| 4581 | II->getUnwindDest() == BB && "unexpected successor"); |
| 4582 | II->setUnwindDest(OtherPred); |
| 4583 | } |
| 4584 | |
| 4585 | // The debug info in OtherPred doesn't cover the merged control flow that |
| 4586 | // used to go through BB. We need to delete it or update it. |
| 4587 | for (auto I = OtherPred->begin(), E = OtherPred->end(); |
| 4588 | I != E;) { |
| 4589 | Instruction &Inst = *I; I++; |
| 4590 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 4591 | Inst.eraseFromParent(); |
| 4592 | } |
| 4593 | |
| 4594 | SmallSet<BasicBlock *, 16> Succs; |
| 4595 | Succs.insert(succ_begin(BB), succ_end(BB)); |
| 4596 | for (BasicBlock *Succ : Succs) { |
| 4597 | Succ->removePredecessor(BB); |
| 4598 | } |
| 4599 | |
| 4600 | IRBuilder<> Builder(BI); |
| 4601 | Builder.CreateUnreachable(); |
| 4602 | BI->eraseFromParent(); |
| 4603 | return true; |
| 4604 | } |
| 4605 | return false; |
| 4606 | } |
| 4607 | |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 4608 | bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){ |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4609 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4610 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 4611 | if (SinkCommon && SinkThenElseCodeToEnd(BI)) |
| 4612 | return true; |
| 4613 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4614 | // If the Terminator is the only non-phi instruction, simplify the block. |
Rafael Espindola | d07cf40 | 2014-07-30 21:04:00 +0000 | [diff] [blame] | 4615 | BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4616 | if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && |
| 4617 | TryToSimplifyUncondBranchFromEmptyBlock(BB)) |
| 4618 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4619 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4620 | // If the only instruction in the block is a seteq/setne comparison |
| 4621 | // against a constant, try to simplify the block. |
| 4622 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) |
| 4623 | if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { |
| 4624 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) |
| 4625 | ; |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 4626 | if (I->isTerminator() && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4627 | TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, |
| 4628 | BonusInstThreshold, AC)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4629 | return true; |
| 4630 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4631 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 4632 | // See if we can merge an empty landing pad block with another which is |
| 4633 | // equivalent. |
| 4634 | if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { |
| 4635 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) {} |
| 4636 | if (I->isTerminator() && |
| 4637 | TryToMergeLandingPad(LPad, BI, BB)) |
| 4638 | return true; |
| 4639 | } |
| 4640 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 4641 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4642 | // branches to us and our successor, fold the comparison into the |
| 4643 | // predecessor and use logical operations to update the incoming value |
| 4644 | // for PHI nodes in common successor. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4645 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 4646 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4647 | return false; |
| 4648 | } |
| 4649 | |
| 4650 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4651 | bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4652 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4653 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4654 | // Conditional branch |
| 4655 | if (isValueEqualityComparison(BI)) { |
| 4656 | // If we only have one predecessor, and if it is a branch on this value, |
| 4657 | // see if that predecessor totally determines the outcome of this |
| 4658 | // switch. |
| 4659 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4660 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4661 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4662 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4663 | // This block must be empty, except for the setcond inst, if it exists. |
| 4664 | // Ignore dbg intrinsics. |
| 4665 | BasicBlock::iterator I = BB->begin(); |
| 4666 | // Ignore dbg intrinsics. |
| 4667 | while (isa<DbgInfoIntrinsic>(I)) |
| 4668 | ++I; |
| 4669 | if (&*I == BI) { |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4670 | if (FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4671 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4672 | } else if (&*I == cast<Instruction>(BI->getCondition())){ |
| 4673 | ++I; |
| 4674 | // Ignore dbg intrinsics. |
| 4675 | while (isa<DbgInfoIntrinsic>(I)) |
| 4676 | ++I; |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4677 | if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4678 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4679 | } |
| 4680 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4681 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4682 | // 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] | 4683 | if (SimplifyBranchOnICmpChain(BI, Builder, DL)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4684 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4685 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 4686 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4687 | // branches to us and one of our successors, fold the comparison into the |
| 4688 | // predecessor and use logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4689 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 4690 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4691 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4692 | // We have a conditional branch to two blocks that are only reachable |
| 4693 | // from BI. We know that the condbr dominates the two blocks, so see if |
| 4694 | // there is any identical code in the "then" and "else" blocks. If so, we |
| 4695 | // can hoist it up to the branching block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4696 | if (BI->getSuccessor(0)->getSinglePredecessor()) { |
| 4697 | if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4698 | if (HoistThenElseCodeToIf(BI, TTI)) |
| 4699 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4700 | } else { |
| 4701 | // If Successor #1 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4702 | // execute Successor #0 if it branches to Successor #1. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4703 | TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); |
| 4704 | if (Succ0TI->getNumSuccessors() == 1 && |
| 4705 | Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4706 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) |
| 4707 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4708 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4709 | } else if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4710 | // If Successor #0 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4711 | // execute Successor #1 if it branches to Successor #0. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4712 | TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); |
| 4713 | if (Succ1TI->getNumSuccessors() == 1 && |
| 4714 | Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4715 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) |
| 4716 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4717 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4718 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4719 | // If this is a branch on a phi node in the current block, thread control |
| 4720 | // through this block if any PHI node entries are constants. |
| 4721 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 4722 | if (PN->getParent() == BI->getParent()) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4723 | if (FoldCondBranchOnPHI(BI, DL)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4724 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4725 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4726 | // Scan predecessor blocks for conditional branches. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 4727 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 4728 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4729 | if (PBI != BI && PBI->isConditional()) |
| 4730 | if (SimplifyCondBranchToCondBranch(PBI, BI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4731 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4732 | |
| 4733 | return false; |
| 4734 | } |
| 4735 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4736 | /// Check if passing a value to an instruction will cause undefined behavior. |
| 4737 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { |
| 4738 | Constant *C = dyn_cast<Constant>(V); |
| 4739 | if (!C) |
| 4740 | return false; |
| 4741 | |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 4742 | if (I->use_empty()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4743 | return false; |
| 4744 | |
| 4745 | if (C->isNullValue()) { |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 4746 | // 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] | 4747 | User *Use = *I->user_begin(); |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4748 | |
| 4749 | // Now make sure that there are no instructions in between that can alter |
| 4750 | // control flow (eg. calls) |
| 4751 | for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i) |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4752 | if (i == I->getParent()->end() || i->mayHaveSideEffects()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4753 | return false; |
| 4754 | |
| 4755 | // Look through GEPs. A load from a GEP derived from NULL is still undefined |
| 4756 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) |
| 4757 | if (GEP->getPointerOperand() == I) |
| 4758 | return passingValueIsAlwaysUndefined(V, GEP); |
| 4759 | |
| 4760 | // Look through bitcasts. |
| 4761 | if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) |
| 4762 | return passingValueIsAlwaysUndefined(V, BC); |
| 4763 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4764 | // Load from null is undefined. |
| 4765 | if (LoadInst *LI = dyn_cast<LoadInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 4766 | if (!LI->isVolatile()) |
| 4767 | return LI->getPointerAddressSpace() == 0; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4768 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4769 | // Store to null is undefined. |
| 4770 | if (StoreInst *SI = dyn_cast<StoreInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 4771 | if (!SI->isVolatile()) |
| 4772 | return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4773 | } |
| 4774 | return false; |
| 4775 | } |
| 4776 | |
| 4777 | /// If BB has an incoming value that will always trigger undefined behavior |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 4778 | /// (eg. null pointer dereference), remove the branch leading here. |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4779 | static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { |
| 4780 | for (BasicBlock::iterator i = BB->begin(); |
| 4781 | PHINode *PHI = dyn_cast<PHINode>(i); ++i) |
| 4782 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
| 4783 | if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { |
| 4784 | TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); |
| 4785 | IRBuilder<> Builder(T); |
| 4786 | if (BranchInst *BI = dyn_cast<BranchInst>(T)) { |
| 4787 | BB->removePredecessor(PHI->getIncomingBlock(i)); |
| 4788 | // Turn uncoditional branches into unreachables and remove the dead |
| 4789 | // destination from conditional branches. |
| 4790 | if (BI->isUnconditional()) |
| 4791 | Builder.CreateUnreachable(); |
| 4792 | else |
| 4793 | Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) : |
| 4794 | BI->getSuccessor(0)); |
| 4795 | BI->eraseFromParent(); |
| 4796 | return true; |
| 4797 | } |
| 4798 | // TODO: SwitchInst. |
| 4799 | } |
| 4800 | |
| 4801 | return false; |
| 4802 | } |
| 4803 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4804 | bool SimplifyCFGOpt::run(BasicBlock *BB) { |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 4805 | bool Changed = false; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4806 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 4807 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4808 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4809 | |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 4810 | // Remove basic blocks that have no predecessors (except the entry block)... |
| 4811 | // or that just have themself as a predecessor. These are unreachable. |
Ramkumar Ramachandra | 181233b | 2015-01-13 04:17:47 +0000 | [diff] [blame] | 4812 | if ((pred_empty(BB) && |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 4813 | BB != &BB->getParent()->getEntryBlock()) || |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 4814 | BB->getSinglePredecessor() == BB) { |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 4815 | DEBUG(dbgs() << "Removing BB: \n" << *BB); |
Chris Lattner | 7eb270e | 2008-12-03 06:40:52 +0000 | [diff] [blame] | 4816 | DeleteDeadBlock(BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4817 | return true; |
| 4818 | } |
| 4819 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4820 | // Check to see if we can constant propagate this terminator instruction |
| 4821 | // away... |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 4822 | Changed |= ConstantFoldTerminator(BB, true); |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4823 | |
Dan Gohman | 1a95106 | 2009-10-30 22:39:04 +0000 | [diff] [blame] | 4824 | // Check for and eliminate duplicate PHI nodes in this block. |
| 4825 | Changed |= EliminateDuplicatePHINodes(BB); |
| 4826 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4827 | // Check for and remove branches that will always cause undefined behavior. |
| 4828 | Changed |= removeUndefIntroducingPredecessor(BB); |
| 4829 | |
Chris Lattner | 2e3832d | 2010-12-13 05:10:48 +0000 | [diff] [blame] | 4830 | // Merge basic blocks into their predecessor if there is only one distinct |
| 4831 | // pred, and if there is only one distinct successor of the predecessor, and |
| 4832 | // if there are no PHI nodes. |
| 4833 | // |
| 4834 | if (MergeBlockIntoPredecessor(BB)) |
| 4835 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4836 | |
Devang Patel | 15ad676 | 2011-05-18 18:01:27 +0000 | [diff] [blame] | 4837 | IRBuilder<> Builder(BB); |
| 4838 | |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 4839 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 4840 | // eliminate it, do so now. |
| 4841 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 4842 | if (PN->getNumIncomingValues() == 2) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4843 | Changed |= FoldTwoEntryPHINode(PN, TTI, DL); |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 4844 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4845 | Builder.SetInsertPoint(BB->getTerminator()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4846 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4847 | if (BI->isUnconditional()) { |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 4848 | if (SimplifyUncondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4849 | } else { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4850 | if (SimplifyCondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4851 | } |
| 4852 | } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 4853 | if (SimplifyReturn(RI, Builder)) return true; |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 4854 | } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { |
| 4855 | if (SimplifyResume(RI, Builder)) return true; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 4856 | } else if (CleanupReturnInst *RI = |
| 4857 | dyn_cast<CleanupReturnInst>(BB->getTerminator())) { |
| 4858 | if (SimplifyCleanupReturn(RI)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4859 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4860 | if (SimplifySwitch(SI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4861 | } else if (UnreachableInst *UI = |
| 4862 | dyn_cast<UnreachableInst>(BB->getTerminator())) { |
| 4863 | if (SimplifyUnreachable(UI)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4864 | } else if (IndirectBrInst *IBI = |
| 4865 | dyn_cast<IndirectBrInst>(BB->getTerminator())) { |
| 4866 | if (SimplifyIndirectBr(IBI)) return true; |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 4867 | } |
| 4868 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4869 | return Changed; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4870 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4871 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4872 | /// This function is used to do simplification of a CFG. |
| 4873 | /// 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] | 4874 | /// eliminates unreachable basic blocks, and does other "peephole" optimization |
| 4875 | /// of the CFG. It returns true if a modification was made. |
| 4876 | /// |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4877 | bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4878 | unsigned BonusInstThreshold, AssumptionCache *AC) { |
| 4879 | return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), |
| 4880 | BonusInstThreshold, AC).run(BB); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4881 | } |