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