SimpleSValBuilder.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. // LHS is a simple symbol (not a symbolic expression).
  463. QualType lhsType = Sym->getType(Context);
  464. // Does the symbol simplify to a constant? If so, "fold" the constant
  465. // by setting 'lhs' to a ConcreteInt and try again.
  466. if (const llvm::APSInt *Constant = state->getSymVal(Sym)) {
  467. lhs = nonloc::ConcreteInt(*Constant);
  468. continue;
  469. }
  470. // Is the RHS a constant?
  471. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
  472. return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
  473. }
  474. // Give up -- this is not a symbolic expression we can handle.
  475. return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
  476. }
  477. }
  478. }
  479. }
  480. // FIXME: all this logic will change if/when we have MemRegion::getLocation().
  481. SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
  482. BinaryOperator::Opcode op,
  483. Loc lhs, Loc rhs,
  484. QualType resultTy) {
  485. // Only comparisons and subtractions are valid operations on two pointers.
  486. // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
  487. // However, if a pointer is casted to an integer, evalBinOpNN may end up
  488. // calling this function with another operation (PR7527). We don't attempt to
  489. // model this for now, but it could be useful, particularly when the
  490. // "location" is actually an integer value that's been passed through a void*.
  491. if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
  492. return UnknownVal();
  493. // Special cases for when both sides are identical.
  494. if (lhs == rhs) {
  495. switch (op) {
  496. default:
  497. llvm_unreachable("Unimplemented operation for two identical values");
  498. case BO_Sub:
  499. return makeZeroVal(resultTy);
  500. case BO_EQ:
  501. case BO_LE:
  502. case BO_GE:
  503. return makeTruthVal(true, resultTy);
  504. case BO_NE:
  505. case BO_LT:
  506. case BO_GT:
  507. return makeTruthVal(false, resultTy);
  508. }
  509. }
  510. switch (lhs.getSubKind()) {
  511. default:
  512. llvm_unreachable("Ordering not implemented for this Loc.");
  513. case loc::GotoLabelKind:
  514. // The only thing we know about labels is that they're non-null.
  515. if (rhs.isZeroConstant()) {
  516. switch (op) {
  517. default:
  518. break;
  519. case BO_Sub:
  520. return evalCastFromLoc(lhs, resultTy);
  521. case BO_EQ:
  522. case BO_LE:
  523. case BO_LT:
  524. return makeTruthVal(false, resultTy);
  525. case BO_NE:
  526. case BO_GT:
  527. case BO_GE:
  528. return makeTruthVal(true, resultTy);
  529. }
  530. }
  531. // There may be two labels for the same location, and a function region may
  532. // have the same address as a label at the start of the function (depending
  533. // on the ABI).
  534. // FIXME: we can probably do a comparison against other MemRegions, though.
  535. // FIXME: is there a way to tell if two labels refer to the same location?
  536. return UnknownVal();
  537. case loc::ConcreteIntKind: {
  538. // If one of the operands is a symbol and the other is a constant,
  539. // build an expression for use by the constraint manager.
  540. if (SymbolRef rSym = rhs.getAsLocSymbol()) {
  541. // We can only build expressions with symbols on the left,
  542. // so we need a reversible operator.
  543. if (!BinaryOperator::isComparisonOp(op))
  544. return UnknownVal();
  545. const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
  546. return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
  547. }
  548. // If both operands are constants, just perform the operation.
  549. if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
  550. SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
  551. *rInt);
  552. if (Loc *Result = dyn_cast<Loc>(&ResultVal))
  553. return evalCastFromLoc(*Result, resultTy);
  554. else
  555. return UnknownVal();
  556. }
  557. // Special case comparisons against NULL.
  558. // This must come after the test if the RHS is a symbol, which is used to
  559. // build constraints. The address of any non-symbolic region is guaranteed
  560. // to be non-NULL, as is any label.
  561. assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
  562. if (lhs.isZeroConstant()) {
  563. switch (op) {
  564. default:
  565. break;
  566. case BO_EQ:
  567. case BO_GT:
  568. case BO_GE:
  569. return makeTruthVal(false, resultTy);
  570. case BO_NE:
  571. case BO_LT:
  572. case BO_LE:
  573. return makeTruthVal(true, resultTy);
  574. }
  575. }
  576. // Comparing an arbitrary integer to a region or label address is
  577. // completely unknowable.
  578. return UnknownVal();
  579. }
  580. case loc::MemRegionKind: {
  581. if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
  582. // If one of the operands is a symbol and the other is a constant,
  583. // build an expression for use by the constraint manager.
  584. if (SymbolRef lSym = lhs.getAsLocSymbol())
  585. return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
  586. // Special case comparisons to NULL.
  587. // This must come after the test if the LHS is a symbol, which is used to
  588. // build constraints. The address of any non-symbolic region is guaranteed
  589. // to be non-NULL.
  590. if (rInt->isZeroConstant()) {
  591. switch (op) {
  592. default:
  593. break;
  594. case BO_Sub:
  595. return evalCastFromLoc(lhs, resultTy);
  596. case BO_EQ:
  597. case BO_LT:
  598. case BO_LE:
  599. return makeTruthVal(false, resultTy);
  600. case BO_NE:
  601. case BO_GT:
  602. case BO_GE:
  603. return makeTruthVal(true, resultTy);
  604. }
  605. }
  606. // Comparing a region to an arbitrary integer is completely unknowable.
  607. return UnknownVal();
  608. }
  609. // Get both values as regions, if possible.
  610. const MemRegion *LeftMR = lhs.getAsRegion();
  611. assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
  612. const MemRegion *RightMR = rhs.getAsRegion();
  613. if (!RightMR)
  614. // The RHS is probably a label, which in theory could address a region.
  615. // FIXME: we can probably make a more useful statement about non-code
  616. // regions, though.
  617. return UnknownVal();
  618. // If both values wrap regions, see if they're from different base regions.
  619. const MemRegion *LeftBase = LeftMR->getBaseRegion();
  620. const MemRegion *RightBase = RightMR->getBaseRegion();
  621. if (LeftBase != RightBase &&
  622. !isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) {
  623. switch (op) {
  624. default:
  625. return UnknownVal();
  626. case BO_EQ:
  627. return makeTruthVal(false, resultTy);
  628. case BO_NE:
  629. return makeTruthVal(true, resultTy);
  630. }
  631. }
  632. // The two regions are from the same base region. See if they're both a
  633. // type of region we know how to compare.
  634. const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
  635. const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
  636. // Heuristic: assume that no symbolic region (whose memory space is
  637. // unknown) is on the stack.
  638. // FIXME: we should be able to be more precise once we can do better
  639. // aliasing constraints for symbolic regions, but this is a reasonable,
  640. // albeit unsound, assumption that holds most of the time.
  641. if (isa<StackSpaceRegion>(LeftMS) ^ isa<StackSpaceRegion>(RightMS)) {
  642. switch (op) {
  643. default:
  644. break;
  645. case BO_EQ:
  646. return makeTruthVal(false, resultTy);
  647. case BO_NE:
  648. return makeTruthVal(true, resultTy);
  649. }
  650. }
  651. // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
  652. // ElementRegion path and the FieldRegion path below should be unified.
  653. if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
  654. // First see if the right region is also an ElementRegion.
  655. const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
  656. if (!RightER)
  657. return UnknownVal();
  658. // Next, see if the two ERs have the same super-region and matching types.
  659. // FIXME: This should do something useful even if the types don't match,
  660. // though if both indexes are constant the RegionRawOffset path will
  661. // give the correct answer.
  662. if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
  663. LeftER->getElementType() == RightER->getElementType()) {
  664. // Get the left index and cast it to the correct type.
  665. // If the index is unknown or undefined, bail out here.
  666. SVal LeftIndexVal = LeftER->getIndex();
  667. NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
  668. if (!LeftIndex)
  669. return UnknownVal();
  670. LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
  671. LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
  672. if (!LeftIndex)
  673. return UnknownVal();
  674. // Do the same for the right index.
  675. SVal RightIndexVal = RightER->getIndex();
  676. NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
  677. if (!RightIndex)
  678. return UnknownVal();
  679. RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
  680. RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
  681. if (!RightIndex)
  682. return UnknownVal();
  683. // Actually perform the operation.
  684. // evalBinOpNN expects the two indexes to already be the right type.
  685. return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
  686. }
  687. // If the element indexes aren't comparable, see if the raw offsets are.
  688. RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
  689. RegionRawOffset RightOffset = RightER->getAsArrayOffset();
  690. if (LeftOffset.getRegion() != NULL &&
  691. LeftOffset.getRegion() == RightOffset.getRegion()) {
  692. CharUnits left = LeftOffset.getOffset();
  693. CharUnits right = RightOffset.getOffset();
  694. switch (op) {
  695. default:
  696. return UnknownVal();
  697. case BO_LT:
  698. return makeTruthVal(left < right, resultTy);
  699. case BO_GT:
  700. return makeTruthVal(left > right, resultTy);
  701. case BO_LE:
  702. return makeTruthVal(left <= right, resultTy);
  703. case BO_GE:
  704. return makeTruthVal(left >= right, resultTy);
  705. case BO_EQ:
  706. return makeTruthVal(left == right, resultTy);
  707. case BO_NE:
  708. return makeTruthVal(left != right, resultTy);
  709. }
  710. }
  711. // If we get here, we have no way of comparing the ElementRegions.
  712. return UnknownVal();
  713. }
  714. // See if both regions are fields of the same structure.
  715. // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
  716. if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
  717. // Only comparisons are meaningful here!
  718. if (!BinaryOperator::isComparisonOp(op))
  719. return UnknownVal();
  720. // First see if the right region is also a FieldRegion.
  721. const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
  722. if (!RightFR)
  723. return UnknownVal();
  724. // Next, see if the two FRs have the same super-region.
  725. // FIXME: This doesn't handle casts yet, and simply stripping the casts
  726. // doesn't help.
  727. if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
  728. return UnknownVal();
  729. const FieldDecl *LeftFD = LeftFR->getDecl();
  730. const FieldDecl *RightFD = RightFR->getDecl();
  731. const RecordDecl *RD = LeftFD->getParent();
  732. // Make sure the two FRs are from the same kind of record. Just in case!
  733. // FIXME: This is probably where inheritance would be a problem.
  734. if (RD != RightFD->getParent())
  735. return UnknownVal();
  736. // We know for sure that the two fields are not the same, since that
  737. // would have given us the same SVal.
  738. if (op == BO_EQ)
  739. return makeTruthVal(false, resultTy);
  740. if (op == BO_NE)
  741. return makeTruthVal(true, resultTy);
  742. // Iterate through the fields and see which one comes first.
  743. // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
  744. // members and the units in which bit-fields reside have addresses that
  745. // increase in the order in which they are declared."
  746. bool leftFirst = (op == BO_LT || op == BO_LE);
  747. for (RecordDecl::field_iterator I = RD->field_begin(),
  748. E = RD->field_end(); I!=E; ++I) {
  749. if (&*I == LeftFD)
  750. return makeTruthVal(leftFirst, resultTy);
  751. if (&*I == RightFD)
  752. return makeTruthVal(!leftFirst, resultTy);
  753. }
  754. llvm_unreachable("Fields not found in parent record's definition");
  755. }
  756. // If we get here, we have no way of comparing the regions.
  757. return UnknownVal();
  758. }
  759. }
  760. }
  761. SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
  762. BinaryOperator::Opcode op,
  763. Loc lhs, NonLoc rhs, QualType resultTy) {
  764. // Special case: rhs is a zero constant.
  765. if (rhs.isZeroConstant())
  766. return lhs;
  767. // Special case: 'rhs' is an integer that has the same width as a pointer and
  768. // we are using the integer location in a comparison. Normally this cannot be
  769. // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
  770. // can generate comparisons that trigger this code.
  771. // FIXME: Are all locations guaranteed to have pointer width?
  772. if (BinaryOperator::isComparisonOp(op)) {
  773. if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
  774. const llvm::APSInt *x = &rhsInt->getValue();
  775. ASTContext &ctx = Context;
  776. if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
  777. // Convert the signedness of the integer (if necessary).
  778. if (x->isSigned())
  779. x = &getBasicValueFactory().getValue(*x, true);
  780. return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
  781. }
  782. }
  783. }
  784. // We are dealing with pointer arithmetic.
  785. // Handle pointer arithmetic on constant values.
  786. if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
  787. if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
  788. const llvm::APSInt &leftI = lhsInt->getValue();
  789. assert(leftI.isUnsigned());
  790. llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
  791. // Convert the bitwidth of rightI. This should deal with overflow
  792. // since we are dealing with concrete values.
  793. rightI = rightI.extOrTrunc(leftI.getBitWidth());
  794. // Offset the increment by the pointer size.
  795. llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
  796. rightI *= Multiplicand;
  797. // Compute the adjusted pointer.
  798. switch (op) {
  799. case BO_Add:
  800. rightI = leftI + rightI;
  801. break;
  802. case BO_Sub:
  803. rightI = leftI - rightI;
  804. break;
  805. default:
  806. llvm_unreachable("Invalid pointer arithmetic operation");
  807. }
  808. return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
  809. }
  810. }
  811. // Handle cases where 'lhs' is a region.
  812. if (const MemRegion *region = lhs.getAsRegion()) {
  813. rhs = cast<NonLoc>(convertToArrayIndex(rhs));
  814. SVal index = UnknownVal();
  815. const MemRegion *superR = 0;
  816. QualType elementType;
  817. if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
  818. assert(op == BO_Add || op == BO_Sub);
  819. index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
  820. getArrayIndexType());
  821. superR = elemReg->getSuperRegion();
  822. elementType = elemReg->getElementType();
  823. }
  824. else if (isa<SubRegion>(region)) {
  825. superR = region;
  826. index = rhs;
  827. if (const PointerType *PT = resultTy->getAs<PointerType>()) {
  828. elementType = PT->getPointeeType();
  829. }
  830. else {
  831. const ObjCObjectPointerType *OT =
  832. resultTy->getAs<ObjCObjectPointerType>();
  833. elementType = OT->getPointeeType();
  834. }
  835. }
  836. if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
  837. return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
  838. superR, getContext()));
  839. }
  840. }
  841. return UnknownVal();
  842. }
  843. const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
  844. SVal V) {
  845. if (V.isUnknownOrUndef())
  846. return NULL;
  847. if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
  848. return &X->getValue();
  849. if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
  850. return &X->getValue();
  851. if (SymbolRef Sym = V.getAsSymbol())
  852. return state->getSymVal(Sym);
  853. // FIXME: Add support for SymExprs.
  854. return NULL;
  855. }