1 //===- CorrelatedExprs.cpp - Pass to detect and eliminated c.e.'s ---------===//
3 // Correlated Expression Elimination propogates information from conditional
4 // branches to blocks dominated by destinations of the branch. It propogates
5 // information from the condition check itself into the body of the branch,
6 // allowing transformations like these for example:
9 // ... 4*i; // constant propogation
13 // X = M-N; // = M-M == 0;
15 // This is called Correlated Expression Elimination because we eliminate or
16 // simplify expressions that are correlated with the direction of a branch. In
17 // this way we use static information to give us some information about the
18 // dynamic value of a variable.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOperators.h"
27 #include "llvm/ConstantHandling.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/PostOrderIterator.h"
34 #include "Support/StatisticReporter.h"
38 Statistic<>NumSetCCRemoved("cee\t\t- Number of setcc instruction eliminated");
39 Statistic<>NumOperandsCann("cee\t\t- Number of operands cannonicalized");
40 Statistic<>BranchRevectors("cee\t\t- Number of branches revectored");
44 Value *Val; // Relation to what value?
45 Instruction::BinaryOps Rel; // SetCC relation, or Add if no information
47 Relation(Value *V) : Val(V), Rel(Instruction::Add) {}
48 bool operator<(const Relation &R) const { return Val < R.Val; }
49 Value *getValue() const { return Val; }
50 Instruction::BinaryOps getRelation() const { return Rel; }
52 // contradicts - Return true if the relationship specified by the operand
53 // contradicts already known information.
55 bool contradicts(Instruction::BinaryOps Rel, const ValueInfo &VI) const;
57 // incorporate - Incorporate information in the argument into this relation
58 // entry. This assumes that the information doesn't contradict itself. If
59 // any new information is gained, true is returned, otherwise false is
60 // returned to indicate that nothing was updated.
62 bool incorporate(Instruction::BinaryOps Rel, ValueInfo &VI);
64 // KnownResult - Whether or not this condition determines the result of a
65 // setcc in the program. False & True are intentionally 0 & 1 so we can
66 // convert to bool by casting after checking for unknown.
68 enum KnownResult { KnownFalse = 0, KnownTrue = 1, Unknown = 2 };
70 // getImpliedResult - If this relationship between two values implies that
71 // the specified relationship is true or false, return that. If we cannot
72 // determine the result required, return Unknown.
74 KnownResult getImpliedResult(Instruction::BinaryOps Rel) const;
76 // print - Output this relation to the specified stream
77 void print(std::ostream &OS) const;
82 // ValueInfo - One instance of this record exists for every value with
83 // relationships between other values. It keeps track of all of the
84 // relationships to other values in the program (specified with Relation) that
85 // are known to be valid in a region.
88 // RelationShips - this value is know to have the specified relationships to
89 // other values. There can only be one entry per value, and this list is
90 // kept sorted by the Val field.
91 std::vector<Relation> Relationships;
93 // If information about this value is known or propogated from constant
94 // expressions, this range contains the possible values this value may hold.
97 // If we find that this value is equal to another value that has a lower
98 // rank, this value is used as it's replacement.
102 ValueInfo(const Type *Ty)
103 : Bounds(Ty->isIntegral() ? Ty : Type::IntTy), Replacement(0) {}
105 // getBounds() - Return the constant bounds of the value...
106 const ConstantRange &getBounds() const { return Bounds; }
107 ConstantRange &getBounds() { return Bounds; }
109 const std::vector<Relation> &getRelationships() { return Relationships; }
111 // getReplacement - Return the value this value is to be replaced with if it
112 // exists, otherwise return null.
114 Value *getReplacement() const { return Replacement; }
116 // setReplacement - Used by the replacement calculation pass to figure out
117 // what to replace this value with, if anything.
119 void setReplacement(Value *Repl) { Replacement = Repl; }
121 // getRelation - return the relationship entry for the specified value.
122 // This can invalidate references to other Relation's, so use it carefully.
124 Relation &getRelation(Value *V) {
125 // Binary search for V's entry...
126 std::vector<Relation>::iterator I =
127 std::lower_bound(Relationships.begin(), Relationships.end(), V);
129 // If we found the entry, return it...
130 if (I != Relationships.end() && I->getValue() == V)
133 // Insert and return the new relationship...
134 return *Relationships.insert(I, V);
137 const Relation *requestRelation(Value *V) const {
138 // Binary search for V's entry...
139 std::vector<Relation>::const_iterator I =
140 std::lower_bound(Relationships.begin(), Relationships.end(), V);
141 if (I != Relationships.end() && I->getValue() == V)
146 // print - Output information about this value relation...
147 void print(std::ostream &OS, Value *V) const;
151 // RegionInfo - Keeps track of all of the value relationships for a region. A
152 // region is the are dominated by a basic block. RegionInfo's keep track of
153 // the RegionInfo for their dominator, because anything known in a dominator
154 // is known to be true in a dominated block as well.
159 // ValueMap - Tracks the ValueInformation known for this region
160 typedef std::map<Value*, ValueInfo> ValueMapTy;
163 RegionInfo(BasicBlock *bb) : BB(bb) {}
165 // getEntryBlock - Return the block that dominates all of the members of
167 BasicBlock *getEntryBlock() const { return BB; }
169 const RegionInfo &operator=(const RegionInfo &RI) {
170 ValueMap = RI.ValueMap;
174 // print - Output information about this region...
175 void print(std::ostream &OS) const;
177 // Allow external access.
178 typedef ValueMapTy::iterator iterator;
179 iterator begin() { return ValueMap.begin(); }
180 iterator end() { return ValueMap.end(); }
182 ValueInfo &getValueInfo(Value *V) {
183 ValueMapTy::iterator I = ValueMap.lower_bound(V);
184 if (I != ValueMap.end() && I->first == V) return I->second;
185 return ValueMap.insert(I, std::make_pair(V, V->getType()))->second;
188 const ValueInfo *requestValueInfo(Value *V) const {
189 ValueMapTy::const_iterator I = ValueMap.find(V);
190 if (I != ValueMap.end()) return &I->second;
195 /// CEE - Correlated Expression Elimination
196 class CEE : public FunctionPass {
197 std::map<Value*, unsigned> RankMap;
198 std::map<BasicBlock*, RegionInfo> RegionInfoMap;
202 virtual bool runOnFunction(Function &F);
204 // We don't modify the program, so we preserve all analyses
205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207 AU.addRequired<DominatorSet>();
208 AU.addRequired<DominatorTree>();
211 // print - Implement the standard print form to print out analysis
213 virtual void print(std::ostream &O, const Module *M) const;
216 RegionInfo &getRegionInfo(BasicBlock *BB) {
217 std::map<BasicBlock*, RegionInfo>::iterator I
218 = RegionInfoMap.lower_bound(BB);
219 if (I != RegionInfoMap.end() && I->first == BB) return I->second;
220 return RegionInfoMap.insert(I, std::make_pair(BB, BB))->second;
223 void BuildRankMap(Function &F);
224 unsigned getRank(Value *V) const {
225 if (isa<Constant>(V) || isa<GlobalValue>(V)) return 0;
226 std::map<Value*, unsigned>::const_iterator I = RankMap.find(V);
227 if (I != RankMap.end()) return I->second;
228 return 0; // Must be some other global thing
231 bool TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks);
233 BasicBlock *isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI);
234 void PropogateBranchInfo(BranchInst *BI);
235 void PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI);
236 void PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
237 Value *Op1, RegionInfo &RI);
238 void UpdateUsersOfValue(Value *V, RegionInfo &RI);
239 void IncorporateInstruction(Instruction *Inst, RegionInfo &RI);
240 void ComputeReplacements(RegionInfo &RI);
243 // getSetCCResult - Given a setcc instruction, determine if the result is
244 // determined by facts we already know about the region under analysis.
245 // Return KnownTrue, KnownFalse, or Unknown based on what we can determine.
247 Relation::KnownResult getSetCCResult(SetCondInst *SC, const RegionInfo &RI);
250 bool SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI);
251 bool SimplifyInstruction(Instruction *Inst, const RegionInfo &RI);
253 RegisterOpt<CEE> X("cee", "Correlated Expression Elimination");
256 Pass *createCorrelatedExpressionEliminationPass() { return new CEE(); }
259 bool CEE::runOnFunction(Function &F) {
260 // Build a rank map for the function...
263 // Traverse the dominator tree, computing information for each node in the
264 // tree. Note that our traversal will not even touch unreachable basic
266 DS = &getAnalysis<DominatorSet>();
267 DT = &getAnalysis<DominatorTree>();
269 std::set<BasicBlock*> VisitedBlocks;
270 bool Changed = TransformRegion(&F.getEntryNode(), VisitedBlocks);
272 RegionInfoMap.clear();
277 // TransformRegion - Transform the region starting with BB according to the
278 // calculated region information for the block. Transforming the region
279 // involves analyzing any information this block provides to successors,
280 // propogating the information to successors, and finally transforming
283 // This method processes the function in depth first order, which guarantees
284 // that we process the immediate dominator of a block before the block itself.
285 // Because we are passing information from immediate dominators down to
286 // dominatees, we obviously have to process the information source before the
287 // information consumer.
289 bool CEE::TransformRegion(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks){
290 // Prevent infinite recursion...
291 if (VisitedBlocks.count(BB)) return false;
292 VisitedBlocks.insert(BB);
294 // Get the computed region information for this block...
295 RegionInfo &RI = getRegionInfo(BB);
297 // Compute the replacement information for this block...
298 ComputeReplacements(RI);
300 // If debugging, print computed region information...
301 DEBUG(RI.print(std::cerr));
303 // Simplify the contents of this block...
304 bool Changed = SimplifyBasicBlock(*BB, RI);
306 // Get the terminator of this basic block...
307 TerminatorInst *TI = BB->getTerminator();
309 // If this is a conditional branch, make sure that there is a branch target
310 // for each successor that can hold any information gleaned from the branch,
311 // by breaking any critical edges that may be laying about.
313 if (TI->getNumSuccessors() > 1) {
314 // If any of the successors has multiple incoming branches, add a new dummy
315 // destination branch that only contains an unconditional branch to the real
317 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
318 BasicBlock *Succ = TI->getSuccessor(i);
319 // If there is more than one predecessor of the destination block, break
320 // this critical edge by inserting a new block. This updates dominatorset
321 // and dominatortree information.
323 if (isCriticalEdge(TI, i))
324 SplitCriticalEdge(TI, i, this);
328 // Loop over all of the blocks that this block is the immediate dominator for.
329 // Because all information known in this region is also known in all of the
330 // blocks that are dominated by this one, we can safely propogate the
331 // information down now.
333 DominatorTree::Node *BBN = (*DT)[BB];
334 for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i) {
335 BasicBlock *Dominated = BBN->getChildren()[i]->getNode();
336 assert(RegionInfoMap.find(Dominated) == RegionInfoMap.end() &&
337 "RegionInfo should be calculated in dominanace order!");
338 getRegionInfo(Dominated) = RI;
341 // Now that all of our successors have information if they deserve it,
342 // propogate any information our terminator instruction finds to our
344 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
345 if (BI->isConditional())
346 PropogateBranchInfo(BI);
348 // If this is a branch to a block outside our region that simply performs
349 // another conditional branch, one whose outcome is known inside of this
350 // region, then vector this outgoing edge directly to the known destination.
352 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
353 while (BasicBlock *Dest = isCorrelatedBranchBlock(TI->getSuccessor(i), RI)){
354 TI->setSuccessor(i, Dest);
359 // Now that all of our successors have information, recursively process them.
360 for (unsigned i = 0, e = BBN->getChildren().size(); i != e; ++i)
361 Changed |= TransformRegion(BBN->getChildren()[i]->getNode(), VisitedBlocks);
363 // for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
364 //Changed |= TransformRegion(TI->getSuccessor(i), VisitedBlocks);
369 // If this block is a simple block not in the current region, which contains
370 // only a conditional branch, we determine if the outcome of the branch can be
371 // determined from information inside of the region. Instead of going to this
372 // block, we can instead go to the destination we know is the right target.
374 BasicBlock *CEE::isCorrelatedBranchBlock(BasicBlock *BB, RegionInfo &RI) {
375 // Check to see if we dominate the block. If so, this block will get the
376 // condition turned to a constant anyway.
378 //if (DS->dominates(RI.getEntryBlock(), BB))
381 // Check to see if this is a conditional branch...
382 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
383 if (BI->isConditional()) {
384 // Make sure that the block is either empty, or only contains a setcc.
385 if (BB->size() == 1 ||
386 (BB->size() == 2 && &BB->front() == BI->getCondition() &&
387 BI->getCondition()->use_size() == 1))
388 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition())) {
389 Relation::KnownResult Result = getSetCCResult(SCI, RI);
391 if (Result == Relation::KnownTrue)
392 return BI->getSuccessor(0);
393 else if (Result == Relation::KnownFalse)
394 return BI->getSuccessor(1);
400 // BuildRankMap - This method builds the rank map data structure which gives
401 // each instruction/value in the function a value based on how early it appears
402 // in the function. We give constants and globals rank 0, arguments are
403 // numbered starting at one, and instructions are numbered in reverse post-order
404 // from where the arguments leave off. This gives instructions in loops higher
405 // values than instructions not in loops.
407 void CEE::BuildRankMap(Function &F) {
408 unsigned Rank = 1; // Skip rank zero.
410 // Number the arguments...
411 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
414 // Number the instructions in reverse post order...
415 ReversePostOrderTraversal<Function*> RPOT(&F);
416 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
417 E = RPOT.end(); I != E; ++I)
418 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
420 if (BBI->getType() != Type::VoidTy)
421 RankMap[BBI] = Rank++;
425 // PropogateBranchInfo - When this method is invoked, we need to propogate
426 // information derived from the branch condition into the true and false
427 // branches of BI. Since we know that there aren't any critical edges in the
428 // flow graph, this can proceed unconditionally.
430 void CEE::PropogateBranchInfo(BranchInst *BI) {
431 assert(BI->isConditional() && "Must be a conditional branch!");
432 BasicBlock *BB = BI->getParent();
433 BasicBlock *TrueBB = BI->getSuccessor(0);
434 BasicBlock *FalseBB = BI->getSuccessor(1);
436 // Propogate information into the true block...
438 PropogateEquality(BI->getCondition(), ConstantBool::True,
439 getRegionInfo(TrueBB));
441 // Propogate information into the false block...
443 PropogateEquality(BI->getCondition(), ConstantBool::False,
444 getRegionInfo(FalseBB));
448 // PropogateEquality - If we discover that two values are equal to each other in
449 // a specified region, propogate this knowledge recursively.
451 void CEE::PropogateEquality(Value *Op0, Value *Op1, RegionInfo &RI) {
452 if (Op0 == Op1) return; // Gee whiz. Are these really equal each other?
454 if (isa<Constant>(Op0)) // Make sure the constant is always Op1
457 // Make sure we don't already know these are equal, to avoid infinite loops...
458 ValueInfo &VI = RI.getValueInfo(Op0);
460 // Get information about the known relationship between Op0 & Op1
461 Relation &KnownRelation = VI.getRelation(Op1);
463 // If we already know they're equal, don't reprocess...
464 if (KnownRelation.getRelation() == Instruction::SetEQ)
467 // If this is boolean, check to see if one of the operands is a constant. If
468 // it's a constant, then see if the other one is one of a setcc instruction,
469 // an AND, OR, or XOR instruction.
471 if (ConstantBool *CB = dyn_cast<ConstantBool>(Op1)) {
473 if (Instruction *Inst = dyn_cast<Instruction>(Op0)) {
474 // If we know that this instruction is an AND instruction, and the result
475 // is true, this means that both operands to the OR are known to be true
478 if (CB->getValue() && Inst->getOpcode() == Instruction::And) {
479 PropogateEquality(Inst->getOperand(0), CB, RI);
480 PropogateEquality(Inst->getOperand(1), CB, RI);
483 // If we know that this instruction is an OR instruction, and the result
484 // is false, this means that both operands to the OR are know to be false
487 if (!CB->getValue() && Inst->getOpcode() == Instruction::Or) {
488 PropogateEquality(Inst->getOperand(0), CB, RI);
489 PropogateEquality(Inst->getOperand(1), CB, RI);
492 // If we know that this instruction is a NOT instruction, we know that the
493 // operand is known to be the inverse of whatever the current value is.
495 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Inst))
496 if (BinaryOperator::isNot(BOp))
497 PropogateEquality(BinaryOperator::getNotArgument(BOp),
498 ConstantBool::get(!CB->getValue()), RI);
500 // If we know the value of a SetCC instruction, propogate the information
501 // about the relation into this region as well.
503 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
504 if (CB->getValue()) { // If we know the condition is true...
505 // Propogate info about the LHS to the RHS & RHS to LHS
506 PropogateRelation(SCI->getOpcode(), SCI->getOperand(0),
507 SCI->getOperand(1), RI);
508 PropogateRelation(SCI->getSwappedCondition(),
509 SCI->getOperand(1), SCI->getOperand(0), RI);
511 } else { // If we know the condition is false...
512 // We know the opposite of the condition is true...
513 Instruction::BinaryOps C = SCI->getInverseCondition();
515 PropogateRelation(C, SCI->getOperand(0), SCI->getOperand(1), RI);
516 PropogateRelation(SetCondInst::getSwappedCondition(C),
517 SCI->getOperand(1), SCI->getOperand(0), RI);
523 // Propogate information about Op0 to Op1 & visa versa
524 PropogateRelation(Instruction::SetEQ, Op0, Op1, RI);
525 PropogateRelation(Instruction::SetEQ, Op1, Op0, RI);
529 // PropogateRelation - We know that the specified relation is true in all of the
530 // blocks in the specified region. Propogate the information about Op0 and
531 // anything derived from it into this region.
533 void CEE::PropogateRelation(Instruction::BinaryOps Opcode, Value *Op0,
534 Value *Op1, RegionInfo &RI) {
535 assert(Op0->getType() == Op1->getType() && "Equal types expected!");
537 // Constants are already pretty well understood. We will apply information
538 // about the constant to Op1 in another call to PropogateRelation.
540 if (isa<Constant>(Op0)) return;
542 // Get the region information for this block to update...
543 ValueInfo &VI = RI.getValueInfo(Op0);
545 // Get information about the known relationship between Op0 & Op1
546 Relation &Op1R = VI.getRelation(Op1);
548 // Quick bailout for common case if we are reprocessing an instruction...
549 if (Op1R.getRelation() == Opcode)
552 // If we already have information that contradicts the current information we
553 // are propogating, ignore this info. Something bad must have happened!
555 if (Op1R.contradicts(Opcode, VI)) {
556 Op1R.contradicts(Opcode, VI);
557 std::cerr << "Contradiction found for opcode: "
558 << Instruction::getOpcodeName(Opcode) << "\n";
559 Op1R.print(std::cerr);
563 // If the information propogted is new, then we want process the uses of this
564 // instruction to propogate the information down to them.
566 if (Op1R.incorporate(Opcode, VI))
567 UpdateUsersOfValue(Op0, RI);
571 // UpdateUsersOfValue - The information about V in this region has been updated.
572 // Propogate this to all consumers of the value.
574 void CEE::UpdateUsersOfValue(Value *V, RegionInfo &RI) {
575 for (Value::use_iterator I = V->use_begin(), E = V->use_end();
577 if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
578 // If this is an instruction using a value that we know something about,
579 // try to propogate information to the value produced by the
580 // instruction. We can only do this if it is an instruction we can
581 // propogate information for (a setcc for example), and we only WANT to
582 // do this if the instruction dominates this region.
584 // If the instruction doesn't dominate this region, then it cannot be
585 // used in this region and we don't care about it. If the instruction
586 // is IN this region, then we will simplify the instruction before we
587 // get to uses of it anyway, so there is no reason to bother with it
588 // here. This check is also effectively checking to make sure that Inst
589 // is in the same function as our region (in case V is a global f.e.).
591 if (DS->properlyDominates(Inst->getParent(), RI.getEntryBlock()))
592 IncorporateInstruction(Inst, RI);
596 // IncorporateInstruction - We just updated the information about one of the
597 // operands to the specified instruction. Update the information about the
598 // value produced by this instruction
600 void CEE::IncorporateInstruction(Instruction *Inst, RegionInfo &RI) {
601 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
602 // See if we can figure out a result for this instruction...
603 Relation::KnownResult Result = getSetCCResult(SCI, RI);
604 if (Result != Relation::Unknown) {
605 PropogateEquality(SCI, Result ? ConstantBool::True : ConstantBool::False,
612 // ComputeReplacements - Some values are known to be equal to other values in a
613 // region. For example if there is a comparison of equality between a variable
614 // X and a constant C, we can replace all uses of X with C in the region we are
615 // interested in. We generalize this replacement to replace variables with
616 // other variables if they are equal and there is a variable with lower rank
617 // than the current one. This offers a cannonicalizing property that exposes
618 // more redundancies for later transformations to take advantage of.
620 void CEE::ComputeReplacements(RegionInfo &RI) {
621 // Loop over all of the values in the region info map...
622 for (RegionInfo::iterator I = RI.begin(), E = RI.end(); I != E; ++I) {
623 ValueInfo &VI = I->second;
625 // If we know that this value is a particular constant, set Replacement to
627 Value *Replacement = VI.getBounds().getSingleElement();
629 // If this value is not known to be some constant, figure out the lowest
630 // rank value that it is known to be equal to (if anything).
632 if (Replacement == 0) {
633 // Find out if there are any equality relationships with values of lower
634 // rank than VI itself...
635 unsigned MinRank = getRank(I->first);
637 // Loop over the relationships known about Op0.
638 const std::vector<Relation> &Relationships = VI.getRelationships();
639 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
640 if (Relationships[i].getRelation() == Instruction::SetEQ) {
641 unsigned R = getRank(Relationships[i].getValue());
644 Replacement = Relationships[i].getValue();
649 // If we found something to replace this value with, keep track of it.
651 VI.setReplacement(Replacement);
655 // SimplifyBasicBlock - Given information about values in region RI, simplify
656 // the instructions in the specified basic block.
658 bool CEE::SimplifyBasicBlock(BasicBlock &BB, const RegionInfo &RI) {
659 bool Changed = false;
660 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
661 Instruction *Inst = &*I++;
663 // Convert instruction arguments to canonical forms...
664 Changed |= SimplifyInstruction(Inst, RI);
666 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Inst)) {
667 // Try to simplify a setcc instruction based on inherited information
668 Relation::KnownResult Result = getSetCCResult(SCI, RI);
669 if (Result != Relation::Unknown) {
670 DEBUG(std::cerr << "Replacing setcc with " << Result
671 << " constant: " << SCI);
673 SCI->replaceAllUsesWith(ConstantBool::get((bool)Result));
674 // The instruction is now dead, remove it from the program.
675 SCI->getParent()->getInstList().erase(SCI);
685 // SimplifyInstruction - Inspect the operands of the instruction, converting
686 // them to their cannonical form if possible. This takes care of, for example,
687 // replacing a value 'X' with a constant 'C' if the instruction in question is
688 // dominated by a true seteq 'X', 'C'.
690 bool CEE::SimplifyInstruction(Instruction *I, const RegionInfo &RI) {
691 bool Changed = false;
693 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
694 if (const ValueInfo *VI = RI.requestValueInfo(I->getOperand(i)))
695 if (Value *Repl = VI->getReplacement()) {
696 // If we know if a replacement with lower rank than Op0, make the
698 DEBUG(std::cerr << "In Inst: " << I << " Replacing operand #" << i
699 << " with " << Repl << "\n");
700 I->setOperand(i, Repl);
709 // SimplifySetCC - Try to simplify a setcc instruction based on information
710 // inherited from a dominating setcc instruction. V is one of the operands to
711 // the setcc instruction, and VI is the set of information known about it. We
712 // take two cases into consideration here. If the comparison is against a
713 // constant value, we can use the constant range to see if the comparison is
714 // possible to succeed. If it is not a comparison against a constant, we check
715 // to see if there is a known relationship between the two values. If so, we
716 // may be able to eliminate the check.
718 Relation::KnownResult CEE::getSetCCResult(SetCondInst *SCI,
719 const RegionInfo &RI) {
720 Value *Op0 = SCI->getOperand(0), *Op1 = SCI->getOperand(1);
721 Instruction::BinaryOps Opcode = SCI->getOpcode();
723 if (isa<Constant>(Op0)) {
724 if (isa<Constant>(Op1)) {
725 if (Constant *Result = ConstantFoldInstruction(SCI)) {
726 // Wow, this is easy, directly eliminate the SetCondInst.
727 DEBUG(std::cerr << "Replacing setcc with constant fold: " << SCI);
728 return cast<ConstantBool>(Result)->getValue()
729 ? Relation::KnownTrue : Relation::KnownFalse;
732 // We want to swap this instruction so that operand #0 is the constant.
734 Opcode = SCI->getSwappedCondition();
738 // Try to figure out what the result of this comparison will be...
739 Relation::KnownResult Result = Relation::Unknown;
741 // We have to know something about the relationship to prove anything...
742 if (const ValueInfo *Op0VI = RI.requestValueInfo(Op0)) {
744 // At this point, we know that if we have a constant argument that it is in
745 // Op1. Check to see if we know anything about comparing value with a
746 // constant, and if we can use this info to fold the setcc.
748 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Op1)) {
749 // Check to see if we already know the result of this comparison...
750 ConstantRange R = ConstantRange(Opcode, C);
751 ConstantRange Int = R.intersectWith(Op0VI->getBounds());
753 // If the intersection of the two ranges is empty, then the condition
754 // could never be true!
756 if (Int.isEmptySet()) {
757 Result = Relation::KnownFalse;
759 // Otherwise, if VI.getBounds() (the possible values) is a subset of R
760 // (the allowed values) then we know that the condition must always be
763 } else if (Int == Op0VI->getBounds()) {
764 Result = Relation::KnownTrue;
767 // If we are here, we know that the second argument is not a constant
768 // integral. See if we know anything about Op0 & Op1 that allows us to
771 // Do we have value information about Op0 and a relation to Op1?
772 if (const Relation *Op2R = Op0VI->requestRelation(Op1))
773 Result = Op2R->getImpliedResult(Opcode);
779 //===----------------------------------------------------------------------===//
780 // Relation Implementation
781 //===----------------------------------------------------------------------===//
783 // CheckCondition - Return true if the specified condition is false. Bound may
785 static bool CheckCondition(Constant *Bound, Constant *C,
786 Instruction::BinaryOps BO) {
787 assert(C != 0 && "C is not specified!");
788 if (Bound == 0) return false;
792 default: assert(0 && "Unknown Condition code!");
793 case Instruction::SetEQ: Val = *Bound == *C; break;
794 case Instruction::SetNE: Val = *Bound != *C; break;
795 case Instruction::SetLT: Val = *Bound < *C; break;
796 case Instruction::SetGT: Val = *Bound > *C; break;
797 case Instruction::SetLE: Val = *Bound <= *C; break;
798 case Instruction::SetGE: Val = *Bound >= *C; break;
801 // ConstantHandling code may not succeed in the comparison...
802 if (Val == 0) return false;
803 return !Val->getValue(); // Return true if the condition is false...
806 // contradicts - Return true if the relationship specified by the operand
807 // contradicts already known information.
809 bool Relation::contradicts(Instruction::BinaryOps Op,
810 const ValueInfo &VI) const {
811 assert (Op != Instruction::Add && "Invalid relation argument!");
813 // If this is a relationship with a constant, make sure that this relationship
814 // does not contradict properties known about the bounds of the constant.
816 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
817 if (ConstantRange(Op, C).intersectWith(VI.getBounds()).isEmptySet())
821 default: assert(0 && "Unknown Relationship code!");
822 case Instruction::Add: return false; // Nothing known, nothing contradicts
823 case Instruction::SetEQ:
824 return Op == Instruction::SetLT || Op == Instruction::SetGT ||
825 Op == Instruction::SetNE;
826 case Instruction::SetNE: return Op == Instruction::SetEQ;
827 case Instruction::SetLE: return Op == Instruction::SetGT;
828 case Instruction::SetGE: return Op == Instruction::SetLT;
829 case Instruction::SetLT:
830 return Op == Instruction::SetEQ || Op == Instruction::SetGT ||
831 Op == Instruction::SetGE;
832 case Instruction::SetGT:
833 return Op == Instruction::SetEQ || Op == Instruction::SetLT ||
834 Op == Instruction::SetLE;
838 // incorporate - Incorporate information in the argument into this relation
839 // entry. This assumes that the information doesn't contradict itself. If any
840 // new information is gained, true is returned, otherwise false is returned to
841 // indicate that nothing was updated.
843 bool Relation::incorporate(Instruction::BinaryOps Op, ValueInfo &VI) {
844 assert(!contradicts(Op, VI) &&
845 "Cannot incorporate contradictory information!");
847 // If this is a relationship with a constant, make sure that we update the
848 // range that is possible for the value to have...
850 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(Val))
851 VI.getBounds() = ConstantRange(Op, C).intersectWith(VI.getBounds());
854 default: assert(0 && "Unknown prior value!");
855 case Instruction::Add: Rel = Op; return true;
856 case Instruction::SetEQ: return false; // Nothing is more precise
857 case Instruction::SetNE: return false; // Nothing is more precise
858 case Instruction::SetLT: return false; // Nothing is more precise
859 case Instruction::SetGT: return false; // Nothing is more precise
860 case Instruction::SetLE:
861 if (Op == Instruction::SetEQ || Op == Instruction::SetLT) {
864 } else if (Op == Instruction::SetNE) {
865 Rel = Instruction::SetLT;
869 case Instruction::SetGE: return Op == Instruction::SetLT;
870 if (Op == Instruction::SetEQ || Op == Instruction::SetGT) {
873 } else if (Op == Instruction::SetNE) {
874 Rel = Instruction::SetGT;
881 // getImpliedResult - If this relationship between two values implies that
882 // the specified relationship is true or false, return that. If we cannot
883 // determine the result required, return Unknown.
885 Relation::KnownResult
886 Relation::getImpliedResult(Instruction::BinaryOps Op) const {
887 if (Rel == Op) return KnownTrue;
888 if (Rel == SetCondInst::getInverseCondition(Op)) return KnownFalse;
891 default: assert(0 && "Unknown prior value!");
892 case Instruction::SetEQ:
893 if (Op == Instruction::SetLE || Op == Instruction::SetGE) return KnownTrue;
894 if (Op == Instruction::SetLT || Op == Instruction::SetGT) return KnownFalse;
896 case Instruction::SetLT:
897 if (Op == Instruction::SetNE || Op == Instruction::SetLE) return KnownTrue;
898 if (Op == Instruction::SetEQ) return KnownFalse;
900 case Instruction::SetGT:
901 if (Op == Instruction::SetNE || Op == Instruction::SetGE) return KnownTrue;
902 if (Op == Instruction::SetEQ) return KnownFalse;
904 case Instruction::SetNE:
905 case Instruction::SetLE:
906 case Instruction::SetGE:
907 case Instruction::Add:
914 //===----------------------------------------------------------------------===//
915 // Printing Support...
916 //===----------------------------------------------------------------------===//
918 // print - Implement the standard print form to print out analysis information.
919 void CEE::print(std::ostream &O, const Module *M) const {
920 O << "\nPrinting Correlated Expression Info:\n";
921 for (std::map<BasicBlock*, RegionInfo>::const_iterator I =
922 RegionInfoMap.begin(), E = RegionInfoMap.end(); I != E; ++I)
926 // print - Output information about this region...
927 void RegionInfo::print(std::ostream &OS) const {
928 if (ValueMap.empty()) return;
930 OS << " RegionInfo for basic block: " << BB->getName() << "\n";
931 for (std::map<Value*, ValueInfo>::const_iterator
932 I = ValueMap.begin(), E = ValueMap.end(); I != E; ++I)
933 I->second.print(OS, I->first);
937 // print - Output information about this value relation...
938 void ValueInfo::print(std::ostream &OS, Value *V) const {
939 if (Relationships.empty()) return;
942 OS << " ValueInfo for: ";
943 WriteAsOperand(OS, V);
945 OS << "\n Bounds = " << Bounds << "\n";
947 OS << " Replacement = ";
948 WriteAsOperand(OS, Replacement);
951 for (unsigned i = 0, e = Relationships.size(); i != e; ++i)
952 Relationships[i].print(OS);
955 // print - Output this relation to the specified stream
956 void Relation::print(std::ostream &OS) const {
959 default: OS << "*UNKNOWN*"; break;
960 case Instruction::SetEQ: OS << "== "; break;
961 case Instruction::SetNE: OS << "!= "; break;
962 case Instruction::SetLT: OS << "< "; break;
963 case Instruction::SetGT: OS << "> "; break;
964 case Instruction::SetLE: OS << "<= "; break;
965 case Instruction::SetGE: OS << ">= "; break;
968 WriteAsOperand(OS, Val);
972 void Relation::dump() const { print(std::cerr); }
973 void ValueInfo::dump() const { print(std::cerr, 0); }