SimpleSValBuilder.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
  17. using namespace clang;
  18. using namespace ento;
  19. namespace {
  20. class SimpleSValBuilder : public SValBuilder {
  21. // With one `simplifySValOnce` call, a compound symbols might collapse to
  22. // simpler symbol tree that is still possible to further simplify. Thus, we
  23. // do the simplification on a new symbol tree until we reach the simplest
  24. // form, i.e. the fixpoint.
  25. // Consider the following symbol `(b * b) * b * b` which has this tree:
  26. // *
  27. // / \
  28. // * b
  29. // / \
  30. // / b
  31. // (b * b)
  32. // Now, if the `b * b == 1` new constraint is added then during the first
  33. // iteration we have the following transformations:
  34. // * *
  35. // / \ / \
  36. // * b --> b b
  37. // / \
  38. // / b
  39. // 1
  40. // We need another iteration to reach the final result `1`.
  41. SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
  42. // Recursively descends into symbolic expressions and replaces symbols
  43. // with their known values (in the sense of the getKnownValue() method).
  44. // We traverse the symbol tree and query the constraint values for the
  45. // sub-trees and if a value is a constant we do the constant folding.
  46. SVal simplifySValOnce(ProgramStateRef State, SVal V);
  47. public:
  48. SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
  49. ProgramStateManager &stateMgr)
  50. : SValBuilder(alloc, context, stateMgr) {}
  51. ~SimpleSValBuilder() override {}
  52. SVal evalMinus(NonLoc val) override;
  53. SVal evalComplement(NonLoc val) override;
  54. SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
  55. NonLoc lhs, NonLoc rhs, QualType resultTy) override;
  56. SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
  57. Loc lhs, Loc rhs, QualType resultTy) override;
  58. SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
  59. Loc lhs, NonLoc rhs, QualType resultTy) override;
  60. /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
  61. /// (integer) value, that value is returned. Otherwise, returns NULL.
  62. const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
  63. SVal simplifySVal(ProgramStateRef State, SVal V) override;
  64. SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
  65. const llvm::APSInt &RHS, QualType resultTy);
  66. };
  67. } // end anonymous namespace
  68. SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
  69. ASTContext &context,
  70. ProgramStateManager &stateMgr) {
  71. return new SimpleSValBuilder(alloc, context, stateMgr);
  72. }
  73. //===----------------------------------------------------------------------===//
  74. // Transfer function for unary operators.
  75. //===----------------------------------------------------------------------===//
  76. SVal SimpleSValBuilder::evalMinus(NonLoc val) {
  77. switch (val.getSubKind()) {
  78. case nonloc::ConcreteIntKind:
  79. return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
  80. default:
  81. return UnknownVal();
  82. }
  83. }
  84. SVal SimpleSValBuilder::evalComplement(NonLoc X) {
  85. switch (X.getSubKind()) {
  86. case nonloc::ConcreteIntKind:
  87. return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
  88. default:
  89. return UnknownVal();
  90. }
  91. }
  92. //===----------------------------------------------------------------------===//
  93. // Transfer function for binary operators.
  94. //===----------------------------------------------------------------------===//
  95. SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
  96. BinaryOperator::Opcode op,
  97. const llvm::APSInt &RHS,
  98. QualType resultTy) {
  99. bool isIdempotent = false;
  100. // Check for a few special cases with known reductions first.
  101. switch (op) {
  102. default:
  103. // We can't reduce this case; just treat it normally.
  104. break;
  105. case BO_Mul:
  106. // a*0 and a*1
  107. if (RHS == 0)
  108. return makeIntVal(0, resultTy);
  109. else if (RHS == 1)
  110. isIdempotent = true;
  111. break;
  112. case BO_Div:
  113. // a/0 and a/1
  114. if (RHS == 0)
  115. // This is also handled elsewhere.
  116. return UndefinedVal();
  117. else if (RHS == 1)
  118. isIdempotent = true;
  119. break;
  120. case BO_Rem:
  121. // a%0 and a%1
  122. if (RHS == 0)
  123. // This is also handled elsewhere.
  124. return UndefinedVal();
  125. else if (RHS == 1)
  126. return makeIntVal(0, resultTy);
  127. break;
  128. case BO_Add:
  129. case BO_Sub:
  130. case BO_Shl:
  131. case BO_Shr:
  132. case BO_Xor:
  133. // a+0, a-0, a<<0, a>>0, a^0
  134. if (RHS == 0)
  135. isIdempotent = true;
  136. break;
  137. case BO_And:
  138. // a&0 and a&(~0)
  139. if (RHS == 0)
  140. return makeIntVal(0, resultTy);
  141. else if (RHS.isAllOnes())
  142. isIdempotent = true;
  143. break;
  144. case BO_Or:
  145. // a|0 and a|(~0)
  146. if (RHS == 0)
  147. isIdempotent = true;
  148. else if (RHS.isAllOnes()) {
  149. const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
  150. return nonloc::ConcreteInt(Result);
  151. }
  152. break;
  153. }
  154. // Idempotent ops (like a*1) can still change the type of an expression.
  155. // Wrap the LHS up in a NonLoc again and let evalCast do the
  156. // dirty work.
  157. if (isIdempotent)
  158. return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
  159. // If we reach this point, the expression cannot be simplified.
  160. // Make a SymbolVal for the entire expression, after converting the RHS.
  161. const llvm::APSInt *ConvertedRHS = &RHS;
  162. if (BinaryOperator::isComparisonOp(op)) {
  163. // We're looking for a type big enough to compare the symbolic value
  164. // with the given constant.
  165. // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
  166. ASTContext &Ctx = getContext();
  167. QualType SymbolType = LHS->getType();
  168. uint64_t ValWidth = RHS.getBitWidth();
  169. uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
  170. if (ValWidth < TypeWidth) {
  171. // If the value is too small, extend it.
  172. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  173. } else if (ValWidth == TypeWidth) {
  174. // If the value is signed but the symbol is unsigned, do the comparison
  175. // in unsigned space. [C99 6.3.1.8]
  176. // (For the opposite case, the value is already unsigned.)
  177. if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
  178. ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
  179. }
  180. } else
  181. ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
  182. return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
  183. }
  184. // See if Sym is known to be a relation Rel with Bound.
  185. static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
  186. llvm::APSInt Bound, ProgramStateRef State) {
  187. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  188. SVal Result =
  189. SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
  190. nonloc::ConcreteInt(Bound), SVB.getConditionType());
  191. if (auto DV = Result.getAs<DefinedSVal>()) {
  192. return !State->assume(*DV, false);
  193. }
  194. return false;
  195. }
  196. // See if Sym is known to be within [min/4, max/4], where min and max
  197. // are the bounds of the symbol's integral type. With such symbols,
  198. // some manipulations can be performed without the risk of overflow.
  199. // assume() doesn't cause infinite recursion because we should be dealing
  200. // with simpler symbols on every recursive call.
  201. static bool isWithinConstantOverflowBounds(SymbolRef Sym,
  202. ProgramStateRef State) {
  203. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  204. BasicValueFactory &BV = SVB.getBasicValueFactory();
  205. QualType T = Sym->getType();
  206. assert(T->isSignedIntegerOrEnumerationType() &&
  207. "This only works with signed integers!");
  208. APSIntType AT = BV.getAPSIntType(T);
  209. llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
  210. return isInRelation(BO_LE, Sym, Max, State) &&
  211. isInRelation(BO_GE, Sym, Min, State);
  212. }
  213. // Same for the concrete integers: see if I is within [min/4, max/4].
  214. static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
  215. APSIntType AT(I);
  216. assert(!AT.isUnsigned() &&
  217. "This only works with signed integers!");
  218. llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
  219. return (I <= Max) && (I >= -Max);
  220. }
  221. static std::pair<SymbolRef, llvm::APSInt>
  222. decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
  223. if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
  224. if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
  225. return std::make_pair(SymInt->getLHS(),
  226. (SymInt->getOpcode() == BO_Add) ?
  227. (SymInt->getRHS()) :
  228. (-SymInt->getRHS()));
  229. // Fail to decompose: "reduce" the problem to the "$x + 0" case.
  230. return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
  231. }
  232. // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
  233. // same signed integral type and no overflows occur (which should be checked
  234. // by the caller).
  235. static NonLoc doRearrangeUnchecked(ProgramStateRef State,
  236. BinaryOperator::Opcode Op,
  237. SymbolRef LSym, llvm::APSInt LInt,
  238. SymbolRef RSym, llvm::APSInt RInt) {
  239. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  240. BasicValueFactory &BV = SVB.getBasicValueFactory();
  241. SymbolManager &SymMgr = SVB.getSymbolManager();
  242. QualType SymTy = LSym->getType();
  243. assert(SymTy == RSym->getType() &&
  244. "Symbols are not of the same type!");
  245. assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
  246. "Integers are not of the same type as symbols!");
  247. assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
  248. "Integers are not of the same type as symbols!");
  249. QualType ResultTy;
  250. if (BinaryOperator::isComparisonOp(Op))
  251. ResultTy = SVB.getConditionType();
  252. else if (BinaryOperator::isAdditiveOp(Op))
  253. ResultTy = SymTy;
  254. else
  255. llvm_unreachable("Operation not suitable for unchecked rearrangement!");
  256. // FIXME: Can we use assume() without getting into an infinite recursion?
  257. if (LSym == RSym)
  258. return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
  259. nonloc::ConcreteInt(RInt), ResultTy)
  260. .castAs<NonLoc>();
  261. SymbolRef ResultSym = nullptr;
  262. BinaryOperator::Opcode ResultOp;
  263. llvm::APSInt ResultInt;
  264. if (BinaryOperator::isComparisonOp(Op)) {
  265. // Prefer comparing to a non-negative number.
  266. // FIXME: Maybe it'd be better to have consistency in
  267. // "$x - $y" vs. "$y - $x" because those are solver's keys.
  268. if (LInt > RInt) {
  269. ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
  270. ResultOp = BinaryOperator::reverseComparisonOp(Op);
  271. ResultInt = LInt - RInt; // Opposite order!
  272. } else {
  273. ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
  274. ResultOp = Op;
  275. ResultInt = RInt - LInt; // Opposite order!
  276. }
  277. } else {
  278. ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
  279. ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
  280. ResultOp = BO_Add;
  281. // Bring back the cosmetic difference.
  282. if (ResultInt < 0) {
  283. ResultInt = -ResultInt;
  284. ResultOp = BO_Sub;
  285. } else if (ResultInt == 0) {
  286. // Shortcut: Simplify "$x + 0" to "$x".
  287. return nonloc::SymbolVal(ResultSym);
  288. }
  289. }
  290. const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
  291. return nonloc::SymbolVal(
  292. SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
  293. }
  294. // Rearrange if symbol type matches the result type and if the operator is a
  295. // comparison operator, both symbol and constant must be within constant
  296. // overflow bounds.
  297. static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
  298. SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
  299. return Sym->getType() == Ty &&
  300. (!BinaryOperator::isComparisonOp(Op) ||
  301. (isWithinConstantOverflowBounds(Sym, State) &&
  302. isWithinConstantOverflowBounds(Int)));
  303. }
  304. static Optional<NonLoc> tryRearrange(ProgramStateRef State,
  305. BinaryOperator::Opcode Op, NonLoc Lhs,
  306. NonLoc Rhs, QualType ResultTy) {
  307. ProgramStateManager &StateMgr = State->getStateManager();
  308. SValBuilder &SVB = StateMgr.getSValBuilder();
  309. // We expect everything to be of the same type - this type.
  310. QualType SingleTy;
  311. // FIXME: After putting complexity threshold to the symbols we can always
  312. // rearrange additive operations but rearrange comparisons only if
  313. // option is set.
  314. if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
  315. return None;
  316. SymbolRef LSym = Lhs.getAsSymbol();
  317. if (!LSym)
  318. return None;
  319. if (BinaryOperator::isComparisonOp(Op)) {
  320. SingleTy = LSym->getType();
  321. if (ResultTy != SVB.getConditionType())
  322. return None;
  323. // Initialize SingleTy later with a symbol's type.
  324. } else if (BinaryOperator::isAdditiveOp(Op)) {
  325. SingleTy = ResultTy;
  326. if (LSym->getType() != SingleTy)
  327. return None;
  328. } else {
  329. // Don't rearrange other operations.
  330. return None;
  331. }
  332. assert(!SingleTy.isNull() && "We should have figured out the type by now!");
  333. // Rearrange signed symbolic expressions only
  334. if (!SingleTy->isSignedIntegerOrEnumerationType())
  335. return None;
  336. SymbolRef RSym = Rhs.getAsSymbol();
  337. if (!RSym || RSym->getType() != SingleTy)
  338. return None;
  339. BasicValueFactory &BV = State->getBasicVals();
  340. llvm::APSInt LInt, RInt;
  341. std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
  342. std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
  343. if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
  344. !shouldRearrange(State, Op, RSym, RInt, SingleTy))
  345. return None;
  346. // We know that no overflows can occur anymore.
  347. return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
  348. }
  349. SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
  350. BinaryOperator::Opcode op,
  351. NonLoc lhs, NonLoc rhs,
  352. QualType resultTy) {
  353. NonLoc InputLHS = lhs;
  354. NonLoc InputRHS = rhs;
  355. // Constraints may have changed since the creation of a bound SVal. Check if
  356. // the values can be simplified based on those new constraints.
  357. SVal simplifiedLhs = simplifySVal(state, lhs);
  358. SVal simplifiedRhs = simplifySVal(state, rhs);
  359. if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
  360. lhs = *simplifiedLhsAsNonLoc;
  361. if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
  362. rhs = *simplifiedRhsAsNonLoc;
  363. // Handle trivial case where left-side and right-side are the same.
  364. if (lhs == rhs)
  365. switch (op) {
  366. default:
  367. break;
  368. case BO_EQ:
  369. case BO_LE:
  370. case BO_GE:
  371. return makeTruthVal(true, resultTy);
  372. case BO_LT:
  373. case BO_GT:
  374. case BO_NE:
  375. return makeTruthVal(false, resultTy);
  376. case BO_Xor:
  377. case BO_Sub:
  378. if (resultTy->isIntegralOrEnumerationType())
  379. return makeIntVal(0, resultTy);
  380. return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
  381. QualType{});
  382. case BO_Or:
  383. case BO_And:
  384. return evalCast(lhs, resultTy, QualType{});
  385. }
  386. while (true) {
  387. switch (lhs.getSubKind()) {
  388. default:
  389. return makeSymExprValNN(op, lhs, rhs, resultTy);
  390. case nonloc::PointerToMemberKind: {
  391. assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
  392. "Both SVals should have pointer-to-member-type");
  393. auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
  394. RPTM = rhs.castAs<nonloc::PointerToMember>();
  395. auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
  396. switch (op) {
  397. case BO_EQ:
  398. return makeTruthVal(LPTMD == RPTMD, resultTy);
  399. case BO_NE:
  400. return makeTruthVal(LPTMD != RPTMD, resultTy);
  401. default:
  402. return UnknownVal();
  403. }
  404. }
  405. case nonloc::LocAsIntegerKind: {
  406. Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
  407. switch (rhs.getSubKind()) {
  408. case nonloc::LocAsIntegerKind:
  409. // FIXME: at the moment the implementation
  410. // of modeling "pointers as integers" is not complete.
  411. if (!BinaryOperator::isComparisonOp(op))
  412. return UnknownVal();
  413. return evalBinOpLL(state, op, lhsL,
  414. rhs.castAs<nonloc::LocAsInteger>().getLoc(),
  415. resultTy);
  416. case nonloc::ConcreteIntKind: {
  417. // FIXME: at the moment the implementation
  418. // of modeling "pointers as integers" is not complete.
  419. if (!BinaryOperator::isComparisonOp(op))
  420. return UnknownVal();
  421. // Transform the integer into a location and compare.
  422. // FIXME: This only makes sense for comparisons. If we want to, say,
  423. // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
  424. // then pack it back into a LocAsInteger.
  425. llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
  426. // If the region has a symbolic base, pay attention to the type; it
  427. // might be coming from a non-default address space. For non-symbolic
  428. // regions it doesn't matter that much because such comparisons would
  429. // most likely evaluate to concrete false anyway. FIXME: We might
  430. // still need to handle the non-comparison case.
  431. if (SymbolRef lSym = lhs.getAsLocSymbol(true))
  432. BasicVals.getAPSIntType(lSym->getType()).apply(i);
  433. else
  434. BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
  435. return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
  436. }
  437. default:
  438. switch (op) {
  439. case BO_EQ:
  440. return makeTruthVal(false, resultTy);
  441. case BO_NE:
  442. return makeTruthVal(true, resultTy);
  443. default:
  444. // This case also handles pointer arithmetic.
  445. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  446. }
  447. }
  448. }
  449. case nonloc::ConcreteIntKind: {
  450. llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
  451. // If we're dealing with two known constants, just perform the operation.
  452. if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
  453. llvm::APSInt RHSValue = *KnownRHSValue;
  454. if (BinaryOperator::isComparisonOp(op)) {
  455. // We're looking for a type big enough to compare the two values.
  456. // FIXME: This is not correct. char + short will result in a promotion
  457. // to int. Unfortunately we have lost types by this point.
  458. APSIntType CompareType = std::max(APSIntType(LHSValue),
  459. APSIntType(RHSValue));
  460. CompareType.apply(LHSValue);
  461. CompareType.apply(RHSValue);
  462. } else if (!BinaryOperator::isShiftOp(op)) {
  463. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  464. IntType.apply(LHSValue);
  465. IntType.apply(RHSValue);
  466. }
  467. const llvm::APSInt *Result =
  468. BasicVals.evalAPSInt(op, LHSValue, RHSValue);
  469. if (!Result)
  470. return UndefinedVal();
  471. return nonloc::ConcreteInt(*Result);
  472. }
  473. // Swap the left and right sides and flip the operator if doing so
  474. // allows us to better reason about the expression (this is a form
  475. // of expression canonicalization).
  476. // While we're at it, catch some special cases for non-commutative ops.
  477. switch (op) {
  478. case BO_LT:
  479. case BO_GT:
  480. case BO_LE:
  481. case BO_GE:
  482. op = BinaryOperator::reverseComparisonOp(op);
  483. LLVM_FALLTHROUGH;
  484. case BO_EQ:
  485. case BO_NE:
  486. case BO_Add:
  487. case BO_Mul:
  488. case BO_And:
  489. case BO_Xor:
  490. case BO_Or:
  491. std::swap(lhs, rhs);
  492. continue;
  493. case BO_Shr:
  494. // (~0)>>a
  495. if (LHSValue.isAllOnes() && LHSValue.isSigned())
  496. return evalCast(lhs, resultTy, QualType{});
  497. LLVM_FALLTHROUGH;
  498. case BO_Shl:
  499. // 0<<a and 0>>a
  500. if (LHSValue == 0)
  501. return evalCast(lhs, resultTy, QualType{});
  502. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  503. case BO_Div:
  504. // 0 / x == 0
  505. case BO_Rem:
  506. // 0 % x == 0
  507. if (LHSValue == 0)
  508. return makeZeroVal(resultTy);
  509. LLVM_FALLTHROUGH;
  510. default:
  511. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  512. }
  513. }
  514. case nonloc::SymbolValKind: {
  515. // We only handle LHS as simple symbols or SymIntExprs.
  516. SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
  517. // LHS is a symbolic expression.
  518. if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
  519. // Is this a logical not? (!x is represented as x == 0.)
  520. if (op == BO_EQ && rhs.isZeroConstant()) {
  521. // We know how to negate certain expressions. Simplify them here.
  522. BinaryOperator::Opcode opc = symIntExpr->getOpcode();
  523. switch (opc) {
  524. default:
  525. // We don't know how to negate this operation.
  526. // Just handle it as if it were a normal comparison to 0.
  527. break;
  528. case BO_LAnd:
  529. case BO_LOr:
  530. llvm_unreachable("Logical operators handled by branching logic.");
  531. case BO_Assign:
  532. case BO_MulAssign:
  533. case BO_DivAssign:
  534. case BO_RemAssign:
  535. case BO_AddAssign:
  536. case BO_SubAssign:
  537. case BO_ShlAssign:
  538. case BO_ShrAssign:
  539. case BO_AndAssign:
  540. case BO_XorAssign:
  541. case BO_OrAssign:
  542. case BO_Comma:
  543. llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
  544. case BO_PtrMemD:
  545. case BO_PtrMemI:
  546. llvm_unreachable("Pointer arithmetic not handled here.");
  547. case BO_LT:
  548. case BO_GT:
  549. case BO_LE:
  550. case BO_GE:
  551. case BO_EQ:
  552. case BO_NE:
  553. assert(resultTy->isBooleanType() ||
  554. resultTy == getConditionType());
  555. assert(symIntExpr->getType()->isBooleanType() ||
  556. getContext().hasSameUnqualifiedType(symIntExpr->getType(),
  557. getConditionType()));
  558. // Negate the comparison and make a value.
  559. opc = BinaryOperator::negateComparisonOp(opc);
  560. return makeNonLoc(symIntExpr->getLHS(), opc,
  561. symIntExpr->getRHS(), resultTy);
  562. }
  563. }
  564. // For now, only handle expressions whose RHS is a constant.
  565. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
  566. // If both the LHS and the current expression are additive,
  567. // fold their constants and try again.
  568. if (BinaryOperator::isAdditiveOp(op)) {
  569. BinaryOperator::Opcode lop = symIntExpr->getOpcode();
  570. if (BinaryOperator::isAdditiveOp(lop)) {
  571. // Convert the two constants to a common type, then combine them.
  572. // resultTy may not be the best type to convert to, but it's
  573. // probably the best choice in expressions with mixed type
  574. // (such as x+1U+2LL). The rules for implicit conversions should
  575. // choose a reasonable type to preserve the expression, and will
  576. // at least match how the value is going to be used.
  577. APSIntType IntType = BasicVals.getAPSIntType(resultTy);
  578. const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
  579. const llvm::APSInt &second = IntType.convert(*RHSValue);
  580. const llvm::APSInt *newRHS;
  581. if (lop == op)
  582. newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
  583. else
  584. newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
  585. assert(newRHS && "Invalid operation despite common type!");
  586. rhs = nonloc::ConcreteInt(*newRHS);
  587. lhs = nonloc::SymbolVal(symIntExpr->getLHS());
  588. op = lop;
  589. continue;
  590. }
  591. }
  592. // Otherwise, make a SymIntExpr out of the expression.
  593. return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
  594. }
  595. }
  596. // Is the RHS a constant?
  597. if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
  598. return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
  599. if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
  600. return *V;
  601. // Give up -- this is not a symbolic expression we can handle.
  602. return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
  603. }
  604. }
  605. }
  606. }
  607. static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
  608. const FieldRegion *RightFR,
  609. BinaryOperator::Opcode op,
  610. QualType resultTy,
  611. SimpleSValBuilder &SVB) {
  612. // Only comparisons are meaningful here!
  613. if (!BinaryOperator::isComparisonOp(op))
  614. return UnknownVal();
  615. // Next, see if the two FRs have the same super-region.
  616. // FIXME: This doesn't handle casts yet, and simply stripping the casts
  617. // doesn't help.
  618. if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
  619. return UnknownVal();
  620. const FieldDecl *LeftFD = LeftFR->getDecl();
  621. const FieldDecl *RightFD = RightFR->getDecl();
  622. const RecordDecl *RD = LeftFD->getParent();
  623. // Make sure the two FRs are from the same kind of record. Just in case!
  624. // FIXME: This is probably where inheritance would be a problem.
  625. if (RD != RightFD->getParent())
  626. return UnknownVal();
  627. // We know for sure that the two fields are not the same, since that
  628. // would have given us the same SVal.
  629. if (op == BO_EQ)
  630. return SVB.makeTruthVal(false, resultTy);
  631. if (op == BO_NE)
  632. return SVB.makeTruthVal(true, resultTy);
  633. // Iterate through the fields and see which one comes first.
  634. // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
  635. // members and the units in which bit-fields reside have addresses that
  636. // increase in the order in which they are declared."
  637. bool leftFirst = (op == BO_LT || op == BO_LE);
  638. for (const auto *I : RD->fields()) {
  639. if (I == LeftFD)
  640. return SVB.makeTruthVal(leftFirst, resultTy);
  641. if (I == RightFD)
  642. return SVB.makeTruthVal(!leftFirst, resultTy);
  643. }
  644. llvm_unreachable("Fields not found in parent record's definition");
  645. }
  646. // FIXME: all this logic will change if/when we have MemRegion::getLocation().
  647. SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
  648. BinaryOperator::Opcode op,
  649. Loc lhs, Loc rhs,
  650. QualType resultTy) {
  651. // Only comparisons and subtractions are valid operations on two pointers.
  652. // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
  653. // However, if a pointer is casted to an integer, evalBinOpNN may end up
  654. // calling this function with another operation (PR7527). We don't attempt to
  655. // model this for now, but it could be useful, particularly when the
  656. // "location" is actually an integer value that's been passed through a void*.
  657. if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
  658. return UnknownVal();
  659. // Special cases for when both sides are identical.
  660. if (lhs == rhs) {
  661. switch (op) {
  662. default:
  663. llvm_unreachable("Unimplemented operation for two identical values");
  664. case BO_Sub:
  665. return makeZeroVal(resultTy);
  666. case BO_EQ:
  667. case BO_LE:
  668. case BO_GE:
  669. return makeTruthVal(true, resultTy);
  670. case BO_NE:
  671. case BO_LT:
  672. case BO_GT:
  673. return makeTruthVal(false, resultTy);
  674. }
  675. }
  676. switch (lhs.getSubKind()) {
  677. default:
  678. llvm_unreachable("Ordering not implemented for this Loc.");
  679. case loc::GotoLabelKind:
  680. // The only thing we know about labels is that they're non-null.
  681. if (rhs.isZeroConstant()) {
  682. switch (op) {
  683. default:
  684. break;
  685. case BO_Sub:
  686. return evalCast(lhs, resultTy, QualType{});
  687. case BO_EQ:
  688. case BO_LE:
  689. case BO_LT:
  690. return makeTruthVal(false, resultTy);
  691. case BO_NE:
  692. case BO_GT:
  693. case BO_GE:
  694. return makeTruthVal(true, resultTy);
  695. }
  696. }
  697. // There may be two labels for the same location, and a function region may
  698. // have the same address as a label at the start of the function (depending
  699. // on the ABI).
  700. // FIXME: we can probably do a comparison against other MemRegions, though.
  701. // FIXME: is there a way to tell if two labels refer to the same location?
  702. return UnknownVal();
  703. case loc::ConcreteIntKind: {
  704. // If one of the operands is a symbol and the other is a constant,
  705. // build an expression for use by the constraint manager.
  706. if (SymbolRef rSym = rhs.getAsLocSymbol()) {
  707. // We can only build expressions with symbols on the left,
  708. // so we need a reversible operator.
  709. if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
  710. return UnknownVal();
  711. const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
  712. op = BinaryOperator::reverseComparisonOp(op);
  713. return makeNonLoc(rSym, op, lVal, resultTy);
  714. }
  715. // If both operands are constants, just perform the operation.
  716. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  717. SVal ResultVal =
  718. lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
  719. if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
  720. return evalCast(*Result, resultTy, QualType{});
  721. assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
  722. return UnknownVal();
  723. }
  724. // Special case comparisons against NULL.
  725. // This must come after the test if the RHS is a symbol, which is used to
  726. // build constraints. The address of any non-symbolic region is guaranteed
  727. // to be non-NULL, as is any label.
  728. assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
  729. if (lhs.isZeroConstant()) {
  730. switch (op) {
  731. default:
  732. break;
  733. case BO_EQ:
  734. case BO_GT:
  735. case BO_GE:
  736. return makeTruthVal(false, resultTy);
  737. case BO_NE:
  738. case BO_LT:
  739. case BO_LE:
  740. return makeTruthVal(true, resultTy);
  741. }
  742. }
  743. // Comparing an arbitrary integer to a region or label address is
  744. // completely unknowable.
  745. return UnknownVal();
  746. }
  747. case loc::MemRegionValKind: {
  748. if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
  749. // If one of the operands is a symbol and the other is a constant,
  750. // build an expression for use by the constraint manager.
  751. if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
  752. if (BinaryOperator::isComparisonOp(op))
  753. return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
  754. return UnknownVal();
  755. }
  756. // Special case comparisons to NULL.
  757. // This must come after the test if the LHS is a symbol, which is used to
  758. // build constraints. The address of any non-symbolic region is guaranteed
  759. // to be non-NULL.
  760. if (rInt->isZeroConstant()) {
  761. if (op == BO_Sub)
  762. return evalCast(lhs, resultTy, QualType{});
  763. if (BinaryOperator::isComparisonOp(op)) {
  764. QualType boolType = getContext().BoolTy;
  765. NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
  766. NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
  767. return evalBinOpNN(state, op, l, r, resultTy);
  768. }
  769. }
  770. // Comparing a region to an arbitrary integer is completely unknowable.
  771. return UnknownVal();
  772. }
  773. // Get both values as regions, if possible.
  774. const MemRegion *LeftMR = lhs.getAsRegion();
  775. assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
  776. const MemRegion *RightMR = rhs.getAsRegion();
  777. if (!RightMR)
  778. // The RHS is probably a label, which in theory could address a region.
  779. // FIXME: we can probably make a more useful statement about non-code
  780. // regions, though.
  781. return UnknownVal();
  782. const MemRegion *LeftBase = LeftMR->getBaseRegion();
  783. const MemRegion *RightBase = RightMR->getBaseRegion();
  784. const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
  785. const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
  786. const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
  787. // If the two regions are from different known memory spaces they cannot be
  788. // equal. Also, assume that no symbolic region (whose memory space is
  789. // unknown) is on the stack.
  790. if (LeftMS != RightMS &&
  791. ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
  792. (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
  793. switch (op) {
  794. default:
  795. return UnknownVal();
  796. case BO_EQ:
  797. return makeTruthVal(false, resultTy);
  798. case BO_NE:
  799. return makeTruthVal(true, resultTy);
  800. }
  801. }
  802. // If both values wrap regions, see if they're from different base regions.
  803. // Note, heap base symbolic regions are assumed to not alias with
  804. // each other; for example, we assume that malloc returns different address
  805. // on each invocation.
  806. // FIXME: ObjC object pointers always reside on the heap, but currently
  807. // we treat their memory space as unknown, because symbolic pointers
  808. // to ObjC objects may alias. There should be a way to construct
  809. // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
  810. // guesses memory space for ObjC object pointers manually instead of
  811. // relying on us.
  812. if (LeftBase != RightBase &&
  813. ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
  814. (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
  815. switch (op) {
  816. default:
  817. return UnknownVal();
  818. case BO_EQ:
  819. return makeTruthVal(false, resultTy);
  820. case BO_NE:
  821. return makeTruthVal(true, resultTy);
  822. }
  823. }
  824. // Handle special cases for when both regions are element regions.
  825. const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
  826. const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
  827. if (RightER && LeftER) {
  828. // Next, see if the two ERs have the same super-region and matching types.
  829. // FIXME: This should do something useful even if the types don't match,
  830. // though if both indexes are constant the RegionRawOffset path will
  831. // give the correct answer.
  832. if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
  833. LeftER->getElementType() == RightER->getElementType()) {
  834. // Get the left index and cast it to the correct type.
  835. // If the index is unknown or undefined, bail out here.
  836. SVal LeftIndexVal = LeftER->getIndex();
  837. Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
  838. if (!LeftIndex)
  839. return UnknownVal();
  840. LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
  841. LeftIndex = LeftIndexVal.getAs<NonLoc>();
  842. if (!LeftIndex)
  843. return UnknownVal();
  844. // Do the same for the right index.
  845. SVal RightIndexVal = RightER->getIndex();
  846. Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
  847. if (!RightIndex)
  848. return UnknownVal();
  849. RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
  850. RightIndex = RightIndexVal.getAs<NonLoc>();
  851. if (!RightIndex)
  852. return UnknownVal();
  853. // Actually perform the operation.
  854. // evalBinOpNN expects the two indexes to already be the right type.
  855. return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
  856. }
  857. }
  858. // Special handling of the FieldRegions, even with symbolic offsets.
  859. const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
  860. const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
  861. if (RightFR && LeftFR) {
  862. SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
  863. *this);
  864. if (!R.isUnknown())
  865. return R;
  866. }
  867. // Compare the regions using the raw offsets.
  868. RegionOffset LeftOffset = LeftMR->getAsOffset();
  869. RegionOffset RightOffset = RightMR->getAsOffset();
  870. if (LeftOffset.getRegion() != nullptr &&
  871. LeftOffset.getRegion() == RightOffset.getRegion() &&
  872. !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
  873. int64_t left = LeftOffset.getOffset();
  874. int64_t right = RightOffset.getOffset();
  875. switch (op) {
  876. default:
  877. return UnknownVal();
  878. case BO_LT:
  879. return makeTruthVal(left < right, resultTy);
  880. case BO_GT:
  881. return makeTruthVal(left > right, resultTy);
  882. case BO_LE:
  883. return makeTruthVal(left <= right, resultTy);
  884. case BO_GE:
  885. return makeTruthVal(left >= right, resultTy);
  886. case BO_EQ:
  887. return makeTruthVal(left == right, resultTy);
  888. case BO_NE:
  889. return makeTruthVal(left != right, resultTy);
  890. }
  891. }
  892. // At this point we're not going to get a good answer, but we can try
  893. // conjuring an expression instead.
  894. SymbolRef LHSSym = lhs.getAsLocSymbol();
  895. SymbolRef RHSSym = rhs.getAsLocSymbol();
  896. if (LHSSym && RHSSym)
  897. return makeNonLoc(LHSSym, op, RHSSym, resultTy);
  898. // If we get here, we have no way of comparing the regions.
  899. return UnknownVal();
  900. }
  901. }
  902. }
  903. SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
  904. BinaryOperator::Opcode op, Loc lhs,
  905. NonLoc rhs, QualType resultTy) {
  906. if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
  907. if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
  908. if (PTMSV->isNullMemberPointer())
  909. return UndefinedVal();
  910. auto getFieldLValue = [&](const auto *FD) -> SVal {
  911. SVal Result = lhs;
  912. for (const auto &I : *PTMSV)
  913. Result = StateMgr.getStoreManager().evalDerivedToBase(
  914. Result, I->getType(), I->isVirtual());
  915. return state->getLValue(FD, Result);
  916. };
  917. if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
  918. return getFieldLValue(FD);
  919. }
  920. if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
  921. return getFieldLValue(FD);
  922. }
  923. }
  924. return rhs;
  925. }
  926. assert(!BinaryOperator::isComparisonOp(op) &&
  927. "arguments to comparison ops must be of the same type");
  928. // Special case: rhs is a zero constant.
  929. if (rhs.isZeroConstant())
  930. return lhs;
  931. // Perserve the null pointer so that it can be found by the DerefChecker.
  932. if (lhs.isZeroConstant())
  933. return lhs;
  934. // We are dealing with pointer arithmetic.
  935. // Handle pointer arithmetic on constant values.
  936. if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
  937. if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
  938. const llvm::APSInt &leftI = lhsInt->getValue();
  939. assert(leftI.isUnsigned());
  940. llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
  941. // Convert the bitwidth of rightI. This should deal with overflow
  942. // since we are dealing with concrete values.
  943. rightI = rightI.extOrTrunc(leftI.getBitWidth());
  944. // Offset the increment by the pointer size.
  945. llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
  946. QualType pointeeType = resultTy->getPointeeType();
  947. Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
  948. rightI *= Multiplicand;
  949. // Compute the adjusted pointer.
  950. switch (op) {
  951. case BO_Add:
  952. rightI = leftI + rightI;
  953. break;
  954. case BO_Sub:
  955. rightI = leftI - rightI;
  956. break;
  957. default:
  958. llvm_unreachable("Invalid pointer arithmetic operation");
  959. }
  960. return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
  961. }
  962. }
  963. // Handle cases where 'lhs' is a region.
  964. if (const MemRegion *region = lhs.getAsRegion()) {
  965. rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
  966. SVal index = UnknownVal();
  967. const SubRegion *superR = nullptr;
  968. // We need to know the type of the pointer in order to add an integer to it.
  969. // Depending on the type, different amount of bytes is added.
  970. QualType elementType;
  971. if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
  972. assert(op == BO_Add || op == BO_Sub);
  973. index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
  974. getArrayIndexType());
  975. superR = cast<SubRegion>(elemReg->getSuperRegion());
  976. elementType = elemReg->getElementType();
  977. }
  978. else if (isa<SubRegion>(region)) {
  979. assert(op == BO_Add || op == BO_Sub);
  980. index = (op == BO_Add) ? rhs : evalMinus(rhs);
  981. superR = cast<SubRegion>(region);
  982. // TODO: Is this actually reliable? Maybe improving our MemRegion
  983. // hierarchy to provide typed regions for all non-void pointers would be
  984. // better. For instance, we cannot extend this towards LocAsInteger
  985. // operations, where result type of the expression is integer.
  986. if (resultTy->isAnyPointerType())
  987. elementType = resultTy->getPointeeType();
  988. }
  989. // Represent arithmetic on void pointers as arithmetic on char pointers.
  990. // It is fine when a TypedValueRegion of char value type represents
  991. // a void pointer. Note that arithmetic on void pointers is a GCC extension.
  992. if (elementType->isVoidType())
  993. elementType = getContext().CharTy;
  994. if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
  995. return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
  996. superR, getContext()));
  997. }
  998. }
  999. return UnknownVal();
  1000. }
  1001. const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
  1002. SVal V) {
  1003. V = simplifySVal(state, V);
  1004. if (V.isUnknownOrUndef())
  1005. return nullptr;
  1006. if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
  1007. return &X->getValue();
  1008. if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
  1009. return &X->getValue();
  1010. if (SymbolRef Sym = V.getAsSymbol())
  1011. return state->getConstraintManager().getSymVal(state, Sym);
  1012. return nullptr;
  1013. }
  1014. SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
  1015. SVal SimplifiedVal = simplifySValOnce(State, Val);
  1016. while (SimplifiedVal != Val) {
  1017. Val = SimplifiedVal;
  1018. SimplifiedVal = simplifySValOnce(State, Val);
  1019. }
  1020. return SimplifiedVal;
  1021. }
  1022. SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
  1023. return simplifyUntilFixpoint(State, V);
  1024. }
  1025. SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
  1026. // For now, this function tries to constant-fold symbols inside a
  1027. // nonloc::SymbolVal, and does nothing else. More simplifications should
  1028. // be possible, such as constant-folding an index in an ElementRegion.
  1029. class Simplifier : public FullSValVisitor<Simplifier, SVal> {
  1030. ProgramStateRef State;
  1031. SValBuilder &SVB;
  1032. // Cache results for the lifetime of the Simplifier. Results change every
  1033. // time new constraints are added to the program state, which is the whole
  1034. // point of simplifying, and for that very reason it's pointless to maintain
  1035. // the same cache for the duration of the whole analysis.
  1036. llvm::DenseMap<SymbolRef, SVal> Cached;
  1037. static bool isUnchanged(SymbolRef Sym, SVal Val) {
  1038. return Sym == Val.getAsSymbol();
  1039. }
  1040. SVal cache(SymbolRef Sym, SVal V) {
  1041. Cached[Sym] = V;
  1042. return V;
  1043. }
  1044. SVal skip(SymbolRef Sym) {
  1045. return cache(Sym, SVB.makeSymbolVal(Sym));
  1046. }
  1047. // Return the known const value for the Sym if available, or return Undef
  1048. // otherwise.
  1049. SVal getConst(SymbolRef Sym) {
  1050. const llvm::APSInt *Const =
  1051. State->getConstraintManager().getSymVal(State, Sym);
  1052. if (Const)
  1053. return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
  1054. : (SVal)SVB.makeIntVal(*Const);
  1055. return UndefinedVal();
  1056. }
  1057. SVal getConstOrVisit(SymbolRef Sym) {
  1058. const SVal Ret = getConst(Sym);
  1059. if (Ret.isUndef())
  1060. return Visit(Sym);
  1061. return Ret;
  1062. }
  1063. public:
  1064. Simplifier(ProgramStateRef State)
  1065. : State(State), SVB(State->getStateManager().getSValBuilder()) {}
  1066. SVal VisitSymbolData(const SymbolData *S) {
  1067. // No cache here.
  1068. if (const llvm::APSInt *I =
  1069. SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
  1070. return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
  1071. : (SVal)SVB.makeIntVal(*I);
  1072. return SVB.makeSymbolVal(S);
  1073. }
  1074. // TODO: Support SymbolCast.
  1075. SVal VisitSymIntExpr(const SymIntExpr *S) {
  1076. auto I = Cached.find(S);
  1077. if (I != Cached.end())
  1078. return I->second;
  1079. SVal LHS = getConstOrVisit(S->getLHS());
  1080. if (isUnchanged(S->getLHS(), LHS))
  1081. return skip(S);
  1082. SVal RHS;
  1083. // By looking at the APSInt in the right-hand side of S, we cannot
  1084. // figure out if it should be treated as a Loc or as a NonLoc.
  1085. // So make our guess by recalling that we cannot multiply pointers
  1086. // or compare a pointer to an integer.
  1087. if (Loc::isLocType(S->getLHS()->getType()) &&
  1088. BinaryOperator::isComparisonOp(S->getOpcode())) {
  1089. // The usual conversion of $sym to &SymRegion{$sym}, as they have
  1090. // the same meaning for Loc-type symbols, but the latter form
  1091. // is preferred in SVal computations for being Loc itself.
  1092. if (SymbolRef Sym = LHS.getAsSymbol()) {
  1093. assert(Loc::isLocType(Sym->getType()));
  1094. LHS = SVB.makeLoc(Sym);
  1095. }
  1096. RHS = SVB.makeIntLocVal(S->getRHS());
  1097. } else {
  1098. RHS = SVB.makeIntVal(S->getRHS());
  1099. }
  1100. return cache(
  1101. S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
  1102. }
  1103. SVal VisitIntSymExpr(const IntSymExpr *S) {
  1104. auto I = Cached.find(S);
  1105. if (I != Cached.end())
  1106. return I->second;
  1107. SVal RHS = getConstOrVisit(S->getRHS());
  1108. if (isUnchanged(S->getRHS(), RHS))
  1109. return skip(S);
  1110. SVal LHS = SVB.makeIntVal(S->getLHS());
  1111. return cache(
  1112. S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
  1113. }
  1114. SVal VisitSymSymExpr(const SymSymExpr *S) {
  1115. auto I = Cached.find(S);
  1116. if (I != Cached.end())
  1117. return I->second;
  1118. // For now don't try to simplify mixed Loc/NonLoc expressions
  1119. // because they often appear from LocAsInteger operations
  1120. // and we don't know how to combine a LocAsInteger
  1121. // with a concrete value.
  1122. if (Loc::isLocType(S->getLHS()->getType()) !=
  1123. Loc::isLocType(S->getRHS()->getType()))
  1124. return skip(S);
  1125. SVal LHS = getConstOrVisit(S->getLHS());
  1126. SVal RHS = getConstOrVisit(S->getRHS());
  1127. if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
  1128. return skip(S);
  1129. return cache(
  1130. S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
  1131. }
  1132. SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
  1133. SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
  1134. SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
  1135. // Simplification is much more costly than computing complexity.
  1136. // For high complexity, it may be not worth it.
  1137. return Visit(V.getSymbol());
  1138. }
  1139. SVal VisitSVal(SVal V) { return V; }
  1140. };
  1141. // A crude way of preventing this function from calling itself from evalBinOp.
  1142. static bool isReentering = false;
  1143. if (isReentering)
  1144. return V;
  1145. isReentering = true;
  1146. SVal SimplifiedV = Simplifier(State).Visit(V);
  1147. isReentering = false;
  1148. return SimplifiedV;
  1149. }