clang 24.0.0git
SimpleSValBuilder.cpp
Go to the documentation of this file.
1// SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- 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// This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
10//
11//===----------------------------------------------------------------------===//
12
19#include <optional>
20
21using namespace clang;
22using namespace ento;
23
24namespace {
25class SimpleSValBuilder : public SValBuilder {
26
27 // Query the constraint manager whether the SVal has only one possible
28 // (integer) value. If that is the case, the value is returned. Otherwise,
29 // returns NULL.
30 // This is an implementation detail. Checkers should use `getKnownValue()`
31 // instead.
32 static const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V);
33
34 // Helper function that returns the value stored in a nonloc::ConcreteInt or
35 // loc::ConcreteInt.
36 static const llvm::APSInt *getConcreteValue(SVal V);
37
38 // With one `simplifySValOnce` call, a compound symbols might collapse to
39 // simpler symbol tree that is still possible to further simplify. Thus, we
40 // do the simplification on a new symbol tree until we reach the simplest
41 // form, i.e. the fixpoint.
42 // Consider the following symbol `(b * b) * b * b` which has this tree:
43 // *
44 // / \
45 // * b
46 // / \
47 // / b
48 // (b * b)
49 // Now, if the `b * b == 1` new constraint is added then during the first
50 // iteration we have the following transformations:
51 // * *
52 // / \ / \
53 // * b --> b b
54 // / \
55 // / b
56 // 1
57 // We need another iteration to reach the final result `1`.
58 SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
59
60 // Recursively descends into symbolic expressions and replaces symbols
61 // with their known values (in the sense of the getConstValue() method).
62 // We traverse the symbol tree and query the constraint values for the
63 // sub-trees and if a value is a constant we do the constant folding.
64 SVal simplifySValOnce(ProgramStateRef State, SVal V);
65
66public:
67 SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
68 ProgramStateManager &stateMgr)
69 : SValBuilder(alloc, context, stateMgr) {}
70 ~SimpleSValBuilder() override {}
71
72 SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
73 NonLoc lhs, NonLoc rhs, QualType resultTy) override;
74 SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
75 Loc lhs, Loc rhs, QualType resultTy) override;
76 SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
77 Loc lhs, NonLoc rhs, QualType resultTy) override;
78
79 /// Evaluates a given SVal by recursively evaluating and
80 /// simplifying the children SVals. If the SVal has only one possible
81 /// (integer) value, that value is returned. Otherwise, returns NULL.
82 const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
83
84 /// Evaluates a given SVal by recursively evaluating and simplifying the
85 /// children SVals, then returns its minimal possible (integer) value. If the
86 /// constraint manager cannot provide a meaningful answer, this returns NULL.
87 const llvm::APSInt *getMinValue(ProgramStateRef state, SVal V) override;
88
89 /// Evaluates a given SVal by recursively evaluating and simplifying the
90 /// children SVals, then returns its maximal possible (integer) value. If the
91 /// constraint manager cannot provide a meaningful answer, this returns NULL.
92 const llvm::APSInt *getMaxValue(ProgramStateRef state, SVal V) override;
93
94 SVal simplifySVal(ProgramStateRef State, SVal V) override;
95
96 SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
97 const llvm::APSInt &RHS, QualType resultTy);
98};
99} // end anonymous namespace
100
101SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
102 ASTContext &context,
103 ProgramStateManager &stateMgr) {
104 return new SimpleSValBuilder(alloc, context, stateMgr);
105}
106
107// Checks if the negation the value and flipping sign preserve
108// the semantics on the operation in the resultType
109static bool isNegationValuePreserving(const llvm::APSInt &Value,
110 APSIntType ResultType) {
111 const unsigned ValueBits = Value.getSignificantBits();
112 if (ValueBits == ResultType.getBitWidth()) {
113 // The value is the lowest negative value that is representable
114 // in signed integer with bitWith of result type. The
115 // negation is representable if resultType is unsigned.
116 return ResultType.isUnsigned();
117 }
118
119 // If resultType bitWith is higher that number of bits required
120 // to represent RHS, the sign flip produce same value.
121 return ValueBits < ResultType.getBitWidth();
122}
123
124//===----------------------------------------------------------------------===//
125// Transfer function for binary operators.
126//===----------------------------------------------------------------------===//
127
128SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
130 const llvm::APSInt &RHS,
131 QualType resultTy) {
132 bool isIdempotent = false;
133
134 // Check for a few special cases with known reductions first.
135 switch (op) {
136 default:
137 // We can't reduce this case; just treat it normally.
138 break;
139 case BO_Mul:
140 // a*0 and a*1
141 if (RHS == 0)
142 return makeIntVal(0, resultTy);
143 else if (RHS == 1)
144 isIdempotent = true;
145 break;
146 case BO_Div:
147 // a/0 and a/1
148 if (RHS == 0)
149 // This is also handled elsewhere.
150 return UndefinedVal();
151 else if (RHS == 1)
152 isIdempotent = true;
153 break;
154 case BO_Rem:
155 // a%0 and a%1
156 if (RHS == 0)
157 // This is also handled elsewhere.
158 return UndefinedVal();
159 else if (RHS == 1)
160 return makeIntVal(0, resultTy);
161 break;
162 case BO_Add:
163 case BO_Sub:
164 case BO_Shl:
165 case BO_Shr:
166 case BO_Xor:
167 // a+0, a-0, a<<0, a>>0, a^0
168 if (RHS == 0)
169 isIdempotent = true;
170 break;
171 case BO_And:
172 // a&0 and a&(~0)
173 if (RHS == 0)
174 return makeIntVal(0, resultTy);
175 else if (RHS.isAllOnes())
176 isIdempotent = true;
177 break;
178 case BO_Or:
179 // a|0 and a|(~0)
180 if (RHS == 0)
181 isIdempotent = true;
182 else if (RHS.isAllOnes()) {
183 return nonloc::ConcreteInt(BasicVals.Convert(resultTy, RHS));
184 }
185 break;
186 }
187
188 // Idempotent ops (like a*1) can still change the type of an expression.
189 // Wrap the LHS up in a NonLoc again and let evalCast do the
190 // dirty work.
191 if (isIdempotent)
192 return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
193
194 // If we reach this point, the expression cannot be simplified.
195 // Make a SymbolVal for the entire expression, after converting the RHS.
196 std::optional<APSIntPtr> ConvertedRHS = BasicVals.getValue(RHS);
198 // We're looking for a type big enough to compare the symbolic value
199 // with the given constant.
200 // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
201 ASTContext &Ctx = getContext();
202 QualType SymbolType = LHS->getType();
203 uint64_t ValWidth = RHS.getBitWidth();
204 uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
205
206 if (ValWidth < TypeWidth) {
207 // If the value is too small, extend it.
208 ConvertedRHS = BasicVals.Convert(SymbolType, RHS);
209 } else if (ValWidth == TypeWidth) {
210 // If the value is signed but the symbol is unsigned, do the comparison
211 // in unsigned space. [C99 6.3.1.8]
212 // (For the opposite case, the value is already unsigned.)
213 if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
214 ConvertedRHS = BasicVals.Convert(SymbolType, RHS);
215 }
216 } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
217 // Change a+(-N) into a-N, and a-(-N) into a+N
218 // Adjust addition/subtraction of negative value, to
219 // subtraction/addition of the negated value.
220 APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
221 if (isNegationValuePreserving(RHS, resultIntTy)) {
222 ConvertedRHS = BasicVals.getValue(-resultIntTy.convert(RHS));
223 op = (op == BO_Add) ? BO_Sub : BO_Add;
224 } else {
225 ConvertedRHS = BasicVals.Convert(resultTy, RHS);
226 }
227 } else
228 ConvertedRHS = BasicVals.Convert(resultTy, RHS);
229
230 return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
231}
232
233// See if Sym is known to be a relation Rel with Bound.
235 llvm::APSInt Bound, ProgramStateRef State) {
238 SVal Result = SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
239 nonloc::ConcreteInt(BV.getValue(Bound)),
240 SVB.getConditionType());
241 if (auto DV = Result.getAs<DefinedSVal>()) {
242 return !State->assume(*DV, false);
243 }
244 return false;
245}
246
247// See if Sym is known to be within [min/4, max/4], where min and max
248// are the bounds of the symbol's integral type. With such symbols,
249// some manipulations can be performed without the risk of overflow.
250// assume() doesn't cause infinite recursion because we should be dealing
251// with simpler symbols on every recursive call.
253 ProgramStateRef State) {
256
257 QualType T = Sym->getType();
258 assert(T->isSignedIntegerOrEnumerationType() &&
259 "This only works with signed integers!");
260 APSIntType AT = BV.getAPSIntType(T);
261
262 llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
263 return isInRelation(BO_LE, Sym, Max, State) &&
264 isInRelation(BO_GE, Sym, Min, State);
265}
266
267// Same for the concrete integers: see if I is within [min/4, max/4].
269 APSIntType AT(I);
270 assert(!AT.isUnsigned() &&
271 "This only works with signed integers!");
272
273 llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4);
274 return (I <= Max) && (I >= -Max);
275}
276
277static std::pair<SymbolRef, APSIntPtr> decomposeSymbol(SymbolRef Sym,
278 BasicValueFactory &BV) {
279 if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
280 if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
281 return std::make_pair(SymInt->getLHS(),
282 (SymInt->getOpcode() == BO_Add)
283 ? BV.getValue(SymInt->getRHS())
284 : BV.getValue(-SymInt->getRHS()));
285
286 // Fail to decompose: "reduce" the problem to the "$x + 0" case.
287 return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
288}
289
290// Simplify "(LSym + LInt) Op (RSym + RInt)" when all values are of the
291// same signed integral type and no overflow occurs. Returns the simplified
292// value or std::nullopt when the preconditions are not satisfied or the
293// symbol complexity limit is reached.
294static std::optional<NonLoc> tryRearrange(ProgramStateRef State,
296 NonLoc Rhs, QualType ResultTy) {
297 ProgramStateManager &StateMgr = State->getStateManager();
298 SValBuilder &SVB = StateMgr.getSValBuilder();
299
300 // FIXME: This should be enabled by default, at least for additive operations.
301 if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
302 return std::nullopt;
303
304 SymbolRef LSym = Lhs.getAsSymbol();
305 if (!LSym)
306 return std::nullopt;
307
308 // We expect everything to be of the same type - this type.
309 QualType CommonTy = LSym->getType();
310
312 if (ResultTy != SVB.getConditionType())
313 return std::nullopt;
314 } else if (BinaryOperator::isAdditiveOp(Op)) {
315 if (ResultTy != CommonTy)
316 return std::nullopt;
317 } else {
318 // Don't rearrange other operations.
319 return std::nullopt;
320 }
321
322 // Rearrange signed symbolic expressions only.
323 // FIXME: This should also handle unsigned, at least for additive operations.
324 if (!CommonTy->isSignedIntegerOrEnumerationType())
325 return std::nullopt;
326
327 SymbolRef RSym = Rhs.getAsSymbol();
328 if (!RSym || RSym->getType() != CommonTy)
329 return std::nullopt;
330
331 BasicValueFactory &BV = State->getBasicVals();
332 llvm::APSInt LInt, RInt;
333 std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
334 std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
335
336 if (LSym->getType() != CommonTy || RSym->getType() != CommonTy)
337 return std::nullopt;
338
339 APSIntType CommonAPSIntTy = BV.getAPSIntType(CommonTy);
340 if (APSIntType(LInt) != CommonAPSIntTy || APSIntType(RInt) != CommonAPSIntTy)
341 return std::nullopt;
342
343 auto InBounds = [State](auto... X) {
344 return (... && isWithinConstantOverflowBounds(X, State));
345 };
346 if (BinaryOperator::isComparisonOp(Op) && !InBounds(LInt, RInt, LSym, RSym))
347 return std::nullopt;
348
349 if (LSym == RSym)
350 return SVB
351 .evalBinOpNN(State, Op, nonloc::ConcreteInt(BV.getValue(LInt)),
352 nonloc::ConcreteInt(BV.getValue(RInt)), ResultTy)
353 .getAs<NonLoc>();
354
355 auto MakeSymExprVal = [&SVB, CommonTy](SymbolRef Lhs, BinaryOperatorKind Op,
356 SymbolRef Rhs) {
357 return SVB.makeSymExprValNN(Op, nonloc::SymbolVal(Lhs),
358 nonloc::SymbolVal(Rhs), CommonTy);
359 };
360
361 SVal ResultSV = UnknownVal();
362 BinaryOperator::Opcode ResultOp;
363 llvm::APSInt ResultInt;
365 // Prefer comparing to a non-negative number.
366 // FIXME: Maybe it'd be better to have consistency in
367 // "$x - $y" vs. "$y - $x" because those are solver's keys.
368 if (LInt > RInt) {
369 ResultSV = MakeSymExprVal(RSym, BO_Sub, LSym);
371 ResultInt = LInt - RInt; // Opposite order!
372 } else {
373 ResultSV = MakeSymExprVal(LSym, BO_Sub, RSym);
374 ResultOp = Op;
375 ResultInt = RInt - LInt; // Opposite order!
376 }
377 } else {
378 ResultSV = MakeSymExprVal(LSym, Op, RSym);
379 ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
380 ResultOp = BO_Add;
381 // Bring back the cosmetic difference.
382 if (ResultInt < 0) {
383 ResultInt = -ResultInt;
384 ResultOp = BO_Sub;
385 } else if (ResultInt == 0) {
386 // Shortcut: Simplify "$x + 0" to "$x".
387 return ResultSV.getAs<NonLoc>();
388 }
389 }
390 if (auto ResultNL = ResultSV.getAs<NonLoc>()) {
391 nonloc::ConcreteInt ResultCI(BV.getValue(ResultInt));
392 return SVB.makeSymExprValNN(ResultOp, *ResultNL, ResultCI, ResultTy)
393 .getAs<NonLoc>();
394 }
395 return std::nullopt;
396}
397
398SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
400 NonLoc lhs, NonLoc rhs,
401 QualType resultTy) {
402 NonLoc InputLHS = lhs;
403 NonLoc InputRHS = rhs;
404
405 // Constraints may have changed since the creation of a bound SVal. Check if
406 // the values can be simplified based on those new constraints.
407 SVal simplifiedLhs = simplifySVal(state, lhs);
408 SVal simplifiedRhs = simplifySVal(state, rhs);
409 if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
410 lhs = *simplifiedLhsAsNonLoc;
411 if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
412 rhs = *simplifiedRhsAsNonLoc;
413
414 // Handle trivial case where left-side and right-side are the same.
415 if (lhs == rhs)
416 switch (op) {
417 default:
418 break;
419 case BO_EQ:
420 case BO_LE:
421 case BO_GE:
422 return makeTruthVal(true, resultTy);
423 case BO_LT:
424 case BO_GT:
425 case BO_NE:
426 return makeTruthVal(false, resultTy);
427 case BO_Xor:
428 case BO_Sub:
429 if (resultTy->isIntegralOrEnumerationType())
430 return makeIntVal(0, resultTy);
431 return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
432 QualType{});
433 case BO_Or:
434 case BO_And:
435 return evalCast(lhs, resultTy, QualType{});
436 }
437
438 while (true) {
439 switch (lhs.getKind()) {
440 default:
441 return makeSymExprValNN(op, lhs, rhs, resultTy);
442 case nonloc::PointerToMemberKind: {
443 assert(rhs.getKind() == nonloc::PointerToMemberKind &&
444 "Both SVals should have pointer-to-member-type");
445 auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
446 RPTM = rhs.castAs<nonloc::PointerToMember>();
447 auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
448 switch (op) {
449 case BO_EQ:
450 return makeTruthVal(LPTMD == RPTMD, resultTy);
451 case BO_NE:
452 return makeTruthVal(LPTMD != RPTMD, resultTy);
453 default:
454 return UnknownVal();
455 }
456 }
457 case nonloc::LocAsIntegerKind: {
458 Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
459 switch (rhs.getKind()) {
460 case nonloc::LocAsIntegerKind:
461 // FIXME: at the moment the implementation
462 // of modeling "pointers as integers" is not complete.
464 return UnknownVal();
465 return evalBinOpLL(state, op, lhsL,
466 rhs.castAs<nonloc::LocAsInteger>().getLoc(),
467 resultTy);
468 case nonloc::ConcreteIntKind: {
469 // FIXME: at the moment the implementation
470 // of modeling "pointers as integers" is not complete.
472 return UnknownVal();
473 // Transform the integer into a location and compare.
474 // FIXME: This only makes sense for comparisons. If we want to, say,
475 // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
476 // then pack it back into a LocAsInteger.
477 llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
478 // If the region has a symbolic base, pay attention to the type; it
479 // might be coming from a non-default address space. For non-symbolic
480 // regions it doesn't matter that much because such comparisons would
481 // most likely evaluate to concrete false anyway. FIXME: We might
482 // still need to handle the non-comparison case.
483 if (SymbolRef lSym = lhs.getAsLocSymbol(true))
484 BasicVals.getAPSIntType(lSym->getType()).apply(i);
485 else
486 BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
487 return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
488 }
489 default:
490 switch (op) {
491 case BO_EQ:
492 return makeTruthVal(false, resultTy);
493 case BO_NE:
494 return makeTruthVal(true, resultTy);
495 default:
496 // This case also handles pointer arithmetic.
497 return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
498 }
499 }
500 }
501 case nonloc::ConcreteIntKind: {
502 llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
503
504 // If we're dealing with two known constants, just perform the operation.
505 if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) {
506 llvm::APSInt RHSValue = *KnownRHSValue;
508 // We're looking for a type big enough to compare the two values.
509 // FIXME: This is not correct. char + short will result in a promotion
510 // to int. Unfortunately we have lost types by this point.
511 APSIntType CompareType = std::max(APSIntType(LHSValue),
512 APSIntType(RHSValue));
513 CompareType.apply(LHSValue);
514 CompareType.apply(RHSValue);
515 } else if (!BinaryOperator::isShiftOp(op)) {
516 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
517 IntType.apply(LHSValue);
518 IntType.apply(RHSValue);
519 }
520
521 std::optional<APSIntPtr> Result =
522 BasicVals.evalAPSInt(op, LHSValue, RHSValue);
523 if (!Result) {
524 if (op == BO_Shl || op == BO_Shr) {
525 // FIXME: At this point the constant folding claims that the result
526 // of a bitwise shift is undefined. However, constant folding
527 // relies on the inaccurate type information that is stored in the
528 // bit size of APSInt objects, and if we reached this point, then
529 // the checker core.BitwiseShift already determined that the shift
530 // is valid (in a PreStmt callback, by querying the real type from
531 // the AST node).
532 // To avoid embarrassing false positives, let's just say that we
533 // don't know anything about the result of the shift.
534 return UnknownVal();
535 }
536 return UndefinedVal();
537 }
538
539 return nonloc::ConcreteInt(*Result);
540 }
541
542 // Swap the left and right sides and flip the operator if doing so
543 // allows us to better reason about the expression (this is a form
544 // of expression canonicalization).
545 // While we're at it, catch some special cases for non-commutative ops.
546 switch (op) {
547 case BO_LT:
548 case BO_GT:
549 case BO_LE:
550 case BO_GE:
552 [[fallthrough]];
553 case BO_EQ:
554 case BO_NE:
555 case BO_Add:
556 case BO_Mul:
557 case BO_And:
558 case BO_Xor:
559 case BO_Or:
560 std::swap(lhs, rhs);
561 continue;
562 case BO_Shr:
563 // (~0)>>a
564 if (LHSValue.isAllOnes() && LHSValue.isSigned())
565 return evalCast(lhs, resultTy, QualType{});
566 [[fallthrough]];
567 case BO_Shl:
568 // 0<<a and 0>>a
569 if (LHSValue == 0)
570 return evalCast(lhs, resultTy, QualType{});
571 return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
572 case BO_Div:
573 // 0 / x == 0
574 case BO_Rem:
575 // 0 % x == 0
576 if (LHSValue == 0)
577 return makeZeroVal(resultTy);
578 [[fallthrough]];
579 default:
580 return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
581 }
582 }
583 case nonloc::SymbolValKind: {
584 // We only handle LHS as simple symbols or SymIntExprs.
585 SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
586
587 // LHS is a symbolic expression.
588 if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
589
590 // Is this a logical not? (!x is represented as x == 0.)
591 if (op == BO_EQ && rhs.isZeroConstant()) {
592 // We know how to negate certain expressions. Simplify them here.
593
594 BinaryOperator::Opcode opc = symIntExpr->getOpcode();
595 switch (opc) {
596 default:
597 // We don't know how to negate this operation.
598 // Just handle it as if it were a normal comparison to 0.
599 break;
600 case BO_LAnd:
601 case BO_LOr:
602 llvm_unreachable("Logical operators handled by branching logic.");
603 case BO_Assign:
604 case BO_MulAssign:
605 case BO_DivAssign:
606 case BO_RemAssign:
607 case BO_AddAssign:
608 case BO_SubAssign:
609 case BO_ShlAssign:
610 case BO_ShrAssign:
611 case BO_AndAssign:
612 case BO_XorAssign:
613 case BO_OrAssign:
614 case BO_Comma:
615 llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
616 case BO_PtrMemD:
617 case BO_PtrMemI:
618 llvm_unreachable("Pointer arithmetic not handled here.");
619 case BO_LT:
620 case BO_GT:
621 case BO_LE:
622 case BO_GE:
623 case BO_EQ:
624 case BO_NE:
625 assert(resultTy->isBooleanType() ||
626 resultTy == getConditionType());
627 assert(symIntExpr->getType()->isBooleanType() ||
628 getContext().hasSameUnqualifiedType(symIntExpr->getType(),
629 getConditionType()));
630 // Negate the comparison and make a value.
632 return makeNonLoc(symIntExpr->getLHS(), opc,
633 symIntExpr->getRHS(), resultTy);
634 }
635 }
636
637 // For now, only handle expressions whose RHS is a constant.
638 if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) {
639 // If both the LHS and the current expression are additive,
640 // fold their constants and try again.
642 BinaryOperator::Opcode lop = symIntExpr->getOpcode();
644 // Convert the two constants to a common type, then combine them.
645
646 // resultTy may not be the best type to convert to, but it's
647 // probably the best choice in expressions with mixed type
648 // (such as x+1U+2LL). The rules for implicit conversions should
649 // choose a reasonable type to preserve the expression, and will
650 // at least match how the value is going to be used.
651 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
652 const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
653 const llvm::APSInt &second = IntType.convert(*RHSValue);
654
655 // If the op and lop agrees, then we just need to
656 // sum the constants. Otherwise, we change to operation
657 // type if substraction would produce negative value
658 // (and cause overflow for unsigned integers),
659 // as consequence x+1U-10 produces x-9U, instead
660 // of x+4294967287U, that would be produced without this
661 // additional check.
662 std::optional<APSIntPtr> newRHS;
663 if (lop == op) {
664 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
665 } else if (first >= second) {
666 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
667 op = lop;
668 } else {
669 newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
670 }
671
672 assert(newRHS && "Invalid operation despite common type!");
673 rhs = nonloc::ConcreteInt(*newRHS);
674 lhs = nonloc::SymbolVal(symIntExpr->getLHS());
675 continue;
676 }
677 }
678
679 // Otherwise, make a SymIntExpr out of the expression.
680 return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
681 }
682 }
683
684 // Is the RHS a constant?
685 if (const llvm::APSInt *RHSValue = getConstValue(state, rhs))
686 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
687
688 if (std::optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
689 return *V;
690
691 // Give up -- this is not a symbolic expression we can handle.
692 return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
693 }
694 }
695 }
696}
697
699 const FieldRegion *RightFR,
701 QualType resultTy,
702 SimpleSValBuilder &SVB) {
703 // Only comparisons are meaningful here!
705 return UnknownVal();
706
707 // Next, see if the two FRs have the same super-region.
708 // FIXME: This doesn't handle casts yet, and simply stripping the casts
709 // doesn't help.
710 if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
711 return UnknownVal();
712
713 const FieldDecl *LeftFD = LeftFR->getDecl();
714 const FieldDecl *RightFD = RightFR->getDecl();
715 const RecordDecl *RD = LeftFD->getParent();
716
717 // Make sure the two FRs are from the same kind of record. Just in case!
718 // FIXME: This is probably where inheritance would be a problem.
719 if (RD != RightFD->getParent())
720 return UnknownVal();
721
722 // We know for sure that the two fields are not the same, since that
723 // would have given us the same SVal.
724 if (op == BO_EQ)
725 return SVB.makeTruthVal(false, resultTy);
726 if (op == BO_NE)
727 return SVB.makeTruthVal(true, resultTy);
728
729 // Iterate through the fields and see which one comes first.
730 // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
731 // members and the units in which bit-fields reside have addresses that
732 // increase in the order in which they are declared."
733 bool leftFirst = (op == BO_LT || op == BO_LE);
734 for (const auto *I : RD->fields()) {
735 if (I == LeftFD)
736 return SVB.makeTruthVal(leftFirst, resultTy);
737 if (I == RightFD)
738 return SVB.makeTruthVal(!leftFirst, resultTy);
739 }
740
741 llvm_unreachable("Fields not found in parent record's definition");
742}
743
744// This is used in debug builds only for now because some downstream users
745// may hit this assert in their subsequent merges.
746// There are still places in the analyzer where equal bitwidth Locs
747// are compared, and need to be found and corrected. Recent previous fixes have
748// addressed the known problems of making NULLs with specific bitwidths
749// for Loc comparisons along with deprecation of APIs for the same purpose.
750//
751static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
752 Loc LhsLoc) {
753 // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
754 ASTContext &Ctx = State->getStateManager().getContext();
755 uint64_t RhsBitwidth =
756 RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
757 uint64_t LhsBitwidth =
758 LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
759 if (RhsBitwidth && LhsBitwidth && (LhsLoc.getKind() == RhsLoc.getKind())) {
760 assert(RhsBitwidth == LhsBitwidth &&
761 "RhsLoc and LhsLoc bitwidth must be same!");
762 }
763}
764
765// FIXME: all this logic will change if/when we have MemRegion::getLocation().
766SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
768 Loc lhs, Loc rhs,
769 QualType resultTy) {
770
771 // Assert that bitwidth of lhs and rhs are the same.
772 // This can happen if two different address spaces are used,
773 // and the bitwidths of the address spaces are different.
774 // See LIT case clang/test/Analysis/cstring-checker-addressspace.c
775 // FIXME: See comment above in the function assertEqualBitWidths
776 assertEqualBitWidths(state, rhs, lhs);
777
778 // Only comparisons and subtractions are valid operations on two pointers.
779 // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
780 // However, if a pointer is casted to an integer, evalBinOpNN may end up
781 // calling this function with another operation (PR7527). We don't attempt to
782 // model this for now, but it could be useful, particularly when the
783 // "location" is actually an integer value that's been passed through a void*.
784 if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
785 return UnknownVal();
786
787 // Special cases for when both sides are identical.
788 if (lhs == rhs) {
789 switch (op) {
790 default:
791 llvm_unreachable("Unimplemented operation for two identical values");
792 case BO_Sub:
793 return makeZeroVal(resultTy);
794 case BO_EQ:
795 case BO_LE:
796 case BO_GE:
797 return makeTruthVal(true, resultTy);
798 case BO_NE:
799 case BO_LT:
800 case BO_GT:
801 return makeTruthVal(false, resultTy);
802 }
803 }
804
805 switch (lhs.getKind()) {
806 default:
807 llvm_unreachable("Ordering not implemented for this Loc.");
808
809 case loc::GotoLabelKind:
810 // The only thing we know about labels is that they're non-null.
811 if (rhs.isZeroConstant()) {
812 switch (op) {
813 default:
814 break;
815 case BO_Sub:
816 return evalCast(lhs, resultTy, QualType{});
817 case BO_EQ:
818 case BO_LE:
819 case BO_LT:
820 return makeTruthVal(false, resultTy);
821 case BO_NE:
822 case BO_GT:
823 case BO_GE:
824 return makeTruthVal(true, resultTy);
825 }
826 }
827 // There may be two labels for the same location, and a function region may
828 // have the same address as a label at the start of the function (depending
829 // on the ABI).
830 // FIXME: we can probably do a comparison against other MemRegions, though.
831 // FIXME: is there a way to tell if two labels refer to the same location?
832 return UnknownVal();
833
834 case loc::ConcreteIntKind: {
835 auto L = lhs.castAs<loc::ConcreteInt>();
836
837 // If one of the operands is a symbol and the other is a constant,
838 // build an expression for use by the constraint manager.
839 if (SymbolRef rSym = rhs.getAsLocSymbol(true)) {
840 if (op == BO_Cmp)
841 return UnknownVal();
842
844 return makeNonLoc(L.getValue(), op, rSym, resultTy);
845
847 return makeNonLoc(rSym, op, L.getValue(), resultTy);
848 }
849
850 // If both operands are constants, just perform the operation.
851 if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
852 assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub);
853
854 if (std::optional<APSIntPtr> ResultInt =
855 BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue()))
856 return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{});
857 return UnknownVal();
858 }
859
860 // Special case comparisons against NULL.
861 // This must come after the test if the RHS is a symbol, which is used to
862 // build constraints. The address of any non-symbolic region is guaranteed
863 // to be non-NULL, as is any label.
865 if (lhs.isZeroConstant()) {
866 switch (op) {
867 default:
868 break;
869 case BO_EQ:
870 case BO_GT:
871 case BO_GE:
872 return makeTruthVal(false, resultTy);
873 case BO_NE:
874 case BO_LT:
875 case BO_LE:
876 return makeTruthVal(true, resultTy);
877 }
878 }
879
880 // Comparing an arbitrary integer to a region or label address is
881 // completely unknowable.
882 return UnknownVal();
883 }
884 case loc::MemRegionValKind: {
885 if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
886 // If one of the operands is a symbol and the other is a constant,
887 // build an expression for use by the constraint manager.
888 if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
890 return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
891 return UnknownVal();
892 }
893 // Special case comparisons to NULL.
894 // This must come after the test if the LHS is a symbol, which is used to
895 // build constraints. The address of any non-symbolic region is guaranteed
896 // to be non-NULL.
897 if (rInt->isZeroConstant()) {
898 if (op == BO_Sub)
899 return evalCast(lhs, resultTy, QualType{});
900
902 QualType boolType = getContext().BoolTy;
903 NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
904 NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
905 return evalBinOpNN(state, op, l, r, resultTy);
906 }
907 }
908
909 // Comparing a region to an arbitrary integer is completely unknowable.
910 return UnknownVal();
911 }
912
913 // Get both values as regions, if possible.
914 const MemRegion *LeftMR = lhs.getAsRegion();
915 assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
916
917 const MemRegion *RightMR = rhs.getAsRegion();
918 if (!RightMR)
919 // The RHS is probably a label, which in theory could address a region.
920 // FIXME: we can probably make a more useful statement about non-code
921 // regions, though.
922 return UnknownVal();
923
924 const MemRegion *LeftBase = LeftMR->getBaseRegion();
925 const MemRegion *RightBase = RightMR->getBaseRegion();
926 const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(state);
927 const MemSpaceRegion *RightMS = RightBase->getMemorySpace(state);
928 const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
929
930 // Two regions from different known memory spaces cannot be equal.
931 if (LeftMS != RightMS && LeftMS != UnknownMS && RightMS != UnknownMS) {
932 switch (op) {
933 default:
934 return UnknownVal();
935 case BO_EQ:
936 return makeTruthVal(false, resultTy);
937 case BO_NE:
938 return makeTruthVal(true, resultTy);
939 }
940 }
941
942 // If both values wrap regions, see if they're from different base regions.
943 // Note, heap base symbolic regions are assumed to not alias with
944 // each other; for example, we assume that malloc returns different address
945 // on each invocation.
946 // FIXME: ObjC object pointers always reside on the heap, but currently
947 // we treat their memory space as unknown, because symbolic pointers
948 // to ObjC objects may alias. There should be a way to construct
949 // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
950 // guesses memory space for ObjC object pointers manually instead of
951 // relying on us.
952 if (LeftBase != RightBase &&
953 ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
954 (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
955 switch (op) {
956 default:
957 return UnknownVal();
958 case BO_EQ:
959 return makeTruthVal(false, resultTy);
960 case BO_NE:
961 return makeTruthVal(true, resultTy);
962 }
963 }
964
965 // Handle special cases for when both regions are element regions.
966 const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
967 const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
968 if (RightER && LeftER) {
969 // Next, see if the two ERs have the same super-region and matching types.
970 // FIXME: This should do something useful even if the types don't match,
971 // though if both indexes are constant the RegionRawOffset path will
972 // give the correct answer.
973 if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
974 LeftER->getElementType() == RightER->getElementType()) {
975 // Get the left index and cast it to the correct type.
976 // If the index is unknown or undefined, bail out here.
977 SVal LeftIndexVal = LeftER->getIndex();
978 std::optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
979 if (!LeftIndex)
980 return UnknownVal();
981 LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
982 LeftIndex = LeftIndexVal.getAs<NonLoc>();
983 if (!LeftIndex)
984 return UnknownVal();
985
986 // Do the same for the right index.
987 SVal RightIndexVal = RightER->getIndex();
988 std::optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
989 if (!RightIndex)
990 return UnknownVal();
991 RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
992 RightIndex = RightIndexVal.getAs<NonLoc>();
993 if (!RightIndex)
994 return UnknownVal();
995
996 // Actually perform the operation.
997 // evalBinOpNN expects the two indexes to already be the right type.
998 return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
999 }
1000 }
1001
1002 // Special handling of the FieldRegions, even with symbolic offsets.
1003 const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1004 const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1005 if (RightFR && LeftFR) {
1006 SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1007 *this);
1008 if (!R.isUnknown())
1009 return R;
1010 }
1011
1012 // Compare the regions using the raw offsets.
1013 RegionOffset LeftOffset = LeftMR->getAsOffset();
1014 RegionOffset RightOffset = RightMR->getAsOffset();
1015
1016 if (LeftOffset.getRegion() != nullptr &&
1017 LeftOffset.getRegion() == RightOffset.getRegion() &&
1018 !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1019 int64_t left = LeftOffset.getOffset();
1020 int64_t right = RightOffset.getOffset();
1021
1022 switch (op) {
1023 default:
1024 return UnknownVal();
1025 case BO_LT:
1026 return makeTruthVal(left < right, resultTy);
1027 case BO_GT:
1028 return makeTruthVal(left > right, resultTy);
1029 case BO_LE:
1030 return makeTruthVal(left <= right, resultTy);
1031 case BO_GE:
1032 return makeTruthVal(left >= right, resultTy);
1033 case BO_EQ:
1034 return makeTruthVal(left == right, resultTy);
1035 case BO_NE:
1036 return makeTruthVal(left != right, resultTy);
1037 }
1038 }
1039
1040 // At this point we're not going to get a good answer, but we can try
1041 // conjuring an expression instead.
1042 SymbolRef LHSSym = lhs.getAsLocSymbol();
1043 SymbolRef RHSSym = rhs.getAsLocSymbol();
1044 if (LHSSym && RHSSym)
1045 return makeNonLoc(LHSSym, op, RHSSym, resultTy);
1046
1047 // If we get here, we have no way of comparing the regions.
1048 return UnknownVal();
1049 }
1050 }
1051}
1052
1053SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1054 BinaryOperator::Opcode op, Loc lhs,
1055 NonLoc rhs, QualType resultTy) {
1056 if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
1057 if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
1058 if (PTMSV->isNullMemberPointer())
1059 return UndefinedVal();
1060
1061 auto getFieldLValue = [&](const auto *FD) -> SVal {
1062 SVal Result = lhs;
1063
1064 for (const auto &I : *PTMSV)
1065 Result = StateMgr.getStoreManager().evalDerivedToBase(
1066 Result, I->getType(), I->isVirtual());
1067
1068 return state->getLValue(FD, Result);
1069 };
1070
1071 if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
1072 return getFieldLValue(FD);
1073 }
1074 if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
1075 return getFieldLValue(FD);
1076 }
1077 }
1078
1079 return rhs;
1080 }
1081
1082 assert(!BinaryOperator::isComparisonOp(op) &&
1083 "arguments to comparison ops must be of the same type");
1084
1085 SVal simplifiedRhs = simplifySVal(state, rhs);
1086 if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
1087 rhs = *simplifiedRhsAsNonLoc;
1088
1089 // Special case: rhs is a zero constant.
1090 if (rhs.isZeroConstant())
1091 return lhs;
1092
1093 // Perserve the null pointer so that it can be found by the DerefChecker.
1094 if (lhs.isZeroConstant())
1095 return lhs;
1096
1097 // We are dealing with pointer arithmetic.
1098
1099 // Handle pointer arithmetic on constant values.
1100 if (std::optional<nonloc::ConcreteInt> rhsInt =
1101 rhs.getAs<nonloc::ConcreteInt>()) {
1102 if (std::optional<loc::ConcreteInt> lhsInt =
1103 lhs.getAs<loc::ConcreteInt>()) {
1104 const llvm::APSInt &leftI = lhsInt->getValue();
1105 assert(leftI.isUnsigned());
1106 llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1107
1108 // Convert the bitwidth of rightI. This should deal with overflow
1109 // since we are dealing with concrete values.
1110 rightI = rightI.extOrTrunc(leftI.getBitWidth());
1111
1112 // Offset the increment by the pointer size.
1113 llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
1114 QualType pointeeType = resultTy->getPointeeType();
1115 Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1116 rightI *= Multiplicand;
1117
1118 // Compute the adjusted pointer.
1119 switch (op) {
1120 case BO_Add:
1121 rightI = leftI + rightI;
1122 break;
1123 case BO_Sub:
1124 rightI = leftI - rightI;
1125 break;
1126 default:
1127 llvm_unreachable("Invalid pointer arithmetic operation");
1128 }
1129 return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1130 }
1131 }
1132
1133 // Handle cases where 'lhs' is a region.
1134 if (const MemRegion *region = lhs.getAsRegion()) {
1135 rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1136 SVal index = UnknownVal();
1137 const SubRegion *superR = nullptr;
1138 // We need to know the type of the pointer in order to add an integer to it.
1139 // Depending on the type, different amount of bytes is added.
1140 QualType elementType;
1141
1142 if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
1143 assert(op == BO_Add || op == BO_Sub);
1144 index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1145 getArrayIndexType());
1146 superR = cast<SubRegion>(elemReg->getSuperRegion());
1147 elementType = elemReg->getElementType();
1148 }
1149 else if (isa<SubRegion>(region)) {
1150 assert(op == BO_Add || op == BO_Sub);
1151 index = (op == BO_Add) ? rhs : evalMinus(rhs);
1152 superR = cast<SubRegion>(region);
1153 // TODO: Is this actually reliable? Maybe improving our MemRegion
1154 // hierarchy to provide typed regions for all non-void pointers would be
1155 // better. For instance, we cannot extend this towards LocAsInteger
1156 // operations, where result type of the expression is integer.
1157 if (resultTy->isAnyPointerType())
1158 elementType = resultTy->getPointeeType();
1159 }
1160
1161 // Represent arithmetic on void pointers as arithmetic on char pointers.
1162 // It is fine when a TypedValueRegion of char value type represents
1163 // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1164 if (elementType->isVoidType())
1165 elementType = getContext().CharTy;
1166
1167 if (std::optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1168 return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1169 superR, getContext()));
1170 }
1171 }
1172 return UnknownVal();
1173}
1174
1175const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state,
1176 SVal V) {
1177 if (const llvm::APSInt *Res = getConcreteValue(V))
1178 return Res;
1179
1180 if (SymbolRef Sym = V.getAsSymbol())
1181 return state->getConstraintManager().getSymVal(state, Sym);
1182
1183 return nullptr;
1184}
1185
1186const llvm::APSInt *SimpleSValBuilder::getConcreteValue(SVal V) {
1187 if (std::optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1188 return X->getValue().get();
1189
1190 if (std::optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1191 return X->getValue().get();
1192
1193 return nullptr;
1194}
1195
1196const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1197 SVal V) {
1198 return getConstValue(state, simplifySVal(state, V));
1199}
1200
1201const llvm::APSInt *SimpleSValBuilder::getMinValue(ProgramStateRef state,
1202 SVal V) {
1203 V = simplifySVal(state, V);
1204
1205 if (const llvm::APSInt *Res = getConcreteValue(V))
1206 return Res;
1207
1208 if (SymbolRef Sym = V.getAsSymbol())
1209 return state->getConstraintManager().getSymMinVal(state, Sym);
1210
1211 return nullptr;
1212}
1213
1214const llvm::APSInt *SimpleSValBuilder::getMaxValue(ProgramStateRef state,
1215 SVal V) {
1216 V = simplifySVal(state, V);
1217
1218 if (const llvm::APSInt *Res = getConcreteValue(V))
1219 return Res;
1220
1221 if (SymbolRef Sym = V.getAsSymbol())
1222 return state->getConstraintManager().getSymMaxVal(state, Sym);
1223
1224 return nullptr;
1225}
1226
1227SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
1228 SVal SimplifiedVal = simplifySValOnce(State, Val);
1229 while (SimplifiedVal != Val) {
1230 Val = SimplifiedVal;
1231 SimplifiedVal = simplifySValOnce(State, Val);
1232 }
1233 return SimplifiedVal;
1234}
1235
1236SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1237 return simplifyUntilFixpoint(State, V);
1238}
1239
1240SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
1241 // For now, this function tries to constant-fold symbols inside a
1242 // nonloc::SymbolVal, and does nothing else. More simplifications should
1243 // be possible, such as constant-folding an index in an ElementRegion.
1244
1245 class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1246 ProgramStateRef State;
1247 SValBuilder &SVB;
1248
1249 // Cache results for the lifetime of the Simplifier. Results change every
1250 // time new constraints are added to the program state, which is the whole
1251 // point of simplifying, and for that very reason it's pointless to maintain
1252 // the same cache for the duration of the whole analysis.
1253 llvm::DenseMap<SymbolRef, SVal> Cached;
1254
1255 static bool isUnchanged(SymbolRef Sym, SVal Val) {
1256 return Sym == Val.getAsSymbol();
1257 }
1258
1259 SVal cache(SymbolRef Sym, SVal V) {
1260 Cached[Sym] = V;
1261 return V;
1262 }
1263
1264 SVal skip(SymbolRef Sym) {
1265 return cache(Sym, SVB.makeSymbolVal(Sym));
1266 }
1267
1268 // Return the known const value for the Sym if available, or return Undef
1269 // otherwise.
1270 SVal getConst(SymbolRef Sym) {
1271 const llvm::APSInt *Const =
1272 State->getConstraintManager().getSymVal(State, Sym);
1273 if (Const)
1274 return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
1275 : (SVal)SVB.makeIntVal(*Const);
1276 return UndefinedVal();
1277 }
1278
1279 SVal getConstOrVisit(SymbolRef Sym) {
1280 const SVal Ret = getConst(Sym);
1281 if (Ret.isUndef())
1282 return Visit(Sym);
1283 return Ret;
1284 }
1285
1286 public:
1287 Simplifier(ProgramStateRef State)
1288 : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1289
1290 SVal VisitSymbolData(const SymbolData *S) {
1291 // No cache here.
1292 if (const llvm::APSInt *I =
1293 State->getConstraintManager().getSymVal(State, S))
1294 return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1295 : (SVal)SVB.makeIntVal(*I);
1296 return SVB.makeSymbolVal(S);
1297 }
1298
1299 SVal VisitSymIntExpr(const SymIntExpr *S) {
1300 auto I = Cached.find(S);
1301 if (I != Cached.end())
1302 return I->second;
1303
1304 SVal LHS = getConstOrVisit(S->getLHS());
1305 if (isUnchanged(S->getLHS(), LHS))
1306 return skip(S);
1307
1308 SVal RHS;
1309 // By looking at the APSInt in the right-hand side of S, we cannot
1310 // figure out if it should be treated as a Loc or as a NonLoc.
1311 // So make our guess by recalling that we cannot multiply pointers
1312 // or compare a pointer to an integer.
1313 if (Loc::isLocType(S->getLHS()->getType()) &&
1315 // The usual conversion of $sym to &SymRegion{$sym}, as they have
1316 // the same meaning for Loc-type symbols, but the latter form
1317 // is preferred in SVal computations for being Loc itself.
1318 if (SymbolRef Sym = LHS.getAsSymbol()) {
1319 assert(Loc::isLocType(Sym->getType()));
1320 LHS = SVB.makeLoc(Sym);
1321 }
1322 RHS = SVB.makeIntLocVal(S->getRHS());
1323 } else {
1324 RHS = SVB.makeIntVal(S->getRHS());
1325 }
1326
1327 return cache(
1328 S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1329 }
1330
1331 SVal VisitIntSymExpr(const IntSymExpr *S) {
1332 auto I = Cached.find(S);
1333 if (I != Cached.end())
1334 return I->second;
1335
1336 SVal RHS = getConstOrVisit(S->getRHS());
1337 if (isUnchanged(S->getRHS(), RHS))
1338 return skip(S);
1339
1340 SVal LHS = SVB.makeIntVal(S->getLHS());
1341 return cache(
1342 S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1343 }
1344
1345 SVal VisitSymSymExpr(const SymSymExpr *S) {
1346 auto I = Cached.find(S);
1347 if (I != Cached.end())
1348 return I->second;
1349
1350 // For now don't try to simplify mixed Loc/NonLoc expressions
1351 // because they often appear from LocAsInteger operations
1352 // and we don't know how to combine a LocAsInteger
1353 // with a concrete value.
1354 if (Loc::isLocType(S->getLHS()->getType()) !=
1355 Loc::isLocType(S->getRHS()->getType()))
1356 return skip(S);
1357
1358 SVal LHS = getConstOrVisit(S->getLHS());
1359 SVal RHS = getConstOrVisit(S->getRHS());
1360
1361 if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
1362 return skip(S);
1363
1364 return cache(
1365 S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1366 }
1367
1368 SVal VisitSymbolCast(const SymbolCast *S) {
1369 auto I = Cached.find(S);
1370 if (I != Cached.end())
1371 return I->second;
1372 const SymExpr *OpSym = S->getOperand();
1373 SVal OpVal = getConstOrVisit(OpSym);
1374 if (isUnchanged(OpSym, OpVal))
1375 return skip(S);
1376
1377 return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
1378 }
1379
1380 SVal VisitUnarySymExpr(const UnarySymExpr *S) {
1381 auto I = Cached.find(S);
1382 if (I != Cached.end())
1383 return I->second;
1384 SVal Op = getConstOrVisit(S->getOperand());
1385 if (isUnchanged(S->getOperand(), Op))
1386 return skip(S);
1387
1388 return cache(
1389 S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType()));
1390 }
1391
1392 SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1393
1394 SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1395
1396 SVal VisitSymbolVal(nonloc::SymbolVal V) {
1397 // Simplification is much more costly than computing complexity.
1398 // For high complexity, it may be not worth it.
1399 return Visit(V.getSymbol());
1400 }
1401
1402 SVal VisitSVal(SVal V) { return V; }
1403 };
1404
1405 SVal SimplifiedV = Simplifier(State).Visit(V);
1406 return SimplifiedV;
1407}
#define V(N, I)
static std::optional< int64_t > getConcreteValue(NonLoc SV)
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
mlir::Value getConst(mlir::OpBuilder &bld, mlir::Location loc, mlir::Type typ, unsigned val)
static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym, llvm::APSInt Bound, ProgramStateRef State)
static bool isNegationValuePreserving(const llvm::APSInt &Value, APSIntType ResultType)
static std::optional< NonLoc > tryRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, NonLoc Lhs, NonLoc Rhs, QualType ResultTy)
static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR, const FieldRegion *RightFR, BinaryOperator::Opcode op, QualType resultTy, SimpleSValBuilder &SVB)
static bool isWithinConstantOverflowBounds(SymbolRef Sym, ProgramStateRef State)
static std::pair< SymbolRef, APSIntPtr > decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV)
static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc, Loc LhsLoc)
static std::optional< int64_t > getKnownValue(ProgramStateRef State, SVal V)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CanQualType VoidPtrTy
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4207
bool isComparisonOp() const
Definition Expr.h:4208
static Opcode negateComparisonOp(Opcode Opc)
Definition Expr.h:4213
static Opcode reverseComparisonOp(Opcode Opc)
Definition Expr.h:4226
bool isShiftOp() const
Definition Expr.h:4196
bool isAdditiveOp() const
Definition Expr.h:4194
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
BinaryOperatorKind Opcode
Definition Expr.h:4112
Represents a member of a struct/union/class.
Definition Decl.h:3311
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3547
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
Represents a struct/union/class.
Definition Decl.h:4476
field_range fields() const
Definition Decl.h:4679
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool isAnyPointerType() const
Definition TypeBase.h:8691
A record of the "type" of an APSInt, used for conversions.
Definition APSIntType.h:19
bool isUnsigned() const
Definition APSIntType.h:31
uint32_t getBitWidth() const
Definition APSIntType.h:30
llvm::APSInt getMaxValue() const LLVM_READONLY
Returns the maximum value for this type.
Definition APSIntType.h:65
void apply(llvm::APSInt &Value) const
Convert a given APSInt, in place, to match this type.
Definition APSIntType.h:37
llvm::APSInt convert(const llvm::APSInt &Value) const LLVM_READONLY
Convert and return a new APSInt with the given value, but this type's bit width and signedness.
Definition APSIntType.h:48
llvm::APSInt getValue(uint64_t RawValue) const LLVM_READONLY
Definition APSIntType.h:69
APSIntType getAPSIntType(QualType T) const
Returns the type of the APSInt used to store values of the given QualType.
QualType getType() const override
BinaryOperator::Opcode getOpcode() const
QualType getElementType() const
Definition MemRegion.h:1261
LLVM_ATTRIBUTE_RETURNS_NONNULL const FieldDecl * getDecl() const override
Definition MemRegion.h:1163
static bool isLocType(QualType T)
Definition SVals.h:268
RegionOffset getAsOffset() const
Compute the offset within the top level memory object.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
bool hasSymbolicOffset() const
Definition MemRegion.h:82
const MemRegion * getRegion() const
It might return null.
Definition MemRegion.h:80
int64_t getOffset() const
Definition MemRegion.h:84
BasicValueFactory & getBasicValueFactory()
ProgramStateManager & getStateManager()
SVal makeSymExprValNN(BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)
Constructs a symbolic expression for two non-location values.
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
loc::MemRegionVal makeLoc(SymbolRef sym)
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
DefinedSVal makeSymbolVal(SymbolRef Sym)
Make an SVal that represents the given symbol.
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
const AnalyzerOptions & getAnalyzerOptions() const
QualType getConditionType() const
SVal evalUnaryOp(ProgramStateRef state, UnaryOperator::Opcode opc, SVal operand, QualType type)
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
bool isZeroConstant() const
Definition SVals.cpp:257
SValKind getKind() const
Definition SVals.h:92
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition SVals.cpp:103
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition SVals.cpp:180
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
Definition SVals.cpp:67
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition MemRegion.h:493
Symbolic value.
Definition SymExpr.h:32
virtual QualType getType() const =0
QualType getType() const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const SymExpr * getOperand() const
QualType getType() const override
UnaryOperator::Opcode getOpcode() const
const SymExpr * getOperand() const
Value representing integer constant.
Definition SVals.h:306
Represents symbolic expression that isn't a location.
Definition SVals.h:285
SValBuilder * createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, ProgramStateManager &stateMgr)
BinarySymExprImpl< APSIntPtr, const SymExpr *, SymExpr::Kind::IntSymExprKind > IntSymExpr
Represents a symbolic expression like 3 - 'x'.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
BinarySymExprImpl< const SymExpr *, const SymExpr *, SymExpr::Kind::SymSymExprKind > SymSymExpr
Represents a symbolic expression like 'x' + 'y'.
BinarySymExprImpl< const SymExpr *, APSIntPtr, SymExpr::Kind::SymIntExprKind > SymIntExpr
Represents a symbolic expression like 'x' + 3.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:278
bool Const(InterpState &S, const T &Arg)
Definition Interp.h:1584
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
QualType pointeeType(QualType T)
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t