SimpleSValBuilder.cpp 34 KB

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