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