LoopUnrolling.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //===--- LoopUnrolling.cpp - Unroll loops -----------------------*- 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 contains functions which are used to decide if a loop worth to be
  10. /// unrolled. Moreover, these functions manages the stack of loop which is
  11. /// tracked by the ProgramState.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/ASTMatchers/ASTMatchers.h"
  15. #include "clang/ASTMatchers/ASTMatchFinder.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  19. #include <optional>
  20. using namespace clang;
  21. using namespace ento;
  22. using namespace clang::ast_matchers;
  23. static const int MAXIMUM_STEP_UNROLLED = 128;
  24. namespace {
  25. struct LoopState {
  26. private:
  27. enum Kind { Normal, Unrolled } K;
  28. const Stmt *LoopStmt;
  29. const LocationContext *LCtx;
  30. unsigned maxStep;
  31. LoopState(Kind InK, const Stmt *S, const LocationContext *L, unsigned N)
  32. : K(InK), LoopStmt(S), LCtx(L), maxStep(N) {}
  33. public:
  34. static LoopState getNormal(const Stmt *S, const LocationContext *L,
  35. unsigned N) {
  36. return LoopState(Normal, S, L, N);
  37. }
  38. static LoopState getUnrolled(const Stmt *S, const LocationContext *L,
  39. unsigned N) {
  40. return LoopState(Unrolled, S, L, N);
  41. }
  42. bool isUnrolled() const { return K == Unrolled; }
  43. unsigned getMaxStep() const { return maxStep; }
  44. const Stmt *getLoopStmt() const { return LoopStmt; }
  45. const LocationContext *getLocationContext() const { return LCtx; }
  46. bool operator==(const LoopState &X) const {
  47. return K == X.K && LoopStmt == X.LoopStmt;
  48. }
  49. void Profile(llvm::FoldingSetNodeID &ID) const {
  50. ID.AddInteger(K);
  51. ID.AddPointer(LoopStmt);
  52. ID.AddPointer(LCtx);
  53. ID.AddInteger(maxStep);
  54. }
  55. };
  56. } // namespace
  57. // The tracked stack of loops. The stack indicates that which loops the
  58. // simulated element contained by. The loops are marked depending if we decided
  59. // to unroll them.
  60. // TODO: The loop stack should not need to be in the program state since it is
  61. // lexical in nature. Instead, the stack of loops should be tracked in the
  62. // LocationContext.
  63. REGISTER_LIST_WITH_PROGRAMSTATE(LoopStack, LoopState)
  64. namespace clang {
  65. namespace ento {
  66. static bool isLoopStmt(const Stmt *S) {
  67. return isa_and_nonnull<ForStmt, WhileStmt, DoStmt>(S);
  68. }
  69. ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State) {
  70. auto LS = State->get<LoopStack>();
  71. if (!LS.isEmpty() && LS.getHead().getLoopStmt() == LoopStmt)
  72. State = State->set<LoopStack>(LS.getTail());
  73. return State;
  74. }
  75. static internal::Matcher<Stmt> simpleCondition(StringRef BindName,
  76. StringRef RefName) {
  77. return binaryOperator(
  78. anyOf(hasOperatorName("<"), hasOperatorName(">"),
  79. hasOperatorName("<="), hasOperatorName(">="),
  80. hasOperatorName("!=")),
  81. hasEitherOperand(ignoringParenImpCasts(
  82. declRefExpr(to(varDecl(hasType(isInteger())).bind(BindName)))
  83. .bind(RefName))),
  84. hasEitherOperand(
  85. ignoringParenImpCasts(integerLiteral().bind("boundNum"))))
  86. .bind("conditionOperator");
  87. }
  88. static internal::Matcher<Stmt>
  89. changeIntBoundNode(internal::Matcher<Decl> VarNodeMatcher) {
  90. return anyOf(
  91. unaryOperator(anyOf(hasOperatorName("--"), hasOperatorName("++")),
  92. hasUnaryOperand(ignoringParenImpCasts(
  93. declRefExpr(to(varDecl(VarNodeMatcher)))))),
  94. binaryOperator(isAssignmentOperator(),
  95. hasLHS(ignoringParenImpCasts(
  96. declRefExpr(to(varDecl(VarNodeMatcher)))))));
  97. }
  98. static internal::Matcher<Stmt>
  99. callByRef(internal::Matcher<Decl> VarNodeMatcher) {
  100. return callExpr(forEachArgumentWithParam(
  101. declRefExpr(to(varDecl(VarNodeMatcher))),
  102. parmVarDecl(hasType(references(qualType(unless(isConstQualified())))))));
  103. }
  104. static internal::Matcher<Stmt>
  105. assignedToRef(internal::Matcher<Decl> VarNodeMatcher) {
  106. return declStmt(hasDescendant(varDecl(
  107. allOf(hasType(referenceType()),
  108. hasInitializer(anyOf(
  109. initListExpr(has(declRefExpr(to(varDecl(VarNodeMatcher))))),
  110. declRefExpr(to(varDecl(VarNodeMatcher)))))))));
  111. }
  112. static internal::Matcher<Stmt>
  113. getAddrTo(internal::Matcher<Decl> VarNodeMatcher) {
  114. return unaryOperator(
  115. hasOperatorName("&"),
  116. hasUnaryOperand(declRefExpr(hasDeclaration(VarNodeMatcher))));
  117. }
  118. static internal::Matcher<Stmt> hasSuspiciousStmt(StringRef NodeName) {
  119. return hasDescendant(stmt(
  120. anyOf(gotoStmt(), switchStmt(), returnStmt(),
  121. // Escaping and not known mutation of the loop counter is handled
  122. // by exclusion of assigning and address-of operators and
  123. // pass-by-ref function calls on the loop counter from the body.
  124. changeIntBoundNode(equalsBoundNode(std::string(NodeName))),
  125. callByRef(equalsBoundNode(std::string(NodeName))),
  126. getAddrTo(equalsBoundNode(std::string(NodeName))),
  127. assignedToRef(equalsBoundNode(std::string(NodeName))))));
  128. }
  129. static internal::Matcher<Stmt> forLoopMatcher() {
  130. return forStmt(
  131. hasCondition(simpleCondition("initVarName", "initVarRef")),
  132. // Initialization should match the form: 'int i = 6' or 'i = 42'.
  133. hasLoopInit(
  134. anyOf(declStmt(hasSingleDecl(
  135. varDecl(allOf(hasInitializer(ignoringParenImpCasts(
  136. integerLiteral().bind("initNum"))),
  137. equalsBoundNode("initVarName"))))),
  138. binaryOperator(hasLHS(declRefExpr(to(varDecl(
  139. equalsBoundNode("initVarName"))))),
  140. hasRHS(ignoringParenImpCasts(
  141. integerLiteral().bind("initNum")))))),
  142. // Incrementation should be a simple increment or decrement
  143. // operator call.
  144. hasIncrement(unaryOperator(
  145. anyOf(hasOperatorName("++"), hasOperatorName("--")),
  146. hasUnaryOperand(declRefExpr(
  147. to(varDecl(allOf(equalsBoundNode("initVarName"),
  148. hasType(isInteger())))))))),
  149. unless(hasBody(hasSuspiciousStmt("initVarName"))))
  150. .bind("forLoop");
  151. }
  152. static bool isCapturedByReference(ExplodedNode *N, const DeclRefExpr *DR) {
  153. // Get the lambda CXXRecordDecl
  154. assert(DR->refersToEnclosingVariableOrCapture());
  155. const LocationContext *LocCtxt = N->getLocationContext();
  156. const Decl *D = LocCtxt->getDecl();
  157. const auto *MD = cast<CXXMethodDecl>(D);
  158. assert(MD && MD->getParent()->isLambda() &&
  159. "Captured variable should only be seen while evaluating a lambda");
  160. const CXXRecordDecl *LambdaCXXRec = MD->getParent();
  161. // Lookup the fields of the lambda
  162. llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
  163. FieldDecl *LambdaThisCaptureField;
  164. LambdaCXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  165. // Check if the counter is captured by reference
  166. const VarDecl *VD = cast<VarDecl>(DR->getDecl()->getCanonicalDecl());
  167. assert(VD);
  168. const FieldDecl *FD = LambdaCaptureFields[VD];
  169. assert(FD && "Captured variable without a corresponding field");
  170. return FD->getType()->isReferenceType();
  171. }
  172. // A loop counter is considered escaped if:
  173. // case 1: It is a global variable.
  174. // case 2: It is a reference parameter or a reference capture.
  175. // case 3: It is assigned to a non-const reference variable or parameter.
  176. // case 4: Has its address taken.
  177. static bool isPossiblyEscaped(ExplodedNode *N, const DeclRefExpr *DR) {
  178. const VarDecl *VD = cast<VarDecl>(DR->getDecl()->getCanonicalDecl());
  179. assert(VD);
  180. // Case 1:
  181. if (VD->hasGlobalStorage())
  182. return true;
  183. const bool IsRefParamOrCapture =
  184. isa<ParmVarDecl>(VD) || DR->refersToEnclosingVariableOrCapture();
  185. // Case 2:
  186. if ((DR->refersToEnclosingVariableOrCapture() &&
  187. isCapturedByReference(N, DR)) ||
  188. (IsRefParamOrCapture && VD->getType()->isReferenceType()))
  189. return true;
  190. while (!N->pred_empty()) {
  191. // FIXME: getStmtForDiagnostics() does nasty things in order to provide
  192. // a valid statement for body farms, do we need this behavior here?
  193. const Stmt *S = N->getStmtForDiagnostics();
  194. if (!S) {
  195. N = N->getFirstPred();
  196. continue;
  197. }
  198. if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  199. for (const Decl *D : DS->decls()) {
  200. // Once we reach the declaration of the VD we can return.
  201. if (D->getCanonicalDecl() == VD)
  202. return false;
  203. }
  204. }
  205. // Check the usage of the pass-by-ref function calls and adress-of operator
  206. // on VD and reference initialized by VD.
  207. ASTContext &ASTCtx =
  208. N->getLocationContext()->getAnalysisDeclContext()->getASTContext();
  209. // Case 3 and 4:
  210. auto Match =
  211. match(stmt(anyOf(callByRef(equalsNode(VD)), getAddrTo(equalsNode(VD)),
  212. assignedToRef(equalsNode(VD)))),
  213. *S, ASTCtx);
  214. if (!Match.empty())
  215. return true;
  216. N = N->getFirstPred();
  217. }
  218. // Reference parameter and reference capture will not be found.
  219. if (IsRefParamOrCapture)
  220. return false;
  221. llvm_unreachable("Reached root without finding the declaration of VD");
  222. }
  223. bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
  224. ExplodedNode *Pred, unsigned &maxStep) {
  225. if (!isLoopStmt(LoopStmt))
  226. return false;
  227. // TODO: Match the cases where the bound is not a concrete literal but an
  228. // integer with known value
  229. auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
  230. if (Matches.empty())
  231. return false;
  232. const auto *CounterVarRef = Matches[0].getNodeAs<DeclRefExpr>("initVarRef");
  233. llvm::APInt BoundNum =
  234. Matches[0].getNodeAs<IntegerLiteral>("boundNum")->getValue();
  235. llvm::APInt InitNum =
  236. Matches[0].getNodeAs<IntegerLiteral>("initNum")->getValue();
  237. auto CondOp = Matches[0].getNodeAs<BinaryOperator>("conditionOperator");
  238. if (InitNum.getBitWidth() != BoundNum.getBitWidth()) {
  239. InitNum = InitNum.zext(BoundNum.getBitWidth());
  240. BoundNum = BoundNum.zext(InitNum.getBitWidth());
  241. }
  242. if (CondOp->getOpcode() == BO_GE || CondOp->getOpcode() == BO_LE)
  243. maxStep = (BoundNum - InitNum + 1).abs().getZExtValue();
  244. else
  245. maxStep = (BoundNum - InitNum).abs().getZExtValue();
  246. // Check if the counter of the loop is not escaped before.
  247. return !isPossiblyEscaped(Pred, CounterVarRef);
  248. }
  249. bool madeNewBranch(ExplodedNode *N, const Stmt *LoopStmt) {
  250. const Stmt *S = nullptr;
  251. while (!N->pred_empty()) {
  252. if (N->succ_size() > 1)
  253. return true;
  254. ProgramPoint P = N->getLocation();
  255. if (std::optional<BlockEntrance> BE = P.getAs<BlockEntrance>())
  256. S = BE->getBlock()->getTerminatorStmt();
  257. if (S == LoopStmt)
  258. return false;
  259. N = N->getFirstPred();
  260. }
  261. llvm_unreachable("Reached root without encountering the previous step");
  262. }
  263. // updateLoopStack is called on every basic block, therefore it needs to be fast
  264. ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
  265. ExplodedNode *Pred, unsigned maxVisitOnPath) {
  266. auto State = Pred->getState();
  267. auto LCtx = Pred->getLocationContext();
  268. if (!isLoopStmt(LoopStmt))
  269. return State;
  270. auto LS = State->get<LoopStack>();
  271. if (!LS.isEmpty() && LoopStmt == LS.getHead().getLoopStmt() &&
  272. LCtx == LS.getHead().getLocationContext()) {
  273. if (LS.getHead().isUnrolled() && madeNewBranch(Pred, LoopStmt)) {
  274. State = State->set<LoopStack>(LS.getTail());
  275. State = State->add<LoopStack>(
  276. LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
  277. }
  278. return State;
  279. }
  280. unsigned maxStep;
  281. if (!shouldCompletelyUnroll(LoopStmt, ASTCtx, Pred, maxStep)) {
  282. State = State->add<LoopStack>(
  283. LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
  284. return State;
  285. }
  286. unsigned outerStep = (LS.isEmpty() ? 1 : LS.getHead().getMaxStep());
  287. unsigned innerMaxStep = maxStep * outerStep;
  288. if (innerMaxStep > MAXIMUM_STEP_UNROLLED)
  289. State = State->add<LoopStack>(
  290. LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
  291. else
  292. State = State->add<LoopStack>(
  293. LoopState::getUnrolled(LoopStmt, LCtx, innerMaxStep));
  294. return State;
  295. }
  296. bool isUnrolledState(ProgramStateRef State) {
  297. auto LS = State->get<LoopStack>();
  298. if (LS.isEmpty() || !LS.getHead().isUnrolled())
  299. return false;
  300. return true;
  301. }
  302. }
  303. }