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