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 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/InstVisitor.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/IPO.h"
40 #include "llvm/Transforms/Utils/Local.h"
44 #define DEBUG_TYPE "sccp"
46 STATISTIC(NumInstRemoved, "Number of instructions removed");
47 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
50 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
51 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54 /// LatticeVal class - This class represents the different lattice values that
55 /// an LLVM value may occupy. It is a simple class with value semantics.
59 /// undefined - This LLVM Value has no known value yet.
62 /// constant - This LLVM Value has a specific constant value.
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
71 /// overdefined - This instruction is not known to be constant, and we know
76 /// Val: This stores the current lattice value along with the Constant* for
77 /// the constant if this is a 'constant' or 'forcedconstant' value.
78 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
80 LatticeValueTy getLatticeValue() const {
85 LatticeVal() : Val(nullptr, undefined) {}
87 bool isUndefined() const { return getLatticeValue() == undefined; }
88 bool isConstant() const {
89 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 bool isOverdefined() const { return getLatticeValue() == overdefined; }
93 Constant *getConstant() const {
94 assert(isConstant() && "Cannot get the constant of a non-constant!");
95 return Val.getPointer();
98 /// markOverdefined - Return true if this is a change in status.
99 bool markOverdefined() {
103 Val.setInt(overdefined);
107 /// markConstant - Return true if this is a change in status.
108 bool markConstant(Constant *V) {
109 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
110 assert(getConstant() == V && "Marking constant with different value");
115 Val.setInt(constant);
116 assert(V && "Marking constant with NULL");
119 assert(getLatticeValue() == forcedconstant &&
120 "Cannot move from overdefined to constant!");
121 // Stay at forcedconstant if the constant is the same.
122 if (V == getConstant()) return false;
124 // Otherwise, we go to overdefined. Assumptions made based on the
125 // forced value are possibly wrong. Assuming this is another constant
126 // could expose a contradiction.
127 Val.setInt(overdefined);
132 /// getConstantInt - If this is a constant with a ConstantInt value, return it
133 /// otherwise return null.
134 ConstantInt *getConstantInt() const {
136 return dyn_cast<ConstantInt>(getConstant());
140 void markForcedConstant(Constant *V) {
141 assert(isUndefined() && "Can't force a defined value!");
142 Val.setInt(forcedconstant);
146 } // end anonymous namespace.
151 //===----------------------------------------------------------------------===//
153 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
154 /// Constant Propagation.
156 class SCCPSolver : public InstVisitor<SCCPSolver> {
157 const DataLayout &DL;
158 const TargetLibraryInfo *TLI;
159 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
162 /// StructValueState - This maintains ValueState for values that have
163 /// StructType, for example for formal arguments, calls, insertelement, etc.
165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
167 /// GlobalValue - If we are tracking any values for the contents of a global
168 /// variable, we keep a mapping from the constant accessor to the element of
169 /// the global, to the currently known value. If the value becomes
170 /// overdefined, it's entry is simply removed from this map.
171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
173 /// TrackedRetVals - If we are tracking arguments into and the return
174 /// value out of a function, it will have an entry in this map, indicating
175 /// what the known return value for the function is.
176 DenseMap<Function*, LatticeVal> TrackedRetVals;
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
191 /// The reason for two worklists is that overdefined is the lowest state
192 /// on the lattice, and moving things to overdefined as fast as possible
193 /// makes SCCP converge much faster.
195 /// By having a separate worklist, we accomplish this because everything
196 /// possibly overdefined will become overdefined at the soonest possible
198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
204 /// KnownFeasibleEdges - Entries in this set are edges which have already had
205 /// PHI nodes retriggered.
206 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
207 DenseSet<Edge> KnownFeasibleEdges;
209 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
210 : DL(DL), TLI(tli) {}
212 /// MarkBlockExecutable - This method can be used by clients to mark all of
213 /// the blocks that are known to be intrinsically live in the processed unit.
215 /// This returns true if the block was not considered live before.
216 bool MarkBlockExecutable(BasicBlock *BB) {
217 if (!BBExecutable.insert(BB).second)
219 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
220 BBWorkList.push_back(BB); // Add the block to the work list!
224 /// TrackValueOfGlobalVariable - Clients can use this method to
225 /// inform the SCCPSolver that it should track loads and stores to the
226 /// specified global variable if it can. This is only legal to call if
227 /// performing Interprocedural SCCP.
228 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
229 // We only track the contents of scalar globals.
230 if (GV->getType()->getElementType()->isSingleValueType()) {
231 LatticeVal &IV = TrackedGlobals[GV];
232 if (!isa<UndefValue>(GV->getInitializer()))
233 IV.markConstant(GV->getInitializer());
237 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
238 /// and out of the specified function (which cannot have its address taken),
239 /// this method must be called.
240 void AddTrackedFunction(Function *F) {
241 // Add an entry, F -> undef.
242 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
243 MRVFunctionsTracked.insert(F);
244 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
245 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
251 void AddArgumentTrackedFunction(Function *F) {
252 TrackingIncomingArguments.insert(F);
255 /// Solve - Solve for constants and executable blocks.
259 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
260 /// that branches on undef values cannot reach any of their successors.
261 /// However, this is not a safe assumption. After we solve dataflow, this
262 /// method should be use to handle this. If this returns true, the solver
264 bool ResolvedUndefsIn(Function &F);
266 bool isBlockExecutable(BasicBlock *BB) const {
267 return BBExecutable.count(BB);
270 LatticeVal getLatticeValueFor(Value *V) const {
271 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
272 assert(I != ValueState.end() && "V is not in valuemap!");
276 /// getTrackedRetVals - Get the inferred return value map.
278 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
279 return TrackedRetVals;
282 /// getTrackedGlobals - Get and return the set of inferred initializers for
283 /// global variables.
284 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
285 return TrackedGlobals;
288 void markOverdefined(Value *V) {
289 assert(!V->getType()->isStructTy() && "Should use other method");
290 markOverdefined(ValueState[V], V);
293 /// markAnythingOverdefined - Mark the specified value overdefined. This
294 /// works with both scalars and structs.
295 void markAnythingOverdefined(Value *V) {
296 if (StructType *STy = dyn_cast<StructType>(V->getType()))
297 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
298 markOverdefined(getStructValueState(V, i), V);
304 // markConstant - Make a value be marked as "constant". If the value
305 // is not already a constant, add it to the instruction work list so that
306 // the users of the instruction are updated later.
308 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
309 if (!IV.markConstant(C)) return;
310 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
311 if (IV.isOverdefined())
312 OverdefinedInstWorkList.push_back(V);
314 InstWorkList.push_back(V);
317 void markConstant(Value *V, Constant *C) {
318 assert(!V->getType()->isStructTy() && "Should use other method");
319 markConstant(ValueState[V], V, C);
322 void markForcedConstant(Value *V, Constant *C) {
323 assert(!V->getType()->isStructTy() && "Should use other method");
324 LatticeVal &IV = ValueState[V];
325 IV.markForcedConstant(C);
326 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
327 if (IV.isOverdefined())
328 OverdefinedInstWorkList.push_back(V);
330 InstWorkList.push_back(V);
334 // markOverdefined - Make a value be marked as "overdefined". If the
335 // value is not already overdefined, add it to the overdefined instruction
336 // work list so that the users of the instruction are updated later.
337 void markOverdefined(LatticeVal &IV, Value *V) {
338 if (!IV.markOverdefined()) return;
340 DEBUG(dbgs() << "markOverdefined: ";
341 if (Function *F = dyn_cast<Function>(V))
342 dbgs() << "Function '" << F->getName() << "'\n";
344 dbgs() << *V << '\n');
345 // Only instructions go on the work list
346 OverdefinedInstWorkList.push_back(V);
349 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
350 if (IV.isOverdefined() || MergeWithV.isUndefined())
352 if (MergeWithV.isOverdefined())
353 markOverdefined(IV, V);
354 else if (IV.isUndefined())
355 markConstant(IV, V, MergeWithV.getConstant());
356 else if (IV.getConstant() != MergeWithV.getConstant())
357 markOverdefined(IV, V);
360 void mergeInValue(Value *V, LatticeVal MergeWithV) {
361 assert(!V->getType()->isStructTy() && "Should use other method");
362 mergeInValue(ValueState[V], V, MergeWithV);
366 /// getValueState - Return the LatticeVal object that corresponds to the
367 /// value. This function handles the case when the value hasn't been seen yet
368 /// by properly seeding constants etc.
369 LatticeVal &getValueState(Value *V) {
370 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
372 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
373 ValueState.insert(std::make_pair(V, LatticeVal()));
374 LatticeVal &LV = I.first->second;
377 return LV; // Common case, already in the map.
379 if (Constant *C = dyn_cast<Constant>(V)) {
380 // Undef values remain undefined.
381 if (!isa<UndefValue>(V))
382 LV.markConstant(C); // Constants are constant
385 // All others are underdefined by default.
389 /// getStructValueState - Return the LatticeVal object that corresponds to the
390 /// value/field pair. This function handles the case when the value hasn't
391 /// been seen yet by properly seeding constants etc.
392 LatticeVal &getStructValueState(Value *V, unsigned i) {
393 assert(V->getType()->isStructTy() && "Should use getValueState");
394 assert(i < cast<StructType>(V->getType())->getNumElements() &&
395 "Invalid element #");
397 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
398 bool> I = StructValueState.insert(
399 std::make_pair(std::make_pair(V, i), LatticeVal()));
400 LatticeVal &LV = I.first->second;
403 return LV; // Common case, already in the map.
405 if (Constant *C = dyn_cast<Constant>(V)) {
406 Constant *Elt = C->getAggregateElement(i);
409 LV.markOverdefined(); // Unknown sort of constant.
410 else if (isa<UndefValue>(Elt))
411 ; // Undef values remain undefined.
413 LV.markConstant(Elt); // Constants are constant.
416 // All others are underdefined by default.
421 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
422 /// work list if it is not already executable.
423 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
424 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
425 return; // This edge is already known to be executable!
427 if (!MarkBlockExecutable(Dest)) {
428 // If the destination is already executable, we just made an *edge*
429 // feasible that wasn't before. Revisit the PHI nodes in the block
430 // because they have potentially new operands.
431 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
432 << " -> " << Dest->getName() << '\n');
435 for (BasicBlock::iterator I = Dest->begin();
436 (PN = dyn_cast<PHINode>(I)); ++I)
441 // getFeasibleSuccessors - Return a vector of booleans to indicate which
442 // successors are reachable from a given terminator instruction.
444 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
446 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
447 // block to the 'To' basic block is currently feasible.
449 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
451 // OperandChangedState - This method is invoked on all of the users of an
452 // instruction that was just changed state somehow. Based on this
453 // information, we need to update the specified user of this instruction.
455 void OperandChangedState(Instruction *I) {
456 if (BBExecutable.count(I->getParent())) // Inst is executable?
461 friend class InstVisitor<SCCPSolver>;
463 // visit implementations - Something changed in this instruction. Either an
464 // operand made a transition, or the instruction is newly executable. Change
465 // the value type of I to reflect these changes if appropriate.
466 void visitPHINode(PHINode &I);
469 void visitReturnInst(ReturnInst &I);
470 void visitTerminatorInst(TerminatorInst &TI);
472 void visitCastInst(CastInst &I);
473 void visitSelectInst(SelectInst &I);
474 void visitBinaryOperator(Instruction &I);
475 void visitCmpInst(CmpInst &I);
476 void visitExtractElementInst(ExtractElementInst &I);
477 void visitInsertElementInst(InsertElementInst &I);
478 void visitShuffleVectorInst(ShuffleVectorInst &I);
479 void visitExtractValueInst(ExtractValueInst &EVI);
480 void visitInsertValueInst(InsertValueInst &IVI);
481 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
482 void visitCleanupPadInst(CleanupPadInst &CPI) { markAnythingOverdefined(&CPI); }
483 void visitCatchPadInst(CatchPadInst &CPI) {
484 markAnythingOverdefined(&CPI);
485 visitTerminatorInst(CPI);
488 // Instructions that cannot be folded away.
489 void visitStoreInst (StoreInst &I);
490 void visitLoadInst (LoadInst &I);
491 void visitGetElementPtrInst(GetElementPtrInst &I);
492 void visitCallInst (CallInst &I) {
495 void visitInvokeInst (InvokeInst &II) {
497 visitTerminatorInst(II);
499 void visitCallSite (CallSite CS);
500 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
501 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
502 void visitFenceInst (FenceInst &I) { /*returns void*/ }
503 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
504 markAnythingOverdefined(&I);
506 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
507 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
508 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
510 void visitInstruction(Instruction &I) {
511 // If a new instruction is added to LLVM that we don't handle.
512 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
513 markAnythingOverdefined(&I); // Just in case
517 } // end anonymous namespace
520 // getFeasibleSuccessors - Return a vector of booleans to indicate which
521 // successors are reachable from a given terminator instruction.
523 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
524 SmallVectorImpl<bool> &Succs) {
525 Succs.resize(TI.getNumSuccessors());
526 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
527 if (BI->isUnconditional()) {
532 LatticeVal BCValue = getValueState(BI->getCondition());
533 ConstantInt *CI = BCValue.getConstantInt();
535 // Overdefined condition variables, and branches on unfoldable constant
536 // conditions, mean the branch could go either way.
537 if (!BCValue.isUndefined())
538 Succs[0] = Succs[1] = true;
542 // Constant condition variables mean the branch can only go a single way.
543 Succs[CI->isZero()] = true;
547 // Unwinding instructions successors are always executable.
548 if (TI.isExceptional()) {
549 Succs.assign(TI.getNumSuccessors(), true);
553 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
554 if (!SI->getNumCases()) {
558 LatticeVal SCValue = getValueState(SI->getCondition());
559 ConstantInt *CI = SCValue.getConstantInt();
561 if (!CI) { // Overdefined or undefined condition?
562 // All destinations are executable!
563 if (!SCValue.isUndefined())
564 Succs.assign(TI.getNumSuccessors(), true);
568 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
572 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
573 if (isa<IndirectBrInst>(&TI)) {
574 // Just mark all destinations executable!
575 Succs.assign(TI.getNumSuccessors(), true);
580 dbgs() << "Unknown terminator instruction: " << TI << '\n';
582 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
586 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
587 // block to the 'To' basic block is currently feasible.
589 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
590 assert(BBExecutable.count(To) && "Dest should always be alive!");
592 // Make sure the source basic block is executable!!
593 if (!BBExecutable.count(From)) return false;
595 // Check to make sure this edge itself is actually feasible now.
596 TerminatorInst *TI = From->getTerminator();
597 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
598 if (BI->isUnconditional())
601 LatticeVal BCValue = getValueState(BI->getCondition());
603 // Overdefined condition variables mean the branch could go either way,
604 // undef conditions mean that neither edge is feasible yet.
605 ConstantInt *CI = BCValue.getConstantInt();
607 return !BCValue.isUndefined();
609 // Constant condition variables mean the branch can only go a single way.
610 return BI->getSuccessor(CI->isZero()) == To;
613 // Unwinding instructions successors are always executable.
614 if (TI->isExceptional())
617 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
618 if (SI->getNumCases() < 1)
621 LatticeVal SCValue = getValueState(SI->getCondition());
622 ConstantInt *CI = SCValue.getConstantInt();
625 return !SCValue.isUndefined();
627 return SI->findCaseValue(CI).getCaseSuccessor() == To;
630 // Just mark all destinations executable!
631 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
632 if (isa<IndirectBrInst>(TI))
636 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
638 llvm_unreachable(nullptr);
641 // visit Implementations - Something changed in this instruction, either an
642 // operand made a transition, or the instruction is newly executable. Change
643 // the value type of I to reflect these changes if appropriate. This method
644 // makes sure to do the following actions:
646 // 1. If a phi node merges two constants in, and has conflicting value coming
647 // from different branches, or if the PHI node merges in an overdefined
648 // value, then the PHI node becomes overdefined.
649 // 2. If a phi node merges only constants in, and they all agree on value, the
650 // PHI node becomes a constant value equal to that.
651 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
652 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
653 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
654 // 6. If a conditional branch has a value that is constant, make the selected
655 // destination executable
656 // 7. If a conditional branch has a value that is overdefined, make all
657 // successors executable.
659 void SCCPSolver::visitPHINode(PHINode &PN) {
660 // If this PN returns a struct, just mark the result overdefined.
661 // TODO: We could do a lot better than this if code actually uses this.
662 if (PN.getType()->isStructTy())
663 return markAnythingOverdefined(&PN);
665 if (getValueState(&PN).isOverdefined())
666 return; // Quick exit
668 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
669 // and slow us down a lot. Just mark them overdefined.
670 if (PN.getNumIncomingValues() > 64)
671 return markOverdefined(&PN);
673 // Look at all of the executable operands of the PHI node. If any of them
674 // are overdefined, the PHI becomes overdefined as well. If they are all
675 // constant, and they agree with each other, the PHI becomes the identical
676 // constant. If they are constant and don't agree, the PHI is overdefined.
677 // If there are no executable operands, the PHI remains undefined.
679 Constant *OperandVal = nullptr;
680 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
681 LatticeVal IV = getValueState(PN.getIncomingValue(i));
682 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
684 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
687 if (IV.isOverdefined()) // PHI node becomes overdefined!
688 return markOverdefined(&PN);
690 if (!OperandVal) { // Grab the first value.
691 OperandVal = IV.getConstant();
695 // There is already a reachable operand. If we conflict with it,
696 // then the PHI node becomes overdefined. If we agree with it, we
699 // Check to see if there are two different constants merging, if so, the PHI
700 // node is overdefined.
701 if (IV.getConstant() != OperandVal)
702 return markOverdefined(&PN);
705 // If we exited the loop, this means that the PHI node only has constant
706 // arguments that agree with each other(and OperandVal is the constant) or
707 // OperandVal is null because there are no defined incoming arguments. If
708 // this is the case, the PHI remains undefined.
711 markConstant(&PN, OperandVal); // Acquire operand value
714 void SCCPSolver::visitReturnInst(ReturnInst &I) {
715 if (I.getNumOperands() == 0) return; // ret void
717 Function *F = I.getParent()->getParent();
718 Value *ResultOp = I.getOperand(0);
720 // If we are tracking the return value of this function, merge it in.
721 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
722 DenseMap<Function*, LatticeVal>::iterator TFRVI =
723 TrackedRetVals.find(F);
724 if (TFRVI != TrackedRetVals.end()) {
725 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
730 // Handle functions that return multiple values.
731 if (!TrackedMultipleRetVals.empty()) {
732 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
733 if (MRVFunctionsTracked.count(F))
734 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
735 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
736 getStructValueState(ResultOp, i));
741 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
742 SmallVector<bool, 16> SuccFeasible;
743 getFeasibleSuccessors(TI, SuccFeasible);
745 BasicBlock *BB = TI.getParent();
747 // Mark all feasible successors executable.
748 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
750 markEdgeExecutable(BB, TI.getSuccessor(i));
753 void SCCPSolver::visitCastInst(CastInst &I) {
754 LatticeVal OpSt = getValueState(I.getOperand(0));
755 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
757 else if (OpSt.isConstant()) // Propagate constant value
758 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
759 OpSt.getConstant(), I.getType()));
763 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
764 // If this returns a struct, mark all elements over defined, we don't track
765 // structs in structs.
766 if (EVI.getType()->isStructTy())
767 return markAnythingOverdefined(&EVI);
769 // If this is extracting from more than one level of struct, we don't know.
770 if (EVI.getNumIndices() != 1)
771 return markOverdefined(&EVI);
773 Value *AggVal = EVI.getAggregateOperand();
774 if (AggVal->getType()->isStructTy()) {
775 unsigned i = *EVI.idx_begin();
776 LatticeVal EltVal = getStructValueState(AggVal, i);
777 mergeInValue(getValueState(&EVI), &EVI, EltVal);
779 // Otherwise, must be extracting from an array.
780 return markOverdefined(&EVI);
784 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
785 StructType *STy = dyn_cast<StructType>(IVI.getType());
787 return markOverdefined(&IVI);
789 // If this has more than one index, we can't handle it, drive all results to
791 if (IVI.getNumIndices() != 1)
792 return markAnythingOverdefined(&IVI);
794 Value *Aggr = IVI.getAggregateOperand();
795 unsigned Idx = *IVI.idx_begin();
797 // Compute the result based on what we're inserting.
798 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
799 // This passes through all values that aren't the inserted element.
801 LatticeVal EltVal = getStructValueState(Aggr, i);
802 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
806 Value *Val = IVI.getInsertedValueOperand();
807 if (Val->getType()->isStructTy())
808 // We don't track structs in structs.
809 markOverdefined(getStructValueState(&IVI, i), &IVI);
811 LatticeVal InVal = getValueState(Val);
812 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
817 void SCCPSolver::visitSelectInst(SelectInst &I) {
818 // If this select returns a struct, just mark the result overdefined.
819 // TODO: We could do a lot better than this if code actually uses this.
820 if (I.getType()->isStructTy())
821 return markAnythingOverdefined(&I);
823 LatticeVal CondValue = getValueState(I.getCondition());
824 if (CondValue.isUndefined())
827 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
828 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
829 mergeInValue(&I, getValueState(OpVal));
833 // Otherwise, the condition is overdefined or a constant we can't evaluate.
834 // See if we can produce something better than overdefined based on the T/F
836 LatticeVal TVal = getValueState(I.getTrueValue());
837 LatticeVal FVal = getValueState(I.getFalseValue());
839 // select ?, C, C -> C.
840 if (TVal.isConstant() && FVal.isConstant() &&
841 TVal.getConstant() == FVal.getConstant())
842 return markConstant(&I, FVal.getConstant());
844 if (TVal.isUndefined()) // select ?, undef, X -> X.
845 return mergeInValue(&I, FVal);
846 if (FVal.isUndefined()) // select ?, X, undef -> X.
847 return mergeInValue(&I, TVal);
851 // Handle Binary Operators.
852 void SCCPSolver::visitBinaryOperator(Instruction &I) {
853 LatticeVal V1State = getValueState(I.getOperand(0));
854 LatticeVal V2State = getValueState(I.getOperand(1));
856 LatticeVal &IV = ValueState[&I];
857 if (IV.isOverdefined()) return;
859 if (V1State.isConstant() && V2State.isConstant())
860 return markConstant(IV, &I,
861 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
862 V2State.getConstant()));
864 // If something is undef, wait for it to resolve.
865 if (!V1State.isOverdefined() && !V2State.isOverdefined())
868 // Otherwise, one of our operands is overdefined. Try to produce something
869 // better than overdefined with some tricks.
871 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
872 // operand is overdefined.
873 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
874 LatticeVal *NonOverdefVal = nullptr;
875 if (!V1State.isOverdefined())
876 NonOverdefVal = &V1State;
877 else if (!V2State.isOverdefined())
878 NonOverdefVal = &V2State;
881 if (NonOverdefVal->isUndefined()) {
882 // Could annihilate value.
883 if (I.getOpcode() == Instruction::And)
884 markConstant(IV, &I, Constant::getNullValue(I.getType()));
885 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
886 markConstant(IV, &I, Constant::getAllOnesValue(PT));
889 Constant::getAllOnesValue(I.getType()));
893 if (I.getOpcode() == Instruction::And) {
895 if (NonOverdefVal->getConstant()->isNullValue())
896 return markConstant(IV, &I, NonOverdefVal->getConstant());
898 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
899 if (CI->isAllOnesValue()) // X or -1 = -1
900 return markConstant(IV, &I, NonOverdefVal->getConstant());
909 // Handle ICmpInst instruction.
910 void SCCPSolver::visitCmpInst(CmpInst &I) {
911 LatticeVal V1State = getValueState(I.getOperand(0));
912 LatticeVal V2State = getValueState(I.getOperand(1));
914 LatticeVal &IV = ValueState[&I];
915 if (IV.isOverdefined()) return;
917 if (V1State.isConstant() && V2State.isConstant())
918 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
919 V1State.getConstant(),
920 V2State.getConstant()));
922 // If operands are still undefined, wait for it to resolve.
923 if (!V1State.isOverdefined() && !V2State.isOverdefined())
929 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
930 // TODO : SCCP does not handle vectors properly.
931 return markOverdefined(&I);
934 LatticeVal &ValState = getValueState(I.getOperand(0));
935 LatticeVal &IdxState = getValueState(I.getOperand(1));
937 if (ValState.isOverdefined() || IdxState.isOverdefined())
939 else if(ValState.isConstant() && IdxState.isConstant())
940 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
941 IdxState.getConstant()));
945 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
946 // TODO : SCCP does not handle vectors properly.
947 return markOverdefined(&I);
949 LatticeVal &ValState = getValueState(I.getOperand(0));
950 LatticeVal &EltState = getValueState(I.getOperand(1));
951 LatticeVal &IdxState = getValueState(I.getOperand(2));
953 if (ValState.isOverdefined() || EltState.isOverdefined() ||
954 IdxState.isOverdefined())
956 else if(ValState.isConstant() && EltState.isConstant() &&
957 IdxState.isConstant())
958 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
959 EltState.getConstant(),
960 IdxState.getConstant()));
961 else if (ValState.isUndefined() && EltState.isConstant() &&
962 IdxState.isConstant())
963 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
964 EltState.getConstant(),
965 IdxState.getConstant()));
969 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
970 // TODO : SCCP does not handle vectors properly.
971 return markOverdefined(&I);
973 LatticeVal &V1State = getValueState(I.getOperand(0));
974 LatticeVal &V2State = getValueState(I.getOperand(1));
975 LatticeVal &MaskState = getValueState(I.getOperand(2));
977 if (MaskState.isUndefined() ||
978 (V1State.isUndefined() && V2State.isUndefined()))
979 return; // Undefined output if mask or both inputs undefined.
981 if (V1State.isOverdefined() || V2State.isOverdefined() ||
982 MaskState.isOverdefined()) {
985 // A mix of constant/undef inputs.
986 Constant *V1 = V1State.isConstant() ?
987 V1State.getConstant() : UndefValue::get(I.getType());
988 Constant *V2 = V2State.isConstant() ?
989 V2State.getConstant() : UndefValue::get(I.getType());
990 Constant *Mask = MaskState.isConstant() ?
991 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
992 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
997 // Handle getelementptr instructions. If all operands are constants then we
998 // can turn this into a getelementptr ConstantExpr.
1000 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1001 if (ValueState[&I].isOverdefined()) return;
1003 SmallVector<Constant*, 8> Operands;
1004 Operands.reserve(I.getNumOperands());
1006 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1007 LatticeVal State = getValueState(I.getOperand(i));
1008 if (State.isUndefined())
1009 return; // Operands are not resolved yet.
1011 if (State.isOverdefined())
1012 return markOverdefined(&I);
1014 assert(State.isConstant() && "Unknown state!");
1015 Operands.push_back(State.getConstant());
1018 Constant *Ptr = Operands[0];
1019 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1020 markConstant(&I, ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr,
1024 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1025 // If this store is of a struct, ignore it.
1026 if (SI.getOperand(0)->getType()->isStructTy())
1029 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1032 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1033 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1034 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1036 // Get the value we are storing into the global, then merge it.
1037 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1038 if (I->second.isOverdefined())
1039 TrackedGlobals.erase(I); // No need to keep tracking this!
1043 // Handle load instructions. If the operand is a constant pointer to a constant
1044 // global, we can replace the load with the loaded constant value!
1045 void SCCPSolver::visitLoadInst(LoadInst &I) {
1046 // If this load is of a struct, just mark the result overdefined.
1047 if (I.getType()->isStructTy())
1048 return markAnythingOverdefined(&I);
1050 LatticeVal PtrVal = getValueState(I.getOperand(0));
1051 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1053 LatticeVal &IV = ValueState[&I];
1054 if (IV.isOverdefined()) return;
1056 if (!PtrVal.isConstant() || I.isVolatile())
1057 return markOverdefined(IV, &I);
1059 Constant *Ptr = PtrVal.getConstant();
1061 // load null -> null
1062 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1063 return markConstant(IV, &I, UndefValue::get(I.getType()));
1065 // Transform load (constant global) into the value loaded.
1066 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1067 if (!TrackedGlobals.empty()) {
1068 // If we are tracking this global, merge in the known value for it.
1069 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1070 TrackedGlobals.find(GV);
1071 if (It != TrackedGlobals.end()) {
1072 mergeInValue(IV, &I, It->second);
1078 // Transform load from a constant into a constant if possible.
1079 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
1080 return markConstant(IV, &I, C);
1082 // Otherwise we cannot say for certain what value this load will produce.
1084 markOverdefined(IV, &I);
1087 void SCCPSolver::visitCallSite(CallSite CS) {
1088 Function *F = CS.getCalledFunction();
1089 Instruction *I = CS.getInstruction();
1091 // The common case is that we aren't tracking the callee, either because we
1092 // are not doing interprocedural analysis or the callee is indirect, or is
1093 // external. Handle these cases first.
1094 if (!F || F->isDeclaration()) {
1096 // Void return and not tracking callee, just bail.
1097 if (I->getType()->isVoidTy()) return;
1099 // Otherwise, if we have a single return value case, and if the function is
1100 // a declaration, maybe we can constant fold it.
1101 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1102 canConstantFoldCallTo(F)) {
1104 SmallVector<Constant*, 8> Operands;
1105 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1107 LatticeVal State = getValueState(*AI);
1109 if (State.isUndefined())
1110 return; // Operands are not resolved yet.
1111 if (State.isOverdefined())
1112 return markOverdefined(I);
1113 assert(State.isConstant() && "Unknown state!");
1114 Operands.push_back(State.getConstant());
1117 if (getValueState(I).isOverdefined())
1120 // If we can constant fold this, mark the result of the call as a
1122 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
1123 return markConstant(I, C);
1126 // Otherwise, we don't know anything about this call, mark it overdefined.
1127 return markAnythingOverdefined(I);
1130 // If this is a local function that doesn't have its address taken, mark its
1131 // entry block executable and merge in the actual arguments to the call into
1132 // the formal arguments of the function.
1133 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1134 MarkBlockExecutable(F->begin());
1136 // Propagate information from this call site into the callee.
1137 CallSite::arg_iterator CAI = CS.arg_begin();
1138 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1139 AI != E; ++AI, ++CAI) {
1140 // If this argument is byval, and if the function is not readonly, there
1141 // will be an implicit copy formed of the input aggregate.
1142 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1143 markOverdefined(AI);
1147 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1148 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1149 LatticeVal CallArg = getStructValueState(*CAI, i);
1150 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1153 mergeInValue(AI, getValueState(*CAI));
1158 // If this is a single/zero retval case, see if we're tracking the function.
1159 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1160 if (!MRVFunctionsTracked.count(F))
1161 goto CallOverdefined; // Not tracking this callee.
1163 // If we are tracking this callee, propagate the result of the function
1164 // into this call site.
1165 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1166 mergeInValue(getStructValueState(I, i), I,
1167 TrackedMultipleRetVals[std::make_pair(F, i)]);
1169 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1170 if (TFRVI == TrackedRetVals.end())
1171 goto CallOverdefined; // Not tracking this callee.
1173 // If so, propagate the return value of the callee into this call result.
1174 mergeInValue(I, TFRVI->second);
1178 void SCCPSolver::Solve() {
1179 // Process the work lists until they are empty!
1180 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1181 !OverdefinedInstWorkList.empty()) {
1182 // Process the overdefined instruction's work list first, which drives other
1183 // things to overdefined more quickly.
1184 while (!OverdefinedInstWorkList.empty()) {
1185 Value *I = OverdefinedInstWorkList.pop_back_val();
1187 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1189 // "I" got into the work list because it either made the transition from
1190 // bottom to constant, or to overdefined.
1192 // Anything on this worklist that is overdefined need not be visited
1193 // since all of its users will have already been marked as overdefined
1194 // Update all of the users of this instruction's value.
1196 for (User *U : I->users())
1197 if (Instruction *UI = dyn_cast<Instruction>(U))
1198 OperandChangedState(UI);
1201 // Process the instruction work list.
1202 while (!InstWorkList.empty()) {
1203 Value *I = InstWorkList.pop_back_val();
1205 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1207 // "I" got into the work list because it made the transition from undef to
1210 // Anything on this worklist that is overdefined need not be visited
1211 // since all of its users will have already been marked as overdefined.
1212 // Update all of the users of this instruction's value.
1214 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1215 for (User *U : I->users())
1216 if (Instruction *UI = dyn_cast<Instruction>(U))
1217 OperandChangedState(UI);
1220 // Process the basic block work list.
1221 while (!BBWorkList.empty()) {
1222 BasicBlock *BB = BBWorkList.back();
1223 BBWorkList.pop_back();
1225 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1227 // Notify all instructions in this basic block that they are newly
1234 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1235 /// that branches on undef values cannot reach any of their successors.
1236 /// However, this is not a safe assumption. After we solve dataflow, this
1237 /// method should be use to handle this. If this returns true, the solver
1238 /// should be rerun.
1240 /// This method handles this by finding an unresolved branch and marking it one
1241 /// of the edges from the block as being feasible, even though the condition
1242 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1243 /// CFG and only slightly pessimizes the analysis results (by marking one,
1244 /// potentially infeasible, edge feasible). This cannot usefully modify the
1245 /// constraints on the condition of the branch, as that would impact other users
1248 /// This scan also checks for values that use undefs, whose results are actually
1249 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1250 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1251 /// even if X isn't defined.
1252 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1253 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1254 if (!BBExecutable.count(BB))
1257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1258 // Look for instructions which produce undef values.
1259 if (I->getType()->isVoidTy()) continue;
1261 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
1262 // Only a few things that can be structs matter for undef.
1264 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1265 if (CallSite CS = CallSite(I))
1266 if (Function *F = CS.getCalledFunction())
1267 if (MRVFunctionsTracked.count(F))
1270 // extractvalue and insertvalue don't need to be marked; they are
1271 // tracked as precisely as their operands.
1272 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1275 // Send the results of everything else to overdefined. We could be
1276 // more precise than this but it isn't worth bothering.
1277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278 LatticeVal &LV = getStructValueState(I, i);
1279 if (LV.isUndefined())
1280 markOverdefined(LV, I);
1285 LatticeVal &LV = getValueState(I);
1286 if (!LV.isUndefined()) continue;
1288 // extractvalue is safe; check here because the argument is a struct.
1289 if (isa<ExtractValueInst>(I))
1292 // Compute the operand LatticeVals, for convenience below.
1293 // Anything taking a struct is conservatively assumed to require
1294 // overdefined markings.
1295 if (I->getOperand(0)->getType()->isStructTy()) {
1299 LatticeVal Op0LV = getValueState(I->getOperand(0));
1301 if (I->getNumOperands() == 2) {
1302 if (I->getOperand(1)->getType()->isStructTy()) {
1307 Op1LV = getValueState(I->getOperand(1));
1309 // If this is an instructions whose result is defined even if the input is
1310 // not fully defined, propagate the information.
1311 Type *ITy = I->getType();
1312 switch (I->getOpcode()) {
1313 case Instruction::Add:
1314 case Instruction::Sub:
1315 case Instruction::Trunc:
1316 case Instruction::FPTrunc:
1317 case Instruction::BitCast:
1318 break; // Any undef -> undef
1319 case Instruction::FSub:
1320 case Instruction::FAdd:
1321 case Instruction::FMul:
1322 case Instruction::FDiv:
1323 case Instruction::FRem:
1324 // Floating-point binary operation: be conservative.
1325 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1326 markForcedConstant(I, Constant::getNullValue(ITy));
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPToUI:
1333 case Instruction::FPToSI:
1334 case Instruction::FPExt:
1335 case Instruction::PtrToInt:
1336 case Instruction::IntToPtr:
1337 case Instruction::SIToFP:
1338 case Instruction::UIToFP:
1339 // undef -> 0; some outputs are impossible
1340 markForcedConstant(I, Constant::getNullValue(ITy));
1342 case Instruction::Mul:
1343 case Instruction::And:
1344 // Both operands undef -> undef
1345 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1347 // undef * X -> 0. X could be zero.
1348 // undef & X -> 0. X could be zero.
1349 markForcedConstant(I, Constant::getNullValue(ITy));
1352 case Instruction::Or:
1353 // Both operands undef -> undef
1354 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1356 // undef | X -> -1. X could be -1.
1357 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1360 case Instruction::Xor:
1361 // undef ^ undef -> 0; strictly speaking, this is not strictly
1362 // necessary, but we try to be nice to people who expect this
1363 // behavior in simple cases
1364 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1365 markForcedConstant(I, Constant::getNullValue(ITy));
1368 // undef ^ X -> undef
1371 case Instruction::SDiv:
1372 case Instruction::UDiv:
1373 case Instruction::SRem:
1374 case Instruction::URem:
1375 // X / undef -> undef. No change.
1376 // X % undef -> undef. No change.
1377 if (Op1LV.isUndefined()) break;
1379 // undef / X -> 0. X could be maxint.
1380 // undef % X -> 0. X could be 1.
1381 markForcedConstant(I, Constant::getNullValue(ITy));
1384 case Instruction::AShr:
1385 // X >>a undef -> undef.
1386 if (Op1LV.isUndefined()) break;
1388 // undef >>a X -> all ones
1389 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1391 case Instruction::LShr:
1392 case Instruction::Shl:
1393 // X << undef -> undef.
1394 // X >> undef -> undef.
1395 if (Op1LV.isUndefined()) break;
1399 markForcedConstant(I, Constant::getNullValue(ITy));
1401 case Instruction::Select:
1402 Op1LV = getValueState(I->getOperand(1));
1403 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1404 if (Op0LV.isUndefined()) {
1405 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1406 Op1LV = getValueState(I->getOperand(2));
1407 } else if (Op1LV.isUndefined()) {
1408 // c ? undef : undef -> undef. No change.
1409 Op1LV = getValueState(I->getOperand(2));
1410 if (Op1LV.isUndefined())
1412 // Otherwise, c ? undef : x -> x.
1414 // Leave Op1LV as Operand(1)'s LatticeValue.
1417 if (Op1LV.isConstant())
1418 markForcedConstant(I, Op1LV.getConstant());
1422 case Instruction::Load:
1423 // A load here means one of two things: a load of undef from a global,
1424 // a load from an unknown pointer. Either way, having it return undef
1427 case Instruction::ICmp:
1428 // X == undef -> undef. Other comparisons get more complicated.
1429 if (cast<ICmpInst>(I)->isEquality())
1433 case Instruction::Call:
1434 case Instruction::Invoke: {
1435 // There are two reasons a call can have an undef result
1436 // 1. It could be tracked.
1437 // 2. It could be constant-foldable.
1438 // Because of the way we solve return values, tracked calls must
1439 // never be marked overdefined in ResolvedUndefsIn.
1440 if (Function *F = CallSite(I).getCalledFunction())
1441 if (TrackedRetVals.count(F))
1444 // If the call is constant-foldable, we mark it overdefined because
1445 // we do not know what return values are valid.
1450 // If we don't know what should happen here, conservatively mark it
1457 // Check to see if we have a branch or switch on an undefined value. If so
1458 // we force the branch to go one way or the other to make the successor
1459 // values live. It doesn't really matter which way we force it.
1460 TerminatorInst *TI = BB->getTerminator();
1461 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1462 if (!BI->isConditional()) continue;
1463 if (!getValueState(BI->getCondition()).isUndefined())
1466 // If the input to SCCP is actually branch on undef, fix the undef to
1468 if (isa<UndefValue>(BI->getCondition())) {
1469 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1470 markEdgeExecutable(BB, TI->getSuccessor(1));
1474 // Otherwise, it is a branch on a symbolic value which is currently
1475 // considered to be undef. Handle this by forcing the input value to the
1477 markForcedConstant(BI->getCondition(),
1478 ConstantInt::getFalse(TI->getContext()));
1482 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1483 if (!SI->getNumCases())
1485 if (!getValueState(SI->getCondition()).isUndefined())
1488 // If the input to SCCP is actually switch on undef, fix the undef to
1489 // the first constant.
1490 if (isa<UndefValue>(SI->getCondition())) {
1491 SI->setCondition(SI->case_begin().getCaseValue());
1492 markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
1496 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
1506 //===--------------------------------------------------------------------===//
1508 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1509 /// Sparse Conditional Constant Propagator.
1511 struct SCCP : public FunctionPass {
1512 void getAnalysisUsage(AnalysisUsage &AU) const override {
1513 AU.addRequired<TargetLibraryInfoWrapperPass>();
1515 static char ID; // Pass identification, replacement for typeid
1516 SCCP() : FunctionPass(ID) {
1517 initializeSCCPPass(*PassRegistry::getPassRegistry());
1520 // runOnFunction - Run the Sparse Conditional Constant Propagation
1521 // algorithm, and return true if the function was modified.
1523 bool runOnFunction(Function &F) override;
1525 } // end anonymous namespace
1528 INITIALIZE_PASS(SCCP, "sccp",
1529 "Sparse Conditional Constant Propagation", false, false)
1531 // createSCCPPass - This is the public interface to this file.
1532 FunctionPass *llvm::createSCCPPass() {
1536 static void DeleteInstructionInBlock(BasicBlock *BB) {
1537 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1540 // Check to see if there are non-terminating instructions to delete.
1541 if (isa<TerminatorInst>(BB->begin()))
1544 // Delete the instructions backwards, as it has a reduced likelihood of having
1545 // to update as many def-use and use-def chains.
1546 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1547 while (EndInst != BB->begin()) {
1548 // Delete the next to last instruction.
1549 BasicBlock::iterator I = EndInst;
1550 Instruction *Inst = --I;
1551 if (!Inst->use_empty())
1552 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1553 if (Inst->isEHPad()) {
1557 BB->getInstList().erase(Inst);
1562 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1563 // and return true if the function was modified.
1565 bool SCCP::runOnFunction(Function &F) {
1566 if (skipOptnoneFunction(F))
1569 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1570 const DataLayout &DL = F.getParent()->getDataLayout();
1571 const TargetLibraryInfo *TLI =
1572 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1573 SCCPSolver Solver(DL, TLI);
1575 // Mark the first block of the function as being executable.
1576 Solver.MarkBlockExecutable(F.begin());
1578 // Mark all arguments to the function as being overdefined.
1579 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1580 Solver.markAnythingOverdefined(AI);
1582 // Solve for constants.
1583 bool ResolvedUndefs = true;
1584 while (ResolvedUndefs) {
1586 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1587 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1590 bool MadeChanges = false;
1592 // If we decided that there are basic blocks that are dead in this function,
1593 // delete their contents now. Note that we cannot actually delete the blocks,
1594 // as we cannot modify the CFG of the function.
1596 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1597 if (!Solver.isBlockExecutable(BB)) {
1598 DeleteInstructionInBlock(BB);
1603 // Iterate over all of the instructions in a function, replacing them with
1604 // constants if we have found them to be of constant values.
1606 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1607 Instruction *Inst = BI++;
1608 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1611 // TODO: Reconstruct structs from their elements.
1612 if (Inst->getType()->isStructTy())
1615 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1616 if (IV.isOverdefined())
1619 Constant *Const = IV.isConstant()
1620 ? IV.getConstant() : UndefValue::get(Inst->getType());
1621 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
1623 // Replaces all of the uses of a variable with uses of the constant.
1624 Inst->replaceAllUsesWith(Const);
1626 // Delete the instruction.
1627 Inst->eraseFromParent();
1629 // Hey, we just changed something!
1639 //===--------------------------------------------------------------------===//
1641 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1642 /// Constant Propagation.
1644 struct IPSCCP : public ModulePass {
1645 void getAnalysisUsage(AnalysisUsage &AU) const override {
1646 AU.addRequired<TargetLibraryInfoWrapperPass>();
1649 IPSCCP() : ModulePass(ID) {
1650 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1652 bool runOnModule(Module &M) override;
1654 } // end anonymous namespace
1656 char IPSCCP::ID = 0;
1657 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1658 "Interprocedural Sparse Conditional Constant Propagation",
1660 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1661 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
1662 "Interprocedural Sparse Conditional Constant Propagation",
1665 // createIPSCCPPass - This is the public interface to this file.
1666 ModulePass *llvm::createIPSCCPPass() {
1667 return new IPSCCP();
1671 static bool AddressIsTaken(const GlobalValue *GV) {
1672 // Delete any dead constantexpr klingons.
1673 GV->removeDeadConstantUsers();
1675 for (const Use &U : GV->uses()) {
1676 const User *UR = U.getUser();
1677 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
1678 if (SI->getOperand(0) == GV || SI->isVolatile())
1679 return true; // Storing addr of GV.
1680 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1681 // Make sure we are calling the function, not passing the address.
1682 ImmutableCallSite CS(cast<Instruction>(UR));
1683 if (!CS.isCallee(&U))
1685 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
1686 if (LI->isVolatile())
1688 } else if (isa<BlockAddress>(UR)) {
1689 // blockaddress doesn't take the address of the function, it takes addr
1698 bool IPSCCP::runOnModule(Module &M) {
1699 const DataLayout &DL = M.getDataLayout();
1700 const TargetLibraryInfo *TLI =
1701 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1702 SCCPSolver Solver(DL, TLI);
1704 // AddressTakenFunctions - This set keeps track of the address-taken functions
1705 // that are in the input. As IPSCCP runs through and simplifies code,
1706 // functions that were address taken can end up losing their
1707 // address-taken-ness. Because of this, we keep track of their addresses from
1708 // the first pass so we can use them for the later simplification pass.
1709 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1711 // Loop over all functions, marking arguments to those with their addresses
1712 // taken or that are external as overdefined.
1714 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1715 if (F->isDeclaration())
1718 // If this is a strong or ODR definition of this function, then we can
1719 // propagate information about its result into callsites of it.
1720 if (!F->mayBeOverridden())
1721 Solver.AddTrackedFunction(F);
1723 // If this function only has direct calls that we can see, we can track its
1724 // arguments and return value aggressively, and can assume it is not called
1725 // unless we see evidence to the contrary.
1726 if (F->hasLocalLinkage()) {
1727 if (AddressIsTaken(F))
1728 AddressTakenFunctions.insert(F);
1730 Solver.AddArgumentTrackedFunction(F);
1735 // Assume the function is called.
1736 Solver.MarkBlockExecutable(F->begin());
1738 // Assume nothing about the incoming arguments.
1739 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1741 Solver.markAnythingOverdefined(AI);
1744 // Loop over global variables. We inform the solver about any internal global
1745 // variables that do not have their 'addresses taken'. If they don't have
1746 // their addresses taken, we can propagate constants through them.
1747 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1749 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1750 Solver.TrackValueOfGlobalVariable(G);
1752 // Solve for constants.
1753 bool ResolvedUndefs = true;
1754 while (ResolvedUndefs) {
1757 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1758 ResolvedUndefs = false;
1759 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1760 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1763 bool MadeChanges = false;
1765 // Iterate over all of the instructions in the module, replacing them with
1766 // constants if we have found them to be of constant values.
1768 SmallVector<BasicBlock*, 512> BlocksToErase;
1770 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1771 if (Solver.isBlockExecutable(F->begin())) {
1772 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1774 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1776 // TODO: Could use getStructLatticeValueFor to find out if the entire
1777 // result is a constant and replace it entirely if so.
1779 LatticeVal IV = Solver.getLatticeValueFor(AI);
1780 if (IV.isOverdefined()) continue;
1782 Constant *CST = IV.isConstant() ?
1783 IV.getConstant() : UndefValue::get(AI->getType());
1784 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1786 // Replaces all of the uses of a variable with uses of the
1788 AI->replaceAllUsesWith(CST);
1793 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1794 if (!Solver.isBlockExecutable(BB)) {
1795 DeleteInstructionInBlock(BB);
1798 TerminatorInst *TI = BB->getTerminator();
1799 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1800 BasicBlock *Succ = TI->getSuccessor(i);
1801 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1802 TI->getSuccessor(i)->removePredecessor(BB);
1804 if (!TI->use_empty())
1805 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1806 TI->eraseFromParent();
1807 new UnreachableInst(M.getContext(), BB);
1809 if (&*BB != &F->front())
1810 BlocksToErase.push_back(BB);
1814 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1815 Instruction *Inst = BI++;
1816 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1819 // TODO: Could use getStructLatticeValueFor to find out if the entire
1820 // result is a constant and replace it entirely if so.
1822 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1823 if (IV.isOverdefined())
1826 Constant *Const = IV.isConstant()
1827 ? IV.getConstant() : UndefValue::get(Inst->getType());
1828 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
1830 // Replaces all of the uses of a variable with uses of the
1832 Inst->replaceAllUsesWith(Const);
1834 // Delete the instruction.
1835 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1836 Inst->eraseFromParent();
1838 // Hey, we just changed something!
1844 // Now that all instructions in the function are constant folded, erase dead
1845 // blocks, because we can now use ConstantFoldTerminator to get rid of
1847 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1848 // If there are any PHI nodes in this successor, drop entries for BB now.
1849 BasicBlock *DeadBB = BlocksToErase[i];
1850 for (Value::user_iterator UI = DeadBB->user_begin(),
1851 UE = DeadBB->user_end();
1853 // Grab the user and then increment the iterator early, as the user
1854 // will be deleted. Step past all adjacent uses from the same user.
1855 Instruction *I = dyn_cast<Instruction>(*UI);
1856 do { ++UI; } while (UI != UE && *UI == I);
1858 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1861 bool Folded = ConstantFoldTerminator(I->getParent());
1863 // The constant folder may not have been able to fold the terminator
1864 // if this is a branch or switch on undef. Fold it manually as a
1865 // branch to the first successor.
1867 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1868 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1869 "Branch should be foldable!");
1870 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1871 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1873 llvm_unreachable("Didn't fold away reference to block!");
1877 // Make this an uncond branch to the first successor.
1878 TerminatorInst *TI = I->getParent()->getTerminator();
1879 BranchInst::Create(TI->getSuccessor(0), TI);
1881 // Remove entries in successor phi nodes to remove edges.
1882 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1883 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1885 // Remove the old terminator.
1886 TI->eraseFromParent();
1890 // Finally, delete the basic block.
1891 F->getBasicBlockList().erase(DeadBB);
1893 BlocksToErase.clear();
1896 // If we inferred constant or undef return values for a function, we replaced
1897 // all call uses with the inferred value. This means we don't need to bother
1898 // actually returning anything from the function. Replace all return
1899 // instructions with return undef.
1901 // Do this in two stages: first identify the functions we should process, then
1902 // actually zap their returns. This is important because we can only do this
1903 // if the address of the function isn't taken. In cases where a return is the
1904 // last use of a function, the order of processing functions would affect
1905 // whether other functions are optimizable.
1906 SmallVector<ReturnInst*, 8> ReturnsToZap;
1908 // TODO: Process multiple value ret instructions also.
1909 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1910 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1911 E = RV.end(); I != E; ++I) {
1912 Function *F = I->first;
1913 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1916 // We can only do this if we know that nothing else can call the function.
1917 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1920 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1921 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1922 if (!isa<UndefValue>(RI->getOperand(0)))
1923 ReturnsToZap.push_back(RI);
1926 // Zap all returns which we've identified as zap to change.
1927 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1928 Function *F = ReturnsToZap[i]->getParent()->getParent();
1929 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1932 // If we inferred constant or undef values for globals variables, we can
1933 // delete the global and any stores that remain to it.
1934 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1935 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1936 E = TG.end(); I != E; ++I) {
1937 GlobalVariable *GV = I->first;
1938 assert(!I->second.isOverdefined() &&
1939 "Overdefined values should have been taken out of the map!");
1940 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1941 while (!GV->use_empty()) {
1942 StoreInst *SI = cast<StoreInst>(GV->user_back());
1943 SI->eraseFromParent();
1945 M.getGlobalList().erase(GV);