SimpleSValBuilder.cpp 32 KB

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