1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements sparse conditional constant propagation and merging:
12 // Specifically, this:
13 // * Assumes values are constant unless proven otherwise
14 // * Assumes BasicBlocks are dead unless proven otherwise
15 // * Proves values to be constant, and replaces them with constants
16 // * Proves conditional branches to be unconditional
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "sccp"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
48 STATISTIC(NumInstRemoved, "Number of instructions removed");
49 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
51 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
52 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
56 /// LatticeVal class - This class represents the different lattice values that
57 /// an LLVM value may occupy. It is a simple class with value semantics.
61 /// undefined - This LLVM Value has no known value yet.
64 /// constant - This LLVM Value has a specific constant value.
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
73 /// overdefined - This instruction is not known to be constant, and we know
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
82 LatticeValueTy getLatticeValue() const {
87 LatticeVal() : Val(0, undefined) {}
89 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
91 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
93 bool isOverdefined() const { return getLatticeValue() == overdefined; }
95 Constant *getConstant() const {
96 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
100 /// markOverdefined - Return true if this is a change in status.
101 bool markOverdefined() {
105 Val.setInt(overdefined);
109 /// markConstant - Return true if this is a change in status.
110 bool markConstant(Constant *V) {
112 assert(getConstant() == V && "Marking constant with different value");
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
134 /// getConstantInt - If this is a constant with a ConstantInt value, return it
135 /// otherwise return null.
136 ConstantInt *getConstantInt() const {
138 return dyn_cast<ConstantInt>(getConstant());
142 void markForcedConstant(Constant *V) {
143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
148 } // end anonymous namespace.
153 //===----------------------------------------------------------------------===//
155 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156 /// Constant Propagation.
158 class SCCPSolver : public InstVisitor<SCCPSolver> {
159 const TargetData *TD;
160 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
161 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
163 /// GlobalValue - If we are tracking any values for the contents of a global
164 /// variable, we keep a mapping from the constant accessor to the element of
165 /// the global, to the currently known value. If the value becomes
166 /// overdefined, it's entry is simply removed from this map.
167 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
169 /// TrackedRetVals - If we are tracking arguments into and the return
170 /// value out of a function, it will have an entry in this map, indicating
171 /// what the known return value for the function is.
172 DenseMap<Function*, LatticeVal> TrackedRetVals;
174 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
175 /// that return multiple values.
176 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
178 /// The reason for two worklists is that overdefined is the lowest state
179 /// on the lattice, and moving things to overdefined as fast as possible
180 /// makes SCCP converge much faster.
182 /// By having a separate worklist, we accomplish this because everything
183 /// possibly overdefined will become overdefined at the soonest possible
185 SmallVector<Value*, 64> OverdefinedInstWorkList;
186 SmallVector<Value*, 64> InstWorkList;
189 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
191 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
192 /// overdefined, despite the fact that the PHI node is overdefined.
193 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
195 /// KnownFeasibleEdges - Entries in this set are edges which have already had
196 /// PHI nodes retriggered.
197 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
198 DenseSet<Edge> KnownFeasibleEdges;
200 SCCPSolver(const TargetData *td) : TD(td) {}
202 /// MarkBlockExecutable - This method can be used by clients to mark all of
203 /// the blocks that are known to be intrinsically live in the processed unit.
205 /// This returns true if the block was not considered live before.
206 bool MarkBlockExecutable(BasicBlock *BB) {
207 if (!BBExecutable.insert(BB)) return false;
208 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
209 BBWorkList.push_back(BB); // Add the block to the work list!
213 /// TrackValueOfGlobalVariable - Clients can use this method to
214 /// inform the SCCPSolver that it should track loads and stores to the
215 /// specified global variable if it can. This is only legal to call if
216 /// performing Interprocedural SCCP.
217 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
218 const Type *ElTy = GV->getType()->getElementType();
219 if (ElTy->isFirstClassType()) {
220 LatticeVal &IV = TrackedGlobals[GV];
221 if (!isa<UndefValue>(GV->getInitializer()))
222 IV.markConstant(GV->getInitializer());
226 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
227 /// and out of the specified function (which cannot have its address taken),
228 /// this method must be called.
229 void AddTrackedFunction(Function *F) {
230 assert(F->hasLocalLinkage() && "Can only track internal functions!");
231 // Add an entry, F -> undef.
232 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
233 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
234 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
237 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
240 /// Solve - Solve for constants and executable blocks.
244 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
245 /// that branches on undef values cannot reach any of their successors.
246 /// However, this is not a safe assumption. After we solve dataflow, this
247 /// method should be use to handle this. If this returns true, the solver
249 bool ResolvedUndefsIn(Function &F);
251 bool isBlockExecutable(BasicBlock *BB) const {
252 return BBExecutable.count(BB);
255 LatticeVal getLatticeValueFor(Value *V) const {
256 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
257 assert(I != ValueState.end() && "V is not in valuemap!");
261 /// getTrackedRetVals - Get the inferred return value map.
263 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
264 return TrackedRetVals;
267 /// getTrackedGlobals - Get and return the set of inferred initializers for
268 /// global variables.
269 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
270 return TrackedGlobals;
273 void markOverdefined(Value *V) {
274 markOverdefined(ValueState[V], V);
278 // markConstant - Make a value be marked as "constant". If the value
279 // is not already a constant, add it to the instruction work list so that
280 // the users of the instruction are updated later.
282 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
283 if (!IV.markConstant(C)) return;
284 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
285 InstWorkList.push_back(V);
288 void markConstant(Value *V, Constant *C) {
289 markConstant(ValueState[V], V, C);
292 void markForcedConstant(Value *V, Constant *C) {
293 ValueState[V].markForcedConstant(C);
294 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
295 InstWorkList.push_back(V);
299 // markOverdefined - Make a value be marked as "overdefined". If the
300 // value is not already overdefined, add it to the overdefined instruction
301 // work list so that the users of the instruction are updated later.
302 void markOverdefined(LatticeVal &IV, Value *V) {
303 if (!IV.markOverdefined()) return;
305 DEBUG(errs() << "markOverdefined: ";
306 if (Function *F = dyn_cast<Function>(V))
307 errs() << "Function '" << F->getName() << "'\n";
309 errs() << *V << '\n');
310 // Only instructions go on the work list
311 OverdefinedInstWorkList.push_back(V);
314 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
315 if (IV.isOverdefined() || MergeWithV.isUndefined())
317 if (MergeWithV.isOverdefined())
318 markOverdefined(IV, V);
319 else if (IV.isUndefined())
320 markConstant(IV, V, MergeWithV.getConstant());
321 else if (IV.getConstant() != MergeWithV.getConstant())
322 markOverdefined(IV, V);
325 void mergeInValue(Value *V, LatticeVal MergeWithV) {
326 mergeInValue(ValueState[V], V, MergeWithV);
330 /// getValueState - Return the LatticeVal object that corresponds to the
331 /// value. This function handles the case when the value hasn't been seen yet
332 /// by properly seeding constants etc.
333 LatticeVal &getValueState(Value *V) {
334 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
335 if (I != ValueState.end()) return I->second; // Common case, in the map
337 LatticeVal &LV = ValueState[V];
339 if (Constant *C = dyn_cast<Constant>(V)) {
340 // Undef values remain undefined.
341 if (!isa<UndefValue>(V))
342 LV.markConstant(C); // Constants are constant
345 // All others are underdefined by default.
349 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
350 /// work list if it is not already executable.
351 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
352 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
353 return; // This edge is already known to be executable!
355 if (!MarkBlockExecutable(Dest)) {
356 // If the destination is already executable, we just made an *edge*
357 // feasible that wasn't before. Revisit the PHI nodes in the block
358 // because they have potentially new operands.
359 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
360 << " -> " << Dest->getName() << "\n");
363 for (BasicBlock::iterator I = Dest->begin();
364 (PN = dyn_cast<PHINode>(I)); ++I)
369 // getFeasibleSuccessors - Return a vector of booleans to indicate which
370 // successors are reachable from a given terminator instruction.
372 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
374 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
375 // block to the 'To' basic block is currently feasible.
377 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
379 // OperandChangedState - This method is invoked on all of the users of an
380 // instruction that was just changed state somehow. Based on this
381 // information, we need to update the specified user of this instruction.
383 void OperandChangedState(User *U) {
384 // Only instructions use other variable values!
385 Instruction &I = cast<Instruction>(*U);
386 if (BBExecutable.count(I.getParent())) // Inst is executable?
391 friend class InstVisitor<SCCPSolver>;
393 // visit implementations - Something changed in this instruction. Either an
394 // operand made a transition, or the instruction is newly executable. Change
395 // the value type of I to reflect these changes if appropriate.
396 void visitPHINode(PHINode &I);
399 void visitReturnInst(ReturnInst &I);
400 void visitTerminatorInst(TerminatorInst &TI);
402 void visitCastInst(CastInst &I);
403 void visitSelectInst(SelectInst &I);
404 void visitBinaryOperator(Instruction &I);
405 void visitCmpInst(CmpInst &I);
406 void visitExtractElementInst(ExtractElementInst &I);
407 void visitInsertElementInst(InsertElementInst &I);
408 void visitShuffleVectorInst(ShuffleVectorInst &I);
409 void visitExtractValueInst(ExtractValueInst &EVI);
410 void visitInsertValueInst(InsertValueInst &IVI);
412 // Instructions that cannot be folded away.
413 void visitStoreInst (StoreInst &I);
414 void visitLoadInst (LoadInst &I);
415 void visitGetElementPtrInst(GetElementPtrInst &I);
416 void visitCallInst (CallInst &I) {
419 visitCallSite(CallSite::get(&I));
421 void visitInvokeInst (InvokeInst &II) {
422 visitCallSite(CallSite::get(&II));
423 visitTerminatorInst(II);
425 void visitCallSite (CallSite CS);
426 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
427 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
428 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
429 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
430 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
432 void visitInstruction(Instruction &I) {
433 // If a new instruction is added to LLVM that we don't handle.
434 errs() << "SCCP: Don't know how to handle: " << I;
435 markOverdefined(&I); // Just in case
439 } // end anonymous namespace
442 // getFeasibleSuccessors - Return a vector of booleans to indicate which
443 // successors are reachable from a given terminator instruction.
445 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
446 SmallVector<bool, 16> &Succs) {
447 Succs.resize(TI.getNumSuccessors());
448 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
449 if (BI->isUnconditional()) {
454 LatticeVal BCValue = getValueState(BI->getCondition());
455 ConstantInt *CI = BCValue.getConstantInt();
457 // Overdefined condition variables, and branches on unfoldable constant
458 // conditions, mean the branch could go either way.
459 if (!BCValue.isUndefined())
460 Succs[0] = Succs[1] = true;
464 // Constant condition variables mean the branch can only go a single way.
465 Succs[CI->isZero()] = true;
469 if (isa<InvokeInst>(TI)) {
470 // Invoke instructions successors are always executable.
471 Succs[0] = Succs[1] = true;
475 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
476 LatticeVal SCValue = getValueState(SI->getCondition());
477 ConstantInt *CI = SCValue.getConstantInt();
479 if (CI == 0) { // Overdefined or undefined condition?
480 // All destinations are executable!
481 if (!SCValue.isUndefined())
482 Succs.assign(TI.getNumSuccessors(), true);
486 Succs[SI->findCaseValue(CI)] = true;
490 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
491 if (isa<IndirectBrInst>(&TI)) {
492 // Just mark all destinations executable!
493 Succs.assign(TI.getNumSuccessors(), true);
498 errs() << "Unknown terminator instruction: " << TI << '\n';
500 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
504 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
505 // block to the 'To' basic block is currently feasible.
507 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
508 assert(BBExecutable.count(To) && "Dest should always be alive!");
510 // Make sure the source basic block is executable!!
511 if (!BBExecutable.count(From)) return false;
513 // Check to make sure this edge itself is actually feasible now.
514 TerminatorInst *TI = From->getTerminator();
515 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
516 if (BI->isUnconditional())
519 LatticeVal BCValue = getValueState(BI->getCondition());
521 // Overdefined condition variables mean the branch could go either way,
522 // undef conditions mean that neither edge is feasible yet.
523 ConstantInt *CI = BCValue.getConstantInt();
525 return !BCValue.isUndefined();
527 // Constant condition variables mean the branch can only go a single way.
528 return BI->getSuccessor(CI->isZero()) == To;
531 // Invoke instructions successors are always executable.
532 if (isa<InvokeInst>(TI))
535 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
536 LatticeVal SCValue = getValueState(SI->getCondition());
537 ConstantInt *CI = SCValue.getConstantInt();
540 return !SCValue.isUndefined();
542 // Make sure to skip the "default value" which isn't a value
543 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
544 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
545 return SI->getSuccessor(i) == To;
547 // If the constant value is not equal to any of the branches, we must
548 // execute default branch.
549 return SI->getDefaultDest() == To;
552 // Just mark all destinations executable!
553 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
554 if (isa<IndirectBrInst>(&TI))
558 errs() << "Unknown terminator instruction: " << *TI << '\n';
563 // visit Implementations - Something changed in this instruction, either an
564 // operand made a transition, or the instruction is newly executable. Change
565 // the value type of I to reflect these changes if appropriate. This method
566 // makes sure to do the following actions:
568 // 1. If a phi node merges two constants in, and has conflicting value coming
569 // from different branches, or if the PHI node merges in an overdefined
570 // value, then the PHI node becomes overdefined.
571 // 2. If a phi node merges only constants in, and they all agree on value, the
572 // PHI node becomes a constant value equal to that.
573 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
574 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
575 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
576 // 6. If a conditional branch has a value that is constant, make the selected
577 // destination executable
578 // 7. If a conditional branch has a value that is overdefined, make all
579 // successors executable.
581 void SCCPSolver::visitPHINode(PHINode &PN) {
582 if (getValueState(&PN).isOverdefined()) {
583 // There may be instructions using this PHI node that are not overdefined
584 // themselves. If so, make sure that they know that the PHI node operand
586 std::multimap<PHINode*, Instruction*>::iterator I, E;
587 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
591 SmallVector<Instruction*, 16> Users;
593 Users.push_back(I->second);
594 while (!Users.empty())
595 visit(Users.pop_back_val());
596 return; // Quick exit
599 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
600 // and slow us down a lot. Just mark them overdefined.
601 if (PN.getNumIncomingValues() > 64)
602 return markOverdefined(&PN);
604 // Look at all of the executable operands of the PHI node. If any of them
605 // are overdefined, the PHI becomes overdefined as well. If they are all
606 // constant, and they agree with each other, the PHI becomes the identical
607 // constant. If they are constant and don't agree, the PHI is overdefined.
608 // If there are no executable operands, the PHI remains undefined.
610 Constant *OperandVal = 0;
611 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
612 LatticeVal IV = getValueState(PN.getIncomingValue(i));
613 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
615 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
618 if (IV.isOverdefined()) // PHI node becomes overdefined!
619 return markOverdefined(&PN);
621 if (OperandVal == 0) { // Grab the first value.
622 OperandVal = IV.getConstant();
626 // There is already a reachable operand. If we conflict with it,
627 // then the PHI node becomes overdefined. If we agree with it, we
630 // Check to see if there are two different constants merging, if so, the PHI
631 // node is overdefined.
632 if (IV.getConstant() != OperandVal)
633 return markOverdefined(&PN);
636 // If we exited the loop, this means that the PHI node only has constant
637 // arguments that agree with each other(and OperandVal is the constant) or
638 // OperandVal is null because there are no defined incoming arguments. If
639 // this is the case, the PHI remains undefined.
642 markConstant(&PN, OperandVal); // Acquire operand value
645 void SCCPSolver::visitReturnInst(ReturnInst &I) {
646 if (I.getNumOperands() == 0) return; // ret void
648 Function *F = I.getParent()->getParent();
649 // If we are tracking the return value of this function, merge it in.
650 if (!F->hasLocalLinkage())
653 if (!TrackedRetVals.empty()) {
654 DenseMap<Function*, LatticeVal>::iterator TFRVI =
655 TrackedRetVals.find(F);
656 if (TFRVI != TrackedRetVals.end() &&
657 !TFRVI->second.isOverdefined()) {
658 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
663 // Handle functions that return multiple values.
664 if (!TrackedMultipleRetVals.empty() &&
665 isa<StructType>(I.getOperand(0)->getType())) {
666 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
668 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
669 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
670 if (It == TrackedMultipleRetVals.end()) break;
671 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
672 mergeInValue(It->second, F, getValueState(Val));
677 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
678 SmallVector<bool, 16> SuccFeasible;
679 getFeasibleSuccessors(TI, SuccFeasible);
681 BasicBlock *BB = TI.getParent();
683 // Mark all feasible successors executable.
684 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
686 markEdgeExecutable(BB, TI.getSuccessor(i));
689 void SCCPSolver::visitCastInst(CastInst &I) {
690 LatticeVal OpSt = getValueState(I.getOperand(0));
691 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
693 else if (OpSt.isConstant()) // Propagate constant value
694 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
695 OpSt.getConstant(), I.getType()));
698 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
699 Value *Aggr = EVI.getAggregateOperand();
701 // If the operand to the extractvalue is an undef, the result is undef.
702 if (isa<UndefValue>(Aggr))
705 // Currently only handle single-index extractvalues.
706 if (EVI.getNumIndices() != 1)
707 return markOverdefined(&EVI);
710 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
711 F = CI->getCalledFunction();
712 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
713 F = II->getCalledFunction();
715 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
717 if (F == 0 || TrackedMultipleRetVals.empty())
718 return markOverdefined(&EVI);
720 // See if we are tracking the result of the callee. If not tracking this
721 // function (for example, it is a declaration) just move to overdefined.
722 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
723 return markOverdefined(&EVI);
725 // Otherwise, the value will be merged in here as a result of CallSite
729 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
730 Value *Aggr = IVI.getAggregateOperand();
731 Value *Val = IVI.getInsertedValueOperand();
733 // If the operands to the insertvalue are undef, the result is undef.
734 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
737 // Currently only handle single-index insertvalues.
738 if (IVI.getNumIndices() != 1)
739 return markOverdefined(&IVI);
741 // Currently only handle insertvalue instructions that are in a single-use
742 // chain that builds up a return value.
743 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
744 if (!TmpIVI->hasOneUse())
745 return markOverdefined(&IVI);
747 const Value *V = *TmpIVI->use_begin();
748 if (isa<ReturnInst>(V))
750 TmpIVI = dyn_cast<InsertValueInst>(V);
752 return markOverdefined(&IVI);
755 // See if we are tracking the result of the callee.
756 Function *F = IVI.getParent()->getParent();
757 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
758 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
760 // Merge in the inserted member value.
761 if (It != TrackedMultipleRetVals.end())
762 mergeInValue(It->second, F, getValueState(Val));
764 // Mark the aggregate result of the IVI overdefined; any tracking that we do
765 // will be done on the individual member values.
766 markOverdefined(&IVI);
769 void SCCPSolver::visitSelectInst(SelectInst &I) {
770 LatticeVal CondValue = getValueState(I.getCondition());
771 if (CondValue.isUndefined())
774 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
775 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
776 mergeInValue(&I, getValueState(OpVal));
780 // Otherwise, the condition is overdefined or a constant we can't evaluate.
781 // See if we can produce something better than overdefined based on the T/F
783 LatticeVal TVal = getValueState(I.getTrueValue());
784 LatticeVal FVal = getValueState(I.getFalseValue());
786 // select ?, C, C -> C.
787 if (TVal.isConstant() && FVal.isConstant() &&
788 TVal.getConstant() == FVal.getConstant())
789 return markConstant(&I, FVal.getConstant());
791 if (TVal.isUndefined()) // select ?, undef, X -> X.
792 return mergeInValue(&I, FVal);
793 if (FVal.isUndefined()) // select ?, X, undef -> X.
794 return mergeInValue(&I, TVal);
798 // Handle Binary Operators.
799 void SCCPSolver::visitBinaryOperator(Instruction &I) {
800 LatticeVal V1State = getValueState(I.getOperand(0));
801 LatticeVal V2State = getValueState(I.getOperand(1));
803 LatticeVal &IV = ValueState[&I];
804 if (IV.isOverdefined()) return;
806 if (V1State.isConstant() && V2State.isConstant())
807 return markConstant(IV, &I,
808 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
809 V2State.getConstant()));
811 // If something is undef, wait for it to resolve.
812 if (!V1State.isOverdefined() && !V2State.isOverdefined())
815 // Otherwise, one of our operands is overdefined. Try to produce something
816 // better than overdefined with some tricks.
818 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
819 // operand is overdefined.
820 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
821 LatticeVal *NonOverdefVal = 0;
822 if (!V1State.isOverdefined())
823 NonOverdefVal = &V1State;
824 else if (!V2State.isOverdefined())
825 NonOverdefVal = &V2State;
828 if (NonOverdefVal->isUndefined()) {
829 // Could annihilate value.
830 if (I.getOpcode() == Instruction::And)
831 markConstant(IV, &I, Constant::getNullValue(I.getType()));
832 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
833 markConstant(IV, &I, Constant::getAllOnesValue(PT));
836 Constant::getAllOnesValue(I.getType()));
840 if (I.getOpcode() == Instruction::And) {
842 if (NonOverdefVal->getConstant()->isNullValue())
843 return markConstant(IV, &I, NonOverdefVal->getConstant());
845 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
846 if (CI->isAllOnesValue()) // X or -1 = -1
847 return markConstant(IV, &I, NonOverdefVal->getConstant());
853 // If both operands are PHI nodes, it is possible that this instruction has
854 // a constant value, despite the fact that the PHI node doesn't. Check for
855 // this condition now.
856 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
857 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
858 if (PN1->getParent() == PN2->getParent()) {
859 // Since the two PHI nodes are in the same basic block, they must have
860 // entries for the same predecessors. Walk the predecessor list, and
861 // if all of the incoming values are constants, and the result of
862 // evaluating this expression with all incoming value pairs is the
863 // same, then this expression is a constant even though the PHI node
864 // is not a constant!
866 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
867 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
868 BasicBlock *InBlock = PN1->getIncomingBlock(i);
869 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
871 if (In1.isOverdefined() || In2.isOverdefined()) {
872 Result.markOverdefined();
873 break; // Cannot fold this operation over the PHI nodes!
876 if (In1.isConstant() && In2.isConstant()) {
877 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
879 if (Result.isUndefined())
880 Result.markConstant(V);
881 else if (Result.isConstant() && Result.getConstant() != V) {
882 Result.markOverdefined();
888 // If we found a constant value here, then we know the instruction is
889 // constant despite the fact that the PHI nodes are overdefined.
890 if (Result.isConstant()) {
891 markConstant(IV, &I, Result.getConstant());
892 // Remember that this instruction is virtually using the PHI node
894 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
895 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
899 if (Result.isUndefined())
902 // Okay, this really is overdefined now. Since we might have
903 // speculatively thought that this was not overdefined before, and
904 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
905 // make sure to clean out any entries that we put there, for
907 UsersOfOverdefinedPHIs.erase(PN1);
908 UsersOfOverdefinedPHIs.erase(PN2);
914 // Handle ICmpInst instruction.
915 void SCCPSolver::visitCmpInst(CmpInst &I) {
916 LatticeVal V1State = getValueState(I.getOperand(0));
917 LatticeVal V2State = getValueState(I.getOperand(1));
919 LatticeVal &IV = ValueState[&I];
920 if (IV.isOverdefined()) return;
922 if (V1State.isConstant() && V2State.isConstant())
923 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
924 V1State.getConstant(),
925 V2State.getConstant()));
927 // If operands are still undefined, wait for it to resolve.
928 if (!V1State.isOverdefined() && !V2State.isOverdefined())
931 // If something is overdefined, use some tricks to avoid ending up and over
932 // defined if we can.
934 // If both operands are PHI nodes, it is possible that this instruction has
935 // a constant value, despite the fact that the PHI node doesn't. Check for
936 // this condition now.
937 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
938 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
939 if (PN1->getParent() == PN2->getParent()) {
940 // Since the two PHI nodes are in the same basic block, they must have
941 // entries for the same predecessors. Walk the predecessor list, and
942 // if all of the incoming values are constants, and the result of
943 // evaluating this expression with all incoming value pairs is the
944 // same, then this expression is a constant even though the PHI node
945 // is not a constant!
947 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
948 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
949 BasicBlock *InBlock = PN1->getIncomingBlock(i);
950 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
952 if (In1.isOverdefined() || In2.isOverdefined()) {
953 Result.markOverdefined();
954 break; // Cannot fold this operation over the PHI nodes!
957 if (In1.isConstant() && In2.isConstant()) {
958 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
961 if (Result.isUndefined())
962 Result.markConstant(V);
963 else if (Result.isConstant() && Result.getConstant() != V) {
964 Result.markOverdefined();
970 // If we found a constant value here, then we know the instruction is
971 // constant despite the fact that the PHI nodes are overdefined.
972 if (Result.isConstant()) {
973 markConstant(&I, Result.getConstant());
974 // Remember that this instruction is virtually using the PHI node
976 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
977 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
981 if (Result.isUndefined())
984 // Okay, this really is overdefined now. Since we might have
985 // speculatively thought that this was not overdefined before, and
986 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
987 // make sure to clean out any entries that we put there, for
989 UsersOfOverdefinedPHIs.erase(PN1);
990 UsersOfOverdefinedPHIs.erase(PN2);
996 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
997 // FIXME : SCCP does not handle vectors properly.
998 return markOverdefined(&I);
1001 LatticeVal &ValState = getValueState(I.getOperand(0));
1002 LatticeVal &IdxState = getValueState(I.getOperand(1));
1004 if (ValState.isOverdefined() || IdxState.isOverdefined())
1005 markOverdefined(&I);
1006 else if(ValState.isConstant() && IdxState.isConstant())
1007 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1008 IdxState.getConstant()));
1012 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1013 // FIXME : SCCP does not handle vectors properly.
1014 return markOverdefined(&I);
1016 LatticeVal &ValState = getValueState(I.getOperand(0));
1017 LatticeVal &EltState = getValueState(I.getOperand(1));
1018 LatticeVal &IdxState = getValueState(I.getOperand(2));
1020 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1021 IdxState.isOverdefined())
1022 markOverdefined(&I);
1023 else if(ValState.isConstant() && EltState.isConstant() &&
1024 IdxState.isConstant())
1025 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1026 EltState.getConstant(),
1027 IdxState.getConstant()));
1028 else if (ValState.isUndefined() && EltState.isConstant() &&
1029 IdxState.isConstant())
1030 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1031 EltState.getConstant(),
1032 IdxState.getConstant()));
1036 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1037 // FIXME : SCCP does not handle vectors properly.
1038 return markOverdefined(&I);
1040 LatticeVal &V1State = getValueState(I.getOperand(0));
1041 LatticeVal &V2State = getValueState(I.getOperand(1));
1042 LatticeVal &MaskState = getValueState(I.getOperand(2));
1044 if (MaskState.isUndefined() ||
1045 (V1State.isUndefined() && V2State.isUndefined()))
1046 return; // Undefined output if mask or both inputs undefined.
1048 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1049 MaskState.isOverdefined()) {
1050 markOverdefined(&I);
1052 // A mix of constant/undef inputs.
1053 Constant *V1 = V1State.isConstant() ?
1054 V1State.getConstant() : UndefValue::get(I.getType());
1055 Constant *V2 = V2State.isConstant() ?
1056 V2State.getConstant() : UndefValue::get(I.getType());
1057 Constant *Mask = MaskState.isConstant() ?
1058 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1059 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1064 // Handle getelementptr instructions. If all operands are constants then we
1065 // can turn this into a getelementptr ConstantExpr.
1067 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1068 LatticeVal &IV = ValueState[&I];
1069 if (IV.isOverdefined()) return;
1071 SmallVector<Constant*, 8> Operands;
1072 Operands.reserve(I.getNumOperands());
1074 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1075 LatticeVal State = getValueState(I.getOperand(i));
1076 if (State.isUndefined())
1077 return; // Operands are not resolved yet.
1079 if (State.isOverdefined())
1080 return markOverdefined(IV, &I);
1082 assert(State.isConstant() && "Unknown state!");
1083 Operands.push_back(State.getConstant());
1086 Constant *Ptr = Operands[0];
1087 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1088 Operands.size()-1));
1091 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1092 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1095 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1096 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1097 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1099 // Get the value we are storing into the global, then merge it.
1100 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1101 if (I->second.isOverdefined())
1102 TrackedGlobals.erase(I); // No need to keep tracking this!
1106 // Handle load instructions. If the operand is a constant pointer to a constant
1107 // global, we can replace the load with the loaded constant value!
1108 void SCCPSolver::visitLoadInst(LoadInst &I) {
1109 LatticeVal PtrVal = getValueState(I.getOperand(0));
1110 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1112 LatticeVal &IV = ValueState[&I];
1113 if (IV.isOverdefined()) return;
1115 if (!PtrVal.isConstant() || I.isVolatile())
1116 return markOverdefined(IV, &I);
1118 Constant *Ptr = PtrVal.getConstant();
1120 // load null -> null
1121 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1122 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1124 // Transform load (constant global) into the value loaded.
1125 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1126 if (!TrackedGlobals.empty()) {
1127 // If we are tracking this global, merge in the known value for it.
1128 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1129 TrackedGlobals.find(GV);
1130 if (It != TrackedGlobals.end()) {
1131 mergeInValue(IV, &I, It->second);
1137 // Transform load from a constant into a constant if possible.
1138 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1139 return markConstant(IV, &I, C);
1141 // Otherwise we cannot say for certain what value this load will produce.
1143 markOverdefined(IV, &I);
1146 void SCCPSolver::visitCallSite(CallSite CS) {
1147 Function *F = CS.getCalledFunction();
1148 Instruction *I = CS.getInstruction();
1150 // The common case is that we aren't tracking the callee, either because we
1151 // are not doing interprocedural analysis or the callee is indirect, or is
1152 // external. Handle these cases first.
1153 if (F == 0 || !F->hasLocalLinkage()) {
1155 // Void return and not tracking callee, just bail.
1156 if (I->getType()->isVoidTy()) return;
1158 // Otherwise, if we have a single return value case, and if the function is
1159 // a declaration, maybe we can constant fold it.
1160 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1161 canConstantFoldCallTo(F)) {
1163 SmallVector<Constant*, 8> Operands;
1164 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1166 LatticeVal State = getValueState(*AI);
1168 if (State.isUndefined())
1169 return; // Operands are not resolved yet.
1170 if (State.isOverdefined())
1171 return markOverdefined(I);
1172 assert(State.isConstant() && "Unknown state!");
1173 Operands.push_back(State.getConstant());
1176 // If we can constant fold this, mark the result of the call as a
1178 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1179 return markConstant(I, C);
1182 // Otherwise, we don't know anything about this call, mark it overdefined.
1183 return markOverdefined(I);
1186 // If this is a single/zero retval case, see if we're tracking the function.
1187 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1188 if (TFRVI != TrackedRetVals.end()) {
1189 // If so, propagate the return value of the callee into this call result.
1190 mergeInValue(I, TFRVI->second);
1191 } else if (isa<StructType>(I->getType())) {
1192 // Check to see if we're tracking this callee, if not, handle it in the
1193 // common path above.
1194 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1195 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1196 if (TMRVI == TrackedMultipleRetVals.end())
1197 goto CallOverdefined;
1199 // Need to mark as overdefined, otherwise it stays undefined which
1200 // creates extractvalue undef, <idx>
1203 // If we are tracking this callee, propagate the return values of the call
1204 // into this call site. We do this by walking all the uses. Single-index
1205 // ExtractValueInst uses can be tracked; anything more complicated is
1206 // currently handled conservatively.
1207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1209 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1210 if (EVI->getNumIndices() == 1) {
1212 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
1216 // The aggregate value is used in a way not handled here. Assume nothing.
1217 markOverdefined(*UI);
1220 // Otherwise we're not tracking this callee, so handle it in the
1221 // common path above.
1222 goto CallOverdefined;
1225 // Finally, if this is the first call to the function hit, mark its entry
1226 // block executable.
1227 MarkBlockExecutable(F->begin());
1229 // Propagate information from this call site into the callee.
1230 CallSite::arg_iterator CAI = CS.arg_begin();
1231 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1232 AI != E; ++AI, ++CAI) {
1233 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1234 markOverdefined(AI);
1238 mergeInValue(AI, getValueState(*CAI));
1242 void SCCPSolver::Solve() {
1243 // Process the work lists until they are empty!
1244 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1245 !OverdefinedInstWorkList.empty()) {
1246 // Process the overdefined instruction's work list first, which drives other
1247 // things to overdefined more quickly.
1248 while (!OverdefinedInstWorkList.empty()) {
1249 Value *I = OverdefinedInstWorkList.pop_back_val();
1251 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
1253 // "I" got into the work list because it either made the transition from
1254 // bottom to constant
1256 // Anything on this worklist that is overdefined need not be visited
1257 // since all of its users will have already been marked as overdefined
1258 // Update all of the users of this instruction's value.
1260 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1262 OperandChangedState(*UI);
1265 // Process the instruction work list.
1266 while (!InstWorkList.empty()) {
1267 Value *I = InstWorkList.pop_back_val();
1269 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
1271 // "I" got into the work list because it made the transition from undef to
1274 // Anything on this worklist that is overdefined need not be visited
1275 // since all of its users will have already been marked as overdefined.
1276 // Update all of the users of this instruction's value.
1278 if (!getValueState(I).isOverdefined())
1279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1281 OperandChangedState(*UI);
1284 // Process the basic block work list.
1285 while (!BBWorkList.empty()) {
1286 BasicBlock *BB = BBWorkList.back();
1287 BBWorkList.pop_back();
1289 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
1291 // Notify all instructions in this basic block that they are newly
1298 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1299 /// that branches on undef values cannot reach any of their successors.
1300 /// However, this is not a safe assumption. After we solve dataflow, this
1301 /// method should be use to handle this. If this returns true, the solver
1302 /// should be rerun.
1304 /// This method handles this by finding an unresolved branch and marking it one
1305 /// of the edges from the block as being feasible, even though the condition
1306 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1307 /// CFG and only slightly pessimizes the analysis results (by marking one,
1308 /// potentially infeasible, edge feasible). This cannot usefully modify the
1309 /// constraints on the condition of the branch, as that would impact other users
1312 /// This scan also checks for values that use undefs, whose results are actually
1313 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1314 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1315 /// even if X isn't defined.
1316 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1317 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1318 if (!BBExecutable.count(BB))
1321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1322 // Look for instructions which produce undef values.
1323 if (I->getType()->isVoidTy()) continue;
1325 LatticeVal &LV = getValueState(I);
1326 if (!LV.isUndefined()) continue;
1328 // Get the lattice values of the first two operands for use below.
1329 LatticeVal Op0LV = getValueState(I->getOperand(0));
1331 if (I->getNumOperands() == 2) {
1332 // If this is a two-operand instruction, and if both operands are
1333 // undefs, the result stays undef.
1334 Op1LV = getValueState(I->getOperand(1));
1335 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1339 // If this is an instructions whose result is defined even if the input is
1340 // not fully defined, propagate the information.
1341 const Type *ITy = I->getType();
1342 switch (I->getOpcode()) {
1343 default: break; // Leave the instruction as an undef.
1344 case Instruction::ZExt:
1345 // After a zero extend, we know the top part is zero. SExt doesn't have
1346 // to be handled here, because we don't know whether the top part is 1's
1348 markForcedConstant(I, Constant::getNullValue(ITy));
1350 case Instruction::Mul:
1351 case Instruction::And:
1352 // undef * X -> 0. X could be zero.
1353 // undef & X -> 0. X could be zero.
1354 markForcedConstant(I, Constant::getNullValue(ITy));
1357 case Instruction::Or:
1358 // undef | X -> -1. X could be -1.
1359 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1362 case Instruction::SDiv:
1363 case Instruction::UDiv:
1364 case Instruction::SRem:
1365 case Instruction::URem:
1366 // X / undef -> undef. No change.
1367 // X % undef -> undef. No change.
1368 if (Op1LV.isUndefined()) break;
1370 // undef / X -> 0. X could be maxint.
1371 // undef % X -> 0. X could be 1.
1372 markForcedConstant(I, Constant::getNullValue(ITy));
1375 case Instruction::AShr:
1376 // undef >>s X -> undef. No change.
1377 if (Op0LV.isUndefined()) break;
1379 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1380 if (Op0LV.isConstant())
1381 markForcedConstant(I, Op0LV.getConstant());
1385 case Instruction::LShr:
1386 case Instruction::Shl:
1387 // undef >> X -> undef. No change.
1388 // undef << X -> undef. No change.
1389 if (Op0LV.isUndefined()) break;
1391 // X >> undef -> 0. X could be 0.
1392 // X << undef -> 0. X could be 0.
1393 markForcedConstant(I, Constant::getNullValue(ITy));
1395 case Instruction::Select:
1396 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1397 if (Op0LV.isUndefined()) {
1398 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1399 Op1LV = getValueState(I->getOperand(2));
1400 } else if (Op1LV.isUndefined()) {
1401 // c ? undef : undef -> undef. No change.
1402 Op1LV = getValueState(I->getOperand(2));
1403 if (Op1LV.isUndefined())
1405 // Otherwise, c ? undef : x -> x.
1407 // Leave Op1LV as Operand(1)'s LatticeValue.
1410 if (Op1LV.isConstant())
1411 markForcedConstant(I, Op1LV.getConstant());
1415 case Instruction::Call:
1416 // If a call has an undef result, it is because it is constant foldable
1417 // but one of the inputs was undef. Just force the result to
1424 TerminatorInst *TI = BB->getTerminator();
1425 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1426 if (!BI->isConditional()) continue;
1427 if (!getValueState(BI->getCondition()).isUndefined())
1429 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1430 if (SI->getNumSuccessors() < 2) // no cases
1432 if (!getValueState(SI->getCondition()).isUndefined())
1438 // If the edge to the second successor isn't thought to be feasible yet,
1439 // mark it so now. We pick the second one so that this goes to some
1440 // enumerated value in a switch instead of going to the default destination.
1441 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1444 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1445 // and return. This will make other blocks reachable, which will allow new
1446 // values to be discovered and existing ones to be moved in the lattice.
1447 markEdgeExecutable(BB, TI->getSuccessor(1));
1449 // This must be a conditional branch of switch on undef. At this point,
1450 // force the old terminator to branch to the first successor. This is
1451 // required because we are now influencing the dataflow of the function with
1452 // the assumption that this edge is taken. If we leave the branch condition
1453 // as undef, then further analysis could think the undef went another way
1454 // leading to an inconsistent set of conclusions.
1455 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1456 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1458 SwitchInst *SI = cast<SwitchInst>(TI);
1459 SI->setCondition(SI->getCaseValue(1));
1470 //===--------------------------------------------------------------------===//
1472 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1473 /// Sparse Conditional Constant Propagator.
1475 struct SCCP : public FunctionPass {
1476 static char ID; // Pass identification, replacement for typeid
1477 SCCP() : FunctionPass(&ID) {}
1479 // runOnFunction - Run the Sparse Conditional Constant Propagation
1480 // algorithm, and return true if the function was modified.
1482 bool runOnFunction(Function &F);
1484 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1485 AU.setPreservesCFG();
1488 } // end anonymous namespace
1491 static RegisterPass<SCCP>
1492 X("sccp", "Sparse Conditional Constant Propagation");
1494 // createSCCPPass - This is the public interface to this file.
1495 FunctionPass *llvm::createSCCPPass() {
1499 static void DeleteInstructionInBlock(BasicBlock *BB) {
1500 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1503 // Delete the instructions backwards, as it has a reduced likelihood of
1504 // having to update as many def-use and use-def chains.
1505 while (!isa<TerminatorInst>(BB->begin())) {
1506 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1508 if (!I->use_empty())
1509 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1510 BB->getInstList().erase(I);
1515 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1516 // and return true if the function was modified.
1518 bool SCCP::runOnFunction(Function &F) {
1519 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
1520 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1522 // Mark the first block of the function as being executable.
1523 Solver.MarkBlockExecutable(F.begin());
1525 // Mark all arguments to the function as being overdefined.
1526 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1527 Solver.markOverdefined(AI);
1529 // Solve for constants.
1530 bool ResolvedUndefs = true;
1531 while (ResolvedUndefs) {
1533 DEBUG(errs() << "RESOLVING UNDEFs\n");
1534 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1537 bool MadeChanges = false;
1539 // If we decided that there are basic blocks that are dead in this function,
1540 // delete their contents now. Note that we cannot actually delete the blocks,
1541 // as we cannot modify the CFG of the function.
1543 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1544 if (!Solver.isBlockExecutable(BB)) {
1545 DeleteInstructionInBlock(BB);
1550 // Iterate over all of the instructions in a function, replacing them with
1551 // constants if we have found them to be of constant values.
1553 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1554 Instruction *Inst = BI++;
1555 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1558 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1559 if (IV.isOverdefined())
1562 Constant *Const = IV.isConstant()
1563 ? IV.getConstant() : UndefValue::get(Inst->getType());
1564 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1566 // Replaces all of the uses of a variable with uses of the constant.
1567 Inst->replaceAllUsesWith(Const);
1569 // Delete the instruction.
1570 Inst->eraseFromParent();
1572 // Hey, we just changed something!
1582 //===--------------------------------------------------------------------===//
1584 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1585 /// Constant Propagation.
1587 struct IPSCCP : public ModulePass {
1589 IPSCCP() : ModulePass(&ID) {}
1590 bool runOnModule(Module &M);
1592 } // end anonymous namespace
1594 char IPSCCP::ID = 0;
1595 static RegisterPass<IPSCCP>
1596 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1598 // createIPSCCPPass - This is the public interface to this file.
1599 ModulePass *llvm::createIPSCCPPass() {
1600 return new IPSCCP();
1604 static bool AddressIsTaken(GlobalValue *GV) {
1605 // Delete any dead constantexpr klingons.
1606 GV->removeDeadConstantUsers();
1608 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1610 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1611 if (SI->getOperand(0) == GV || SI->isVolatile())
1612 return true; // Storing addr of GV.
1613 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1614 // Make sure we are calling the function, not passing the address.
1615 if (UI.getOperandNo() != 0)
1617 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1618 if (LI->isVolatile())
1620 } else if (isa<BlockAddress>(*UI)) {
1621 // blockaddress doesn't take the address of the function, it takes addr
1629 bool IPSCCP::runOnModule(Module &M) {
1630 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1632 // Loop over all functions, marking arguments to those with their addresses
1633 // taken or that are external as overdefined.
1635 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1636 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
1637 if (!F->isDeclaration())
1638 Solver.MarkBlockExecutable(F->begin());
1639 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1641 Solver.markOverdefined(AI);
1643 Solver.AddTrackedFunction(F);
1646 // Loop over global variables. We inform the solver about any internal global
1647 // variables that do not have their 'addresses taken'. If they don't have
1648 // their addresses taken, we can propagate constants through them.
1649 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1651 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1652 Solver.TrackValueOfGlobalVariable(G);
1654 // Solve for constants.
1655 bool ResolvedUndefs = true;
1656 while (ResolvedUndefs) {
1659 DEBUG(errs() << "RESOLVING UNDEFS\n");
1660 ResolvedUndefs = false;
1661 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1662 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1665 bool MadeChanges = false;
1667 // Iterate over all of the instructions in the module, replacing them with
1668 // constants if we have found them to be of constant values.
1670 SmallVector<BasicBlock*, 512> BlocksToErase;
1672 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1673 if (Solver.isBlockExecutable(F->begin())) {
1674 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1676 if (AI->use_empty()) continue;
1678 LatticeVal IV = Solver.getLatticeValueFor(AI);
1679 if (IV.isOverdefined()) continue;
1681 Constant *CST = IV.isConstant() ?
1682 IV.getConstant() : UndefValue::get(AI->getType());
1683 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1685 // Replaces all of the uses of a variable with uses of the
1687 AI->replaceAllUsesWith(CST);
1692 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1693 if (!Solver.isBlockExecutable(BB)) {
1694 DeleteInstructionInBlock(BB);
1697 TerminatorInst *TI = BB->getTerminator();
1698 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1699 BasicBlock *Succ = TI->getSuccessor(i);
1700 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1701 TI->getSuccessor(i)->removePredecessor(BB);
1703 if (!TI->use_empty())
1704 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1705 TI->eraseFromParent();
1707 if (&*BB != &F->front())
1708 BlocksToErase.push_back(BB);
1710 new UnreachableInst(M.getContext(), BB);
1714 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1715 Instruction *Inst = BI++;
1716 if (Inst->getType()->isVoidTy())
1719 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1720 if (IV.isOverdefined())
1723 Constant *Const = IV.isConstant()
1724 ? IV.getConstant() : UndefValue::get(Inst->getType());
1725 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1727 // Replaces all of the uses of a variable with uses of the
1729 Inst->replaceAllUsesWith(Const);
1731 // Delete the instruction.
1732 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1733 Inst->eraseFromParent();
1735 // Hey, we just changed something!
1741 // Now that all instructions in the function are constant folded, erase dead
1742 // blocks, because we can now use ConstantFoldTerminator to get rid of
1744 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1745 // If there are any PHI nodes in this successor, drop entries for BB now.
1746 BasicBlock *DeadBB = BlocksToErase[i];
1747 while (!DeadBB->use_empty()) {
1748 Instruction *I = cast<Instruction>(DeadBB->use_back());
1749 bool Folded = ConstantFoldTerminator(I->getParent());
1751 // The constant folder may not have been able to fold the terminator
1752 // if this is a branch or switch on undef. Fold it manually as a
1753 // branch to the first successor.
1755 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1756 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1757 "Branch should be foldable!");
1758 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1759 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1761 llvm_unreachable("Didn't fold away reference to block!");
1765 // Make this an uncond branch to the first successor.
1766 TerminatorInst *TI = I->getParent()->getTerminator();
1767 BranchInst::Create(TI->getSuccessor(0), TI);
1769 // Remove entries in successor phi nodes to remove edges.
1770 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1771 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1773 // Remove the old terminator.
1774 TI->eraseFromParent();
1778 // Finally, delete the basic block.
1779 F->getBasicBlockList().erase(DeadBB);
1781 BlocksToErase.clear();
1784 // If we inferred constant or undef return values for a function, we replaced
1785 // all call uses with the inferred value. This means we don't need to bother
1786 // actually returning anything from the function. Replace all return
1787 // instructions with return undef.
1788 // TODO: Process multiple value ret instructions also.
1789 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1790 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1791 E = RV.end(); I != E; ++I)
1792 if (!I->second.isOverdefined() &&
1793 !I->first->getReturnType()->isVoidTy()) {
1794 Function *F = I->first;
1795 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1796 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1797 if (!isa<UndefValue>(RI->getOperand(0)))
1798 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1801 // If we infered constant or undef values for globals variables, we can delete
1802 // the global and any stores that remain to it.
1803 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1804 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1805 E = TG.end(); I != E; ++I) {
1806 GlobalVariable *GV = I->first;
1807 assert(!I->second.isOverdefined() &&
1808 "Overdefined values should have been taken out of the map!");
1809 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1810 while (!GV->use_empty()) {
1811 StoreInst *SI = cast<StoreInst>(GV->use_back());
1812 SI->eraseFromParent();
1814 M.getGlobalList().erase(GV);