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