1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 
18 using namespace clang;
19 using namespace ento;
20 
21 namespace {
22 class SimpleSValBuilder : public SValBuilder {
23 protected:
24   virtual SVal dispatchCast(SVal val, QualType castTy);
25   virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
26   virtual SVal evalCastFromLoc(Loc val, QualType castTy);
27 
28 public:
29   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
30                     ProgramStateManager &stateMgr)
31                     : SValBuilder(alloc, context, stateMgr) {}
32   virtual ~SimpleSValBuilder() {}
33 
34   virtual SVal evalMinus(NonLoc val);
35   virtual SVal evalComplement(NonLoc val);
36   virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
37                            NonLoc lhs, NonLoc rhs, QualType resultTy);
38   virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
39                            Loc lhs, Loc rhs, QualType resultTy);
40   virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
41                            Loc lhs, NonLoc rhs, QualType resultTy);
42 
43   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
44   ///  (integer) value, that value is returned. Otherwise, returns NULL.
45   virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
46 
47   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
48                      const llvm::APSInt &RHS, QualType resultTy);
49 };
50 } // end anonymous namespace
51 
52 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
53                                            ASTContext &context,
54                                            ProgramStateManager &stateMgr) {
55   return new SimpleSValBuilder(alloc, context, stateMgr);
56 }
57 
58 //===----------------------------------------------------------------------===//
59 // Transfer function for Casts.
60 //===----------------------------------------------------------------------===//
61 
62 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
63   assert(isa<Loc>(&Val) || isa<NonLoc>(&Val));
64   return isa<Loc>(Val) ? evalCastFromLoc(cast<Loc>(Val), CastTy)
65                        : evalCastFromNonLoc(cast<NonLoc>(Val), CastTy);
66 }
67 
68 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
69 
70   bool isLocType = Loc::isLocType(castTy);
71 
72   if (nonloc::LocAsInteger *LI = dyn_cast<nonloc::LocAsInteger>(&val)) {
73     if (isLocType)
74       return LI->getLoc();
75 
76     // FIXME: Correctly support promotions/truncations.
77     unsigned castSize = Context.getTypeSize(castTy);
78     if (castSize == LI->getNumBits())
79       return val;
80     return makeLocAsInteger(LI->getLoc(), castSize);
81   }
82 
83   if (const SymExpr *se = val.getAsSymbolicExpression()) {
84     QualType T = Context.getCanonicalType(se->getType(Context));
85     // If types are the same or both are integers, ignore the cast.
86     // FIXME: Remove this hack when we support symbolic truncation/extension.
87     // HACK: If both castTy and T are integers, ignore the cast.  This is
88     // not a permanent solution.  Eventually we want to precisely handle
89     // extension/truncation of symbolic integers.  This prevents us from losing
90     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
91     // different integer types.
92    if (haveSameType(T, castTy))
93       return val;
94 
95     if (!isLocType)
96       return makeNonLoc(se, T, castTy);
97     return UnknownVal();
98   }
99 
100   // If value is a non integer constant, produce unknown.
101   if (!isa<nonloc::ConcreteInt>(val))
102     return UnknownVal();
103 
104   // Only handle casts from integers to integers - if val is an integer constant
105   // being cast to a non integer type, produce unknown.
106   if (!isLocType && !castTy->isIntegerType())
107     return UnknownVal();
108 
109   llvm::APSInt i = cast<nonloc::ConcreteInt>(val).getValue();
110   BasicVals.getAPSIntType(castTy).apply(i);
111 
112   if (isLocType)
113     return makeIntLocVal(i);
114   else
115     return makeIntVal(i);
116 }
117 
118 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
119 
120   // Casts from pointers -> pointers, just return the lval.
121   //
122   // Casts from pointers -> references, just return the lval.  These
123   //   can be introduced by the frontend for corner cases, e.g
124   //   casting from va_list* to __builtin_va_list&.
125   //
126   if (Loc::isLocType(castTy) || castTy->isReferenceType())
127     return val;
128 
129   // FIXME: Handle transparent unions where a value can be "transparently"
130   //  lifted into a union type.
131   if (castTy->isUnionType())
132     return UnknownVal();
133 
134   if (castTy->isIntegerType()) {
135     unsigned BitWidth = Context.getTypeSize(castTy);
136 
137     if (!isa<loc::ConcreteInt>(val))
138       return makeLocAsInteger(val, BitWidth);
139 
140     llvm::APSInt i = cast<loc::ConcreteInt>(val).getValue();
141     BasicVals.getAPSIntType(castTy).apply(i);
142     return makeIntVal(i);
143   }
144 
145   // All other cases: return 'UnknownVal'.  This includes casting pointers
146   // to floats, which is probably badness it itself, but this is a good
147   // intermediate solution until we do something better.
148   return UnknownVal();
149 }
150 
151 //===----------------------------------------------------------------------===//
152 // Transfer function for unary operators.
153 //===----------------------------------------------------------------------===//
154 
155 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
156   switch (val.getSubKind()) {
157   case nonloc::ConcreteIntKind:
158     return cast<nonloc::ConcreteInt>(val).evalMinus(*this);
159   default:
160     return UnknownVal();
161   }
162 }
163 
164 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
165   switch (X.getSubKind()) {
166   case nonloc::ConcreteIntKind:
167     return cast<nonloc::ConcreteInt>(X).evalComplement(*this);
168   default:
169     return UnknownVal();
170   }
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // Transfer function for binary operators.
175 //===----------------------------------------------------------------------===//
176 
177 static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
178   switch (op) {
179   default:
180     llvm_unreachable("Invalid opcode.");
181   case BO_LT: return BO_GE;
182   case BO_GT: return BO_LE;
183   case BO_LE: return BO_GT;
184   case BO_GE: return BO_LT;
185   case BO_EQ: return BO_NE;
186   case BO_NE: return BO_EQ;
187   }
188 }
189 
190 static BinaryOperator::Opcode ReverseComparison(BinaryOperator::Opcode op) {
191   switch (op) {
192   default:
193     llvm_unreachable("Invalid opcode.");
194   case BO_LT: return BO_GT;
195   case BO_GT: return BO_LT;
196   case BO_LE: return BO_GE;
197   case BO_GE: return BO_LE;
198   case BO_EQ:
199   case BO_NE:
200     return op;
201   }
202 }
203 
204 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
205                                     BinaryOperator::Opcode op,
206                                     const llvm::APSInt &RHS,
207                                     QualType resultTy) {
208   bool isIdempotent = false;
209 
210   // Check for a few special cases with known reductions first.
211   switch (op) {
212   default:
213     // We can't reduce this case; just treat it normally.
214     break;
215   case BO_Mul:
216     // a*0 and a*1
217     if (RHS == 0)
218       return makeIntVal(0, resultTy);
219     else if (RHS == 1)
220       isIdempotent = true;
221     break;
222   case BO_Div:
223     // a/0 and a/1
224     if (RHS == 0)
225       // This is also handled elsewhere.
226       return UndefinedVal();
227     else if (RHS == 1)
228       isIdempotent = true;
229     break;
230   case BO_Rem:
231     // a%0 and a%1
232     if (RHS == 0)
233       // This is also handled elsewhere.
234       return UndefinedVal();
235     else if (RHS == 1)
236       return makeIntVal(0, resultTy);
237     break;
238   case BO_Add:
239   case BO_Sub:
240   case BO_Shl:
241   case BO_Shr:
242   case BO_Xor:
243     // a+0, a-0, a<<0, a>>0, a^0
244     if (RHS == 0)
245       isIdempotent = true;
246     break;
247   case BO_And:
248     // a&0 and a&(~0)
249     if (RHS == 0)
250       return makeIntVal(0, resultTy);
251     else if (RHS.isAllOnesValue())
252       isIdempotent = true;
253     break;
254   case BO_Or:
255     // a|0 and a|(~0)
256     if (RHS == 0)
257       isIdempotent = true;
258     else if (RHS.isAllOnesValue()) {
259       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
260       return nonloc::ConcreteInt(Result);
261     }
262     break;
263   }
264 
265   // Idempotent ops (like a*1) can still change the type of an expression.
266   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
267   // dirty work.
268   if (isIdempotent)
269       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
270 
271   // If we reach this point, the expression cannot be simplified.
272   // Make a SymbolVal for the entire expression, after converting the RHS.
273   const llvm::APSInt *ConvertedRHS = &RHS;
274   if (BinaryOperator::isComparisonOp(op)) {
275     // We're looking for a type big enough to compare the symbolic value
276     // with the given constant.
277     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
278     ASTContext &Ctx = getContext();
279     QualType SymbolType = LHS->getType(Ctx);
280     uint64_t ValWidth = RHS.getBitWidth();
281     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
282 
283     if (ValWidth < TypeWidth) {
284       // If the value is too small, extend it.
285       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
286     } else if (ValWidth == TypeWidth) {
287       // If the value is signed but the symbol is unsigned, do the comparison
288       // in unsigned space. [C99 6.3.1.8]
289       // (For the opposite case, the value is already unsigned.)
290       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
291         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
292     }
293   } else
294     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
295 
296   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
297 }
298 
299 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
300                                   BinaryOperator::Opcode op,
301                                   NonLoc lhs, NonLoc rhs,
302                                   QualType resultTy)  {
303   NonLoc InputLHS = lhs;
304   NonLoc InputRHS = rhs;
305 
306   // Handle trivial case where left-side and right-side are the same.
307   if (lhs == rhs)
308     switch (op) {
309       default:
310         break;
311       case BO_EQ:
312       case BO_LE:
313       case BO_GE:
314         return makeTruthVal(true, resultTy);
315       case BO_LT:
316       case BO_GT:
317       case BO_NE:
318         return makeTruthVal(false, resultTy);
319       case BO_Xor:
320       case BO_Sub:
321         return makeIntVal(0, resultTy);
322       case BO_Or:
323       case BO_And:
324         return evalCastFromNonLoc(lhs, resultTy);
325     }
326 
327   while (1) {
328     switch (lhs.getSubKind()) {
329     default:
330       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
331     case nonloc::LocAsIntegerKind: {
332       Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();
333       switch (rhs.getSubKind()) {
334         case nonloc::LocAsIntegerKind:
335           return evalBinOpLL(state, op, lhsL,
336                              cast<nonloc::LocAsInteger>(rhs).getLoc(),
337                              resultTy);
338         case nonloc::ConcreteIntKind: {
339           // Transform the integer into a location and compare.
340           llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
341           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
342           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
343         }
344         default:
345           switch (op) {
346             case BO_EQ:
347               return makeTruthVal(false, resultTy);
348             case BO_NE:
349               return makeTruthVal(true, resultTy);
350             default:
351               // This case also handles pointer arithmetic.
352               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
353           }
354       }
355     }
356     case nonloc::ConcreteIntKind: {
357       llvm::APSInt LHSValue = cast<nonloc::ConcreteInt>(lhs).getValue();
358 
359       // If we're dealing with two known constants, just perform the operation.
360       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
361         llvm::APSInt RHSValue = *KnownRHSValue;
362         if (BinaryOperator::isComparisonOp(op)) {
363           // We're looking for a type big enough to compare the two values.
364           // FIXME: This is not correct. char + short will result in a promotion
365           // to int. Unfortunately we have lost types by this point.
366           APSIntType CompareType = std::max(APSIntType(LHSValue),
367                                             APSIntType(RHSValue));
368           CompareType.apply(LHSValue);
369           CompareType.apply(RHSValue);
370         } else if (!BinaryOperator::isShiftOp(op)) {
371           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
372           IntType.apply(LHSValue);
373           IntType.apply(RHSValue);
374         }
375 
376         const llvm::APSInt *Result =
377           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
378         if (!Result)
379           return UndefinedVal();
380 
381         return nonloc::ConcreteInt(*Result);
382       }
383 
384       // Swap the left and right sides and flip the operator if doing so
385       // allows us to better reason about the expression (this is a form
386       // of expression canonicalization).
387       // While we're at it, catch some special cases for non-commutative ops.
388       switch (op) {
389       case BO_LT:
390       case BO_GT:
391       case BO_LE:
392       case BO_GE:
393         op = ReverseComparison(op);
394         // FALL-THROUGH
395       case BO_EQ:
396       case BO_NE:
397       case BO_Add:
398       case BO_Mul:
399       case BO_And:
400       case BO_Xor:
401       case BO_Or:
402         std::swap(lhs, rhs);
403         continue;
404       case BO_Shr:
405         // (~0)>>a
406         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
407           return evalCastFromNonLoc(lhs, resultTy);
408         // FALL-THROUGH
409       case BO_Shl:
410         // 0<<a and 0>>a
411         if (LHSValue == 0)
412           return evalCastFromNonLoc(lhs, resultTy);
413         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
414       default:
415         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
416       }
417     }
418     case nonloc::SymbolValKind: {
419       // We only handle LHS as simple symbols or SymIntExprs.
420       SymbolRef Sym = cast<nonloc::SymbolVal>(lhs).getSymbol();
421 
422       // LHS is a symbolic expression.
423       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
424 
425         // Is this a logical not? (!x is represented as x == 0.)
426         if (op == BO_EQ && rhs.isZeroConstant()) {
427           // We know how to negate certain expressions. Simplify them here.
428 
429           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
430           switch (opc) {
431           default:
432             // We don't know how to negate this operation.
433             // Just handle it as if it were a normal comparison to 0.
434             break;
435           case BO_LAnd:
436           case BO_LOr:
437             llvm_unreachable("Logical operators handled by branching logic.");
438           case BO_Assign:
439           case BO_MulAssign:
440           case BO_DivAssign:
441           case BO_RemAssign:
442           case BO_AddAssign:
443           case BO_SubAssign:
444           case BO_ShlAssign:
445           case BO_ShrAssign:
446           case BO_AndAssign:
447           case BO_XorAssign:
448           case BO_OrAssign:
449           case BO_Comma:
450             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
451           case BO_PtrMemD:
452           case BO_PtrMemI:
453             llvm_unreachable("Pointer arithmetic not handled here.");
454           case BO_LT:
455           case BO_GT:
456           case BO_LE:
457           case BO_GE:
458           case BO_EQ:
459           case BO_NE:
460             // Negate the comparison and make a value.
461             opc = NegateComparison(opc);
462             assert(symIntExpr->getType(Context) == resultTy);
463             return makeNonLoc(symIntExpr->getLHS(), opc,
464                 symIntExpr->getRHS(), resultTy);
465           }
466         }
467 
468         // For now, only handle expressions whose RHS is a constant.
469         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
470           // If both the LHS and the current expression are additive,
471           // fold their constants and try again.
472           if (BinaryOperator::isAdditiveOp(op)) {
473             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
474             if (BinaryOperator::isAdditiveOp(lop)) {
475               // Convert the two constants to a common type, then combine them.
476 
477               // resultTy may not be the best type to convert to, but it's
478               // probably the best choice in expressions with mixed type
479               // (such as x+1U+2LL). The rules for implicit conversions should
480               // choose a reasonable type to preserve the expression, and will
481               // at least match how the value is going to be used.
482               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
483               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
484               const llvm::APSInt &second = IntType.convert(*RHSValue);
485 
486               const llvm::APSInt *newRHS;
487               if (lop == op)
488                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
489               else
490                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
491 
492               assert(newRHS && "Invalid operation despite common type!");
493               rhs = nonloc::ConcreteInt(*newRHS);
494               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
495               op = lop;
496               continue;
497             }
498           }
499 
500           // Otherwise, make a SymIntExpr out of the expression.
501           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
502         }
503 
504 
505       } else if (isa<SymbolData>(Sym)) {
506         // Does the symbol simplify to a constant?  If so, "fold" the constant
507         // by setting 'lhs' to a ConcreteInt and try again.
508         if (const llvm::APSInt *Constant = state->getSymVal(Sym)) {
509           lhs = nonloc::ConcreteInt(*Constant);
510           continue;
511         }
512 
513         // Is the RHS a constant?
514         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
515           return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
516       }
517 
518       // Give up -- this is not a symbolic expression we can handle.
519       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
520     }
521     }
522   }
523 }
524 
525 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
526 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
527                                   BinaryOperator::Opcode op,
528                                   Loc lhs, Loc rhs,
529                                   QualType resultTy) {
530   // Only comparisons and subtractions are valid operations on two pointers.
531   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
532   // However, if a pointer is casted to an integer, evalBinOpNN may end up
533   // calling this function with another operation (PR7527). We don't attempt to
534   // model this for now, but it could be useful, particularly when the
535   // "location" is actually an integer value that's been passed through a void*.
536   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
537     return UnknownVal();
538 
539   // Special cases for when both sides are identical.
540   if (lhs == rhs) {
541     switch (op) {
542     default:
543       llvm_unreachable("Unimplemented operation for two identical values");
544     case BO_Sub:
545       return makeZeroVal(resultTy);
546     case BO_EQ:
547     case BO_LE:
548     case BO_GE:
549       return makeTruthVal(true, resultTy);
550     case BO_NE:
551     case BO_LT:
552     case BO_GT:
553       return makeTruthVal(false, resultTy);
554     }
555   }
556 
557   switch (lhs.getSubKind()) {
558   default:
559     llvm_unreachable("Ordering not implemented for this Loc.");
560 
561   case loc::GotoLabelKind:
562     // The only thing we know about labels is that they're non-null.
563     if (rhs.isZeroConstant()) {
564       switch (op) {
565       default:
566         break;
567       case BO_Sub:
568         return evalCastFromLoc(lhs, resultTy);
569       case BO_EQ:
570       case BO_LE:
571       case BO_LT:
572         return makeTruthVal(false, resultTy);
573       case BO_NE:
574       case BO_GT:
575       case BO_GE:
576         return makeTruthVal(true, resultTy);
577       }
578     }
579     // There may be two labels for the same location, and a function region may
580     // have the same address as a label at the start of the function (depending
581     // on the ABI).
582     // FIXME: we can probably do a comparison against other MemRegions, though.
583     // FIXME: is there a way to tell if two labels refer to the same location?
584     return UnknownVal();
585 
586   case loc::ConcreteIntKind: {
587     // If one of the operands is a symbol and the other is a constant,
588     // build an expression for use by the constraint manager.
589     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
590       // We can only build expressions with symbols on the left,
591       // so we need a reversible operator.
592       if (!BinaryOperator::isComparisonOp(op))
593         return UnknownVal();
594 
595       const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
596       return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
597     }
598 
599     // If both operands are constants, just perform the operation.
600     if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
601       SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
602                                                              *rInt);
603       if (Loc *Result = dyn_cast<Loc>(&ResultVal))
604         return evalCastFromLoc(*Result, resultTy);
605       else
606         return UnknownVal();
607     }
608 
609     // Special case comparisons against NULL.
610     // This must come after the test if the RHS is a symbol, which is used to
611     // build constraints. The address of any non-symbolic region is guaranteed
612     // to be non-NULL, as is any label.
613     assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
614     if (lhs.isZeroConstant()) {
615       switch (op) {
616       default:
617         break;
618       case BO_EQ:
619       case BO_GT:
620       case BO_GE:
621         return makeTruthVal(false, resultTy);
622       case BO_NE:
623       case BO_LT:
624       case BO_LE:
625         return makeTruthVal(true, resultTy);
626       }
627     }
628 
629     // Comparing an arbitrary integer to a region or label address is
630     // completely unknowable.
631     return UnknownVal();
632   }
633   case loc::MemRegionKind: {
634     if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
635       // If one of the operands is a symbol and the other is a constant,
636       // build an expression for use by the constraint manager.
637       if (SymbolRef lSym = lhs.getAsLocSymbol())
638         return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
639 
640       // Special case comparisons to NULL.
641       // This must come after the test if the LHS is a symbol, which is used to
642       // build constraints. The address of any non-symbolic region is guaranteed
643       // to be non-NULL.
644       if (rInt->isZeroConstant()) {
645         switch (op) {
646         default:
647           break;
648         case BO_Sub:
649           return evalCastFromLoc(lhs, resultTy);
650         case BO_EQ:
651         case BO_LT:
652         case BO_LE:
653           return makeTruthVal(false, resultTy);
654         case BO_NE:
655         case BO_GT:
656         case BO_GE:
657           return makeTruthVal(true, resultTy);
658         }
659       }
660 
661       // Comparing a region to an arbitrary integer is completely unknowable.
662       return UnknownVal();
663     }
664 
665     // Get both values as regions, if possible.
666     const MemRegion *LeftMR = lhs.getAsRegion();
667     assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
668 
669     const MemRegion *RightMR = rhs.getAsRegion();
670     if (!RightMR)
671       // The RHS is probably a label, which in theory could address a region.
672       // FIXME: we can probably make a more useful statement about non-code
673       // regions, though.
674       return UnknownVal();
675 
676     const MemSpaceRegion *LeftMS = LeftMR->getMemorySpace();
677     const MemSpaceRegion *RightMS = RightMR->getMemorySpace();
678     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
679     const MemRegion *LeftBase = LeftMR->getBaseRegion();
680     const MemRegion *RightBase = RightMR->getBaseRegion();
681 
682     // If the two regions are from different known memory spaces they cannot be
683     // equal. Also, assume that no symbolic region (whose memory space is
684     // unknown) is on the stack.
685     if (LeftMS != RightMS &&
686         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
687          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
688       switch (op) {
689       default:
690         return UnknownVal();
691       case BO_EQ:
692         return makeTruthVal(false, resultTy);
693       case BO_NE:
694         return makeTruthVal(true, resultTy);
695       }
696     }
697 
698     // If both values wrap regions, see if they're from different base regions.
699     // Note, heap base symbolic regions are assumed to not alias with
700     // each other; for example, we assume that malloc returns different address
701     // on each invocation.
702     if (LeftBase != RightBase &&
703         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
704          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
705       switch (op) {
706       default:
707         return UnknownVal();
708       case BO_EQ:
709         return makeTruthVal(false, resultTy);
710       case BO_NE:
711         return makeTruthVal(true, resultTy);
712       }
713     }
714 
715     // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
716     // ElementRegion path and the FieldRegion path below should be unified.
717     if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
718       // First see if the right region is also an ElementRegion.
719       const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
720       if (!RightER)
721         return UnknownVal();
722 
723       // Next, see if the two ERs have the same super-region and matching types.
724       // FIXME: This should do something useful even if the types don't match,
725       // though if both indexes are constant the RegionRawOffset path will
726       // give the correct answer.
727       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
728           LeftER->getElementType() == RightER->getElementType()) {
729         // Get the left index and cast it to the correct type.
730         // If the index is unknown or undefined, bail out here.
731         SVal LeftIndexVal = LeftER->getIndex();
732         NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
733         if (!LeftIndex)
734           return UnknownVal();
735         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
736         LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
737         if (!LeftIndex)
738           return UnknownVal();
739 
740         // Do the same for the right index.
741         SVal RightIndexVal = RightER->getIndex();
742         NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
743         if (!RightIndex)
744           return UnknownVal();
745         RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
746         RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
747         if (!RightIndex)
748           return UnknownVal();
749 
750         // Actually perform the operation.
751         // evalBinOpNN expects the two indexes to already be the right type.
752         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
753       }
754 
755       // If the element indexes aren't comparable, see if the raw offsets are.
756       RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
757       RegionRawOffset RightOffset = RightER->getAsArrayOffset();
758 
759       if (LeftOffset.getRegion() != NULL &&
760           LeftOffset.getRegion() == RightOffset.getRegion()) {
761         CharUnits left = LeftOffset.getOffset();
762         CharUnits right = RightOffset.getOffset();
763 
764         switch (op) {
765         default:
766           return UnknownVal();
767         case BO_LT:
768           return makeTruthVal(left < right, resultTy);
769         case BO_GT:
770           return makeTruthVal(left > right, resultTy);
771         case BO_LE:
772           return makeTruthVal(left <= right, resultTy);
773         case BO_GE:
774           return makeTruthVal(left >= right, resultTy);
775         case BO_EQ:
776           return makeTruthVal(left == right, resultTy);
777         case BO_NE:
778           return makeTruthVal(left != right, resultTy);
779         }
780       }
781 
782       // If we get here, we have no way of comparing the ElementRegions.
783       return UnknownVal();
784     }
785 
786     // See if both regions are fields of the same structure.
787     // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
788     if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
789       // Only comparisons are meaningful here!
790       if (!BinaryOperator::isComparisonOp(op))
791         return UnknownVal();
792 
793       // First see if the right region is also a FieldRegion.
794       const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
795       if (!RightFR)
796         return UnknownVal();
797 
798       // Next, see if the two FRs have the same super-region.
799       // FIXME: This doesn't handle casts yet, and simply stripping the casts
800       // doesn't help.
801       if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
802         return UnknownVal();
803 
804       const FieldDecl *LeftFD = LeftFR->getDecl();
805       const FieldDecl *RightFD = RightFR->getDecl();
806       const RecordDecl *RD = LeftFD->getParent();
807 
808       // Make sure the two FRs are from the same kind of record. Just in case!
809       // FIXME: This is probably where inheritance would be a problem.
810       if (RD != RightFD->getParent())
811         return UnknownVal();
812 
813       // We know for sure that the two fields are not the same, since that
814       // would have given us the same SVal.
815       if (op == BO_EQ)
816         return makeTruthVal(false, resultTy);
817       if (op == BO_NE)
818         return makeTruthVal(true, resultTy);
819 
820       // Iterate through the fields and see which one comes first.
821       // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
822       // members and the units in which bit-fields reside have addresses that
823       // increase in the order in which they are declared."
824       bool leftFirst = (op == BO_LT || op == BO_LE);
825       for (RecordDecl::field_iterator I = RD->field_begin(),
826            E = RD->field_end(); I!=E; ++I) {
827         if (*I == LeftFD)
828           return makeTruthVal(leftFirst, resultTy);
829         if (*I == RightFD)
830           return makeTruthVal(!leftFirst, resultTy);
831       }
832 
833       llvm_unreachable("Fields not found in parent record's definition");
834     }
835 
836     // If we get here, we have no way of comparing the regions.
837     return UnknownVal();
838   }
839   }
840 }
841 
842 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
843                                   BinaryOperator::Opcode op,
844                                   Loc lhs, NonLoc rhs, QualType resultTy) {
845 
846   // Special case: rhs is a zero constant.
847   if (rhs.isZeroConstant())
848     return lhs;
849 
850   // Special case: 'rhs' is an integer that has the same width as a pointer and
851   // we are using the integer location in a comparison.  Normally this cannot be
852   // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
853   // can generate comparisons that trigger this code.
854   // FIXME: Are all locations guaranteed to have pointer width?
855   if (BinaryOperator::isComparisonOp(op)) {
856     if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
857       const llvm::APSInt *x = &rhsInt->getValue();
858       ASTContext &ctx = Context;
859       if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
860         // Convert the signedness of the integer (if necessary).
861         if (x->isSigned())
862           x = &getBasicValueFactory().getValue(*x, true);
863 
864         return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
865       }
866     }
867     return UnknownVal();
868   }
869 
870   // We are dealing with pointer arithmetic.
871 
872   // Handle pointer arithmetic on constant values.
873   if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
874     if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
875       const llvm::APSInt &leftI = lhsInt->getValue();
876       assert(leftI.isUnsigned());
877       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
878 
879       // Convert the bitwidth of rightI.  This should deal with overflow
880       // since we are dealing with concrete values.
881       rightI = rightI.extOrTrunc(leftI.getBitWidth());
882 
883       // Offset the increment by the pointer size.
884       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
885       rightI *= Multiplicand;
886 
887       // Compute the adjusted pointer.
888       switch (op) {
889         case BO_Add:
890           rightI = leftI + rightI;
891           break;
892         case BO_Sub:
893           rightI = leftI - rightI;
894           break;
895         default:
896           llvm_unreachable("Invalid pointer arithmetic operation");
897       }
898       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
899     }
900   }
901 
902   // Handle cases where 'lhs' is a region.
903   if (const MemRegion *region = lhs.getAsRegion()) {
904     rhs = cast<NonLoc>(convertToArrayIndex(rhs));
905     SVal index = UnknownVal();
906     const MemRegion *superR = 0;
907     QualType elementType;
908 
909     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
910       assert(op == BO_Add || op == BO_Sub);
911       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
912                           getArrayIndexType());
913       superR = elemReg->getSuperRegion();
914       elementType = elemReg->getElementType();
915     }
916     else if (isa<SubRegion>(region)) {
917       superR = region;
918       index = rhs;
919       if (const PointerType *PT = resultTy->getAs<PointerType>()) {
920         elementType = PT->getPointeeType();
921       }
922       else {
923         const ObjCObjectPointerType *OT =
924           resultTy->getAs<ObjCObjectPointerType>();
925         elementType = OT->getPointeeType();
926       }
927     }
928 
929     if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
930       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
931                                                        superR, getContext()));
932     }
933   }
934   return UnknownVal();
935 }
936 
937 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
938                                                    SVal V) {
939   if (V.isUnknownOrUndef())
940     return NULL;
941 
942   if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
943     return &X->getValue();
944 
945   if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
946     return &X->getValue();
947 
948   if (SymbolRef Sym = V.getAsSymbol())
949     return state->getSymVal(Sym);
950 
951   // FIXME: Add support for SymExprs.
952   return NULL;
953 }
954