blob: 9e1aa71e8b545871274307de9a7a8f0df9f560ab [file] [log] [blame]
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001//===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00009//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000010// Correlated Expression Elimination propagates information from conditional
11// branches to blocks dominated by destinations of the branch. It propagates
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000012// information from the condition check itself into the body of the branch,
13// allowing transformations like these for example:
14//
15// if (i == 7)
Misha Brukmana3bbcb52002-10-29 23:06:16 +000016// ... 4*i; // constant propagation
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000017//
18// M = i+1; N = j+1;
19// if (i == j)
20// X = M-N; // = M-M == 0;
21//
22// This is called Correlated Expression Elimination because we eliminate or
23// simplify expressions that are correlated with the direction of a branch. In
24// this way we use static information to give us some information about the
25// dynamic value of a variable.
26//
27//===----------------------------------------------------------------------===//
28
Chris Lattner0e5f4992006-12-19 21:40:18 +000029#define DEBUG_TYPE "cee"
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000030#include "llvm/Transforms/Scalar.h"
Chris Lattner5585b332004-01-12 19:12:50 +000031#include "llvm/Constants.h"
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000032#include "llvm/Pass.h"
33#include "llvm/Function.h"
Chris Lattnerd23520c2003-11-10 04:10:50 +000034#include "llvm/Instructions.h"
Chris Lattner5585b332004-01-12 19:12:50 +000035#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000036#include "llvm/DerivedTypes.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000037#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000038#include "llvm/Analysis/Dominators.h"
Chris Lattnerd23520c2003-11-10 04:10:50 +000039#include "llvm/Assembly/Writer.h"
Chris Lattnerd23520c2003-11-10 04:10:50 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000041#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000042#include "llvm/Support/Compiler.h"
43#include "llvm/Support/ConstantRange.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/Support/Debug.h"
45#include "llvm/ADT/PostOrderIterator.h"
46#include "llvm/ADT/Statistic.h"
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000047#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Reid Spencere4d87aa2006-12-23 06:05:41 +000050STATISTIC(NumCmpRemoved, "Number of cmp instruction eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(NumOperandsCann, "Number of operands canonicalized");
52STATISTIC(BranchRevectors, "Number of branches revectored");
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000053
Chris Lattner0e5f4992006-12-19 21:40:18 +000054namespace {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000055 class ValueInfo;
Reid Spencer9133fe22007-02-05 23:32:05 +000056 class VISIBILITY_HIDDEN Relation {
Reid Spencere4d87aa2006-12-23 06:05:41 +000057 Value *Val; // Relation to what value?
58 unsigned Rel; // SetCC or ICmp relation, or Add if no information
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000059 public:
Dan Gohmanadf3eab2007-11-19 15:30:20 +000060 explicit Relation(Value *V) : Val(V), Rel(Instruction::Add) {}
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000061 bool operator<(const Relation &R) const { return Val < R.Val; }
62 Value *getValue() const { return Val; }
Reid Spencere4d87aa2006-12-23 06:05:41 +000063 unsigned getRelation() const { return Rel; }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000064
65 // contradicts - Return true if the relationship specified by the operand
66 // contradicts already known information.
67 //
Reid Spencere4d87aa2006-12-23 06:05:41 +000068 bool contradicts(unsigned Rel, const ValueInfo &VI) const;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000069
70 // incorporate - Incorporate information in the argument into this relation
71 // entry. This assumes that the information doesn't contradict itself. If
72 // any new information is gained, true is returned, otherwise false is
73 // returned to indicate that nothing was updated.
74 //
Reid Spencere4d87aa2006-12-23 06:05:41 +000075 bool incorporate(unsigned Rel, ValueInfo &VI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000076
77 // KnownResult - Whether or not this condition determines the result of a
Reid Spencere4d87aa2006-12-23 06:05:41 +000078 // setcc or icmp in the program. False & True are intentionally 0 & 1
79 // so we can convert to bool by casting after checking for unknown.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000080 //
81 enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
82
83 // getImpliedResult - If this relationship between two values implies that
84 // the specified relationship is true or false, return that. If we cannot
85 // determine the result required, return Unknown.
86 //
Reid Spencere4d87aa2006-12-23 06:05:41 +000087 KnownResult getImpliedResult(unsigned Rel) const;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +000088
89 // print - Output this relation to the specified stream
90 void print(std::ostream &OS) const;
91 void dump() const;
92 };
93
94
95 // ValueInfo - One instance of this record exists for every value with
96 // relationships between other values. It keeps track of all of the
97 // relationships to other values in the program (specified with Relation) that
98 // are known to be valid in a region.
99 //
Reid Spencer9133fe22007-02-05 23:32:05 +0000100 class VISIBILITY_HIDDEN ValueInfo {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000101 // RelationShips - this value is know to have the specified relationships to
102 // other values. There can only be one entry per value, and this list is
103 // kept sorted by the Val field.
104 std::vector<Relation> Relationships;
105
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000106 // If information about this value is known or propagated from constant
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000107 // expressions, this range contains the possible values this value may hold.
108 ConstantRange Bounds;
109
110 // If we find that this value is equal to another value that has a lower
111 // rank, this value is used as it's replacement.
112 //
113 Value *Replacement;
114 public:
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000115 explicit ValueInfo(const Type *Ty)
Reid Spencerc6aedf72007-02-28 22:03:51 +0000116 : Bounds(Ty->isInteger() ? cast<IntegerType>(Ty)->getBitWidth() : 32),
117 Replacement(0) {}
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000118
119 // getBounds() - Return the constant bounds of the value...
120 const ConstantRange &getBounds() const { return Bounds; }
121 ConstantRange &getBounds() { return Bounds; }
122
123 const std::vector<Relation> &getRelationships() { return Relationships; }
124
125 // getReplacement - Return the value this value is to be replaced with if it
126 // exists, otherwise return null.
127 //
128 Value *getReplacement() const { return Replacement; }
129
130 // setReplacement - Used by the replacement calculation pass to figure out
131 // what to replace this value with, if anything.
132 //
133 void setReplacement(Value *Repl) { Replacement = Repl; }
134
135 // getRelation - return the relationship entry for the specified value.
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000136 // This can invalidate references to other Relations, so use it carefully.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000137 //
138 Relation &getRelation(Value *V) {
139 // Binary search for V's entry...
140 std::vector<Relation>::iterator I =
Jeff Cohen9471c8a2006-01-26 20:41:32 +0000141 std::lower_bound(Relationships.begin(), Relationships.end(),
142 Relation(V));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000143
144 // If we found the entry, return it...
145 if (I != Relationships.end() && I->getValue() == V)
146 return *I;
147
148 // Insert and return the new relationship...
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000149 return *Relationships.insert(I, Relation(V));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000150 }
151
152 const Relation *requestRelation(Value *V) const {
153 // Binary search for V's entry...
154 std::vector<Relation>::const_iterator I =
Jeff Cohen9471c8a2006-01-26 20:41:32 +0000155 std::lower_bound(Relationships.begin(), Relationships.end(),
156 Relation(V));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000157 if (I != Relationships.end() && I->getValue() == V)
158 return &*I;
159 return 0;
160 }
161
162 // print - Output information about this value relation...
163 void print(std::ostream &OS, Value *V) const;
164 void dump() const;
165 };
166
167 // RegionInfo - Keeps track of all of the value relationships for a region. A
168 // region is the are dominated by a basic block. RegionInfo's keep track of
169 // the RegionInfo for their dominator, because anything known in a dominator
170 // is known to be true in a dominated block as well.
171 //
Reid Spencer9133fe22007-02-05 23:32:05 +0000172 class VISIBILITY_HIDDEN RegionInfo {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000173 BasicBlock *BB;
174
175 // ValueMap - Tracks the ValueInformation known for this region
176 typedef std::map<Value*, ValueInfo> ValueMapTy;
177 ValueMapTy ValueMap;
178 public:
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000179 explicit RegionInfo(BasicBlock *bb) : BB(bb) {}
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000180
181 // getEntryBlock - Return the block that dominates all of the members of
182 // this region.
183 BasicBlock *getEntryBlock() const { return BB; }
184
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000185 // empty - return true if this region has no information known about it.
186 bool empty() const { return ValueMap.empty(); }
Misha Brukmanfd939082005-04-21 23:48:37 +0000187
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000188 const RegionInfo &operator=(const RegionInfo &RI) {
189 ValueMap = RI.ValueMap;
190 return *this;
191 }
192
193 // print - Output information about this region...
194 void print(std::ostream &OS) const;
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000195 void dump() const;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000196
197 // Allow external access.
198 typedef ValueMapTy::iterator iterator;
199 iterator begin() { return ValueMap.begin(); }
200 iterator end() { return ValueMap.end(); }
201
202 ValueInfo &getValueInfo(Value *V) {
203 ValueMapTy::iterator I = ValueMap.lower_bound(V);
204 if (I != ValueMap.end() && I->first == V) return I->second;
205 return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
206 }
207
208 const ValueInfo *requestValueInfo(Value *V) const {
209 ValueMapTy::const_iterator I = ValueMap.find(V);
210 if (I != ValueMap.end()) return &I->second;
211 return 0;
212 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000213
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000214 /// removeValueInfo - Remove anything known about V from our records. This
215 /// works whether or not we know anything about V.
216 ///
217 void removeValueInfo(Value *V) {
218 ValueMap.erase(V);
219 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000220 };
221
222 /// CEE - Correlated Expression Elimination
Reid Spencer9133fe22007-02-05 23:32:05 +0000223 class VISIBILITY_HIDDEN CEE : public FunctionPass {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000224 std::map<Value*, unsigned> RankMap;
225 std::map<BasicBlock*, RegionInfo> RegionInfoMap;
Devang Patelfa51f9a2007-06-07 21:35:27 +0000226 DominatorTree *DT;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000227 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000228 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000229 CEE() : FunctionPass((intptr_t)&ID) {}
230
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000231 virtual bool runOnFunction(Function &F);
232
233 // We don't modify the program, so we preserve all analyses
234 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfa51f9a2007-06-07 21:35:27 +0000235 AU.addRequired<DominatorTree>();
Chris Lattner16e7a522002-09-24 15:43:56 +0000236 AU.addRequiredID(BreakCriticalEdgesID);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000237 };
238
239 // print - Implement the standard print form to print out analysis
240 // information.
241 virtual void print(std::ostream &O, const Module *M) const;
242
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000243 private:
244 RegionInfo &getRegionInfo(BasicBlock *BB) {
245 std::map<BasicBlock*, RegionInfo>::iterator I
246 = RegionInfoMap.lower_bound(BB);
247 if (I != RegionInfoMap.end() && I->first == BB) return I->second;
248 return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
249 }
250
251 void BuildRankMap(Function &F);
252 unsigned getRank(Value *V) const {
Reid Spencer48dc46a2004-07-18 00:29:57 +0000253 if (isa<Constant>(V)) return 0;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000254 std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
255 if (I != RankMap.end()) return I->second;
256 return 0; // Must be some other global thing
257 }
258
259 bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
260
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000261 bool ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
262 RegionInfo &RI);
263
264 void ForwardSuccessorTo(TerminatorInst *TI, unsigned Succ, BasicBlock *D,
265 RegionInfo &RI);
266 void ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
267 BasicBlock *RegionDominator);
268 void CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
269 std::vector<BasicBlock*> &RegionExitBlocks);
270 void InsertRegionExitMerges(PHINode *NewPHI, Instruction *OldVal,
271 const std::vector<BasicBlock*> &RegionExitBlocks);
272
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000273 void PropagateBranchInfo(BranchInst *BI);
Chris Lattner273f2022006-03-19 19:37:24 +0000274 void PropagateSwitchInfo(SwitchInst *SI);
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000275 void PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000276 void PropagateRelation(unsigned Opcode, Value *Op0,
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000277 Value *Op1, RegionInfo &RI);
278 void UpdateUsersOfValue(Value *V, RegionInfo &RI);
279 void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
280 void ComputeReplacements(RegionInfo &RI);
281
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 // getCmpResult - Given a icmp instruction, determine if the result is
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000283 // determined by facts we already know about the region under analysis.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000284 // Return KnownTrue, KnownFalse, or UnKnown based on what we can determine.
285 Relation::KnownResult getCmpResult(CmpInst *ICI, const RegionInfo &RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000286
287 bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
288 bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000289 };
Devang Patel794fd752007-05-01 21:15:47 +0000290
Devang Patel19974732007-05-03 01:11:54 +0000291 char CEE::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000292 RegisterPass<CEE> X("cee", "Correlated Expression Elimination");
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000293}
294
Chris Lattner4b501562004-09-20 04:43:15 +0000295FunctionPass *llvm::createCorrelatedExpressionEliminationPass() {
296 return new CEE();
297}
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000298
299
300bool CEE::runOnFunction(Function &F) {
301 // Build a rank map for the function...
302 BuildRankMap(F);
303
304 // Traverse the dominator tree, computing information for each node in the
305 // tree. Note that our traversal will not even touch unreachable basic
306 // blocks.
Devang Patelfa51f9a2007-06-07 21:35:27 +0000307 DT = &getAnalysis<DominatorTree>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000308
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000309 std::set<BasicBlock*> VisitedBlocks;
Chris Lattner02a3be02003-09-20 14:39:18 +0000310 bool Changed = TransformRegion(&F.getEntryBlock(), VisitedBlocks);
Chris Lattnerbd786962002-09-08 18:55:04 +0000311
312 RegionInfoMap.clear();
313 RankMap.clear();
314 return Changed;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000315}
316
317// TransformRegion - Transform the region starting with BB according to the
318// calculated region information for the block. Transforming the region
319// involves analyzing any information this block provides to successors,
Misha Brukman82c89b92003-05-20 21:01:22 +0000320// propagating the information to successors, and finally transforming
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000321// successors.
322//
323// This method processes the function in depth first order, which guarantees
324// that we process the immediate dominator of a block before the block itself.
325// Because we are passing information from immediate dominators down to
326// dominatees, we obviously have to process the information source before the
327// information consumer.
328//
329bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
330 // Prevent infinite recursion...
331 if (VisitedBlocks.count(BB)) return false;
332 VisitedBlocks.insert(BB);
333
334 // Get the computed region information for this block...
335 RegionInfo &RI = getRegionInfo(BB);
336
337 // Compute the replacement information for this block...
338 ComputeReplacements(RI);
339
340 // If debugging, print computed region information...
Bill Wendling832171c2006-12-07 20:04:42 +0000341 DEBUG(RI.print(*cerr.stream()));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000342
343 // Simplify the contents of this block...
344 bool Changed = SimplifyBasicBlock(*BB, RI);
345
346 // Get the terminator of this basic block...
347 TerminatorInst *TI = BB->getTerminator();
348
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000349 // Loop over all of the blocks that this block is the immediate dominator for.
350 // Because all information known in this region is also known in all of the
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000351 // blocks that are dominated by this one, we can safely propagate the
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000352 // information down now.
353 //
Devang Patelfa51f9a2007-06-07 21:35:27 +0000354 DomTreeNode *BBDom = DT->getNode(BB);
Chris Lattnerd717c182007-05-05 22:32:24 +0000355 if (!RI.empty()) { // Time opt: only propagate if we can change something
Devang Patelfa51f9a2007-06-07 21:35:27 +0000356 for (std::vector<DomTreeNode*>::iterator DI = BBDom->begin(),
357 E = BBDom->end(); DI != E; ++DI) {
358 BasicBlock *ChildBB = (*DI)->getBlock();
359 assert(RegionInfoMap.find(ChildBB) == RegionInfoMap.end() &&
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000360 "RegionInfo should be calculated in dominanace order!");
Devang Patelfa51f9a2007-06-07 21:35:27 +0000361 getRegionInfo(ChildBB) = RI;
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000362 }
Owen Andersonfb4b3d12007-04-18 05:25:43 +0000363 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000364
365 // Now that all of our successors have information if they deserve it,
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000366 // propagate any information our terminator instruction finds to our
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000367 // successors.
Chris Lattner273f2022006-03-19 19:37:24 +0000368 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000369 if (BI->isConditional())
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000370 PropagateBranchInfo(BI);
Chris Lattner273f2022006-03-19 19:37:24 +0000371 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
372 PropagateSwitchInfo(SI);
373 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000374
375 // If this is a branch to a block outside our region that simply performs
376 // another conditional branch, one whose outcome is known inside of this
377 // region, then vector this outgoing edge directly to the known destination.
378 //
Chris Lattnerc017d912002-09-23 20:06:22 +0000379 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000380 while (ForwardCorrelatedEdgeDestination(TI, i, RI)) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000381 ++BranchRevectors;
Chris Lattnerc017d912002-09-23 20:06:22 +0000382 Changed = true;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000383 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000384
385 // Now that all of our successors have information, recursively process them.
Devang Patelfa51f9a2007-06-07 21:35:27 +0000386 for (std::vector<DomTreeNode*>::iterator DI = BBDom->begin(),
387 E = BBDom->end(); DI != E; ++DI) {
388 BasicBlock *ChildBB = (*DI)->getBlock();
389 Changed |= TransformRegion(ChildBB, VisitedBlocks);
390 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000391
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000392 return Changed;
393}
394
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000395// isBlockSimpleEnoughForCheck to see if the block is simple enough for us to
396// revector the conditional branch in the bottom of the block, do so now.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000397//
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000398static bool isBlockSimpleEnough(BasicBlock *BB) {
399 assert(isa<BranchInst>(BB->getTerminator()));
400 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
401 assert(BI->isConditional());
402
403 // Check the common case first: empty block, or block with just a setcc.
404 if (BB->size() == 1 ||
405 (BB->size() == 2 && &BB->front() == BI->getCondition() &&
Chris Lattnerfd059242003-10-15 16:48:29 +0000406 BI->getCondition()->hasOneUse()))
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000407 return true;
408
409 // Check the more complex case now...
410 BasicBlock::iterator I = BB->begin();
411
412 // FIXME: This should be reenabled once the regression with SIM is fixed!
413#if 0
414 // PHI Nodes are ok, just skip over them...
415 while (isa<PHINode>(*I)) ++I;
416#endif
417
418 // Accept the setcc instruction...
419 if (&*I == BI->getCondition())
420 ++I;
421
422 // Nothing else is acceptable here yet. We must not revector... unless we are
423 // at the terminator instruction.
424 if (&*I == BI)
425 return true;
426
427 return false;
428}
429
430
431bool CEE::ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
432 RegionInfo &RI) {
433 // If this successor is a simple block not in the current region, which
434 // contains only a conditional branch, we decide if the outcome of the branch
435 // can be determined from information inside of the region. Instead of going
436 // to this block, we can instead go to the destination we know is the right
437 // target.
438 //
439
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000440 // Check to see if we dominate the block. If so, this block will get the
441 // condition turned to a constant anyway.
442 //
Chris Lattner19ef3d52006-01-11 05:09:40 +0000443 //if (EF->dominates(RI.getEntryBlock(), BB))
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000444 // return 0;
445
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000446 BasicBlock *BB = TI->getParent();
447
448 // Get the destination block of this edge...
449 BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
450
451 // Make sure that the block ends with a conditional branch and is simple
452 // enough for use to be able to revector over.
453 BranchInst *BI = dyn_cast<BranchInst>(OldSucc->getTerminator());
454 if (BI == 0 || !BI->isConditional() || !isBlockSimpleEnough(OldSucc))
455 return false;
456
457 // We can only forward the branch over the block if the block ends with a
Reid Spencere4d87aa2006-12-23 06:05:41 +0000458 // cmp we can determine the outcome for.
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000459 //
460 // FIXME: we can make this more generic. Code below already handles more
461 // generic case.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000462 if (!isa<CmpInst>(BI->getCondition()))
463 return false;
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000464
465 // Make a new RegionInfo structure so that we can simulate the effect of the
466 // PHI nodes in the block we are skipping over...
467 //
468 RegionInfo NewRI(RI);
469
470 // Remove value information for all of the values we are simulating... to make
471 // sure we don't have any stale information.
472 for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
473 if (I->getType() != Type::VoidTy)
474 NewRI.removeValueInfo(I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000475
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000476 // Put the newly discovered information into the RegionInfo...
477 for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
Chris Lattnere408e252003-04-23 16:37:45 +0000478 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000479 int OpNum = PN->getBasicBlockIndex(BB);
480 assert(OpNum != -1 && "PHI doesn't have incoming edge for predecessor!?");
Misha Brukmanfd939082005-04-21 23:48:37 +0000481 PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000482 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
483 Relation::KnownResult Res = getCmpResult(CI, NewRI);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000484 if (Res == Relation::Unknown) return false;
Reid Spencer579dca12007-01-12 04:24:46 +0000485 PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Res), NewRI);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000486 } else {
487 assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000488 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000489
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000490 // Compute the facts implied by what we have discovered...
491 ComputeReplacements(NewRI);
492
493 ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
494 if (PredicateVI.getReplacement() &&
Reid Spencer48dc46a2004-07-18 00:29:57 +0000495 isa<Constant>(PredicateVI.getReplacement()) &&
496 !isa<GlobalValue>(PredicateVI.getReplacement())) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000497 ConstantInt *CB = cast<ConstantInt>(PredicateVI.getReplacement());
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000498
499 // Forward to the successor that corresponds to the branch we will take.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000500 ForwardSuccessorTo(TI, SuccNo,
Reid Spencer579dca12007-01-12 04:24:46 +0000501 BI->getSuccessor(!CB->getZExtValue()), NewRI);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000502 return true;
503 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000504
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000505 return false;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000506}
507
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000508static Value *getReplacementOrValue(Value *V, RegionInfo &RI) {
509 if (const ValueInfo *VI = RI.requestValueInfo(V))
510 if (Value *Repl = VI->getReplacement())
511 return Repl;
512 return V;
513}
514
515/// ForwardSuccessorTo - We have found that we can forward successor # 'SuccNo'
516/// of Terminator 'TI' to the 'Dest' BasicBlock. This method performs the
517/// mechanics of updating SSA information and revectoring the branch.
518///
519void CEE::ForwardSuccessorTo(TerminatorInst *TI, unsigned SuccNo,
520 BasicBlock *Dest, RegionInfo &RI) {
521 // If there are any PHI nodes in the Dest BB, we must duplicate the entry
522 // in the PHI node for the old successor to now include an entry from the
523 // current basic block.
524 //
525 BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
526 BasicBlock *BB = TI->getParent();
527
Bill Wendling832171c2006-12-07 20:04:42 +0000528 DOUT << "Forwarding branch in basic block %" << BB->getName()
529 << " from block %" << OldSucc->getName() << " to block %"
530 << Dest->getName() << "\n"
531 << "Before forwarding: " << *BB->getParent();
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000532
533 // Because we know that there cannot be critical edges in the flow graph, and
534 // that OldSucc has multiple outgoing edges, this means that Dest cannot have
535 // multiple incoming edges.
536 //
537#ifndef NDEBUG
538 pred_iterator DPI = pred_begin(Dest); ++DPI;
539 assert(DPI == pred_end(Dest) && "Critical edge found!!");
540#endif
541
542 // Loop over any PHI nodes in the destination, eliminating them, because they
543 // may only have one input.
544 //
545 while (PHINode *PN = dyn_cast<PHINode>(&Dest->front())) {
546 assert(PN->getNumIncomingValues() == 1 && "Crit edge found!");
547 // Eliminate the PHI node
548 PN->replaceAllUsesWith(PN->getIncomingValue(0));
549 Dest->getInstList().erase(PN);
550 }
551
552 // If there are values defined in the "OldSucc" basic block, we need to insert
553 // PHI nodes in the regions we are dealing with to emulate them. This can
554 // insert dead phi nodes, but it is more trouble to see if they are used than
555 // to just blindly insert them.
556 //
Devang Patelfa51f9a2007-06-07 21:35:27 +0000557 if (DT->dominates(OldSucc, Dest)) {
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000558 // RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
559 // but have predecessors that are. Additionally, prune down the set to only
560 // include blocks that are dominated by OldSucc as well.
561 //
562 std::vector<BasicBlock*> RegionExitBlocks;
563 CalculateRegionExitBlocks(Dest, OldSucc, RegionExitBlocks);
564
565 for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end();
566 I != E; ++I)
567 if (I->getType() != Type::VoidTy) {
568 // Create and insert the PHI node into the top of Dest.
569 PHINode *NewPN = new PHINode(I->getType(), I->getName()+".fw_merge",
570 Dest->begin());
Chris Lattner51c20e92002-11-08 23:18:37 +0000571 // There is definitely an edge from OldSucc... add the edge now
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000572 NewPN->addIncoming(I, OldSucc);
573
574 // There is also an edge from BB now, add the edge with the calculated
575 // value from the RI.
576 NewPN->addIncoming(getReplacementOrValue(I, RI), BB);
577
578 // Make everything in the Dest region use the new PHI node now...
579 ReplaceUsesOfValueInRegion(I, NewPN, Dest);
580
581 // Make sure that exits out of the region dominated by NewPN get PHI
582 // nodes that merge the values as appropriate.
583 InsertRegionExitMerges(NewPN, I, RegionExitBlocks);
584 }
585 }
586
587 // If there were PHI nodes in OldSucc, we need to remove the entry for this
588 // edge from the PHI node, and we need to replace any references to the PHI
589 // node with a new value.
590 //
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000591 for (BasicBlock::iterator I = OldSucc->begin(); isa<PHINode>(I); ) {
592 PHINode *PN = cast<PHINode>(I);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000593
594 // Get the value flowing across the old edge and remove the PHI node entry
595 // for this edge: we are about to remove the edge! Don't remove the PHI
596 // node yet though if this is the last edge into it.
597 Value *EdgeValue = PN->removeIncomingValue(BB, false);
598
Misha Brukmanfd939082005-04-21 23:48:37 +0000599 // Make sure that anything that used to use PN now refers to EdgeValue
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000600 ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
601
602 // If there is only one value left coming into the PHI node, replace the PHI
603 // node itself with the one incoming value left.
604 //
605 if (PN->getNumIncomingValues() == 1) {
606 assert(PN->getNumIncomingValues() == 1);
607 PN->replaceAllUsesWith(PN->getIncomingValue(0));
608 PN->getParent()->getInstList().erase(PN);
609 I = OldSucc->begin();
610 } else if (PN->getNumIncomingValues() == 0) { // Nuke the PHI
611 // If we removed the last incoming value to this PHI, nuke the PHI node
612 // now.
613 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
614 PN->getParent()->getInstList().erase(PN);
615 I = OldSucc->begin();
616 } else {
617 ++I; // Otherwise, move on to the next PHI node
618 }
619 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000620
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000621 // Actually revector the branch now...
622 TI->setSuccessor(SuccNo, Dest);
623
624 // If we just introduced a critical edge in the flow graph, make sure to break
625 // it right away...
Chris Lattnerd23520c2003-11-10 04:10:50 +0000626 SplitCriticalEdge(TI, SuccNo, this);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000627
628 // Make sure that we don't introduce critical edges from oldsucc now!
629 for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
630 i != e; ++i)
Chris Lattnerf6de8ad2006-10-28 06:38:14 +0000631 SplitCriticalEdge(OldSucc->getTerminator(), i, this);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000632
633 // Since we invalidated the CFG, recalculate the dominator set so that it is
634 // useful for later processing!
635 // FIXME: This is much worse than it really should be!
Chris Lattner19ef3d52006-01-11 05:09:40 +0000636 //EF->recalculate();
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000637
Bill Wendling832171c2006-12-07 20:04:42 +0000638 DOUT << "After forwarding: " << *BB->getParent();
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000639}
640
641/// ReplaceUsesOfValueInRegion - This method replaces all uses of Orig with uses
642/// of New. It only affects instructions that are defined in basic blocks that
643/// are dominated by Head.
644///
645void CEE::ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
646 BasicBlock *RegionDominator) {
647 assert(Orig != New && "Cannot replace value with itself");
648 std::vector<Instruction*> InstsToChange;
649 std::vector<PHINode*> PHIsToChange;
Chris Lattnerac930042005-02-01 01:23:49 +0000650 InstsToChange.reserve(Orig->getNumUses());
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000651
652 // Loop over instructions adding them to InstsToChange vector, this allows us
653 // an easy way to avoid invalidating the use_iterator at a bad time.
654 for (Value::use_iterator I = Orig->use_begin(), E = Orig->use_end();
655 I != E; ++I)
656 if (Instruction *User = dyn_cast<Instruction>(*I))
Devang Patelfa51f9a2007-06-07 21:35:27 +0000657 if (DT->dominates(RegionDominator, User->getParent()))
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000658 InstsToChange.push_back(User);
659 else if (PHINode *PN = dyn_cast<PHINode>(User)) {
660 PHIsToChange.push_back(PN);
661 }
662
663 // PHIsToChange contains PHI nodes that use Orig that do not live in blocks
664 // dominated by orig. If the block the value flows in from is dominated by
665 // RegionDominator, then we rewrite the PHI
666 for (unsigned i = 0, e = PHIsToChange.size(); i != e; ++i) {
667 PHINode *PN = PHIsToChange[i];
668 for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
669 if (PN->getIncomingValue(j) == Orig &&
Devang Patelfa51f9a2007-06-07 21:35:27 +0000670 DT->dominates(RegionDominator, PN->getIncomingBlock(j)))
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000671 PN->setIncomingValue(j, New);
672 }
673
674 // Loop over the InstsToChange list, replacing all uses of Orig with uses of
675 // New. This list contains all of the instructions in our region that use
676 // Orig.
677 for (unsigned i = 0, e = InstsToChange.size(); i != e; ++i)
678 if (PHINode *PN = dyn_cast<PHINode>(InstsToChange[i])) {
679 // PHINodes must be handled carefully. If the PHI node itself is in the
680 // region, we have to make sure to only do the replacement for incoming
681 // values that correspond to basic blocks in the region.
682 for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
683 if (PN->getIncomingValue(j) == Orig &&
Devang Patelfa51f9a2007-06-07 21:35:27 +0000684 DT->dominates(RegionDominator, PN->getIncomingBlock(j)))
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000685 PN->setIncomingValue(j, New);
686
687 } else {
688 InstsToChange[i]->replaceUsesOfWith(Orig, New);
689 }
690}
691
692static void CalcRegionExitBlocks(BasicBlock *Header, BasicBlock *BB,
693 std::set<BasicBlock*> &Visited,
Devang Patelfa51f9a2007-06-07 21:35:27 +0000694 DominatorTree &DT,
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000695 std::vector<BasicBlock*> &RegionExitBlocks) {
696 if (Visited.count(BB)) return;
697 Visited.insert(BB);
698
Devang Patelfa51f9a2007-06-07 21:35:27 +0000699 if (DT.dominates(Header, BB)) { // Block in the region, recursively traverse
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000700 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Devang Patelfa51f9a2007-06-07 21:35:27 +0000701 CalcRegionExitBlocks(Header, *I, Visited, DT, RegionExitBlocks);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000702 } else {
703 // Header does not dominate this block, but we have a predecessor that does
704 // dominate us. Add ourself to the list.
Misha Brukmanfd939082005-04-21 23:48:37 +0000705 RegionExitBlocks.push_back(BB);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000706 }
707}
708
709/// CalculateRegionExitBlocks - Find all of the blocks that are not dominated by
710/// BB, but have predecessors that are. Additionally, prune down the set to
711/// only include blocks that are dominated by OldSucc as well.
712///
713void CEE::CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
714 std::vector<BasicBlock*> &RegionExitBlocks){
715 std::set<BasicBlock*> Visited; // Don't infinite loop
716
717 // Recursively calculate blocks we are interested in...
Devang Patelfa51f9a2007-06-07 21:35:27 +0000718 CalcRegionExitBlocks(BB, BB, Visited, *DT, RegionExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000719
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000720 // Filter out blocks that are not dominated by OldSucc...
721 for (unsigned i = 0; i != RegionExitBlocks.size(); ) {
Devang Patelfa51f9a2007-06-07 21:35:27 +0000722 if (DT->dominates(OldSucc, RegionExitBlocks[i]))
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000723 ++i; // Block is ok, keep it.
724 else {
725 // Move to end of list...
726 std::swap(RegionExitBlocks[i], RegionExitBlocks.back());
727 RegionExitBlocks.pop_back(); // Nuke the end
728 }
729 }
730}
731
732void CEE::InsertRegionExitMerges(PHINode *BBVal, Instruction *OldVal,
733 const std::vector<BasicBlock*> &RegionExitBlocks) {
734 assert(BBVal->getType() == OldVal->getType() && "Should be derived values!");
735 BasicBlock *BB = BBVal->getParent();
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000736
737 // Loop over all of the blocks we have to place PHIs in, doing it.
738 for (unsigned i = 0, e = RegionExitBlocks.size(); i != e; ++i) {
739 BasicBlock *FBlock = RegionExitBlocks[i]; // Block on the frontier
740
741 // Create the new PHI node
742 PHINode *NewPN = new PHINode(BBVal->getType(),
743 OldVal->getName()+".fw_frontier",
744 FBlock->begin());
745
746 // Add an incoming value for every predecessor of the block...
747 for (pred_iterator PI = pred_begin(FBlock), PE = pred_end(FBlock);
748 PI != PE; ++PI) {
749 // If the incoming edge is from the region dominated by BB, use BBVal,
750 // otherwise use OldVal.
Devang Patelfa51f9a2007-06-07 21:35:27 +0000751 NewPN->addIncoming(DT->dominates(BB, *PI) ? BBVal : OldVal, *PI);
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000752 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000753
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000754 // Now make everyone dominated by this block use this new value!
755 ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
756 }
757}
758
759
760
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000761// BuildRankMap - This method builds the rank map data structure which gives
762// each instruction/value in the function a value based on how early it appears
763// in the function. We give constants and globals rank 0, arguments are
764// numbered starting at one, and instructions are numbered in reverse post-order
765// from where the arguments leave off. This gives instructions in loops higher
766// values than instructions not in loops.
767//
768void CEE::BuildRankMap(Function &F) {
769 unsigned Rank = 1; // Skip rank zero.
770
771 // Number the arguments...
Chris Lattnere4d5c442005-03-15 04:54:21 +0000772 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000773 RankMap[I] = Rank++;
774
775 // Number the instructions in reverse post order...
776 ReversePostOrderTraversal<Function*> RPOT(&F);
777 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
778 E = RPOT.end(); I != E; ++I)
779 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
780 BBI != E; ++BBI)
781 if (BBI->getType() != Type::VoidTy)
782 RankMap[BBI] = Rank++;
783}
784
785
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000786// PropagateBranchInfo - When this method is invoked, we need to propagate
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000787// information derived from the branch condition into the true and false
788// branches of BI. Since we know that there aren't any critical edges in the
789// flow graph, this can proceed unconditionally.
790//
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000791void CEE::PropagateBranchInfo(BranchInst *BI) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000792 assert(BI->isConditional() && "Must be a conditional branch!");
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000793
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000794 // Propagate information into the true block...
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000795 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000796 PropagateEquality(BI->getCondition(), ConstantInt::getTrue(),
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000797 getRegionInfo(BI->getSuccessor(0)));
Misha Brukmanfd939082005-04-21 23:48:37 +0000798
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000799 // Propagate information into the false block...
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000800 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000801 PropagateEquality(BI->getCondition(), ConstantInt::getFalse(),
Chris Lattnerf7f009d2002-10-08 21:34:15 +0000802 getRegionInfo(BI->getSuccessor(1)));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000803}
804
805
Chris Lattner273f2022006-03-19 19:37:24 +0000806// PropagateSwitchInfo - We need to propagate the value tested by the
807// switch statement through each case block.
808//
809void CEE::PropagateSwitchInfo(SwitchInst *SI) {
810 // Propagate information down each of our non-default case labels. We
811 // don't yet propagate information down the default label, because a
812 // potentially large number of inequality constraints provide less
813 // benefit per unit work than a single equality constraint.
814 //
815 Value *cond = SI->getCondition();
816 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
817 PropagateEquality(cond, SI->getSuccessorValue(i),
818 getRegionInfo(SI->getSuccessor(i)));
819}
820
821
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000822// PropagateEquality - If we discover that two values are equal to each other in
823// a specified region, propagate this knowledge recursively.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000824//
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000825void CEE::PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000826 if (Op0 == Op1) return; // Gee whiz. Are these really equal each other?
827
828 if (isa<Constant>(Op0)) // Make sure the constant is always Op1
829 std::swap(Op0, Op1);
830
831 // Make sure we don't already know these are equal, to avoid infinite loops...
832 ValueInfo &VI = RI.getValueInfo(Op0);
833
834 // Get information about the known relationship between Op0 & Op1
835 Relation &KnownRelation = VI.getRelation(Op1);
836
837 // If we already know they're equal, don't reprocess...
Reid Spencere4d87aa2006-12-23 06:05:41 +0000838 if (KnownRelation.getRelation() == FCmpInst::FCMP_OEQ ||
839 KnownRelation.getRelation() == ICmpInst::ICMP_EQ)
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000840 return;
841
842 // If this is boolean, check to see if one of the operands is a constant. If
843 // it's a constant, then see if the other one is one of a setcc instruction,
844 // an AND, OR, or XOR instruction.
845 //
Reid Spencerac3e76c2007-01-13 05:10:53 +0000846 ConstantInt *CB = dyn_cast<ConstantInt>(Op1);
847 if (CB && Op1->getType() == Type::Int1Ty) {
848 if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
849 // If we know that this instruction is an AND instruction, and the
850 // result is true, this means that both operands to the OR are known
851 // to be true as well.
852 //
853 if (CB->getZExtValue() && Inst->getOpcode() == Instruction::And) {
854 PropagateEquality(Inst->getOperand(0), CB, RI);
855 PropagateEquality(Inst->getOperand(1), CB, RI);
856 }
857
858 // If we know that this instruction is an OR instruction, and the result
859 // is false, this means that both operands to the OR are know to be
860 // false as well.
861 //
862 if (!CB->getZExtValue() && Inst->getOpcode() == Instruction::Or) {
863 PropagateEquality(Inst->getOperand(0), CB, RI);
864 PropagateEquality(Inst->getOperand(1), CB, RI);
865 }
866
867 // If we know that this instruction is a NOT instruction, we know that
868 // the operand is known to be the inverse of whatever the current
869 // value is.
870 //
871 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
872 if (BinaryOperator::isNot(BOp))
873 PropagateEquality(BinaryOperator::getNotArgument(BOp),
874 ConstantInt::get(Type::Int1Ty,
875 !CB->getZExtValue()), RI);
876
877 // If we know the value of a FCmp instruction, propagate the information
878 // about the relation into this region as well.
879 //
880 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Inst)) {
881 if (CB->getZExtValue()) { // If we know the condition is true...
882 // Propagate info about the LHS to the RHS & RHS to LHS
883 PropagateRelation(FCI->getPredicate(), FCI->getOperand(0),
884 FCI->getOperand(1), RI);
885 PropagateRelation(FCI->getSwappedPredicate(),
886 FCI->getOperand(1), FCI->getOperand(0), RI);
887
888 } else { // If we know the condition is false...
889 // We know the opposite of the condition is true...
890 FCmpInst::Predicate C = FCI->getInversePredicate();
891
892 PropagateRelation(C, FCI->getOperand(0), FCI->getOperand(1), RI);
893 PropagateRelation(FCmpInst::getSwappedPredicate(C),
894 FCI->getOperand(1), FCI->getOperand(0), RI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000895 }
Reid Spencerac3e76c2007-01-13 05:10:53 +0000896 }
897
898 // If we know the value of a ICmp instruction, propagate the information
899 // about the relation into this region as well.
900 //
901 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
902 if (CB->getZExtValue()) { // If we know the condition is true...
903 // Propagate info about the LHS to the RHS & RHS to LHS
904 PropagateRelation(ICI->getPredicate(), ICI->getOperand(0),
905 ICI->getOperand(1), RI);
906 PropagateRelation(ICI->getSwappedPredicate(), ICI->getOperand(1),
907 ICI->getOperand(1), RI);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000908
Reid Spencerac3e76c2007-01-13 05:10:53 +0000909 } else { // If we know the condition is false ...
910 // We know the opposite of the condition is true...
911 ICmpInst::Predicate C = ICI->getInversePredicate();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000912
Reid Spencerac3e76c2007-01-13 05:10:53 +0000913 PropagateRelation(C, ICI->getOperand(0), ICI->getOperand(1), RI);
914 PropagateRelation(ICmpInst::getSwappedPredicate(C),
915 ICI->getOperand(1), ICI->getOperand(0), RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000916 }
917 }
918 }
Reid Spencerac3e76c2007-01-13 05:10:53 +0000919 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000920
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000921 // Propagate information about Op0 to Op1 & visa versa
Zhou Sheng057809a2007-01-11 10:33:26 +0000922 PropagateRelation(ICmpInst::ICMP_EQ, Op0, Op1, RI);
923 PropagateRelation(ICmpInst::ICMP_EQ, Op1, Op0, RI);
924 PropagateRelation(FCmpInst::FCMP_OEQ, Op0, Op1, RI);
925 PropagateRelation(FCmpInst::FCMP_OEQ, Op1, Op0, RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000926}
927
928
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000929// PropagateRelation - We know that the specified relation is true in all of the
930// blocks in the specified region. Propagate the information about Op0 and
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000931// anything derived from it into this region.
932//
Reid Spencere4d87aa2006-12-23 06:05:41 +0000933void CEE::PropagateRelation(unsigned Opcode, Value *Op0,
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000934 Value *Op1, RegionInfo &RI) {
935 assert(Op0->getType() == Op1->getType() && "Equal types expected!");
936
937 // Constants are already pretty well understood. We will apply information
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000938 // about the constant to Op1 in another call to PropagateRelation.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000939 //
940 if (isa<Constant>(Op0)) return;
941
942 // Get the region information for this block to update...
943 ValueInfo &VI = RI.getValueInfo(Op0);
944
945 // Get information about the known relationship between Op0 & Op1
946 Relation &Op1R = VI.getRelation(Op1);
947
948 // Quick bailout for common case if we are reprocessing an instruction...
949 if (Op1R.getRelation() == Opcode)
950 return;
951
952 // If we already have information that contradicts the current information we
Misha Brukman82c89b92003-05-20 21:01:22 +0000953 // are propagating, ignore this info. Something bad must have happened!
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000954 //
955 if (Op1R.contradicts(Opcode, VI)) {
956 Op1R.contradicts(Opcode, VI);
Bill Wendling832171c2006-12-07 20:04:42 +0000957 cerr << "Contradiction found for opcode: "
Reid Spencere4d87aa2006-12-23 06:05:41 +0000958 << ((isa<ICmpInst>(Op0)||isa<ICmpInst>(Op1)) ?
959 Instruction::getOpcodeName(Instruction::ICmp) :
960 Instruction::getOpcodeName(Opcode))
961 << "\n";
Bill Wendling832171c2006-12-07 20:04:42 +0000962 Op1R.print(*cerr.stream());
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000963 return;
964 }
965
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000966 // If the information propagated is new, then we want process the uses of this
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000967 // instruction to propagate the information down to them.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000968 //
969 if (Op1R.incorporate(Opcode, VI))
970 UpdateUsersOfValue(Op0, RI);
971}
972
973
974// UpdateUsersOfValue - The information about V in this region has been updated.
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000975// Propagate this to all consumers of the value.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000976//
977void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
978 for (Value::use_iterator I = V->use_begin(), E = V->use_end();
979 I != E; ++I)
980 if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
981 // If this is an instruction using a value that we know something about,
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000982 // try to propagate information to the value produced by the
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000983 // instruction. We can only do this if it is an instruction we can
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000984 // propagate information for (a setcc for example), and we only WANT to
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000985 // do this if the instruction dominates this region.
986 //
987 // If the instruction doesn't dominate this region, then it cannot be
988 // used in this region and we don't care about it. If the instruction
989 // is IN this region, then we will simplify the instruction before we
990 // get to uses of it anyway, so there is no reason to bother with it
991 // here. This check is also effectively checking to make sure that Inst
992 // is in the same function as our region (in case V is a global f.e.).
993 //
Devang Patelfa51f9a2007-06-07 21:35:27 +0000994 if (DT->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +0000995 IncorporateInstruction(Inst, RI);
996 }
997}
998
999// IncorporateInstruction - We just updated the information about one of the
1000// operands to the specified instruction. Update the information about the
1001// value produced by this instruction
1002//
1003void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001004 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001005 // See if we can figure out a result for this instruction...
Reid Spencere4d87aa2006-12-23 06:05:41 +00001006 Relation::KnownResult Result = getCmpResult(CI, RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001007 if (Result != Relation::Unknown) {
Reid Spencer579dca12007-01-12 04:24:46 +00001008 PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Result != 0), RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001009 }
1010 }
1011}
1012
1013
1014// ComputeReplacements - Some values are known to be equal to other values in a
1015// region. For example if there is a comparison of equality between a variable
1016// X and a constant C, we can replace all uses of X with C in the region we are
1017// interested in. We generalize this replacement to replace variables with
1018// other variables if they are equal and there is a variable with lower rank
Chris Lattner065a6162003-09-10 05:29:43 +00001019// than the current one. This offers a canonicalizing property that exposes
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001020// more redundancies for later transformations to take advantage of.
1021//
1022void CEE::ComputeReplacements(RegionInfo &RI) {
1023 // Loop over all of the values in the region info map...
1024 for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
1025 ValueInfo &VI = I->second;
1026
1027 // If we know that this value is a particular constant, set Replacement to
1028 // the constant...
Reid Spencer581b0d42007-02-28 19:57:34 +00001029 Value *Replacement = 0;
1030 const APInt * Rplcmnt = VI.getBounds().getSingleElement();
1031 if (Rplcmnt)
1032 Replacement = ConstantInt::get(*Rplcmnt);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001033
1034 // If this value is not known to be some constant, figure out the lowest
1035 // rank value that it is known to be equal to (if anything).
1036 //
1037 if (Replacement == 0) {
1038 // Find out if there are any equality relationships with values of lower
1039 // rank than VI itself...
1040 unsigned MinRank = getRank(I->first);
1041
1042 // Loop over the relationships known about Op0.
1043 const std::vector<Relation> &Relationships = VI.getRelationships();
1044 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001045 if (Relationships[i].getRelation() == FCmpInst::FCMP_OEQ) {
1046 unsigned R = getRank(Relationships[i].getValue());
1047 if (R < MinRank) {
1048 MinRank = R;
1049 Replacement = Relationships[i].getValue();
1050 }
1051 }
1052 else if (Relationships[i].getRelation() == ICmpInst::ICMP_EQ) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001053 unsigned R = getRank(Relationships[i].getValue());
1054 if (R < MinRank) {
1055 MinRank = R;
1056 Replacement = Relationships[i].getValue();
1057 }
1058 }
1059 }
1060
1061 // If we found something to replace this value with, keep track of it.
1062 if (Replacement)
1063 VI.setReplacement(Replacement);
1064 }
1065}
1066
1067// SimplifyBasicBlock - Given information about values in region RI, simplify
1068// the instructions in the specified basic block.
1069//
1070bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
1071 bool Changed = false;
1072 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
Chris Lattnere408e252003-04-23 16:37:45 +00001073 Instruction *Inst = I++;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001074
1075 // Convert instruction arguments to canonical forms...
1076 Changed |= SimplifyInstruction(Inst, RI);
1077
Reid Spencere4d87aa2006-12-23 06:05:41 +00001078 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001079 // Try to simplify a setcc instruction based on inherited information
Reid Spencere4d87aa2006-12-23 06:05:41 +00001080 Relation::KnownResult Result = getCmpResult(CI, RI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001081 if (Result != Relation::Unknown) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001082 DEBUG(cerr << "Replacing icmp with " << Result
1083 << " constant: " << *CI);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001084
Reid Spencer579dca12007-01-12 04:24:46 +00001085 CI->replaceAllUsesWith(ConstantInt::get(Type::Int1Ty, (bool)Result));
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001086 // The instruction is now dead, remove it from the program.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001087 CI->getParent()->getInstList().erase(CI);
1088 ++NumCmpRemoved;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001089 Changed = true;
1090 }
1091 }
1092 }
1093
1094 return Changed;
1095}
1096
1097// SimplifyInstruction - Inspect the operands of the instruction, converting
Chris Lattner065a6162003-09-10 05:29:43 +00001098// them to their canonical form if possible. This takes care of, for example,
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001099// replacing a value 'X' with a constant 'C' if the instruction in question is
1100// dominated by a true seteq 'X', 'C'.
1101//
1102bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
1103 bool Changed = false;
1104
1105 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1106 if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
1107 if (Value *Repl = VI->getReplacement()) {
1108 // If we know if a replacement with lower rank than Op0, make the
1109 // replacement now.
Bill Wendling832171c2006-12-07 20:04:42 +00001110 DOUT << "In Inst: " << *I << " Replacing operand #" << i
1111 << " with " << *Repl << "\n";
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001112 I->setOperand(i, Repl);
1113 Changed = true;
1114 ++NumOperandsCann;
1115 }
1116
1117 return Changed;
1118}
1119
Reid Spencere4d87aa2006-12-23 06:05:41 +00001120// getCmpResult - Try to simplify a cmp instruction based on information
1121// inherited from a dominating icmp instruction. V is one of the operands to
1122// the icmp instruction, and VI is the set of information known about it. We
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001123// take two cases into consideration here. If the comparison is against a
1124// constant value, we can use the constant range to see if the comparison is
1125// possible to succeed. If it is not a comparison against a constant, we check
1126// to see if there is a known relationship between the two values. If so, we
1127// may be able to eliminate the check.
1128//
Reid Spencere4d87aa2006-12-23 06:05:41 +00001129Relation::KnownResult CEE::getCmpResult(CmpInst *CI,
1130 const RegionInfo &RI) {
1131 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1132 unsigned short predicate = CI->getPredicate();
Misha Brukmanfd939082005-04-21 23:48:37 +00001133
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001134 if (isa<Constant>(Op0)) {
1135 if (isa<Constant>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001136 if (Constant *Result = ConstantFoldInstruction(CI)) {
1137 // Wow, this is easy, directly eliminate the ICmpInst.
1138 DEBUG(cerr << "Replacing cmp with constant fold: " << *CI);
Reid Spencer579dca12007-01-12 04:24:46 +00001139 return cast<ConstantInt>(Result)->getZExtValue()
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001140 ? Relation::KnownTrue : Relation::KnownFalse;
1141 }
1142 } else {
1143 // We want to swap this instruction so that operand #0 is the constant.
1144 std::swap(Op0, Op1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001145 if (isa<ICmpInst>(CI))
1146 predicate = cast<ICmpInst>(CI)->getSwappedPredicate();
1147 else
1148 predicate = cast<FCmpInst>(CI)->getSwappedPredicate();
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001149 }
1150 }
1151
1152 // Try to figure out what the result of this comparison will be...
1153 Relation::KnownResult Result = Relation::Unknown;
1154
1155 // We have to know something about the relationship to prove anything...
1156 if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
1157
1158 // At this point, we know that if we have a constant argument that it is in
1159 // Op1. Check to see if we know anything about comparing value with a
Reid Spencere4d87aa2006-12-23 06:05:41 +00001160 // constant, and if we can use this info to fold the icmp.
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001161 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001162 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001163 // Check to see if we already know the result of this comparison...
Reid Spencerc6aedf72007-02-28 22:03:51 +00001164 ICmpInst::Predicate ipred = ICmpInst::Predicate(predicate);
1165 ConstantRange R = ICmpInst::makeConstantRange(ipred, C->getValue());
Reid Spencera6e8a952007-03-01 07:54:15 +00001166 ConstantRange Int = R.intersectWith(Op0VI->getBounds());
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001167
1168 // If the intersection of the two ranges is empty, then the condition
1169 // could never be true!
Misha Brukmanfd939082005-04-21 23:48:37 +00001170 //
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001171 if (Int.isEmptySet()) {
1172 Result = Relation::KnownFalse;
1173
1174 // Otherwise, if VI.getBounds() (the possible values) is a subset of R
1175 // (the allowed values) then we know that the condition must always be
1176 // true!
1177 //
1178 } else if (Int == Op0VI->getBounds()) {
1179 Result = Relation::KnownTrue;
1180 }
1181 } else {
1182 // If we are here, we know that the second argument is not a constant
1183 // integral. See if we know anything about Op0 & Op1 that allows us to
1184 // fold this anyway.
1185 //
1186 // Do we have value information about Op0 and a relation to Op1?
1187 if (const Relation *Op2R = Op0VI->requestRelation(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001188 Result = Op2R->getImpliedResult(predicate);
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001189 }
1190 }
1191 return Result;
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// Relation Implementation
1196//===----------------------------------------------------------------------===//
1197
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001198// contradicts - Return true if the relationship specified by the operand
1199// contradicts already known information.
1200//
Reid Spencere4d87aa2006-12-23 06:05:41 +00001201bool Relation::contradicts(unsigned Op,
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001202 const ValueInfo &VI) const {
1203 assert (Op != Instruction::Add && "Invalid relation argument!");
1204
1205 // If this is a relationship with a constant, make sure that this relationship
1206 // does not contradict properties known about the bounds of the constant.
1207 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001208 if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001209 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
Reid Spencerc6aedf72007-02-28 22:03:51 +00001210 Op <= ICmpInst::LAST_ICMP_PREDICATE) {
1211 ICmpInst::Predicate ipred = ICmpInst::Predicate(Op);
Reid Spencera6e8a952007-03-01 07:54:15 +00001212 if (ICmpInst::makeConstantRange(ipred, C->getValue())
1213 .intersectWith(VI.getBounds()).isEmptySet())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001214 return true;
Reid Spencerc6aedf72007-02-28 22:03:51 +00001215 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001216
1217 switch (Rel) {
1218 default: assert(0 && "Unknown Relationship code!");
1219 case Instruction::Add: return false; // Nothing known, nothing contradicts
Reid Spencere4d87aa2006-12-23 06:05:41 +00001220 case ICmpInst::ICMP_EQ:
1221 return Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT ||
1222 Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT ||
1223 Op == ICmpInst::ICMP_NE;
1224 case ICmpInst::ICMP_NE: return Op == ICmpInst::ICMP_EQ;
1225 case ICmpInst::ICMP_ULE:
1226 case ICmpInst::ICMP_SLE: return Op == ICmpInst::ICMP_UGT ||
1227 Op == ICmpInst::ICMP_SGT;
1228 case ICmpInst::ICMP_UGE:
1229 case ICmpInst::ICMP_SGE: return Op == ICmpInst::ICMP_ULT ||
1230 Op == ICmpInst::ICMP_SLT;
1231 case ICmpInst::ICMP_ULT:
1232 case ICmpInst::ICMP_SLT:
1233 return Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_UGT ||
1234 Op == ICmpInst::ICMP_SGT || Op == ICmpInst::ICMP_UGE ||
1235 Op == ICmpInst::ICMP_SGE;
1236 case ICmpInst::ICMP_UGT:
1237 case ICmpInst::ICMP_SGT:
1238 return Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_ULT ||
1239 Op == ICmpInst::ICMP_SLT || Op == ICmpInst::ICMP_ULE ||
1240 Op == ICmpInst::ICMP_SLE;
1241 case FCmpInst::FCMP_OEQ:
1242 return Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT ||
1243 Op == FCmpInst::FCMP_ONE;
1244 case FCmpInst::FCMP_ONE: return Op == FCmpInst::FCMP_OEQ;
1245 case FCmpInst::FCMP_OLE: return Op == FCmpInst::FCMP_OGT;
1246 case FCmpInst::FCMP_OGE: return Op == FCmpInst::FCMP_OLT;
1247 case FCmpInst::FCMP_OLT:
1248 return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT ||
1249 Op == FCmpInst::FCMP_OGE;
1250 case FCmpInst::FCMP_OGT:
1251 return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT ||
1252 Op == FCmpInst::FCMP_OLE;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001253 }
1254}
1255
1256// incorporate - Incorporate information in the argument into this relation
1257// entry. This assumes that the information doesn't contradict itself. If any
1258// new information is gained, true is returned, otherwise false is returned to
1259// indicate that nothing was updated.
1260//
Reid Spencere4d87aa2006-12-23 06:05:41 +00001261bool Relation::incorporate(unsigned Op, ValueInfo &VI) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001262 assert(!contradicts(Op, VI) &&
1263 "Cannot incorporate contradictory information!");
1264
1265 // If this is a relationship with a constant, make sure that we update the
1266 // range that is possible for the value to have...
1267 //
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001268 if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001269 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
Reid Spencerc6aedf72007-02-28 22:03:51 +00001270 Op <= ICmpInst::LAST_ICMP_PREDICATE) {
1271 ICmpInst::Predicate ipred = ICmpInst::Predicate(Op);
Reid Spencerdc5c1592007-02-28 18:57:32 +00001272 VI.getBounds() =
Reid Spencera6e8a952007-03-01 07:54:15 +00001273 ICmpInst::makeConstantRange(ipred, C->getValue())
1274 .intersectWith(VI.getBounds());
Reid Spencerc6aedf72007-02-28 22:03:51 +00001275 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001276
1277 switch (Rel) {
1278 default: assert(0 && "Unknown prior value!");
1279 case Instruction::Add: Rel = Op; return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001280 case ICmpInst::ICMP_EQ:
1281 case ICmpInst::ICMP_NE:
1282 case ICmpInst::ICMP_ULT:
1283 case ICmpInst::ICMP_SLT:
1284 case ICmpInst::ICMP_UGT:
1285 case ICmpInst::ICMP_SGT: return false; // Nothing is more precise
1286 case ICmpInst::ICMP_ULE:
1287 case ICmpInst::ICMP_SLE:
1288 if (Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_ULT ||
1289 Op == ICmpInst::ICMP_SLT) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001290 Rel = Op;
1291 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001292 } else if (Op == ICmpInst::ICMP_NE) {
1293 Rel = Rel == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_ULT :
1294 ICmpInst::ICMP_SLT;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001295 return true;
1296 }
1297 return false;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001298 case ICmpInst::ICMP_UGE:
1299 case ICmpInst::ICMP_SGE:
1300 if (Op == ICmpInst::ICMP_EQ || ICmpInst::ICMP_UGT ||
1301 Op == ICmpInst::ICMP_SGT) {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001302 Rel = Op;
1303 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001304 } else if (Op == ICmpInst::ICMP_NE) {
1305 Rel = Rel == ICmpInst::ICMP_UGE ? ICmpInst::ICMP_UGT :
1306 ICmpInst::ICMP_SGT;
1307 return true;
1308 }
1309 return false;
1310 case FCmpInst::FCMP_OEQ: return false; // Nothing is more precise
1311 case FCmpInst::FCMP_ONE: return false; // Nothing is more precise
1312 case FCmpInst::FCMP_OLT: return false; // Nothing is more precise
1313 case FCmpInst::FCMP_OGT: return false; // Nothing is more precise
1314 case FCmpInst::FCMP_OLE:
1315 if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT) {
1316 Rel = Op;
1317 return true;
1318 } else if (Op == FCmpInst::FCMP_ONE) {
1319 Rel = FCmpInst::FCMP_OLT;
1320 return true;
1321 }
1322 return false;
1323 case FCmpInst::FCMP_OGE:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001324 if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT) {
1325 Rel = Op;
1326 return true;
1327 } else if (Op == FCmpInst::FCMP_ONE) {
1328 Rel = FCmpInst::FCMP_OGT;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001329 return true;
1330 }
1331 return false;
1332 }
1333}
1334
1335// getImpliedResult - If this relationship between two values implies that
1336// the specified relationship is true or false, return that. If we cannot
1337// determine the result required, return Unknown.
1338//
1339Relation::KnownResult
Reid Spencere4d87aa2006-12-23 06:05:41 +00001340Relation::getImpliedResult(unsigned Op) const {
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001341 if (Rel == Op) return KnownTrue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001342 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
1343 Op <= ICmpInst::LAST_ICMP_PREDICATE) {
1344 if (Rel == unsigned(ICmpInst::getInversePredicate(ICmpInst::Predicate(Op))))
1345 return KnownFalse;
1346 } else if (Op <= FCmpInst::LAST_FCMP_PREDICATE) {
1347 if (Rel == unsigned(FCmpInst::getInversePredicate(FCmpInst::Predicate(Op))))
1348 return KnownFalse;
1349 }
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001350
1351 switch (Rel) {
1352 default: assert(0 && "Unknown prior value!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001353 case ICmpInst::ICMP_EQ:
1354 if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE ||
1355 Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE) return KnownTrue;
1356 if (Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT ||
1357 Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT) return KnownFalse;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001358 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001359 case ICmpInst::ICMP_ULT:
1360 case ICmpInst::ICMP_SLT:
1361 if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE ||
1362 Op == ICmpInst::ICMP_NE) return KnownTrue;
1363 if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001364 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001365 case ICmpInst::ICMP_UGT:
1366 case ICmpInst::ICMP_SGT:
1367 if (Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE ||
1368 Op == ICmpInst::ICMP_NE) return KnownTrue;
1369 if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001370 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001371 case FCmpInst::FCMP_OEQ:
1372 if (Op == FCmpInst::FCMP_OLE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1373 if (Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT) return KnownFalse;
1374 break;
1375 case FCmpInst::FCMP_OLT:
1376 if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OLE) return KnownTrue;
1377 if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1378 break;
1379 case FCmpInst::FCMP_OGT:
1380 if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1381 if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1382 break;
1383 case ICmpInst::ICMP_NE:
1384 case ICmpInst::ICMP_SLE:
1385 case ICmpInst::ICMP_ULE:
1386 case ICmpInst::ICMP_UGE:
1387 case ICmpInst::ICMP_SGE:
1388 case FCmpInst::FCMP_ONE:
1389 case FCmpInst::FCMP_OLE:
1390 case FCmpInst::FCMP_OGE:
1391 case FCmpInst::FCMP_FALSE:
1392 case FCmpInst::FCMP_ORD:
1393 case FCmpInst::FCMP_UNO:
1394 case FCmpInst::FCMP_UEQ:
1395 case FCmpInst::FCMP_UGT:
1396 case FCmpInst::FCMP_UGE:
1397 case FCmpInst::FCMP_ULT:
1398 case FCmpInst::FCMP_ULE:
1399 case FCmpInst::FCMP_UNE:
1400 case FCmpInst::FCMP_TRUE:
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001401 break;
1402 }
1403 return Unknown;
1404}
1405
1406
1407//===----------------------------------------------------------------------===//
1408// Printing Support...
1409//===----------------------------------------------------------------------===//
1410
1411// print - Implement the standard print form to print out analysis information.
1412void CEE::print(std::ostream &O, const Module *M) const {
1413 O << "\nPrinting Correlated Expression Info:\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001414 for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001415 RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
1416 I->second.print(O);
1417}
1418
1419// print - Output information about this region...
1420void RegionInfo::print(std::ostream &OS) const {
1421 if (ValueMap.empty()) return;
1422
1423 OS << " RegionInfo for basic block: " << BB->getName() << "\n";
1424 for (std::map<Value*, ValueInfo>::const_iterator
1425 I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
1426 I->second.print(OS, I->first);
1427 OS << "\n";
1428}
1429
1430// print - Output information about this value relation...
1431void ValueInfo::print(std::ostream &OS, Value *V) const {
1432 if (Relationships.empty()) return;
1433
1434 if (V) {
1435 OS << " ValueInfo for: ";
1436 WriteAsOperand(OS, V);
1437 }
1438 OS << "\n Bounds = " << Bounds << "\n";
1439 if (Replacement) {
1440 OS << " Replacement = ";
1441 WriteAsOperand(OS, Replacement);
1442 OS << "\n";
1443 }
1444 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1445 Relationships[i].print(OS);
1446}
1447
1448// print - Output this relation to the specified stream
1449void Relation::print(std::ostream &OS) const {
1450 OS << " is ";
1451 switch (Rel) {
1452 default: OS << "*UNKNOWN*"; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001453 case ICmpInst::ICMP_EQ:
1454 case FCmpInst::FCMP_ORD:
1455 case FCmpInst::FCMP_UEQ:
1456 case FCmpInst::FCMP_OEQ: OS << "== "; break;
1457 case ICmpInst::ICMP_NE:
1458 case FCmpInst::FCMP_UNO:
1459 case FCmpInst::FCMP_UNE:
1460 case FCmpInst::FCMP_ONE: OS << "!= "; break;
1461 case ICmpInst::ICMP_ULT:
1462 case ICmpInst::ICMP_SLT:
1463 case FCmpInst::FCMP_ULT:
1464 case FCmpInst::FCMP_OLT: OS << "< "; break;
1465 case ICmpInst::ICMP_UGT:
1466 case ICmpInst::ICMP_SGT:
1467 case FCmpInst::FCMP_UGT:
1468 case FCmpInst::FCMP_OGT: OS << "> "; break;
1469 case ICmpInst::ICMP_ULE:
1470 case ICmpInst::ICMP_SLE:
1471 case FCmpInst::FCMP_ULE:
1472 case FCmpInst::FCMP_OLE: OS << "<= "; break;
1473 case ICmpInst::ICMP_UGE:
1474 case ICmpInst::ICMP_SGE:
1475 case FCmpInst::FCMP_UGE:
1476 case FCmpInst::FCMP_OGE: OS << ">= "; break;
Chris Lattnerb0dbd7f2002-09-06 18:41:55 +00001477 }
1478
1479 WriteAsOperand(OS, Val);
1480 OS << "\n";
1481}
1482
Chris Lattnerf7f009d2002-10-08 21:34:15 +00001483// Don't inline these methods or else we won't be able to call them from GDB!
Bill Wendling832171c2006-12-07 20:04:42 +00001484void Relation::dump() const { print(*cerr.stream()); }
1485void ValueInfo::dump() const { print(*cerr.stream(), 0); }
1486void RegionInfo::dump() const { print(*cerr.stream()); }