-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathVariableMissingConstexpr.ql
70 lines (66 loc) · 2.44 KB
/
VariableMissingConstexpr.ql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* @id cpp/autosar/variable-missing-constexpr
* @name A7-1-2: The constexpr specifier shall be used for variables that can be determined at compile time
* @description Using 'constexpr' makes it clear that a variable is intended to be compile time
* constant.
* @kind problem
* @precision high
* @problem.severity recommendation
* @tags external/autosar/id/a7-1-2
* maintainability
* external/autosar/allocated-target/implementation
* external/autosar/enforcement/automated
* external/autosar/obligation/required
*/
import cpp
import codingstandards.cpp.autosar
import codingstandards.cpp.TrivialType
import codingstandards.cpp.SideEffect
import semmle.code.cpp.controlflow.SSA
import codingstandards.cpp.Expr
predicate isZeroInitializable(Variable v) {
not exists(v.getInitializer().getExpr()) and
(
v instanceof StaticStorageDurationVariable
or
isTypeZeroInitializable(v.getType())
)
}
predicate isTypeZeroInitializable(Type t) {
t.getUnspecifiedType() instanceof Class
or
t.getUnderlyingType() instanceof ArrayType
}
from Variable v
where
not isExcluded(v, ConstPackage::variableMissingConstexprQuery()) and
v.hasDefinition() and
not v.isConstexpr() and
not v instanceof Parameter and
not v.isAffectedByMacro() and
isLiteralType(v.getType()) and
// Unfortunately, `isConstant` is not sufficient here because it doesn't include calls to
// constexpr constructors, and does not take into account zero initialization
(
v.getInitializer().getExpr().isConstant()
or
any(Call call | isCompileTimeEvaluatedCall(call)) = v.getInitializer().getExpr()
or
isZeroInitializable(v)
or
// Value initialized
v.getInitializer().getExpr().(AggregateLiteral).getNumChild() = 0
) and
// Not modified directly
not exists(VariableEffect e | e.getTarget() = v) and
// No address taken in a non-const way
not v.getAnAccess().isAddressOfAccessNonConst() and
// Not assigned by a user in a constructor
not exists(ConstructorFieldInit cfi | cfi.getTarget() = v and not cfi.isCompilerGenerated()) and
// Ignore union members
not v.getDeclaringType() instanceof Union and
// Exclude variables in uninstantiated templates, as they may be incomplete
not v.isFromUninstantiatedTemplate(_) and
// Exclude compiler generated variables, which are not user controllable
not v.isCompilerGenerated()
select v, "Variable '" + v.getName() + "' could be marked 'constexpr'."