1 | //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // \file |
10 | // This file implements the Sparse Conditional Constant Propagation (SCCP) |
11 | // utility. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #include "llvm/Transforms/Utils/SCCPSolver.h" |
16 | #include "llvm/Analysis/ConstantFolding.h" |
17 | #include "llvm/Analysis/InstructionSimplify.h" |
18 | #include "llvm/Analysis/ValueLattice.h" |
19 | #include "llvm/Analysis/ValueLatticeUtils.h" |
20 | #include "llvm/Analysis/ValueTracking.h" |
21 | #include "llvm/IR/InstVisitor.h" |
22 | #include "llvm/Support/Casting.h" |
23 | #include "llvm/Support/Debug.h" |
24 | #include "llvm/Support/ErrorHandling.h" |
25 | #include "llvm/Support/raw_ostream.h" |
26 | #include "llvm/Transforms/Utils/Local.h" |
27 | #include <cassert> |
28 | #include <utility> |
29 | #include <vector> |
30 | |
31 | using namespace llvm; |
32 | |
33 | #define DEBUG_TYPE "sccp" |
34 | |
35 | // The maximum number of range extensions allowed for operations requiring |
36 | // widening. |
37 | static const unsigned MaxNumRangeExtensions = 10; |
38 | |
39 | /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions. |
40 | static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() { |
41 | return ValueLatticeElement::MergeOptions().setMaxWidenSteps( |
42 | MaxNumRangeExtensions); |
43 | } |
44 | |
45 | static ConstantRange getConstantRange(const ValueLatticeElement &LV, Type *Ty, |
46 | bool UndefAllowed = true) { |
47 | assert(Ty->isIntOrIntVectorTy() && "Should be int or int vector" ); |
48 | if (LV.isConstantRange(UndefAllowed)) |
49 | return LV.getConstantRange(); |
50 | return ConstantRange::getFull(BitWidth: Ty->getScalarSizeInBits()); |
51 | } |
52 | |
53 | namespace llvm { |
54 | |
55 | bool SCCPSolver::isConstant(const ValueLatticeElement &LV) { |
56 | return LV.isConstant() || |
57 | (LV.isConstantRange() && LV.getConstantRange().isSingleElement()); |
58 | } |
59 | |
60 | bool SCCPSolver::isOverdefined(const ValueLatticeElement &LV) { |
61 | return !LV.isUnknownOrUndef() && !SCCPSolver::isConstant(LV); |
62 | } |
63 | |
64 | static bool canRemoveInstruction(Instruction *I) { |
65 | if (wouldInstructionBeTriviallyDead(I)) |
66 | return true; |
67 | |
68 | // Some instructions can be handled but are rejected above. Catch |
69 | // those cases by falling through to here. |
70 | // TODO: Mark globals as being constant earlier, so |
71 | // TODO: wouldInstructionBeTriviallyDead() knows that atomic loads |
72 | // TODO: are safe to remove. |
73 | return isa<LoadInst>(Val: I); |
74 | } |
75 | |
76 | bool SCCPSolver::tryToReplaceWithConstant(Value *V) { |
77 | Constant *Const = getConstantOrNull(V); |
78 | if (!Const) |
79 | return false; |
80 | // Replacing `musttail` instructions with constant breaks `musttail` invariant |
81 | // unless the call itself can be removed. |
82 | // Calls with "clang.arc.attachedcall" implicitly use the return value and |
83 | // those uses cannot be updated with a constant. |
84 | CallBase *CB = dyn_cast<CallBase>(Val: V); |
85 | if (CB && ((CB->isMustTailCall() && |
86 | !canRemoveInstruction(I: CB)) || |
87 | CB->getOperandBundle(ID: LLVMContext::OB_clang_arc_attachedcall))) { |
88 | Function *F = CB->getCalledFunction(); |
89 | |
90 | // Don't zap returns of the callee |
91 | if (F) |
92 | addToMustPreserveReturnsInFunctions(F); |
93 | |
94 | LLVM_DEBUG(dbgs() << " Can\'t treat the result of call " << *CB |
95 | << " as a constant\n" ); |
96 | return false; |
97 | } |
98 | |
99 | LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n'); |
100 | |
101 | // Replaces all of the uses of a variable with uses of the constant. |
102 | V->replaceAllUsesWith(V: Const); |
103 | return true; |
104 | } |
105 | |
106 | /// Try to use \p Inst's value range from \p Solver to infer the NUW flag. |
107 | static bool refineInstruction(SCCPSolver &Solver, |
108 | const SmallPtrSetImpl<Value *> &InsertedValues, |
109 | Instruction &Inst) { |
110 | bool Changed = false; |
111 | auto GetRange = [&Solver, &InsertedValues](Value *Op) { |
112 | if (auto *Const = dyn_cast<ConstantInt>(Val: Op)) |
113 | return ConstantRange(Const->getValue()); |
114 | if (isa<Constant>(Val: Op) || InsertedValues.contains(Ptr: Op)) { |
115 | unsigned Bitwidth = Op->getType()->getScalarSizeInBits(); |
116 | return ConstantRange::getFull(BitWidth: Bitwidth); |
117 | } |
118 | return getConstantRange(LV: Solver.getLatticeValueFor(V: Op), Ty: Op->getType(), |
119 | /*UndefAllowed=*/false); |
120 | }; |
121 | |
122 | if (isa<OverflowingBinaryOperator>(Val: Inst)) { |
123 | if (Inst.hasNoSignedWrap() && Inst.hasNoUnsignedWrap()) |
124 | return false; |
125 | |
126 | auto RangeA = GetRange(Inst.getOperand(i: 0)); |
127 | auto RangeB = GetRange(Inst.getOperand(i: 1)); |
128 | if (!Inst.hasNoUnsignedWrap()) { |
129 | auto NUWRange = ConstantRange::makeGuaranteedNoWrapRegion( |
130 | BinOp: Instruction::BinaryOps(Inst.getOpcode()), Other: RangeB, |
131 | NoWrapKind: OverflowingBinaryOperator::NoUnsignedWrap); |
132 | if (NUWRange.contains(CR: RangeA)) { |
133 | Inst.setHasNoUnsignedWrap(); |
134 | Changed = true; |
135 | } |
136 | } |
137 | if (!Inst.hasNoSignedWrap()) { |
138 | auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion( |
139 | BinOp: Instruction::BinaryOps(Inst.getOpcode()), Other: RangeB, |
140 | NoWrapKind: OverflowingBinaryOperator::NoSignedWrap); |
141 | if (NSWRange.contains(CR: RangeA)) { |
142 | Inst.setHasNoSignedWrap(); |
143 | Changed = true; |
144 | } |
145 | } |
146 | } else if (isa<ZExtInst>(Val: Inst) && !Inst.hasNonNeg()) { |
147 | auto Range = GetRange(Inst.getOperand(i: 0)); |
148 | if (Range.isAllNonNegative()) { |
149 | Inst.setNonNeg(); |
150 | Changed = true; |
151 | } |
152 | } else if (TruncInst *TI = dyn_cast<TruncInst>(Val: &Inst)) { |
153 | if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap()) |
154 | return false; |
155 | |
156 | auto Range = GetRange(Inst.getOperand(i: 0)); |
157 | uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits(); |
158 | if (!TI->hasNoUnsignedWrap()) { |
159 | if (Range.getActiveBits() <= DestWidth) { |
160 | TI->setHasNoUnsignedWrap(true); |
161 | Changed = true; |
162 | } |
163 | } |
164 | if (!TI->hasNoSignedWrap()) { |
165 | if (Range.getMinSignedBits() <= DestWidth) { |
166 | TI->setHasNoSignedWrap(true); |
167 | Changed = true; |
168 | } |
169 | } |
170 | } |
171 | |
172 | return Changed; |
173 | } |
174 | |
175 | /// Try to replace signed instructions with their unsigned equivalent. |
176 | static bool replaceSignedInst(SCCPSolver &Solver, |
177 | SmallPtrSetImpl<Value *> &InsertedValues, |
178 | Instruction &Inst) { |
179 | // Determine if a signed value is known to be >= 0. |
180 | auto isNonNegative = [&Solver](Value *V) { |
181 | // If this value was constant-folded, it may not have a solver entry. |
182 | // Handle integers. Otherwise, return false. |
183 | if (auto *C = dyn_cast<Constant>(Val: V)) { |
184 | auto *CInt = dyn_cast<ConstantInt>(Val: C); |
185 | return CInt && !CInt->isNegative(); |
186 | } |
187 | const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); |
188 | return IV.isConstantRange(/*UndefAllowed=*/false) && |
189 | IV.getConstantRange().isAllNonNegative(); |
190 | }; |
191 | |
192 | Instruction *NewInst = nullptr; |
193 | switch (Inst.getOpcode()) { |
194 | // Note: We do not fold sitofp -> uitofp here because that could be more |
195 | // expensive in codegen and may not be reversible in the backend. |
196 | case Instruction::SExt: { |
197 | // If the source value is not negative, this is a zext. |
198 | Value *Op0 = Inst.getOperand(i: 0); |
199 | if (InsertedValues.count(Ptr: Op0) || !isNonNegative(Op0)) |
200 | return false; |
201 | NewInst = new ZExtInst(Op0, Inst.getType(), "" , Inst.getIterator()); |
202 | NewInst->setNonNeg(); |
203 | break; |
204 | } |
205 | case Instruction::AShr: { |
206 | // If the shifted value is not negative, this is a logical shift right. |
207 | Value *Op0 = Inst.getOperand(i: 0); |
208 | if (InsertedValues.count(Ptr: Op0) || !isNonNegative(Op0)) |
209 | return false; |
210 | NewInst = BinaryOperator::CreateLShr(V1: Op0, V2: Inst.getOperand(i: 1), Name: "" , It: Inst.getIterator()); |
211 | NewInst->setIsExact(Inst.isExact()); |
212 | break; |
213 | } |
214 | case Instruction::SDiv: |
215 | case Instruction::SRem: { |
216 | // If both operands are not negative, this is the same as udiv/urem. |
217 | Value *Op0 = Inst.getOperand(i: 0), *Op1 = Inst.getOperand(i: 1); |
218 | if (InsertedValues.count(Ptr: Op0) || InsertedValues.count(Ptr: Op1) || |
219 | !isNonNegative(Op0) || !isNonNegative(Op1)) |
220 | return false; |
221 | auto NewOpcode = Inst.getOpcode() == Instruction::SDiv ? Instruction::UDiv |
222 | : Instruction::URem; |
223 | NewInst = BinaryOperator::Create(Op: NewOpcode, S1: Op0, S2: Op1, Name: "" , InsertBefore: Inst.getIterator()); |
224 | if (Inst.getOpcode() == Instruction::SDiv) |
225 | NewInst->setIsExact(Inst.isExact()); |
226 | break; |
227 | } |
228 | default: |
229 | return false; |
230 | } |
231 | |
232 | // Wire up the new instruction and update state. |
233 | assert(NewInst && "Expected replacement instruction" ); |
234 | NewInst->takeName(V: &Inst); |
235 | InsertedValues.insert(Ptr: NewInst); |
236 | Inst.replaceAllUsesWith(V: NewInst); |
237 | Solver.removeLatticeValueFor(V: &Inst); |
238 | Inst.eraseFromParent(); |
239 | return true; |
240 | } |
241 | |
242 | bool SCCPSolver::simplifyInstsInBlock(BasicBlock &BB, |
243 | SmallPtrSetImpl<Value *> &InsertedValues, |
244 | Statistic &InstRemovedStat, |
245 | Statistic &InstReplacedStat) { |
246 | bool MadeChanges = false; |
247 | for (Instruction &Inst : make_early_inc_range(Range&: BB)) { |
248 | if (Inst.getType()->isVoidTy()) |
249 | continue; |
250 | if (tryToReplaceWithConstant(V: &Inst)) { |
251 | if (canRemoveInstruction(I: &Inst)) |
252 | Inst.eraseFromParent(); |
253 | |
254 | MadeChanges = true; |
255 | ++InstRemovedStat; |
256 | } else if (replaceSignedInst(Solver&: *this, InsertedValues, Inst)) { |
257 | MadeChanges = true; |
258 | ++InstReplacedStat; |
259 | } else if (refineInstruction(Solver&: *this, InsertedValues, Inst)) { |
260 | MadeChanges = true; |
261 | } |
262 | } |
263 | return MadeChanges; |
264 | } |
265 | |
266 | bool SCCPSolver::removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU, |
267 | BasicBlock *&NewUnreachableBB) const { |
268 | SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors; |
269 | bool HasNonFeasibleEdges = false; |
270 | for (BasicBlock *Succ : successors(BB)) { |
271 | if (isEdgeFeasible(From: BB, To: Succ)) |
272 | FeasibleSuccessors.insert(Ptr: Succ); |
273 | else |
274 | HasNonFeasibleEdges = true; |
275 | } |
276 | |
277 | // All edges feasible, nothing to do. |
278 | if (!HasNonFeasibleEdges) |
279 | return false; |
280 | |
281 | // SCCP can only determine non-feasible edges for br, switch and indirectbr. |
282 | Instruction *TI = BB->getTerminator(); |
283 | assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) || |
284 | isa<IndirectBrInst>(TI)) && |
285 | "Terminator must be a br, switch or indirectbr" ); |
286 | |
287 | if (FeasibleSuccessors.size() == 0) { |
288 | // Branch on undef/poison, replace with unreachable. |
289 | SmallPtrSet<BasicBlock *, 8> SeenSuccs; |
290 | SmallVector<DominatorTree::UpdateType, 8> Updates; |
291 | for (BasicBlock *Succ : successors(BB)) { |
292 | Succ->removePredecessor(Pred: BB); |
293 | if (SeenSuccs.insert(Ptr: Succ).second) |
294 | Updates.push_back(Elt: {DominatorTree::Delete, BB, Succ}); |
295 | } |
296 | TI->eraseFromParent(); |
297 | new UnreachableInst(BB->getContext(), BB); |
298 | DTU.applyUpdatesPermissive(Updates); |
299 | } else if (FeasibleSuccessors.size() == 1) { |
300 | // Replace with an unconditional branch to the only feasible successor. |
301 | BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin(); |
302 | SmallVector<DominatorTree::UpdateType, 8> Updates; |
303 | bool HaveSeenOnlyFeasibleSuccessor = false; |
304 | for (BasicBlock *Succ : successors(BB)) { |
305 | if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) { |
306 | // Don't remove the edge to the only feasible successor the first time |
307 | // we see it. We still do need to remove any multi-edges to it though. |
308 | HaveSeenOnlyFeasibleSuccessor = true; |
309 | continue; |
310 | } |
311 | |
312 | Succ->removePredecessor(Pred: BB); |
313 | Updates.push_back(Elt: {DominatorTree::Delete, BB, Succ}); |
314 | } |
315 | |
316 | BranchInst::Create(IfTrue: OnlyFeasibleSuccessor, InsertAtEnd: BB); |
317 | TI->eraseFromParent(); |
318 | DTU.applyUpdatesPermissive(Updates); |
319 | } else if (FeasibleSuccessors.size() > 1) { |
320 | SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(Val: TI)); |
321 | SmallVector<DominatorTree::UpdateType, 8> Updates; |
322 | |
323 | // If the default destination is unfeasible it will never be taken. Replace |
324 | // it with a new block with a single Unreachable instruction. |
325 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
326 | if (!FeasibleSuccessors.contains(Ptr: DefaultDest)) { |
327 | if (!NewUnreachableBB) { |
328 | NewUnreachableBB = |
329 | BasicBlock::Create(Context&: DefaultDest->getContext(), Name: "default.unreachable" , |
330 | Parent: DefaultDest->getParent(), InsertBefore: DefaultDest); |
331 | new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB); |
332 | } |
333 | |
334 | DefaultDest->removePredecessor(Pred: BB); |
335 | SI->setDefaultDest(NewUnreachableBB); |
336 | Updates.push_back(Elt: {DominatorTree::Delete, BB, DefaultDest}); |
337 | Updates.push_back(Elt: {DominatorTree::Insert, BB, NewUnreachableBB}); |
338 | } |
339 | |
340 | for (auto CI = SI->case_begin(); CI != SI->case_end();) { |
341 | if (FeasibleSuccessors.contains(Ptr: CI->getCaseSuccessor())) { |
342 | ++CI; |
343 | continue; |
344 | } |
345 | |
346 | BasicBlock *Succ = CI->getCaseSuccessor(); |
347 | Succ->removePredecessor(Pred: BB); |
348 | Updates.push_back(Elt: {DominatorTree::Delete, BB, Succ}); |
349 | SI.removeCase(I: CI); |
350 | // Don't increment CI, as we removed a case. |
351 | } |
352 | |
353 | DTU.applyUpdatesPermissive(Updates); |
354 | } else { |
355 | llvm_unreachable("Must have at least one feasible successor" ); |
356 | } |
357 | return true; |
358 | } |
359 | |
360 | /// Helper class for SCCPSolver. This implements the instruction visitor and |
361 | /// holds all the state. |
362 | class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> { |
363 | const DataLayout &DL; |
364 | std::function<const TargetLibraryInfo &(Function &)> GetTLI; |
365 | SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable. |
366 | DenseMap<Value *, ValueLatticeElement> |
367 | ValueState; // The state each value is in. |
368 | |
369 | /// StructValueState - This maintains ValueState for values that have |
370 | /// StructType, for example for formal arguments, calls, insertelement, etc. |
371 | DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState; |
372 | |
373 | /// GlobalValue - If we are tracking any values for the contents of a global |
374 | /// variable, we keep a mapping from the constant accessor to the element of |
375 | /// the global, to the currently known value. If the value becomes |
376 | /// overdefined, it's entry is simply removed from this map. |
377 | DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals; |
378 | |
379 | /// TrackedRetVals - If we are tracking arguments into and the return |
380 | /// value out of a function, it will have an entry in this map, indicating |
381 | /// what the known return value for the function is. |
382 | MapVector<Function *, ValueLatticeElement> TrackedRetVals; |
383 | |
384 | /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions |
385 | /// that return multiple values. |
386 | MapVector<std::pair<Function *, unsigned>, ValueLatticeElement> |
387 | TrackedMultipleRetVals; |
388 | |
389 | /// The set of values whose lattice has been invalidated. |
390 | /// Populated by resetLatticeValueFor(), cleared after resolving undefs. |
391 | DenseSet<Value *> Invalidated; |
392 | |
393 | /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is |
394 | /// represented here for efficient lookup. |
395 | SmallPtrSet<Function *, 16> MRVFunctionsTracked; |
396 | |
397 | /// A list of functions whose return cannot be modified. |
398 | SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions; |
399 | |
400 | /// TrackingIncomingArguments - This is the set of functions for whose |
401 | /// arguments we make optimistic assumptions about and try to prove as |
402 | /// constants. |
403 | SmallPtrSet<Function *, 16> TrackingIncomingArguments; |
404 | |
405 | /// The reason for two worklists is that overdefined is the lowest state |
406 | /// on the lattice, and moving things to overdefined as fast as possible |
407 | /// makes SCCP converge much faster. |
408 | /// |
409 | /// By having a separate worklist, we accomplish this because everything |
410 | /// possibly overdefined will become overdefined at the soonest possible |
411 | /// point. |
412 | SmallVector<Value *, 64> OverdefinedInstWorkList; |
413 | SmallVector<Value *, 64> InstWorkList; |
414 | |
415 | // The BasicBlock work list |
416 | SmallVector<BasicBlock *, 64> BBWorkList; |
417 | |
418 | /// KnownFeasibleEdges - Entries in this set are edges which have already had |
419 | /// PHI nodes retriggered. |
420 | using Edge = std::pair<BasicBlock *, BasicBlock *>; |
421 | DenseSet<Edge> KnownFeasibleEdges; |
422 | |
423 | DenseMap<Function *, std::unique_ptr<PredicateInfo>> FnPredicateInfo; |
424 | |
425 | DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers; |
426 | |
427 | LLVMContext &Ctx; |
428 | |
429 | private: |
430 | ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const { |
431 | return dyn_cast_or_null<ConstantInt>(Val: getConstant(LV: IV, Ty)); |
432 | } |
433 | |
434 | // pushToWorkList - Helper for markConstant/markOverdefined |
435 | void pushToWorkList(ValueLatticeElement &IV, Value *V); |
436 | |
437 | // Helper to push \p V to the worklist, after updating it to \p IV. Also |
438 | // prints a debug message with the updated value. |
439 | void pushToWorkListMsg(ValueLatticeElement &IV, Value *V); |
440 | |
441 | // markConstant - Make a value be marked as "constant". If the value |
442 | // is not already a constant, add it to the instruction work list so that |
443 | // the users of the instruction are updated later. |
444 | bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C, |
445 | bool MayIncludeUndef = false); |
446 | |
447 | bool markConstant(Value *V, Constant *C) { |
448 | assert(!V->getType()->isStructTy() && "structs should use mergeInValue" ); |
449 | return markConstant(IV&: ValueState[V], V, C); |
450 | } |
451 | |
452 | /// markConstantRange - Mark the object as constant range with \p CR. If the |
453 | /// object is not a constant range with the range \p CR, add it to the |
454 | /// instruction work list so that the users of the instruction are updated |
455 | /// later. |
456 | bool markConstantRange(ValueLatticeElement &IV, Value *V, |
457 | const ConstantRange &CR); |
458 | |
459 | // markOverdefined - Make a value be marked as "overdefined". If the |
460 | // value is not already overdefined, add it to the overdefined instruction |
461 | // work list so that the users of the instruction are updated later. |
462 | bool markOverdefined(ValueLatticeElement &IV, Value *V); |
463 | |
464 | /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV |
465 | /// changes. |
466 | bool mergeInValue(ValueLatticeElement &IV, Value *V, |
467 | ValueLatticeElement MergeWithV, |
468 | ValueLatticeElement::MergeOptions Opts = { |
469 | /*MayIncludeUndef=*/false, /*CheckWiden=*/false}); |
470 | |
471 | bool mergeInValue(Value *V, ValueLatticeElement MergeWithV, |
472 | ValueLatticeElement::MergeOptions Opts = { |
473 | /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) { |
474 | assert(!V->getType()->isStructTy() && |
475 | "non-structs should use markConstant" ); |
476 | return mergeInValue(IV&: ValueState[V], V, MergeWithV, Opts); |
477 | } |
478 | |
479 | /// getValueState - Return the ValueLatticeElement object that corresponds to |
480 | /// the value. This function handles the case when the value hasn't been seen |
481 | /// yet by properly seeding constants etc. |
482 | ValueLatticeElement &getValueState(Value *V) { |
483 | assert(!V->getType()->isStructTy() && "Should use getStructValueState" ); |
484 | |
485 | auto I = ValueState.insert(KV: std::make_pair(x&: V, y: ValueLatticeElement())); |
486 | ValueLatticeElement &LV = I.first->second; |
487 | |
488 | if (!I.second) |
489 | return LV; // Common case, already in the map. |
490 | |
491 | if (auto *C = dyn_cast<Constant>(Val: V)) |
492 | LV.markConstant(V: C); // Constants are constant |
493 | |
494 | // All others are unknown by default. |
495 | return LV; |
496 | } |
497 | |
498 | /// getStructValueState - Return the ValueLatticeElement object that |
499 | /// corresponds to the value/field pair. This function handles the case when |
500 | /// the value hasn't been seen yet by properly seeding constants etc. |
501 | ValueLatticeElement &getStructValueState(Value *V, unsigned i) { |
502 | assert(V->getType()->isStructTy() && "Should use getValueState" ); |
503 | assert(i < cast<StructType>(V->getType())->getNumElements() && |
504 | "Invalid element #" ); |
505 | |
506 | auto I = StructValueState.insert( |
507 | KV: std::make_pair(x: std::make_pair(x&: V, y&: i), y: ValueLatticeElement())); |
508 | ValueLatticeElement &LV = I.first->second; |
509 | |
510 | if (!I.second) |
511 | return LV; // Common case, already in the map. |
512 | |
513 | if (auto *C = dyn_cast<Constant>(Val: V)) { |
514 | Constant *Elt = C->getAggregateElement(Elt: i); |
515 | |
516 | if (!Elt) |
517 | LV.markOverdefined(); // Unknown sort of constant. |
518 | else |
519 | LV.markConstant(V: Elt); // Constants are constant. |
520 | } |
521 | |
522 | // All others are underdefined by default. |
523 | return LV; |
524 | } |
525 | |
526 | /// Traverse the use-def chain of \p Call, marking itself and its users as |
527 | /// "unknown" on the way. |
528 | void invalidate(CallBase *Call) { |
529 | SmallVector<Instruction *, 64> ToInvalidate; |
530 | ToInvalidate.push_back(Elt: Call); |
531 | |
532 | while (!ToInvalidate.empty()) { |
533 | Instruction *Inst = ToInvalidate.pop_back_val(); |
534 | |
535 | if (!Invalidated.insert(V: Inst).second) |
536 | continue; |
537 | |
538 | if (!BBExecutable.count(Ptr: Inst->getParent())) |
539 | continue; |
540 | |
541 | Value *V = nullptr; |
542 | // For return instructions we need to invalidate the tracked returns map. |
543 | // Anything else has its lattice in the value map. |
544 | if (auto *RetInst = dyn_cast<ReturnInst>(Val: Inst)) { |
545 | Function *F = RetInst->getParent()->getParent(); |
546 | if (auto It = TrackedRetVals.find(Key: F); It != TrackedRetVals.end()) { |
547 | It->second = ValueLatticeElement(); |
548 | V = F; |
549 | } else if (MRVFunctionsTracked.count(Ptr: F)) { |
550 | auto *STy = cast<StructType>(Val: F->getReturnType()); |
551 | for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) |
552 | TrackedMultipleRetVals[{F, I}] = ValueLatticeElement(); |
553 | V = F; |
554 | } |
555 | } else if (auto *STy = dyn_cast<StructType>(Val: Inst->getType())) { |
556 | for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) { |
557 | if (auto It = StructValueState.find(Val: {Inst, I}); |
558 | It != StructValueState.end()) { |
559 | It->second = ValueLatticeElement(); |
560 | V = Inst; |
561 | } |
562 | } |
563 | } else if (auto It = ValueState.find(Val: Inst); It != ValueState.end()) { |
564 | It->second = ValueLatticeElement(); |
565 | V = Inst; |
566 | } |
567 | |
568 | if (V) { |
569 | LLVM_DEBUG(dbgs() << "Invalidated lattice for " << *V << "\n" ); |
570 | |
571 | for (User *U : V->users()) |
572 | if (auto *UI = dyn_cast<Instruction>(Val: U)) |
573 | ToInvalidate.push_back(Elt: UI); |
574 | |
575 | auto It = AdditionalUsers.find(Val: V); |
576 | if (It != AdditionalUsers.end()) |
577 | for (User *U : It->second) |
578 | if (auto *UI = dyn_cast<Instruction>(Val: U)) |
579 | ToInvalidate.push_back(Elt: UI); |
580 | } |
581 | } |
582 | } |
583 | |
584 | /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB |
585 | /// work list if it is not already executable. |
586 | bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest); |
587 | |
588 | // getFeasibleSuccessors - Return a vector of booleans to indicate which |
589 | // successors are reachable from a given terminator instruction. |
590 | void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs); |
591 | |
592 | // OperandChangedState - This method is invoked on all of the users of an |
593 | // instruction that was just changed state somehow. Based on this |
594 | // information, we need to update the specified user of this instruction. |
595 | void operandChangedState(Instruction *I) { |
596 | if (BBExecutable.count(Ptr: I->getParent())) // Inst is executable? |
597 | visit(I&: *I); |
598 | } |
599 | |
600 | // Add U as additional user of V. |
601 | void addAdditionalUser(Value *V, User *U) { |
602 | auto Iter = AdditionalUsers.insert(KV: {V, {}}); |
603 | Iter.first->second.insert(Ptr: U); |
604 | } |
605 | |
606 | // Mark I's users as changed, including AdditionalUsers. |
607 | void markUsersAsChanged(Value *I) { |
608 | // Functions include their arguments in the use-list. Changed function |
609 | // values mean that the result of the function changed. We only need to |
610 | // update the call sites with the new function result and do not have to |
611 | // propagate the call arguments. |
612 | if (isa<Function>(Val: I)) { |
613 | for (User *U : I->users()) { |
614 | if (auto *CB = dyn_cast<CallBase>(Val: U)) |
615 | handleCallResult(CB&: *CB); |
616 | } |
617 | } else { |
618 | for (User *U : I->users()) |
619 | if (auto *UI = dyn_cast<Instruction>(Val: U)) |
620 | operandChangedState(I: UI); |
621 | } |
622 | |
623 | auto Iter = AdditionalUsers.find(Val: I); |
624 | if (Iter != AdditionalUsers.end()) { |
625 | // Copy additional users before notifying them of changes, because new |
626 | // users may be added, potentially invalidating the iterator. |
627 | SmallVector<Instruction *, 2> ToNotify; |
628 | for (User *U : Iter->second) |
629 | if (auto *UI = dyn_cast<Instruction>(Val: U)) |
630 | ToNotify.push_back(Elt: UI); |
631 | for (Instruction *UI : ToNotify) |
632 | operandChangedState(I: UI); |
633 | } |
634 | } |
635 | void handleCallOverdefined(CallBase &CB); |
636 | void handleCallResult(CallBase &CB); |
637 | void handleCallArguments(CallBase &CB); |
638 | void handleExtractOfWithOverflow(ExtractValueInst &EVI, |
639 | const WithOverflowInst *WO, unsigned Idx); |
640 | |
641 | private: |
642 | friend class InstVisitor<SCCPInstVisitor>; |
643 | |
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. |
647 | void visitPHINode(PHINode &I); |
648 | |
649 | // Terminators |
650 | |
651 | void visitReturnInst(ReturnInst &I); |
652 | void visitTerminator(Instruction &TI); |
653 | |
654 | void visitCastInst(CastInst &I); |
655 | void visitSelectInst(SelectInst &I); |
656 | void visitUnaryOperator(Instruction &I); |
657 | void visitFreezeInst(FreezeInst &I); |
658 | void visitBinaryOperator(Instruction &I); |
659 | void visitCmpInst(CmpInst &I); |
660 | void visitExtractValueInst(ExtractValueInst &EVI); |
661 | void visitInsertValueInst(InsertValueInst &IVI); |
662 | |
663 | void visitCatchSwitchInst(CatchSwitchInst &CPI) { |
664 | markOverdefined(V: &CPI); |
665 | visitTerminator(TI&: CPI); |
666 | } |
667 | |
668 | // Instructions that cannot be folded away. |
669 | |
670 | void visitStoreInst(StoreInst &I); |
671 | void visitLoadInst(LoadInst &I); |
672 | void visitGetElementPtrInst(GetElementPtrInst &I); |
673 | |
674 | void visitInvokeInst(InvokeInst &II) { |
675 | visitCallBase(CB&: II); |
676 | visitTerminator(TI&: II); |
677 | } |
678 | |
679 | void visitCallBrInst(CallBrInst &CBI) { |
680 | visitCallBase(CB&: CBI); |
681 | visitTerminator(TI&: CBI); |
682 | } |
683 | |
684 | void visitCallBase(CallBase &CB); |
685 | void visitResumeInst(ResumeInst &I) { /*returns void*/ |
686 | } |
687 | void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ |
688 | } |
689 | void visitFenceInst(FenceInst &I) { /*returns void*/ |
690 | } |
691 | |
692 | void visitInstruction(Instruction &I); |
693 | |
694 | public: |
695 | void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC) { |
696 | FnPredicateInfo.insert(KV: {&F, std::make_unique<PredicateInfo>(args&: F, args&: DT, args&: AC)}); |
697 | } |
698 | |
699 | void visitCallInst(CallInst &I) { visitCallBase(CB&: I); } |
700 | |
701 | bool markBlockExecutable(BasicBlock *BB); |
702 | |
703 | const PredicateBase *getPredicateInfoFor(Instruction *I) { |
704 | auto It = FnPredicateInfo.find(Val: I->getParent()->getParent()); |
705 | if (It == FnPredicateInfo.end()) |
706 | return nullptr; |
707 | return It->second->getPredicateInfoFor(V: I); |
708 | } |
709 | |
710 | SCCPInstVisitor(const DataLayout &DL, |
711 | std::function<const TargetLibraryInfo &(Function &)> GetTLI, |
712 | LLVMContext &Ctx) |
713 | : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {} |
714 | |
715 | void trackValueOfGlobalVariable(GlobalVariable *GV) { |
716 | // We only track the contents of scalar globals. |
717 | if (GV->getValueType()->isSingleValueType()) { |
718 | ValueLatticeElement &IV = TrackedGlobals[GV]; |
719 | IV.markConstant(V: GV->getInitializer()); |
720 | } |
721 | } |
722 | |
723 | void addTrackedFunction(Function *F) { |
724 | // Add an entry, F -> undef. |
725 | if (auto *STy = dyn_cast<StructType>(Val: F->getReturnType())) { |
726 | MRVFunctionsTracked.insert(Ptr: F); |
727 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
728 | TrackedMultipleRetVals.insert( |
729 | KV: std::make_pair(x: std::make_pair(x&: F, y&: i), y: ValueLatticeElement())); |
730 | } else if (!F->getReturnType()->isVoidTy()) |
731 | TrackedRetVals.insert(KV: std::make_pair(x&: F, y: ValueLatticeElement())); |
732 | } |
733 | |
734 | void addToMustPreserveReturnsInFunctions(Function *F) { |
735 | MustPreserveReturnsInFunctions.insert(Ptr: F); |
736 | } |
737 | |
738 | bool mustPreserveReturn(Function *F) { |
739 | return MustPreserveReturnsInFunctions.count(Ptr: F); |
740 | } |
741 | |
742 | void addArgumentTrackedFunction(Function *F) { |
743 | TrackingIncomingArguments.insert(Ptr: F); |
744 | } |
745 | |
746 | bool isArgumentTrackedFunction(Function *F) { |
747 | return TrackingIncomingArguments.count(Ptr: F); |
748 | } |
749 | |
750 | void solve(); |
751 | |
752 | bool resolvedUndef(Instruction &I); |
753 | |
754 | bool resolvedUndefsIn(Function &F); |
755 | |
756 | bool isBlockExecutable(BasicBlock *BB) const { |
757 | return BBExecutable.count(Ptr: BB); |
758 | } |
759 | |
760 | bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const; |
761 | |
762 | std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const { |
763 | std::vector<ValueLatticeElement> StructValues; |
764 | auto *STy = dyn_cast<StructType>(Val: V->getType()); |
765 | assert(STy && "getStructLatticeValueFor() can be called only on structs" ); |
766 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
767 | auto I = StructValueState.find(Val: std::make_pair(x&: V, y&: i)); |
768 | assert(I != StructValueState.end() && "Value not in valuemap!" ); |
769 | StructValues.push_back(x: I->second); |
770 | } |
771 | return StructValues; |
772 | } |
773 | |
774 | void removeLatticeValueFor(Value *V) { ValueState.erase(Val: V); } |
775 | |
776 | /// Invalidate the Lattice Value of \p Call and its users after specializing |
777 | /// the call. Then recompute it. |
778 | void resetLatticeValueFor(CallBase *Call) { |
779 | // Calls to void returning functions do not need invalidation. |
780 | Function *F = Call->getCalledFunction(); |
781 | (void)F; |
782 | assert(!F->getReturnType()->isVoidTy() && |
783 | (TrackedRetVals.count(F) || MRVFunctionsTracked.count(F)) && |
784 | "All non void specializations should be tracked" ); |
785 | invalidate(Call); |
786 | handleCallResult(CB&: *Call); |
787 | } |
788 | |
789 | const ValueLatticeElement &getLatticeValueFor(Value *V) const { |
790 | assert(!V->getType()->isStructTy() && |
791 | "Should use getStructLatticeValueFor" ); |
792 | DenseMap<Value *, ValueLatticeElement>::const_iterator I = |
793 | ValueState.find(Val: V); |
794 | assert(I != ValueState.end() && |
795 | "V not found in ValueState nor Paramstate map!" ); |
796 | return I->second; |
797 | } |
798 | |
799 | const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() { |
800 | return TrackedRetVals; |
801 | } |
802 | |
803 | const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() { |
804 | return TrackedGlobals; |
805 | } |
806 | |
807 | const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() { |
808 | return MRVFunctionsTracked; |
809 | } |
810 | |
811 | void markOverdefined(Value *V) { |
812 | if (auto *STy = dyn_cast<StructType>(Val: V->getType())) |
813 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
814 | markOverdefined(IV&: getStructValueState(V, i), V); |
815 | else |
816 | markOverdefined(IV&: ValueState[V], V); |
817 | } |
818 | |
819 | void trackValueOfArgument(Argument *A) { |
820 | if (A->getType()->isIntegerTy()) { |
821 | if (std::optional<ConstantRange> Range = A->getRange()) { |
822 | markConstantRange(IV&: ValueState[A], V: A, CR: *Range); |
823 | return; |
824 | } |
825 | } |
826 | // Assume nothing about the incoming arguments without range. |
827 | markOverdefined(V: A); |
828 | } |
829 | |
830 | bool isStructLatticeConstant(Function *F, StructType *STy); |
831 | |
832 | Constant *getConstant(const ValueLatticeElement &LV, Type *Ty) const; |
833 | |
834 | Constant *getConstantOrNull(Value *V) const; |
835 | |
836 | SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() { |
837 | return TrackingIncomingArguments; |
838 | } |
839 | |
840 | void setLatticeValueForSpecializationArguments(Function *F, |
841 | const SmallVectorImpl<ArgInfo> &Args); |
842 | |
843 | void markFunctionUnreachable(Function *F) { |
844 | for (auto &BB : *F) |
845 | BBExecutable.erase(Ptr: &BB); |
846 | } |
847 | |
848 | void solveWhileResolvedUndefsIn(Module &M) { |
849 | bool ResolvedUndefs = true; |
850 | while (ResolvedUndefs) { |
851 | solve(); |
852 | ResolvedUndefs = false; |
853 | for (Function &F : M) |
854 | ResolvedUndefs |= resolvedUndefsIn(F); |
855 | } |
856 | } |
857 | |
858 | void solveWhileResolvedUndefsIn(SmallVectorImpl<Function *> &WorkList) { |
859 | bool ResolvedUndefs = true; |
860 | while (ResolvedUndefs) { |
861 | solve(); |
862 | ResolvedUndefs = false; |
863 | for (Function *F : WorkList) |
864 | ResolvedUndefs |= resolvedUndefsIn(F&: *F); |
865 | } |
866 | } |
867 | |
868 | void solveWhileResolvedUndefs() { |
869 | bool ResolvedUndefs = true; |
870 | while (ResolvedUndefs) { |
871 | solve(); |
872 | ResolvedUndefs = false; |
873 | for (Value *V : Invalidated) |
874 | if (auto *I = dyn_cast<Instruction>(Val: V)) |
875 | ResolvedUndefs |= resolvedUndef(I&: *I); |
876 | } |
877 | Invalidated.clear(); |
878 | } |
879 | }; |
880 | |
881 | } // namespace llvm |
882 | |
883 | bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) { |
884 | if (!BBExecutable.insert(Ptr: BB).second) |
885 | return false; |
886 | LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); |
887 | BBWorkList.push_back(Elt: BB); // Add the block to the work list! |
888 | return true; |
889 | } |
890 | |
891 | void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) { |
892 | if (IV.isOverdefined()) { |
893 | if (OverdefinedInstWorkList.empty() || OverdefinedInstWorkList.back() != V) |
894 | OverdefinedInstWorkList.push_back(Elt: V); |
895 | return; |
896 | } |
897 | if (InstWorkList.empty() || InstWorkList.back() != V) |
898 | InstWorkList.push_back(Elt: V); |
899 | } |
900 | |
901 | void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) { |
902 | LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n'); |
903 | pushToWorkList(IV, V); |
904 | } |
905 | |
906 | bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V, |
907 | Constant *C, bool MayIncludeUndef) { |
908 | if (!IV.markConstant(V: C, MayIncludeUndef)) |
909 | return false; |
910 | LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); |
911 | pushToWorkList(IV, V); |
912 | return true; |
913 | } |
914 | |
915 | bool SCCPInstVisitor::markConstantRange(ValueLatticeElement &IV, Value *V, |
916 | const ConstantRange &CR) { |
917 | if (!IV.markConstantRange(NewR: CR)) |
918 | return false; |
919 | LLVM_DEBUG(dbgs() << "markConstantRange: " << CR << ": " << *V << '\n'); |
920 | pushToWorkList(IV, V); |
921 | return true; |
922 | } |
923 | |
924 | bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) { |
925 | if (!IV.markOverdefined()) |
926 | return false; |
927 | |
928 | LLVM_DEBUG(dbgs() << "markOverdefined: " ; |
929 | if (auto *F = dyn_cast<Function>(V)) dbgs() |
930 | << "Function '" << F->getName() << "'\n" ; |
931 | else dbgs() << *V << '\n'); |
932 | // Only instructions go on the work list |
933 | pushToWorkList(IV, V); |
934 | return true; |
935 | } |
936 | |
937 | bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) { |
938 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
939 | const auto &It = TrackedMultipleRetVals.find(Key: std::make_pair(x&: F, y&: i)); |
940 | assert(It != TrackedMultipleRetVals.end()); |
941 | ValueLatticeElement LV = It->second; |
942 | if (!SCCPSolver::isConstant(LV)) |
943 | return false; |
944 | } |
945 | return true; |
946 | } |
947 | |
948 | Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV, |
949 | Type *Ty) const { |
950 | if (LV.isConstant()) { |
951 | Constant *C = LV.getConstant(); |
952 | assert(C->getType() == Ty && "Type mismatch" ); |
953 | return C; |
954 | } |
955 | |
956 | if (LV.isConstantRange()) { |
957 | const auto &CR = LV.getConstantRange(); |
958 | if (CR.getSingleElement()) |
959 | return ConstantInt::get(Ty, V: *CR.getSingleElement()); |
960 | } |
961 | return nullptr; |
962 | } |
963 | |
964 | Constant *SCCPInstVisitor::getConstantOrNull(Value *V) const { |
965 | Constant *Const = nullptr; |
966 | if (V->getType()->isStructTy()) { |
967 | std::vector<ValueLatticeElement> LVs = getStructLatticeValueFor(V); |
968 | if (any_of(Range&: LVs, P: SCCPSolver::isOverdefined)) |
969 | return nullptr; |
970 | std::vector<Constant *> ConstVals; |
971 | auto *ST = cast<StructType>(Val: V->getType()); |
972 | for (unsigned I = 0, E = ST->getNumElements(); I != E; ++I) { |
973 | ValueLatticeElement LV = LVs[I]; |
974 | ConstVals.push_back(x: SCCPSolver::isConstant(LV) |
975 | ? getConstant(LV, Ty: ST->getElementType(N: I)) |
976 | : UndefValue::get(T: ST->getElementType(N: I))); |
977 | } |
978 | Const = ConstantStruct::get(T: ST, V: ConstVals); |
979 | } else { |
980 | const ValueLatticeElement &LV = getLatticeValueFor(V); |
981 | if (SCCPSolver::isOverdefined(LV)) |
982 | return nullptr; |
983 | Const = SCCPSolver::isConstant(LV) ? getConstant(LV, Ty: V->getType()) |
984 | : UndefValue::get(T: V->getType()); |
985 | } |
986 | assert(Const && "Constant is nullptr here!" ); |
987 | return Const; |
988 | } |
989 | |
990 | void SCCPInstVisitor::setLatticeValueForSpecializationArguments(Function *F, |
991 | const SmallVectorImpl<ArgInfo> &Args) { |
992 | assert(!Args.empty() && "Specialization without arguments" ); |
993 | assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() && |
994 | "Functions should have the same number of arguments" ); |
995 | |
996 | auto Iter = Args.begin(); |
997 | Function::arg_iterator NewArg = F->arg_begin(); |
998 | Function::arg_iterator OldArg = Args[0].Formal->getParent()->arg_begin(); |
999 | for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) { |
1000 | |
1001 | LLVM_DEBUG(dbgs() << "SCCP: Marking argument " |
1002 | << NewArg->getNameOrAsOperand() << "\n" ); |
1003 | |
1004 | // Mark the argument constants in the new function |
1005 | // or copy the lattice state over from the old function. |
1006 | if (Iter != Args.end() && Iter->Formal == &*OldArg) { |
1007 | if (auto *STy = dyn_cast<StructType>(Val: NewArg->getType())) { |
1008 | for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) { |
1009 | ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}]; |
1010 | NewValue.markConstant(V: Iter->Actual->getAggregateElement(Elt: I)); |
1011 | } |
1012 | } else { |
1013 | ValueState[&*NewArg].markConstant(V: Iter->Actual); |
1014 | } |
1015 | ++Iter; |
1016 | } else { |
1017 | if (auto *STy = dyn_cast<StructType>(Val: NewArg->getType())) { |
1018 | for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) { |
1019 | ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}]; |
1020 | NewValue = StructValueState[{&*OldArg, I}]; |
1021 | } |
1022 | } else { |
1023 | ValueLatticeElement &NewValue = ValueState[&*NewArg]; |
1024 | NewValue = ValueState[&*OldArg]; |
1025 | } |
1026 | } |
1027 | } |
1028 | } |
1029 | |
1030 | void SCCPInstVisitor::visitInstruction(Instruction &I) { |
1031 | // All the instructions we don't do any special handling for just |
1032 | // go to overdefined. |
1033 | LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); |
1034 | markOverdefined(V: &I); |
1035 | } |
1036 | |
1037 | bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V, |
1038 | ValueLatticeElement MergeWithV, |
1039 | ValueLatticeElement::MergeOptions Opts) { |
1040 | if (IV.mergeIn(RHS: MergeWithV, Opts)) { |
1041 | pushToWorkList(IV, V); |
1042 | LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : " |
1043 | << IV << "\n" ); |
1044 | return true; |
1045 | } |
1046 | return false; |
1047 | } |
1048 | |
1049 | bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { |
1050 | if (!KnownFeasibleEdges.insert(V: Edge(Source, Dest)).second) |
1051 | return false; // This edge is already known to be executable! |
1052 | |
1053 | if (!markBlockExecutable(BB: Dest)) { |
1054 | // If the destination is already executable, we just made an *edge* |
1055 | // feasible that wasn't before. Revisit the PHI nodes in the block |
1056 | // because they have potentially new operands. |
1057 | LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() |
1058 | << " -> " << Dest->getName() << '\n'); |
1059 | |
1060 | for (PHINode &PN : Dest->phis()) |
1061 | visitPHINode(I&: PN); |
1062 | } |
1063 | return true; |
1064 | } |
1065 | |
1066 | // getFeasibleSuccessors - Return a vector of booleans to indicate which |
1067 | // successors are reachable from a given terminator instruction. |
1068 | void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI, |
1069 | SmallVectorImpl<bool> &Succs) { |
1070 | Succs.resize(N: TI.getNumSuccessors()); |
1071 | if (auto *BI = dyn_cast<BranchInst>(Val: &TI)) { |
1072 | if (BI->isUnconditional()) { |
1073 | Succs[0] = true; |
1074 | return; |
1075 | } |
1076 | |
1077 | ValueLatticeElement BCValue = getValueState(V: BI->getCondition()); |
1078 | ConstantInt *CI = getConstantInt(IV: BCValue, Ty: BI->getCondition()->getType()); |
1079 | if (!CI) { |
1080 | // Overdefined condition variables, and branches on unfoldable constant |
1081 | // conditions, mean the branch could go either way. |
1082 | if (!BCValue.isUnknownOrUndef()) |
1083 | Succs[0] = Succs[1] = true; |
1084 | return; |
1085 | } |
1086 | |
1087 | // Constant condition variables mean the branch can only go a single way. |
1088 | Succs[CI->isZero()] = true; |
1089 | return; |
1090 | } |
1091 | |
1092 | // We cannot analyze special terminators, so consider all successors |
1093 | // executable. |
1094 | if (TI.isSpecialTerminator()) { |
1095 | Succs.assign(NumElts: TI.getNumSuccessors(), Elt: true); |
1096 | return; |
1097 | } |
1098 | |
1099 | if (auto *SI = dyn_cast<SwitchInst>(Val: &TI)) { |
1100 | if (!SI->getNumCases()) { |
1101 | Succs[0] = true; |
1102 | return; |
1103 | } |
1104 | const ValueLatticeElement &SCValue = getValueState(V: SI->getCondition()); |
1105 | if (ConstantInt *CI = |
1106 | getConstantInt(IV: SCValue, Ty: SI->getCondition()->getType())) { |
1107 | Succs[SI->findCaseValue(C: CI)->getSuccessorIndex()] = true; |
1108 | return; |
1109 | } |
1110 | |
1111 | // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM |
1112 | // is ready. |
1113 | if (SCValue.isConstantRange(/*UndefAllowed=*/false)) { |
1114 | const ConstantRange &Range = SCValue.getConstantRange(); |
1115 | unsigned ReachableCaseCount = 0; |
1116 | for (const auto &Case : SI->cases()) { |
1117 | const APInt &CaseValue = Case.getCaseValue()->getValue(); |
1118 | if (Range.contains(Val: CaseValue)) { |
1119 | Succs[Case.getSuccessorIndex()] = true; |
1120 | ++ReachableCaseCount; |
1121 | } |
1122 | } |
1123 | |
1124 | Succs[SI->case_default()->getSuccessorIndex()] = |
1125 | Range.isSizeLargerThan(MaxSize: ReachableCaseCount); |
1126 | return; |
1127 | } |
1128 | |
1129 | // Overdefined or unknown condition? All destinations are executable! |
1130 | if (!SCValue.isUnknownOrUndef()) |
1131 | Succs.assign(NumElts: TI.getNumSuccessors(), Elt: true); |
1132 | return; |
1133 | } |
1134 | |
1135 | // In case of indirect branch and its address is a blockaddress, we mark |
1136 | // the target as executable. |
1137 | if (auto *IBR = dyn_cast<IndirectBrInst>(Val: &TI)) { |
1138 | // Casts are folded by visitCastInst. |
1139 | ValueLatticeElement IBRValue = getValueState(V: IBR->getAddress()); |
1140 | BlockAddress *Addr = dyn_cast_or_null<BlockAddress>( |
1141 | Val: getConstant(LV: IBRValue, Ty: IBR->getAddress()->getType())); |
1142 | if (!Addr) { // Overdefined or unknown condition? |
1143 | // All destinations are executable! |
1144 | if (!IBRValue.isUnknownOrUndef()) |
1145 | Succs.assign(NumElts: TI.getNumSuccessors(), Elt: true); |
1146 | return; |
1147 | } |
1148 | |
1149 | BasicBlock *T = Addr->getBasicBlock(); |
1150 | assert(Addr->getFunction() == T->getParent() && |
1151 | "Block address of a different function ?" ); |
1152 | for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) { |
1153 | // This is the target. |
1154 | if (IBR->getDestination(i) == T) { |
1155 | Succs[i] = true; |
1156 | return; |
1157 | } |
1158 | } |
1159 | |
1160 | // If we didn't find our destination in the IBR successor list, then we |
1161 | // have undefined behavior. Its ok to assume no successor is executable. |
1162 | return; |
1163 | } |
1164 | |
1165 | LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n'); |
1166 | llvm_unreachable("SCCP: Don't know how to handle this terminator!" ); |
1167 | } |
1168 | |
1169 | // isEdgeFeasible - Return true if the control flow edge from the 'From' basic |
1170 | // block to the 'To' basic block is currently feasible. |
1171 | bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const { |
1172 | // Check if we've called markEdgeExecutable on the edge yet. (We could |
1173 | // be more aggressive and try to consider edges which haven't been marked |
1174 | // yet, but there isn't any need.) |
1175 | return KnownFeasibleEdges.count(V: Edge(From, To)); |
1176 | } |
1177 | |
1178 | // visit Implementations - Something changed in this instruction, either an |
1179 | // operand made a transition, or the instruction is newly executable. Change |
1180 | // the value type of I to reflect these changes if appropriate. This method |
1181 | // makes sure to do the following actions: |
1182 | // |
1183 | // 1. If a phi node merges two constants in, and has conflicting value coming |
1184 | // from different branches, or if the PHI node merges in an overdefined |
1185 | // value, then the PHI node becomes overdefined. |
1186 | // 2. If a phi node merges only constants in, and they all agree on value, the |
1187 | // PHI node becomes a constant value equal to that. |
1188 | // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant |
1189 | // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined |
1190 | // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined |
1191 | // 6. If a conditional branch has a value that is constant, make the selected |
1192 | // destination executable |
1193 | // 7. If a conditional branch has a value that is overdefined, make all |
1194 | // successors executable. |
1195 | void SCCPInstVisitor::visitPHINode(PHINode &PN) { |
1196 | // If this PN returns a struct, just mark the result overdefined. |
1197 | // TODO: We could do a lot better than this if code actually uses this. |
1198 | if (PN.getType()->isStructTy()) |
1199 | return (void)markOverdefined(V: &PN); |
1200 | |
1201 | if (getValueState(V: &PN).isOverdefined()) |
1202 | return; // Quick exit |
1203 | |
1204 | // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, |
1205 | // and slow us down a lot. Just mark them overdefined. |
1206 | if (PN.getNumIncomingValues() > 64) |
1207 | return (void)markOverdefined(V: &PN); |
1208 | |
1209 | unsigned NumActiveIncoming = 0; |
1210 | |
1211 | // Look at all of the executable operands of the PHI node. If any of them |
1212 | // are overdefined, the PHI becomes overdefined as well. If they are all |
1213 | // constant, and they agree with each other, the PHI becomes the identical |
1214 | // constant. If they are constant and don't agree, the PHI is a constant |
1215 | // range. If there are no executable operands, the PHI remains unknown. |
1216 | ValueLatticeElement PhiState = getValueState(V: &PN); |
1217 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { |
1218 | if (!isEdgeFeasible(From: PN.getIncomingBlock(i), To: PN.getParent())) |
1219 | continue; |
1220 | |
1221 | ValueLatticeElement IV = getValueState(V: PN.getIncomingValue(i)); |
1222 | PhiState.mergeIn(RHS: IV); |
1223 | NumActiveIncoming++; |
1224 | if (PhiState.isOverdefined()) |
1225 | break; |
1226 | } |
1227 | |
1228 | // We allow up to 1 range extension per active incoming value and one |
1229 | // additional extension. Note that we manually adjust the number of range |
1230 | // extensions to match the number of active incoming values. This helps to |
1231 | // limit multiple extensions caused by the same incoming value, if other |
1232 | // incoming values are equal. |
1233 | mergeInValue(V: &PN, MergeWithV: PhiState, |
1234 | Opts: ValueLatticeElement::MergeOptions().setMaxWidenSteps( |
1235 | NumActiveIncoming + 1)); |
1236 | ValueLatticeElement &PhiStateRef = getValueState(V: &PN); |
1237 | PhiStateRef.setNumRangeExtensions( |
1238 | std::max(a: NumActiveIncoming, b: PhiStateRef.getNumRangeExtensions())); |
1239 | } |
1240 | |
1241 | void SCCPInstVisitor::visitReturnInst(ReturnInst &I) { |
1242 | if (I.getNumOperands() == 0) |
1243 | return; // ret void |
1244 | |
1245 | Function *F = I.getParent()->getParent(); |
1246 | Value *ResultOp = I.getOperand(i_nocapture: 0); |
1247 | |
1248 | // If we are tracking the return value of this function, merge it in. |
1249 | if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) { |
1250 | auto TFRVI = TrackedRetVals.find(Key: F); |
1251 | if (TFRVI != TrackedRetVals.end()) { |
1252 | mergeInValue(IV&: TFRVI->second, V: F, MergeWithV: getValueState(V: ResultOp)); |
1253 | return; |
1254 | } |
1255 | } |
1256 | |
1257 | // Handle functions that return multiple values. |
1258 | if (!TrackedMultipleRetVals.empty()) { |
1259 | if (auto *STy = dyn_cast<StructType>(Val: ResultOp->getType())) |
1260 | if (MRVFunctionsTracked.count(Ptr: F)) |
1261 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
1262 | mergeInValue(IV&: TrackedMultipleRetVals[std::make_pair(x&: F, y&: i)], V: F, |
1263 | MergeWithV: getStructValueState(V: ResultOp, i)); |
1264 | } |
1265 | } |
1266 | |
1267 | void SCCPInstVisitor::visitTerminator(Instruction &TI) { |
1268 | SmallVector<bool, 16> SuccFeasible; |
1269 | getFeasibleSuccessors(TI, Succs&: SuccFeasible); |
1270 | |
1271 | BasicBlock *BB = TI.getParent(); |
1272 | |
1273 | // Mark all feasible successors executable. |
1274 | for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) |
1275 | if (SuccFeasible[i]) |
1276 | markEdgeExecutable(Source: BB, Dest: TI.getSuccessor(Idx: i)); |
1277 | } |
1278 | |
1279 | void SCCPInstVisitor::visitCastInst(CastInst &I) { |
1280 | // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1281 | // discover a concrete value later. |
1282 | if (ValueState[&I].isOverdefined()) |
1283 | return; |
1284 | |
1285 | ValueLatticeElement OpSt = getValueState(V: I.getOperand(i_nocapture: 0)); |
1286 | if (OpSt.isUnknownOrUndef()) |
1287 | return; |
1288 | |
1289 | if (Constant *OpC = getConstant(LV: OpSt, Ty: I.getOperand(i_nocapture: 0)->getType())) { |
1290 | // Fold the constant as we build. |
1291 | if (Constant *C = |
1292 | ConstantFoldCastOperand(Opcode: I.getOpcode(), C: OpC, DestTy: I.getType(), DL)) |
1293 | return (void)markConstant(V: &I, C); |
1294 | } |
1295 | |
1296 | if (I.getDestTy()->isIntegerTy() && I.getSrcTy()->isIntOrIntVectorTy()) { |
1297 | auto &LV = getValueState(V: &I); |
1298 | ConstantRange OpRange = getConstantRange(LV: OpSt, Ty: I.getSrcTy()); |
1299 | |
1300 | Type *DestTy = I.getDestTy(); |
1301 | // Vectors where all elements have the same known constant range are treated |
1302 | // as a single constant range in the lattice. When bitcasting such vectors, |
1303 | // there is a mis-match between the width of the lattice value (single |
1304 | // constant range) and the original operands (vector). Go to overdefined in |
1305 | // that case. |
1306 | if (I.getOpcode() == Instruction::BitCast && |
1307 | I.getOperand(i_nocapture: 0)->getType()->isVectorTy() && |
1308 | OpRange.getBitWidth() < DL.getTypeSizeInBits(Ty: DestTy)) |
1309 | return (void)markOverdefined(V: &I); |
1310 | |
1311 | ConstantRange Res = |
1312 | OpRange.castOp(CastOp: I.getOpcode(), BitWidth: DL.getTypeSizeInBits(Ty: DestTy)); |
1313 | mergeInValue(IV&: LV, V: &I, MergeWithV: ValueLatticeElement::getRange(CR: Res)); |
1314 | } else |
1315 | markOverdefined(V: &I); |
1316 | } |
1317 | |
1318 | void SCCPInstVisitor::handleExtractOfWithOverflow(ExtractValueInst &EVI, |
1319 | const WithOverflowInst *WO, |
1320 | unsigned Idx) { |
1321 | Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); |
1322 | ValueLatticeElement L = getValueState(V: LHS); |
1323 | ValueLatticeElement R = getValueState(V: RHS); |
1324 | addAdditionalUser(V: LHS, U: &EVI); |
1325 | addAdditionalUser(V: RHS, U: &EVI); |
1326 | if (L.isUnknownOrUndef() || R.isUnknownOrUndef()) |
1327 | return; // Wait to resolve. |
1328 | |
1329 | Type *Ty = LHS->getType(); |
1330 | ConstantRange LR = getConstantRange(LV: L, Ty); |
1331 | ConstantRange RR = getConstantRange(LV: R, Ty); |
1332 | if (Idx == 0) { |
1333 | ConstantRange Res = LR.binaryOp(BinOp: WO->getBinaryOp(), Other: RR); |
1334 | mergeInValue(V: &EVI, MergeWithV: ValueLatticeElement::getRange(CR: Res)); |
1335 | } else { |
1336 | assert(Idx == 1 && "Index can only be 0 or 1" ); |
1337 | ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
1338 | BinOp: WO->getBinaryOp(), Other: RR, NoWrapKind: WO->getNoWrapKind()); |
1339 | if (NWRegion.contains(CR: LR)) |
1340 | return (void)markConstant(V: &EVI, C: ConstantInt::getFalse(Ty: EVI.getType())); |
1341 | markOverdefined(V: &EVI); |
1342 | } |
1343 | } |
1344 | |
1345 | void SCCPInstVisitor::(ExtractValueInst &EVI) { |
1346 | // If this returns a struct, mark all elements over defined, we don't track |
1347 | // structs in structs. |
1348 | if (EVI.getType()->isStructTy()) |
1349 | return (void)markOverdefined(V: &EVI); |
1350 | |
1351 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1352 | // discover a concrete value later. |
1353 | if (ValueState[&EVI].isOverdefined()) |
1354 | return (void)markOverdefined(V: &EVI); |
1355 | |
1356 | // If this is extracting from more than one level of struct, we don't know. |
1357 | if (EVI.getNumIndices() != 1) |
1358 | return (void)markOverdefined(V: &EVI); |
1359 | |
1360 | Value *AggVal = EVI.getAggregateOperand(); |
1361 | if (AggVal->getType()->isStructTy()) { |
1362 | unsigned i = *EVI.idx_begin(); |
1363 | if (auto *WO = dyn_cast<WithOverflowInst>(Val: AggVal)) |
1364 | return handleExtractOfWithOverflow(EVI, WO, Idx: i); |
1365 | ValueLatticeElement EltVal = getStructValueState(V: AggVal, i); |
1366 | mergeInValue(IV&: getValueState(V: &EVI), V: &EVI, MergeWithV: EltVal); |
1367 | } else { |
1368 | // Otherwise, must be extracting from an array. |
1369 | return (void)markOverdefined(V: &EVI); |
1370 | } |
1371 | } |
1372 | |
1373 | void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) { |
1374 | auto *STy = dyn_cast<StructType>(Val: IVI.getType()); |
1375 | if (!STy) |
1376 | return (void)markOverdefined(V: &IVI); |
1377 | |
1378 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1379 | // discover a concrete value later. |
1380 | if (SCCPSolver::isOverdefined(LV: ValueState[&IVI])) |
1381 | return (void)markOverdefined(V: &IVI); |
1382 | |
1383 | // If this has more than one index, we can't handle it, drive all results to |
1384 | // undef. |
1385 | if (IVI.getNumIndices() != 1) |
1386 | return (void)markOverdefined(V: &IVI); |
1387 | |
1388 | Value *Aggr = IVI.getAggregateOperand(); |
1389 | unsigned Idx = *IVI.idx_begin(); |
1390 | |
1391 | // Compute the result based on what we're inserting. |
1392 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
1393 | // This passes through all values that aren't the inserted element. |
1394 | if (i != Idx) { |
1395 | ValueLatticeElement EltVal = getStructValueState(V: Aggr, i); |
1396 | mergeInValue(IV&: getStructValueState(V: &IVI, i), V: &IVI, MergeWithV: EltVal); |
1397 | continue; |
1398 | } |
1399 | |
1400 | Value *Val = IVI.getInsertedValueOperand(); |
1401 | if (Val->getType()->isStructTy()) |
1402 | // We don't track structs in structs. |
1403 | markOverdefined(IV&: getStructValueState(V: &IVI, i), V: &IVI); |
1404 | else { |
1405 | ValueLatticeElement InVal = getValueState(V: Val); |
1406 | mergeInValue(IV&: getStructValueState(V: &IVI, i), V: &IVI, MergeWithV: InVal); |
1407 | } |
1408 | } |
1409 | } |
1410 | |
1411 | void SCCPInstVisitor::visitSelectInst(SelectInst &I) { |
1412 | // If this select returns a struct, just mark the result overdefined. |
1413 | // TODO: We could do a lot better than this if code actually uses this. |
1414 | if (I.getType()->isStructTy()) |
1415 | return (void)markOverdefined(V: &I); |
1416 | |
1417 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1418 | // discover a concrete value later. |
1419 | if (ValueState[&I].isOverdefined()) |
1420 | return (void)markOverdefined(V: &I); |
1421 | |
1422 | ValueLatticeElement CondValue = getValueState(V: I.getCondition()); |
1423 | if (CondValue.isUnknownOrUndef()) |
1424 | return; |
1425 | |
1426 | if (ConstantInt *CondCB = |
1427 | getConstantInt(IV: CondValue, Ty: I.getCondition()->getType())) { |
1428 | Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue(); |
1429 | mergeInValue(V: &I, MergeWithV: getValueState(V: OpVal)); |
1430 | return; |
1431 | } |
1432 | |
1433 | // Otherwise, the condition is overdefined or a constant we can't evaluate. |
1434 | // See if we can produce something better than overdefined based on the T/F |
1435 | // value. |
1436 | ValueLatticeElement TVal = getValueState(V: I.getTrueValue()); |
1437 | ValueLatticeElement FVal = getValueState(V: I.getFalseValue()); |
1438 | |
1439 | bool Changed = ValueState[&I].mergeIn(RHS: TVal); |
1440 | Changed |= ValueState[&I].mergeIn(RHS: FVal); |
1441 | if (Changed) |
1442 | pushToWorkListMsg(IV&: ValueState[&I], V: &I); |
1443 | } |
1444 | |
1445 | // Handle Unary Operators. |
1446 | void SCCPInstVisitor::visitUnaryOperator(Instruction &I) { |
1447 | ValueLatticeElement V0State = getValueState(V: I.getOperand(i: 0)); |
1448 | |
1449 | ValueLatticeElement &IV = ValueState[&I]; |
1450 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1451 | // discover a concrete value later. |
1452 | if (SCCPSolver::isOverdefined(LV: IV)) |
1453 | return (void)markOverdefined(V: &I); |
1454 | |
1455 | // If something is unknown/undef, wait for it to resolve. |
1456 | if (V0State.isUnknownOrUndef()) |
1457 | return; |
1458 | |
1459 | if (SCCPSolver::isConstant(LV: V0State)) |
1460 | if (Constant *C = ConstantFoldUnaryOpOperand( |
1461 | Opcode: I.getOpcode(), Op: getConstant(LV: V0State, Ty: I.getType()), DL)) |
1462 | return (void)markConstant(IV, V: &I, C); |
1463 | |
1464 | markOverdefined(V: &I); |
1465 | } |
1466 | |
1467 | void SCCPInstVisitor::visitFreezeInst(FreezeInst &I) { |
1468 | // If this freeze returns a struct, just mark the result overdefined. |
1469 | // TODO: We could do a lot better than this. |
1470 | if (I.getType()->isStructTy()) |
1471 | return (void)markOverdefined(V: &I); |
1472 | |
1473 | ValueLatticeElement V0State = getValueState(V: I.getOperand(i_nocapture: 0)); |
1474 | ValueLatticeElement &IV = ValueState[&I]; |
1475 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1476 | // discover a concrete value later. |
1477 | if (SCCPSolver::isOverdefined(LV: IV)) |
1478 | return (void)markOverdefined(V: &I); |
1479 | |
1480 | // If something is unknown/undef, wait for it to resolve. |
1481 | if (V0State.isUnknownOrUndef()) |
1482 | return; |
1483 | |
1484 | if (SCCPSolver::isConstant(LV: V0State) && |
1485 | isGuaranteedNotToBeUndefOrPoison(V: getConstant(LV: V0State, Ty: I.getType()))) |
1486 | return (void)markConstant(IV, V: &I, C: getConstant(LV: V0State, Ty: I.getType())); |
1487 | |
1488 | markOverdefined(V: &I); |
1489 | } |
1490 | |
1491 | // Handle Binary Operators. |
1492 | void SCCPInstVisitor::visitBinaryOperator(Instruction &I) { |
1493 | ValueLatticeElement V1State = getValueState(V: I.getOperand(i: 0)); |
1494 | ValueLatticeElement V2State = getValueState(V: I.getOperand(i: 1)); |
1495 | |
1496 | ValueLatticeElement &IV = ValueState[&I]; |
1497 | if (IV.isOverdefined()) |
1498 | return; |
1499 | |
1500 | // If something is undef, wait for it to resolve. |
1501 | if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) |
1502 | return; |
1503 | |
1504 | if (V1State.isOverdefined() && V2State.isOverdefined()) |
1505 | return (void)markOverdefined(V: &I); |
1506 | |
1507 | // If either of the operands is a constant, try to fold it to a constant. |
1508 | // TODO: Use information from notconstant better. |
1509 | if ((V1State.isConstant() || V2State.isConstant())) { |
1510 | Value *V1 = SCCPSolver::isConstant(LV: V1State) |
1511 | ? getConstant(LV: V1State, Ty: I.getOperand(i: 0)->getType()) |
1512 | : I.getOperand(i: 0); |
1513 | Value *V2 = SCCPSolver::isConstant(LV: V2State) |
1514 | ? getConstant(LV: V2State, Ty: I.getOperand(i: 1)->getType()) |
1515 | : I.getOperand(i: 1); |
1516 | Value *R = simplifyBinOp(Opcode: I.getOpcode(), LHS: V1, RHS: V2, Q: SimplifyQuery(DL)); |
1517 | auto *C = dyn_cast_or_null<Constant>(Val: R); |
1518 | if (C) { |
1519 | // Conservatively assume that the result may be based on operands that may |
1520 | // be undef. Note that we use mergeInValue to combine the constant with |
1521 | // the existing lattice value for I, as different constants might be found |
1522 | // after one of the operands go to overdefined, e.g. due to one operand |
1523 | // being a special floating value. |
1524 | ValueLatticeElement NewV; |
1525 | NewV.markConstant(V: C, /*MayIncludeUndef=*/true); |
1526 | return (void)mergeInValue(V: &I, MergeWithV: NewV); |
1527 | } |
1528 | } |
1529 | |
1530 | // Only use ranges for binary operators on integers. |
1531 | if (!I.getType()->isIntegerTy()) |
1532 | return markOverdefined(V: &I); |
1533 | |
1534 | // Try to simplify to a constant range. |
1535 | ConstantRange A = getConstantRange(LV: V1State, Ty: I.getType()); |
1536 | ConstantRange B = getConstantRange(LV: V2State, Ty: I.getType()); |
1537 | |
1538 | auto *BO = cast<BinaryOperator>(Val: &I); |
1539 | ConstantRange R = ConstantRange::getEmpty(BitWidth: I.getType()->getScalarSizeInBits()); |
1540 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: BO)) |
1541 | R = A.overflowingBinaryOp(BinOp: BO->getOpcode(), Other: B, NoWrapKind: OBO->getNoWrapKind()); |
1542 | else |
1543 | R = A.binaryOp(BinOp: BO->getOpcode(), Other: B); |
1544 | mergeInValue(V: &I, MergeWithV: ValueLatticeElement::getRange(CR: R)); |
1545 | |
1546 | // TODO: Currently we do not exploit special values that produce something |
1547 | // better than overdefined with an overdefined operand for vector or floating |
1548 | // point types, like and <4 x i32> overdefined, zeroinitializer. |
1549 | } |
1550 | |
1551 | // Handle ICmpInst instruction. |
1552 | void SCCPInstVisitor::visitCmpInst(CmpInst &I) { |
1553 | // Do not cache this lookup, getValueState calls later in the function might |
1554 | // invalidate the reference. |
1555 | if (SCCPSolver::isOverdefined(LV: ValueState[&I])) |
1556 | return (void)markOverdefined(V: &I); |
1557 | |
1558 | Value *Op1 = I.getOperand(i_nocapture: 0); |
1559 | Value *Op2 = I.getOperand(i_nocapture: 1); |
1560 | |
1561 | // For parameters, use ParamState which includes constant range info if |
1562 | // available. |
1563 | auto V1State = getValueState(V: Op1); |
1564 | auto V2State = getValueState(V: Op2); |
1565 | |
1566 | Constant *C = V1State.getCompare(Pred: I.getPredicate(), Ty: I.getType(), Other: V2State, DL); |
1567 | if (C) { |
1568 | ValueLatticeElement CV; |
1569 | CV.markConstant(V: C); |
1570 | mergeInValue(V: &I, MergeWithV: CV); |
1571 | return; |
1572 | } |
1573 | |
1574 | // If operands are still unknown, wait for it to resolve. |
1575 | if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) && |
1576 | !SCCPSolver::isConstant(LV: ValueState[&I])) |
1577 | return; |
1578 | |
1579 | markOverdefined(V: &I); |
1580 | } |
1581 | |
1582 | // Handle getelementptr instructions. If all operands are constants then we |
1583 | // can turn this into a getelementptr ConstantExpr. |
1584 | void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) { |
1585 | if (SCCPSolver::isOverdefined(LV: ValueState[&I])) |
1586 | return (void)markOverdefined(V: &I); |
1587 | |
1588 | SmallVector<Constant *, 8> Operands; |
1589 | Operands.reserve(N: I.getNumOperands()); |
1590 | |
1591 | for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { |
1592 | ValueLatticeElement State = getValueState(V: I.getOperand(i_nocapture: i)); |
1593 | if (State.isUnknownOrUndef()) |
1594 | return; // Operands are not resolved yet. |
1595 | |
1596 | if (SCCPSolver::isOverdefined(LV: State)) |
1597 | return (void)markOverdefined(V: &I); |
1598 | |
1599 | if (Constant *C = getConstant(LV: State, Ty: I.getOperand(i_nocapture: i)->getType())) { |
1600 | Operands.push_back(Elt: C); |
1601 | continue; |
1602 | } |
1603 | |
1604 | return (void)markOverdefined(V: &I); |
1605 | } |
1606 | |
1607 | if (Constant *C = ConstantFoldInstOperands(I: &I, Ops: Operands, DL)) |
1608 | markConstant(V: &I, C); |
1609 | } |
1610 | |
1611 | void SCCPInstVisitor::visitStoreInst(StoreInst &SI) { |
1612 | // If this store is of a struct, ignore it. |
1613 | if (SI.getOperand(i_nocapture: 0)->getType()->isStructTy()) |
1614 | return; |
1615 | |
1616 | if (TrackedGlobals.empty() || !isa<GlobalVariable>(Val: SI.getOperand(i_nocapture: 1))) |
1617 | return; |
1618 | |
1619 | GlobalVariable *GV = cast<GlobalVariable>(Val: SI.getOperand(i_nocapture: 1)); |
1620 | auto I = TrackedGlobals.find(Val: GV); |
1621 | if (I == TrackedGlobals.end()) |
1622 | return; |
1623 | |
1624 | // Get the value we are storing into the global, then merge it. |
1625 | mergeInValue(IV&: I->second, V: GV, MergeWithV: getValueState(V: SI.getOperand(i_nocapture: 0)), |
1626 | Opts: ValueLatticeElement::MergeOptions().setCheckWiden(false)); |
1627 | if (I->second.isOverdefined()) |
1628 | TrackedGlobals.erase(I); // No need to keep tracking this! |
1629 | } |
1630 | |
1631 | static ValueLatticeElement getValueFromMetadata(const Instruction *I) { |
1632 | if (I->getType()->isIntegerTy()) { |
1633 | if (MDNode *Ranges = I->getMetadata(KindID: LLVMContext::MD_range)) |
1634 | return ValueLatticeElement::getRange( |
1635 | CR: getConstantRangeFromMetadata(RangeMD: *Ranges)); |
1636 | |
1637 | if (const auto *CB = dyn_cast<CallBase>(Val: I)) |
1638 | if (std::optional<ConstantRange> Range = CB->getRange()) |
1639 | return ValueLatticeElement::getRange(CR: *Range); |
1640 | } |
1641 | if (I->hasMetadata(KindID: LLVMContext::MD_nonnull)) |
1642 | return ValueLatticeElement::getNot( |
1643 | C: ConstantPointerNull::get(T: cast<PointerType>(Val: I->getType()))); |
1644 | return ValueLatticeElement::getOverdefined(); |
1645 | } |
1646 | |
1647 | // Handle load instructions. If the operand is a constant pointer to a constant |
1648 | // global, we can replace the load with the loaded constant value! |
1649 | void SCCPInstVisitor::visitLoadInst(LoadInst &I) { |
1650 | // If this load is of a struct or the load is volatile, just mark the result |
1651 | // as overdefined. |
1652 | if (I.getType()->isStructTy() || I.isVolatile()) |
1653 | return (void)markOverdefined(V: &I); |
1654 | |
1655 | // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would |
1656 | // discover a concrete value later. |
1657 | if (ValueState[&I].isOverdefined()) |
1658 | return (void)markOverdefined(V: &I); |
1659 | |
1660 | ValueLatticeElement PtrVal = getValueState(V: I.getOperand(i_nocapture: 0)); |
1661 | if (PtrVal.isUnknownOrUndef()) |
1662 | return; // The pointer is not resolved yet! |
1663 | |
1664 | ValueLatticeElement &IV = ValueState[&I]; |
1665 | |
1666 | if (SCCPSolver::isConstant(LV: PtrVal)) { |
1667 | Constant *Ptr = getConstant(LV: PtrVal, Ty: I.getOperand(i_nocapture: 0)->getType()); |
1668 | |
1669 | // load null is undefined. |
1670 | if (isa<ConstantPointerNull>(Val: Ptr)) { |
1671 | if (NullPointerIsDefined(F: I.getFunction(), AS: I.getPointerAddressSpace())) |
1672 | return (void)markOverdefined(IV, V: &I); |
1673 | else |
1674 | return; |
1675 | } |
1676 | |
1677 | // Transform load (constant global) into the value loaded. |
1678 | if (auto *GV = dyn_cast<GlobalVariable>(Val: Ptr)) { |
1679 | if (!TrackedGlobals.empty()) { |
1680 | // If we are tracking this global, merge in the known value for it. |
1681 | auto It = TrackedGlobals.find(Val: GV); |
1682 | if (It != TrackedGlobals.end()) { |
1683 | mergeInValue(IV, V: &I, MergeWithV: It->second, Opts: getMaxWidenStepsOpts()); |
1684 | return; |
1685 | } |
1686 | } |
1687 | } |
1688 | |
1689 | // Transform load from a constant into a constant if possible. |
1690 | if (Constant *C = ConstantFoldLoadFromConstPtr(C: Ptr, Ty: I.getType(), DL)) |
1691 | return (void)markConstant(IV, V: &I, C); |
1692 | } |
1693 | |
1694 | // Fall back to metadata. |
1695 | mergeInValue(V: &I, MergeWithV: getValueFromMetadata(I: &I)); |
1696 | } |
1697 | |
1698 | void SCCPInstVisitor::visitCallBase(CallBase &CB) { |
1699 | handleCallResult(CB); |
1700 | handleCallArguments(CB); |
1701 | } |
1702 | |
1703 | void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) { |
1704 | Function *F = CB.getCalledFunction(); |
1705 | |
1706 | // Void return and not tracking callee, just bail. |
1707 | if (CB.getType()->isVoidTy()) |
1708 | return; |
1709 | |
1710 | // Always mark struct return as overdefined. |
1711 | if (CB.getType()->isStructTy()) |
1712 | return (void)markOverdefined(V: &CB); |
1713 | |
1714 | // Otherwise, if we have a single return value case, and if the function is |
1715 | // a declaration, maybe we can constant fold it. |
1716 | if (F && F->isDeclaration() && canConstantFoldCallTo(Call: &CB, F)) { |
1717 | SmallVector<Constant *, 8> Operands; |
1718 | for (const Use &A : CB.args()) { |
1719 | if (A.get()->getType()->isStructTy()) |
1720 | return markOverdefined(V: &CB); // Can't handle struct args. |
1721 | if (A.get()->getType()->isMetadataTy()) |
1722 | continue; // Carried in CB, not allowed in Operands. |
1723 | ValueLatticeElement State = getValueState(V: A); |
1724 | |
1725 | if (State.isUnknownOrUndef()) |
1726 | return; // Operands are not resolved yet. |
1727 | if (SCCPSolver::isOverdefined(LV: State)) |
1728 | return (void)markOverdefined(V: &CB); |
1729 | assert(SCCPSolver::isConstant(State) && "Unknown state!" ); |
1730 | Operands.push_back(Elt: getConstant(LV: State, Ty: A->getType())); |
1731 | } |
1732 | |
1733 | if (SCCPSolver::isOverdefined(LV: getValueState(V: &CB))) |
1734 | return (void)markOverdefined(V: &CB); |
1735 | |
1736 | // If we can constant fold this, mark the result of the call as a |
1737 | // constant. |
1738 | if (Constant *C = ConstantFoldCall(Call: &CB, F, Operands, TLI: &GetTLI(*F))) |
1739 | return (void)markConstant(V: &CB, C); |
1740 | } |
1741 | |
1742 | // Fall back to metadata. |
1743 | mergeInValue(V: &CB, MergeWithV: getValueFromMetadata(I: &CB)); |
1744 | } |
1745 | |
1746 | void SCCPInstVisitor::handleCallArguments(CallBase &CB) { |
1747 | Function *F = CB.getCalledFunction(); |
1748 | // If this is a local function that doesn't have its address taken, mark its |
1749 | // entry block executable and merge in the actual arguments to the call into |
1750 | // the formal arguments of the function. |
1751 | if (TrackingIncomingArguments.count(Ptr: F)) { |
1752 | markBlockExecutable(BB: &F->front()); |
1753 | |
1754 | // Propagate information from this call site into the callee. |
1755 | auto CAI = CB.arg_begin(); |
1756 | for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; |
1757 | ++AI, ++CAI) { |
1758 | // If this argument is byval, and if the function is not readonly, there |
1759 | // will be an implicit copy formed of the input aggregate. |
1760 | if (AI->hasByValAttr() && !F->onlyReadsMemory()) { |
1761 | markOverdefined(V: &*AI); |
1762 | continue; |
1763 | } |
1764 | |
1765 | if (auto *STy = dyn_cast<StructType>(Val: AI->getType())) { |
1766 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
1767 | ValueLatticeElement CallArg = getStructValueState(V: *CAI, i); |
1768 | mergeInValue(IV&: getStructValueState(V: &*AI, i), V: &*AI, MergeWithV: CallArg, |
1769 | Opts: getMaxWidenStepsOpts()); |
1770 | } |
1771 | } else |
1772 | mergeInValue(V: &*AI, MergeWithV: getValueState(V: *CAI), Opts: getMaxWidenStepsOpts()); |
1773 | } |
1774 | } |
1775 | } |
1776 | |
1777 | void SCCPInstVisitor::handleCallResult(CallBase &CB) { |
1778 | Function *F = CB.getCalledFunction(); |
1779 | |
1780 | if (auto *II = dyn_cast<IntrinsicInst>(Val: &CB)) { |
1781 | if (II->getIntrinsicID() == Intrinsic::ssa_copy) { |
1782 | if (ValueState[&CB].isOverdefined()) |
1783 | return; |
1784 | |
1785 | Value *CopyOf = CB.getOperand(i_nocapture: 0); |
1786 | ValueLatticeElement CopyOfVal = getValueState(V: CopyOf); |
1787 | const auto *PI = getPredicateInfoFor(I: &CB); |
1788 | assert(PI && "Missing predicate info for ssa.copy" ); |
1789 | |
1790 | const std::optional<PredicateConstraint> &Constraint = |
1791 | PI->getConstraint(); |
1792 | if (!Constraint) { |
1793 | mergeInValue(IV&: ValueState[&CB], V: &CB, MergeWithV: CopyOfVal); |
1794 | return; |
1795 | } |
1796 | |
1797 | CmpInst::Predicate Pred = Constraint->Predicate; |
1798 | Value *OtherOp = Constraint->OtherOp; |
1799 | |
1800 | // Wait until OtherOp is resolved. |
1801 | if (getValueState(V: OtherOp).isUnknown()) { |
1802 | addAdditionalUser(V: OtherOp, U: &CB); |
1803 | return; |
1804 | } |
1805 | |
1806 | ValueLatticeElement CondVal = getValueState(V: OtherOp); |
1807 | ValueLatticeElement &IV = ValueState[&CB]; |
1808 | if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) { |
1809 | auto ImposedCR = |
1810 | ConstantRange::getFull(BitWidth: DL.getTypeSizeInBits(Ty: CopyOf->getType())); |
1811 | |
1812 | // Get the range imposed by the condition. |
1813 | if (CondVal.isConstantRange()) |
1814 | ImposedCR = ConstantRange::makeAllowedICmpRegion( |
1815 | Pred, Other: CondVal.getConstantRange()); |
1816 | |
1817 | // Combine range info for the original value with the new range from the |
1818 | // condition. |
1819 | auto CopyOfCR = getConstantRange(LV: CopyOfVal, Ty: CopyOf->getType()); |
1820 | auto NewCR = ImposedCR.intersectWith(CR: CopyOfCR); |
1821 | // If the existing information is != x, do not use the information from |
1822 | // a chained predicate, as the != x information is more likely to be |
1823 | // helpful in practice. |
1824 | if (!CopyOfCR.contains(CR: NewCR) && CopyOfCR.getSingleMissingElement()) |
1825 | NewCR = CopyOfCR; |
1826 | |
1827 | // The new range is based on a branch condition. That guarantees that |
1828 | // neither of the compare operands can be undef in the branch targets, |
1829 | // unless we have conditions that are always true/false (e.g. icmp ule |
1830 | // i32, %a, i32_max). For the latter overdefined/empty range will be |
1831 | // inferred, but the branch will get folded accordingly anyways. |
1832 | addAdditionalUser(V: OtherOp, U: &CB); |
1833 | mergeInValue( |
1834 | IV, V: &CB, |
1835 | MergeWithV: ValueLatticeElement::getRange(CR: NewCR, /*MayIncludeUndef*/ false)); |
1836 | return; |
1837 | } else if (Pred == CmpInst::ICMP_EQ && |
1838 | (CondVal.isConstant() || CondVal.isNotConstant())) { |
1839 | // For non-integer values or integer constant expressions, only |
1840 | // propagate equal constants or not-constants. |
1841 | addAdditionalUser(V: OtherOp, U: &CB); |
1842 | mergeInValue(IV, V: &CB, MergeWithV: CondVal); |
1843 | return; |
1844 | } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) { |
1845 | // Propagate inequalities. |
1846 | addAdditionalUser(V: OtherOp, U: &CB); |
1847 | mergeInValue(IV, V: &CB, |
1848 | MergeWithV: ValueLatticeElement::getNot(C: CondVal.getConstant())); |
1849 | return; |
1850 | } |
1851 | |
1852 | return (void)mergeInValue(IV, V: &CB, MergeWithV: CopyOfVal); |
1853 | } |
1854 | |
1855 | if (ConstantRange::isIntrinsicSupported(IntrinsicID: II->getIntrinsicID())) { |
1856 | // Compute result range for intrinsics supported by ConstantRange. |
1857 | // Do this even if we don't know a range for all operands, as we may |
1858 | // still know something about the result range, e.g. of abs(x). |
1859 | SmallVector<ConstantRange, 2> OpRanges; |
1860 | for (Value *Op : II->args()) { |
1861 | const ValueLatticeElement &State = getValueState(V: Op); |
1862 | if (State.isUnknownOrUndef()) |
1863 | return; |
1864 | OpRanges.push_back(Elt: getConstantRange(LV: State, Ty: Op->getType())); |
1865 | } |
1866 | |
1867 | ConstantRange Result = |
1868 | ConstantRange::intrinsic(IntrinsicID: II->getIntrinsicID(), Ops: OpRanges); |
1869 | return (void)mergeInValue(V: II, MergeWithV: ValueLatticeElement::getRange(CR: Result)); |
1870 | } |
1871 | } |
1872 | |
1873 | // The common case is that we aren't tracking the callee, either because we |
1874 | // are not doing interprocedural analysis or the callee is indirect, or is |
1875 | // external. Handle these cases first. |
1876 | if (!F || F->isDeclaration()) |
1877 | return handleCallOverdefined(CB); |
1878 | |
1879 | // If this is a single/zero retval case, see if we're tracking the function. |
1880 | if (auto *STy = dyn_cast<StructType>(Val: F->getReturnType())) { |
1881 | if (!MRVFunctionsTracked.count(Ptr: F)) |
1882 | return handleCallOverdefined(CB); // Not tracking this callee. |
1883 | |
1884 | // If we are tracking this callee, propagate the result of the function |
1885 | // into this call site. |
1886 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
1887 | mergeInValue(IV&: getStructValueState(V: &CB, i), V: &CB, |
1888 | MergeWithV: TrackedMultipleRetVals[std::make_pair(x&: F, y&: i)], |
1889 | Opts: getMaxWidenStepsOpts()); |
1890 | } else { |
1891 | auto TFRVI = TrackedRetVals.find(Key: F); |
1892 | if (TFRVI == TrackedRetVals.end()) |
1893 | return handleCallOverdefined(CB); // Not tracking this callee. |
1894 | |
1895 | // If so, propagate the return value of the callee into this call result. |
1896 | mergeInValue(V: &CB, MergeWithV: TFRVI->second, Opts: getMaxWidenStepsOpts()); |
1897 | } |
1898 | } |
1899 | |
1900 | void SCCPInstVisitor::solve() { |
1901 | // Process the work lists until they are empty! |
1902 | while (!BBWorkList.empty() || !InstWorkList.empty() || |
1903 | !OverdefinedInstWorkList.empty()) { |
1904 | // Process the overdefined instruction's work list first, which drives other |
1905 | // things to overdefined more quickly. |
1906 | while (!OverdefinedInstWorkList.empty()) { |
1907 | Value *I = OverdefinedInstWorkList.pop_back_val(); |
1908 | Invalidated.erase(V: I); |
1909 | |
1910 | LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n'); |
1911 | |
1912 | // "I" got into the work list because it either made the transition from |
1913 | // bottom to constant, or to overdefined. |
1914 | // |
1915 | // Anything on this worklist that is overdefined need not be visited |
1916 | // since all of its users will have already been marked as overdefined |
1917 | // Update all of the users of this instruction's value. |
1918 | // |
1919 | markUsersAsChanged(I); |
1920 | } |
1921 | |
1922 | // Process the instruction work list. |
1923 | while (!InstWorkList.empty()) { |
1924 | Value *I = InstWorkList.pop_back_val(); |
1925 | Invalidated.erase(V: I); |
1926 | |
1927 | LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n'); |
1928 | |
1929 | // "I" got into the work list because it made the transition from undef to |
1930 | // constant. |
1931 | // |
1932 | // Anything on this worklist that is overdefined need not be visited |
1933 | // since all of its users will have already been marked as overdefined. |
1934 | // Update all of the users of this instruction's value. |
1935 | // |
1936 | if (I->getType()->isStructTy() || !getValueState(V: I).isOverdefined()) |
1937 | markUsersAsChanged(I); |
1938 | } |
1939 | |
1940 | // Process the basic block work list. |
1941 | while (!BBWorkList.empty()) { |
1942 | BasicBlock *BB = BBWorkList.pop_back_val(); |
1943 | |
1944 | LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n'); |
1945 | |
1946 | // Notify all instructions in this basic block that they are newly |
1947 | // executable. |
1948 | visit(BB); |
1949 | } |
1950 | } |
1951 | } |
1952 | |
1953 | bool SCCPInstVisitor::resolvedUndef(Instruction &I) { |
1954 | // Look for instructions which produce undef values. |
1955 | if (I.getType()->isVoidTy()) |
1956 | return false; |
1957 | |
1958 | if (auto *STy = dyn_cast<StructType>(Val: I.getType())) { |
1959 | // Only a few things that can be structs matter for undef. |
1960 | |
1961 | // Tracked calls must never be marked overdefined in resolvedUndefsIn. |
1962 | if (auto *CB = dyn_cast<CallBase>(Val: &I)) |
1963 | if (Function *F = CB->getCalledFunction()) |
1964 | if (MRVFunctionsTracked.count(Ptr: F)) |
1965 | return false; |
1966 | |
1967 | // extractvalue and insertvalue don't need to be marked; they are |
1968 | // tracked as precisely as their operands. |
1969 | if (isa<ExtractValueInst>(Val: I) || isa<InsertValueInst>(Val: I)) |
1970 | return false; |
1971 | // Send the results of everything else to overdefined. We could be |
1972 | // more precise than this but it isn't worth bothering. |
1973 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
1974 | ValueLatticeElement &LV = getStructValueState(V: &I, i); |
1975 | if (LV.isUnknown()) { |
1976 | markOverdefined(IV&: LV, V: &I); |
1977 | return true; |
1978 | } |
1979 | } |
1980 | return false; |
1981 | } |
1982 | |
1983 | ValueLatticeElement &LV = getValueState(V: &I); |
1984 | if (!LV.isUnknown()) |
1985 | return false; |
1986 | |
1987 | // There are two reasons a call can have an undef result |
1988 | // 1. It could be tracked. |
1989 | // 2. It could be constant-foldable. |
1990 | // Because of the way we solve return values, tracked calls must |
1991 | // never be marked overdefined in resolvedUndefsIn. |
1992 | if (auto *CB = dyn_cast<CallBase>(Val: &I)) |
1993 | if (Function *F = CB->getCalledFunction()) |
1994 | if (TrackedRetVals.count(Key: F)) |
1995 | return false; |
1996 | |
1997 | if (isa<LoadInst>(Val: I)) { |
1998 | // A load here means one of two things: a load of undef from a global, |
1999 | // a load from an unknown pointer. Either way, having it return undef |
2000 | // is okay. |
2001 | return false; |
2002 | } |
2003 | |
2004 | markOverdefined(V: &I); |
2005 | return true; |
2006 | } |
2007 | |
2008 | /// While solving the dataflow for a function, we don't compute a result for |
2009 | /// operations with an undef operand, to allow undef to be lowered to a |
2010 | /// constant later. For example, constant folding of "zext i8 undef to i16" |
2011 | /// would result in "i16 0", and if undef is later lowered to "i8 1", then the |
2012 | /// zext result would become "i16 1" and would result into an overdefined |
2013 | /// lattice value once merged with the previous result. Not computing the |
2014 | /// result of the zext (treating undef the same as unknown) allows us to handle |
2015 | /// a later undef->constant lowering more optimally. |
2016 | /// |
2017 | /// However, if the operand remains undef when the solver returns, we do need |
2018 | /// to assign some result to the instruction (otherwise we would treat it as |
2019 | /// unreachable). For simplicity, we mark any instructions that are still |
2020 | /// unknown as overdefined. |
2021 | bool SCCPInstVisitor::resolvedUndefsIn(Function &F) { |
2022 | bool MadeChange = false; |
2023 | for (BasicBlock &BB : F) { |
2024 | if (!BBExecutable.count(Ptr: &BB)) |
2025 | continue; |
2026 | |
2027 | for (Instruction &I : BB) |
2028 | MadeChange |= resolvedUndef(I); |
2029 | } |
2030 | |
2031 | LLVM_DEBUG(if (MadeChange) dbgs() |
2032 | << "\nResolved undefs in " << F.getName() << '\n'); |
2033 | |
2034 | return MadeChange; |
2035 | } |
2036 | |
2037 | //===----------------------------------------------------------------------===// |
2038 | // |
2039 | // SCCPSolver implementations |
2040 | // |
2041 | SCCPSolver::SCCPSolver( |
2042 | const DataLayout &DL, |
2043 | std::function<const TargetLibraryInfo &(Function &)> GetTLI, |
2044 | LLVMContext &Ctx) |
2045 | : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {} |
2046 | |
2047 | SCCPSolver::~SCCPSolver() = default; |
2048 | |
2049 | void SCCPSolver::addPredicateInfo(Function &F, DominatorTree &DT, |
2050 | AssumptionCache &AC) { |
2051 | Visitor->addPredicateInfo(F, DT, AC); |
2052 | } |
2053 | |
2054 | bool SCCPSolver::markBlockExecutable(BasicBlock *BB) { |
2055 | return Visitor->markBlockExecutable(BB); |
2056 | } |
2057 | |
2058 | const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) { |
2059 | return Visitor->getPredicateInfoFor(I); |
2060 | } |
2061 | |
2062 | void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) { |
2063 | Visitor->trackValueOfGlobalVariable(GV); |
2064 | } |
2065 | |
2066 | void SCCPSolver::addTrackedFunction(Function *F) { |
2067 | Visitor->addTrackedFunction(F); |
2068 | } |
2069 | |
2070 | void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) { |
2071 | Visitor->addToMustPreserveReturnsInFunctions(F); |
2072 | } |
2073 | |
2074 | bool SCCPSolver::mustPreserveReturn(Function *F) { |
2075 | return Visitor->mustPreserveReturn(F); |
2076 | } |
2077 | |
2078 | void SCCPSolver::addArgumentTrackedFunction(Function *F) { |
2079 | Visitor->addArgumentTrackedFunction(F); |
2080 | } |
2081 | |
2082 | bool SCCPSolver::isArgumentTrackedFunction(Function *F) { |
2083 | return Visitor->isArgumentTrackedFunction(F); |
2084 | } |
2085 | |
2086 | void SCCPSolver::solve() { Visitor->solve(); } |
2087 | |
2088 | bool SCCPSolver::resolvedUndefsIn(Function &F) { |
2089 | return Visitor->resolvedUndefsIn(F); |
2090 | } |
2091 | |
2092 | void SCCPSolver::solveWhileResolvedUndefsIn(Module &M) { |
2093 | Visitor->solveWhileResolvedUndefsIn(M); |
2094 | } |
2095 | |
2096 | void |
2097 | SCCPSolver::solveWhileResolvedUndefsIn(SmallVectorImpl<Function *> &WorkList) { |
2098 | Visitor->solveWhileResolvedUndefsIn(WorkList); |
2099 | } |
2100 | |
2101 | void SCCPSolver::solveWhileResolvedUndefs() { |
2102 | Visitor->solveWhileResolvedUndefs(); |
2103 | } |
2104 | |
2105 | bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const { |
2106 | return Visitor->isBlockExecutable(BB); |
2107 | } |
2108 | |
2109 | bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const { |
2110 | return Visitor->isEdgeFeasible(From, To); |
2111 | } |
2112 | |
2113 | std::vector<ValueLatticeElement> |
2114 | SCCPSolver::getStructLatticeValueFor(Value *V) const { |
2115 | return Visitor->getStructLatticeValueFor(V); |
2116 | } |
2117 | |
2118 | void SCCPSolver::removeLatticeValueFor(Value *V) { |
2119 | return Visitor->removeLatticeValueFor(V); |
2120 | } |
2121 | |
2122 | void SCCPSolver::resetLatticeValueFor(CallBase *Call) { |
2123 | Visitor->resetLatticeValueFor(Call); |
2124 | } |
2125 | |
2126 | const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const { |
2127 | return Visitor->getLatticeValueFor(V); |
2128 | } |
2129 | |
2130 | const MapVector<Function *, ValueLatticeElement> & |
2131 | SCCPSolver::getTrackedRetVals() { |
2132 | return Visitor->getTrackedRetVals(); |
2133 | } |
2134 | |
2135 | const DenseMap<GlobalVariable *, ValueLatticeElement> & |
2136 | SCCPSolver::getTrackedGlobals() { |
2137 | return Visitor->getTrackedGlobals(); |
2138 | } |
2139 | |
2140 | const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() { |
2141 | return Visitor->getMRVFunctionsTracked(); |
2142 | } |
2143 | |
2144 | void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); } |
2145 | |
2146 | void SCCPSolver::trackValueOfArgument(Argument *V) { |
2147 | Visitor->trackValueOfArgument(A: V); |
2148 | } |
2149 | |
2150 | bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) { |
2151 | return Visitor->isStructLatticeConstant(F, STy); |
2152 | } |
2153 | |
2154 | Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV, |
2155 | Type *Ty) const { |
2156 | return Visitor->getConstant(LV, Ty); |
2157 | } |
2158 | |
2159 | Constant *SCCPSolver::getConstantOrNull(Value *V) const { |
2160 | return Visitor->getConstantOrNull(V); |
2161 | } |
2162 | |
2163 | SmallPtrSetImpl<Function *> &SCCPSolver::getArgumentTrackedFunctions() { |
2164 | return Visitor->getArgumentTrackedFunctions(); |
2165 | } |
2166 | |
2167 | void SCCPSolver::setLatticeValueForSpecializationArguments(Function *F, |
2168 | const SmallVectorImpl<ArgInfo> &Args) { |
2169 | Visitor->setLatticeValueForSpecializationArguments(F, Args); |
2170 | } |
2171 | |
2172 | void SCCPSolver::markFunctionUnreachable(Function *F) { |
2173 | Visitor->markFunctionUnreachable(F); |
2174 | } |
2175 | |
2176 | void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); } |
2177 | |
2178 | void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); } |
2179 | |