Coverage Report

Created: 2020-02-15 09:57

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