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/GlobalsModRef.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/InstVisitor.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/Utils/Local.h"
45 #define DEBUG_TYPE "sccp"
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy. It is a simple class with value semantics.
60 /// undefined - This LLVM Value has no known value yet.
63 /// constant - This LLVM Value has a specific constant value.
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
72 /// overdefined - This instruction is not known to be constant, and we know
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
81 LatticeValueTy getLatticeValue() const {
86 LatticeVal() : Val(nullptr, undefined) {}
88 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
90 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 bool isOverdefined() const { return getLatticeValue() == overdefined; }
94 Constant *getConstant() const {
95 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
99 /// markOverdefined - Return true if this is a change in status.
100 bool markOverdefined() {
104 Val.setInt(overdefined);
108 /// markConstant - Return true if this is a change in status.
109 bool markConstant(Constant *V) {
110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
111 assert(getConstant() == V && "Marking constant with different value");
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
137 return dyn_cast<ConstantInt>(getConstant());
141 void markForcedConstant(Constant *V) {
142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
147 } // end anonymous namespace.
152 //===----------------------------------------------------------------------===//
154 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155 /// Constant Propagation.
157 class SCCPSolver : public InstVisitor<SCCPSolver> {
158 const DataLayout &DL;
159 const TargetLibraryInfo *TLI;
160 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
161 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
163 /// StructValueState - This maintains ValueState for values that have
164 /// StructType, for example for formal arguments, calls, insertelement, etc.
166 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
168 /// GlobalValue - If we are tracking any values for the contents of a global
169 /// variable, we keep a mapping from the constant accessor to the element of
170 /// the global, to the currently known value. If the value becomes
171 /// overdefined, it's entry is simply removed from this map.
172 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
174 /// TrackedRetVals - If we are tracking arguments into and the return
175 /// value out of a function, it will have an entry in this map, indicating
176 /// what the known return value for the function is.
177 DenseMap<Function*, LatticeVal> TrackedRetVals;
179 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
180 /// that return multiple values.
181 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
183 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
184 /// represented here for efficient lookup.
185 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
187 /// TrackingIncomingArguments - This is the set of functions for whose
188 /// arguments we make optimistic assumptions about and try to prove as
190 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
192 /// The reason for two worklists is that overdefined is the lowest state
193 /// on the lattice, and moving things to overdefined as fast as possible
194 /// makes SCCP converge much faster.
196 /// By having a separate worklist, we accomplish this because everything
197 /// possibly overdefined will become overdefined at the soonest possible
199 SmallVector<Value*, 64> OverdefinedInstWorkList;
200 SmallVector<Value*, 64> InstWorkList;
203 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
205 /// KnownFeasibleEdges - Entries in this set are edges which have already had
206 /// PHI nodes retriggered.
207 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
208 DenseSet<Edge> KnownFeasibleEdges;
210 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
211 : DL(DL), TLI(tli) {}
213 /// MarkBlockExecutable - This method can be used by clients to mark all of
214 /// the blocks that are known to be intrinsically live in the processed unit.
216 /// This returns true if the block was not considered live before.
217 bool MarkBlockExecutable(BasicBlock *BB) {
218 if (!BBExecutable.insert(BB).second)
220 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
221 BBWorkList.push_back(BB); // Add the block to the work list!
225 /// TrackValueOfGlobalVariable - Clients can use this method to
226 /// inform the SCCPSolver that it should track loads and stores to the
227 /// specified global variable if it can. This is only legal to call if
228 /// performing Interprocedural SCCP.
229 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
230 // We only track the contents of scalar globals.
231 if (GV->getType()->getElementType()->isSingleValueType()) {
232 LatticeVal &IV = TrackedGlobals[GV];
233 if (!isa<UndefValue>(GV->getInitializer()))
234 IV.markConstant(GV->getInitializer());
238 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
239 /// and out of the specified function (which cannot have its address taken),
240 /// this method must be called.
241 void AddTrackedFunction(Function *F) {
242 // Add an entry, F -> undef.
243 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
244 MRVFunctionsTracked.insert(F);
245 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
246 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
249 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
252 void AddArgumentTrackedFunction(Function *F) {
253 TrackingIncomingArguments.insert(F);
256 /// Solve - Solve for constants and executable blocks.
260 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
261 /// that branches on undef values cannot reach any of their successors.
262 /// However, this is not a safe assumption. After we solve dataflow, this
263 /// method should be use to handle this. If this returns true, the solver
265 bool ResolvedUndefsIn(Function &F);
267 bool isBlockExecutable(BasicBlock *BB) const {
268 return BBExecutable.count(BB);
271 LatticeVal getLatticeValueFor(Value *V) const {
272 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
273 assert(I != ValueState.end() && "V is not in valuemap!");
277 /// getTrackedRetVals - Get the inferred return value map.
279 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
280 return TrackedRetVals;
283 /// getTrackedGlobals - Get and return the set of inferred initializers for
284 /// global variables.
285 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
286 return TrackedGlobals;
289 void markOverdefined(Value *V) {
290 assert(!V->getType()->isStructTy() && "Should use other method");
291 markOverdefined(ValueState[V], V);
294 /// markAnythingOverdefined - Mark the specified value overdefined. This
295 /// works with both scalars and structs.
296 void markAnythingOverdefined(Value *V) {
297 if (StructType *STy = dyn_cast<StructType>(V->getType()))
298 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
299 markOverdefined(getStructValueState(V, i), V);
305 // markConstant - Make a value be marked as "constant". If the value
306 // is not already a constant, add it to the instruction work list so that
307 // the users of the instruction are updated later.
309 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
310 if (!IV.markConstant(C)) return;
311 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
312 if (IV.isOverdefined())
313 OverdefinedInstWorkList.push_back(V);
315 InstWorkList.push_back(V);
318 void markConstant(Value *V, Constant *C) {
319 assert(!V->getType()->isStructTy() && "Should use other method");
320 markConstant(ValueState[V], V, C);
323 void markForcedConstant(Value *V, Constant *C) {
324 assert(!V->getType()->isStructTy() && "Should use other method");
325 LatticeVal &IV = ValueState[V];
326 IV.markForcedConstant(C);
327 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
328 if (IV.isOverdefined())
329 OverdefinedInstWorkList.push_back(V);
331 InstWorkList.push_back(V);
335 // markOverdefined - Make a value be marked as "overdefined". If the
336 // value is not already overdefined, add it to the overdefined instruction
337 // work list so that the users of the instruction are updated later.
338 void markOverdefined(LatticeVal &IV, Value *V) {
339 if (!IV.markOverdefined()) return;
341 DEBUG(dbgs() << "markOverdefined: ";
342 if (Function *F = dyn_cast<Function>(V))
343 dbgs() << "Function '" << F->getName() << "'\n";
345 dbgs() << *V << '\n');
346 // Only instructions go on the work list
347 OverdefinedInstWorkList.push_back(V);
350 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
351 if (IV.isOverdefined() || MergeWithV.isUndefined())
353 if (MergeWithV.isOverdefined())
354 markOverdefined(IV, V);
355 else if (IV.isUndefined())
356 markConstant(IV, V, MergeWithV.getConstant());
357 else if (IV.getConstant() != MergeWithV.getConstant())
358 markOverdefined(IV, V);
361 void mergeInValue(Value *V, LatticeVal MergeWithV) {
362 assert(!V->getType()->isStructTy() && "Should use other method");
363 mergeInValue(ValueState[V], V, MergeWithV);
367 /// getValueState - Return the LatticeVal object that corresponds to the
368 /// value. This function handles the case when the value hasn't been seen yet
369 /// by properly seeding constants etc.
370 LatticeVal &getValueState(Value *V) {
371 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
373 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
374 ValueState.insert(std::make_pair(V, LatticeVal()));
375 LatticeVal &LV = I.first->second;
378 return LV; // Common case, already in the map.
380 if (Constant *C = dyn_cast<Constant>(V)) {
381 // Undef values remain undefined.
382 if (!isa<UndefValue>(V))
383 LV.markConstant(C); // Constants are constant
386 // All others are underdefined by default.
390 /// getStructValueState - Return the LatticeVal object that corresponds to the
391 /// value/field pair. This function handles the case when the value hasn't
392 /// been seen yet by properly seeding constants etc.
393 LatticeVal &getStructValueState(Value *V, unsigned i) {
394 assert(V->getType()->isStructTy() && "Should use getValueState");
395 assert(i < cast<StructType>(V->getType())->getNumElements() &&
396 "Invalid element #");
398 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
399 bool> I = StructValueState.insert(
400 std::make_pair(std::make_pair(V, i), LatticeVal()));
401 LatticeVal &LV = I.first->second;
404 return LV; // Common case, already in the map.
406 if (Constant *C = dyn_cast<Constant>(V)) {
407 Constant *Elt = C->getAggregateElement(i);
410 LV.markOverdefined(); // Unknown sort of constant.
411 else if (isa<UndefValue>(Elt))
412 ; // Undef values remain undefined.
414 LV.markConstant(Elt); // Constants are constant.
417 // All others are underdefined by default.
422 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
423 /// work list if it is not already executable.
424 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
425 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
426 return; // This edge is already known to be executable!
428 if (!MarkBlockExecutable(Dest)) {
429 // If the destination is already executable, we just made an *edge*
430 // feasible that wasn't before. Revisit the PHI nodes in the block
431 // because they have potentially new operands.
432 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
433 << " -> " << Dest->getName() << '\n');
436 for (BasicBlock::iterator I = Dest->begin();
437 (PN = dyn_cast<PHINode>(I)); ++I)
442 // getFeasibleSuccessors - Return a vector of booleans to indicate which
443 // successors are reachable from a given terminator instruction.
445 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
447 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
448 // block to the 'To' basic block is currently feasible.
450 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
452 // OperandChangedState - This method is invoked on all of the users of an
453 // instruction that was just changed state somehow. Based on this
454 // information, we need to update the specified user of this instruction.
456 void OperandChangedState(Instruction *I) {
457 if (BBExecutable.count(I->getParent())) // Inst is executable?
462 friend class InstVisitor<SCCPSolver>;
464 // visit implementations - Something changed in this instruction. Either an
465 // operand made a transition, or the instruction is newly executable. Change
466 // the value type of I to reflect these changes if appropriate.
467 void visitPHINode(PHINode &I);
470 void visitReturnInst(ReturnInst &I);
471 void visitTerminatorInst(TerminatorInst &TI);
473 void visitCastInst(CastInst &I);
474 void visitSelectInst(SelectInst &I);
475 void visitBinaryOperator(Instruction &I);
476 void visitCmpInst(CmpInst &I);
477 void visitExtractElementInst(ExtractElementInst &I);
478 void visitInsertElementInst(InsertElementInst &I);
479 void visitShuffleVectorInst(ShuffleVectorInst &I);
480 void visitExtractValueInst(ExtractValueInst &EVI);
481 void visitInsertValueInst(InsertValueInst &IVI);
482 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
483 void visitFuncletPadInst(FuncletPadInst &FPI) {
484 markAnythingOverdefined(&FPI);
486 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
487 markAnythingOverdefined(&CPI);
488 visitTerminatorInst(CPI);
491 // Instructions that cannot be folded away.
492 void visitStoreInst (StoreInst &I);
493 void visitLoadInst (LoadInst &I);
494 void visitGetElementPtrInst(GetElementPtrInst &I);
495 void visitCallInst (CallInst &I) {
498 void visitInvokeInst (InvokeInst &II) {
500 visitTerminatorInst(II);
502 void visitCallSite (CallSite CS);
503 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
504 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
505 void visitFenceInst (FenceInst &I) { /*returns void*/ }
506 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
507 markAnythingOverdefined(&I);
509 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
510 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
511 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
513 void visitInstruction(Instruction &I) {
514 // If a new instruction is added to LLVM that we don't handle.
515 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
516 markAnythingOverdefined(&I); // Just in case
520 } // end anonymous namespace
523 // getFeasibleSuccessors - Return a vector of booleans to indicate which
524 // successors are reachable from a given terminator instruction.
526 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
527 SmallVectorImpl<bool> &Succs) {
528 Succs.resize(TI.getNumSuccessors());
529 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
530 if (BI->isUnconditional()) {
535 LatticeVal BCValue = getValueState(BI->getCondition());
536 ConstantInt *CI = BCValue.getConstantInt();
538 // Overdefined condition variables, and branches on unfoldable constant
539 // conditions, mean the branch could go either way.
540 if (!BCValue.isUndefined())
541 Succs[0] = Succs[1] = true;
545 // Constant condition variables mean the branch can only go a single way.
546 Succs[CI->isZero()] = true;
550 // Unwinding instructions successors are always executable.
551 if (TI.isExceptional()) {
552 Succs.assign(TI.getNumSuccessors(), true);
556 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
557 if (!SI->getNumCases()) {
561 LatticeVal SCValue = getValueState(SI->getCondition());
562 ConstantInt *CI = SCValue.getConstantInt();
564 if (!CI) { // Overdefined or undefined condition?
565 // All destinations are executable!
566 if (!SCValue.isUndefined())
567 Succs.assign(TI.getNumSuccessors(), true);
571 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
575 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
576 if (isa<IndirectBrInst>(&TI)) {
577 // Just mark all destinations executable!
578 Succs.assign(TI.getNumSuccessors(), true);
583 dbgs() << "Unknown terminator instruction: " << TI << '\n';
585 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
589 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
590 // block to the 'To' basic block is currently feasible.
592 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
593 assert(BBExecutable.count(To) && "Dest should always be alive!");
595 // Make sure the source basic block is executable!!
596 if (!BBExecutable.count(From)) return false;
598 // Check to make sure this edge itself is actually feasible now.
599 TerminatorInst *TI = From->getTerminator();
600 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
601 if (BI->isUnconditional())
604 LatticeVal BCValue = getValueState(BI->getCondition());
606 // Overdefined condition variables mean the branch could go either way,
607 // undef conditions mean that neither edge is feasible yet.
608 ConstantInt *CI = BCValue.getConstantInt();
610 return !BCValue.isUndefined();
612 // Constant condition variables mean the branch can only go a single way.
613 return BI->getSuccessor(CI->isZero()) == To;
616 // Unwinding instructions successors are always executable.
617 if (TI->isExceptional())
620 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
621 if (SI->getNumCases() < 1)
624 LatticeVal SCValue = getValueState(SI->getCondition());
625 ConstantInt *CI = SCValue.getConstantInt();
628 return !SCValue.isUndefined();
630 return SI->findCaseValue(CI).getCaseSuccessor() == To;
633 // Just mark all destinations executable!
634 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
635 if (isa<IndirectBrInst>(TI))
639 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
641 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
644 // visit Implementations - Something changed in this instruction, either an
645 // operand made a transition, or the instruction is newly executable. Change
646 // the value type of I to reflect these changes if appropriate. This method
647 // makes sure to do the following actions:
649 // 1. If a phi node merges two constants in, and has conflicting value coming
650 // from different branches, or if the PHI node merges in an overdefined
651 // value, then the PHI node becomes overdefined.
652 // 2. If a phi node merges only constants in, and they all agree on value, the
653 // PHI node becomes a constant value equal to that.
654 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
655 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
656 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
657 // 6. If a conditional branch has a value that is constant, make the selected
658 // destination executable
659 // 7. If a conditional branch has a value that is overdefined, make all
660 // successors executable.
662 void SCCPSolver::visitPHINode(PHINode &PN) {
663 // If this PN returns a struct, just mark the result overdefined.
664 // TODO: We could do a lot better than this if code actually uses this.
665 if (PN.getType()->isStructTy())
666 return markAnythingOverdefined(&PN);
668 if (getValueState(&PN).isOverdefined())
669 return; // Quick exit
671 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
672 // and slow us down a lot. Just mark them overdefined.
673 if (PN.getNumIncomingValues() > 64)
674 return markOverdefined(&PN);
676 // Look at all of the executable operands of the PHI node. If any of them
677 // are overdefined, the PHI becomes overdefined as well. If they are all
678 // constant, and they agree with each other, the PHI becomes the identical
679 // constant. If they are constant and don't agree, the PHI is overdefined.
680 // If there are no executable operands, the PHI remains undefined.
682 Constant *OperandVal = nullptr;
683 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
684 LatticeVal IV = getValueState(PN.getIncomingValue(i));
685 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
687 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
690 if (IV.isOverdefined()) // PHI node becomes overdefined!
691 return markOverdefined(&PN);
693 if (!OperandVal) { // Grab the first value.
694 OperandVal = IV.getConstant();
698 // There is already a reachable operand. If we conflict with it,
699 // then the PHI node becomes overdefined. If we agree with it, we
702 // Check to see if there are two different constants merging, if so, the PHI
703 // node is overdefined.
704 if (IV.getConstant() != OperandVal)
705 return markOverdefined(&PN);
708 // If we exited the loop, this means that the PHI node only has constant
709 // arguments that agree with each other(and OperandVal is the constant) or
710 // OperandVal is null because there are no defined incoming arguments. If
711 // this is the case, the PHI remains undefined.
714 markConstant(&PN, OperandVal); // Acquire operand value
717 void SCCPSolver::visitReturnInst(ReturnInst &I) {
718 if (I.getNumOperands() == 0) return; // ret void
720 Function *F = I.getParent()->getParent();
721 Value *ResultOp = I.getOperand(0);
723 // If we are tracking the return value of this function, merge it in.
724 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
725 DenseMap<Function*, LatticeVal>::iterator TFRVI =
726 TrackedRetVals.find(F);
727 if (TFRVI != TrackedRetVals.end()) {
728 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
733 // Handle functions that return multiple values.
734 if (!TrackedMultipleRetVals.empty()) {
735 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
736 if (MRVFunctionsTracked.count(F))
737 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
738 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
739 getStructValueState(ResultOp, i));
744 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
745 SmallVector<bool, 16> SuccFeasible;
746 getFeasibleSuccessors(TI, SuccFeasible);
748 BasicBlock *BB = TI.getParent();
750 // Mark all feasible successors executable.
751 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
753 markEdgeExecutable(BB, TI.getSuccessor(i));
756 void SCCPSolver::visitCastInst(CastInst &I) {
757 LatticeVal OpSt = getValueState(I.getOperand(0));
758 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
760 else if (OpSt.isConstant()) {
762 ConstantExpr::getCast(I.getOpcode(), OpSt.getConstant(), I.getType());
763 if (isa<UndefValue>(C))
765 // Propagate constant value
771 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
772 // If this returns a struct, mark all elements over defined, we don't track
773 // structs in structs.
774 if (EVI.getType()->isStructTy())
775 return markAnythingOverdefined(&EVI);
777 // If this is extracting from more than one level of struct, we don't know.
778 if (EVI.getNumIndices() != 1)
779 return markOverdefined(&EVI);
781 Value *AggVal = EVI.getAggregateOperand();
782 if (AggVal->getType()->isStructTy()) {
783 unsigned i = *EVI.idx_begin();
784 LatticeVal EltVal = getStructValueState(AggVal, i);
785 mergeInValue(getValueState(&EVI), &EVI, EltVal);
787 // Otherwise, must be extracting from an array.
788 return markOverdefined(&EVI);
792 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
793 StructType *STy = dyn_cast<StructType>(IVI.getType());
795 return markOverdefined(&IVI);
797 // If this has more than one index, we can't handle it, drive all results to
799 if (IVI.getNumIndices() != 1)
800 return markAnythingOverdefined(&IVI);
802 Value *Aggr = IVI.getAggregateOperand();
803 unsigned Idx = *IVI.idx_begin();
805 // Compute the result based on what we're inserting.
806 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
807 // This passes through all values that aren't the inserted element.
809 LatticeVal EltVal = getStructValueState(Aggr, i);
810 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
814 Value *Val = IVI.getInsertedValueOperand();
815 if (Val->getType()->isStructTy())
816 // We don't track structs in structs.
817 markOverdefined(getStructValueState(&IVI, i), &IVI);
819 LatticeVal InVal = getValueState(Val);
820 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
825 void SCCPSolver::visitSelectInst(SelectInst &I) {
826 // If this select returns a struct, just mark the result overdefined.
827 // TODO: We could do a lot better than this if code actually uses this.
828 if (I.getType()->isStructTy())
829 return markAnythingOverdefined(&I);
831 LatticeVal CondValue = getValueState(I.getCondition());
832 if (CondValue.isUndefined())
835 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
836 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
837 mergeInValue(&I, getValueState(OpVal));
841 // Otherwise, the condition is overdefined or a constant we can't evaluate.
842 // See if we can produce something better than overdefined based on the T/F
844 LatticeVal TVal = getValueState(I.getTrueValue());
845 LatticeVal FVal = getValueState(I.getFalseValue());
847 // select ?, C, C -> C.
848 if (TVal.isConstant() && FVal.isConstant() &&
849 TVal.getConstant() == FVal.getConstant())
850 return markConstant(&I, FVal.getConstant());
852 if (TVal.isUndefined()) // select ?, undef, X -> X.
853 return mergeInValue(&I, FVal);
854 if (FVal.isUndefined()) // select ?, X, undef -> X.
855 return mergeInValue(&I, TVal);
859 // Handle Binary Operators.
860 void SCCPSolver::visitBinaryOperator(Instruction &I) {
861 LatticeVal V1State = getValueState(I.getOperand(0));
862 LatticeVal V2State = getValueState(I.getOperand(1));
864 LatticeVal &IV = ValueState[&I];
865 if (IV.isOverdefined()) return;
867 if (V1State.isConstant() && V2State.isConstant()) {
868 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
869 V2State.getConstant());
871 if (isa<UndefValue>(C))
873 return markConstant(IV, &I, C);
876 // If something is undef, wait for it to resolve.
877 if (!V1State.isOverdefined() && !V2State.isOverdefined())
880 // Otherwise, one of our operands is overdefined. Try to produce something
881 // better than overdefined with some tricks.
883 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
884 // operand is overdefined.
885 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
886 LatticeVal *NonOverdefVal = nullptr;
887 if (!V1State.isOverdefined())
888 NonOverdefVal = &V1State;
889 else if (!V2State.isOverdefined())
890 NonOverdefVal = &V2State;
893 if (NonOverdefVal->isUndefined()) {
894 // Could annihilate value.
895 if (I.getOpcode() == Instruction::And)
896 markConstant(IV, &I, Constant::getNullValue(I.getType()));
897 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
898 markConstant(IV, &I, Constant::getAllOnesValue(PT));
901 Constant::getAllOnesValue(I.getType()));
905 if (I.getOpcode() == Instruction::And) {
907 if (NonOverdefVal->getConstant()->isNullValue())
908 return markConstant(IV, &I, NonOverdefVal->getConstant());
910 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
911 if (CI->isAllOnesValue()) // X or -1 = -1
912 return markConstant(IV, &I, NonOverdefVal->getConstant());
921 // Handle ICmpInst instruction.
922 void SCCPSolver::visitCmpInst(CmpInst &I) {
923 LatticeVal V1State = getValueState(I.getOperand(0));
924 LatticeVal V2State = getValueState(I.getOperand(1));
926 LatticeVal &IV = ValueState[&I];
927 if (IV.isOverdefined()) return;
929 if (V1State.isConstant() && V2State.isConstant()) {
930 Constant *C = ConstantExpr::getCompare(
931 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
932 if (isa<UndefValue>(C))
934 return markConstant(IV, &I, C);
937 // If operands are still undefined, wait for it to resolve.
938 if (!V1State.isOverdefined() && !V2State.isOverdefined())
944 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
945 // TODO : SCCP does not handle vectors properly.
946 return markOverdefined(&I);
949 LatticeVal &ValState = getValueState(I.getOperand(0));
950 LatticeVal &IdxState = getValueState(I.getOperand(1));
952 if (ValState.isOverdefined() || IdxState.isOverdefined())
954 else if(ValState.isConstant() && IdxState.isConstant())
955 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
956 IdxState.getConstant()));
960 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
961 // TODO : SCCP does not handle vectors properly.
962 return markOverdefined(&I);
964 LatticeVal &ValState = getValueState(I.getOperand(0));
965 LatticeVal &EltState = getValueState(I.getOperand(1));
966 LatticeVal &IdxState = getValueState(I.getOperand(2));
968 if (ValState.isOverdefined() || EltState.isOverdefined() ||
969 IdxState.isOverdefined())
971 else if(ValState.isConstant() && EltState.isConstant() &&
972 IdxState.isConstant())
973 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
974 EltState.getConstant(),
975 IdxState.getConstant()));
976 else if (ValState.isUndefined() && EltState.isConstant() &&
977 IdxState.isConstant())
978 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
979 EltState.getConstant(),
980 IdxState.getConstant()));
984 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
985 // TODO : SCCP does not handle vectors properly.
986 return markOverdefined(&I);
988 LatticeVal &V1State = getValueState(I.getOperand(0));
989 LatticeVal &V2State = getValueState(I.getOperand(1));
990 LatticeVal &MaskState = getValueState(I.getOperand(2));
992 if (MaskState.isUndefined() ||
993 (V1State.isUndefined() && V2State.isUndefined()))
994 return; // Undefined output if mask or both inputs undefined.
996 if (V1State.isOverdefined() || V2State.isOverdefined() ||
997 MaskState.isOverdefined()) {
1000 // A mix of constant/undef inputs.
1001 Constant *V1 = V1State.isConstant() ?
1002 V1State.getConstant() : UndefValue::get(I.getType());
1003 Constant *V2 = V2State.isConstant() ?
1004 V2State.getConstant() : UndefValue::get(I.getType());
1005 Constant *Mask = MaskState.isConstant() ?
1006 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1007 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1012 // Handle getelementptr instructions. If all operands are constants then we
1013 // can turn this into a getelementptr ConstantExpr.
1015 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1016 if (ValueState[&I].isOverdefined()) return;
1018 SmallVector<Constant*, 8> Operands;
1019 Operands.reserve(I.getNumOperands());
1021 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1022 LatticeVal State = getValueState(I.getOperand(i));
1023 if (State.isUndefined())
1024 return; // Operands are not resolved yet.
1026 if (State.isOverdefined())
1027 return markOverdefined(&I);
1029 assert(State.isConstant() && "Unknown state!");
1030 Operands.push_back(State.getConstant());
1033 Constant *Ptr = Operands[0];
1034 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1036 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1037 if (isa<UndefValue>(C))
1039 markConstant(&I, C);
1042 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1043 // If this store is of a struct, ignore it.
1044 if (SI.getOperand(0)->getType()->isStructTy())
1047 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1050 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1051 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1052 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1054 // Get the value we are storing into the global, then merge it.
1055 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1056 if (I->second.isOverdefined())
1057 TrackedGlobals.erase(I); // No need to keep tracking this!
1061 // Handle load instructions. If the operand is a constant pointer to a constant
1062 // global, we can replace the load with the loaded constant value!
1063 void SCCPSolver::visitLoadInst(LoadInst &I) {
1064 // If this load is of a struct, just mark the result overdefined.
1065 if (I.getType()->isStructTy())
1066 return markAnythingOverdefined(&I);
1068 LatticeVal PtrVal = getValueState(I.getOperand(0));
1069 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1071 LatticeVal &IV = ValueState[&I];
1072 if (IV.isOverdefined()) return;
1074 if (!PtrVal.isConstant() || I.isVolatile())
1075 return markOverdefined(IV, &I);
1077 Constant *Ptr = PtrVal.getConstant();
1079 // load null is undefined.
1080 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1083 // Transform load (constant global) into the value loaded.
1084 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1085 if (!TrackedGlobals.empty()) {
1086 // If we are tracking this global, merge in the known value for it.
1087 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1088 TrackedGlobals.find(GV);
1089 if (It != TrackedGlobals.end()) {
1090 mergeInValue(IV, &I, It->second);
1096 // Transform load from a constant into a constant if possible.
1097 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL)) {
1098 if (isa<UndefValue>(C))
1100 return markConstant(IV, &I, C);
1103 // Otherwise we cannot say for certain what value this load will produce.
1105 markOverdefined(IV, &I);
1108 void SCCPSolver::visitCallSite(CallSite CS) {
1109 Function *F = CS.getCalledFunction();
1110 Instruction *I = CS.getInstruction();
1112 // The common case is that we aren't tracking the callee, either because we
1113 // are not doing interprocedural analysis or the callee is indirect, or is
1114 // external. Handle these cases first.
1115 if (!F || F->isDeclaration()) {
1117 // Void return and not tracking callee, just bail.
1118 if (I->getType()->isVoidTy()) return;
1120 // Otherwise, if we have a single return value case, and if the function is
1121 // a declaration, maybe we can constant fold it.
1122 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1123 canConstantFoldCallTo(F)) {
1125 SmallVector<Constant*, 8> Operands;
1126 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1128 LatticeVal State = getValueState(*AI);
1130 if (State.isUndefined())
1131 return; // Operands are not resolved yet.
1132 if (State.isOverdefined())
1133 return markOverdefined(I);
1134 assert(State.isConstant() && "Unknown state!");
1135 Operands.push_back(State.getConstant());
1138 if (getValueState(I).isOverdefined())
1141 // If we can constant fold this, mark the result of the call as a
1143 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1145 if (isa<UndefValue>(C))
1147 return markConstant(I, C);
1151 // Otherwise, we don't know anything about this call, mark it overdefined.
1152 return markAnythingOverdefined(I);
1155 // If this is a local function that doesn't have its address taken, mark its
1156 // entry block executable and merge in the actual arguments to the call into
1157 // the formal arguments of the function.
1158 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1159 MarkBlockExecutable(&F->front());
1161 // Propagate information from this call site into the callee.
1162 CallSite::arg_iterator CAI = CS.arg_begin();
1163 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1164 AI != E; ++AI, ++CAI) {
1165 // If this argument is byval, and if the function is not readonly, there
1166 // will be an implicit copy formed of the input aggregate.
1167 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1168 markOverdefined(&*AI);
1172 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1173 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1174 LatticeVal CallArg = getStructValueState(*CAI, i);
1175 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1178 mergeInValue(&*AI, getValueState(*CAI));
1183 // If this is a single/zero retval case, see if we're tracking the function.
1184 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1185 if (!MRVFunctionsTracked.count(F))
1186 goto CallOverdefined; // Not tracking this callee.
1188 // If we are tracking this callee, propagate the result of the function
1189 // into this call site.
1190 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1191 mergeInValue(getStructValueState(I, i), I,
1192 TrackedMultipleRetVals[std::make_pair(F, i)]);
1194 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1195 if (TFRVI == TrackedRetVals.end())
1196 goto CallOverdefined; // Not tracking this callee.
1198 // If so, propagate the return value of the callee into this call result.
1199 mergeInValue(I, TFRVI->second);
1203 void SCCPSolver::Solve() {
1204 // Process the work lists until they are empty!
1205 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1206 !OverdefinedInstWorkList.empty()) {
1207 // Process the overdefined instruction's work list first, which drives other
1208 // things to overdefined more quickly.
1209 while (!OverdefinedInstWorkList.empty()) {
1210 Value *I = OverdefinedInstWorkList.pop_back_val();
1212 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1214 // "I" got into the work list because it either made the transition from
1215 // bottom to constant, or to overdefined.
1217 // Anything on this worklist that is overdefined need not be visited
1218 // since all of its users will have already been marked as overdefined
1219 // Update all of the users of this instruction's value.
1221 for (User *U : I->users())
1222 if (Instruction *UI = dyn_cast<Instruction>(U))
1223 OperandChangedState(UI);
1226 // Process the instruction work list.
1227 while (!InstWorkList.empty()) {
1228 Value *I = InstWorkList.pop_back_val();
1230 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1232 // "I" got into the work list because it made the transition from undef to
1235 // Anything on this worklist that is overdefined need not be visited
1236 // since all of its users will have already been marked as overdefined.
1237 // Update all of the users of this instruction's value.
1239 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1240 for (User *U : I->users())
1241 if (Instruction *UI = dyn_cast<Instruction>(U))
1242 OperandChangedState(UI);
1245 // Process the basic block work list.
1246 while (!BBWorkList.empty()) {
1247 BasicBlock *BB = BBWorkList.back();
1248 BBWorkList.pop_back();
1250 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1252 // Notify all instructions in this basic block that they are newly
1259 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1260 /// that branches on undef values cannot reach any of their successors.
1261 /// However, this is not a safe assumption. After we solve dataflow, this
1262 /// method should be use to handle this. If this returns true, the solver
1263 /// should be rerun.
1265 /// This method handles this by finding an unresolved branch and marking it one
1266 /// of the edges from the block as being feasible, even though the condition
1267 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1268 /// CFG and only slightly pessimizes the analysis results (by marking one,
1269 /// potentially infeasible, edge feasible). This cannot usefully modify the
1270 /// constraints on the condition of the branch, as that would impact other users
1273 /// This scan also checks for values that use undefs, whose results are actually
1274 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1275 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1276 /// even if X isn't defined.
1277 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1278 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1279 if (!BBExecutable.count(&*BB))
1282 for (Instruction &I : *BB) {
1283 // Look for instructions which produce undef values.
1284 if (I.getType()->isVoidTy()) continue;
1286 if (StructType *STy = dyn_cast<StructType>(I.getType())) {
1287 // Only a few things that can be structs matter for undef.
1289 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1290 if (CallSite CS = CallSite(&I))
1291 if (Function *F = CS.getCalledFunction())
1292 if (MRVFunctionsTracked.count(F))
1295 // extractvalue and insertvalue don't need to be marked; they are
1296 // tracked as precisely as their operands.
1297 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1300 // Send the results of everything else to overdefined. We could be
1301 // more precise than this but it isn't worth bothering.
1302 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1303 LatticeVal &LV = getStructValueState(&I, i);
1304 if (LV.isUndefined())
1305 markOverdefined(LV, &I);
1310 LatticeVal &LV = getValueState(&I);
1311 if (!LV.isUndefined()) continue;
1313 // extractvalue is safe; check here because the argument is a struct.
1314 if (isa<ExtractValueInst>(I))
1317 // Compute the operand LatticeVals, for convenience below.
1318 // Anything taking a struct is conservatively assumed to require
1319 // overdefined markings.
1320 if (I.getOperand(0)->getType()->isStructTy()) {
1321 markOverdefined(&I);
1324 LatticeVal Op0LV = getValueState(I.getOperand(0));
1326 if (I.getNumOperands() == 2) {
1327 if (I.getOperand(1)->getType()->isStructTy()) {
1328 markOverdefined(&I);
1332 Op1LV = getValueState(I.getOperand(1));
1334 // If this is an instructions whose result is defined even if the input is
1335 // not fully defined, propagate the information.
1336 Type *ITy = I.getType();
1337 switch (I.getOpcode()) {
1338 case Instruction::Add:
1339 case Instruction::Sub:
1340 case Instruction::Trunc:
1341 case Instruction::FPTrunc:
1342 case Instruction::BitCast:
1343 break; // Any undef -> undef
1344 case Instruction::FSub:
1345 case Instruction::FAdd:
1346 case Instruction::FMul:
1347 case Instruction::FDiv:
1348 case Instruction::FRem:
1349 // Floating-point binary operation: be conservative.
1350 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1351 markForcedConstant(&I, Constant::getNullValue(ITy));
1353 markOverdefined(&I);
1355 case Instruction::ZExt:
1356 case Instruction::SExt:
1357 case Instruction::FPToUI:
1358 case Instruction::FPToSI:
1359 case Instruction::FPExt:
1360 case Instruction::PtrToInt:
1361 case Instruction::IntToPtr:
1362 case Instruction::SIToFP:
1363 case Instruction::UIToFP:
1364 // undef -> 0; some outputs are impossible
1365 markForcedConstant(&I, Constant::getNullValue(ITy));
1367 case Instruction::Mul:
1368 case Instruction::And:
1369 // Both operands undef -> undef
1370 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1372 // undef * X -> 0. X could be zero.
1373 // undef & X -> 0. X could be zero.
1374 markForcedConstant(&I, Constant::getNullValue(ITy));
1377 case Instruction::Or:
1378 // Both operands undef -> undef
1379 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1381 // undef | X -> -1. X could be -1.
1382 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1385 case Instruction::Xor:
1386 // undef ^ undef -> 0; strictly speaking, this is not strictly
1387 // necessary, but we try to be nice to people who expect this
1388 // behavior in simple cases
1389 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1390 markForcedConstant(&I, Constant::getNullValue(ITy));
1393 // undef ^ X -> undef
1396 case Instruction::SDiv:
1397 case Instruction::UDiv:
1398 case Instruction::SRem:
1399 case Instruction::URem:
1400 // X / undef -> undef. No change.
1401 // X % undef -> undef. No change.
1402 if (Op1LV.isUndefined()) break;
1404 // X / 0 -> undef. No change.
1405 // X % 0 -> undef. No change.
1406 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1409 // undef / X -> 0. X could be maxint.
1410 // undef % X -> 0. X could be 1.
1411 markForcedConstant(&I, Constant::getNullValue(ITy));
1414 case Instruction::AShr:
1415 // X >>a undef -> undef.
1416 if (Op1LV.isUndefined()) break;
1418 // undef >>a X -> all ones
1419 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1421 case Instruction::LShr:
1422 case Instruction::Shl:
1423 // X << undef -> undef.
1424 // X >> undef -> undef.
1425 if (Op1LV.isUndefined()) break;
1429 markForcedConstant(&I, Constant::getNullValue(ITy));
1431 case Instruction::Select:
1432 Op1LV = getValueState(I.getOperand(1));
1433 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1434 if (Op0LV.isUndefined()) {
1435 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1436 Op1LV = getValueState(I.getOperand(2));
1437 } else if (Op1LV.isUndefined()) {
1438 // c ? undef : undef -> undef. No change.
1439 Op1LV = getValueState(I.getOperand(2));
1440 if (Op1LV.isUndefined())
1442 // Otherwise, c ? undef : x -> x.
1444 // Leave Op1LV as Operand(1)'s LatticeValue.
1447 if (Op1LV.isConstant())
1448 markForcedConstant(&I, Op1LV.getConstant());
1450 markOverdefined(&I);
1452 case Instruction::Load:
1453 // A load here means one of two things: a load of undef from a global,
1454 // a load from an unknown pointer. Either way, having it return undef
1457 case Instruction::ICmp:
1458 // X == undef -> undef. Other comparisons get more complicated.
1459 if (cast<ICmpInst>(&I)->isEquality())
1461 markOverdefined(&I);
1463 case Instruction::Call:
1464 case Instruction::Invoke: {
1465 // There are two reasons a call can have an undef result
1466 // 1. It could be tracked.
1467 // 2. It could be constant-foldable.
1468 // Because of the way we solve return values, tracked calls must
1469 // never be marked overdefined in ResolvedUndefsIn.
1470 if (Function *F = CallSite(&I).getCalledFunction())
1471 if (TrackedRetVals.count(F))
1474 // If the call is constant-foldable, we mark it overdefined because
1475 // we do not know what return values are valid.
1476 markOverdefined(&I);
1480 // If we don't know what should happen here, conservatively mark it
1482 markOverdefined(&I);
1487 // Check to see if we have a branch or switch on an undefined value. If so
1488 // we force the branch to go one way or the other to make the successor
1489 // values live. It doesn't really matter which way we force it.
1490 TerminatorInst *TI = BB->getTerminator();
1491 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1492 if (!BI->isConditional()) continue;
1493 if (!getValueState(BI->getCondition()).isUndefined())
1496 // If the input to SCCP is actually branch on undef, fix the undef to
1498 if (isa<UndefValue>(BI->getCondition())) {
1499 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1500 markEdgeExecutable(&*BB, TI->getSuccessor(1));
1504 // Otherwise, it is a branch on a symbolic value which is currently
1505 // considered to be undef. Handle this by forcing the input value to the
1507 markForcedConstant(BI->getCondition(),
1508 ConstantInt::getFalse(TI->getContext()));
1512 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1513 if (!SI->getNumCases())
1515 if (!getValueState(SI->getCondition()).isUndefined())
1518 // If the input to SCCP is actually switch on undef, fix the undef to
1519 // the first constant.
1520 if (isa<UndefValue>(SI->getCondition())) {
1521 SI->setCondition(SI->case_begin().getCaseValue());
1522 markEdgeExecutable(&*BB, SI->case_begin().getCaseSuccessor());
1526 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
1536 //===--------------------------------------------------------------------===//
1538 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1539 /// Sparse Conditional Constant Propagator.
1541 struct SCCP : public FunctionPass {
1542 void getAnalysisUsage(AnalysisUsage &AU) const override {
1543 AU.addRequired<TargetLibraryInfoWrapperPass>();
1544 AU.addPreserved<GlobalsAAWrapperPass>();
1546 static char ID; // Pass identification, replacement for typeid
1547 SCCP() : FunctionPass(ID) {
1548 initializeSCCPPass(*PassRegistry::getPassRegistry());
1551 // runOnFunction - Run the Sparse Conditional Constant Propagation
1552 // algorithm, and return true if the function was modified.
1554 bool runOnFunction(Function &F) override;
1556 } // end anonymous namespace
1559 INITIALIZE_PASS(SCCP, "sccp",
1560 "Sparse Conditional Constant Propagation", false, false)
1562 // createSCCPPass - This is the public interface to this file.
1563 FunctionPass *llvm::createSCCPPass() {
1567 static void DeleteInstructionInBlock(BasicBlock *BB) {
1568 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1571 // Check to see if there are non-terminating instructions to delete.
1572 if (isa<TerminatorInst>(BB->begin()))
1575 // Delete the instructions backwards, as it has a reduced likelihood of having
1576 // to update as many def-use and use-def chains.
1577 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1578 while (EndInst != BB->begin()) {
1579 // Delete the next to last instruction.
1580 Instruction *Inst = &*--EndInst->getIterator();
1581 if (!Inst->use_empty())
1582 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1583 if (Inst->isEHPad()) {
1587 BB->getInstList().erase(Inst);
1592 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1593 // and return true if the function was modified.
1595 bool SCCP::runOnFunction(Function &F) {
1596 if (skipOptnoneFunction(F))
1599 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1600 const DataLayout &DL = F.getParent()->getDataLayout();
1601 const TargetLibraryInfo *TLI =
1602 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1603 SCCPSolver Solver(DL, TLI);
1605 // Mark the first block of the function as being executable.
1606 Solver.MarkBlockExecutable(&F.front());
1608 // Mark all arguments to the function as being overdefined.
1609 for (Argument &AI : F.args())
1610 Solver.markAnythingOverdefined(&AI);
1612 // Solve for constants.
1613 bool ResolvedUndefs = true;
1614 while (ResolvedUndefs) {
1616 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1617 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1620 bool MadeChanges = false;
1622 // If we decided that there are basic blocks that are dead in this function,
1623 // delete their contents now. Note that we cannot actually delete the blocks,
1624 // as we cannot modify the CFG of the function.
1626 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1627 if (!Solver.isBlockExecutable(&*BB)) {
1628 DeleteInstructionInBlock(&*BB);
1633 // Iterate over all of the instructions in a function, replacing them with
1634 // constants if we have found them to be of constant values.
1636 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1637 Instruction *Inst = &*BI++;
1638 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1641 // TODO: Reconstruct structs from their elements.
1642 if (Inst->getType()->isStructTy())
1645 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1646 if (IV.isOverdefined())
1649 Constant *Const = IV.isConstant()
1650 ? IV.getConstant() : UndefValue::get(Inst->getType());
1651 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
1653 // Replaces all of the uses of a variable with uses of the constant.
1654 Inst->replaceAllUsesWith(Const);
1656 // Delete the instruction.
1657 Inst->eraseFromParent();
1659 // Hey, we just changed something!
1669 //===--------------------------------------------------------------------===//
1671 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1672 /// Constant Propagation.
1674 struct IPSCCP : public ModulePass {
1675 void getAnalysisUsage(AnalysisUsage &AU) const override {
1676 AU.addRequired<TargetLibraryInfoWrapperPass>();
1679 IPSCCP() : ModulePass(ID) {
1680 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1682 bool runOnModule(Module &M) override;
1684 } // end anonymous namespace
1686 char IPSCCP::ID = 0;
1687 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1688 "Interprocedural Sparse Conditional Constant Propagation",
1690 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1691 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
1692 "Interprocedural Sparse Conditional Constant Propagation",
1695 // createIPSCCPPass - This is the public interface to this file.
1696 ModulePass *llvm::createIPSCCPPass() {
1697 return new IPSCCP();
1701 static bool AddressIsTaken(const GlobalValue *GV) {
1702 // Delete any dead constantexpr klingons.
1703 GV->removeDeadConstantUsers();
1705 for (const Use &U : GV->uses()) {
1706 const User *UR = U.getUser();
1707 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
1708 if (SI->getOperand(0) == GV || SI->isVolatile())
1709 return true; // Storing addr of GV.
1710 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1711 // Make sure we are calling the function, not passing the address.
1712 ImmutableCallSite CS(cast<Instruction>(UR));
1713 if (!CS.isCallee(&U))
1715 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
1716 if (LI->isVolatile())
1718 } else if (isa<BlockAddress>(UR)) {
1719 // blockaddress doesn't take the address of the function, it takes addr
1728 bool IPSCCP::runOnModule(Module &M) {
1729 const DataLayout &DL = M.getDataLayout();
1730 const TargetLibraryInfo *TLI =
1731 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1732 SCCPSolver Solver(DL, TLI);
1734 // AddressTakenFunctions - This set keeps track of the address-taken functions
1735 // that are in the input. As IPSCCP runs through and simplifies code,
1736 // functions that were address taken can end up losing their
1737 // address-taken-ness. Because of this, we keep track of their addresses from
1738 // the first pass so we can use them for the later simplification pass.
1739 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1741 // Loop over all functions, marking arguments to those with their addresses
1742 // taken or that are external as overdefined.
1744 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1745 if (F->isDeclaration())
1748 // If this is a strong or ODR definition of this function, then we can
1749 // propagate information about its result into callsites of it.
1750 if (!F->mayBeOverridden())
1751 Solver.AddTrackedFunction(&*F);
1753 // If this function only has direct calls that we can see, we can track its
1754 // arguments and return value aggressively, and can assume it is not called
1755 // unless we see evidence to the contrary.
1756 if (F->hasLocalLinkage()) {
1757 if (AddressIsTaken(&*F))
1758 AddressTakenFunctions.insert(&*F);
1760 Solver.AddArgumentTrackedFunction(&*F);
1765 // Assume the function is called.
1766 Solver.MarkBlockExecutable(&F->front());
1768 // Assume nothing about the incoming arguments.
1769 for (Argument &AI : F->args())
1770 Solver.markAnythingOverdefined(&AI);
1773 // Loop over global variables. We inform the solver about any internal global
1774 // variables that do not have their 'addresses taken'. If they don't have
1775 // their addresses taken, we can propagate constants through them.
1776 for (GlobalVariable &G : M.globals())
1777 if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1778 Solver.TrackValueOfGlobalVariable(&G);
1780 // Solve for constants.
1781 bool ResolvedUndefs = true;
1782 while (ResolvedUndefs) {
1785 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1786 ResolvedUndefs = false;
1787 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1788 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1791 bool MadeChanges = false;
1793 // Iterate over all of the instructions in the module, replacing them with
1794 // constants if we have found them to be of constant values.
1796 SmallVector<BasicBlock*, 512> BlocksToErase;
1798 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1799 if (F->isDeclaration())
1802 if (Solver.isBlockExecutable(&F->front())) {
1803 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1805 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1807 // TODO: Could use getStructLatticeValueFor to find out if the entire
1808 // result is a constant and replace it entirely if so.
1810 LatticeVal IV = Solver.getLatticeValueFor(&*AI);
1811 if (IV.isOverdefined()) continue;
1813 Constant *CST = IV.isConstant() ?
1814 IV.getConstant() : UndefValue::get(AI->getType());
1815 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1817 // Replaces all of the uses of a variable with uses of the
1819 AI->replaceAllUsesWith(CST);
1824 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1825 if (!Solver.isBlockExecutable(&*BB)) {
1826 DeleteInstructionInBlock(&*BB);
1829 TerminatorInst *TI = BB->getTerminator();
1830 for (BasicBlock *Succ : TI->successors()) {
1831 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1832 Succ->removePredecessor(&*BB);
1834 if (!TI->use_empty())
1835 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1836 TI->eraseFromParent();
1837 new UnreachableInst(M.getContext(), &*BB);
1839 if (&*BB != &F->front())
1840 BlocksToErase.push_back(&*BB);
1844 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1845 Instruction *Inst = &*BI++;
1846 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1849 // TODO: Could use getStructLatticeValueFor to find out if the entire
1850 // result is a constant and replace it entirely if so.
1852 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1853 if (IV.isOverdefined())
1856 Constant *Const = IV.isConstant()
1857 ? IV.getConstant() : UndefValue::get(Inst->getType());
1858 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
1860 // Replaces all of the uses of a variable with uses of the
1862 Inst->replaceAllUsesWith(Const);
1864 // Delete the instruction.
1865 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1866 Inst->eraseFromParent();
1868 // Hey, we just changed something!
1874 // Now that all instructions in the function are constant folded, erase dead
1875 // blocks, because we can now use ConstantFoldTerminator to get rid of
1877 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1878 // If there are any PHI nodes in this successor, drop entries for BB now.
1879 BasicBlock *DeadBB = BlocksToErase[i];
1880 for (Value::user_iterator UI = DeadBB->user_begin(),
1881 UE = DeadBB->user_end();
1883 // Grab the user and then increment the iterator early, as the user
1884 // will be deleted. Step past all adjacent uses from the same user.
1885 Instruction *I = dyn_cast<Instruction>(*UI);
1886 do { ++UI; } while (UI != UE && *UI == I);
1888 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1891 bool Folded = ConstantFoldTerminator(I->getParent());
1893 // The constant folder may not have been able to fold the terminator
1894 // if this is a branch or switch on undef. Fold it manually as a
1895 // branch to the first successor.
1897 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1898 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1899 "Branch should be foldable!");
1900 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1901 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1903 llvm_unreachable("Didn't fold away reference to block!");
1907 // Make this an uncond branch to the first successor.
1908 TerminatorInst *TI = I->getParent()->getTerminator();
1909 BranchInst::Create(TI->getSuccessor(0), TI);
1911 // Remove entries in successor phi nodes to remove edges.
1912 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1913 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1915 // Remove the old terminator.
1916 TI->eraseFromParent();
1920 // Finally, delete the basic block.
1921 F->getBasicBlockList().erase(DeadBB);
1923 BlocksToErase.clear();
1926 // If we inferred constant or undef return values for a function, we replaced
1927 // all call uses with the inferred value. This means we don't need to bother
1928 // actually returning anything from the function. Replace all return
1929 // instructions with return undef.
1931 // Do this in two stages: first identify the functions we should process, then
1932 // actually zap their returns. This is important because we can only do this
1933 // if the address of the function isn't taken. In cases where a return is the
1934 // last use of a function, the order of processing functions would affect
1935 // whether other functions are optimizable.
1936 SmallVector<ReturnInst*, 8> ReturnsToZap;
1938 // TODO: Process multiple value ret instructions also.
1939 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1940 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1941 E = RV.end(); I != E; ++I) {
1942 Function *F = I->first;
1943 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1946 // We can only do this if we know that nothing else can call the function.
1947 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1950 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1951 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1952 if (!isa<UndefValue>(RI->getOperand(0)))
1953 ReturnsToZap.push_back(RI);
1956 // Zap all returns which we've identified as zap to change.
1957 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1958 Function *F = ReturnsToZap[i]->getParent()->getParent();
1959 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1962 // If we inferred constant or undef values for globals variables, we can
1963 // delete the global and any stores that remain to it.
1964 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1965 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1966 E = TG.end(); I != E; ++I) {
1967 GlobalVariable *GV = I->first;
1968 assert(!I->second.isOverdefined() &&
1969 "Overdefined values should have been taken out of the map!");
1970 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1971 while (!GV->use_empty()) {
1972 StoreInst *SI = cast<StoreInst>(GV->user_back());
1973 SI->eraseFromParent();
1975 M.getGlobalList().erase(GV);