clang 20.0.0git
SValBuilder.cpp
Go to the documentation of this file.
1//===- SValBuilder.cpp - Basic class for all SValBuilder implementations --===//
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 SValBuilder, the base class for all (complete) SValBuilder
10// implementations.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/Stmt.h"
21#include "clang/AST/Type.h"
23#include "clang/Basic/LLVM.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/Compiler.h"
39#include <cassert>
40#include <optional>
41#include <tuple>
42
43using namespace clang;
44using namespace ento;
45
46//===----------------------------------------------------------------------===//
47// Basic SVal creation.
48//===----------------------------------------------------------------------===//
49
50void SValBuilder::anchor() {}
51
52SValBuilder::SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
53 ProgramStateManager &stateMgr)
54 : Context(context), BasicVals(context, alloc),
55 SymMgr(context, BasicVals, alloc), MemMgr(context, alloc),
56 StateMgr(stateMgr),
57 AnOpts(
58 stateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions()),
59 ArrayIndexTy(context.LongLongTy),
60 ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) {}
61
64 return makeNullWithType(type);
65
66 if (type->isIntegralOrEnumerationType())
67 return makeIntVal(0, type);
68
69 if (type->isArrayType() || type->isRecordType() || type->isVectorType() ||
70 type->isAnyComplexType())
72
73 // FIXME: Handle floats.
74 return UnknownVal();
75}
76
79 APSIntPtr rhs, QualType type) {
80 assert(lhs);
81 assert(!Loc::isLocType(type));
82 return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
83}
84
87 const SymExpr *rhs, QualType type) {
88 assert(rhs);
89 assert(!Loc::isLocType(type));
90 return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
91}
92
95 const SymExpr *rhs, QualType type) {
96 assert(lhs && rhs);
97 assert(!Loc::isLocType(type));
98 return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
99}
100
102 QualType type) {
103 assert(operand);
104 assert(!Loc::isLocType(type));
105 return nonloc::SymbolVal(SymMgr.getUnarySymExpr(operand, op, type));
106}
107
109 QualType fromTy, QualType toTy) {
110 assert(operand);
111 assert(!Loc::isLocType(toTy));
112 if (fromTy == toTy)
113 return nonloc::SymbolVal(operand);
114 return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
115}
116
118 if (val.isUnknownOrUndef())
119 return val;
120
121 // Common case: we have an appropriately sized integer.
122 if (std::optional<nonloc::ConcreteInt> CI =
123 val.getAs<nonloc::ConcreteInt>()) {
124 const llvm::APSInt& I = CI->getValue();
125 if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
126 return val;
127 }
128
129 return evalCast(val, ArrayIndexTy, QualType{});
130}
131
133 return makeTruthVal(boolean->getValue());
134}
135
138 QualType T = region->getValueType();
139
140 if (T->isNullPtrType())
141 return makeZeroVal(T);
142
144 return UnknownVal();
145
147
148 if (Loc::isLocType(T))
150
151 return nonloc::SymbolVal(sym);
152}
153
155 const Expr *Ex,
156 const LocationContext *LCtx,
157 unsigned Count) {
158 QualType T = Ex->getType();
159
160 if (T->isNullPtrType())
161 return makeZeroVal(T);
162
163 // Compute the type of the result. If the expression is not an R-value, the
164 // result should be a location.
165 QualType ExType = Ex->getType();
166 if (Ex->isGLValue())
168
169 return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count);
170}
171
173 const Stmt *St,
174 const LocationContext *LCtx,
176 unsigned count) {
177 if (type->isNullPtrType())
178 return makeZeroVal(type);
179
181 return UnknownVal();
182
183 SymbolRef sym = SymMgr.conjureSymbol(St, LCtx, type, count, symbolTag);
184
185 if (Loc::isLocType(type))
187
188 return nonloc::SymbolVal(sym);
189}
190
192 const LocationContext *LCtx,
194 unsigned visitCount) {
195 if (type->isNullPtrType())
196 return makeZeroVal(type);
197
199 return UnknownVal();
200
201 SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount);
202
203 if (Loc::isLocType(type))
205
206 return nonloc::SymbolVal(sym);
207}
208
210 const LocationContext *LCtx,
211 unsigned VisitCount) {
212 QualType T = E->getType();
213 return getConjuredHeapSymbolVal(E, LCtx, T, VisitCount);
214}
215
217 const LocationContext *LCtx,
219 unsigned VisitCount) {
220 assert(Loc::isLocType(type));
222 if (type->isNullPtrType()) {
223 // makeZeroVal() returns UnknownVal only in case of FP number, which
224 // is not the case.
226 }
227
230}
231
233 const LocationContext *LCtx,
234 unsigned VisitCount) {
235 const AllocaRegion *R =
237 return loc::MemRegionVal(R);
238}
239
241 const MemRegion *region,
242 const Expr *expr, QualType type,
243 const LocationContext *LCtx,
244 unsigned count) {
245 assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
246
247 SymbolRef sym =
248 SymMgr.getMetadataSymbol(region, expr, type, LCtx, count, symbolTag);
249
250 if (Loc::isLocType(type))
252
253 return nonloc::SymbolVal(sym);
254}
255
258 const TypedValueRegion *region) {
259 QualType T = region->getValueType();
260
261 if (T->isNullPtrType())
262 return makeZeroVal(T);
263
265 return UnknownVal();
266
267 SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
268
269 if (Loc::isLocType(T))
271
272 return nonloc::SymbolVal(sym);
273}
274
276 assert(!ND || (isa<CXXMethodDecl, FieldDecl, IndirectFieldDecl>(ND)));
277
278 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
279 // Sema treats pointers to static member functions as have function pointer
280 // type, so return a function pointer for the method.
281 // We don't need to play a similar trick for static member fields
282 // because these are represented as plain VarDecls and not FieldDecls
283 // in the AST.
284 if (!MD->isImplicitObjectMemberFunction())
285 return getFunctionPointer(MD);
286 }
287
288 return nonloc::PointerToMember(ND);
289}
290
293}
294
296 CanQualType locTy,
297 const LocationContext *locContext,
298 unsigned blockCount) {
299 const BlockCodeRegion *BC =
300 MemMgr.getBlockCodeRegion(block, locTy, locContext->getAnalysisDeclContext());
301 const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext,
302 blockCount);
303 return loc::MemRegionVal(BD);
304}
305
306std::optional<loc::MemRegionVal>
308 if (auto OptR = StateMgr.getStoreManager().castRegion(R, Ty))
309 return loc::MemRegionVal(*OptR);
310 return std::nullopt;
311}
312
313/// Return a memory region for the 'this' object reference.
315 const StackFrameContext *SFC) {
316 return loc::MemRegionVal(
317 getRegionManager().getCXXThisRegion(D->getThisType(), SFC));
318}
319
320/// Return a memory region for the 'this' object reference.
322 const StackFrameContext *SFC) {
323 const Type *T = D->getTypeForDecl();
325 return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
326}
327
328std::optional<SVal> SValBuilder::getConstantVal(const Expr *E) {
329 E = E->IgnoreParens();
330
331 switch (E->getStmtClass()) {
332 // Handle expressions that we treat differently from the AST's constant
333 // evaluator.
334 case Stmt::AddrLabelExprClass:
335 return makeLoc(cast<AddrLabelExpr>(E));
336
337 case Stmt::CXXScalarValueInitExprClass:
338 case Stmt::ImplicitValueInitExprClass:
339 return makeZeroVal(E->getType());
340
341 case Stmt::ObjCStringLiteralClass: {
342 const auto *SL = cast<ObjCStringLiteral>(E);
343 return makeLoc(getRegionManager().getObjCStringRegion(SL));
344 }
345
346 case Stmt::StringLiteralClass: {
347 const auto *SL = cast<StringLiteral>(E);
348 return makeLoc(getRegionManager().getStringRegion(SL));
349 }
350
351 case Stmt::PredefinedExprClass: {
352 const auto *PE = cast<PredefinedExpr>(E);
353 assert(PE->getFunctionName() &&
354 "Since we analyze only instantiated functions, PredefinedExpr "
355 "should have a function name.");
356 return makeLoc(getRegionManager().getStringRegion(PE->getFunctionName()));
357 }
358
359 // Fast-path some expressions to avoid the overhead of going through the AST's
360 // constant evaluator
361 case Stmt::CharacterLiteralClass: {
362 const auto *C = cast<CharacterLiteral>(E);
363 return makeIntVal(C->getValue(), C->getType());
364 }
365
366 case Stmt::CXXBoolLiteralExprClass:
367 return makeBoolVal(cast<CXXBoolLiteralExpr>(E));
368
369 case Stmt::TypeTraitExprClass: {
370 const auto *TE = cast<TypeTraitExpr>(E);
371 return makeTruthVal(TE->getValue(), TE->getType());
372 }
373
374 case Stmt::IntegerLiteralClass:
375 return makeIntVal(cast<IntegerLiteral>(E));
376
377 case Stmt::ObjCBoolLiteralExprClass:
378 return makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
379
380 case Stmt::CXXNullPtrLiteralExprClass:
381 return makeNullWithType(E->getType());
382
383 case Stmt::CStyleCastExprClass:
384 case Stmt::CXXFunctionalCastExprClass:
385 case Stmt::CXXConstCastExprClass:
386 case Stmt::CXXReinterpretCastExprClass:
387 case Stmt::CXXStaticCastExprClass:
388 case Stmt::ImplicitCastExprClass: {
389 const auto *CE = cast<CastExpr>(E);
390 switch (CE->getCastKind()) {
391 default:
392 break;
393 case CK_ArrayToPointerDecay:
394 case CK_IntegralToPointer:
395 case CK_NoOp:
396 case CK_BitCast: {
397 const Expr *SE = CE->getSubExpr();
398 std::optional<SVal> Val = getConstantVal(SE);
399 if (!Val)
400 return std::nullopt;
401 return evalCast(*Val, CE->getType(), SE->getType());
402 }
403 }
404 [[fallthrough]];
405 }
406
407 // If we don't have a special case, fall back to the AST's constant evaluator.
408 default: {
409 // Don't try to come up with a value for materialized temporaries.
410 if (E->isGLValue())
411 return std::nullopt;
412
413 ASTContext &Ctx = getContext();
415 if (E->EvaluateAsInt(Result, Ctx))
416 return makeIntVal(Result.Val.getInt());
417
418 if (Loc::isLocType(E->getType()))
420 return makeNullWithType(E->getType());
421
422 return std::nullopt;
423 }
424 }
425}
426
428 NonLoc LHS, NonLoc RHS,
429 QualType ResultTy) {
430 SymbolRef symLHS = LHS.getAsSymbol();
431 SymbolRef symRHS = RHS.getAsSymbol();
432
433 // TODO: When the Max Complexity is reached, we should conjure a symbol
434 // instead of generating an Unknown value and propagate the taint info to it.
435 const unsigned MaxComp = AnOpts.MaxSymbolComplexity;
436
437 if (symLHS && symRHS &&
438 (symLHS->computeComplexity() + symRHS->computeComplexity()) < MaxComp)
439 return makeNonLoc(symLHS, Op, symRHS, ResultTy);
440
441 if (symLHS && symLHS->computeComplexity() < MaxComp)
442 if (std::optional<nonloc::ConcreteInt> rInt =
444 return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
445
446 if (symRHS && symRHS->computeComplexity() < MaxComp)
447 if (std::optional<nonloc::ConcreteInt> lInt =
449 return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
450
451 return UnknownVal();
452}
453
455 switch (X.getKind()) {
456 case nonloc::ConcreteIntKind:
457 return makeIntVal(-X.castAs<nonloc::ConcreteInt>().getValue());
458 case nonloc::SymbolValKind:
459 return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Minus,
460 X.getType(Context));
461 default:
462 return UnknownVal();
463 }
464}
465
467 switch (X.getKind()) {
468 case nonloc::ConcreteIntKind:
469 return makeIntVal(~X.castAs<nonloc::ConcreteInt>().getValue());
470 case nonloc::SymbolValKind:
471 return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Not,
472 X.getType(Context));
473 default:
474 return UnknownVal();
475 }
476}
477
479 SVal operand, QualType type) {
480 auto OpN = operand.getAs<NonLoc>();
481 if (!OpN)
482 return UnknownVal();
483
484 if (opc == UO_Minus)
485 return evalMinus(*OpN);
486 if (opc == UO_Not)
487 return evalComplement(*OpN);
488 llvm_unreachable("Unexpected unary operator");
489}
490
492 SVal lhs, SVal rhs, QualType type) {
493 if (lhs.isUndef() || rhs.isUndef())
494 return UndefinedVal();
495
496 if (lhs.isUnknown() || rhs.isUnknown())
497 return UnknownVal();
498
499 if (isa<nonloc::LazyCompoundVal>(lhs) || isa<nonloc::LazyCompoundVal>(rhs)) {
500 return UnknownVal();
501 }
502
503 if (op == BinaryOperatorKind::BO_Cmp) {
504 // We can't reason about C++20 spaceship operator yet.
505 //
506 // FIXME: Support C++20 spaceship operator.
507 // The main problem here is that the result is not integer.
508 return UnknownVal();
509 }
510
511 if (std::optional<Loc> LV = lhs.getAs<Loc>()) {
512 if (std::optional<Loc> RV = rhs.getAs<Loc>())
513 return evalBinOpLL(state, op, *LV, *RV, type);
514
515 return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
516 }
517
518 if (const std::optional<Loc> RV = rhs.getAs<Loc>()) {
519 const auto IsCommutative = [](BinaryOperatorKind Op) {
520 return Op == BO_Mul || Op == BO_Add || Op == BO_And || Op == BO_Xor ||
521 Op == BO_Or;
522 };
523
524 if (IsCommutative(op)) {
525 // Swap operands.
526 return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
527 }
528
529 // If the right operand is a concrete int location then we have nothing
530 // better but to treat it as a simple nonloc.
531 if (auto RV = rhs.getAs<loc::ConcreteInt>()) {
532 const nonloc::ConcreteInt RhsAsLoc = makeIntVal(RV->getValue());
533 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), RhsAsLoc, type);
534 }
535 }
536
537 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
538 type);
539}
540
542 SVal rhs) {
543 return state->isNonNull(evalEQ(state, lhs, rhs));
544}
545
547 return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType());
548}
549
553 return evalEQ(state, static_cast<SVal>(lhs), static_cast<SVal>(rhs))
555}
556
557/// Recursively check if the pointer types are equal modulo const, volatile,
558/// and restrict qualifiers. Also, assume that all types are similar to 'void'.
559/// Assumes the input types are canonical.
560static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
561 QualType FromTy) {
562 while (Context.UnwrapSimilarTypes(ToTy, FromTy)) {
563 Qualifiers Quals1, Quals2;
564 ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
565 FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
566
567 // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address
568 // spaces) are identical.
569 Quals1.removeCVRQualifiers();
570 Quals2.removeCVRQualifiers();
571 if (Quals1 != Quals2)
572 return false;
573 }
574
575 // If we are casting to void, the 'From' value can be used to represent the
576 // 'To' value.
577 //
578 // FIXME: Doing this after unwrapping the types doesn't make any sense. A
579 // cast from 'int**' to 'void**' is not special in the way that a cast from
580 // 'int*' to 'void*' is.
581 if (ToTy->isVoidType())
582 return true;
583
584 if (ToTy != FromTy)
585 return false;
586
587 return true;
588}
589
590// Handles casts of type CK_IntegralCast.
591// At the moment, this function will redirect to evalCast, except when the range
592// of the original value is known to be greater than the max of the target type.
594 QualType castTy, QualType originalTy) {
595 // No truncations if target type is big enough.
596 if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
597 return evalCast(val, castTy, originalTy);
598
599 auto AsNonLoc = val.getAs<NonLoc>();
600 SymbolRef AsSymbol = val.getAsSymbol();
601 if (!AsSymbol || !AsNonLoc) // Let evalCast handle non symbolic expressions.
602 return evalCast(val, castTy, originalTy);
603
604 // Find the maximum value of the target type.
605 APSIntType ToType(getContext().getTypeSize(castTy),
606 castTy->isUnsignedIntegerType());
607 llvm::APSInt ToTypeMax = ToType.getMaxValue();
608
609 NonLoc ToTypeMaxVal = makeIntVal(ToTypeMax);
610
611 // Check the range of the symbol being casted against the maximum value of the
612 // target type.
613 QualType CmpTy = getConditionType();
614 NonLoc CompVal = evalBinOpNN(state, BO_LE, *AsNonLoc, ToTypeMaxVal, CmpTy)
615 .castAs<NonLoc>();
616 ProgramStateRef IsNotTruncated, IsTruncated;
617 std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
618 if (!IsNotTruncated && IsTruncated) {
619 // Symbol is truncated so we evaluate it as a cast.
620 return makeNonLoc(AsSymbol, originalTy, castTy);
621 }
622 return evalCast(val, castTy, originalTy);
623}
624
625//===----------------------------------------------------------------------===//
626// Cast method.
627// `evalCast` and its helper `EvalCastVisitor`
628//===----------------------------------------------------------------------===//
629
630namespace {
631class EvalCastVisitor : public SValVisitor<EvalCastVisitor, SVal> {
632private:
633 SValBuilder &VB;
634 ASTContext &Context;
635 QualType CastTy, OriginalTy;
636
637public:
638 EvalCastVisitor(SValBuilder &VB, QualType CastTy, QualType OriginalTy)
639 : VB(VB), Context(VB.getContext()), CastTy(CastTy),
640 OriginalTy(OriginalTy) {}
641
642 SVal Visit(SVal V) {
643 if (CastTy.isNull())
644 return V;
645
646 CastTy = Context.getCanonicalType(CastTy);
647
648 const bool IsUnknownOriginalType = OriginalTy.isNull();
649 if (!IsUnknownOriginalType) {
650 OriginalTy = Context.getCanonicalType(OriginalTy);
651
652 if (CastTy == OriginalTy)
653 return V;
654
655 // FIXME: Move this check to the most appropriate
656 // evalCastKind/evalCastSubKind function. For const casts, casts to void,
657 // just propagate the value.
658 if (!CastTy->isVariableArrayType() && !OriginalTy->isVariableArrayType())
659 if (shouldBeModeledWithNoOp(Context, Context.getPointerType(CastTy),
660 Context.getPointerType(OriginalTy)))
661 return V;
662 }
663 return SValVisitor::Visit(V);
664 }
665 SVal VisitUndefinedVal(UndefinedVal V) { return V; }
666 SVal VisitUnknownVal(UnknownVal V) { return V; }
667 SVal VisitConcreteInt(loc::ConcreteInt V) {
668 // Pointer to bool.
669 if (CastTy->isBooleanType())
670 return VB.makeTruthVal(V.getValue()->getBoolValue(), CastTy);
671
672 // Pointer to integer.
673 if (CastTy->isIntegralOrEnumerationType()) {
674 llvm::APSInt Value = V.getValue();
676 return VB.makeIntVal(Value);
677 }
678
679 // Pointer to any pointer.
680 if (Loc::isLocType(CastTy)) {
681 llvm::APSInt Value = V.getValue();
683 return loc::ConcreteInt(VB.getBasicValueFactory().getValue(Value));
684 }
685
686 // Pointer to whatever else.
687 return UnknownVal();
688 }
689 SVal VisitGotoLabel(loc::GotoLabel V) {
690 // Pointer to bool.
691 if (CastTy->isBooleanType())
692 // Labels are always true.
693 return VB.makeTruthVal(true, CastTy);
694
695 // Pointer to integer.
696 if (CastTy->isIntegralOrEnumerationType()) {
697 const unsigned BitWidth = Context.getIntWidth(CastTy);
698 return VB.makeLocAsInteger(V, BitWidth);
699 }
700
701 const bool IsUnknownOriginalType = OriginalTy.isNull();
702 if (!IsUnknownOriginalType) {
703 // Array to pointer.
704 if (isa<ArrayType>(OriginalTy))
705 if (CastTy->isPointerType() || CastTy->isReferenceType())
706 return UnknownVal();
707 }
708
709 // Pointer to any pointer.
710 if (Loc::isLocType(CastTy))
711 return V;
712
713 // Pointer to whatever else.
714 return UnknownVal();
715 }
716 SVal VisitMemRegionVal(loc::MemRegionVal V) {
717 // Pointer to bool.
718 if (CastTy->isBooleanType()) {
719 const MemRegion *R = V.getRegion();
720 if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
721 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
722 if (FD->isWeak())
723 // FIXME: Currently we are using an extent symbol here,
724 // because there are no generic region address metadata
725 // symbols to use, only content metadata.
726 return nonloc::SymbolVal(
728
729 if (const SymbolicRegion *SymR = R->getSymbolicBase()) {
730 SymbolRef Sym = SymR->getSymbol();
731 QualType Ty = Sym->getType();
732 // This change is needed for architectures with varying
733 // pointer widths. See the amdgcn opencl reproducer with
734 // this change as an example: solver-sym-simplification-ptr-bool.cl
735 if (!Ty->isReferenceType())
736 return VB.makeNonLoc(
737 Sym, BO_NE, VB.getBasicValueFactory().getZeroWithTypeSize(Ty),
738 CastTy);
739 }
740 // Non-symbolic memory regions are always true.
741 return VB.makeTruthVal(true, CastTy);
742 }
743
744 const bool IsUnknownOriginalType = OriginalTy.isNull();
745 // Try to cast to array
746 const auto *ArrayTy =
747 IsUnknownOriginalType
748 ? nullptr
749 : dyn_cast<ArrayType>(OriginalTy.getCanonicalType());
750
751 // Pointer to integer.
752 if (CastTy->isIntegralOrEnumerationType()) {
753 SVal Val = V;
754 // Array to integer.
755 if (ArrayTy) {
756 // We will always decay to a pointer.
757 QualType ElemTy = ArrayTy->getElementType();
758 Val = VB.getStateManager().ArrayToPointer(V, ElemTy);
759 // FIXME: Keep these here for now in case we decide soon that we
760 // need the original decayed type.
761 // QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
762 // QualType pointerTy = C.getPointerType(elemTy);
763 }
764 const unsigned BitWidth = Context.getIntWidth(CastTy);
765 return VB.makeLocAsInteger(Val.castAs<Loc>(), BitWidth);
766 }
767
768 // Pointer to pointer.
769 if (Loc::isLocType(CastTy)) {
770
771 if (IsUnknownOriginalType) {
772 // When retrieving symbolic pointer and expecting a non-void pointer,
773 // wrap them into element regions of the expected type if necessary.
774 // It is necessary to make sure that the retrieved value makes sense,
775 // because there's no other cast in the AST that would tell us to cast
776 // it to the correct pointer type. We might need to do that for non-void
777 // pointers as well.
778 // FIXME: We really need a single good function to perform casts for us
779 // correctly every time we need it.
780 const MemRegion *R = V.getRegion();
781 if (CastTy->isPointerType() && !CastTy->isVoidPointerType()) {
782 if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
783 QualType SRTy = SR->getSymbol()->getType();
784
785 auto HasSameUnqualifiedPointeeType = [](QualType ty1,
786 QualType ty2) {
787 return ty1->getPointeeType().getCanonicalType().getTypePtr() ==
789 };
790 if (!HasSameUnqualifiedPointeeType(SRTy, CastTy)) {
791 if (auto OptMemRegV = VB.getCastedMemRegionVal(SR, CastTy))
792 return *OptMemRegV;
793 }
794 }
795 }
796 // Next fixes pointer dereference using type different from its initial
797 // one. See PR37503 and PR49007 for details.
798 if (const auto *ER = dyn_cast<ElementRegion>(R)) {
799 if (auto OptMemRegV = VB.getCastedMemRegionVal(ER, CastTy))
800 return *OptMemRegV;
801 }
802
803 return V;
804 }
805
806 if (OriginalTy->isIntegralOrEnumerationType() ||
807 OriginalTy->isBlockPointerType() ||
808 OriginalTy->isFunctionPointerType())
809 return V;
810
811 // Array to pointer.
812 if (ArrayTy) {
813 // Are we casting from an array to a pointer? If so just pass on
814 // the decayed value.
815 if (CastTy->isPointerType() || CastTy->isReferenceType()) {
816 // We will always decay to a pointer.
817 QualType ElemTy = ArrayTy->getElementType();
818 return VB.getStateManager().ArrayToPointer(V, ElemTy);
819 }
820 // Are we casting from an array to an integer? If so, cast the decayed
821 // pointer value to an integer.
822 assert(CastTy->isIntegralOrEnumerationType());
823 }
824
825 // Other pointer to pointer.
826 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() ||
827 CastTy->isReferenceType());
828
829 // We get a symbolic function pointer for a dereference of a function
830 // pointer, but it is of function type. Example:
831
832 // struct FPRec {
833 // void (*my_func)(int * x);
834 // };
835 //
836 // int bar(int x);
837 //
838 // int f1_a(struct FPRec* foo) {
839 // int x;
840 // (*foo->my_func)(&x);
841 // return bar(x)+1; // no-warning
842 // }
843
844 // Get the result of casting a region to a different type.
845 const MemRegion *R = V.getRegion();
846 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
847 return *OptMemRegV;
848 }
849
850 // Pointer to whatever else.
851 // FIXME: There can be gross cases where one casts the result of a
852 // function (that returns a pointer) to some other value that happens to
853 // fit within that pointer value. We currently have no good way to model
854 // such operations. When this happens, the underlying operation is that
855 // the caller is reasoning about bits. Conceptually we are layering a
856 // "view" of a location on top of those bits. Perhaps we need to be more
857 // lazy about mutual possible views, even on an SVal? This may be
858 // necessary for bit-level reasoning as well.
859 return UnknownVal();
860 }
861 SVal VisitCompoundVal(nonloc::CompoundVal V) {
862 // Compound to whatever.
863 return UnknownVal();
864 }
865 SVal VisitConcreteInt(nonloc::ConcreteInt V) {
866 auto CastedValue = [V, this]() {
867 llvm::APSInt Value = V.getValue();
869 return Value;
870 };
871
872 // Integer to bool.
873 if (CastTy->isBooleanType())
874 return VB.makeTruthVal(V.getValue()->getBoolValue(), CastTy);
875
876 // Integer to pointer.
877 if (CastTy->isIntegralOrEnumerationType())
878 return VB.makeIntVal(CastedValue());
879
880 // Integer to pointer.
881 if (Loc::isLocType(CastTy))
882 return VB.makeIntLocVal(CastedValue());
883
884 // Pointer to whatever else.
885 return UnknownVal();
886 }
887 SVal VisitLazyCompoundVal(nonloc::LazyCompoundVal V) {
888 // LazyCompound to whatever.
889 return UnknownVal();
890 }
891 SVal VisitLocAsInteger(nonloc::LocAsInteger V) {
892 Loc L = V.getLoc();
893
894 // Pointer as integer to bool.
895 if (CastTy->isBooleanType())
896 // Pass to Loc function.
897 return Visit(L);
898
899 const bool IsUnknownOriginalType = OriginalTy.isNull();
900 // Pointer as integer to pointer.
901 if (!IsUnknownOriginalType && Loc::isLocType(CastTy) &&
902 OriginalTy->isIntegralOrEnumerationType()) {
903 if (const MemRegion *R = L.getAsRegion())
904 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
905 return *OptMemRegV;
906 return L;
907 }
908
909 // Pointer as integer with region to integer/pointer.
910 const MemRegion *R = L.getAsRegion();
911 if (!IsUnknownOriginalType && R) {
912 if (CastTy->isIntegralOrEnumerationType())
913 return VisitMemRegionVal(loc::MemRegionVal(R));
914
915 if (Loc::isLocType(CastTy)) {
916 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() ||
917 CastTy->isReferenceType());
918 // Delegate to store manager to get the result of casting a region to a
919 // different type. If the MemRegion* returned is NULL, this expression
920 // Evaluates to UnknownVal.
921 if (auto OptMemRegV = VB.getCastedMemRegionVal(R, CastTy))
922 return *OptMemRegV;
923 }
924 } else {
925 if (Loc::isLocType(CastTy)) {
926 if (IsUnknownOriginalType)
927 return VisitMemRegionVal(loc::MemRegionVal(R));
928 return L;
929 }
930
931 SymbolRef SE = nullptr;
932 if (R) {
933 if (const SymbolicRegion *SR =
934 dyn_cast<SymbolicRegion>(R->StripCasts())) {
935 SE = SR->getSymbol();
936 }
937 }
938
939 if (!CastTy->isFloatingType() || !SE || SE->getType()->isFloatingType()) {
940 // FIXME: Correctly support promotions/truncations.
941 const unsigned CastSize = Context.getIntWidth(CastTy);
942 if (CastSize == V.getNumBits())
943 return V;
944
945 return VB.makeLocAsInteger(L, CastSize);
946 }
947 }
948
949 // Pointer as integer to whatever else.
950 return UnknownVal();
951 }
952 SVal VisitSymbolVal(nonloc::SymbolVal V) {
953 SymbolRef SE = V.getSymbol();
954
955 const bool IsUnknownOriginalType = OriginalTy.isNull();
956 // Symbol to bool.
957 if (!IsUnknownOriginalType && CastTy->isBooleanType()) {
958 // Non-float to bool.
959 if (Loc::isLocType(OriginalTy) ||
960 OriginalTy->isIntegralOrEnumerationType() ||
961 OriginalTy->isMemberPointerType()) {
963 return VB.makeNonLoc(SE, BO_NE, BVF.getValue(0, SE->getType()), CastTy);
964 }
965 } else {
966 // Symbol to integer, float.
967 QualType T = Context.getCanonicalType(SE->getType());
968
969 // Produce SymbolCast if CastTy and T are different integers.
970 // NOTE: In the end the type of SymbolCast shall be equal to CastTy.
977 // If appropriate option is disabled, ignore the cast.
978 // NOTE: ShouldSupportSymbolicIntegerCasts is `false` by default.
979 if (!Opts.ShouldSupportSymbolicIntegerCasts)
980 return V;
981 return simplifySymbolCast(V, CastTy);
982 }
983 if (!Loc::isLocType(CastTy))
984 if (!IsUnknownOriginalType || !CastTy->isFloatingType() ||
985 T->isFloatingType())
986 return VB.makeNonLoc(SE, T, CastTy);
987 }
988
989 // FIXME: We should be able to cast NonLoc -> Loc
990 // (when Loc::isLocType(CastTy) is true)
991 // But it's hard to do as SymbolicRegions can't refer to SymbolCasts holding
992 // generic SymExprs. Check the commit message for the details.
993
994 // Symbol to pointer and whatever else.
995 return UnknownVal();
996 }
997 SVal VisitPointerToMember(nonloc::PointerToMember V) {
998 // Member pointer to whatever.
999 return V;
1000 }
1001
1002 /// Reduce cast expression by removing redundant intermediate casts.
1003 /// E.g.
1004 /// - (char)(short)(int x) -> (char)(int x)
1005 /// - (int)(int x) -> int x
1006 ///
1007 /// \param V -- SymbolVal, which pressumably contains SymbolCast or any symbol
1008 /// that is applicable for cast operation.
1009 /// \param CastTy -- QualType, which `V` shall be cast to.
1010 /// \return SVal with simplified cast expression.
1011 /// \note: Currently only support integral casts.
1012 nonloc::SymbolVal simplifySymbolCast(nonloc::SymbolVal V, QualType CastTy) {
1013 // We use seven conditions to recognize a simplification case.
1014 // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type -
1015 // `R`, prefix `u` for unsigned, `s` for signed, no prefix - any sign: E.g.
1016 // (char)(short)(uint x)
1017 // ( sC )( sT )( uR x)
1018 //
1019 // C === R (the same type)
1020 // (char)(char x) -> (char x)
1021 // (long)(long x) -> (long x)
1022 // Note: Comparisons operators below are for bit width.
1023 // C == T
1024 // (short)(short)(int x) -> (short)(int x)
1025 // (int)(long)(char x) -> (int)(char x) (sizeof(long) == sizeof(int))
1026 // (long)(ullong)(char x) -> (long)(char x) (sizeof(long) ==
1027 // sizeof(ullong))
1028 // C < T
1029 // (short)(int)(char x) -> (short)(char x)
1030 // (char)(int)(short x) -> (char)(short x)
1031 // (short)(int)(short x) -> (short x)
1032 // C > T > uR
1033 // (int)(short)(uchar x) -> (int)(uchar x)
1034 // (uint)(short)(uchar x) -> (uint)(uchar x)
1035 // (int)(ushort)(uchar x) -> (int)(uchar x)
1036 // C > sT > sR
1037 // (int)(short)(char x) -> (int)(char x)
1038 // (uint)(short)(char x) -> (uint)(char x)
1039 // C > sT == sR
1040 // (int)(char)(char x) -> (int)(char x)
1041 // (uint)(short)(short x) -> (uint)(short x)
1042 // C > uT == uR
1043 // (int)(uchar)(uchar x) -> (int)(uchar x)
1044 // (uint)(ushort)(ushort x) -> (uint)(ushort x)
1045 // (llong)(ulong)(uint x) -> (llong)(uint x) (sizeof(ulong) ==
1046 // sizeof(uint))
1047
1048 SymbolRef SE = V.getSymbol();
1049 QualType T = Context.getCanonicalType(SE->getType());
1050
1051 if (T == CastTy)
1052 return V;
1053
1054 if (!isa<SymbolCast>(SE))
1055 return VB.makeNonLoc(SE, T, CastTy);
1056
1057 SymbolRef RootSym = cast<SymbolCast>(SE)->getOperand();
1058 QualType RT = RootSym->getType().getCanonicalType();
1059
1060 // FIXME support simplification from non-integers.
1061 if (!RT->isIntegralOrEnumerationType())
1062 return VB.makeNonLoc(SE, T, CastTy);
1063
1065 APSIntType CTy = BVF.getAPSIntType(CastTy);
1066 APSIntType TTy = BVF.getAPSIntType(T);
1067
1068 const auto WC = CTy.getBitWidth();
1069 const auto WT = TTy.getBitWidth();
1070
1071 if (WC <= WT) {
1072 const bool isSameType = (RT == CastTy);
1073 if (isSameType)
1074 return nonloc::SymbolVal(RootSym);
1075 return VB.makeNonLoc(RootSym, RT, CastTy);
1076 }
1077
1078 APSIntType RTy = BVF.getAPSIntType(RT);
1079 const auto WR = RTy.getBitWidth();
1080 const bool UT = TTy.isUnsigned();
1081 const bool UR = RTy.isUnsigned();
1082
1083 if (((WT > WR) && (UR || !UT)) || ((WT == WR) && (UT == UR)))
1084 return VB.makeNonLoc(RootSym, RT, CastTy);
1085
1086 return VB.makeNonLoc(SE, T, CastTy);
1087 }
1088};
1089} // end anonymous namespace
1090
1091/// Cast a given SVal to another SVal using given QualType's.
1092/// \param V -- SVal that should be casted.
1093/// \param CastTy -- QualType that V should be casted according to.
1094/// \param OriginalTy -- QualType which is associated to V. It provides
1095/// additional information about what type the cast performs from.
1096/// \returns the most appropriate casted SVal.
1097/// Note: Many cases don't use an exact OriginalTy. It can be extracted
1098/// from SVal or the cast can performs unconditionaly. Always pass OriginalTy!
1099/// It can be crucial in certain cases and generates different results.
1100/// FIXME: If `OriginalTy.isNull()` is true, then cast performs based on CastTy
1101/// only. This behavior is uncertain and should be improved.
1103 EvalCastVisitor TRV{*this, CastTy, OriginalTy};
1104 return TRV.Visit(V);
1105}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
#define X(type, name)
Definition: Value.h:144
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::DenseMap< const CFGBlock *, unsigned > VisitCount
Definition: Logger.cpp:30
static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy, QualType FromTy)
Recursively check if the pointer types are equal modulo const, volatile, and restrict qualifiers.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
ASTContext & getASTContext() const
Stores options for the analyzer from the command line.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
bool getValue() const
Definition: ExprCXX.h:737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3963
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1935
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
This represents a decl that may have a name.
Definition: Decl.h:253
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
QualType getCanonicalType() const
Definition: Type.h:7983
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
It represents a stack frame of the call stack (based on CallEvent).
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1390
The base class of the type hierarchy.
Definition: Type.h:1828
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:8204
bool isVariableArrayType() const
Definition: Type.h:8270
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isMemberPointerType() const
Definition: Type.h:8240
bool isFunctionType() const
Definition: Type.h:8182
bool isFloatingType() const
Definition: Type.cpp:2283
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2230
bool isNullPtrType() const
Definition: Type.h:8543
A safe wrapper around APSInt objects allocated and owned by BasicValueFactory.
Definition: APSIntPtr.h:19
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
AllocaRegion - A region that represents an untyped blob of bytes created by a call to 'alloca'.
Definition: MemRegion.h:478
AnalyzerOptions & getAnalyzerOptions() override
APSIntPtr getZeroWithTypeSize(QualType T)
APSIntType getAPSIntType(QualType T) const
Returns the type of the APSInt used to store values of the given QualType.
llvm::ImmutableList< SVal > getEmptySValList()
BlockCodeRegion - A region that represents code texts of blocks (closures).
Definition: MemRegion.h:631
BlockDataRegion - A region that represents a block instance.
Definition: MemRegion.h:678
AnalysisManager & getAnalysisManager()
Definition: ExprEngine.h:198
FunctionCodeRegion - A region that represents code texts of function.
Definition: MemRegion.h:584
static bool isLocType(QualType T)
Definition: SVals.h:262
const BlockCodeRegion * getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy, AnalysisDeclContext *AC)
Definition: MemRegion.cpp:1220
const AllocaRegion * getAllocaRegion(const Expr *Ex, unsigned Cnt, const LocationContext *LC)
getAllocaRegion - Retrieve a region associated with a call to alloca().
Definition: MemRegion.cpp:1344
const SymbolicRegion * getSymbolicHeapRegion(SymbolRef sym)
Return a unique symbolic region belonging to heap memory space.
Definition: MemRegion.cpp:1233
const SymbolicRegion * getSymbolicRegion(SymbolRef Sym, const MemSpaceRegion *MemSpace=nullptr)
Retrieve or create a "symbolic" memory region.
Definition: MemRegion.cpp:1226
const FunctionCodeRegion * getFunctionCodeRegion(const NamedDecl *FD)
Definition: MemRegion.cpp:1214
const BlockDataRegion * getBlockDataRegion(const BlockCodeRegion *bc, const LocationContext *lc, unsigned blockCount)
getBlockDataRegion - Get the memory region associated with an instance of a block.
Definition: MemRegion.cpp:1145
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
Definition: MemRegion.cpp:1412
const SymbolicRegion * getSymbolicBase() const
If this is a symbolic region, returns the region.
Definition: MemRegion.cpp:1435
SVal ArrayToPointer(Loc Array, QualType ElementTy)
Definition: ProgramState.h:584
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
Definition: SValBuilder.cpp:62
DefinedSVal getMemberPointer(const NamedDecl *ND)
SVal evalMinus(NonLoc val)
SVal evalComplement(NonLoc val)
BasicValueFactory & getBasicValueFactory()
Definition: SValBuilder.h:161
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
Definition: SValBuilder.h:260
SymbolManager SymMgr
Manages the creation of symbols.
Definition: SValBuilder.h:63
virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with a memory location and non-location opera...
DefinedSVal getMetadataSymbolVal(const void *symbolTag, const MemRegion *region, const Expr *expr, QualType type, const LocationContext *LCtx, unsigned count)
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:167
ProgramStateManager & getStateManager()
Definition: SValBuilder.h:151
SVal makeSymExprValNN(BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)
Constructs a symbolic expression for two non-location values.
virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, Loc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two memory location operands.
const unsigned ArrayIndexWidth
The width of the scalar type used for array indices.
Definition: SValBuilder.h:76
DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy, const LocationContext *locContext, unsigned blockCount)
DefinedSVal getFunctionPointer(const FunctionDecl *func)
const QualType ArrayIndexTy
The scalar type to use for array indices.
Definition: SValBuilder.h:73
ASTContext & getContext()
Definition: SValBuilder.h:148
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:288
SVal convertToArrayIndex(SVal val)
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:374
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.
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique 'name'.
BasicValueFactory BasicVals
Manager of APSInt values.
Definition: SValBuilder.h:60
ConditionTruthVal areEqual(ProgramStateRef state, SVal lhs, SVal rhs)
QualType getConditionType() const
Definition: SValBuilder.h:153
MemRegionManager MemMgr
Manages the creation of memory regions.
Definition: SValBuilder.h:66
SVal evalEQ(ProgramStateRef state, SVal lhs, SVal rhs)
SVal evalUnaryOp(ProgramStateRef state, UnaryOperator::Opcode opc, SVal operand, QualType type)
DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, const TypedValueRegion *region)
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the 'this' object reference.
nonloc::ConcreteInt makeTruthVal(bool b, QualType type)
Definition: SValBuilder.h:347
loc::ConcreteInt makeNullWithType(QualType type)
Create NULL pointer, with proper pointer bit-width for given address space.
Definition: SValBuilder.h:358
ProgramStateManager & StateMgr
Definition: SValBuilder.h:68
std::optional< SVal > getConstantVal(const Expr *E)
Returns the value of E, if it can be determined in a non-path-sensitive manner.
NonLoc makeLocAsInteger(Loc loc, unsigned bits)
Definition: SValBuilder.h:327
SVal evalIntegralCast(ProgramStateRef state, SVal val, QualType castTy, QualType originalType)
SymbolManager & getSymbolManager()
Definition: SValBuilder.h:164
DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region)
Make a unique symbol for value of region.
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer)
Definition: SValBuilder.h:304
nonloc::SymbolVal makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, APSIntPtr rhs, QualType type)
Definition: SValBuilder.cpp:77
const AnalyzerOptions & AnOpts
Definition: SValBuilder.h:70
DefinedSVal getConjuredHeapSymbolVal(const Expr *E, const LocationContext *LCtx, unsigned Count)
Conjure a symbol representing heap allocated memory region.
std::optional< loc::MemRegionVal > getCastedMemRegionVal(const MemRegion *region, QualType type)
Return MemRegionVal on success cast, otherwise return std::nullopt.
loc::MemRegionVal getAllocaRegionVal(const Expr *E, const LocationContext *LCtx, unsigned Count)
Create an SVal representing the result of an alloca()-like call, that is, an AllocaRegion on the stac...
nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean)
Definition: SValBuilder.h:294
SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, ProgramStateManager &stateMgr)
Definition: SValBuilder.cpp:52
SValVisitor - this class implements a simple visitor for SVal subclasses.
Definition: SValVisitor.h:27
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:56
bool isUndef() const
Definition: SVals.h:107
bool isUnknownOrUndef() const
Definition: SVals.h:109
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition: SVals.cpp:104
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:87
const MemRegion * getAsRegion() const
Definition: SVals.cpp:120
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:83
bool isUnknown() const
Definition: SVals.h:105
std::optional< const MemRegion * > castRegion(const MemRegion *region, QualType CastToTy)
castRegion - Used by ExprEngine::VisitCast to handle casts from a MemRegion* to a specific location t...
Definition: Store.cpp:74
Symbolic value.
Definition: SymExpr.h:30
virtual QualType getType() const =0
virtual unsigned computeComplexity() const =0
const SymbolExtent * getExtentSymbol(const SubRegion *R)
const SymbolDerived * getDerivedSymbol(SymbolRef parentSymbol, const TypedValueRegion *R)
const SymbolMetadata * getMetadataSymbol(const MemRegion *R, const Stmt *S, QualType T, const LocationContext *LCtx, unsigned VisitCount, const void *SymbolTag=nullptr)
Creates a metadata symbol associated with a specific region.
const SymbolRegionValue * getRegionValueSymbol(const TypedValueRegion *R)
Make a unique symbol for MemRegion R according to its kind.
const SymIntExpr * getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op, APSIntPtr rhs, QualType t)
const SymbolConjured * conjureSymbol(const Stmt *E, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag=nullptr)
const IntSymExpr * getIntSymExpr(APSIntPtr lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t)
const SymbolCast * getCastSymbol(const SymExpr *Operand, QualType From, QualType To)
const UnarySymExpr * getUnarySymExpr(const SymExpr *operand, UnaryOperator::Opcode op, QualType t)
static bool canSymbolicate(QualType T)
const SymSymExpr * getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t)
SymbolicRegion - A special, "non-concrete" region.
Definition: MemRegion.h:780
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:535
virtual QualType getValueType() const =0
The simplest example of a concrete compound value is nonloc::CompoundVal, which represents a concrete...
Definition: SVals.h:339
Value representing integer constant.
Definition: SVals.h:300
APSIntPtr getValue() const
Definition: SVals.h:304
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition: SVals.h:389
Value representing pointer-to-member.
Definition: SVals.h:434
Represents symbolic expression that isn't a location.
Definition: SVals.h:279
LLVM_ATTRIBUTE_RETURNS_NONNULL SymbolRef getSymbol() const
Definition: SVals.h:288
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
BinaryOperatorKind
@ Result
The result type of a method or function.
UnaryOperatorKind
const FunctionProtoType * T
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642