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