LoopUnrolling.cpp 13 KB

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