SimpleSValBuilder.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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.
  239. return makeNonLoc(LHS, op, RHS, resultTy);
  240. }
  241. SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
  242. BinaryOperator::Opcode op,
  243. NonLoc lhs, NonLoc rhs,
  244. QualType resultTy) {
  245. // Handle trivial case where left-side and right-side are the same.
  246. if (lhs == rhs)
  247. switch (op) {
  248. default:
  249. break;
  250. case BO_EQ:
  251. case BO_LE:
  252. case BO_GE:
  253. return makeTruthVal(true, resultTy);
  254. case BO_LT:
  255. case BO_GT:
  256. case BO_NE:
  257. return makeTruthVal(false, resultTy);
  258. case BO_Xor:
  259. case BO_Sub:
  260. return makeIntVal(0, resultTy);
  261. case BO_Or:
  262. case BO_And:
  263. return evalCastFromNonLoc(lhs, resultTy);
  264. }
  265. while (1) {
  266. switch (lhs.getSubKind()) {
  267. default:
  268. return makeGenericVal(state, op, lhs, rhs, resultTy);
  269. case nonloc::LocAsIntegerKind: {
  270. Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();
  271. switch (rhs.getSubKind()) {
  272. case nonloc::LocAsIntegerKind:
  273. return evalBinOpLL(state, op, lhsL,
  274. cast<nonloc::LocAsInteger>(rhs).getLoc(),
  275. resultTy);
  276. case nonloc::ConcreteIntKind: {
  277. // Transform the integer into a location and compare.
  278. llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
  279. i.setIsUnsigned(true);
  280. i = i.extOrTrunc(Context.getTypeSize(Context.VoidPtrTy));
  281. return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
  282. }
  283. default:
  284. switch (op) {
  285. case BO_EQ:
  286. return makeTruthVal(false, resultTy);
  287. case BO_NE:
  288. return makeTruthVal(true, resultTy);
  289. default:
  290. // This case also handles pointer arithmetic.
  291. return makeGenericVal(state, op, lhs, rhs, resultTy);
  292. }
  293. }
  294. }
  295. case nonloc::ConcreteIntKind: {
  296. const nonloc::ConcreteInt& lhsInt = cast<nonloc::ConcreteInt>(lhs);
  297. // Is the RHS a symbol we can simplify?
  298. // FIXME: This was mostly copy/pasted from the LHS-is-a-symbol case.
  299. if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
  300. SymbolRef RSym = srhs->getSymbol();
  301. if (RSym->getType(Context)->isIntegerType()) {
  302. if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
  303. // The symbol evaluates to a constant.
  304. const llvm::APSInt *rhs_I;
  305. if (BinaryOperator::isRelationalOp(op))
  306. rhs_I = &BasicVals.Convert(lhsInt.getValue(), *Constant);
  307. else
  308. rhs_I = &BasicVals.Convert(resultTy, *Constant);
  309. rhs = nonloc::ConcreteInt(*rhs_I);
  310. }
  311. }
  312. }
  313. if (isa<nonloc::ConcreteInt>(rhs)) {
  314. return lhsInt.evalBinOp(*this, op, cast<nonloc::ConcreteInt>(rhs));
  315. } else {
  316. const llvm::APSInt& lhsValue = lhsInt.getValue();
  317. // Swap the left and right sides and flip the operator if doing so
  318. // allows us to better reason about the expression (this is a form
  319. // of expression canonicalization).
  320. // While we're at it, catch some special cases for non-commutative ops.
  321. NonLoc tmp = rhs;
  322. rhs = lhs;
  323. lhs = tmp;
  324. switch (op) {
  325. case BO_LT:
  326. case BO_GT:
  327. case BO_LE:
  328. case BO_GE:
  329. op = ReverseComparison(op);
  330. continue;
  331. case BO_EQ:
  332. case BO_NE:
  333. case BO_Add:
  334. case BO_Mul:
  335. case BO_And:
  336. case BO_Xor:
  337. case BO_Or:
  338. continue;
  339. case BO_Shr:
  340. if (lhsValue.isAllOnesValue() && lhsValue.isSigned())
  341. // At this point lhs and rhs have been swapped.
  342. return rhs;
  343. // FALL-THROUGH
  344. case BO_Shl:
  345. if (lhsValue == 0)
  346. // At this point lhs and rhs have been swapped.
  347. return rhs;
  348. return makeGenericVal(state, op, rhs, lhs, resultTy);
  349. default:
  350. return makeGenericVal(state, op, rhs, lhs, resultTy);
  351. }
  352. }
  353. }
  354. case nonloc::SymbolValKind: {
  355. nonloc::SymbolVal *selhs = cast<nonloc::SymbolVal>(&lhs);
  356. // LHS is a symbolic expression.
  357. if (selhs->isExpression()) {
  358. // Only handle LHS of the form "$sym op constant", at least for now.
  359. const SymIntExpr *symIntExpr =
  360. dyn_cast<SymIntExpr>(selhs->getSymbol());
  361. if (!symIntExpr)
  362. return makeGenericVal(state, op, lhs, rhs, resultTy);
  363. // Is this a logical not? (!x is represented as x == 0.)
  364. if (op == BO_EQ && rhs.isZeroConstant()) {
  365. // We know how to negate certain expressions. Simplify them here.
  366. BinaryOperator::Opcode opc = symIntExpr->getOpcode();
  367. switch (opc) {
  368. default:
  369. // We don't know how to negate this operation.
  370. // Just handle it as if it were a normal comparison to 0.
  371. break;
  372. case BO_LAnd:
  373. case BO_LOr:
  374. llvm_unreachable("Logical operators handled by branching logic.");
  375. case BO_Assign:
  376. case BO_MulAssign:
  377. case BO_DivAssign:
  378. case BO_RemAssign:
  379. case BO_AddAssign:
  380. case BO_SubAssign:
  381. case BO_ShlAssign:
  382. case BO_ShrAssign:
  383. case BO_AndAssign:
  384. case BO_XorAssign:
  385. case BO_OrAssign:
  386. case BO_Comma:
  387. llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
  388. case BO_PtrMemD:
  389. case BO_PtrMemI:
  390. llvm_unreachable("Pointer arithmetic not handled here.");
  391. case BO_LT:
  392. case BO_GT:
  393. case BO_LE:
  394. case BO_GE:
  395. case BO_EQ:
  396. case BO_NE:
  397. // Negate the comparison and make a value.
  398. opc = NegateComparison(opc);
  399. assert(symIntExpr->getType(Context) == resultTy);
  400. return makeNonLoc(symIntExpr->getLHS(), opc,
  401. symIntExpr->getRHS(), resultTy);
  402. }
  403. }
  404. // For now, only handle expressions whose RHS is a constant.
  405. const nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs);
  406. if (!rhsInt)
  407. return makeGenericVal(state, op, lhs, rhs, resultTy);
  408. // If both the LHS and the current expression are additive,
  409. // fold their constants.
  410. if (BinaryOperator::isAdditiveOp(op)) {
  411. BinaryOperator::Opcode lop = symIntExpr->getOpcode();
  412. if (BinaryOperator::isAdditiveOp(lop)) {
  413. // resultTy may not be the best type to convert to, but it's
  414. // probably the best choice in expressions with mixed type
  415. // (such as x+1U+2LL). The rules for implicit conversions should
  416. // choose a reasonable type to preserve the expression, and will
  417. // at least match how the value is going to be used.
  418. const llvm::APSInt &first =
  419. BasicVals.Convert(resultTy, symIntExpr->getRHS());
  420. const llvm::APSInt &second =
  421. BasicVals.Convert(resultTy, rhsInt->getValue());
  422. const llvm::APSInt *newRHS;
  423. if (lop == op)
  424. newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
  425. else
  426. newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
  427. return MakeSymIntVal(symIntExpr->getLHS(), lop, *newRHS, resultTy);
  428. }
  429. }
  430. // Otherwise, make a SymbolVal out of the expression.
  431. return MakeSymIntVal(symIntExpr, op, rhsInt->getValue(), resultTy);
  432. // LHS is a simple symbol (not a symbolic expression).
  433. } else {
  434. nonloc::SymbolVal *slhs = cast<nonloc::SymbolVal>(&lhs);
  435. SymbolRef Sym = slhs->getSymbol();
  436. QualType lhsType = Sym->getType(Context);
  437. // The conversion type is usually the result type, but not in the case
  438. // of relational expressions.
  439. QualType conversionType = resultTy;
  440. if (BinaryOperator::isRelationalOp(op))
  441. conversionType = lhsType;
  442. // Does the symbol simplify to a constant? If so, "fold" the constant
  443. // by setting 'lhs' to a ConcreteInt and try again.
  444. if (lhsType->isIntegerType())
  445. if (const llvm::APSInt *Constant = state->getSymVal(Sym)) {
  446. // The symbol evaluates to a constant. If necessary, promote the
  447. // folded constant (LHS) to the result type.
  448. const llvm::APSInt &lhs_I = BasicVals.Convert(conversionType,
  449. *Constant);
  450. lhs = nonloc::ConcreteInt(lhs_I);
  451. // Also promote the RHS (if necessary).
  452. // For shifts, it is not necessary to promote the RHS.
  453. if (BinaryOperator::isShiftOp(op))
  454. continue;
  455. // Other operators: do an implicit conversion. This shouldn't be
  456. // necessary once we support truncation/extension of symbolic values.
  457. if (nonloc::ConcreteInt *rhs_I = dyn_cast<nonloc::ConcreteInt>(&rhs)){
  458. rhs = nonloc::ConcreteInt(BasicVals.Convert(conversionType,
  459. rhs_I->getValue()));
  460. }
  461. continue;
  462. }
  463. // Is the RHS a symbol we can simplify?
  464. if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
  465. SymbolRef RSym = srhs->getSymbol();
  466. if (RSym->getType(Context)->isIntegerType()) {
  467. if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
  468. // The symbol evaluates to a constant.
  469. const llvm::APSInt &rhs_I = BasicVals.Convert(conversionType,
  470. *Constant);
  471. rhs = nonloc::ConcreteInt(rhs_I);
  472. }
  473. }
  474. }
  475. if (isa<nonloc::ConcreteInt>(rhs)) {
  476. return MakeSymIntVal(slhs->getSymbol(), op,
  477. cast<nonloc::ConcreteInt>(rhs).getValue(),
  478. resultTy);
  479. }
  480. return makeGenericVal(state, op, lhs, rhs, resultTy);
  481. }
  482. }
  483. }
  484. }
  485. }
  486. // FIXME: all this logic will change if/when we have MemRegion::getLocation().
  487. SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
  488. BinaryOperator::Opcode op,
  489. Loc lhs, Loc rhs,
  490. QualType resultTy) {
  491. // Only comparisons and subtractions are valid operations on two pointers.
  492. // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
  493. // However, if a pointer is casted to an integer, evalBinOpNN may end up
  494. // calling this function with another operation (PR7527). We don't attempt to
  495. // model this for now, but it could be useful, particularly when the
  496. // "location" is actually an integer value that's been passed through a void*.
  497. if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
  498. return UnknownVal();
  499. // Special cases for when both sides are identical.
  500. if (lhs == rhs) {
  501. switch (op) {
  502. default:
  503. llvm_unreachable("Unimplemented operation for two identical values");
  504. case BO_Sub:
  505. return makeZeroVal(resultTy);
  506. case BO_EQ:
  507. case BO_LE:
  508. case BO_GE:
  509. return makeTruthVal(true, resultTy);
  510. case BO_NE:
  511. case BO_LT:
  512. case BO_GT:
  513. return makeTruthVal(false, resultTy);
  514. }
  515. }
  516. switch (lhs.getSubKind()) {
  517. default:
  518. llvm_unreachable("Ordering not implemented for this Loc.");
  519. case loc::GotoLabelKind:
  520. // The only thing we know about labels is that they're non-null.
  521. if (rhs.isZeroConstant()) {
  522. switch (op) {
  523. default:
  524. break;
  525. case BO_Sub:
  526. return evalCastFromLoc(lhs, resultTy);
  527. case BO_EQ:
  528. case BO_LE:
  529. case BO_LT:
  530. return makeTruthVal(false, resultTy);
  531. case BO_NE:
  532. case BO_GT:
  533. case BO_GE:
  534. return makeTruthVal(true, resultTy);
  535. }
  536. }
  537. // There may be two labels for the same location, and a function region may
  538. // have the same address as a label at the start of the function (depending
  539. // on the ABI).
  540. // FIXME: we can probably do a comparison against other MemRegions, though.
  541. // FIXME: is there a way to tell if two labels refer to the same location?
  542. return UnknownVal();
  543. case loc::ConcreteIntKind: {
  544. // If one of the operands is a symbol and the other is a constant,
  545. // build an expression for use by the constraint manager.
  546. if (SymbolRef rSym = rhs.getAsLocSymbol()) {
  547. // We can only build expressions with symbols on the left,
  548. // so we need a reversible operator.
  549. if (!BinaryOperator::isComparisonOp(op))
  550. return UnknownVal();
  551. const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
  552. return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
  553. }
  554. // If both operands are constants, just perform the operation.
  555. if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
  556. SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
  557. *rInt);
  558. if (Loc *Result = dyn_cast<Loc>(&ResultVal))
  559. return evalCastFromLoc(*Result, resultTy);
  560. else
  561. return UnknownVal();
  562. }
  563. // Special case comparisons against NULL.
  564. // This must come after the test if the RHS is a symbol, which is used to
  565. // build constraints. The address of any non-symbolic region is guaranteed
  566. // to be non-NULL, as is any label.
  567. assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
  568. if (lhs.isZeroConstant()) {
  569. switch (op) {
  570. default:
  571. break;
  572. case BO_EQ:
  573. case BO_GT:
  574. case BO_GE:
  575. return makeTruthVal(false, resultTy);
  576. case BO_NE:
  577. case BO_LT:
  578. case BO_LE:
  579. return makeTruthVal(true, resultTy);
  580. }
  581. }
  582. // Comparing an arbitrary integer to a region or label address is
  583. // completely unknowable.
  584. return UnknownVal();
  585. }
  586. case loc::MemRegionKind: {
  587. if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
  588. // If one of the operands is a symbol and the other is a constant,
  589. // build an expression for use by the constraint manager.
  590. if (SymbolRef lSym = lhs.getAsLocSymbol())
  591. return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
  592. // Special case comparisons to NULL.
  593. // This must come after the test if the LHS is a symbol, which is used to
  594. // build constraints. The address of any non-symbolic region is guaranteed
  595. // to be non-NULL.
  596. if (rInt->isZeroConstant()) {
  597. switch (op) {
  598. default:
  599. break;
  600. case BO_Sub:
  601. return evalCastFromLoc(lhs, resultTy);
  602. case BO_EQ:
  603. case BO_LT:
  604. case BO_LE:
  605. return makeTruthVal(false, resultTy);
  606. case BO_NE:
  607. case BO_GT:
  608. case BO_GE:
  609. return makeTruthVal(true, resultTy);
  610. }
  611. }
  612. // Comparing a region to an arbitrary integer is completely unknowable.
  613. return UnknownVal();
  614. }
  615. // Get both values as regions, if possible.
  616. const MemRegion *LeftMR = lhs.getAsRegion();
  617. assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
  618. const MemRegion *RightMR = rhs.getAsRegion();
  619. if (!RightMR)
  620. // The RHS is probably a label, which in theory could address a region.
  621. // FIXME: we can probably make a more useful statement about non-code
  622. // regions, though.
  623. return UnknownVal();
  624. // If both values wrap regions, see if they're from different base regions.
  625. const MemRegion *LeftBase = LeftMR->getBaseRegion();
  626. const MemRegion *RightBase = RightMR->getBaseRegion();
  627. if (LeftBase != RightBase &&
  628. !isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) {
  629. switch (op) {
  630. default:
  631. return UnknownVal();
  632. case BO_EQ:
  633. return makeTruthVal(false, resultTy);
  634. case BO_NE:
  635. return makeTruthVal(true, resultTy);
  636. }
  637. }
  638. // The two regions are from the same base region. See if they're both a
  639. // type of region we know how to compare.
  640. const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
  641. const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
  642. // Heuristic: assume that no symbolic region (whose memory space is
  643. // unknown) is on the stack.
  644. // FIXME: we should be able to be more precise once we can do better
  645. // aliasing constraints for symbolic regions, but this is a reasonable,
  646. // albeit unsound, assumption that holds most of the time.
  647. if (isa<StackSpaceRegion>(LeftMS) ^ isa<StackSpaceRegion>(RightMS)) {
  648. switch (op) {
  649. default:
  650. break;
  651. case BO_EQ:
  652. return makeTruthVal(false, resultTy);
  653. case BO_NE:
  654. return makeTruthVal(true, resultTy);
  655. }
  656. }
  657. // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
  658. // ElementRegion path and the FieldRegion path below should be unified.
  659. if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
  660. // First see if the right region is also an ElementRegion.
  661. const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
  662. if (!RightER)
  663. return UnknownVal();
  664. // Next, see if the two ERs have the same super-region and matching types.
  665. // FIXME: This should do something useful even if the types don't match,
  666. // though if both indexes are constant the RegionRawOffset path will
  667. // give the correct answer.
  668. if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
  669. LeftER->getElementType() == RightER->getElementType()) {
  670. // Get the left index and cast it to the correct type.
  671. // If the index is unknown or undefined, bail out here.
  672. SVal LeftIndexVal = LeftER->getIndex();
  673. NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
  674. if (!LeftIndex)
  675. return UnknownVal();
  676. LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
  677. LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
  678. if (!LeftIndex)
  679. return UnknownVal();
  680. // Do the same for the right index.
  681. SVal RightIndexVal = RightER->getIndex();
  682. NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
  683. if (!RightIndex)
  684. return UnknownVal();
  685. RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
  686. RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
  687. if (!RightIndex)
  688. return UnknownVal();
  689. // Actually perform the operation.
  690. // evalBinOpNN expects the two indexes to already be the right type.
  691. return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
  692. }
  693. // If the element indexes aren't comparable, see if the raw offsets are.
  694. RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
  695. RegionRawOffset RightOffset = RightER->getAsArrayOffset();
  696. if (LeftOffset.getRegion() != NULL &&
  697. LeftOffset.getRegion() == RightOffset.getRegion()) {
  698. CharUnits left = LeftOffset.getOffset();
  699. CharUnits right = RightOffset.getOffset();
  700. switch (op) {
  701. default:
  702. return UnknownVal();
  703. case BO_LT:
  704. return makeTruthVal(left < right, resultTy);
  705. case BO_GT:
  706. return makeTruthVal(left > right, resultTy);
  707. case BO_LE:
  708. return makeTruthVal(left <= right, resultTy);
  709. case BO_GE:
  710. return makeTruthVal(left >= right, resultTy);
  711. case BO_EQ:
  712. return makeTruthVal(left == right, resultTy);
  713. case BO_NE:
  714. return makeTruthVal(left != right, resultTy);
  715. }
  716. }
  717. // If we get here, we have no way of comparing the ElementRegions.
  718. return UnknownVal();
  719. }
  720. // See if both regions are fields of the same structure.
  721. // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
  722. if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
  723. // Only comparisons are meaningful here!
  724. if (!BinaryOperator::isComparisonOp(op))
  725. return UnknownVal();
  726. // First see if the right region is also a FieldRegion.
  727. const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
  728. if (!RightFR)
  729. return UnknownVal();
  730. // Next, see if the two FRs have the same super-region.
  731. // FIXME: This doesn't handle casts yet, and simply stripping the casts
  732. // doesn't help.
  733. if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
  734. return UnknownVal();
  735. const FieldDecl *LeftFD = LeftFR->getDecl();
  736. const FieldDecl *RightFD = RightFR->getDecl();
  737. const RecordDecl *RD = LeftFD->getParent();
  738. // Make sure the two FRs are from the same kind of record. Just in case!
  739. // FIXME: This is probably where inheritance would be a problem.
  740. if (RD != RightFD->getParent())
  741. return UnknownVal();
  742. // We know for sure that the two fields are not the same, since that
  743. // would have given us the same SVal.
  744. if (op == BO_EQ)
  745. return makeTruthVal(false, resultTy);
  746. if (op == BO_NE)
  747. return makeTruthVal(true, resultTy);
  748. // Iterate through the fields and see which one comes first.
  749. // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
  750. // members and the units in which bit-fields reside have addresses that
  751. // increase in the order in which they are declared."
  752. bool leftFirst = (op == BO_LT || op == BO_LE);
  753. for (RecordDecl::field_iterator I = RD->field_begin(),
  754. E = RD->field_end(); I!=E; ++I) {
  755. if (&*I == LeftFD)
  756. return makeTruthVal(leftFirst, resultTy);
  757. if (&*I == RightFD)
  758. return makeTruthVal(!leftFirst, resultTy);
  759. }
  760. llvm_unreachable("Fields not found in parent record's definition");
  761. }
  762. // If we get here, we have no way of comparing the regions.
  763. return UnknownVal();
  764. }
  765. }
  766. }
  767. SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
  768. BinaryOperator::Opcode op,
  769. Loc lhs, NonLoc rhs, QualType resultTy) {
  770. // Special case: rhs is a zero constant.
  771. if (rhs.isZeroConstant())
  772. return lhs;
  773. // Special case: 'rhs' is an integer that has the same width as a pointer and
  774. // we are using the integer location in a comparison. Normally this cannot be
  775. // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
  776. // can generate comparisons that trigger this code.
  777. // FIXME: Are all locations guaranteed to have pointer width?
  778. if (BinaryOperator::isComparisonOp(op)) {
  779. if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
  780. const llvm::APSInt *x = &rhsInt->getValue();
  781. ASTContext &ctx = Context;
  782. if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
  783. // Convert the signedness of the integer (if necessary).
  784. if (x->isSigned())
  785. x = &getBasicValueFactory().getValue(*x, true);
  786. return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
  787. }
  788. }
  789. }
  790. // We are dealing with pointer arithmetic.
  791. // Handle pointer arithmetic on constant values.
  792. if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
  793. if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
  794. const llvm::APSInt &leftI = lhsInt->getValue();
  795. assert(leftI.isUnsigned());
  796. llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
  797. // Convert the bitwidth of rightI. This should deal with overflow
  798. // since we are dealing with concrete values.
  799. rightI = rightI.extOrTrunc(leftI.getBitWidth());
  800. // Offset the increment by the pointer size.
  801. llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
  802. rightI *= Multiplicand;
  803. // Compute the adjusted pointer.
  804. switch (op) {
  805. case BO_Add:
  806. rightI = leftI + rightI;
  807. break;
  808. case BO_Sub:
  809. rightI = leftI - rightI;
  810. break;
  811. default:
  812. llvm_unreachable("Invalid pointer arithmetic operation");
  813. }
  814. return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
  815. }
  816. }
  817. // Handle cases where 'lhs' is a region.
  818. if (const MemRegion *region = lhs.getAsRegion()) {
  819. rhs = cast<NonLoc>(convertToArrayIndex(rhs));
  820. SVal index = UnknownVal();
  821. const MemRegion *superR = 0;
  822. QualType elementType;
  823. if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
  824. assert(op == BO_Add || op == BO_Sub);
  825. index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
  826. getArrayIndexType());
  827. superR = elemReg->getSuperRegion();
  828. elementType = elemReg->getElementType();
  829. }
  830. else if (isa<SubRegion>(region)) {
  831. superR = region;
  832. index = rhs;
  833. if (const PointerType *PT = resultTy->getAs<PointerType>()) {
  834. elementType = PT->getPointeeType();
  835. }
  836. else {
  837. const ObjCObjectPointerType *OT =
  838. resultTy->getAs<ObjCObjectPointerType>();
  839. elementType = OT->getPointeeType();
  840. }
  841. }
  842. if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
  843. return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
  844. superR, getContext()));
  845. }
  846. }
  847. return UnknownVal();
  848. }
  849. const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
  850. SVal V) {
  851. if (V.isUnknownOrUndef())
  852. return NULL;
  853. if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
  854. return &X->getValue();
  855. if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
  856. return &X->getValue();
  857. if (SymbolRef Sym = V.getAsSymbol())
  858. return state->getSymVal(Sym);
  859. // FIXME: Add support for SymExprs.
  860. return NULL;
  861. }