SimpleSValBuilder.cpp 52 KB

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