SimpleSValBuilder.cpp 34 KB

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