Hopefully, the final fix for `[Pp]ropogate'.
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedExprs.cpp
1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
2 //
3 // Correlated Expression Elimination propagates information from conditional
4 // branches to blocks dominated by destinations of the branch.  It propagates
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 propagation
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 propagated 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     // empty - return true if this region has no information known about it.
171     bool empty() const { return ValueMap.empty(); }
172     
173     const RegionInfo &operator=(const RegionInfo &RI) {
174       ValueMap = RI.ValueMap;
175       return *this;
176     }
177
178     // print - Output information about this region...
179     void print(std::ostream &OS) const;
180     void dump() const;
181
182     // Allow external access.
183     typedef ValueMapTy::iterator iterator;
184     iterator begin() { return ValueMap.begin(); }
185     iterator end() { return ValueMap.end(); }
186
187     ValueInfo &getValueInfo(Value *V) {
188       ValueMapTy::iterator I = ValueMap.lower_bound(V);
189       if (I != ValueMap.end() && I->first == V) return I->second;
190       return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
191     }
192
193     const ValueInfo *requestValueInfo(Value *V) const {
194       ValueMapTy::const_iterator I = ValueMap.find(V);
195       if (I != ValueMap.end()) return &I->second;
196       return 0;
197     }
198     
199     /// removeValueInfo - Remove anything known about V from our records.  This
200     /// works whether or not we know anything about V.
201     ///
202     void removeValueInfo(Value *V) {
203       ValueMap.erase(V);
204     }
205   };
206
207   /// CEE - Correlated Expression Elimination
208   class CEE : public FunctionPass {
209     std::map<Value*, unsigned> RankMap;
210     std::map<BasicBlock*, RegionInfo> RegionInfoMap;
211     DominatorSet *DS;
212     DominatorTree *DT;
213   public:
214     virtual bool runOnFunction(Function &F);
215
216     // We don't modify the program, so we preserve all analyses
217     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218       AU.addRequired<DominatorSet>();
219       AU.addRequired<DominatorTree>();
220       AU.addRequiredID(BreakCriticalEdgesID);
221     };
222
223     // print - Implement the standard print form to print out analysis
224     // information.
225     virtual void print(std::ostream &O, const Module *M) const;
226
227   private:
228     RegionInfo &getRegionInfo(BasicBlock *BB) {
229       std::map<BasicBlock*, RegionInfo>::iterator I
230         = RegionInfoMap.lower_bound(BB);
231       if (I != RegionInfoMap.end() && I->first == BB) return I->second;
232       return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
233     }
234
235     void BuildRankMap(Function &F);
236     unsigned getRank(Value *V) const {
237       if (isa<Constant>(V) || isa<GlobalValue>(V)) return 0;
238       std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
239       if (I != RankMap.end()) return I->second;
240       return 0; // Must be some other global thing
241     }
242
243     bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
244
245     bool ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
246                                           RegionInfo &RI);
247
248     void ForwardSuccessorTo(TerminatorInst *TI, unsigned Succ, BasicBlock *D,
249                             RegionInfo &RI);
250     void ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
251                                     BasicBlock *RegionDominator);
252     void CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
253                                    std::vector<BasicBlock*> &RegionExitBlocks);
254     void InsertRegionExitMerges(PHINode *NewPHI, Instruction *OldVal,
255                              const std::vector<BasicBlock*> &RegionExitBlocks);
256
257     void PropagateBranchInfo(BranchInst *BI);
258     void PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
259     void PropagateRelation(Instruction::BinaryOps Opcode, Value *Op0,
260                            Value *Op1, RegionInfo &RI);
261     void UpdateUsersOfValue(Value *V, RegionInfo &RI);
262     void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
263     void ComputeReplacements(RegionInfo &RI);
264
265
266     // getSetCCResult - Given a setcc instruction, determine if the result is
267     // determined by facts we already know about the region under analysis.
268     // Return KnownTrue, KnownFalse, or Unknown based on what we can determine.
269     //
270     Relation::KnownResult getSetCCResult(SetCondInst *SC, const RegionInfo &RI);
271
272
273     bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
274     bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
275   }; 
276   RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
277 }
278
279 Pass *createCorrelatedExpressionEliminationPass() { return new CEE(); }
280
281
282 bool CEE::runOnFunction(Function &F) {
283   // Build a rank map for the function...
284   BuildRankMap(F);
285
286   // Traverse the dominator tree, computing information for each node in the
287   // tree.  Note that our traversal will not even touch unreachable basic
288   // blocks.
289   DS = &getAnalysis<DominatorSet>();
290   DT = &getAnalysis<DominatorTree>();
291   
292   std::set<BasicBlock*> VisitedBlocks;
293   bool Changed = TransformRegion(&F.getEntryNode(), VisitedBlocks);
294
295   RegionInfoMap.clear();
296   RankMap.clear();
297   return Changed;
298 }
299
300 // TransformRegion - Transform the region starting with BB according to the
301 // calculated region information for the block.  Transforming the region
302 // involves analyzing any information this block provides to successors,
303 // propagating the information to successors, and finally transforming
304 // successors.
305 //
306 // This method processes the function in depth first order, which guarantees
307 // that we process the immediate dominator of a block before the block itself.
308 // Because we are passing information from immediate dominators down to
309 // dominatees, we obviously have to process the information source before the
310 // information consumer.
311 //
312 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
313   // Prevent infinite recursion...
314   if (VisitedBlocks.count(BB)) return false;
315   VisitedBlocks.insert(BB);
316
317   // Get the computed region information for this block...
318   RegionInfo &RI = getRegionInfo(BB);
319
320   // Compute the replacement information for this block...
321   ComputeReplacements(RI);
322
323   // If debugging, print computed region information...
324   DEBUG(RI.print(std::cerr));
325
326   // Simplify the contents of this block...
327   bool Changed = SimplifyBasicBlock(*BB, RI);
328
329   // Get the terminator of this basic block...
330   TerminatorInst *TI = BB->getTerminator();
331
332   // Loop over all of the blocks that this block is the immediate dominator for.
333   // Because all information known in this region is also known in all of the
334   // blocks that are dominated by this one, we can safely propagate the
335   // information down now.
336   //
337   DominatorTree::Node *BBN = (*DT)[BB];
338   if (!RI.empty())        // Time opt: only propagate if we can change something
339     for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
340       BasicBlock *Dominated = BBN->getChildren()[i]->getNode();
341       assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
342              "RegionInfo should be calculated in dominanace order!");
343       getRegionInfo(Dominated) = RI;
344     }
345
346   // Now that all of our successors have information if they deserve it,
347   // propagate any information our terminator instruction finds to our
348   // successors.
349   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
350     if (BI->isConditional())
351       PropagateBranchInfo(BI);
352
353   // If this is a branch to a block outside our region that simply performs
354   // another conditional branch, one whose outcome is known inside of this
355   // region, then vector this outgoing edge directly to the known destination.
356   //
357   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
358     while (ForwardCorrelatedEdgeDestination(TI, i, RI)) {
359       ++BranchRevectors;
360       Changed = true;
361     }
362
363   // Now that all of our successors have information, recursively process them.
364   for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i)
365     Changed |= TransformRegion(BBN->getChildren()[i]->getNode(), VisitedBlocks);
366
367   return Changed;
368 }
369
370 // isBlockSimpleEnoughForCheck to see if the block is simple enough for us to
371 // revector the conditional branch in the bottom of the block, do so now.
372 //
373 static bool isBlockSimpleEnough(BasicBlock *BB) {
374   assert(isa<BranchInst>(BB->getTerminator()));
375   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
376   assert(BI->isConditional());
377
378   // Check the common case first: empty block, or block with just a setcc.
379   if (BB->size() == 1 ||
380       (BB->size() == 2 && &BB->front() == BI->getCondition() &&
381        BI->getCondition()->use_size() == 1))
382     return true;
383
384   // Check the more complex case now...
385   BasicBlock::iterator I = BB->begin();
386
387   // FIXME: This should be reenabled once the regression with SIM is fixed!
388 #if 0
389   // PHI Nodes are ok, just skip over them...
390   while (isa<PHINode>(*I)) ++I;
391 #endif
392
393   // Accept the setcc instruction...
394   if (&*I == BI->getCondition())
395     ++I;
396
397   // Nothing else is acceptable here yet.  We must not revector... unless we are
398   // at the terminator instruction.
399   if (&*I == BI)
400     return true;
401
402   return false;
403 }
404
405
406 bool CEE::ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
407                                            RegionInfo &RI) {
408   // If this successor is a simple block not in the current region, which
409   // contains only a conditional branch, we decide if the outcome of the branch
410   // can be determined from information inside of the region.  Instead of going
411   // to this block, we can instead go to the destination we know is the right
412   // target.
413   //
414
415   // Check to see if we dominate the block. If so, this block will get the
416   // condition turned to a constant anyway.
417   //
418   //if (DS->dominates(RI.getEntryBlock(), BB))
419   // return 0;
420
421   BasicBlock *BB = TI->getParent();
422
423   // Get the destination block of this edge...
424   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
425
426   // Make sure that the block ends with a conditional branch and is simple
427   // enough for use to be able to revector over.
428   BranchInst *BI = dyn_cast<BranchInst>(OldSucc->getTerminator());
429   if (BI == 0 || !BI->isConditional() || !isBlockSimpleEnough(OldSucc))
430     return false;
431
432   // We can only forward the branch over the block if the block ends with a
433   // setcc we can determine the outcome for.
434   //
435   // FIXME: we can make this more generic.  Code below already handles more
436   // generic case.
437   SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition());
438   if (SCI == 0) return false;
439
440   // Make a new RegionInfo structure so that we can simulate the effect of the
441   // PHI nodes in the block we are skipping over...
442   //
443   RegionInfo NewRI(RI);
444
445   // Remove value information for all of the values we are simulating... to make
446   // sure we don't have any stale information.
447   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
448     if (I->getType() != Type::VoidTy)
449       NewRI.removeValueInfo(I);
450     
451   // Put the newly discovered information into the RegionInfo...
452   for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end(); I!=E; ++I)
453     if (PHINode *PN = dyn_cast<PHINode>(I)) {
454       int OpNum = PN->getBasicBlockIndex(BB);
455       assert(OpNum != -1 && "PHI doesn't have incoming edge for predecessor!?");
456       PropagateEquality(PN, PN->getIncomingValue(OpNum), NewRI);      
457     } else if (SetCondInst *SCI = dyn_cast<SetCondInst>(I)) {
458       Relation::KnownResult Res = getSetCCResult(SCI, NewRI);
459       if (Res == Relation::Unknown) return false;
460       PropagateEquality(SCI, ConstantBool::get(Res), NewRI);
461     } else {
462       assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
463     }
464   
465   // Compute the facts implied by what we have discovered...
466   ComputeReplacements(NewRI);
467
468   ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
469   if (PredicateVI.getReplacement() &&
470       isa<Constant>(PredicateVI.getReplacement())) {
471     ConstantBool *CB = cast<ConstantBool>(PredicateVI.getReplacement());
472
473     // Forward to the successor that corresponds to the branch we will take.
474     ForwardSuccessorTo(TI, SuccNo, BI->getSuccessor(!CB->getValue()), NewRI);
475     return true;
476   }
477   
478   return false;
479 }
480
481 static Value *getReplacementOrValue(Value *V, RegionInfo &RI) {
482   if (const ValueInfo *VI = RI.requestValueInfo(V))
483     if (Value *Repl = VI->getReplacement())
484       return Repl;
485   return V;
486 }
487
488 /// ForwardSuccessorTo - We have found that we can forward successor # 'SuccNo'
489 /// of Terminator 'TI' to the 'Dest' BasicBlock.  This method performs the
490 /// mechanics of updating SSA information and revectoring the branch.
491 ///
492 void CEE::ForwardSuccessorTo(TerminatorInst *TI, unsigned SuccNo,
493                              BasicBlock *Dest, RegionInfo &RI) {
494   // If there are any PHI nodes in the Dest BB, we must duplicate the entry
495   // in the PHI node for the old successor to now include an entry from the
496   // current basic block.
497   //
498   BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
499   BasicBlock *BB = TI->getParent();
500
501   DEBUG(std::cerr << "Forwarding branch in basic block %" << BB->getName()
502         << " from block %" << OldSucc->getName() << " to block %"
503         << Dest->getName() << "\n");
504
505   DEBUG(std::cerr << "Before forwarding: " << *BB->getParent());
506
507   // Because we know that there cannot be critical edges in the flow graph, and
508   // that OldSucc has multiple outgoing edges, this means that Dest cannot have
509   // multiple incoming edges.
510   //
511 #ifndef NDEBUG
512   pred_iterator DPI = pred_begin(Dest); ++DPI;
513   assert(DPI == pred_end(Dest) && "Critical edge found!!");
514 #endif
515
516   // Loop over any PHI nodes in the destination, eliminating them, because they
517   // may only have one input.
518   //
519   while (PHINode *PN = dyn_cast<PHINode>(&Dest->front())) {
520     assert(PN->getNumIncomingValues() == 1 && "Crit edge found!");
521     // Eliminate the PHI node
522     PN->replaceAllUsesWith(PN->getIncomingValue(0));
523     Dest->getInstList().erase(PN);
524   }
525
526   // If there are values defined in the "OldSucc" basic block, we need to insert
527   // PHI nodes in the regions we are dealing with to emulate them.  This can
528   // insert dead phi nodes, but it is more trouble to see if they are used than
529   // to just blindly insert them.
530   //
531   if (DS->dominates(OldSucc, Dest)) {
532     // RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
533     // but have predecessors that are.  Additionally, prune down the set to only
534     // include blocks that are dominated by OldSucc as well.
535     //
536     std::vector<BasicBlock*> RegionExitBlocks;
537     CalculateRegionExitBlocks(Dest, OldSucc, RegionExitBlocks);
538
539     for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end();
540          I != E; ++I)
541       if (I->getType() != Type::VoidTy) {
542         // Create and insert the PHI node into the top of Dest.
543         PHINode *NewPN = new PHINode(I->getType(), I->getName()+".fw_merge",
544                                      Dest->begin());
545         // There is definitely an edge from OldSucc... add the edge now
546         NewPN->addIncoming(I, OldSucc);
547
548         // There is also an edge from BB now, add the edge with the calculated
549         // value from the RI.
550         NewPN->addIncoming(getReplacementOrValue(I, RI), BB);
551
552         // Make everything in the Dest region use the new PHI node now...
553         ReplaceUsesOfValueInRegion(I, NewPN, Dest);
554
555         // Make sure that exits out of the region dominated by NewPN get PHI
556         // nodes that merge the values as appropriate.
557         InsertRegionExitMerges(NewPN, I, RegionExitBlocks);
558       }
559   }
560
561   // If there were PHI nodes in OldSucc, we need to remove the entry for this
562   // edge from the PHI node, and we need to replace any references to the PHI
563   // node with a new value.
564   //
565   for (BasicBlock::iterator I = OldSucc->begin();
566        PHINode *PN = dyn_cast<PHINode>(I); ) {
567
568     // Get the value flowing across the old edge and remove the PHI node entry
569     // for this edge: we are about to remove the edge!  Don't remove the PHI
570     // node yet though if this is the last edge into it.
571     Value *EdgeValue = PN->removeIncomingValue(BB, false);
572
573     // Make sure that anything that used to use PN now refers to EdgeValue    
574     ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
575
576     // If there is only one value left coming into the PHI node, replace the PHI
577     // node itself with the one incoming value left.
578     //
579     if (PN->getNumIncomingValues() == 1) {
580       assert(PN->getNumIncomingValues() == 1);
581       PN->replaceAllUsesWith(PN->getIncomingValue(0));
582       PN->getParent()->getInstList().erase(PN);
583       I = OldSucc->begin();
584     } else if (PN->getNumIncomingValues() == 0) {  // Nuke the PHI
585       // If we removed the last incoming value to this PHI, nuke the PHI node
586       // now.
587       PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
588       PN->getParent()->getInstList().erase(PN);
589       I = OldSucc->begin();
590     } else {
591       ++I;  // Otherwise, move on to the next PHI node
592     }
593   }
594   
595   // Actually revector the branch now...
596   TI->setSuccessor(SuccNo, Dest);
597
598   // If we just introduced a critical edge in the flow graph, make sure to break
599   // it right away...
600   if (isCriticalEdge(TI, SuccNo))
601     SplitCriticalEdge(TI, SuccNo, this);
602
603   // Make sure that we don't introduce critical edges from oldsucc now!
604   for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
605        i != e; ++i)
606     if (isCriticalEdge(OldSucc->getTerminator(), i))
607       SplitCriticalEdge(OldSucc->getTerminator(), i, this);
608
609   // Since we invalidated the CFG, recalculate the dominator set so that it is
610   // useful for later processing!
611   // FIXME: This is much worse than it really should be!
612   //DS->recalculate();
613
614   DEBUG(std::cerr << "After forwarding: " << *BB->getParent());
615 }
616
617 /// ReplaceUsesOfValueInRegion - This method replaces all uses of Orig with uses
618 /// of New.  It only affects instructions that are defined in basic blocks that
619 /// are dominated by Head.
620 ///
621 void CEE::ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
622                                      BasicBlock *RegionDominator) {
623   assert(Orig != New && "Cannot replace value with itself");
624   std::vector<Instruction*> InstsToChange;
625   std::vector<PHINode*>     PHIsToChange;
626   InstsToChange.reserve(Orig->use_size());
627
628   // Loop over instructions adding them to InstsToChange vector, this allows us
629   // an easy way to avoid invalidating the use_iterator at a bad time.
630   for (Value::use_iterator I = Orig->use_begin(), E = Orig->use_end();
631        I != E; ++I)
632     if (Instruction *User = dyn_cast<Instruction>(*I))
633       if (DS->dominates(RegionDominator, User->getParent()))
634         InstsToChange.push_back(User);
635       else if (PHINode *PN = dyn_cast<PHINode>(User)) {
636         PHIsToChange.push_back(PN);
637       }
638
639   // PHIsToChange contains PHI nodes that use Orig that do not live in blocks
640   // dominated by orig.  If the block the value flows in from is dominated by
641   // RegionDominator, then we rewrite the PHI
642   for (unsigned i = 0, e = PHIsToChange.size(); i != e; ++i) {
643     PHINode *PN = PHIsToChange[i];
644     for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
645       if (PN->getIncomingValue(j) == Orig &&
646           DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
647         PN->setIncomingValue(j, New);
648   }
649
650   // Loop over the InstsToChange list, replacing all uses of Orig with uses of
651   // New.  This list contains all of the instructions in our region that use
652   // Orig.
653   for (unsigned i = 0, e = InstsToChange.size(); i != e; ++i)
654     if (PHINode *PN = dyn_cast<PHINode>(InstsToChange[i])) {
655       // PHINodes must be handled carefully.  If the PHI node itself is in the
656       // region, we have to make sure to only do the replacement for incoming
657       // values that correspond to basic blocks in the region.
658       for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
659         if (PN->getIncomingValue(j) == Orig &&
660             DS->dominates(RegionDominator, PN->getIncomingBlock(j)))
661           PN->setIncomingValue(j, New);
662
663     } else {
664       InstsToChange[i]->replaceUsesOfWith(Orig, New);
665     }
666 }
667
668 static void CalcRegionExitBlocks(BasicBlock *Header, BasicBlock *BB,
669                                  std::set<BasicBlock*> &Visited,
670                                  DominatorSet &DS,
671                                  std::vector<BasicBlock*> &RegionExitBlocks) {
672   if (Visited.count(BB)) return;
673   Visited.insert(BB);
674
675   if (DS.dominates(Header, BB)) {  // Block in the region, recursively traverse
676     for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
677       CalcRegionExitBlocks(Header, *I, Visited, DS, RegionExitBlocks);
678   } else {
679     // Header does not dominate this block, but we have a predecessor that does
680     // dominate us.  Add ourself to the list.
681     RegionExitBlocks.push_back(BB);    
682   }
683 }
684
685 /// CalculateRegionExitBlocks - Find all of the blocks that are not dominated by
686 /// BB, but have predecessors that are.  Additionally, prune down the set to
687 /// only include blocks that are dominated by OldSucc as well.
688 ///
689 void CEE::CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
690                                     std::vector<BasicBlock*> &RegionExitBlocks){
691   std::set<BasicBlock*> Visited;  // Don't infinite loop
692
693   // Recursively calculate blocks we are interested in...
694   CalcRegionExitBlocks(BB, BB, Visited, *DS, RegionExitBlocks);
695   
696   // Filter out blocks that are not dominated by OldSucc...
697   for (unsigned i = 0; i != RegionExitBlocks.size(); ) {
698     if (DS->dominates(OldSucc, RegionExitBlocks[i]))
699       ++i;  // Block is ok, keep it.
700     else {
701       // Move to end of list...
702       std::swap(RegionExitBlocks[i], RegionExitBlocks.back());
703       RegionExitBlocks.pop_back();        // Nuke the end
704     }
705   }
706 }
707
708 void CEE::InsertRegionExitMerges(PHINode *BBVal, Instruction *OldVal,
709                              const std::vector<BasicBlock*> &RegionExitBlocks) {
710   assert(BBVal->getType() == OldVal->getType() && "Should be derived values!");
711   BasicBlock *BB = BBVal->getParent();
712   BasicBlock *OldSucc = OldVal->getParent();
713
714   // Loop over all of the blocks we have to place PHIs in, doing it.
715   for (unsigned i = 0, e = RegionExitBlocks.size(); i != e; ++i) {
716     BasicBlock *FBlock = RegionExitBlocks[i];  // Block on the frontier
717
718     // Create the new PHI node
719     PHINode *NewPN = new PHINode(BBVal->getType(),
720                                  OldVal->getName()+".fw_frontier",
721                                  FBlock->begin());
722
723     // Add an incoming value for every predecessor of the block...
724     for (pred_iterator PI = pred_begin(FBlock), PE = pred_end(FBlock);
725          PI != PE; ++PI) {
726       // If the incoming edge is from the region dominated by BB, use BBVal,
727       // otherwise use OldVal.
728       NewPN->addIncoming(DS->dominates(BB, *PI) ? BBVal : OldVal, *PI);
729     }
730     
731     // Now make everyone dominated by this block use this new value!
732     ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
733   }
734 }
735
736
737
738 // BuildRankMap - This method builds the rank map data structure which gives
739 // each instruction/value in the function a value based on how early it appears
740 // in the function.  We give constants and globals rank 0, arguments are
741 // numbered starting at one, and instructions are numbered in reverse post-order
742 // from where the arguments leave off.  This gives instructions in loops higher
743 // values than instructions not in loops.
744 //
745 void CEE::BuildRankMap(Function &F) {
746   unsigned Rank = 1;  // Skip rank zero.
747
748   // Number the arguments...
749   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
750     RankMap[I] = Rank++;
751
752   // Number the instructions in reverse post order...
753   ReversePostOrderTraversal<Function*> RPOT(&F);
754   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
755          E = RPOT.end(); I != E; ++I)
756     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
757          BBI != E; ++BBI)
758       if (BBI->getType() != Type::VoidTy)
759         RankMap[BBI] = Rank++;
760 }
761
762
763 // PropagateBranchInfo - When this method is invoked, we need to propagate
764 // information derived from the branch condition into the true and false
765 // branches of BI.  Since we know that there aren't any critical edges in the
766 // flow graph, this can proceed unconditionally.
767 //
768 void CEE::PropagateBranchInfo(BranchInst *BI) {
769   assert(BI->isConditional() && "Must be a conditional branch!");
770
771   // Propagate information into the true block...
772   //
773   PropagateEquality(BI->getCondition(), ConstantBool::True,
774                     getRegionInfo(BI->getSuccessor(0)));
775   
776   // Propagate information into the false block...
777   //
778   PropagateEquality(BI->getCondition(), ConstantBool::False,
779                     getRegionInfo(BI->getSuccessor(1)));
780 }
781
782
783 // PropagateEquality - If we discover that two values are equal to each other in
784 // a specified region, propagate this knowledge recursively.
785 //
786 void CEE::PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
787   if (Op0 == Op1) return;  // Gee whiz. Are these really equal each other?
788
789   if (isa<Constant>(Op0))  // Make sure the constant is always Op1
790     std::swap(Op0, Op1);
791
792   // Make sure we don't already know these are equal, to avoid infinite loops...
793   ValueInfo &VI = RI.getValueInfo(Op0);
794
795   // Get information about the known relationship between Op0 & Op1
796   Relation &KnownRelation = VI.getRelation(Op1);
797
798   // If we already know they're equal, don't reprocess...
799   if (KnownRelation.getRelation() == Instruction::SetEQ)
800     return;
801
802   // If this is boolean, check to see if one of the operands is a constant.  If
803   // it's a constant, then see if the other one is one of a setcc instruction,
804   // an AND, OR, or XOR instruction.
805   //
806   if (ConstantBool *CB = dyn_cast<ConstantBool>(Op1)) {
807
808     if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
809       // If we know that this instruction is an AND instruction, and the result
810       // is true, this means that both operands to the OR are known to be true
811       // as well.
812       //
813       if (CB->getValue() && Inst->getOpcode() == Instruction::And) {
814         PropagateEquality(Inst->getOperand(0), CB, RI);
815         PropagateEquality(Inst->getOperand(1), CB, RI);
816       }
817       
818       // If we know that this instruction is an OR instruction, and the result
819       // is false, this means that both operands to the OR are know to be false
820       // as well.
821       //
822       if (!CB->getValue() && Inst->getOpcode() == Instruction::Or) {
823         PropagateEquality(Inst->getOperand(0), CB, RI);
824         PropagateEquality(Inst->getOperand(1), CB, RI);
825       }
826       
827       // If we know that this instruction is a NOT instruction, we know that the
828       // operand is known to be the inverse of whatever the current value is.
829       //
830       if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
831         if (BinaryOperator::isNot(BOp))
832           PropagateEquality(BinaryOperator::getNotArgument(BOp),
833                             ConstantBool::get(!CB->getValue()), RI);
834
835       // If we know the value of a SetCC instruction, propagate the information
836       // about the relation into this region as well.
837       //
838       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
839         if (CB->getValue()) {  // If we know the condition is true...
840           // Propagate info about the LHS to the RHS & RHS to LHS
841           PropagateRelation(SCI->getOpcode(), SCI->getOperand(0),
842                             SCI->getOperand(1), RI);
843           PropagateRelation(SCI->getSwappedCondition(),
844                             SCI->getOperand(1), SCI->getOperand(0), RI);
845
846         } else {               // If we know the condition is false...
847           // We know the opposite of the condition is true...
848           Instruction::BinaryOps C = SCI->getInverseCondition();
849           
850           PropagateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
851           PropagateRelation(SetCondInst::getSwappedCondition(C),
852                             SCI->getOperand(1), SCI->getOperand(0), RI);
853         }
854       }
855     }
856   }
857
858   // Propagate information about Op0 to Op1 & visa versa
859   PropagateRelation(Instruction::SetEQ, Op0, Op1, RI);
860   PropagateRelation(Instruction::SetEQ, Op1, Op0, RI);
861 }
862
863
864 // PropagateRelation - We know that the specified relation is true in all of the
865 // blocks in the specified region.  Propagate the information about Op0 and
866 // anything derived from it into this region.
867 //
868 void CEE::PropagateRelation(Instruction::BinaryOps Opcode, Value *Op0,
869                             Value *Op1, RegionInfo &RI) {
870   assert(Op0->getType() == Op1->getType() && "Equal types expected!");
871
872   // Constants are already pretty well understood.  We will apply information
873   // about the constant to Op1 in another call to PropagateRelation.
874   //
875   if (isa<Constant>(Op0)) return;
876
877   // Get the region information for this block to update...
878   ValueInfo &VI = RI.getValueInfo(Op0);
879
880   // Get information about the known relationship between Op0 & Op1
881   Relation &Op1R = VI.getRelation(Op1);
882
883   // Quick bailout for common case if we are reprocessing an instruction...
884   if (Op1R.getRelation() == Opcode)
885     return;
886
887   // If we already have information that contradicts the current information we
888   // are propagating, ignore this info.  Something bad must have happened!
889   //
890   if (Op1R.contradicts(Opcode, VI)) {
891     Op1R.contradicts(Opcode, VI);
892     std::cerr << "Contradiction found for opcode: "
893               << Instruction::getOpcodeName(Opcode) << "\n";
894     Op1R.print(std::cerr);
895     return;
896   }
897
898   // If the information propogted is new, then we want process the uses of this
899   // instruction to propagate the information down to them.
900   //
901   if (Op1R.incorporate(Opcode, VI))
902     UpdateUsersOfValue(Op0, RI);
903 }
904
905
906 // UpdateUsersOfValue - The information about V in this region has been updated.
907 // Propagate this to all consumers of the value.
908 //
909 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
910   for (Value::use_iterator I = V->use_begin(), E = V->use_end();
911        I != E; ++I)
912     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
913       // If this is an instruction using a value that we know something about,
914       // try to propagate information to the value produced by the
915       // instruction.  We can only do this if it is an instruction we can
916       // propagate information for (a setcc for example), and we only WANT to
917       // do this if the instruction dominates this region.
918       //
919       // If the instruction doesn't dominate this region, then it cannot be
920       // used in this region and we don't care about it.  If the instruction
921       // is IN this region, then we will simplify the instruction before we
922       // get to uses of it anyway, so there is no reason to bother with it
923       // here.  This check is also effectively checking to make sure that Inst
924       // is in the same function as our region (in case V is a global f.e.).
925       //
926       if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
927         IncorporateInstruction(Inst, RI);
928     }
929 }
930
931 // IncorporateInstruction - We just updated the information about one of the
932 // operands to the specified instruction.  Update the information about the
933 // value produced by this instruction
934 //
935 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
936   if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
937     // See if we can figure out a result for this instruction...
938     Relation::KnownResult Result = getSetCCResult(SCI, RI);
939     if (Result != Relation::Unknown) {
940       PropagateEquality(SCI, Result ? ConstantBool::True : ConstantBool::False,
941                         RI);
942     }
943   }
944 }
945
946
947 // ComputeReplacements - Some values are known to be equal to other values in a
948 // region.  For example if there is a comparison of equality between a variable
949 // X and a constant C, we can replace all uses of X with C in the region we are
950 // interested in.  We generalize this replacement to replace variables with
951 // other variables if they are equal and there is a variable with lower rank
952 // than the current one.  This offers a cannonicalizing property that exposes
953 // more redundancies for later transformations to take advantage of.
954 //
955 void CEE::ComputeReplacements(RegionInfo &RI) {
956   // Loop over all of the values in the region info map...
957   for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
958     ValueInfo &VI = I->second;
959
960     // If we know that this value is a particular constant, set Replacement to
961     // the constant...
962     Value *Replacement = VI.getBounds().getSingleElement();
963
964     // If this value is not known to be some constant, figure out the lowest
965     // rank value that it is known to be equal to (if anything).
966     //
967     if (Replacement == 0) {
968       // Find out if there are any equality relationships with values of lower
969       // rank than VI itself...
970       unsigned MinRank = getRank(I->first);
971
972       // Loop over the relationships known about Op0.
973       const std::vector<Relation> &Relationships = VI.getRelationships();
974       for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
975         if (Relationships[i].getRelation() == Instruction::SetEQ) {
976           unsigned R = getRank(Relationships[i].getValue());
977           if (R < MinRank) {
978             MinRank = R;
979             Replacement = Relationships[i].getValue();
980           }
981         }
982     }
983
984     // If we found something to replace this value with, keep track of it.
985     if (Replacement)
986       VI.setReplacement(Replacement);
987   }
988 }
989
990 // SimplifyBasicBlock - Given information about values in region RI, simplify
991 // the instructions in the specified basic block.
992 //
993 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
994   bool Changed = false;
995   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
996     Instruction *Inst = I++;
997
998     // Convert instruction arguments to canonical forms...
999     Changed |= SimplifyInstruction(Inst, RI);
1000
1001     if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
1002       // Try to simplify a setcc instruction based on inherited information
1003       Relation::KnownResult Result = getSetCCResult(SCI, RI);
1004       if (Result != Relation::Unknown) {
1005         DEBUG(std::cerr << "Replacing setcc with " << Result
1006                         << " constant: " << SCI);
1007
1008         SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
1009         // The instruction is now dead, remove it from the program.
1010         SCI->getParent()->getInstList().erase(SCI);
1011         ++NumSetCCRemoved;
1012         Changed = true;
1013       }
1014     }
1015   }
1016
1017   return Changed;
1018 }
1019
1020 // SimplifyInstruction - Inspect the operands of the instruction, converting
1021 // them to their cannonical form if possible.  This takes care of, for example,
1022 // replacing a value 'X' with a constant 'C' if the instruction in question is
1023 // dominated by a true seteq 'X', 'C'.
1024 //
1025 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
1026   bool Changed = false;
1027
1028   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1029     if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
1030       if (Value *Repl = VI->getReplacement()) {
1031         // If we know if a replacement with lower rank than Op0, make the
1032         // replacement now.
1033         DEBUG(std::cerr << "In Inst: " << I << "  Replacing operand #" << i
1034                         << " with " << Repl << "\n");
1035         I->setOperand(i, Repl);
1036         Changed = true;
1037         ++NumOperandsCann;
1038       }
1039
1040   return Changed;
1041 }
1042
1043
1044 // getSetCCResult - Try to simplify a setcc instruction based on information
1045 // inherited from a dominating setcc instruction.  V is one of the operands to
1046 // the setcc instruction, and VI is the set of information known about it.  We
1047 // take two cases into consideration here.  If the comparison is against a
1048 // constant value, we can use the constant range to see if the comparison is
1049 // possible to succeed.  If it is not a comparison against a constant, we check
1050 // to see if there is a known relationship between the two values.  If so, we
1051 // may be able to eliminate the check.
1052 //
1053 Relation::KnownResult CEE::getSetCCResult(SetCondInst *SCI,
1054                                           const RegionInfo &RI) {
1055   Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
1056   Instruction::BinaryOps Opcode = SCI->getOpcode();
1057   
1058   if (isa<Constant>(Op0)) {
1059     if (isa<Constant>(Op1)) {
1060       if (Constant *Result = ConstantFoldInstruction(SCI)) {
1061         // Wow, this is easy, directly eliminate the SetCondInst.
1062         DEBUG(std::cerr << "Replacing setcc with constant fold: " << SCI);
1063         return cast<ConstantBool>(Result)->getValue()
1064           ? Relation::KnownTrue : Relation::KnownFalse;
1065       }
1066     } else {
1067       // We want to swap this instruction so that operand #0 is the constant.
1068       std::swap(Op0, Op1);
1069       Opcode = SCI->getSwappedCondition();
1070     }
1071   }
1072
1073   // Try to figure out what the result of this comparison will be...
1074   Relation::KnownResult Result = Relation::Unknown;
1075
1076   // We have to know something about the relationship to prove anything...
1077   if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
1078
1079     // At this point, we know that if we have a constant argument that it is in
1080     // Op1.  Check to see if we know anything about comparing value with a
1081     // constant, and if we can use this info to fold the setcc.
1082     //
1083     if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Op1)) {
1084       // Check to see if we already know the result of this comparison...
1085       ConstantRange R = ConstantRange(Opcode, C);
1086       ConstantRange Int = R.intersectWith(Op0VI->getBounds());
1087
1088       // If the intersection of the two ranges is empty, then the condition
1089       // could never be true!
1090       // 
1091       if (Int.isEmptySet()) {
1092         Result = Relation::KnownFalse;
1093
1094       // Otherwise, if VI.getBounds() (the possible values) is a subset of R
1095       // (the allowed values) then we know that the condition must always be
1096       // true!
1097       //
1098       } else if (Int == Op0VI->getBounds()) {
1099         Result = Relation::KnownTrue;
1100       }
1101     } else {
1102       // If we are here, we know that the second argument is not a constant
1103       // integral.  See if we know anything about Op0 & Op1 that allows us to
1104       // fold this anyway.
1105       //
1106       // Do we have value information about Op0 and a relation to Op1?
1107       if (const Relation *Op2R = Op0VI->requestRelation(Op1))
1108         Result = Op2R->getImpliedResult(Opcode);
1109     }
1110   }
1111   return Result;
1112 }
1113
1114 //===----------------------------------------------------------------------===//
1115 //  Relation Implementation
1116 //===----------------------------------------------------------------------===//
1117
1118 // CheckCondition - Return true if the specified condition is false.  Bound may
1119 // be null.
1120 static bool CheckCondition(Constant *Bound, Constant *C,
1121                            Instruction::BinaryOps BO) {
1122   assert(C != 0 && "C is not specified!");
1123   if (Bound == 0) return false;
1124
1125   ConstantBool *Val;
1126   switch (BO) {
1127   default: assert(0 && "Unknown Condition code!");
1128   case Instruction::SetEQ: Val = *Bound == *C; break;
1129   case Instruction::SetNE: Val = *Bound != *C; break;
1130   case Instruction::SetLT: Val = *Bound <  *C; break;
1131   case Instruction::SetGT: Val = *Bound >  *C; break;
1132   case Instruction::SetLE: Val = *Bound <= *C; break;
1133   case Instruction::SetGE: Val = *Bound >= *C; break;
1134   }
1135
1136   // ConstantHandling code may not succeed in the comparison...
1137   if (Val == 0) return false;
1138   return !Val->getValue();  // Return true if the condition is false...
1139 }
1140
1141 // contradicts - Return true if the relationship specified by the operand
1142 // contradicts already known information.
1143 //
1144 bool Relation::contradicts(Instruction::BinaryOps Op,
1145                            const ValueInfo &VI) const {
1146   assert (Op != Instruction::Add && "Invalid relation argument!");
1147
1148   // If this is a relationship with a constant, make sure that this relationship
1149   // does not contradict properties known about the bounds of the constant.
1150   //
1151   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
1152     if (ConstantRange(Op, C).intersectWith(VI.getBounds()).isEmptySet())
1153       return true;
1154
1155   switch (Rel) {
1156   default: assert(0 && "Unknown Relationship code!");
1157   case Instruction::Add: return false;  // Nothing known, nothing contradicts
1158   case Instruction::SetEQ:
1159     return Op == Instruction::SetLT || Op == Instruction::SetGT ||
1160            Op == Instruction::SetNE;
1161   case Instruction::SetNE: return Op == Instruction::SetEQ;
1162   case Instruction::SetLE: return Op == Instruction::SetGT;
1163   case Instruction::SetGE: return Op == Instruction::SetLT;
1164   case Instruction::SetLT:
1165     return Op == Instruction::SetEQ || Op == Instruction::SetGT ||
1166            Op == Instruction::SetGE;
1167   case Instruction::SetGT:
1168     return Op == Instruction::SetEQ || Op == Instruction::SetLT ||
1169            Op == Instruction::SetLE;
1170   }
1171 }
1172
1173 // incorporate - Incorporate information in the argument into this relation
1174 // entry.  This assumes that the information doesn't contradict itself.  If any
1175 // new information is gained, true is returned, otherwise false is returned to
1176 // indicate that nothing was updated.
1177 //
1178 bool Relation::incorporate(Instruction::BinaryOps Op, ValueInfo &VI) {
1179   assert(!contradicts(Op, VI) &&
1180          "Cannot incorporate contradictory information!");
1181
1182   // If this is a relationship with a constant, make sure that we update the
1183   // range that is possible for the value to have...
1184   //
1185   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
1186     VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds());
1187
1188   switch (Rel) {
1189   default: assert(0 && "Unknown prior value!");
1190   case Instruction::Add:   Rel = Op; return true;
1191   case Instruction::SetEQ: return false;  // Nothing is more precise
1192   case Instruction::SetNE: return false;  // Nothing is more precise
1193   case Instruction::SetLT: return false;  // Nothing is more precise
1194   case Instruction::SetGT: return false;  // Nothing is more precise
1195   case Instruction::SetLE:
1196     if (Op == Instruction::SetEQ || Op == Instruction::SetLT) {
1197       Rel = Op;
1198       return true;
1199     } else if (Op == Instruction::SetNE) {
1200       Rel = Instruction::SetLT;
1201       return true;
1202     }
1203     return false;
1204   case Instruction::SetGE: return Op == Instruction::SetLT;
1205     if (Op == Instruction::SetEQ || Op == Instruction::SetGT) {
1206       Rel = Op;
1207       return true;
1208     } else if (Op == Instruction::SetNE) {
1209       Rel = Instruction::SetGT;
1210       return true;
1211     }
1212     return false;
1213   }
1214 }
1215
1216 // getImpliedResult - If this relationship between two values implies that
1217 // the specified relationship is true or false, return that.  If we cannot
1218 // determine the result required, return Unknown.
1219 //
1220 Relation::KnownResult
1221 Relation::getImpliedResult(Instruction::BinaryOps Op) const {
1222   if (Rel == Op) return KnownTrue;
1223   if (Rel == SetCondInst::getInverseCondition(Op)) return KnownFalse;
1224
1225   switch (Rel) {
1226   default: assert(0 && "Unknown prior value!");
1227   case Instruction::SetEQ:
1228     if (Op == Instruction::SetLE || Op == Instruction::SetGE) return KnownTrue;
1229     if (Op == Instruction::SetLT || Op == Instruction::SetGT) return KnownFalse;
1230     break;
1231   case Instruction::SetLT:
1232     if (Op == Instruction::SetNE || Op == Instruction::SetLE) return KnownTrue;
1233     if (Op == Instruction::SetEQ) return KnownFalse;
1234     break;
1235   case Instruction::SetGT:
1236     if (Op == Instruction::SetNE || Op == Instruction::SetGE) return KnownTrue;
1237     if (Op == Instruction::SetEQ) return KnownFalse;
1238     break;
1239   case Instruction::SetNE:
1240   case Instruction::SetLE:
1241   case Instruction::SetGE:
1242   case Instruction::Add:
1243     break;
1244   }
1245   return Unknown;
1246 }
1247
1248
1249 //===----------------------------------------------------------------------===//
1250 // Printing Support...
1251 //===----------------------------------------------------------------------===//
1252
1253 // print - Implement the standard print form to print out analysis information.
1254 void CEE::print(std::ostream &O, const Module *M) const {
1255   O << "\nPrinting Correlated Expression Info:\n";
1256   for (std::map<BasicBlock*, RegionInfo>::const_iterator I = 
1257          RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
1258     I->second.print(O);
1259 }
1260
1261 // print - Output information about this region...
1262 void RegionInfo::print(std::ostream &OS) const {
1263   if (ValueMap.empty()) return;
1264
1265   OS << " RegionInfo for basic block: " << BB->getName() << "\n";
1266   for (std::map<Value*, ValueInfo>::const_iterator
1267          I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
1268     I->second.print(OS, I->first);
1269   OS << "\n";
1270 }
1271
1272 // print - Output information about this value relation...
1273 void ValueInfo::print(std::ostream &OS, Value *V) const {
1274   if (Relationships.empty()) return;
1275
1276   if (V) {
1277     OS << "  ValueInfo for: ";
1278     WriteAsOperand(OS, V);
1279   }
1280   OS << "\n    Bounds = " << Bounds << "\n";
1281   if (Replacement) {
1282     OS << "    Replacement = ";
1283     WriteAsOperand(OS, Replacement);
1284     OS << "\n";
1285   }
1286   for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1287     Relationships[i].print(OS);
1288 }
1289
1290 // print - Output this relation to the specified stream
1291 void Relation::print(std::ostream &OS) const {
1292   OS << "    is ";
1293   switch (Rel) {
1294   default:           OS << "*UNKNOWN*"; break;
1295   case Instruction::SetEQ: OS << "== "; break;
1296   case Instruction::SetNE: OS << "!= "; break;
1297   case Instruction::SetLT: OS << "< "; break;
1298   case Instruction::SetGT: OS << "> "; break;
1299   case Instruction::SetLE: OS << "<= "; break;
1300   case Instruction::SetGE: OS << ">= "; break;
1301   }
1302
1303   WriteAsOperand(OS, Val);
1304   OS << "\n";
1305 }
1306
1307 // Don't inline these methods or else we won't be able to call them from GDB!
1308 void Relation::dump() const { print(std::cerr); }
1309 void ValueInfo::dump() const { print(std::cerr, 0); }
1310 void RegionInfo::dump() const { print(std::cerr); }