1 //===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===// 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 #include "CFGBuildResult.h" 10 #include "clang/ASTMatchers/ASTMatchFinder.h" 11 #include "clang/Analysis/CFG.h" 12 #include "clang/Tooling/Tooling.h" 13 #include "gtest/gtest.h" 14 #include <string> 15 #include <vector> 16 17 namespace clang { 18 namespace analysis { 19 namespace { 20 21 // Constructing a CFG for a range-based for over a dependent type fails (but 22 // should not crash). 23 TEST(CFG, RangeBasedForOverDependentType) { 24 const char *Code = "class Foo;\n" 25 "template <typename T>\n" 26 "void f(const T &Range) {\n" 27 " for (const Foo *TheFoo : Range) {\n" 28 " }\n" 29 "}\n"; 30 EXPECT_EQ(BuildResult::SawFunctionBody, BuildCFG(Code).getStatus()); 31 } 32 33 // Constructing a CFG containing a delete expression on a dependent type should 34 // not crash. 35 TEST(CFG, DeleteExpressionOnDependentType) { 36 const char *Code = "template<class T>\n" 37 "void f(T t) {\n" 38 " delete t;\n" 39 "}\n"; 40 EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus()); 41 } 42 43 // Constructing a CFG on a function template with a variable of incomplete type 44 // should not crash. 45 TEST(CFG, VariableOfIncompleteType) { 46 const char *Code = "template<class T> void f() {\n" 47 " class Undefined;\n" 48 " Undefined u;\n" 49 "}\n"; 50 EXPECT_EQ(BuildResult::BuiltCFG, BuildCFG(Code).getStatus()); 51 } 52 53 TEST(CFG, IsLinear) { 54 auto expectLinear = [](bool IsLinear, const char *Code) { 55 BuildResult B = BuildCFG(Code); 56 EXPECT_EQ(BuildResult::BuiltCFG, B.getStatus()); 57 EXPECT_EQ(IsLinear, B.getCFG()->isLinear()); 58 }; 59 60 expectLinear(true, "void foo() {}"); 61 expectLinear(true, "void foo() { if (true) return; }"); 62 expectLinear(true, "void foo() { if constexpr (false); }"); 63 expectLinear(false, "void foo(bool coin) { if (coin) return; }"); 64 expectLinear(false, "void foo() { for(;;); }"); 65 expectLinear(false, "void foo() { do {} while (true); }"); 66 expectLinear(true, "void foo() { do {} while (false); }"); 67 expectLinear(true, "void foo() { foo(); }"); // Recursion is not our problem. 68 } 69 70 } // namespace 71 } // namespace analysis 72 } // namespace clang 73