Initial checkin of Correlated Expression Elimination Pass
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedExprs.cpp
1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
2 //
3 // Correlated Expression Elimination propogates information from conditional
4 // branches to blocks dominated by destinations of the branch.  It propogates
5 // information from the condition check itself into the body of the branch,
6 // allowing transformations like these for example:
7 //
8 //  if (i == 7)
9 //    ... 4*i;  // constant propogation
10 //
11 //  M = i+1; N = j+1;
12 //  if (i == j)
13 //    X = M-N;  // = M-M == 0;
14 //
15 // This is called Correlated Expression Elimination because we eliminate or
16 // simplify expressions that are correlated with the direction of a branch.  In
17 // this way we use static information to give us some information about the
18 // dynamic value of a variable.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOperators.h"
27 #include "llvm/ConstantHandling.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/PostOrderIterator.h"
34 #include "Support/StatisticReporter.h"
35 #include <algorithm>
36
37 namespace {
38   Statistic<>NumSetCCRemoved("cee\t\t- Number of setcc instruction eliminated");
39   Statistic<>NumOperandsCann("cee\t\t- Number of operands cannonicalized");
40   Statistic<>BranchRevectors("cee\t\t- Number of branches revectored");
41
42   class ValueInfo;
43   class Relation {
44     Value *Val;                 // Relation to what value?
45     Instruction::BinaryOps Rel; // SetCC relation, or Add if no information
46   public:
47     Relation(Value *V) : Val(V), Rel(Instruction::Add) {}
48     bool operator<(const Relation &R) const { return Val < R.Val; }
49     Value *getValue() const { return Val; }
50     Instruction::BinaryOps getRelation() const { return Rel; }
51
52     // contradicts - Return true if the relationship specified by the operand
53     // contradicts already known information.
54     //
55     bool contradicts(Instruction::BinaryOps Rel, const ValueInfo &VI) const;
56
57     // incorporate - Incorporate information in the argument into this relation
58     // entry.  This assumes that the information doesn't contradict itself.  If
59     // any new information is gained, true is returned, otherwise false is
60     // returned to indicate that nothing was updated.
61     //
62     bool incorporate(Instruction::BinaryOps Rel, ValueInfo &VI);
63
64     // KnownResult - Whether or not this condition determines the result of a
65     // setcc in the program.  False & True are intentionally 0 & 1 so we can
66     // convert to bool by casting after checking for unknown.
67     //
68     enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
69
70     // getImpliedResult - If this relationship between two values implies that
71     // the specified relationship is true or false, return that.  If we cannot
72     // determine the result required, return Unknown.
73     //
74     KnownResult getImpliedResult(Instruction::BinaryOps Rel) const;
75
76     // print - Output this relation to the specified stream
77     void print(std::ostream &OS) const;
78     void dump() const;
79   };
80
81
82   // ValueInfo - One instance of this record exists for every value with
83   // relationships between other values.  It keeps track of all of the
84   // relationships to other values in the program (specified with Relation) that
85   // are known to be valid in a region.
86   //
87   class ValueInfo {
88     // RelationShips - this value is know to have the specified relationships to
89     // other values.  There can only be one entry per value, and this list is
90     // kept sorted by the Val field.
91     std::vector<Relation> Relationships;
92
93     // If information about this value is known or propogated from constant
94     // expressions, this range contains the possible values this value may hold.
95     ConstantRange Bounds;
96
97     // If we find that this value is equal to another value that has a lower
98     // rank, this value is used as it's replacement.
99     //
100     Value *Replacement;
101   public:
102     ValueInfo(const Type *Ty)
103       : Bounds(Ty->isIntegral() ? Ty : Type::IntTy), Replacement(0) {}
104
105     // getBounds() - Return the constant bounds of the value...
106     const ConstantRange &getBounds() const { return Bounds; }
107     ConstantRange &getBounds() { return Bounds; }
108
109     const std::vector<Relation> &getRelationships() { return Relationships; }
110
111     // getReplacement - Return the value this value is to be replaced with if it
112     // exists, otherwise return null.
113     //
114     Value *getReplacement() const { return Replacement; }
115
116     // setReplacement - Used by the replacement calculation pass to figure out
117     // what to replace this value with, if anything.
118     //
119     void setReplacement(Value *Repl) { Replacement = Repl; }
120
121     // getRelation - return the relationship entry for the specified value.
122     // This can invalidate references to other Relation's, so use it carefully.
123     //
124     Relation &getRelation(Value *V) {
125       // Binary search for V's entry...
126       std::vector<Relation>::iterator I =
127         std::lower_bound(Relationships.begin(), Relationships.end(), V);
128
129       // If we found the entry, return it...
130       if (I != Relationships.end() && I->getValue() == V)
131         return *I;
132
133       // Insert and return the new relationship...
134       return *Relationships.insert(I, V);
135     }
136
137     const Relation *requestRelation(Value *V) const {
138       // Binary search for V's entry...
139       std::vector<Relation>::const_iterator I =
140         std::lower_bound(Relationships.begin(), Relationships.end(), V);
141       if (I != Relationships.end() && I->getValue() == V)
142         return &*I;
143       return 0;
144     }
145
146     // print - Output information about this value relation...
147     void print(std::ostream &OS, Value *V) const;
148     void dump() const;
149   };
150
151   // RegionInfo - Keeps track of all of the value relationships for a region.  A
152   // region is the are dominated by a basic block.  RegionInfo's keep track of
153   // the RegionInfo for their dominator, because anything known in a dominator
154   // is known to be true in a dominated block as well.
155   //
156   class RegionInfo {
157     BasicBlock *BB;
158
159     // ValueMap - Tracks the ValueInformation known for this region
160     typedef std::map<Value*, ValueInfo> ValueMapTy;
161     ValueMapTy ValueMap;
162   public:
163     RegionInfo(BasicBlock *bb) : BB(bb) {}
164
165     // getEntryBlock - Return the block that dominates all of the members of
166     // this region.
167     BasicBlock *getEntryBlock() const { return BB; }
168
169     const RegionInfo &operator=(const RegionInfo &RI) {
170       ValueMap = RI.ValueMap;
171       return *this;
172     }
173
174     // print - Output information about this region...
175     void print(std::ostream &OS) const;
176
177     // Allow external access.
178     typedef ValueMapTy::iterator iterator;
179     iterator begin() { return ValueMap.begin(); }
180     iterator end() { return ValueMap.end(); }
181
182     ValueInfo &getValueInfo(Value *V) {
183       ValueMapTy::iterator I = ValueMap.lower_bound(V);
184       if (I != ValueMap.end() && I->first == V) return I->second;
185       return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
186     }
187
188     const ValueInfo *requestValueInfo(Value *V) const {
189       ValueMapTy::const_iterator I = ValueMap.find(V);
190       if (I != ValueMap.end()) return &I->second;
191       return 0;
192     }
193   };
194
195   /// CEE - Correlated Expression Elimination
196   class CEE : public FunctionPass {
197     std::map<Value*, unsigned> RankMap;
198     std::map<BasicBlock*, RegionInfo> RegionInfoMap;
199     DominatorSet *DS;
200     DominatorTree *DT;
201   public:
202     virtual bool runOnFunction(Function &F);
203
204     // We don't modify the program, so we preserve all analyses
205     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
206       //AU.preservesCFG();
207       AU.addRequired<DominatorSet>();
208       AU.addRequired<DominatorTree>();
209     };
210
211     // print - Implement the standard print form to print out analysis
212     // information.
213     virtual void print(std::ostream &O, const Module *M) const;
214
215     virtual void releaseMemory() {
216       RegionInfoMap.clear();
217       RankMap.clear();
218     }
219
220   private:
221     RegionInfo &getRegionInfo(BasicBlock *BB) {
222       std::map<BasicBlock*, RegionInfo>::iterator I
223         = RegionInfoMap.lower_bound(BB);
224       if (I != RegionInfoMap.end() && I->first == BB) return I->second;
225       return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
226     }
227
228     void BuildRankMap(Function &F);
229     unsigned getRank(Value *V) const {
230       if (isa<Constant>(V) || isa<GlobalValue>(V)) return 0;
231       std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
232       if (I != RankMap.end()) return I->second;
233       return 0; // Must be some other global thing
234     }
235
236     bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
237
238     BasicBlock *isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI);
239     void PropogateBranchInfo(BranchInst *BI);
240     void PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
241     void PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
242                            Value *Op1, RegionInfo &RI);
243     void UpdateUsersOfValue(Value *V, RegionInfo &RI);
244     void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
245     void ComputeReplacements(RegionInfo &RI);
246
247
248     // getSetCCResult - Given a setcc instruction, determine if the result is
249     // determined by facts we already know about the region under analysis.
250     // Return KnownTrue, KnownFalse, or Unknown based on what we can determine.
251     //
252     Relation::KnownResult getSetCCResult(SetCondInst *SC, const RegionInfo &RI);
253
254
255     bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
256     bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
257   }; 
258   RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
259 }
260
261 Pass *createCorrelatedExpressionEliminationPass() { return new CEE(); }
262
263
264 bool CEE::runOnFunction(Function &F) {
265   // Build a rank map for the function...
266   BuildRankMap(F);
267
268   // Traverse the dominator tree, computing information for each node in the
269   // tree.  Note that our traversal will not even touch unreachable basic
270   // blocks.
271   DS = &getAnalysis<DominatorSet>();
272   DT = &getAnalysis<DominatorTree>();
273   
274   std::set<BasicBlock*> VisitedBlocks;
275   return TransformRegion(&F.getEntryNode(), VisitedBlocks);
276 }
277
278 // TransformRegion - Transform the region starting with BB according to the
279 // calculated region information for the block.  Transforming the region
280 // involves analyzing any information this block provides to successors,
281 // propogating the information to successors, and finally transforming
282 // successors.
283 //
284 // This method processes the function in depth first order, which guarantees
285 // that we process the immediate dominator of a block before the block itself.
286 // Because we are passing information from immediate dominators down to
287 // dominatees, we obviously have to process the information source before the
288 // information consumer.
289 //
290 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
291   // Prevent infinite recursion...
292   if (VisitedBlocks.count(BB)) return false;
293   VisitedBlocks.insert(BB);
294
295   // Get the computed region information for this block...
296   RegionInfo &RI = getRegionInfo(BB);
297
298   // Compute the replacement information for this block...
299   ComputeReplacements(RI);
300
301   // If debugging, print computed region information...
302   DEBUG(RI.print(std::cerr));
303
304   // Simplify the contents of this block...
305   bool Changed = SimplifyBasicBlock(*BB, RI);
306
307   // Get the terminator of this basic block...
308   TerminatorInst *TI = BB->getTerminator();
309
310   // If this is a conditional branch, make sure that there is a branch target
311   // for each successor that can hold any information gleaned from the branch,
312   // by breaking any critical edges that may be laying about.
313   //
314   if (TI->getNumSuccessors() > 1) {
315     // If any of the successors has multiple incoming branches, add a new dummy
316     // destination branch that only contains an unconditional branch to the real
317     // target.
318     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
319       BasicBlock *Succ = TI->getSuccessor(i);
320       // If there is more than one predecessor of the destination block, break
321       // this critical edge by inserting a new block.  This updates dominatorset
322       // and dominatortree information.
323       //
324       if (isCriticalEdge(TI, i))
325         SplitCriticalEdge(TI, i, this);
326     }
327   }
328
329   // Loop over all of the blocks that this block is the immediate dominator for.
330   // Because all information known in this region is also known in all of the
331   // blocks that are dominated by this one, we can safely propogate the
332   // information down now.
333   //
334   DominatorTree::Node *BBN = (*DT)[BB];
335   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
336     BasicBlock *Dominated = BBN->getChildren()[i]->getNode();
337     assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
338            "RegionInfo should be calculated in dominanace order!");
339     getRegionInfo(Dominated) = RI;
340   }
341
342   // Now that all of our successors have information if they deserve it,
343   // propogate any information our terminator instruction finds to our
344   // successors.
345   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
346     if (BI->isConditional())
347       PropogateBranchInfo(BI);
348
349   // If this is a branch to a block outside our region that simply performs
350   // another conditional branch, one whose outcome is known inside of this
351   // region, then vector this outgoing edge directly to the known destination.
352   //
353   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
354     while (BasicBlock *Dest = isCorrelatedBranchBlock(TI->getSuccessor(i), RI)){
355       TI->setSuccessor(i, Dest);
356       ++BranchRevectors;
357     }
358   }
359
360   // Now that all of our successors have information, recursively process them.
361   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i)
362     Changed |= TransformRegion(BBN->getChildren()[i]->getNode(), VisitedBlocks);
363
364     //  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
365     //Changed |= TransformRegion(TI->getSuccessor(i), VisitedBlocks);
366
367   return Changed;
368 }
369
370 // If this block is a simple block not in the current region, which contains
371 // only a conditional branch, we determine if the outcome of the branch can be
372 // determined from information inside of the region.  Instead of going to this
373 // block, we can instead go to the destination we know is the right target.
374 //
375 BasicBlock *CEE::isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI) {
376   // Check to see if we dominate the block. If so, this block will get the
377   // condition turned to a constant anyway.
378   //
379   //if (DS->dominates(RI.getEntryBlock(), BB))
380   // return 0;
381
382   // Check to see if this is a conditional branch...
383   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
384     if (BI->isConditional()) {
385       // Make sure that the block is either empty, or only contains a setcc.
386       if (BB->size() == 1 || 
387           (BB->size() == 2 && &BB->front() == BI->getCondition() &&
388            BI->getCondition()->use_size() == 1))
389         if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition())) {
390           Relation::KnownResult Result = getSetCCResult(SCI, RI);
391         
392           if (Result == Relation::KnownTrue)
393             return BI->getSuccessor(0);
394           else if (Result == Relation::KnownFalse)
395             return BI->getSuccessor(1);
396         }
397     }
398   return 0;
399 }
400
401 // BuildRankMap - This method builds the rank map data structure which gives
402 // each instruction/value in the function a value based on how early it appears
403 // in the function.  We give constants and globals rank 0, arguments are
404 // numbered starting at one, and instructions are numbered in reverse post-order
405 // from where the arguments leave off.  This gives instructions in loops higher
406 // values than instructions not in loops.
407 //
408 void CEE::BuildRankMap(Function &F) {
409   unsigned Rank = 1;  // Skip rank zero.
410
411   // Number the arguments...
412   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
413     RankMap[I] = Rank++;
414
415   // Number the instructions in reverse post order...
416   ReversePostOrderTraversal<Function*> RPOT(&F);
417   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
418          E = RPOT.end(); I != E; ++I)
419     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
420          BBI != E; ++BBI)
421       if (BBI->getType() != Type::VoidTy)
422         RankMap[BBI] = Rank++;
423 }
424
425
426 // PropogateBranchInfo - When this method is invoked, we need to propogate
427 // information derived from the branch condition into the true and false
428 // branches of BI.  Since we know that there aren't any critical edges in the
429 // flow graph, this can proceed unconditionally.
430 //
431 void CEE::PropogateBranchInfo(BranchInst *BI) {
432   assert(BI->isConditional() && "Must be a conditional branch!");
433   BasicBlock *BB = BI->getParent();
434   BasicBlock *TrueBB  = BI->getSuccessor(0);
435   BasicBlock *FalseBB = BI->getSuccessor(1);
436
437   // Propogate information into the true block...
438   //
439   PropogateEquality(BI->getCondition(), ConstantBool::True,
440                     getRegionInfo(TrueBB));
441   
442   // Propogate information into the false block...
443   //
444   PropogateEquality(BI->getCondition(), ConstantBool::False,
445                     getRegionInfo(FalseBB));
446 }
447
448
449 // PropogateEquality - If we discover that two values are equal to each other in
450 // a specified region, propogate this knowledge recursively.
451 //
452 void CEE::PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
453   if (Op0 == Op1) return;  // Gee whiz. Are these really equal each other?
454
455   if (isa<Constant>(Op0))  // Make sure the constant is always Op1
456     std::swap(Op0, Op1);
457
458   // Make sure we don't already know these are equal, to avoid infinite loops...
459   ValueInfo &VI = RI.getValueInfo(Op0);
460
461   // Get information about the known relationship between Op0 & Op1
462   Relation &KnownRelation = VI.getRelation(Op1);
463
464   // If we already know they're equal, don't reprocess...
465   if (KnownRelation.getRelation() == Instruction::SetEQ)
466     return;
467
468   // If this is boolean, check to see if one of the operands is a constant.  If
469   // it's a constant, then see if the other one is one of a setcc instruction,
470   // an AND, OR, or XOR instruction.
471   //
472   if (ConstantBool *CB = dyn_cast<ConstantBool>(Op1)) {
473
474     if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
475       // If we know that this instruction is an AND instruction, and the result
476       // is true, this means that both operands to the OR are known to be true
477       // as well.
478       //
479       if (CB->getValue() && Inst->getOpcode() == Instruction::And) {
480         PropogateEquality(Inst->getOperand(0), CB, RI);
481         PropogateEquality(Inst->getOperand(1), CB, RI);
482       }
483       
484       // If we know that this instruction is an OR instruction, and the result
485       // is false, this means that both operands to the OR are know to be false
486       // as well.
487       //
488       if (!CB->getValue() && Inst->getOpcode() == Instruction::Or) {
489         PropogateEquality(Inst->getOperand(0), CB, RI);
490         PropogateEquality(Inst->getOperand(1), CB, RI);
491       }
492       
493       // If we know that this instruction is a NOT instruction, we know that the
494       // operand is known to be the inverse of whatever the current value is.
495       //
496       if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
497         if (BinaryOperator::isNot(BOp))
498           PropogateEquality(BinaryOperator::getNotArgument(BOp),
499                             ConstantBool::get(!CB->getValue()), RI);
500
501       // If we know the value of a SetCC instruction, propogate the information
502       // about the relation into this region as well.
503       //
504       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
505         if (CB->getValue()) {  // If we know the condition is true...
506           // Propogate info about the LHS to the RHS & RHS to LHS
507           PropogateRelation(SCI->getOpcode(), SCI->getOperand(0),
508                             SCI->getOperand(1), RI);
509           PropogateRelation(SCI->getSwappedCondition(),
510                             SCI->getOperand(1), SCI->getOperand(0), RI);
511
512         } else {               // If we know the condition is false...
513           // We know the opposite of the condition is true...
514           Instruction::BinaryOps C = SCI->getInverseCondition();
515           
516           PropogateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
517           PropogateRelation(SetCondInst::getSwappedCondition(C),
518                             SCI->getOperand(1), SCI->getOperand(0), RI);
519         }
520       }
521     }
522   }
523
524   // Propogate information about Op0 to Op1 & visa versa
525   PropogateRelation(Instruction::SetEQ, Op0, Op1, RI);
526   PropogateRelation(Instruction::SetEQ, Op1, Op0, RI);
527 }
528
529
530 // PropogateRelation - We know that the specified relation is true in all of the
531 // blocks in the specified region.  Propogate the information about Op0 and
532 // anything derived from it into this region.
533 //
534 void CEE::PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
535                             Value *Op1, RegionInfo &RI) {
536   assert(Op0->getType() == Op1->getType() && "Equal types expected!");
537
538   // Constants are already pretty well understood.  We will apply information
539   // about the constant to Op1 in another call to PropogateRelation.
540   //
541   if (isa<Constant>(Op0)) return;
542
543   // Get the region information for this block to update...
544   ValueInfo &VI = RI.getValueInfo(Op0);
545
546   // Get information about the known relationship between Op0 & Op1
547   Relation &Op1R = VI.getRelation(Op1);
548
549   // Quick bailout for common case if we are reprocessing an instruction...
550   if (Op1R.getRelation() == Opcode)
551     return;
552
553   // If we already have information that contradicts the current information we
554   // are propogating, ignore this info.  Something bad must have happened!
555   //
556   if (Op1R.contradicts(Opcode, VI)) {
557     Op1R.contradicts(Opcode, VI);
558     std::cerr << "Contradiction found for opcode: "
559               << Instruction::getOpcodeName(Opcode) << "\n";
560     Op1R.print(std::cerr);
561     return;
562   }
563
564   // If the information propogted is new, then we want process the uses of this
565   // instruction to propogate the information down to them.
566   //
567   if (Op1R.incorporate(Opcode, VI))
568     UpdateUsersOfValue(Op0, RI);
569 }
570
571
572 // UpdateUsersOfValue - The information about V in this region has been updated.
573 // Propogate this to all consumers of the value.
574 //
575 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
576   for (Value::use_iterator I = V->use_begin(), E = V->use_end();
577        I != E; ++I)
578     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
579       // If this is an instruction using a value that we know something about,
580       // try to propogate information to the value produced by the
581       // instruction.  We can only do this if it is an instruction we can
582       // propogate information for (a setcc for example), and we only WANT to
583       // do this if the instruction dominates this region.
584       //
585       // If the instruction doesn't dominate this region, then it cannot be
586       // used in this region and we don't care about it.  If the instruction
587       // is IN this region, then we will simplify the instruction before we
588       // get to uses of it anyway, so there is no reason to bother with it
589       // here.  This check is also effectively checking to make sure that Inst
590       // is in the same function as our region (in case V is a global f.e.).
591       //
592       if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
593         IncorporateInstruction(Inst, RI);
594     }
595 }
596
597 // IncorporateInstruction - We just updated the information about one of the
598 // operands to the specified instruction.  Update the information about the
599 // value produced by this instruction
600 //
601 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
602   if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
603     // See if we can figure out a result for this instruction...
604     Relation::KnownResult Result = getSetCCResult(SCI, RI);
605     if (Result != Relation::Unknown) {
606       PropogateEquality(SCI, Result ? ConstantBool::True : ConstantBool::False,
607                         RI);
608     }
609   }
610 }
611
612
613 // ComputeReplacements - Some values are known to be equal to other values in a
614 // region.  For example if there is a comparison of equality between a variable
615 // X and a constant C, we can replace all uses of X with C in the region we are
616 // interested in.  We generalize this replacement to replace variables with
617 // other variables if they are equal and there is a variable with lower rank
618 // than the current one.  This offers a cannonicalizing property that exposes
619 // more redundancies for later transformations to take advantage of.
620 //
621 void CEE::ComputeReplacements(RegionInfo &RI) {
622   // Loop over all of the values in the region info map...
623   for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
624     ValueInfo &VI = I->second;
625
626     // If we know that this value is a particular constant, set Replacement to
627     // the constant...
628     Value *Replacement = VI.getBounds().getSingleElement();
629
630     // If this value is not known to be some constant, figure out the lowest
631     // rank value that it is known to be equal to (if anything).
632     //
633     if (Replacement == 0) {
634       // Find out if there are any equality relationships with values of lower
635       // rank than VI itself...
636       unsigned MinRank = getRank(I->first);
637
638       // Loop over the relationships known about Op0.
639       const std::vector<Relation> &Relationships = VI.getRelationships();
640       for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
641         if (Relationships[i].getRelation() == Instruction::SetEQ) {
642           unsigned R = getRank(Relationships[i].getValue());
643           if (R < MinRank) {
644             MinRank = R;
645             Replacement = Relationships[i].getValue();
646           }
647         }
648     }
649
650     // If we found something to replace this value with, keep track of it.
651     if (Replacement)
652       VI.setReplacement(Replacement);
653   }
654 }
655
656 // SimplifyBasicBlock - Given information about values in region RI, simplify
657 // the instructions in the specified basic block.
658 //
659 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
660   bool Changed = false;
661   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
662     Instruction *Inst = &*I++;
663
664     // Convert instruction arguments to canonical forms...
665     Changed |= SimplifyInstruction(Inst, RI);
666
667     if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
668       // Try to simplify a setcc instruction based on inherited information
669       Relation::KnownResult Result = getSetCCResult(SCI, RI);
670       if (Result != Relation::Unknown) {
671         DEBUG(std::cerr << "Replacing setcc with " << Result
672                         << " constant: " << SCI);
673
674         SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
675         // The instruction is now dead, remove it from the program.
676         SCI->getParent()->getInstList().erase(SCI);
677         ++NumSetCCRemoved;
678         Changed = true;
679       }
680     }
681   }
682
683   return Changed;
684 }
685
686 // SimplifyInstruction - Inspect the operands of the instruction, converting
687 // them to their cannonical form if possible.  This takes care of, for example,
688 // replacing a value 'X' with a constant 'C' if the instruction in question is
689 // dominated by a true seteq 'X', 'C'.
690 //
691 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
692   bool Changed = false;
693
694   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
695     if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
696       if (Value *Repl = VI->getReplacement()) {
697         // If we know if a replacement with lower rank than Op0, make the
698         // replacement now.
699         DEBUG(std::cerr << "In Inst: " << I << "  Replacing operand #" << i
700                         << " with " << Repl << "\n");
701         I->setOperand(i, Repl);
702         Changed = true;
703         ++NumOperandsCann;
704       }
705
706   return Changed;
707 }
708
709
710 // SimplifySetCC - Try to simplify a setcc instruction based on information
711 // inherited from a dominating setcc instruction.  V is one of the operands to
712 // the setcc instruction, and VI is the set of information known about it.  We
713 // take two cases into consideration here.  If the comparison is against a
714 // constant value, we can use the constant range to see if the comparison is
715 // possible to succeed.  If it is not a comparison against a constant, we check
716 // to see if there is a known relationship between the two values.  If so, we
717 // may be able to eliminate the check.
718 //
719 Relation::KnownResult CEE::getSetCCResult(SetCondInst *SCI,
720                                           const RegionInfo &RI) {
721   Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
722   Instruction::BinaryOps Opcode = SCI->getOpcode();
723   
724   if (isa<Constant>(Op0)) {
725     if (isa<Constant>(Op1)) {
726       if (Constant *Result = ConstantFoldInstruction(SCI)) {
727         // Wow, this is easy, directly eliminate the SetCondInst.
728         DEBUG(std::cerr << "Replacing setcc with constant fold: " << SCI);
729         return cast<ConstantBool>(Result)->getValue()
730           ? Relation::KnownTrue : Relation::KnownFalse;
731       }
732     } else {
733       // We want to swap this instruction so that operand #0 is the constant.
734       std::swap(Op0, Op1);
735       Opcode = SCI->getSwappedCondition();
736     }
737   }
738
739   // Try to figure out what the result of this comparison will be...
740   Relation::KnownResult Result = Relation::Unknown;
741
742   // We have to know something about the relationship to prove anything...
743   if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
744
745     // At this point, we know that if we have a constant argument that it is in
746     // Op1.  Check to see if we know anything about comparing value with a
747     // constant, and if we can use this info to fold the setcc.
748     //
749     if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Op1)) {
750       // Check to see if we already know the result of this comparison...
751       ConstantRange R = ConstantRange(Opcode, C);
752       ConstantRange Int = R.intersectWith(Op0VI->getBounds());
753
754       // If the intersection of the two ranges is empty, then the condition
755       // could never be true!
756       // 
757       if (Int.isEmptySet()) {
758         Result = Relation::KnownFalse;
759
760       // Otherwise, if VI.getBounds() (the possible values) is a subset of R
761       // (the allowed values) then we know that the condition must always be
762       // true!
763       //
764       } else if (Int == Op0VI->getBounds()) {
765         Result = Relation::KnownTrue;
766       }
767     } else {
768       // If we are here, we know that the second argument is not a constant
769       // integral.  See if we know anything about Op0 & Op1 that allows us to
770       // fold this anyway.
771       //
772       // Do we have value information about Op0 and a relation to Op1?
773       if (const Relation *Op2R = Op0VI->requestRelation(Op1))
774         Result = Op2R->getImpliedResult(Opcode);
775     }
776   }
777   return Result;
778 }
779
780 //===----------------------------------------------------------------------===//
781 //  Relation Implementation
782 //===----------------------------------------------------------------------===//
783
784 // CheckCondition - Return true if the specified condition is false.  Bound may
785 // be null.
786 static bool CheckCondition(Constant *Bound, Constant *C,
787                            Instruction::BinaryOps BO) {
788   assert(C != 0 && "C is not specified!");
789   if (Bound == 0) return false;
790
791   ConstantBool *Val;
792   switch (BO) {
793   default: assert(0 && "Unknown Condition code!");
794   case Instruction::SetEQ: Val = *Bound == *C; break;
795   case Instruction::SetNE: Val = *Bound != *C; break;
796   case Instruction::SetLT: Val = *Bound <  *C; break;
797   case Instruction::SetGT: Val = *Bound >  *C; break;
798   case Instruction::SetLE: Val = *Bound <= *C; break;
799   case Instruction::SetGE: Val = *Bound >= *C; break;
800   }
801
802   // ConstantHandling code may not succeed in the comparison...
803   if (Val == 0) return false;
804   return !Val->getValue();  // Return true if the condition is false...
805 }
806
807 // contradicts - Return true if the relationship specified by the operand
808 // contradicts already known information.
809 //
810 bool Relation::contradicts(Instruction::BinaryOps Op,
811                            const ValueInfo &VI) const {
812   assert (Op != Instruction::Add && "Invalid relation argument!");
813
814   // If this is a relationship with a constant, make sure that this relationship
815   // does not contradict properties known about the bounds of the constant.
816   //
817   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
818     if (ConstantRange(Op, C).intersectWith(VI.getBounds()).isEmptySet())
819       return true;
820
821   switch (Rel) {
822   default: assert(0 && "Unknown Relationship code!");
823   case Instruction::Add: return false;  // Nothing known, nothing contradicts
824   case Instruction::SetEQ:
825     return Op == Instruction::SetLT || Op == Instruction::SetGT ||
826            Op == Instruction::SetNE;
827   case Instruction::SetNE: return Op == Instruction::SetEQ;
828   case Instruction::SetLE: return Op == Instruction::SetGT;
829   case Instruction::SetGE: return Op == Instruction::SetLT;
830   case Instruction::SetLT:
831     return Op == Instruction::SetEQ || Op == Instruction::SetGT ||
832            Op == Instruction::SetGE;
833   case Instruction::SetGT:
834     return Op == Instruction::SetEQ || Op == Instruction::SetLT ||
835            Op == Instruction::SetLE;
836   }
837 }
838
839 // incorporate - Incorporate information in the argument into this relation
840 // entry.  This assumes that the information doesn't contradict itself.  If any
841 // new information is gained, true is returned, otherwise false is returned to
842 // indicate that nothing was updated.
843 //
844 bool Relation::incorporate(Instruction::BinaryOps Op, ValueInfo &VI) {
845   assert(!contradicts(Op, VI) &&
846          "Cannot incorporate contradictory information!");
847
848   // If this is a relationship with a constant, make sure that we update the
849   // range that is possible for the value to have...
850   //
851   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
852     VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds());
853
854   switch (Rel) {
855   default: assert(0 && "Unknown prior value!");
856   case Instruction::Add:   Rel = Op; return true;
857   case Instruction::SetEQ: return false;  // Nothing is more precise
858   case Instruction::SetNE: return false;  // Nothing is more precise
859   case Instruction::SetLT: return false;  // Nothing is more precise
860   case Instruction::SetGT: return false;  // Nothing is more precise
861   case Instruction::SetLE:
862     if (Op == Instruction::SetEQ || Op == Instruction::SetLT) {
863       Rel = Op;
864       return true;
865     } else if (Op == Instruction::SetNE) {
866       Rel = Instruction::SetLT;
867       return true;
868     }
869     return false;
870   case Instruction::SetGE: return Op == Instruction::SetLT;
871     if (Op == Instruction::SetEQ || Op == Instruction::SetGT) {
872       Rel = Op;
873       return true;
874     } else if (Op == Instruction::SetNE) {
875       Rel = Instruction::SetGT;
876       return true;
877     }
878     return false;
879   }
880 }
881
882 // getImpliedResult - If this relationship between two values implies that
883 // the specified relationship is true or false, return that.  If we cannot
884 // determine the result required, return Unknown.
885 //
886 Relation::KnownResult
887 Relation::getImpliedResult(Instruction::BinaryOps Op) const {
888   if (Rel == Op) return KnownTrue;
889   if (Rel == SetCondInst::getInverseCondition(Op)) return KnownFalse;
890
891   switch (Rel) {
892   default: assert(0 && "Unknown prior value!");
893   case Instruction::SetEQ:
894     if (Op == Instruction::SetLE || Op == Instruction::SetGE) return KnownTrue;
895     if (Op == Instruction::SetLT || Op == Instruction::SetGT) return KnownFalse;
896     break;
897   case Instruction::SetLT:
898     if (Op == Instruction::SetNE || Op == Instruction::SetLE) return KnownTrue;
899     if (Op == Instruction::SetEQ) return KnownFalse;
900     break;
901   case Instruction::SetGT:
902     if (Op == Instruction::SetNE || Op == Instruction::SetGE) return KnownTrue;
903     if (Op == Instruction::SetEQ) return KnownFalse;
904     break;
905   case Instruction::SetNE:
906   case Instruction::SetLE:
907   case Instruction::SetGE:
908   case Instruction::Add:
909     break;
910   }
911   return Unknown;
912 }
913
914
915 //===----------------------------------------------------------------------===//
916 // Printing Support...
917 //===----------------------------------------------------------------------===//
918
919 // print - Implement the standard print form to print out analysis information.
920 void CEE::print(std::ostream &O, const Module *M) const {
921   O << "\nPrinting Correlated Expression Info:\n";
922   for (std::map<BasicBlock*, RegionInfo>::const_iterator I = 
923          RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
924     I->second.print(O);
925 }
926
927 // print - Output information about this region...
928 void RegionInfo::print(std::ostream &OS) const {
929   if (ValueMap.empty()) return;
930
931   OS << " RegionInfo for basic block: " << BB->getName() << "\n";
932   for (std::map<Value*, ValueInfo>::const_iterator
933          I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
934     I->second.print(OS, I->first);
935   OS << "\n";
936 }
937
938 // print - Output information about this value relation...
939 void ValueInfo::print(std::ostream &OS, Value *V) const {
940   if (Relationships.empty()) return;
941
942   if (V) {
943     OS << "  ValueInfo for: ";
944     WriteAsOperand(OS, V);
945   }
946   OS << "\n    Bounds = " << Bounds << "\n";
947   if (Replacement) {
948     OS << "    Replacement = ";
949     WriteAsOperand(OS, Replacement);
950     OS << "\n";
951   }
952   for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
953     Relationships[i].print(OS);
954 }
955
956 // print - Output this relation to the specified stream
957 void Relation::print(std::ostream &OS) const {
958   OS << "    is ";
959   switch (Rel) {
960   default:           OS << "*UNKNOWN*"; break;
961   case Instruction::SetEQ: OS << "== "; break;
962   case Instruction::SetNE: OS << "!= "; break;
963   case Instruction::SetLT: OS << "< "; break;
964   case Instruction::SetGT: OS << "> "; break;
965   case Instruction::SetLE: OS << "<= "; break;
966   case Instruction::SetGE: OS << ">= "; break;
967   }
968
969   WriteAsOperand(OS, Val);
970   OS << "\n";
971 }
972
973 void Relation::dump() const { print(std::cerr); }
974 void ValueInfo::dump() const { print(std::cerr, 0); }