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