Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
Line
Count
Source (jump to first uncovered line)
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
13
#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
14
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
15
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
19
20
using namespace clang;
21
using namespace ento;
22
23
namespace {
24
class SimpleSValBuilder : public SValBuilder {
25
protected:
26
  SVal dispatchCast(SVal val, QualType castTy) override;
27
  SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
28
  SVal evalCastFromLoc(Loc val, QualType castTy) override;
29
30
public:
31
  SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
32
                    ProgramStateManager &stateMgr)
33
13.6k
                    : SValBuilder(alloc, context, stateMgr) {}
34
13.6k
  ~SimpleSValBuilder() override {}
35
36
  SVal evalMinus(NonLoc val) override;
37
  SVal evalComplement(NonLoc val) override;
38
  SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
39
                   NonLoc lhs, NonLoc rhs, QualType resultTy) override;
40
  SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
41
                   Loc lhs, Loc rhs, QualType resultTy) override;
42
  SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
43
                   Loc lhs, NonLoc rhs, QualType resultTy) override;
44
45
  /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
46
  ///  (integer) value, that value is returned. Otherwise, returns NULL.
47
  const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
48
49
  /// Recursively descends into symbolic expressions and replaces symbols
50
  /// with their known values (in the sense of the getKnownValue() method).
51
  SVal simplifySVal(ProgramStateRef State, SVal V) override;
52
53
  SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
54
                     const llvm::APSInt &RHS, QualType resultTy);
55
};
56
} // end anonymous namespace
57
58
SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
59
                                           ASTContext &context,
60
13.6k
                                           ProgramStateManager &stateMgr) {
61
13.6k
  return new SimpleSValBuilder(alloc, context, stateMgr);
62
13.6k
}
63
64
//===----------------------------------------------------------------------===//
65
// Transfer function for Casts.
66
//===----------------------------------------------------------------------===//
67
68
340k
SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
69
340k
  assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
70
196k
  return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
71
144k
                           : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
72
340k
}
73
74
166k
SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
75
166k
  bool isLocType = Loc::isLocType(castTy);
76
166k
  if (val.getAs<nonloc::PointerToMember>())
77
78
    return val;
78
79
166k
  if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
80
211
    if (isLocType)
81
16
      return LI->getLoc();
82
    // FIXME: Correctly support promotions/truncations.
83
195
    unsigned castSize = Context.getIntWidth(castTy);
84
195
    if (castSize == LI->getNumBits())
85
194
      return val;
86
1
    return makeLocAsInteger(LI->getLoc(), castSize);
87
1
  }
88
89
166k
  if (SymbolRef se = val.getAsSymbol()) {
90
113k
    QualType T = Context.getCanonicalType(se->getType());
91
    // If types are the same or both are integers, ignore the cast.
92
    // FIXME: Remove this hack when we support symbolic truncation/extension.
93
    // HACK: If both castTy and T are integers, ignore the cast.  This is
94
    // not a permanent solution.  Eventually we want to precisely handle
95
    // extension/truncation of symbolic integers.  This prevents us from losing
96
    // precision when we assign 'x = y' and 'y' is symbolic and x and y are
97
    // different integer types.
98
113k
   if (haveSameType(T, castTy))
99
113k
      return val;
100
101
169
    if (!isLocType)
102
23
      return makeNonLoc(se, T, castTy);
103
146
    return UnknownVal();
104
146
  }
105
106
  // If value is a non-integer constant, produce unknown.
107
52.6k
  if (!val.getAs<nonloc::ConcreteInt>())
108
19
    return UnknownVal();
109
110
  // Handle casts to a boolean type.
111
52.6k
  if (castTy->isBooleanType()) {
112
520
    bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
113
520
    return makeTruthVal(b, castTy);
114
520
  }
115
116
  // Only handle casts from integers to integers - if val is an integer constant
117
  // being cast to a non-integer type, produce unknown.
118
52.1k
  if (!isLocType && 
!castTy->isIntegralOrEnumerationType()51.7k
)
119
221
    return UnknownVal();
120
121
51.8k
  llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
122
51.8k
  BasicVals.getAPSIntType(castTy).apply(i);
123
124
51.8k
  if (isLocType)
125
360
    return makeIntLocVal(i);
126
51.5k
  else
127
51.5k
    return makeIntVal(i);
128
51.8k
}
129
130
695k
SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
131
132
  // Casts from pointers -> pointers, just return the lval.
133
  //
134
  // Casts from pointers -> references, just return the lval.  These
135
  //   can be introduced by the frontend for corner cases, e.g
136
  //   casting from va_list* to __builtin_va_list&.
137
  //
138
695k
  if (Loc::isLocType(castTy) || 
castTy->isReferenceType()499k
)
139
196k
    return val;
140
141
  // FIXME: Handle transparent unions where a value can be "transparently"
142
  //  lifted into a union type.
143
499k
  if (castTy->isUnionType())
144
0
    return UnknownVal();
145
146
  // Casting a Loc to a bool will almost always be true,
147
  // unless this is a weak function or a symbolic region.
148
499k
  if (castTy->isBooleanType()) {
149
499k
    switch (val.getSubKind()) {
150
499k
      case loc::MemRegionValKind: {
151
499k
        const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
152
499k
        if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
153
131k
          if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
154
131k
            if (FD->isWeak())
155
              // FIXME: Currently we are using an extent symbol here,
156
              // because there are no generic region address metadata
157
              // symbols to use, only content metadata.
158
27
              return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
159
160
499k
        if (const SymbolicRegion *SymR = R->getSymbolicBase())
161
40
          return makeNonLoc(SymR->getSymbol(), BO_NE,
162
40
                            BasicVals.getZeroWithPtrWidth(), castTy);
163
164
        // FALL-THROUGH
165
499k
        LLVM_FALLTHROUGH;
166
499k
      }
167
168
499k
      case loc::GotoLabelKind:
169
        // Labels and non-symbolic memory regions are always true.
170
499k
        return makeTruthVal(true, castTy);
171
169
    }
172
169
  }
173
174
169
  if (castTy->isIntegralOrEnumerationType()) {
175
161
    unsigned BitWidth = Context.getIntWidth(castTy);
176
177
161
    if (!val.getAs<loc::ConcreteInt>())
178
131
      return makeLocAsInteger(val, BitWidth);
179
180
30
    llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
181
30
    BasicVals.getAPSIntType(castTy).apply(i);
182
30
    return makeIntVal(i);
183
30
  }
184
185
  // All other cases: return 'UnknownVal'.  This includes casting pointers
186
  // to floats, which is probably badness it itself, but this is a good
187
  // intermediate solution until we do something better.
188
8
  return UnknownVal();
189
8
}
190
191
//===----------------------------------------------------------------------===//
192
// Transfer function for unary operators.
193
//===----------------------------------------------------------------------===//
194
195
1.54k
SVal SimpleSValBuilder::evalMinus(NonLoc val) {
196
1.54k
  switch (val.getSubKind()) {
197
1.52k
  case nonloc::ConcreteIntKind:
198
1.52k
    return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
199
20
  default:
200
20
    return UnknownVal();
201
1.54k
  }
202
1.54k
}
203
204
1.00k
SVal SimpleSValBuilder::evalComplement(NonLoc X) {
205
1.00k
  switch (X.getSubKind()) {
206
992
  case nonloc::ConcreteIntKind:
207
992
    return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
208
8
  default:
209
8
    return UnknownVal();
210
1.00k
  }
211
1.00k
}
212
213
//===----------------------------------------------------------------------===//
214
// Transfer function for binary operators.
215
//===----------------------------------------------------------------------===//
216
217
SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
218
                                    BinaryOperator::Opcode op,
219
                                    const llvm::APSInt &RHS,
220
54.5k
                                    QualType resultTy) {
221
54.5k
  bool isIdempotent = false;
222
223
  // Check for a few special cases with known reductions first.
224
54.5k
  switch (op) {
225
27.2k
  default:
226
    // We can't reduce this case; just treat it normally.
227
27.2k
    break;
228
418
  case BO_Mul:
229
    // a*0 and a*1
230
418
    if (RHS == 0)
231
260
      return makeIntVal(0, resultTy);
232
158
    else if (RHS == 1)
233
12
      isIdempotent = true;
234
158
    break;
235
90
  case BO_Div:
236
    // a/0 and a/1
237
90
    if (RHS == 0)
238
      // This is also handled elsewhere.
239
0
      return UndefinedVal();
240
90
    else if (RHS == 1)
241
27
      isIdempotent = true;
242
90
    break;
243
57
  case BO_Rem:
244
    // a%0 and a%1
245
57
    if (RHS == 0)
246
      // This is also handled elsewhere.
247
0
      return UndefinedVal();
248
57
    else if (RHS == 1)
249
0
      return makeIntVal(0, resultTy);
250
57
    break;
251
8.71k
  case BO_Add:
252
8.71k
  case BO_Sub:
253
8.71k
  case BO_Shl:
254
8.71k
  case BO_Shr:
255
8.71k
  case BO_Xor:
256
    // a+0, a-0, a<<0, a>>0, a^0
257
8.71k
    if (RHS == 0)
258
2.60k
      isIdempotent = true;
259
8.71k
    break;
260
18.0k
  case BO_And:
261
    // a&0 and a&(~0)
262
18.0k
    if (RHS == 0)
263
4
      return makeIntVal(0, resultTy);
264
18.0k
    else if (RHS.isAllOnesValue())
265
1
      isIdempotent = true;
266
18.0k
    break;
267
38
  case BO_Or:
268
    // a|0 and a|(~0)
269
38
    if (RHS == 0)
270
6
      isIdempotent = true;
271
32
    else if (RHS.isAllOnesValue()) {
272
3
      const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
273
3
      return nonloc::ConcreteInt(Result);
274
3
    }
275
35
    break;
276
54.3k
  }
277
278
  // Idempotent ops (like a*1) can still change the type of an expression.
279
  // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
280
  // dirty work.
281
54.3k
  if (isIdempotent)
282
2.64k
      return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
283
284
  // If we reach this point, the expression cannot be simplified.
285
  // Make a SymbolVal for the entire expression, after converting the RHS.
286
51.6k
  const llvm::APSInt *ConvertedRHS = &RHS;
287
51.6k
  if (BinaryOperator::isComparisonOp(op)) {
288
    // We're looking for a type big enough to compare the symbolic value
289
    // with the given constant.
290
    // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
291
27.2k
    ASTContext &Ctx = getContext();
292
27.2k
    QualType SymbolType = LHS->getType();
293
27.2k
    uint64_t ValWidth = RHS.getBitWidth();
294
27.2k
    uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
295
296
27.2k
    if (ValWidth < TypeWidth) {
297
      // If the value is too small, extend it.
298
1.79k
      ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
299
25.4k
    } else if (ValWidth == TypeWidth) {
300
      // If the value is signed but the symbol is unsigned, do the comparison
301
      // in unsigned space. [C99 6.3.1.8]
302
      // (For the opposite case, the value is already unsigned.)
303
24.6k
      if (RHS.isSigned() && 
!SymbolType->isSignedIntegerOrEnumerationType()19.8k
)
304
500
        ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
305
24.6k
    }
306
27.2k
  } else
307
24.4k
    ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
308
309
51.6k
  return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
310
51.6k
}
311
312
// See if Sym is known to be a relation Rel with Bound.
313
static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
314
9.26k
                         llvm::APSInt Bound, ProgramStateRef State) {
315
9.26k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
316
9.26k
  SVal Result =
317
9.26k
      SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
318
9.26k
                      nonloc::ConcreteInt(Bound), SVB.getConditionType());
319
9.26k
  if (auto DV = Result.getAs<DefinedSVal>()) {
320
9.26k
    return !State->assume(*DV, false);
321
9.26k
  }
322
0
  return false;
323
0
}
324
325
// See if Sym is known to be within [min/4, max/4], where min and max
326
// are the bounds of the symbol's integral type. With such symbols,
327
// some manipulations can be performed without the risk of overflow.
328
// assume() doesn't cause infinite recursion because we should be dealing
329
// with simpler symbols on every recursive call.
330
static bool isWithinConstantOverflowBounds(SymbolRef Sym,
331
4.66k
                                           ProgramStateRef State) {
332
4.66k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
333
4.66k
  BasicValueFactory &BV = SVB.getBasicValueFactory();
334
335
4.66k
  QualType T = Sym->getType();
336
4.66k
  assert(T->isSignedIntegerOrEnumerationType() &&
337
4.66k
         "This only works with signed integers!");
338
4.66k
  APSIntType AT = BV.getAPSIntType(T);
339
340
4.66k
  llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
341
4.66k
  return isInRelation(BO_LE, Sym, Max, State) &&
342
4.60k
         isInRelation(BO_GE, Sym, Min, State);
343
4.66k
}
344
345
// Same for the concrete integers: see if I is within [min/4, max/4].
346
4.60k
static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
347
4.60k
  APSIntType AT(I);
348
4.60k
  assert(!AT.isUnsigned() &&
349
4.60k
         "This only works with signed integers!");
350
351
4.60k
  llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
352
4.60k
  return (I <= Max) && (I >= -Max);
353
4.60k
}
354
355
static std::pair<SymbolRef, llvm::APSInt>
356
4.81k
decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
357
4.81k
  if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
358
1.15k
    if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
359
1.15k
      return std::make_pair(SymInt->getLHS(),
360
1.15k
                            (SymInt->getOpcode() == BO_Add) ?
361
621
                            (SymInt->getRHS()) :
362
537
                            (-SymInt->getRHS()));
363
364
  // Fail to decompose: "reduce" the problem to the "$x + 0" case.
365
3.65k
  return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
366
3.65k
}
367
368
// Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
369
// same signed integral type and no overflows occur (which should be checked
370
// by the caller).
371
static NonLoc doRearrangeUnchecked(ProgramStateRef State,
372
                                   BinaryOperator::Opcode Op,
373
                                   SymbolRef LSym, llvm::APSInt LInt,
374
2.34k
                                   SymbolRef RSym, llvm::APSInt RInt) {
375
2.34k
  SValBuilder &SVB = State->getStateManager().getSValBuilder();
376
2.34k
  BasicValueFactory &BV = SVB.getBasicValueFactory();
377
2.34k
  SymbolManager &SymMgr = SVB.getSymbolManager();
378
379
2.34k
  QualType SymTy = LSym->getType();
380
2.34k
  assert(SymTy == RSym->getType() &&
381
2.34k
         "Symbols are not of the same type!");
382
2.34k
  assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
383
2.34k
         "Integers are not of the same type as symbols!");
384
2.34k
  assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
385
2.34k
         "Integers are not of the same type as symbols!");
386
387
2.34k
  QualType ResultTy;
388
2.34k
  if (BinaryOperator::isComparisonOp(Op))
389
2.30k
    ResultTy = SVB.getConditionType();
390
42
  else if (BinaryOperator::isAdditiveOp(Op))
391
42
    ResultTy = SymTy;
392
42
  else
393
0
    llvm_unreachable("Operation not suitable for unchecked rearrangement!");
394
395
  // FIXME: Can we use assume() without getting into an infinite recursion?
396
2.34k
  if (LSym == RSym)
397
698
    return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
398
698
                           nonloc::ConcreteInt(RInt), ResultTy)
399
698
        .castAs<NonLoc>();
400
401
1.64k
  SymbolRef ResultSym = nullptr;
402
1.64k
  BinaryOperator::Opcode ResultOp;
403
1.64k
  llvm::APSInt ResultInt;
404
1.64k
  if (BinaryOperator::isComparisonOp(Op)) {
405
    // Prefer comparing to a non-negative number.
406
    // FIXME: Maybe it'd be better to have consistency in
407
    // "$x - $y" vs. "$y - $x" because those are solver's keys.
408
1.62k
    if (LInt > RInt) {
409
238
      ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
410
238
      ResultOp = BinaryOperator::reverseComparisonOp(Op);
411
238
      ResultInt = LInt - RInt; // Opposite order!
412
1.38k
    } else {
413
1.38k
      ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
414
1.38k
      ResultOp = Op;
415
1.38k
      ResultInt = RInt - LInt; // Opposite order!
416
1.38k
    }
417
24
  } else {
418
24
    ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
419
24
    ResultInt = (Op == BO_Add) ? 
(LInt + RInt)0
: (LInt - RInt);
420
24
    ResultOp = BO_Add;
421
    // Bring back the cosmetic difference.
422
24
    if (ResultInt < 0) {
423
0
      ResultInt = -ResultInt;
424
0
      ResultOp = BO_Sub;
425
24
    } else if (ResultInt == 0) {
426
      // Shortcut: Simplify "$x + 0" to "$x".
427
24
      return nonloc::SymbolVal(ResultSym);
428
24
    }
429
1.62k
  }
430
1.62k
  const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
431
1.62k
  return nonloc::SymbolVal(
432
1.62k
      SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
433
1.62k
}
434
435
// Rearrange if symbol type matches the result type and if the operator is a
436
// comparison operator, both symbol and constant must be within constant
437
// overflow bounds.
438
static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
439
4.75k
                            SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
440
4.75k
  return Sym->getType() == Ty &&
441
4.74k
    (!BinaryOperator::isComparisonOp(Op) ||
442
4.66k
     (isWithinConstantOverflowBounds(Sym, State) &&
443
4.60k
      isWithinConstantOverflowBounds(Int)));
444
4.75k
}
445
446
static Optional<NonLoc> tryRearrange(ProgramStateRef State,
447
                                     BinaryOperator::Opcode Op, NonLoc Lhs,
448
11.8k
                                     NonLoc Rhs, QualType ResultTy) {
449
11.8k
  ProgramStateManager &StateMgr = State->getStateManager();
450
11.8k
  SValBuilder &SVB = StateMgr.getSValBuilder();
451
452
  // We expect everything to be of the same type - this type.
453
11.8k
  QualType SingleTy;
454
455
11.8k
  auto &Opts =
456
11.8k
    StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
457
458
  // FIXME: After putting complexity threshold to the symbols we can always
459
  //        rearrange additive operations but rearrange comparisons only if
460
  //        option is set.
461
11.8k
  if(!Opts.ShouldAggressivelySimplifyBinaryOperation)
462
9.35k
    return None;
463
464
2.45k
  SymbolRef LSym = Lhs.getAsSymbol();
465
2.45k
  if (!LSym)
466
0
    return None;
467
468
2.45k
  if (BinaryOperator::isComparisonOp(Op)) {
469
2.38k
    SingleTy = LSym->getType();
470
2.38k
    if (ResultTy != SVB.getConditionType())
471
0
      return None;
472
    // Initialize SingleTy later with a symbol's type.
473
66
  } else if (BinaryOperator::isAdditiveOp(Op)) {
474
66
    SingleTy = ResultTy;
475
66
    if (LSym->getType() != SingleTy)
476
1
      return None;
477
0
  } else {
478
    // Don't rearrange other operations.
479
0
    return None;
480
0
  }
481
482
2.44k
  assert(!SingleTy.isNull() && "We should have figured out the type by now!");
483
484
  // Rearrange signed symbolic expressions only
485
2.44k
  if (!SingleTy->isSignedIntegerOrEnumerationType())
486
36
    return None;
487
488
2.41k
  SymbolRef RSym = Rhs.getAsSymbol();
489
2.41k
  if (!RSym || RSym->getType() != SingleTy)
490
6
    return None;
491
492
2.40k
  BasicValueFactory &BV = State->getBasicVals();
493
2.40k
  llvm::APSInt LInt, RInt;
494
2.40k
  std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
495
2.40k
  std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
496
2.40k
  if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
497
2.34k
      !shouldRearrange(State, Op, RSym, RInt, SingleTy))
498
64
    return None;
499
500
  // We know that no overflows can occur anymore.
501
2.34k
  return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
502
2.34k
}
503
504
SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
505
                                  BinaryOperator::Opcode op,
506
                                  NonLoc lhs, NonLoc rhs,
507
102k
                                  QualType resultTy)  {
508
102k
  NonLoc InputLHS = lhs;
509
102k
  NonLoc InputRHS = rhs;
510
511
  // Handle trivial case where left-side and right-side are the same.
512
102k
  if (lhs == rhs)
513
10.2k
    switch (op) {
514
1.09k
      default:
515
1.09k
        break;
516
7.09k
      case BO_EQ:
517
7.09k
      case BO_LE:
518
7.09k
      case BO_GE:
519
7.09k
        return makeTruthVal(true, resultTy);
520
1.62k
      case BO_LT:
521
1.62k
      case BO_GT:
522
1.62k
      case BO_NE:
523
1.62k
        return makeTruthVal(false, resultTy);
524
126
      case BO_Xor:
525
126
      case BO_Sub:
526
126
        if (resultTy->isIntegralOrEnumerationType())
527
126
          return makeIntVal(0, resultTy);
528
0
        return evalCastFromNonLoc(makeIntVal(0, /*isUnsigned=*/false), resultTy);
529
292
      case BO_Or:
530
292
      case BO_And:
531
292
        return evalCastFromNonLoc(lhs, resultTy);
532
93.4k
    }
533
534
101k
  
while (93.4k
1) {
535
101k
    switch (lhs.getSubKind()) {
536
0
    default:
537
0
      return makeSymExprValNN(op, lhs, rhs, resultTy);
538
2
    case nonloc::PointerToMemberKind: {
539
2
      assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
540
2
             "Both SVals should have pointer-to-member-type");
541
2
      auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
542
2
           RPTM = rhs.castAs<nonloc::PointerToMember>();
543
2
      auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
544
2
      switch (op) {
545
2
        case BO_EQ:
546
2
          return makeTruthVal(LPTMD == RPTMD, resultTy);
547
0
        case BO_NE:
548
0
          return makeTruthVal(LPTMD != RPTMD, resultTy);
549
0
        default:
550
0
          return UnknownVal();
551
0
      }
552
0
    }
553
45
    case nonloc::LocAsIntegerKind: {
554
45
      Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
555
45
      switch (rhs.getSubKind()) {
556
0
        case nonloc::LocAsIntegerKind:
557
          // FIXME: at the moment the implementation
558
          // of modeling "pointers as integers" is not complete.
559
0
          if (!BinaryOperator::isComparisonOp(op))
560
0
            return UnknownVal();
561
0
          return evalBinOpLL(state, op, lhsL,
562
0
                             rhs.castAs<nonloc::LocAsInteger>().getLoc(),
563
0
                             resultTy);
564
41
        case nonloc::ConcreteIntKind: {
565
          // FIXME: at the moment the implementation
566
          // of modeling "pointers as integers" is not complete.
567
41
          if (!BinaryOperator::isComparisonOp(op))
568
23
            return UnknownVal();
569
          // Transform the integer into a location and compare.
570
          // FIXME: This only makes sense for comparisons. If we want to, say,
571
          // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
572
          // then pack it back into a LocAsInteger.
573
18
          llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
574
          // If the region has a symbolic base, pay attention to the type; it
575
          // might be coming from a non-default address space. For non-symbolic
576
          // regions it doesn't matter that much because such comparisons would
577
          // most likely evaluate to concrete false anyway. FIXME: We might
578
          // still need to handle the non-comparison case.
579
18
          if (SymbolRef lSym = lhs.getAsLocSymbol(true))
580
14
            BasicVals.getAPSIntType(lSym->getType()).apply(i);
581
4
          else
582
4
            BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
583
18
          return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
584
18
        }
585
4
        default:
586
4
          switch (op) {
587
0
            case BO_EQ:
588
0
              return makeTruthVal(false, resultTy);
589
0
            case BO_NE:
590
0
              return makeTruthVal(true, resultTy);
591
4
            default:
592
              // This case also handles pointer arithmetic.
593
4
              return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
594
0
          }
595
0
      }
596
0
    }
597
32.5k
    case nonloc::ConcreteIntKind: {
598
32.5k
      llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
599
600
      // If we're dealing with two known constants, just perform the operation.
601
32.5k
      if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
602
28.6k
        llvm::APSInt RHSValue = *KnownRHSValue;
603
28.6k
        if (BinaryOperator::isComparisonOp(op)) {
604
          // We're looking for a type big enough to compare the two values.
605
          // FIXME: This is not correct. char + short will result in a promotion
606
          // to int. Unfortunately we have lost types by this point.
607
13.0k
          APSIntType CompareType = std::max(APSIntType(LHSValue),
608
13.0k
                                            APSIntType(RHSValue));
609
13.0k
          CompareType.apply(LHSValue);
610
13.0k
          CompareType.apply(RHSValue);
611
15.5k
        } else if (!BinaryOperator::isShiftOp(op)) {
612
14.8k
          APSIntType IntType = BasicVals.getAPSIntType(resultTy);
613
14.8k
          IntType.apply(LHSValue);
614
14.8k
          IntType.apply(RHSValue);
615
14.8k
        }
616
617
28.6k
        const llvm::APSInt *Result =
618
28.6k
          BasicVals.evalAPSInt(op, LHSValue, RHSValue);
619
28.6k
        if (!Result)
620
14
          return UndefinedVal();
621
622
28.6k
        return nonloc::ConcreteInt(*Result);
623
28.6k
      }
624
625
      // Swap the left and right sides and flip the operator if doing so
626
      // allows us to better reason about the expression (this is a form
627
      // of expression canonicalization).
628
      // While we're at it, catch some special cases for non-commutative ops.
629
3.92k
      switch (op) {
630
891
      case BO_LT:
631
891
      case BO_GT:
632
891
      case BO_LE:
633
891
      case BO_GE:
634
891
        op = BinaryOperator::reverseComparisonOp(op);
635
891
        LLVM_FALLTHROUGH;
636
3.72k
      case BO_EQ:
637
3.72k
      case BO_NE:
638
3.72k
      case BO_Add:
639
3.72k
      case BO_Mul:
640
3.72k
      case BO_And:
641
3.72k
      case BO_Xor:
642
3.72k
      case BO_Or:
643
3.72k
        std::swap(lhs, rhs);
644
3.72k
        continue;
645
3
      case BO_Shr:
646
        // (~0)>>a
647
3
        if (LHSValue.isAllOnesValue() && 
LHSValue.isSigned()2
)
648
1
          return evalCastFromNonLoc(lhs, resultTy);
649
2
        LLVM_FALLTHROUGH;
650
3
      case BO_Shl:
651
        // 0<<a and 0>>a
652
3
        if (LHSValue == 0)
653
2
          return evalCastFromNonLoc(lhs, resultTy);
654
1
        return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
655
45
      case BO_Rem:
656
        // 0 % x == 0
657
45
        if (LHSValue == 0)
658
3
          return makeZeroVal(resultTy);
659
42
        LLVM_FALLTHROUGH;
660
188
      default:
661
188
        return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
662
0
      }
663
0
    }
664
68.6k
    case nonloc::SymbolValKind: {
665
      // We only handle LHS as simple symbols or SymIntExprs.
666
68.6k
      SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
667
668
      // LHS is a symbolic expression.
669
68.6k
      if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
670
671
        // Is this a logical not? (!x is represented as x == 0.)
672
7.39k
        if (op == BO_EQ && 
rhs.isZeroConstant()520
) {
673
          // We know how to negate certain expressions. Simplify them here.
674
675
338
          BinaryOperator::Opcode opc = symIntExpr->getOpcode();
676
338
          switch (opc) {
677
131
          default:
678
            // We don't know how to negate this operation.
679
            // Just handle it as if it were a normal comparison to 0.
680
131
            break;
681
0
          case BO_LAnd:
682
0
          case BO_LOr:
683
0
            llvm_unreachable("Logical operators handled by branching logic.");
684
0
          case BO_Assign:
685
0
          case BO_MulAssign:
686
0
          case BO_DivAssign:
687
0
          case BO_RemAssign:
688
0
          case BO_AddAssign:
689
0
          case BO_SubAssign:
690
0
          case BO_ShlAssign:
691
0
          case BO_ShrAssign:
692
0
          case BO_AndAssign:
693
0
          case BO_XorAssign:
694
0
          case BO_OrAssign:
695
0
          case BO_Comma:
696
0
            llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
697
0
          case BO_PtrMemD:
698
0
          case BO_PtrMemI:
699
0
            llvm_unreachable("Pointer arithmetic not handled here.");
700
207
          case BO_LT:
701
207
          case BO_GT:
702
207
          case BO_LE:
703
207
          case BO_GE:
704
207
          case BO_EQ:
705
207
          case BO_NE:
706
207
            assert(resultTy->isBooleanType() ||
707
207
                   resultTy == getConditionType());
708
207
            assert(symIntExpr->getType()->isBooleanType() ||
709
207
                   getContext().hasSameUnqualifiedType(symIntExpr->getType(),
710
207
                                                       getConditionType()));
711
            // Negate the comparison and make a value.
712
207
            opc = BinaryOperator::negateComparisonOp(opc);
713
207
            return makeNonLoc(symIntExpr->getLHS(), opc,
714
207
                symIntExpr->getRHS(), resultTy);
715
7.19k
          }
716
7.19k
        }
717
718
        // For now, only handle expressions whose RHS is a constant.
719
7.19k
        if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
720
          // If both the LHS and the current expression are additive,
721
          // fold their constants and try again.
722
5.10k
          if (BinaryOperator::isAdditiveOp(op)) {
723
3.77k
            BinaryOperator::Opcode lop = symIntExpr->getOpcode();
724
3.77k
            if (BinaryOperator::isAdditiveOp(lop)) {
725
              // Convert the two constants to a common type, then combine them.
726
727
              // resultTy may not be the best type to convert to, but it's
728
              // probably the best choice in expressions with mixed type
729
              // (such as x+1U+2LL). The rules for implicit conversions should
730
              // choose a reasonable type to preserve the expression, and will
731
              // at least match how the value is going to be used.
732
3.64k
              APSIntType IntType = BasicVals.getAPSIntType(resultTy);
733
3.64k
              const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
734
3.64k
              const llvm::APSInt &second = IntType.convert(*RHSValue);
735
736
3.64k
              const llvm::APSInt *newRHS;
737
3.64k
              if (lop == op)
738
3.27k
                newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
739
371
              else
740
371
                newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
741
742
3.64k
              assert(newRHS && "Invalid operation despite common type!");
743
3.64k
              rhs = nonloc::ConcreteInt(*newRHS);
744
3.64k
              lhs = nonloc::SymbolVal(symIntExpr->getLHS());
745
3.64k
              op = lop;
746
3.64k
              continue;
747
3.64k
            }
748
1.45k
          }
749
750
          // Otherwise, make a SymIntExpr out of the expression.
751
1.45k
          return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
752
1.45k
        }
753
7.19k
      }
754
755
      // Does the symbolic expression simplify to a constant?
756
      // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
757
      // and try again.
758
63.3k
      SVal simplifiedLhs = simplifySVal(state, lhs);
759
63.3k
      if (simplifiedLhs != lhs)
760
463
        if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
761
462
          lhs = *simplifiedLhsAsNonLoc;
762
462
          continue;
763
462
        }
764
765
      // Is the RHS a constant?
766
62.9k
      if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
767
51.0k
        return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
768
769
11.8k
      if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
770
2.34k
        return *V;
771
772
      // Give up -- this is not a symbolic expression we can handle.
773
9.46k
      return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
774
9.46k
    }
775
101k
    }
776
101k
  }
777
93.4k
}
778
779
static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
780
                                            const FieldRegion *RightFR,
781
                                            BinaryOperator::Opcode op,
782
                                            QualType resultTy,
783
12
                                            SimpleSValBuilder &SVB) {
784
  // Only comparisons are meaningful here!
785
12
  if (!BinaryOperator::isComparisonOp(op))
786
0
    return UnknownVal();
787
788
  // Next, see if the two FRs have the same super-region.
789
  // FIXME: This doesn't handle casts yet, and simply stripping the casts
790
  // doesn't help.
791
12
  if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
792
2
    return UnknownVal();
793
794
10
  const FieldDecl *LeftFD = LeftFR->getDecl();
795
10
  const FieldDecl *RightFD = RightFR->getDecl();
796
10
  const RecordDecl *RD = LeftFD->getParent();
797
798
  // Make sure the two FRs are from the same kind of record. Just in case!
799
  // FIXME: This is probably where inheritance would be a problem.
800
10
  if (RD != RightFD->getParent())
801
0
    return UnknownVal();
802
803
  // We know for sure that the two fields are not the same, since that
804
  // would have given us the same SVal.
805
10
  if (op == BO_EQ)
806
2
    return SVB.makeTruthVal(false, resultTy);
807
8
  if (op == BO_NE)
808
2
    return SVB.makeTruthVal(true, resultTy);
809
810
  // Iterate through the fields and see which one comes first.
811
  // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
812
  // members and the units in which bit-fields reside have addresses that
813
  // increase in the order in which they are declared."
814
6
  bool leftFirst = (op == BO_LT || 
op == BO_LE2
);
815
6
  for (const auto *I : RD->fields()) {
816
6
    if (I == LeftFD)
817
6
      return SVB.makeTruthVal(leftFirst, resultTy);
818
0
    if (I == RightFD)
819
0
      return SVB.makeTruthVal(!leftFirst, resultTy);
820
0
  }
821
822
6
  
llvm_unreachable0
("Fields not found in parent record's definition");
823
6
}
824
825
// FIXME: all this logic will change if/when we have MemRegion::getLocation().
826
SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
827
                                  BinaryOperator::Opcode op,
828
                                  Loc lhs, Loc rhs,
829
19.9k
                                  QualType resultTy) {
830
  // Only comparisons and subtractions are valid operations on two pointers.
831
  // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
832
  // However, if a pointer is casted to an integer, evalBinOpNN may end up
833
  // calling this function with another operation (PR7527). We don't attempt to
834
  // model this for now, but it could be useful, particularly when the
835
  // "location" is actually an integer value that's been passed through a void*.
836
19.9k
  if (!(BinaryOperator::isComparisonOp(op) || 
op == BO_Sub85
))
837
0
    return UnknownVal();
838
839
  // Special cases for when both sides are identical.
840
19.9k
  if (lhs == rhs) {
841
12.9k
    switch (op) {
842
0
    default:
843
0
      llvm_unreachable("Unimplemented operation for two identical values");
844
1
    case BO_Sub:
845
1
      return makeZeroVal(resultTy);
846
12.8k
    case BO_EQ:
847
12.8k
    case BO_LE:
848
12.8k
    case BO_GE:
849
12.8k
      return makeTruthVal(true, resultTy);
850
132
    case BO_NE:
851
132
    case BO_LT:
852
132
    case BO_GT:
853
132
      return makeTruthVal(false, resultTy);
854
7.01k
    }
855
7.01k
  }
856
857
7.01k
  switch (lhs.getSubKind()) {
858
0
  default:
859
0
    llvm_unreachable("Ordering not implemented for this Loc.");
860
861
20
  case loc::GotoLabelKind:
862
    // The only thing we know about labels is that they're non-null.
863
20
    if (rhs.isZeroConstant()) {
864
18
      switch (op) {
865
0
      default:
866
0
        break;
867
0
      case BO_Sub:
868
0
        return evalCastFromLoc(lhs, resultTy);
869
10
      case BO_EQ:
870
10
      case BO_LE:
871
10
      case BO_LT:
872
10
        return makeTruthVal(false, resultTy);
873
8
      case BO_NE:
874
8
      case BO_GT:
875
8
      case BO_GE:
876
8
        return makeTruthVal(true, resultTy);
877
2
      }
878
2
    }
879
    // There may be two labels for the same location, and a function region may
880
    // have the same address as a label at the start of the function (depending
881
    // on the ABI).
882
    // FIXME: we can probably do a comparison against other MemRegions, though.
883
    // FIXME: is there a way to tell if two labels refer to the same location?
884
2
    return UnknownVal();
885
886
152
  case loc::ConcreteIntKind: {
887
    // If one of the operands is a symbol and the other is a constant,
888
    // build an expression for use by the constraint manager.
889
152
    if (SymbolRef rSym = rhs.getAsLocSymbol()) {
890
      // We can only build expressions with symbols on the left,
891
      // so we need a reversible operator.
892
123
      if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
893
0
        return UnknownVal();
894
895
123
      const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
896
123
      op = BinaryOperator::reverseComparisonOp(op);
897
123
      return makeNonLoc(rSym, op, lVal, resultTy);
898
123
    }
899
900
    // If both operands are constants, just perform the operation.
901
29
    if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
902
18
      SVal ResultVal =
903
18
          lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
904
18
      if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
905
18
        return evalCastFromNonLoc(*Result, resultTy);
906
907
0
      assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
908
0
      return UnknownVal();
909
0
    }
910
911
    // Special case comparisons against NULL.
912
    // This must come after the test if the RHS is a symbol, which is used to
913
    // build constraints. The address of any non-symbolic region is guaranteed
914
    // to be non-NULL, as is any label.
915
11
    assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
916
11
    if (lhs.isZeroConstant()) {
917
7
      switch (op) {
918
0
      default:
919
0
        break;
920
0
      case BO_EQ:
921
0
      case BO_GT:
922
0
      case BO_GE:
923
0
        return makeTruthVal(false, resultTy);
924
7
      case BO_NE:
925
7
      case BO_LT:
926
7
      case BO_LE:
927
7
        return makeTruthVal(true, resultTy);
928
4
      }
929
4
    }
930
931
    // Comparing an arbitrary integer to a region or label address is
932
    // completely unknowable.
933
4
    return UnknownVal();
934
4
  }
935
6.83k
  case loc::MemRegionValKind: {
936
6.83k
    if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
937
      // If one of the operands is a symbol and the other is a constant,
938
      // build an expression for use by the constraint manager.
939
4.69k
      if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
940
2.04k
        if (BinaryOperator::isComparisonOp(op))
941
2.03k
          return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
942
2
        return UnknownVal();
943
2
      }
944
      // Special case comparisons to NULL.
945
      // This must come after the test if the LHS is a symbol, which is used to
946
      // build constraints. The address of any non-symbolic region is guaranteed
947
      // to be non-NULL.
948
2.65k
      if (rInt->isZeroConstant()) {
949
2.65k
        if (op == BO_Sub)
950
0
          return evalCastFromLoc(lhs, resultTy);
951
952
2.65k
        if (BinaryOperator::isComparisonOp(op)) {
953
2.65k
          QualType boolType = getContext().BoolTy;
954
2.65k
          NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
955
2.65k
          NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
956
2.65k
          return evalBinOpNN(state, op, l, r, resultTy);
957
2.65k
        }
958
2
      }
959
960
      // Comparing a region to an arbitrary integer is completely unknowable.
961
2
      return UnknownVal();
962
2
    }
963
964
    // Get both values as regions, if possible.
965
2.14k
    const MemRegion *LeftMR = lhs.getAsRegion();
966
2.14k
    assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
967
968
2.14k
    const MemRegion *RightMR = rhs.getAsRegion();
969
2.14k
    if (!RightMR)
970
      // The RHS is probably a label, which in theory could address a region.
971
      // FIXME: we can probably make a more useful statement about non-code
972
      // regions, though.
973
0
      return UnknownVal();
974
975
2.14k
    const MemRegion *LeftBase = LeftMR->getBaseRegion();
976
2.14k
    const MemRegion *RightBase = RightMR->getBaseRegion();
977
2.14k
    const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
978
2.14k
    const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
979
2.14k
    const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
980
981
    // If the two regions are from different known memory spaces they cannot be
982
    // equal. Also, assume that no symbolic region (whose memory space is
983
    // unknown) is on the stack.
984
2.14k
    if (LeftMS != RightMS &&
985
559
        ((LeftMS != UnknownMS && 
RightMS != UnknownMS494
) ||
986
498
         (isa<StackSpaceRegion>(LeftMS) || 
isa<StackSpaceRegion>(RightMS)66
))) {
987
495
      switch (op) {
988
174
      default:
989
174
        return UnknownVal();
990
184
      case BO_EQ:
991
184
        return makeTruthVal(false, resultTy);
992
137
      case BO_NE:
993
137
        return makeTruthVal(true, resultTy);
994
1.64k
      }
995
1.64k
    }
996
997
    // If both values wrap regions, see if they're from different base regions.
998
    // Note, heap base symbolic regions are assumed to not alias with
999
    // each other; for example, we assume that malloc returns different address
1000
    // on each invocation.
1001
    // FIXME: ObjC object pointers always reside on the heap, but currently
1002
    // we treat their memory space as unknown, because symbolic pointers
1003
    // to ObjC objects may alias. There should be a way to construct
1004
    // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
1005
    // guesses memory space for ObjC object pointers manually instead of
1006
    // relying on us.
1007
1.64k
    if (LeftBase != RightBase &&
1008
1.21k
        ((!isa<SymbolicRegion>(LeftBase) && 
!isa<SymbolicRegion>(RightBase)537
) ||
1009
674
         (isa<HeapSpaceRegion>(LeftMS) || 
isa<HeapSpaceRegion>(RightMS)672
)) ){
1010
546
      switch (op) {
1011
72
      default:
1012
72
        return UnknownVal();
1013
463
      case BO_EQ:
1014
463
        return makeTruthVal(false, resultTy);
1015
11
      case BO_NE:
1016
11
        return makeTruthVal(true, resultTy);
1017
1.09k
      }
1018
1.09k
    }
1019
1020
    // Handle special cases for when both regions are element regions.
1021
1.09k
    const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1022
1.09k
    const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1023
1.09k
    if (RightER && 
LeftER464
) {
1024
      // Next, see if the two ERs have the same super-region and matching types.
1025
      // FIXME: This should do something useful even if the types don't match,
1026
      // though if both indexes are constant the RegionRawOffset path will
1027
      // give the correct answer.
1028
403
      if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1029
392
          LeftER->getElementType() == RightER->getElementType()) {
1030
        // Get the left index and cast it to the correct type.
1031
        // If the index is unknown or undefined, bail out here.
1032
360
        SVal LeftIndexVal = LeftER->getIndex();
1033
360
        Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1034
360
        if (!LeftIndex)
1035
0
          return UnknownVal();
1036
360
        LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
1037
360
        LeftIndex = LeftIndexVal.getAs<NonLoc>();
1038
360
        if (!LeftIndex)
1039
0
          return UnknownVal();
1040
1041
        // Do the same for the right index.
1042
360
        SVal RightIndexVal = RightER->getIndex();
1043
360
        Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1044
360
        if (!RightIndex)
1045
0
          return UnknownVal();
1046
360
        RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
1047
360
        RightIndex = RightIndexVal.getAs<NonLoc>();
1048
360
        if (!RightIndex)
1049
0
          return UnknownVal();
1050
1051
        // Actually perform the operation.
1052
        // evalBinOpNN expects the two indexes to already be the right type.
1053
360
        return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1054
360
      }
1055
403
    }
1056
1057
    // Special handling of the FieldRegions, even with symbolic offsets.
1058
739
    const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1059
739
    const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1060
739
    if (RightFR && 
LeftFR12
) {
1061
12
      SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1062
12
                                               *this);
1063
12
      if (!R.isUnknown())
1064
10
        return R;
1065
729
    }
1066
1067
    // Compare the regions using the raw offsets.
1068
729
    RegionOffset LeftOffset = LeftMR->getAsOffset();
1069
729
    RegionOffset RightOffset = RightMR->getAsOffset();
1070
1071
729
    if (LeftOffset.getRegion() != nullptr &&
1072
729
        LeftOffset.getRegion() == RightOffset.getRegion() &&
1073
64
        !LeftOffset.hasSymbolicOffset() && 
!RightOffset.hasSymbolicOffset()58
) {
1074
54
      int64_t left = LeftOffset.getOffset();
1075
54
      int64_t right = RightOffset.getOffset();
1076
1077
54
      switch (op) {
1078
4
        default:
1079
4
          return UnknownVal();
1080
0
        case BO_LT:
1081
0
          return makeTruthVal(left < right, resultTy);
1082
32
        case BO_GT:
1083
32
          return makeTruthVal(left > right, resultTy);
1084
0
        case BO_LE:
1085
0
          return makeTruthVal(left <= right, resultTy);
1086
0
        case BO_GE:
1087
0
          return makeTruthVal(left >= right, resultTy);
1088
16
        case BO_EQ:
1089
16
          return makeTruthVal(left == right, resultTy);
1090
2
        case BO_NE:
1091
2
          return makeTruthVal(left != right, resultTy);
1092
675
      }
1093
675
    }
1094
1095
    // At this point we're not going to get a good answer, but we can try
1096
    // conjuring an expression instead.
1097
675
    SymbolRef LHSSym = lhs.getAsLocSymbol();
1098
675
    SymbolRef RHSSym = rhs.getAsLocSymbol();
1099
675
    if (LHSSym && 
RHSSym618
)
1100
556
      return makeNonLoc(LHSSym, op, RHSSym, resultTy);
1101
1102
    // If we get here, we have no way of comparing the regions.
1103
119
    return UnknownVal();
1104
119
  }
1105
7.01k
  }
1106
7.01k
}
1107
1108
SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1109
                                    BinaryOperator::Opcode op, Loc lhs,
1110
12.0k
                                    NonLoc rhs, QualType resultTy) {
1111
12.0k
  if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
1112
34
    if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
1113
34
      if (PTMSV->isNullMemberPointer())
1114
1
        return UndefinedVal();
1115
1116
33
      auto getFieldLValue = [&](const auto *FD) -> SVal {
1117
14
        SVal Result = lhs;
1118
1119
14
        for (const auto &I : *PTMSV)
1120
21
          Result = StateMgr.getStoreManager().evalDerivedToBase(
1121
21
              Result, I->getType(), I->isVirtual());
1122
1123
14
        return state->getLValue(FD, Result);
1124
14
      };
SimpleSValBuilder.cpp:clang::ento::SVal (anonymous namespace)::SimpleSValBuilder::evalBinOpLN(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::BinaryOperatorKind, clang::ento::Loc, clang::ento::NonLoc, clang::QualType)::$_0::operator()<clang::FieldDecl>(clang::FieldDecl const*) const
Line
Count
Source
1116
10
      auto getFieldLValue = [&](const auto *FD) -> SVal {
1117
10
        SVal Result = lhs;
1118
1119
10
        for (const auto &I : *PTMSV)
1120
21
          Result = StateMgr.getStoreManager().evalDerivedToBase(
1121
21
              Result, I->getType(), I->isVirtual());
1122
1123
10
        return state->getLValue(FD, Result);
1124
10
      };
SimpleSValBuilder.cpp:clang::ento::SVal (anonymous namespace)::SimpleSValBuilder::evalBinOpLN(llvm::IntrusiveRefCntPtr<clang::ento::ProgramState const>, clang::BinaryOperatorKind, clang::ento::Loc, clang::ento::NonLoc, clang::QualType)::$_0::operator()<clang::IndirectFieldDecl>(clang::IndirectFieldDecl const*) const
Line
Count
Source
1116
4
      auto getFieldLValue = [&](const auto *FD) -> SVal {
1117
4
        SVal Result = lhs;
1118
1119
4
        for (const auto &I : *PTMSV)
1120
0
          Result = StateMgr.getStoreManager().evalDerivedToBase(
1121
0
              Result, I->getType(), I->isVirtual());
1122
1123
4
        return state->getLValue(FD, Result);
1124
4
      };
1125
1126
33
      if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
1127
10
        return getFieldLValue(FD);
1128
10
      }
1129
23
      if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
1130
4
        return getFieldLValue(FD);
1131
4
      }
1132
19
    }
1133
1134
19
    return rhs;
1135
19
  }
1136
1137
11.9k
  assert(!BinaryOperator::isComparisonOp(op) &&
1138
11.9k
         "arguments to comparison ops must be of the same type");
1139
1140
  // Special case: rhs is a zero constant.
1141
11.9k
  if (rhs.isZeroConstant())
1142
443
    return lhs;
1143
1144
  // Perserve the null pointer so that it can be found by the DerefChecker.
1145
11.5k
  if (lhs.isZeroConstant())
1146
7
    return lhs;
1147
1148
  // We are dealing with pointer arithmetic.
1149
1150
  // Handle pointer arithmetic on constant values.
1151
11.5k
  if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
1152
2.29k
    if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1153
15
      const llvm::APSInt &leftI = lhsInt->getValue();
1154
15
      assert(leftI.isUnsigned());
1155
15
      llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1156
1157
      // Convert the bitwidth of rightI.  This should deal with overflow
1158
      // since we are dealing with concrete values.
1159
15
      rightI = rightI.extOrTrunc(leftI.getBitWidth());
1160
1161
      // Offset the increment by the pointer size.
1162
15
      llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
1163
15
      QualType pointeeType = resultTy->getPointeeType();
1164
15
      Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1165
15
      rightI *= Multiplicand;
1166
1167
      // Compute the adjusted pointer.
1168
15
      switch (op) {
1169
2
        case BO_Add:
1170
2
          rightI = leftI + rightI;
1171
2
          break;
1172
13
        case BO_Sub:
1173
13
          rightI = leftI - rightI;
1174
13
          break;
1175
0
        default:
1176
0
          llvm_unreachable("Invalid pointer arithmetic operation");
1177
15
      }
1178
15
      return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1179
15
    }
1180
2.29k
  }
1181
1182
  // Handle cases where 'lhs' is a region.
1183
11.5k
  if (const MemRegion *region = lhs.getAsRegion()) {
1184
11.5k
    rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1185
11.5k
    SVal index = UnknownVal();
1186
11.5k
    const SubRegion *superR = nullptr;
1187
    // We need to know the type of the pointer in order to add an integer to it.
1188
    // Depending on the type, different amount of bytes is added.
1189
11.5k
    QualType elementType;
1190
1191
11.5k
    if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
1192
10.8k
      assert(op == BO_Add || op == BO_Sub);
1193
10.8k
      index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1194
10.8k
                          getArrayIndexType());
1195
10.8k
      superR = cast<SubRegion>(elemReg->getSuperRegion());
1196
10.8k
      elementType = elemReg->getElementType();
1197
10.8k
    }
1198
698
    else if (isa<SubRegion>(region)) {
1199
698
      assert(op == BO_Add || op == BO_Sub);
1200
502
      index = (op == BO_Add) ? rhs : 
evalMinus(rhs)196
;
1201
698
      superR = cast<SubRegion>(region);
1202
      // TODO: Is this actually reliable? Maybe improving our MemRegion
1203
      // hierarchy to provide typed regions for all non-void pointers would be
1204
      // better. For instance, we cannot extend this towards LocAsInteger
1205
      // operations, where result type of the expression is integer.
1206
698
      if (resultTy->isAnyPointerType())
1207
698
        elementType = resultTy->getPointeeType();
1208
698
    }
1209
1210
    // Represent arithmetic on void pointers as arithmetic on char pointers.
1211
    // It is fine when a TypedValueRegion of char value type represents
1212
    // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1213
11.5k
    if (elementType->isVoidType())
1214
5
      elementType = getContext().CharTy;
1215
1216
11.5k
    if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1217
11.5k
      return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1218
11.5k
                                                       superR, getContext()));
1219
11.5k
    }
1220
6
  }
1221
6
  return UnknownVal();
1222
6
}
1223
1224
const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1225
224k
                                                   SVal V) {
1226
224k
  V = simplifySVal(state, V);
1227
224k
  if (V.isUnknownOrUndef())
1228
0
    return nullptr;
1229
1230
224k
  if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1231
4
    return &X->getValue();
1232
1233
224k
  if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1234
85.3k
    return &X->getValue();
1235
1236
138k
  if (SymbolRef Sym = V.getAsSymbol())
1237
138k
    return state->getConstraintManager().getSymVal(state, Sym);
1238
1239
  // FIXME: Add support for SymExprs.
1240
5
  return nullptr;
1241
5
}
1242
1243
287k
SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1244
  // For now, this function tries to constant-fold symbols inside a
1245
  // nonloc::SymbolVal, and does nothing else. More simplifications should
1246
  // be possible, such as constant-folding an index in an ElementRegion.
1247
1248
287k
  class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1249
287k
    ProgramStateRef State;
1250
287k
    SValBuilder &SVB;
1251
1252
    // Cache results for the lifetime of the Simplifier. Results change every
1253
    // time new constraints are added to the program state, which is the whole
1254
    // point of simplifying, and for that very reason it's pointless to maintain
1255
    // the same cache for the duration of the whole analysis.
1256
287k
    llvm::DenseMap<SymbolRef, SVal> Cached;
1257
1258
86.3k
    static bool isUnchanged(SymbolRef Sym, SVal Val) {
1259
86.3k
      return Sym == Val.getAsSymbol();
1260
86.3k
    }
1261
1262
45.4k
    SVal cache(SymbolRef Sym, SVal V) {
1263
45.4k
      Cached[Sym] = V;
1264
45.4k
      return V;
1265
45.4k
    }
1266
1267
45.4k
    SVal skip(SymbolRef Sym) {
1268
45.4k
      return cache(Sym, SVB.makeSymbolVal(Sym));
1269
45.4k
    }
1270
1271
287k
  public:
1272
287k
    Simplifier(ProgramStateRef State)
1273
166k
        : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1274
1275
120k
    SVal VisitSymbolData(const SymbolData *S) {
1276
      // No cache here.
1277
120k
      if (const llvm::APSInt *I =
1278
753
              SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
1279
753
        return Loc::isLocType(S->getType()) ? 
(SVal)SVB.makeIntLocVal(*I)1
1280
752
                                            : (SVal)SVB.makeIntVal(*I);
1281
120k
      return SVB.makeSymbolVal(S);
1282
120k
    }
1283
1284
    // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1285
    // start producing them.
1286
1287
4.71k
    SVal VisitSymIntExpr(const SymIntExpr *S) {
1288
4.71k
      auto I = Cached.find(S);
1289
4.71k
      if (I != Cached.end())
1290
100
        return I->second;
1291
1292
4.61k
      SVal LHS = Visit(S->getLHS());
1293
4.61k
      if (isUnchanged(S->getLHS(), LHS))
1294
4.56k
        return skip(S);
1295
1296
54
      SVal RHS;
1297
      // By looking at the APSInt in the right-hand side of S, we cannot
1298
      // figure out if it should be treated as a Loc or as a NonLoc.
1299
      // So make our guess by recalling that we cannot multiply pointers
1300
      // or compare a pointer to an integer.
1301
54
      if (Loc::isLocType(S->getLHS()->getType()) &&
1302
0
          BinaryOperator::isComparisonOp(S->getOpcode())) {
1303
        // The usual conversion of $sym to &SymRegion{$sym}, as they have
1304
        // the same meaning for Loc-type symbols, but the latter form
1305
        // is preferred in SVal computations for being Loc itself.
1306
0
        if (SymbolRef Sym = LHS.getAsSymbol()) {
1307
0
          assert(Loc::isLocType(Sym->getType()));
1308
0
          LHS = SVB.makeLoc(Sym);
1309
0
        }
1310
0
        RHS = SVB.makeIntLocVal(S->getRHS());
1311
54
      } else {
1312
54
        RHS = SVB.makeIntVal(S->getRHS());
1313
54
      }
1314
1315
54
      return cache(
1316
54
          S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1317
54
    }
1318
1319
41.9k
    SVal VisitSymSymExpr(const SymSymExpr *S) {
1320
41.9k
      auto I = Cached.find(S);
1321
41.9k
      if (I != Cached.end())
1322
1.07k
        return I->second;
1323
1324
      // For now don't try to simplify mixed Loc/NonLoc expressions
1325
      // because they often appear from LocAsInteger operations
1326
      // and we don't know how to combine a LocAsInteger
1327
      // with a concrete value.
1328
40.8k
      if (Loc::isLocType(S->getLHS()->getType()) !=
1329
40.8k
          Loc::isLocType(S->getRHS()->getType()))
1330
2
        return skip(S);
1331
1332
40.8k
      SVal LHS = Visit(S->getLHS());
1333
40.8k
      SVal RHS = Visit(S->getRHS());
1334
40.8k
      if (isUnchanged(S->getLHS(), LHS) && 
isUnchanged(S->getRHS(), RHS)40.8k
)
1335
40.8k
        return skip(S);
1336
1337
13
      return cache(
1338
13
          S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1339
13
    }
1340
1341
330
    SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1342
1343
0
    SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1344
1345
81.5k
    SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1346
      // Simplification is much more costly than computing complexity.
1347
      // For high complexity, it may be not worth it.
1348
81.5k
      return Visit(V.getSymbol());
1349
81.5k
    }
1350
1351
85.0k
    SVal VisitSVal(SVal V) { return V; }
1352
287k
  };
1353
1354
  // A crude way of preventing this function from calling itself from evalBinOp.
1355
287k
  static bool isReentering = false;
1356
287k
  if (isReentering)
1357
120k
    return V;
1358
1359
166k
  isReentering = true;
1360
166k
  SVal SimplifiedV = Simplifier(State).Visit(V);
1361
166k
  isReentering = false;
1362
1363
166k
  return SimplifiedV;
1364
166k
}