1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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:
16 // ... 4*i; // constant propagation
20 // X = M-N; // = M-M == 0;
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.
27 //===----------------------------------------------------------------------===//
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"
50 STATISTIC(NumCmpRemoved, "Number of cmp instruction eliminated");
51 STATISTIC(NumOperandsCann, "Number of operands canonicalized");
52 STATISTIC(BranchRevectors, "Number of branches revectored");
56 class VISIBILITY_HIDDEN Relation {
57 Value *Val; // Relation to what value?
58 unsigned Rel; // SetCC or ICmp relation, or Add if no information
60 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; }
65 // contradicts - Return true if the relationship specified by the operand
66 // contradicts already known information.
68 bool contradicts(unsigned Rel, const ValueInfo &VI) const;
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.
75 bool incorporate(unsigned Rel, ValueInfo &VI);
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.
81 enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
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.
87 KnownResult getImpliedResult(unsigned Rel) const;
89 // print - Output this relation to the specified stream
90 void print(std::ostream &OS) const;
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.
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;
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;
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.
115 ValueInfo(const Type *Ty)
116 : Bounds(Ty->isInteger() ? Ty : Type::Int32Ty), Replacement(0) {}
118 // getBounds() - Return the constant bounds of the value...
119 const ConstantRange &getBounds() const { return Bounds; }
120 ConstantRange &getBounds() { return Bounds; }
122 const std::vector<Relation> &getRelationships() { return Relationships; }
124 // getReplacement - Return the value this value is to be replaced with if it
125 // exists, otherwise return null.
127 Value *getReplacement() const { return Replacement; }
129 // setReplacement - Used by the replacement calculation pass to figure out
130 // what to replace this value with, if anything.
132 void setReplacement(Value *Repl) { Replacement = Repl; }
134 // getRelation - return the relationship entry for the specified value.
135 // This can invalidate references to other Relations, so use it carefully.
137 Relation &getRelation(Value *V) {
138 // Binary search for V's entry...
139 std::vector<Relation>::iterator I =
140 std::lower_bound(Relationships.begin(), Relationships.end(),
143 // If we found the entry, return it...
144 if (I != Relationships.end() && I->getValue() == V)
147 // Insert and return the new relationship...
148 return *Relationships.insert(I, V);
151 const Relation *requestRelation(Value *V) const {
152 // Binary search for V's entry...
153 std::vector<Relation>::const_iterator I =
154 std::lower_bound(Relationships.begin(), Relationships.end(),
156 if (I != Relationships.end() && I->getValue() == V)
161 // print - Output information about this value relation...
162 void print(std::ostream &OS, Value *V) const;
166 // RegionInfo - Keeps track of all of the value relationships for a region. A
167 // region is the are dominated by a basic block. RegionInfo's keep track of
168 // the RegionInfo for their dominator, because anything known in a dominator
169 // is known to be true in a dominated block as well.
171 class VISIBILITY_HIDDEN RegionInfo {
174 // ValueMap - Tracks the ValueInformation known for this region
175 typedef std::map<Value*, ValueInfo> ValueMapTy;
178 RegionInfo(BasicBlock *bb) : BB(bb) {}
180 // getEntryBlock - Return the block that dominates all of the members of
182 BasicBlock *getEntryBlock() const { return BB; }
184 // empty - return true if this region has no information known about it.
185 bool empty() const { return ValueMap.empty(); }
187 const RegionInfo &operator=(const RegionInfo &RI) {
188 ValueMap = RI.ValueMap;
192 // print - Output information about this region...
193 void print(std::ostream &OS) const;
196 // Allow external access.
197 typedef ValueMapTy::iterator iterator;
198 iterator begin() { return ValueMap.begin(); }
199 iterator end() { return ValueMap.end(); }
201 ValueInfo &getValueInfo(Value *V) {
202 ValueMapTy::iterator I = ValueMap.lower_bound(V);
203 if (I != ValueMap.end() && I->first == V) return I->second;
204 return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
207 const ValueInfo *requestValueInfo(Value *V) const {
208 ValueMapTy::const_iterator I = ValueMap.find(V);
209 if (I != ValueMap.end()) return &I->second;
213 /// removeValueInfo - Remove anything known about V from our records. This
214 /// works whether or not we know anything about V.
216 void removeValueInfo(Value *V) {
221 /// CEE - Correlated Expression Elimination
222 class VISIBILITY_HIDDEN CEE : public FunctionPass {
223 std::map<Value*, unsigned> RankMap;
224 std::map<BasicBlock*, RegionInfo> RegionInfoMap;
228 virtual bool runOnFunction(Function &F);
230 // We don't modify the program, so we preserve all analyses
231 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
232 AU.addRequired<ETForest>();
233 AU.addRequired<DominatorTree>();
234 AU.addRequiredID(BreakCriticalEdgesID);
237 // print - Implement the standard print form to print out analysis
239 virtual void print(std::ostream &O, const Module *M) const;
242 RegionInfo &getRegionInfo(BasicBlock *BB) {
243 std::map<BasicBlock*, RegionInfo>::iterator I
244 = RegionInfoMap.lower_bound(BB);
245 if (I != RegionInfoMap.end() && I->first == BB) return I->second;
246 return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
249 void BuildRankMap(Function &F);
250 unsigned getRank(Value *V) const {
251 if (isa<Constant>(V)) return 0;
252 std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
253 if (I != RankMap.end()) return I->second;
254 return 0; // Must be some other global thing
257 bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
259 bool ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
262 void ForwardSuccessorTo(TerminatorInst *TI, unsigned Succ, BasicBlock *D,
264 void ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
265 BasicBlock *RegionDominator);
266 void CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
267 std::vector<BasicBlock*> &RegionExitBlocks);
268 void InsertRegionExitMerges(PHINode *NewPHI, Instruction *OldVal,
269 const std::vector<BasicBlock*> &RegionExitBlocks);
271 void PropagateBranchInfo(BranchInst *BI);
272 void PropagateSwitchInfo(SwitchInst *SI);
273 void PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
274 void PropagateRelation(unsigned Opcode, Value *Op0,
275 Value *Op1, RegionInfo &RI);
276 void UpdateUsersOfValue(Value *V, RegionInfo &RI);
277 void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
278 void ComputeReplacements(RegionInfo &RI);
280 // getCmpResult - Given a icmp instruction, determine if the result is
281 // determined by facts we already know about the region under analysis.
282 // Return KnownTrue, KnownFalse, or UnKnown based on what we can determine.
283 Relation::KnownResult getCmpResult(CmpInst *ICI, const RegionInfo &RI);
285 bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
286 bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
288 RegisterPass<CEE> X("cee", "Correlated Expression Elimination");
291 FunctionPass *llvm::createCorrelatedExpressionEliminationPass() {
296 bool CEE::runOnFunction(Function &F) {
297 // Build a rank map for the function...
300 // Traverse the dominator tree, computing information for each node in the
301 // tree. Note that our traversal will not even touch unreachable basic
303 EF = &getAnalysis<ETForest>();
304 DT = &getAnalysis<DominatorTree>();
306 std::set<BasicBlock*> VisitedBlocks;
307 bool Changed = TransformRegion(&F.getEntryBlock(), VisitedBlocks);
309 RegionInfoMap.clear();
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
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.
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);
331 // Get the computed region information for this block...
332 RegionInfo &RI = getRegionInfo(BB);
334 // Compute the replacement information for this block...
335 ComputeReplacements(RI);
337 // If debugging, print computed region information...
338 DEBUG(RI.print(*cerr.stream()));
340 // Simplify the contents of this block...
341 bool Changed = SimplifyBasicBlock(*BB, RI);
343 // Get the terminator of this basic block...
344 TerminatorInst *TI = BB->getTerminator();
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.
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;
360 // Now that all of our successors have information if they deserve it,
361 // propagate any information our terminator instruction finds to our
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);
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.
374 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
375 while (ForwardCorrelatedEdgeDestination(TI, i, RI)) {
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);
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.
390 static bool isBlockSimpleEnough(BasicBlock *BB) {
391 assert(isa<BranchInst>(BB->getTerminator()));
392 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
393 assert(BI->isConditional());
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()))
401 // Check the more complex case now...
402 BasicBlock::iterator I = BB->begin();
404 // FIXME: This should be reenabled once the regression with SIM is fixed!
406 // PHI Nodes are ok, just skip over them...
407 while (isa<PHINode>(*I)) ++I;
410 // Accept the setcc instruction...
411 if (&*I == BI->getCondition())
414 // Nothing else is acceptable here yet. We must not revector... unless we are
415 // at the terminator instruction.
423 bool CEE::ForwardCorrelatedEdgeDestination(TerminatorInst *TI, unsigned SuccNo,
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
432 // Check to see if we dominate the block. If so, this block will get the
433 // condition turned to a constant anyway.
435 //if (EF->dominates(RI.getEntryBlock(), BB))
438 BasicBlock *BB = TI->getParent();
440 // Get the destination block of this edge...
441 BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
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))
449 // We can only forward the branch over the block if the block ends with a
450 // cmp we can determine the outcome for.
452 // FIXME: we can make this more generic. Code below already handles more
454 if (!isa<CmpInst>(BI->getCondition()))
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...
460 RegionInfo NewRI(RI);
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);
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 (CmpInst *CI = dyn_cast<CmpInst>(I)) {
475 Relation::KnownResult Res = getCmpResult(CI, NewRI);
476 if (Res == Relation::Unknown) return false;
477 PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Res), NewRI);
479 assert(isa<BranchInst>(*I) && "Unexpected instruction type!");
482 // Compute the facts implied by what we have discovered...
483 ComputeReplacements(NewRI);
485 ValueInfo &PredicateVI = NewRI.getValueInfo(BI->getCondition());
486 if (PredicateVI.getReplacement() &&
487 isa<Constant>(PredicateVI.getReplacement()) &&
488 !isa<GlobalValue>(PredicateVI.getReplacement())) {
489 ConstantInt *CB = cast<ConstantInt>(PredicateVI.getReplacement());
491 // Forward to the successor that corresponds to the branch we will take.
492 ForwardSuccessorTo(TI, SuccNo,
493 BI->getSuccessor(!CB->getZExtValue()), NewRI);
500 static Value *getReplacementOrValue(Value *V, RegionInfo &RI) {
501 if (const ValueInfo *VI = RI.requestValueInfo(V))
502 if (Value *Repl = VI->getReplacement())
507 /// ForwardSuccessorTo - We have found that we can forward successor # 'SuccNo'
508 /// of Terminator 'TI' to the 'Dest' BasicBlock. This method performs the
509 /// mechanics of updating SSA information and revectoring the branch.
511 void CEE::ForwardSuccessorTo(TerminatorInst *TI, unsigned SuccNo,
512 BasicBlock *Dest, RegionInfo &RI) {
513 // If there are any PHI nodes in the Dest BB, we must duplicate the entry
514 // in the PHI node for the old successor to now include an entry from the
515 // current basic block.
517 BasicBlock *OldSucc = TI->getSuccessor(SuccNo);
518 BasicBlock *BB = TI->getParent();
520 DOUT << "Forwarding branch in basic block %" << BB->getName()
521 << " from block %" << OldSucc->getName() << " to block %"
522 << Dest->getName() << "\n"
523 << "Before forwarding: " << *BB->getParent();
525 // Because we know that there cannot be critical edges in the flow graph, and
526 // that OldSucc has multiple outgoing edges, this means that Dest cannot have
527 // multiple incoming edges.
530 pred_iterator DPI = pred_begin(Dest); ++DPI;
531 assert(DPI == pred_end(Dest) && "Critical edge found!!");
534 // Loop over any PHI nodes in the destination, eliminating them, because they
535 // may only have one input.
537 while (PHINode *PN = dyn_cast<PHINode>(&Dest->front())) {
538 assert(PN->getNumIncomingValues() == 1 && "Crit edge found!");
539 // Eliminate the PHI node
540 PN->replaceAllUsesWith(PN->getIncomingValue(0));
541 Dest->getInstList().erase(PN);
544 // If there are values defined in the "OldSucc" basic block, we need to insert
545 // PHI nodes in the regions we are dealing with to emulate them. This can
546 // insert dead phi nodes, but it is more trouble to see if they are used than
547 // to just blindly insert them.
549 if (EF->dominates(OldSucc, Dest)) {
550 // RegionExitBlocks - Find all of the blocks that are not dominated by Dest,
551 // but have predecessors that are. Additionally, prune down the set to only
552 // include blocks that are dominated by OldSucc as well.
554 std::vector<BasicBlock*> RegionExitBlocks;
555 CalculateRegionExitBlocks(Dest, OldSucc, RegionExitBlocks);
557 for (BasicBlock::iterator I = OldSucc->begin(), E = OldSucc->end();
559 if (I->getType() != Type::VoidTy) {
560 // Create and insert the PHI node into the top of Dest.
561 PHINode *NewPN = new PHINode(I->getType(), I->getName()+".fw_merge",
563 // There is definitely an edge from OldSucc... add the edge now
564 NewPN->addIncoming(I, OldSucc);
566 // There is also an edge from BB now, add the edge with the calculated
567 // value from the RI.
568 NewPN->addIncoming(getReplacementOrValue(I, RI), BB);
570 // Make everything in the Dest region use the new PHI node now...
571 ReplaceUsesOfValueInRegion(I, NewPN, Dest);
573 // Make sure that exits out of the region dominated by NewPN get PHI
574 // nodes that merge the values as appropriate.
575 InsertRegionExitMerges(NewPN, I, RegionExitBlocks);
579 // If there were PHI nodes in OldSucc, we need to remove the entry for this
580 // edge from the PHI node, and we need to replace any references to the PHI
581 // node with a new value.
583 for (BasicBlock::iterator I = OldSucc->begin(); isa<PHINode>(I); ) {
584 PHINode *PN = cast<PHINode>(I);
586 // Get the value flowing across the old edge and remove the PHI node entry
587 // for this edge: we are about to remove the edge! Don't remove the PHI
588 // node yet though if this is the last edge into it.
589 Value *EdgeValue = PN->removeIncomingValue(BB, false);
591 // Make sure that anything that used to use PN now refers to EdgeValue
592 ReplaceUsesOfValueInRegion(PN, EdgeValue, Dest);
594 // If there is only one value left coming into the PHI node, replace the PHI
595 // node itself with the one incoming value left.
597 if (PN->getNumIncomingValues() == 1) {
598 assert(PN->getNumIncomingValues() == 1);
599 PN->replaceAllUsesWith(PN->getIncomingValue(0));
600 PN->getParent()->getInstList().erase(PN);
601 I = OldSucc->begin();
602 } else if (PN->getNumIncomingValues() == 0) { // Nuke the PHI
603 // If we removed the last incoming value to this PHI, nuke the PHI node
605 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
606 PN->getParent()->getInstList().erase(PN);
607 I = OldSucc->begin();
609 ++I; // Otherwise, move on to the next PHI node
613 // Actually revector the branch now...
614 TI->setSuccessor(SuccNo, Dest);
616 // If we just introduced a critical edge in the flow graph, make sure to break
618 SplitCriticalEdge(TI, SuccNo, this);
620 // Make sure that we don't introduce critical edges from oldsucc now!
621 for (unsigned i = 0, e = OldSucc->getTerminator()->getNumSuccessors();
623 SplitCriticalEdge(OldSucc->getTerminator(), i, this);
625 // Since we invalidated the CFG, recalculate the dominator set so that it is
626 // useful for later processing!
627 // FIXME: This is much worse than it really should be!
630 DOUT << "After forwarding: " << *BB->getParent();
633 /// ReplaceUsesOfValueInRegion - This method replaces all uses of Orig with uses
634 /// of New. It only affects instructions that are defined in basic blocks that
635 /// are dominated by Head.
637 void CEE::ReplaceUsesOfValueInRegion(Value *Orig, Value *New,
638 BasicBlock *RegionDominator) {
639 assert(Orig != New && "Cannot replace value with itself");
640 std::vector<Instruction*> InstsToChange;
641 std::vector<PHINode*> PHIsToChange;
642 InstsToChange.reserve(Orig->getNumUses());
644 // Loop over instructions adding them to InstsToChange vector, this allows us
645 // an easy way to avoid invalidating the use_iterator at a bad time.
646 for (Value::use_iterator I = Orig->use_begin(), E = Orig->use_end();
648 if (Instruction *User = dyn_cast<Instruction>(*I))
649 if (EF->dominates(RegionDominator, User->getParent()))
650 InstsToChange.push_back(User);
651 else if (PHINode *PN = dyn_cast<PHINode>(User)) {
652 PHIsToChange.push_back(PN);
655 // PHIsToChange contains PHI nodes that use Orig that do not live in blocks
656 // dominated by orig. If the block the value flows in from is dominated by
657 // RegionDominator, then we rewrite the PHI
658 for (unsigned i = 0, e = PHIsToChange.size(); i != e; ++i) {
659 PHINode *PN = PHIsToChange[i];
660 for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
661 if (PN->getIncomingValue(j) == Orig &&
662 EF->dominates(RegionDominator, PN->getIncomingBlock(j)))
663 PN->setIncomingValue(j, New);
666 // Loop over the InstsToChange list, replacing all uses of Orig with uses of
667 // New. This list contains all of the instructions in our region that use
669 for (unsigned i = 0, e = InstsToChange.size(); i != e; ++i)
670 if (PHINode *PN = dyn_cast<PHINode>(InstsToChange[i])) {
671 // PHINodes must be handled carefully. If the PHI node itself is in the
672 // region, we have to make sure to only do the replacement for incoming
673 // values that correspond to basic blocks in the region.
674 for (unsigned j = 0, e = PN->getNumIncomingValues(); j != e; ++j)
675 if (PN->getIncomingValue(j) == Orig &&
676 EF->dominates(RegionDominator, PN->getIncomingBlock(j)))
677 PN->setIncomingValue(j, New);
680 InstsToChange[i]->replaceUsesOfWith(Orig, New);
684 static void CalcRegionExitBlocks(BasicBlock *Header, BasicBlock *BB,
685 std::set<BasicBlock*> &Visited,
687 std::vector<BasicBlock*> &RegionExitBlocks) {
688 if (Visited.count(BB)) return;
691 if (EF.dominates(Header, BB)) { // Block in the region, recursively traverse
692 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
693 CalcRegionExitBlocks(Header, *I, Visited, EF, RegionExitBlocks);
695 // Header does not dominate this block, but we have a predecessor that does
696 // dominate us. Add ourself to the list.
697 RegionExitBlocks.push_back(BB);
701 /// CalculateRegionExitBlocks - Find all of the blocks that are not dominated by
702 /// BB, but have predecessors that are. Additionally, prune down the set to
703 /// only include blocks that are dominated by OldSucc as well.
705 void CEE::CalculateRegionExitBlocks(BasicBlock *BB, BasicBlock *OldSucc,
706 std::vector<BasicBlock*> &RegionExitBlocks){
707 std::set<BasicBlock*> Visited; // Don't infinite loop
709 // Recursively calculate blocks we are interested in...
710 CalcRegionExitBlocks(BB, BB, Visited, *EF, RegionExitBlocks);
712 // Filter out blocks that are not dominated by OldSucc...
713 for (unsigned i = 0; i != RegionExitBlocks.size(); ) {
714 if (EF->dominates(OldSucc, RegionExitBlocks[i]))
715 ++i; // Block is ok, keep it.
717 // Move to end of list...
718 std::swap(RegionExitBlocks[i], RegionExitBlocks.back());
719 RegionExitBlocks.pop_back(); // Nuke the end
724 void CEE::InsertRegionExitMerges(PHINode *BBVal, Instruction *OldVal,
725 const std::vector<BasicBlock*> &RegionExitBlocks) {
726 assert(BBVal->getType() == OldVal->getType() && "Should be derived values!");
727 BasicBlock *BB = BBVal->getParent();
729 // Loop over all of the blocks we have to place PHIs in, doing it.
730 for (unsigned i = 0, e = RegionExitBlocks.size(); i != e; ++i) {
731 BasicBlock *FBlock = RegionExitBlocks[i]; // Block on the frontier
733 // Create the new PHI node
734 PHINode *NewPN = new PHINode(BBVal->getType(),
735 OldVal->getName()+".fw_frontier",
738 // Add an incoming value for every predecessor of the block...
739 for (pred_iterator PI = pred_begin(FBlock), PE = pred_end(FBlock);
741 // If the incoming edge is from the region dominated by BB, use BBVal,
742 // otherwise use OldVal.
743 NewPN->addIncoming(EF->dominates(BB, *PI) ? BBVal : OldVal, *PI);
746 // Now make everyone dominated by this block use this new value!
747 ReplaceUsesOfValueInRegion(OldVal, NewPN, FBlock);
753 // BuildRankMap - This method builds the rank map data structure which gives
754 // each instruction/value in the function a value based on how early it appears
755 // in the function. We give constants and globals rank 0, arguments are
756 // numbered starting at one, and instructions are numbered in reverse post-order
757 // from where the arguments leave off. This gives instructions in loops higher
758 // values than instructions not in loops.
760 void CEE::BuildRankMap(Function &F) {
761 unsigned Rank = 1; // Skip rank zero.
763 // Number the arguments...
764 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
767 // Number the instructions in reverse post order...
768 ReversePostOrderTraversal<Function*> RPOT(&F);
769 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
770 E = RPOT.end(); I != E; ++I)
771 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
773 if (BBI->getType() != Type::VoidTy)
774 RankMap[BBI] = Rank++;
778 // PropagateBranchInfo - When this method is invoked, we need to propagate
779 // information derived from the branch condition into the true and false
780 // branches of BI. Since we know that there aren't any critical edges in the
781 // flow graph, this can proceed unconditionally.
783 void CEE::PropagateBranchInfo(BranchInst *BI) {
784 assert(BI->isConditional() && "Must be a conditional branch!");
786 // Propagate information into the true block...
788 PropagateEquality(BI->getCondition(), ConstantInt::getTrue(),
789 getRegionInfo(BI->getSuccessor(0)));
791 // Propagate information into the false block...
793 PropagateEquality(BI->getCondition(), ConstantInt::getFalse(),
794 getRegionInfo(BI->getSuccessor(1)));
798 // PropagateSwitchInfo - We need to propagate the value tested by the
799 // switch statement through each case block.
801 void CEE::PropagateSwitchInfo(SwitchInst *SI) {
802 // Propagate information down each of our non-default case labels. We
803 // don't yet propagate information down the default label, because a
804 // potentially large number of inequality constraints provide less
805 // benefit per unit work than a single equality constraint.
807 Value *cond = SI->getCondition();
808 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
809 PropagateEquality(cond, SI->getSuccessorValue(i),
810 getRegionInfo(SI->getSuccessor(i)));
814 // PropagateEquality - If we discover that two values are equal to each other in
815 // a specified region, propagate this knowledge recursively.
817 void CEE::PropagateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
818 if (Op0 == Op1) return; // Gee whiz. Are these really equal each other?
820 if (isa<Constant>(Op0)) // Make sure the constant is always Op1
823 // Make sure we don't already know these are equal, to avoid infinite loops...
824 ValueInfo &VI = RI.getValueInfo(Op0);
826 // Get information about the known relationship between Op0 & Op1
827 Relation &KnownRelation = VI.getRelation(Op1);
829 // If we already know they're equal, don't reprocess...
830 if (KnownRelation.getRelation() == FCmpInst::FCMP_OEQ ||
831 KnownRelation.getRelation() == ICmpInst::ICMP_EQ)
834 // If this is boolean, check to see if one of the operands is a constant. If
835 // it's a constant, then see if the other one is one of a setcc instruction,
836 // an AND, OR, or XOR instruction.
838 ConstantInt *CB = dyn_cast<ConstantInt>(Op1);
839 if (CB && Op1->getType() == Type::Int1Ty) {
840 if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
841 // If we know that this instruction is an AND instruction, and the
842 // result is true, this means that both operands to the OR are known
843 // to be true as well.
845 if (CB->getZExtValue() && Inst->getOpcode() == Instruction::And) {
846 PropagateEquality(Inst->getOperand(0), CB, RI);
847 PropagateEquality(Inst->getOperand(1), CB, RI);
850 // If we know that this instruction is an OR instruction, and the result
851 // is false, this means that both operands to the OR are know to be
854 if (!CB->getZExtValue() && Inst->getOpcode() == Instruction::Or) {
855 PropagateEquality(Inst->getOperand(0), CB, RI);
856 PropagateEquality(Inst->getOperand(1), CB, RI);
859 // If we know that this instruction is a NOT instruction, we know that
860 // the operand is known to be the inverse of whatever the current
863 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
864 if (BinaryOperator::isNot(BOp))
865 PropagateEquality(BinaryOperator::getNotArgument(BOp),
866 ConstantInt::get(Type::Int1Ty,
867 !CB->getZExtValue()), RI);
869 // If we know the value of a FCmp instruction, propagate the information
870 // about the relation into this region as well.
872 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Inst)) {
873 if (CB->getZExtValue()) { // If we know the condition is true...
874 // Propagate info about the LHS to the RHS & RHS to LHS
875 PropagateRelation(FCI->getPredicate(), FCI->getOperand(0),
876 FCI->getOperand(1), RI);
877 PropagateRelation(FCI->getSwappedPredicate(),
878 FCI->getOperand(1), FCI->getOperand(0), RI);
880 } else { // If we know the condition is false...
881 // We know the opposite of the condition is true...
882 FCmpInst::Predicate C = FCI->getInversePredicate();
884 PropagateRelation(C, FCI->getOperand(0), FCI->getOperand(1), RI);
885 PropagateRelation(FCmpInst::getSwappedPredicate(C),
886 FCI->getOperand(1), FCI->getOperand(0), RI);
890 // If we know the value of a ICmp instruction, propagate the information
891 // about the relation into this region as well.
893 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
894 if (CB->getZExtValue()) { // If we know the condition is true...
895 // Propagate info about the LHS to the RHS & RHS to LHS
896 PropagateRelation(ICI->getPredicate(), ICI->getOperand(0),
897 ICI->getOperand(1), RI);
898 PropagateRelation(ICI->getSwappedPredicate(), ICI->getOperand(1),
899 ICI->getOperand(1), RI);
901 } else { // If we know the condition is false ...
902 // We know the opposite of the condition is true...
903 ICmpInst::Predicate C = ICI->getInversePredicate();
905 PropagateRelation(C, ICI->getOperand(0), ICI->getOperand(1), RI);
906 PropagateRelation(ICmpInst::getSwappedPredicate(C),
907 ICI->getOperand(1), ICI->getOperand(0), RI);
913 // Propagate information about Op0 to Op1 & visa versa
914 PropagateRelation(ICmpInst::ICMP_EQ, Op0, Op1, RI);
915 PropagateRelation(ICmpInst::ICMP_EQ, Op1, Op0, RI);
916 PropagateRelation(FCmpInst::FCMP_OEQ, Op0, Op1, RI);
917 PropagateRelation(FCmpInst::FCMP_OEQ, Op1, Op0, RI);
921 // PropagateRelation - We know that the specified relation is true in all of the
922 // blocks in the specified region. Propagate the information about Op0 and
923 // anything derived from it into this region.
925 void CEE::PropagateRelation(unsigned Opcode, Value *Op0,
926 Value *Op1, RegionInfo &RI) {
927 assert(Op0->getType() == Op1->getType() && "Equal types expected!");
929 // Constants are already pretty well understood. We will apply information
930 // about the constant to Op1 in another call to PropagateRelation.
932 if (isa<Constant>(Op0)) return;
934 // Get the region information for this block to update...
935 ValueInfo &VI = RI.getValueInfo(Op0);
937 // Get information about the known relationship between Op0 & Op1
938 Relation &Op1R = VI.getRelation(Op1);
940 // Quick bailout for common case if we are reprocessing an instruction...
941 if (Op1R.getRelation() == Opcode)
944 // If we already have information that contradicts the current information we
945 // are propagating, ignore this info. Something bad must have happened!
947 if (Op1R.contradicts(Opcode, VI)) {
948 Op1R.contradicts(Opcode, VI);
949 cerr << "Contradiction found for opcode: "
950 << ((isa<ICmpInst>(Op0)||isa<ICmpInst>(Op1)) ?
951 Instruction::getOpcodeName(Instruction::ICmp) :
952 Instruction::getOpcodeName(Opcode))
954 Op1R.print(*cerr.stream());
958 // If the information propagated is new, then we want process the uses of this
959 // instruction to propagate the information down to them.
961 if (Op1R.incorporate(Opcode, VI))
962 UpdateUsersOfValue(Op0, RI);
966 // UpdateUsersOfValue - The information about V in this region has been updated.
967 // Propagate this to all consumers of the value.
969 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
970 for (Value::use_iterator I = V->use_begin(), E = V->use_end();
972 if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
973 // If this is an instruction using a value that we know something about,
974 // try to propagate information to the value produced by the
975 // instruction. We can only do this if it is an instruction we can
976 // propagate information for (a setcc for example), and we only WANT to
977 // do this if the instruction dominates this region.
979 // If the instruction doesn't dominate this region, then it cannot be
980 // used in this region and we don't care about it. If the instruction
981 // is IN this region, then we will simplify the instruction before we
982 // get to uses of it anyway, so there is no reason to bother with it
983 // here. This check is also effectively checking to make sure that Inst
984 // is in the same function as our region (in case V is a global f.e.).
986 if (EF->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
987 IncorporateInstruction(Inst, RI);
991 // IncorporateInstruction - We just updated the information about one of the
992 // operands to the specified instruction. Update the information about the
993 // value produced by this instruction
995 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
996 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
997 // See if we can figure out a result for this instruction...
998 Relation::KnownResult Result = getCmpResult(CI, RI);
999 if (Result != Relation::Unknown) {
1000 PropagateEquality(CI, ConstantInt::get(Type::Int1Ty, Result != 0), RI);
1006 // ComputeReplacements - Some values are known to be equal to other values in a
1007 // region. For example if there is a comparison of equality between a variable
1008 // X and a constant C, we can replace all uses of X with C in the region we are
1009 // interested in. We generalize this replacement to replace variables with
1010 // other variables if they are equal and there is a variable with lower rank
1011 // than the current one. This offers a canonicalizing property that exposes
1012 // more redundancies for later transformations to take advantage of.
1014 void CEE::ComputeReplacements(RegionInfo &RI) {
1015 // Loop over all of the values in the region info map...
1016 for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
1017 ValueInfo &VI = I->second;
1019 // If we know that this value is a particular constant, set Replacement to
1021 Value *Replacement = VI.getBounds().getSingleElement();
1023 // If this value is not known to be some constant, figure out the lowest
1024 // rank value that it is known to be equal to (if anything).
1026 if (Replacement == 0) {
1027 // Find out if there are any equality relationships with values of lower
1028 // rank than VI itself...
1029 unsigned MinRank = getRank(I->first);
1031 // Loop over the relationships known about Op0.
1032 const std::vector<Relation> &Relationships = VI.getRelationships();
1033 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1034 if (Relationships[i].getRelation() == FCmpInst::FCMP_OEQ) {
1035 unsigned R = getRank(Relationships[i].getValue());
1038 Replacement = Relationships[i].getValue();
1041 else if (Relationships[i].getRelation() == ICmpInst::ICMP_EQ) {
1042 unsigned R = getRank(Relationships[i].getValue());
1045 Replacement = Relationships[i].getValue();
1050 // If we found something to replace this value with, keep track of it.
1052 VI.setReplacement(Replacement);
1056 // SimplifyBasicBlock - Given information about values in region RI, simplify
1057 // the instructions in the specified basic block.
1059 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
1060 bool Changed = false;
1061 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
1062 Instruction *Inst = I++;
1064 // Convert instruction arguments to canonical forms...
1065 Changed |= SimplifyInstruction(Inst, RI);
1067 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
1068 // Try to simplify a setcc instruction based on inherited information
1069 Relation::KnownResult Result = getCmpResult(CI, RI);
1070 if (Result != Relation::Unknown) {
1071 DEBUG(cerr << "Replacing icmp with " << Result
1072 << " constant: " << *CI);
1074 CI->replaceAllUsesWith(ConstantInt::get(Type::Int1Ty, (bool)Result));
1075 // The instruction is now dead, remove it from the program.
1076 CI->getParent()->getInstList().erase(CI);
1086 // SimplifyInstruction - Inspect the operands of the instruction, converting
1087 // them to their canonical form if possible. This takes care of, for example,
1088 // replacing a value 'X' with a constant 'C' if the instruction in question is
1089 // dominated by a true seteq 'X', 'C'.
1091 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
1092 bool Changed = false;
1094 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1095 if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
1096 if (Value *Repl = VI->getReplacement()) {
1097 // If we know if a replacement with lower rank than Op0, make the
1099 DOUT << "In Inst: " << *I << " Replacing operand #" << i
1100 << " with " << *Repl << "\n";
1101 I->setOperand(i, Repl);
1109 // getCmpResult - Try to simplify a cmp instruction based on information
1110 // inherited from a dominating icmp instruction. V is one of the operands to
1111 // the icmp instruction, and VI is the set of information known about it. We
1112 // take two cases into consideration here. If the comparison is against a
1113 // constant value, we can use the constant range to see if the comparison is
1114 // possible to succeed. If it is not a comparison against a constant, we check
1115 // to see if there is a known relationship between the two values. If so, we
1116 // may be able to eliminate the check.
1118 Relation::KnownResult CEE::getCmpResult(CmpInst *CI,
1119 const RegionInfo &RI) {
1120 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1121 unsigned short predicate = CI->getPredicate();
1123 if (isa<Constant>(Op0)) {
1124 if (isa<Constant>(Op1)) {
1125 if (Constant *Result = ConstantFoldInstruction(CI)) {
1126 // Wow, this is easy, directly eliminate the ICmpInst.
1127 DEBUG(cerr << "Replacing cmp with constant fold: " << *CI);
1128 return cast<ConstantInt>(Result)->getZExtValue()
1129 ? Relation::KnownTrue : Relation::KnownFalse;
1132 // We want to swap this instruction so that operand #0 is the constant.
1133 std::swap(Op0, Op1);
1134 if (isa<ICmpInst>(CI))
1135 predicate = cast<ICmpInst>(CI)->getSwappedPredicate();
1137 predicate = cast<FCmpInst>(CI)->getSwappedPredicate();
1141 // Try to figure out what the result of this comparison will be...
1142 Relation::KnownResult Result = Relation::Unknown;
1144 // We have to know something about the relationship to prove anything...
1145 if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
1147 // At this point, we know that if we have a constant argument that it is in
1148 // Op1. Check to see if we know anything about comparing value with a
1149 // constant, and if we can use this info to fold the icmp.
1151 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
1152 // Check to see if we already know the result of this comparison...
1153 ConstantRange R = ConstantRange(predicate, C->getValue());
1154 ConstantRange Int = R.intersectWith(Op0VI->getBounds(),
1155 ICmpInst::isSignedPredicate(ICmpInst::Predicate(predicate)));
1157 // If the intersection of the two ranges is empty, then the condition
1158 // could never be true!
1160 if (Int.isEmptySet()) {
1161 Result = Relation::KnownFalse;
1163 // Otherwise, if VI.getBounds() (the possible values) is a subset of R
1164 // (the allowed values) then we know that the condition must always be
1167 } else if (Int == Op0VI->getBounds()) {
1168 Result = Relation::KnownTrue;
1171 // If we are here, we know that the second argument is not a constant
1172 // integral. See if we know anything about Op0 & Op1 that allows us to
1173 // fold this anyway.
1175 // Do we have value information about Op0 and a relation to Op1?
1176 if (const Relation *Op2R = Op0VI->requestRelation(Op1))
1177 Result = Op2R->getImpliedResult(predicate);
1183 //===----------------------------------------------------------------------===//
1184 // Relation Implementation
1185 //===----------------------------------------------------------------------===//
1187 // contradicts - Return true if the relationship specified by the operand
1188 // contradicts already known information.
1190 bool Relation::contradicts(unsigned Op,
1191 const ValueInfo &VI) const {
1192 assert (Op != Instruction::Add && "Invalid relation argument!");
1194 // If this is a relationship with a constant, make sure that this relationship
1195 // does not contradict properties known about the bounds of the constant.
1197 if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
1198 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
1199 Op <= ICmpInst::LAST_ICMP_PREDICATE)
1200 if (ConstantRange(Op, C->getValue()).intersectWith(VI.getBounds(),
1201 ICmpInst::isSignedPredicate(ICmpInst::Predicate(Op))).isEmptySet())
1205 default: assert(0 && "Unknown Relationship code!");
1206 case Instruction::Add: return false; // Nothing known, nothing contradicts
1207 case ICmpInst::ICMP_EQ:
1208 return Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT ||
1209 Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT ||
1210 Op == ICmpInst::ICMP_NE;
1211 case ICmpInst::ICMP_NE: return Op == ICmpInst::ICMP_EQ;
1212 case ICmpInst::ICMP_ULE:
1213 case ICmpInst::ICMP_SLE: return Op == ICmpInst::ICMP_UGT ||
1214 Op == ICmpInst::ICMP_SGT;
1215 case ICmpInst::ICMP_UGE:
1216 case ICmpInst::ICMP_SGE: return Op == ICmpInst::ICMP_ULT ||
1217 Op == ICmpInst::ICMP_SLT;
1218 case ICmpInst::ICMP_ULT:
1219 case ICmpInst::ICMP_SLT:
1220 return Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_UGT ||
1221 Op == ICmpInst::ICMP_SGT || Op == ICmpInst::ICMP_UGE ||
1222 Op == ICmpInst::ICMP_SGE;
1223 case ICmpInst::ICMP_UGT:
1224 case ICmpInst::ICMP_SGT:
1225 return Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_ULT ||
1226 Op == ICmpInst::ICMP_SLT || Op == ICmpInst::ICMP_ULE ||
1227 Op == ICmpInst::ICMP_SLE;
1228 case FCmpInst::FCMP_OEQ:
1229 return Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT ||
1230 Op == FCmpInst::FCMP_ONE;
1231 case FCmpInst::FCMP_ONE: return Op == FCmpInst::FCMP_OEQ;
1232 case FCmpInst::FCMP_OLE: return Op == FCmpInst::FCMP_OGT;
1233 case FCmpInst::FCMP_OGE: return Op == FCmpInst::FCMP_OLT;
1234 case FCmpInst::FCMP_OLT:
1235 return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT ||
1236 Op == FCmpInst::FCMP_OGE;
1237 case FCmpInst::FCMP_OGT:
1238 return Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT ||
1239 Op == FCmpInst::FCMP_OLE;
1243 // incorporate - Incorporate information in the argument into this relation
1244 // entry. This assumes that the information doesn't contradict itself. If any
1245 // new information is gained, true is returned, otherwise false is returned to
1246 // indicate that nothing was updated.
1248 bool Relation::incorporate(unsigned Op, ValueInfo &VI) {
1249 assert(!contradicts(Op, VI) &&
1250 "Cannot incorporate contradictory information!");
1252 // If this is a relationship with a constant, make sure that we update the
1253 // range that is possible for the value to have...
1255 if (ConstantInt *C = dyn_cast<ConstantInt>(Val))
1256 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
1257 Op <= ICmpInst::LAST_ICMP_PREDICATE)
1259 ConstantRange(Op, C->getValue()).intersectWith(VI.getBounds(),
1260 ICmpInst::isSignedPredicate(ICmpInst::Predicate(Op)));
1263 default: assert(0 && "Unknown prior value!");
1264 case Instruction::Add: Rel = Op; return true;
1265 case ICmpInst::ICMP_EQ:
1266 case ICmpInst::ICMP_NE:
1267 case ICmpInst::ICMP_ULT:
1268 case ICmpInst::ICMP_SLT:
1269 case ICmpInst::ICMP_UGT:
1270 case ICmpInst::ICMP_SGT: return false; // Nothing is more precise
1271 case ICmpInst::ICMP_ULE:
1272 case ICmpInst::ICMP_SLE:
1273 if (Op == ICmpInst::ICMP_EQ || Op == ICmpInst::ICMP_ULT ||
1274 Op == ICmpInst::ICMP_SLT) {
1277 } else if (Op == ICmpInst::ICMP_NE) {
1278 Rel = Rel == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_ULT :
1283 case ICmpInst::ICMP_UGE:
1284 case ICmpInst::ICMP_SGE:
1285 if (Op == ICmpInst::ICMP_EQ || ICmpInst::ICMP_UGT ||
1286 Op == ICmpInst::ICMP_SGT) {
1289 } else if (Op == ICmpInst::ICMP_NE) {
1290 Rel = Rel == ICmpInst::ICMP_UGE ? ICmpInst::ICMP_UGT :
1295 case FCmpInst::FCMP_OEQ: return false; // Nothing is more precise
1296 case FCmpInst::FCMP_ONE: return false; // Nothing is more precise
1297 case FCmpInst::FCMP_OLT: return false; // Nothing is more precise
1298 case FCmpInst::FCMP_OGT: return false; // Nothing is more precise
1299 case FCmpInst::FCMP_OLE:
1300 if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OLT) {
1303 } else if (Op == FCmpInst::FCMP_ONE) {
1304 Rel = FCmpInst::FCMP_OLT;
1308 case FCmpInst::FCMP_OGE:
1309 return Op == FCmpInst::FCMP_OLT;
1310 if (Op == FCmpInst::FCMP_OEQ || Op == FCmpInst::FCMP_OGT) {
1313 } else if (Op == FCmpInst::FCMP_ONE) {
1314 Rel = FCmpInst::FCMP_OGT;
1321 // getImpliedResult - If this relationship between two values implies that
1322 // the specified relationship is true or false, return that. If we cannot
1323 // determine the result required, return Unknown.
1325 Relation::KnownResult
1326 Relation::getImpliedResult(unsigned Op) const {
1327 if (Rel == Op) return KnownTrue;
1328 if (Op >= ICmpInst::FIRST_ICMP_PREDICATE &&
1329 Op <= ICmpInst::LAST_ICMP_PREDICATE) {
1330 if (Rel == unsigned(ICmpInst::getInversePredicate(ICmpInst::Predicate(Op))))
1332 } else if (Op <= FCmpInst::LAST_FCMP_PREDICATE) {
1333 if (Rel == unsigned(FCmpInst::getInversePredicate(FCmpInst::Predicate(Op))))
1338 default: assert(0 && "Unknown prior value!");
1339 case ICmpInst::ICMP_EQ:
1340 if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE ||
1341 Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE) return KnownTrue;
1342 if (Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_SLT ||
1343 Op == ICmpInst::ICMP_UGT || Op == ICmpInst::ICMP_SGT) return KnownFalse;
1345 case ICmpInst::ICMP_ULT:
1346 case ICmpInst::ICMP_SLT:
1347 if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_SLE ||
1348 Op == ICmpInst::ICMP_NE) return KnownTrue;
1349 if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
1351 case ICmpInst::ICMP_UGT:
1352 case ICmpInst::ICMP_SGT:
1353 if (Op == ICmpInst::ICMP_UGE || Op == ICmpInst::ICMP_SGE ||
1354 Op == ICmpInst::ICMP_NE) return KnownTrue;
1355 if (Op == ICmpInst::ICMP_EQ) return KnownFalse;
1357 case FCmpInst::FCMP_OEQ:
1358 if (Op == FCmpInst::FCMP_OLE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1359 if (Op == FCmpInst::FCMP_OLT || Op == FCmpInst::FCMP_OGT) return KnownFalse;
1361 case FCmpInst::FCMP_OLT:
1362 if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OLE) return KnownTrue;
1363 if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1365 case FCmpInst::FCMP_OGT:
1366 if (Op == FCmpInst::FCMP_ONE || Op == FCmpInst::FCMP_OGE) return KnownTrue;
1367 if (Op == FCmpInst::FCMP_OEQ) return KnownFalse;
1369 case ICmpInst::ICMP_NE:
1370 case ICmpInst::ICMP_SLE:
1371 case ICmpInst::ICMP_ULE:
1372 case ICmpInst::ICMP_UGE:
1373 case ICmpInst::ICMP_SGE:
1374 case FCmpInst::FCMP_ONE:
1375 case FCmpInst::FCMP_OLE:
1376 case FCmpInst::FCMP_OGE:
1377 case FCmpInst::FCMP_FALSE:
1378 case FCmpInst::FCMP_ORD:
1379 case FCmpInst::FCMP_UNO:
1380 case FCmpInst::FCMP_UEQ:
1381 case FCmpInst::FCMP_UGT:
1382 case FCmpInst::FCMP_UGE:
1383 case FCmpInst::FCMP_ULT:
1384 case FCmpInst::FCMP_ULE:
1385 case FCmpInst::FCMP_UNE:
1386 case FCmpInst::FCMP_TRUE:
1393 //===----------------------------------------------------------------------===//
1394 // Printing Support...
1395 //===----------------------------------------------------------------------===//
1397 // print - Implement the standard print form to print out analysis information.
1398 void CEE::print(std::ostream &O, const Module *M) const {
1399 O << "\nPrinting Correlated Expression Info:\n";
1400 for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
1401 RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
1405 // print - Output information about this region...
1406 void RegionInfo::print(std::ostream &OS) const {
1407 if (ValueMap.empty()) return;
1409 OS << " RegionInfo for basic block: " << BB->getName() << "\n";
1410 for (std::map<Value*, ValueInfo>::const_iterator
1411 I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
1412 I->second.print(OS, I->first);
1416 // print - Output information about this value relation...
1417 void ValueInfo::print(std::ostream &OS, Value *V) const {
1418 if (Relationships.empty()) return;
1421 OS << " ValueInfo for: ";
1422 WriteAsOperand(OS, V);
1424 OS << "\n Bounds = " << Bounds << "\n";
1426 OS << " Replacement = ";
1427 WriteAsOperand(OS, Replacement);
1430 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
1431 Relationships[i].print(OS);
1434 // print - Output this relation to the specified stream
1435 void Relation::print(std::ostream &OS) const {
1438 default: OS << "*UNKNOWN*"; break;
1439 case ICmpInst::ICMP_EQ:
1440 case FCmpInst::FCMP_ORD:
1441 case FCmpInst::FCMP_UEQ:
1442 case FCmpInst::FCMP_OEQ: OS << "== "; break;
1443 case ICmpInst::ICMP_NE:
1444 case FCmpInst::FCMP_UNO:
1445 case FCmpInst::FCMP_UNE:
1446 case FCmpInst::FCMP_ONE: OS << "!= "; break;
1447 case ICmpInst::ICMP_ULT:
1448 case ICmpInst::ICMP_SLT:
1449 case FCmpInst::FCMP_ULT:
1450 case FCmpInst::FCMP_OLT: OS << "< "; break;
1451 case ICmpInst::ICMP_UGT:
1452 case ICmpInst::ICMP_SGT:
1453 case FCmpInst::FCMP_UGT:
1454 case FCmpInst::FCMP_OGT: OS << "> "; break;
1455 case ICmpInst::ICMP_ULE:
1456 case ICmpInst::ICMP_SLE:
1457 case FCmpInst::FCMP_ULE:
1458 case FCmpInst::FCMP_OLE: OS << "<= "; break;
1459 case ICmpInst::ICMP_UGE:
1460 case ICmpInst::ICMP_SGE:
1461 case FCmpInst::FCMP_UGE:
1462 case FCmpInst::FCMP_OGE: OS << ">= "; break;
1465 WriteAsOperand(OS, Val);
1469 // Don't inline these methods or else we won't be able to call them from GDB!
1470 void Relation::dump() const { print(*cerr.stream()); }
1471 void ValueInfo::dump() const { print(*cerr.stream(), 0); }
1472 void RegionInfo::dump() const { print(*cerr.stream()); }