File: | build/source/clang/lib/AST/ExprConstant.cpp |
Warning: | line 8293, column 9 Access to field 'Callee' results in a dereference of a null pointer (loaded from variable 'CurrFrame') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// |
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 implements the Expr constant evaluator. |
10 | // |
11 | // Constant expression evaluation produces four main results: |
12 | // |
13 | // * A success/failure flag indicating whether constant folding was successful. |
14 | // This is the 'bool' return value used by most of the code in this file. A |
15 | // 'false' return value indicates that constant folding has failed, and any |
16 | // appropriate diagnostic has already been produced. |
17 | // |
18 | // * An evaluated result, valid only if constant folding has not failed. |
19 | // |
20 | // * A flag indicating if evaluation encountered (unevaluated) side-effects. |
21 | // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), |
22 | // where it is possible to determine the evaluated result regardless. |
23 | // |
24 | // * A set of notes indicating why the evaluation was not a constant expression |
25 | // (under the C++11 / C++1y rules only, at the moment), or, if folding failed |
26 | // too, why the expression could not be folded. |
27 | // |
28 | // If we are checking for a potential constant expression, failure to constant |
29 | // fold a potential constant sub-expression will be indicated by a 'false' |
30 | // return value (the expression could not be folded) and no diagnostic (the |
31 | // expression is not necessarily non-constant). |
32 | // |
33 | //===----------------------------------------------------------------------===// |
34 | |
35 | #include "Interp/Context.h" |
36 | #include "Interp/Frame.h" |
37 | #include "Interp/State.h" |
38 | #include "clang/AST/APValue.h" |
39 | #include "clang/AST/ASTContext.h" |
40 | #include "clang/AST/ASTDiagnostic.h" |
41 | #include "clang/AST/ASTLambda.h" |
42 | #include "clang/AST/Attr.h" |
43 | #include "clang/AST/CXXInheritance.h" |
44 | #include "clang/AST/CharUnits.h" |
45 | #include "clang/AST/CurrentSourceLocExprScope.h" |
46 | #include "clang/AST/Expr.h" |
47 | #include "clang/AST/OSLog.h" |
48 | #include "clang/AST/OptionalDiagnostic.h" |
49 | #include "clang/AST/RecordLayout.h" |
50 | #include "clang/AST/StmtVisitor.h" |
51 | #include "clang/AST/TypeLoc.h" |
52 | #include "clang/Basic/Builtins.h" |
53 | #include "clang/Basic/TargetInfo.h" |
54 | #include "llvm/ADT/APFixedPoint.h" |
55 | #include "llvm/ADT/SmallBitVector.h" |
56 | #include "llvm/Support/Debug.h" |
57 | #include "llvm/Support/SaveAndRestore.h" |
58 | #include "llvm/Support/TimeProfiler.h" |
59 | #include "llvm/Support/raw_ostream.h" |
60 | #include <cstring> |
61 | #include <functional> |
62 | #include <optional> |
63 | |
64 | #define DEBUG_TYPE"exprconstant" "exprconstant" |
65 | |
66 | using namespace clang; |
67 | using llvm::APFixedPoint; |
68 | using llvm::APInt; |
69 | using llvm::APSInt; |
70 | using llvm::APFloat; |
71 | using llvm::FixedPointSemantics; |
72 | |
73 | namespace { |
74 | struct LValue; |
75 | class CallStackFrame; |
76 | class EvalInfo; |
77 | |
78 | using SourceLocExprScopeGuard = |
79 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; |
80 | |
81 | static QualType getType(APValue::LValueBase B) { |
82 | return B.getType(); |
83 | } |
84 | |
85 | /// Get an LValue path entry, which is known to not be an array index, as a |
86 | /// field declaration. |
87 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { |
88 | return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); |
89 | } |
90 | /// Get an LValue path entry, which is known to not be an array index, as a |
91 | /// base class declaration. |
92 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { |
93 | return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); |
94 | } |
95 | /// Determine whether this LValue path entry for a base class names a virtual |
96 | /// base class. |
97 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { |
98 | return E.getAsBaseOrMember().getInt(); |
99 | } |
100 | |
101 | /// Given an expression, determine the type used to store the result of |
102 | /// evaluating that expression. |
103 | static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { |
104 | if (E->isPRValue()) |
105 | return E->getType(); |
106 | return Ctx.getLValueReferenceType(E->getType()); |
107 | } |
108 | |
109 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. |
110 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { |
111 | if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) |
112 | return DirectCallee->getAttr<AllocSizeAttr>(); |
113 | if (const Decl *IndirectCallee = CE->getCalleeDecl()) |
114 | return IndirectCallee->getAttr<AllocSizeAttr>(); |
115 | return nullptr; |
116 | } |
117 | |
118 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. |
119 | /// This will look through a single cast. |
120 | /// |
121 | /// Returns null if we couldn't unwrap a function with alloc_size. |
122 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { |
123 | if (!E->getType()->isPointerType()) |
124 | return nullptr; |
125 | |
126 | E = E->IgnoreParens(); |
127 | // If we're doing a variable assignment from e.g. malloc(N), there will |
128 | // probably be a cast of some kind. In exotic cases, we might also see a |
129 | // top-level ExprWithCleanups. Ignore them either way. |
130 | if (const auto *FE = dyn_cast<FullExpr>(E)) |
131 | E = FE->getSubExpr()->IgnoreParens(); |
132 | |
133 | if (const auto *Cast = dyn_cast<CastExpr>(E)) |
134 | E = Cast->getSubExpr()->IgnoreParens(); |
135 | |
136 | if (const auto *CE = dyn_cast<CallExpr>(E)) |
137 | return getAllocSizeAttr(CE) ? CE : nullptr; |
138 | return nullptr; |
139 | } |
140 | |
141 | /// Determines whether or not the given Base contains a call to a function |
142 | /// with the alloc_size attribute. |
143 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { |
144 | const auto *E = Base.dyn_cast<const Expr *>(); |
145 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); |
146 | } |
147 | |
148 | /// Determines whether the given kind of constant expression is only ever |
149 | /// used for name mangling. If so, it's permitted to reference things that we |
150 | /// can't generate code for (in particular, dllimported functions). |
151 | static bool isForManglingOnly(ConstantExprKind Kind) { |
152 | switch (Kind) { |
153 | case ConstantExprKind::Normal: |
154 | case ConstantExprKind::ClassTemplateArgument: |
155 | case ConstantExprKind::ImmediateInvocation: |
156 | // Note that non-type template arguments of class type are emitted as |
157 | // template parameter objects. |
158 | return false; |
159 | |
160 | case ConstantExprKind::NonClassTemplateArgument: |
161 | return true; |
162 | } |
163 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "clang/lib/AST/ExprConstant.cpp", 163); |
164 | } |
165 | |
166 | static bool isTemplateArgument(ConstantExprKind Kind) { |
167 | switch (Kind) { |
168 | case ConstantExprKind::Normal: |
169 | case ConstantExprKind::ImmediateInvocation: |
170 | return false; |
171 | |
172 | case ConstantExprKind::ClassTemplateArgument: |
173 | case ConstantExprKind::NonClassTemplateArgument: |
174 | return true; |
175 | } |
176 | llvm_unreachable("unknown ConstantExprKind")::llvm::llvm_unreachable_internal("unknown ConstantExprKind", "clang/lib/AST/ExprConstant.cpp", 176); |
177 | } |
178 | |
179 | /// The bound to claim that an array of unknown bound has. |
180 | /// The value in MostDerivedArraySize is undefined in this case. So, set it |
181 | /// to an arbitrary value that's likely to loudly break things if it's used. |
182 | static const uint64_t AssumedSizeForUnsizedArray = |
183 | std::numeric_limits<uint64_t>::max() / 2; |
184 | |
185 | /// Determines if an LValue with the given LValueBase will have an unsized |
186 | /// array in its designator. |
187 | /// Find the path length and type of the most-derived subobject in the given |
188 | /// path, and find the size of the containing array, if any. |
189 | static unsigned |
190 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, |
191 | ArrayRef<APValue::LValuePathEntry> Path, |
192 | uint64_t &ArraySize, QualType &Type, bool &IsArray, |
193 | bool &FirstEntryIsUnsizedArray) { |
194 | // This only accepts LValueBases from APValues, and APValues don't support |
195 | // arrays that lack size info. |
196 | assert(!isBaseAnAllocSizeCall(Base) &&(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__ )) |
197 | "Unsized arrays shouldn't appear here")(static_cast <bool> (!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here") ? void (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "clang/lib/AST/ExprConstant.cpp", 197, __extension__ __PRETTY_FUNCTION__ )); |
198 | unsigned MostDerivedLength = 0; |
199 | Type = getType(Base); |
200 | |
201 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { |
202 | if (Type->isArrayType()) { |
203 | const ArrayType *AT = Ctx.getAsArrayType(Type); |
204 | Type = AT->getElementType(); |
205 | MostDerivedLength = I + 1; |
206 | IsArray = true; |
207 | |
208 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { |
209 | ArraySize = CAT->getSize().getZExtValue(); |
210 | } else { |
211 | assert(I == 0 && "unexpected unsized array designator")(static_cast <bool> (I == 0 && "unexpected unsized array designator" ) ? void (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\"" , "clang/lib/AST/ExprConstant.cpp", 211, __extension__ __PRETTY_FUNCTION__ )); |
212 | FirstEntryIsUnsizedArray = true; |
213 | ArraySize = AssumedSizeForUnsizedArray; |
214 | } |
215 | } else if (Type->isAnyComplexType()) { |
216 | const ComplexType *CT = Type->castAs<ComplexType>(); |
217 | Type = CT->getElementType(); |
218 | ArraySize = 2; |
219 | MostDerivedLength = I + 1; |
220 | IsArray = true; |
221 | } else if (const FieldDecl *FD = getAsField(Path[I])) { |
222 | Type = FD->getType(); |
223 | ArraySize = 0; |
224 | MostDerivedLength = I + 1; |
225 | IsArray = false; |
226 | } else { |
227 | // Path[I] describes a base class. |
228 | ArraySize = 0; |
229 | IsArray = false; |
230 | } |
231 | } |
232 | return MostDerivedLength; |
233 | } |
234 | |
235 | /// A path from a glvalue to a subobject of that glvalue. |
236 | struct SubobjectDesignator { |
237 | /// True if the subobject was named in a manner not supported by C++11. Such |
238 | /// lvalues can still be folded, but they are not core constant expressions |
239 | /// and we cannot perform lvalue-to-rvalue conversions on them. |
240 | unsigned Invalid : 1; |
241 | |
242 | /// Is this a pointer one past the end of an object? |
243 | unsigned IsOnePastTheEnd : 1; |
244 | |
245 | /// Indicator of whether the first entry is an unsized array. |
246 | unsigned FirstEntryIsAnUnsizedArray : 1; |
247 | |
248 | /// Indicator of whether the most-derived object is an array element. |
249 | unsigned MostDerivedIsArrayElement : 1; |
250 | |
251 | /// The length of the path to the most-derived object of which this is a |
252 | /// subobject. |
253 | unsigned MostDerivedPathLength : 28; |
254 | |
255 | /// The size of the array of which the most-derived object is an element. |
256 | /// This will always be 0 if the most-derived object is not an array |
257 | /// element. 0 is not an indicator of whether or not the most-derived object |
258 | /// is an array, however, because 0-length arrays are allowed. |
259 | /// |
260 | /// If the current array is an unsized array, the value of this is |
261 | /// undefined. |
262 | uint64_t MostDerivedArraySize; |
263 | |
264 | /// The type of the most derived object referred to by this address. |
265 | QualType MostDerivedType; |
266 | |
267 | typedef APValue::LValuePathEntry PathEntry; |
268 | |
269 | /// The entries on the path from the glvalue to the designated subobject. |
270 | SmallVector<PathEntry, 8> Entries; |
271 | |
272 | SubobjectDesignator() : Invalid(true) {} |
273 | |
274 | explicit SubobjectDesignator(QualType T) |
275 | : Invalid(false), IsOnePastTheEnd(false), |
276 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), |
277 | MostDerivedPathLength(0), MostDerivedArraySize(0), |
278 | MostDerivedType(T) {} |
279 | |
280 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) |
281 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), |
282 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), |
283 | MostDerivedPathLength(0), MostDerivedArraySize(0) { |
284 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?")(static_cast <bool> (V.isLValue() && "Non-LValue used to make an LValue designator?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\"" , "clang/lib/AST/ExprConstant.cpp", 284, __extension__ __PRETTY_FUNCTION__ )); |
285 | if (!Invalid) { |
286 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); |
287 | ArrayRef<PathEntry> VEntries = V.getLValuePath(); |
288 | Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); |
289 | if (V.getLValueBase()) { |
290 | bool IsArray = false; |
291 | bool FirstIsUnsizedArray = false; |
292 | MostDerivedPathLength = findMostDerivedSubobject( |
293 | Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, |
294 | MostDerivedType, IsArray, FirstIsUnsizedArray); |
295 | MostDerivedIsArrayElement = IsArray; |
296 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; |
297 | } |
298 | } |
299 | } |
300 | |
301 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, |
302 | unsigned NewLength) { |
303 | if (Invalid) |
304 | return; |
305 | |
306 | assert(Base && "cannot truncate path for null pointer")(static_cast <bool> (Base && "cannot truncate path for null pointer" ) ? void (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\"" , "clang/lib/AST/ExprConstant.cpp", 306, __extension__ __PRETTY_FUNCTION__ )); |
307 | assert(NewLength <= Entries.size() && "not a truncation")(static_cast <bool> (NewLength <= Entries.size() && "not a truncation") ? void (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\"" , "clang/lib/AST/ExprConstant.cpp", 307, __extension__ __PRETTY_FUNCTION__ )); |
308 | |
309 | if (NewLength == Entries.size()) |
310 | return; |
311 | Entries.resize(NewLength); |
312 | |
313 | bool IsArray = false; |
314 | bool FirstIsUnsizedArray = false; |
315 | MostDerivedPathLength = findMostDerivedSubobject( |
316 | Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, |
317 | FirstIsUnsizedArray); |
318 | MostDerivedIsArrayElement = IsArray; |
319 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; |
320 | } |
321 | |
322 | void setInvalid() { |
323 | Invalid = true; |
324 | Entries.clear(); |
325 | } |
326 | |
327 | /// Determine whether the most derived subobject is an array without a |
328 | /// known bound. |
329 | bool isMostDerivedAnUnsizedArray() const { |
330 | assert(!Invalid && "Calling this makes no sense on invalid designators")(static_cast <bool> (!Invalid && "Calling this makes no sense on invalid designators" ) ? void (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\"" , "clang/lib/AST/ExprConstant.cpp", 330, __extension__ __PRETTY_FUNCTION__ )); |
331 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; |
332 | } |
333 | |
334 | /// Determine what the most derived array's size is. Results in an assertion |
335 | /// failure if the most derived array lacks a size. |
336 | uint64_t getMostDerivedArraySize() const { |
337 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")(static_cast <bool> (!isMostDerivedAnUnsizedArray() && "Unsized array has no size") ? void (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\"" , "clang/lib/AST/ExprConstant.cpp", 337, __extension__ __PRETTY_FUNCTION__ )); |
338 | return MostDerivedArraySize; |
339 | } |
340 | |
341 | /// Determine whether this is a one-past-the-end pointer. |
342 | bool isOnePastTheEnd() const { |
343 | assert(!Invalid)(static_cast <bool> (!Invalid) ? void (0) : __assert_fail ("!Invalid", "clang/lib/AST/ExprConstant.cpp", 343, __extension__ __PRETTY_FUNCTION__)); |
344 | if (IsOnePastTheEnd) |
345 | return true; |
346 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && |
347 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == |
348 | MostDerivedArraySize) |
349 | return true; |
350 | return false; |
351 | } |
352 | |
353 | /// Get the range of valid index adjustments in the form |
354 | /// {maximum value that can be subtracted from this pointer, |
355 | /// maximum value that can be added to this pointer} |
356 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { |
357 | if (Invalid || isMostDerivedAnUnsizedArray()) |
358 | return {0, 0}; |
359 | |
360 | // [expr.add]p4: For the purposes of these operators, a pointer to a |
361 | // nonarray object behaves the same as a pointer to the first element of |
362 | // an array of length one with the type of the object as its element type. |
363 | bool IsArray = MostDerivedPathLength == Entries.size() && |
364 | MostDerivedIsArrayElement; |
365 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() |
366 | : (uint64_t)IsOnePastTheEnd; |
367 | uint64_t ArraySize = |
368 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; |
369 | return {ArrayIndex, ArraySize - ArrayIndex}; |
370 | } |
371 | |
372 | /// Check that this refers to a valid subobject. |
373 | bool isValidSubobject() const { |
374 | if (Invalid) |
375 | return false; |
376 | return !isOnePastTheEnd(); |
377 | } |
378 | /// Check that this refers to a valid subobject, and if not, produce a |
379 | /// relevant diagnostic and set the designator as invalid. |
380 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); |
381 | |
382 | /// Get the type of the designated object. |
383 | QualType getType(ASTContext &Ctx) const { |
384 | assert(!Invalid && "invalid designator has no subobject type")(static_cast <bool> (!Invalid && "invalid designator has no subobject type" ) ? void (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\"" , "clang/lib/AST/ExprConstant.cpp", 384, __extension__ __PRETTY_FUNCTION__ )); |
385 | return MostDerivedPathLength == Entries.size() |
386 | ? MostDerivedType |
387 | : Ctx.getRecordType(getAsBaseClass(Entries.back())); |
388 | } |
389 | |
390 | /// Update this designator to refer to the first element within this array. |
391 | void addArrayUnchecked(const ConstantArrayType *CAT) { |
392 | Entries.push_back(PathEntry::ArrayIndex(0)); |
393 | |
394 | // This is a most-derived object. |
395 | MostDerivedType = CAT->getElementType(); |
396 | MostDerivedIsArrayElement = true; |
397 | MostDerivedArraySize = CAT->getSize().getZExtValue(); |
398 | MostDerivedPathLength = Entries.size(); |
399 | } |
400 | /// Update this designator to refer to the first element within the array of |
401 | /// elements of type T. This is an array of unknown size. |
402 | void addUnsizedArrayUnchecked(QualType ElemTy) { |
403 | Entries.push_back(PathEntry::ArrayIndex(0)); |
404 | |
405 | MostDerivedType = ElemTy; |
406 | MostDerivedIsArrayElement = true; |
407 | // The value in MostDerivedArraySize is undefined in this case. So, set it |
408 | // to an arbitrary value that's likely to loudly break things if it's |
409 | // used. |
410 | MostDerivedArraySize = AssumedSizeForUnsizedArray; |
411 | MostDerivedPathLength = Entries.size(); |
412 | } |
413 | /// Update this designator to refer to the given base or member of this |
414 | /// object. |
415 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { |
416 | Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); |
417 | |
418 | // If this isn't a base class, it's a new most-derived object. |
419 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { |
420 | MostDerivedType = FD->getType(); |
421 | MostDerivedIsArrayElement = false; |
422 | MostDerivedArraySize = 0; |
423 | MostDerivedPathLength = Entries.size(); |
424 | } |
425 | } |
426 | /// Update this designator to refer to the given complex component. |
427 | void addComplexUnchecked(QualType EltTy, bool Imag) { |
428 | Entries.push_back(PathEntry::ArrayIndex(Imag)); |
429 | |
430 | // This is technically a most-derived object, though in practice this |
431 | // is unlikely to matter. |
432 | MostDerivedType = EltTy; |
433 | MostDerivedIsArrayElement = true; |
434 | MostDerivedArraySize = 2; |
435 | MostDerivedPathLength = Entries.size(); |
436 | } |
437 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); |
438 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, |
439 | const APSInt &N); |
440 | /// Add N to the address of this subobject. |
441 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { |
442 | if (Invalid || !N) return; |
443 | uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); |
444 | if (isMostDerivedAnUnsizedArray()) { |
445 | diagnoseUnsizedArrayPointerArithmetic(Info, E); |
446 | // Can't verify -- trust that the user is doing the right thing (or if |
447 | // not, trust that the caller will catch the bad behavior). |
448 | // FIXME: Should we reject if this overflows, at least? |
449 | Entries.back() = PathEntry::ArrayIndex( |
450 | Entries.back().getAsArrayIndex() + TruncatedN); |
451 | return; |
452 | } |
453 | |
454 | // [expr.add]p4: For the purposes of these operators, a pointer to a |
455 | // nonarray object behaves the same as a pointer to the first element of |
456 | // an array of length one with the type of the object as its element type. |
457 | bool IsArray = MostDerivedPathLength == Entries.size() && |
458 | MostDerivedIsArrayElement; |
459 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() |
460 | : (uint64_t)IsOnePastTheEnd; |
461 | uint64_t ArraySize = |
462 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; |
463 | |
464 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { |
465 | // Calculate the actual index in a wide enough type, so we can include |
466 | // it in the note. |
467 | N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); |
468 | (llvm::APInt&)N += ArrayIndex; |
469 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")(static_cast <bool> (N.ugt(ArraySize) && "bounds check failed for in-bounds index" ) ? void (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 469, __extension__ __PRETTY_FUNCTION__ )); |
470 | diagnosePointerArithmetic(Info, E, N); |
471 | setInvalid(); |
472 | return; |
473 | } |
474 | |
475 | ArrayIndex += TruncatedN; |
476 | assert(ArrayIndex <= ArraySize &&(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__ )) |
477 | "bounds check succeeded for out-of-bounds index")(static_cast <bool> (ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index") ? void (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "clang/lib/AST/ExprConstant.cpp", 477, __extension__ __PRETTY_FUNCTION__ )); |
478 | |
479 | if (IsArray) |
480 | Entries.back() = PathEntry::ArrayIndex(ArrayIndex); |
481 | else |
482 | IsOnePastTheEnd = (ArrayIndex != 0); |
483 | } |
484 | }; |
485 | |
486 | /// A scope at the end of which an object can need to be destroyed. |
487 | enum class ScopeKind { |
488 | Block, |
489 | FullExpression, |
490 | Call |
491 | }; |
492 | |
493 | /// A reference to a particular call and its arguments. |
494 | struct CallRef { |
495 | CallRef() : OrigCallee(), CallIndex(0), Version() {} |
496 | CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) |
497 | : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} |
498 | |
499 | explicit operator bool() const { return OrigCallee; } |
500 | |
501 | /// Get the parameter that the caller initialized, corresponding to the |
502 | /// given parameter in the callee. |
503 | const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { |
504 | return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) |
505 | : PVD; |
506 | } |
507 | |
508 | /// The callee at the point where the arguments were evaluated. This might |
509 | /// be different from the actual callee (a different redeclaration, or a |
510 | /// virtual override), but this function's parameters are the ones that |
511 | /// appear in the parameter map. |
512 | const FunctionDecl *OrigCallee; |
513 | /// The call index of the frame that holds the argument values. |
514 | unsigned CallIndex; |
515 | /// The version of the parameters corresponding to this call. |
516 | unsigned Version; |
517 | }; |
518 | |
519 | /// A stack frame in the constexpr call stack. |
520 | class CallStackFrame : public interp::Frame { |
521 | public: |
522 | EvalInfo &Info; |
523 | |
524 | /// Parent - The caller of this stack frame. |
525 | CallStackFrame *Caller; |
526 | |
527 | /// Callee - The function which was called. |
528 | const FunctionDecl *Callee; |
529 | |
530 | /// This - The binding for the this pointer in this call, if any. |
531 | const LValue *This; |
532 | |
533 | /// Information on how to find the arguments to this call. Our arguments |
534 | /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a |
535 | /// key and this value as the version. |
536 | CallRef Arguments; |
537 | |
538 | /// Source location information about the default argument or default |
539 | /// initializer expression we're evaluating, if any. |
540 | CurrentSourceLocExprScope CurSourceLocExprScope; |
541 | |
542 | // Note that we intentionally use std::map here so that references to |
543 | // values are stable. |
544 | typedef std::pair<const void *, unsigned> MapKeyTy; |
545 | typedef std::map<MapKeyTy, APValue> MapTy; |
546 | /// Temporaries - Temporary lvalues materialized within this stack frame. |
547 | MapTy Temporaries; |
548 | |
549 | /// CallLoc - The location of the call expression for this call. |
550 | SourceLocation CallLoc; |
551 | |
552 | /// Index - The call index of this call. |
553 | unsigned Index; |
554 | |
555 | /// The stack of integers for tracking version numbers for temporaries. |
556 | SmallVector<unsigned, 2> TempVersionStack = {1}; |
557 | unsigned CurTempVersion = TempVersionStack.back(); |
558 | |
559 | unsigned getTempVersion() const { return TempVersionStack.back(); } |
560 | |
561 | void pushTempVersion() { |
562 | TempVersionStack.push_back(++CurTempVersion); |
563 | } |
564 | |
565 | void popTempVersion() { |
566 | TempVersionStack.pop_back(); |
567 | } |
568 | |
569 | CallRef createCall(const FunctionDecl *Callee) { |
570 | return {Callee, Index, ++CurTempVersion}; |
571 | } |
572 | |
573 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact |
574 | // on the overall stack usage of deeply-recursing constexpr evaluations. |
575 | // (We should cache this map rather than recomputing it repeatedly.) |
576 | // But let's try this and see how it goes; we can look into caching the map |
577 | // as a later change. |
578 | |
579 | /// LambdaCaptureFields - Mapping from captured variables/this to |
580 | /// corresponding data members in the closure class. |
581 | llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; |
582 | FieldDecl *LambdaThisCaptureField; |
583 | |
584 | CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, |
585 | const FunctionDecl *Callee, const LValue *This, |
586 | CallRef Arguments); |
587 | ~CallStackFrame(); |
588 | |
589 | // Return the temporary for Key whose version number is Version. |
590 | APValue *getTemporary(const void *Key, unsigned Version) { |
591 | MapKeyTy KV(Key, Version); |
592 | auto LB = Temporaries.lower_bound(KV); |
593 | if (LB != Temporaries.end() && LB->first == KV) |
594 | return &LB->second; |
595 | return nullptr; |
596 | } |
597 | |
598 | // Return the current temporary for Key in the map. |
599 | APValue *getCurrentTemporary(const void *Key) { |
600 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); |
601 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) |
602 | return &std::prev(UB)->second; |
603 | return nullptr; |
604 | } |
605 | |
606 | // Return the version number of the current temporary for Key. |
607 | unsigned getCurrentTemporaryVersion(const void *Key) const { |
608 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); |
609 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) |
610 | return std::prev(UB)->first.second; |
611 | return 0; |
612 | } |
613 | |
614 | /// Allocate storage for an object of type T in this stack frame. |
615 | /// Populates LV with a handle to the created object. Key identifies |
616 | /// the temporary within the stack frame, and must not be reused without |
617 | /// bumping the temporary version number. |
618 | template<typename KeyT> |
619 | APValue &createTemporary(const KeyT *Key, QualType T, |
620 | ScopeKind Scope, LValue &LV); |
621 | |
622 | /// Allocate storage for a parameter of a function call made in this frame. |
623 | APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); |
624 | |
625 | void describe(llvm::raw_ostream &OS) override; |
626 | |
627 | Frame *getCaller() const override { return Caller; } |
628 | SourceLocation getCallLocation() const override { return CallLoc; } |
629 | const FunctionDecl *getCallee() const override { return Callee; } |
630 | |
631 | bool isStdFunction() const { |
632 | for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) |
633 | if (DC->isStdNamespace()) |
634 | return true; |
635 | return false; |
636 | } |
637 | |
638 | private: |
639 | APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, |
640 | ScopeKind Scope); |
641 | }; |
642 | |
643 | /// Temporarily override 'this'. |
644 | class ThisOverrideRAII { |
645 | public: |
646 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) |
647 | : Frame(Frame), OldThis(Frame.This) { |
648 | if (Enable) |
649 | Frame.This = NewThis; |
650 | } |
651 | ~ThisOverrideRAII() { |
652 | Frame.This = OldThis; |
653 | } |
654 | private: |
655 | CallStackFrame &Frame; |
656 | const LValue *OldThis; |
657 | }; |
658 | |
659 | // A shorthand time trace scope struct, prints source range, for example |
660 | // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}} |
661 | class ExprTimeTraceScope { |
662 | public: |
663 | ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name) |
664 | : TimeScope(Name, [E, &Ctx] { |
665 | return E->getSourceRange().printToString(Ctx.getSourceManager()); |
666 | }) {} |
667 | |
668 | private: |
669 | llvm::TimeTraceScope TimeScope; |
670 | }; |
671 | } |
672 | |
673 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, |
674 | const LValue &This, QualType ThisType); |
675 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, |
676 | APValue::LValueBase LVBase, APValue &Value, |
677 | QualType T); |
678 | |
679 | namespace { |
680 | /// A cleanup, and a flag indicating whether it is lifetime-extended. |
681 | class Cleanup { |
682 | llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; |
683 | APValue::LValueBase Base; |
684 | QualType T; |
685 | |
686 | public: |
687 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, |
688 | ScopeKind Scope) |
689 | : Value(Val, Scope), Base(Base), T(T) {} |
690 | |
691 | /// Determine whether this cleanup should be performed at the end of the |
692 | /// given kind of scope. |
693 | bool isDestroyedAtEndOf(ScopeKind K) const { |
694 | return (int)Value.getInt() >= (int)K; |
695 | } |
696 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { |
697 | if (RunDestructors) { |
698 | SourceLocation Loc; |
699 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) |
700 | Loc = VD->getLocation(); |
701 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) |
702 | Loc = E->getExprLoc(); |
703 | return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); |
704 | } |
705 | *Value.getPointer() = APValue(); |
706 | return true; |
707 | } |
708 | |
709 | bool hasSideEffect() { |
710 | return T.isDestructedType(); |
711 | } |
712 | }; |
713 | |
714 | /// A reference to an object whose construction we are currently evaluating. |
715 | struct ObjectUnderConstruction { |
716 | APValue::LValueBase Base; |
717 | ArrayRef<APValue::LValuePathEntry> Path; |
718 | friend bool operator==(const ObjectUnderConstruction &LHS, |
719 | const ObjectUnderConstruction &RHS) { |
720 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; |
721 | } |
722 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { |
723 | return llvm::hash_combine(Obj.Base, Obj.Path); |
724 | } |
725 | }; |
726 | enum class ConstructionPhase { |
727 | None, |
728 | Bases, |
729 | AfterBases, |
730 | AfterFields, |
731 | Destroying, |
732 | DestroyingBases |
733 | }; |
734 | } |
735 | |
736 | namespace llvm { |
737 | template<> struct DenseMapInfo<ObjectUnderConstruction> { |
738 | using Base = DenseMapInfo<APValue::LValueBase>; |
739 | static ObjectUnderConstruction getEmptyKey() { |
740 | return {Base::getEmptyKey(), {}}; } |
741 | static ObjectUnderConstruction getTombstoneKey() { |
742 | return {Base::getTombstoneKey(), {}}; |
743 | } |
744 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { |
745 | return hash_value(Object); |
746 | } |
747 | static bool isEqual(const ObjectUnderConstruction &LHS, |
748 | const ObjectUnderConstruction &RHS) { |
749 | return LHS == RHS; |
750 | } |
751 | }; |
752 | } |
753 | |
754 | namespace { |
755 | /// A dynamically-allocated heap object. |
756 | struct DynAlloc { |
757 | /// The value of this heap-allocated object. |
758 | APValue Value; |
759 | /// The allocating expression; used for diagnostics. Either a CXXNewExpr |
760 | /// or a CallExpr (the latter is for direct calls to operator new inside |
761 | /// std::allocator<T>::allocate). |
762 | const Expr *AllocExpr = nullptr; |
763 | |
764 | enum Kind { |
765 | New, |
766 | ArrayNew, |
767 | StdAllocator |
768 | }; |
769 | |
770 | /// Get the kind of the allocation. This must match between allocation |
771 | /// and deallocation. |
772 | Kind getKind() const { |
773 | if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) |
774 | return NE->isArray() ? ArrayNew : New; |
775 | assert(isa<CallExpr>(AllocExpr))(static_cast <bool> (isa<CallExpr>(AllocExpr)) ? void (0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "clang/lib/AST/ExprConstant.cpp" , 775, __extension__ __PRETTY_FUNCTION__)); |
776 | return StdAllocator; |
777 | } |
778 | }; |
779 | |
780 | struct DynAllocOrder { |
781 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { |
782 | return L.getIndex() < R.getIndex(); |
783 | } |
784 | }; |
785 | |
786 | /// EvalInfo - This is a private struct used by the evaluator to capture |
787 | /// information about a subexpression as it is folded. It retains information |
788 | /// about the AST context, but also maintains information about the folded |
789 | /// expression. |
790 | /// |
791 | /// If an expression could be evaluated, it is still possible it is not a C |
792 | /// "integer constant expression" or constant expression. If not, this struct |
793 | /// captures information about how and why not. |
794 | /// |
795 | /// One bit of information passed *into* the request for constant folding |
796 | /// indicates whether the subexpression is "evaluated" or not according to C |
797 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can |
798 | /// evaluate the expression regardless of what the RHS is, but C only allows |
799 | /// certain things in certain situations. |
800 | class EvalInfo : public interp::State { |
801 | public: |
802 | ASTContext &Ctx; |
803 | |
804 | /// EvalStatus - Contains information about the evaluation. |
805 | Expr::EvalStatus &EvalStatus; |
806 | |
807 | /// CurrentCall - The top of the constexpr call stack. |
808 | CallStackFrame *CurrentCall; |
809 | |
810 | /// CallStackDepth - The number of calls in the call stack right now. |
811 | unsigned CallStackDepth; |
812 | |
813 | /// NextCallIndex - The next call index to assign. |
814 | unsigned NextCallIndex; |
815 | |
816 | /// StepsLeft - The remaining number of evaluation steps we're permitted |
817 | /// to perform. This is essentially a limit for the number of statements |
818 | /// we will evaluate. |
819 | unsigned StepsLeft; |
820 | |
821 | /// Enable the experimental new constant interpreter. If an expression is |
822 | /// not supported by the interpreter, an error is triggered. |
823 | bool EnableNewConstInterp; |
824 | |
825 | /// BottomFrame - The frame in which evaluation started. This must be |
826 | /// initialized after CurrentCall and CallStackDepth. |
827 | CallStackFrame BottomFrame; |
828 | |
829 | /// A stack of values whose lifetimes end at the end of some surrounding |
830 | /// evaluation frame. |
831 | llvm::SmallVector<Cleanup, 16> CleanupStack; |
832 | |
833 | /// EvaluatingDecl - This is the declaration whose initializer is being |
834 | /// evaluated, if any. |
835 | APValue::LValueBase EvaluatingDecl; |
836 | |
837 | enum class EvaluatingDeclKind { |
838 | None, |
839 | /// We're evaluating the construction of EvaluatingDecl. |
840 | Ctor, |
841 | /// We're evaluating the destruction of EvaluatingDecl. |
842 | Dtor, |
843 | }; |
844 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; |
845 | |
846 | /// EvaluatingDeclValue - This is the value being constructed for the |
847 | /// declaration whose initializer is being evaluated, if any. |
848 | APValue *EvaluatingDeclValue; |
849 | |
850 | /// Set of objects that are currently being constructed. |
851 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> |
852 | ObjectsUnderConstruction; |
853 | |
854 | /// Current heap allocations, along with the location where each was |
855 | /// allocated. We use std::map here because we need stable addresses |
856 | /// for the stored APValues. |
857 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; |
858 | |
859 | /// The number of heap allocations performed so far in this evaluation. |
860 | unsigned NumHeapAllocs = 0; |
861 | |
862 | struct EvaluatingConstructorRAII { |
863 | EvalInfo &EI; |
864 | ObjectUnderConstruction Object; |
865 | bool DidInsert; |
866 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, |
867 | bool HasBases) |
868 | : EI(EI), Object(Object) { |
869 | DidInsert = |
870 | EI.ObjectsUnderConstruction |
871 | .insert({Object, HasBases ? ConstructionPhase::Bases |
872 | : ConstructionPhase::AfterBases}) |
873 | .second; |
874 | } |
875 | void finishedConstructingBases() { |
876 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; |
877 | } |
878 | void finishedConstructingFields() { |
879 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; |
880 | } |
881 | ~EvaluatingConstructorRAII() { |
882 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); |
883 | } |
884 | }; |
885 | |
886 | struct EvaluatingDestructorRAII { |
887 | EvalInfo &EI; |
888 | ObjectUnderConstruction Object; |
889 | bool DidInsert; |
890 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) |
891 | : EI(EI), Object(Object) { |
892 | DidInsert = EI.ObjectsUnderConstruction |
893 | .insert({Object, ConstructionPhase::Destroying}) |
894 | .second; |
895 | } |
896 | void startedDestroyingBases() { |
897 | EI.ObjectsUnderConstruction[Object] = |
898 | ConstructionPhase::DestroyingBases; |
899 | } |
900 | ~EvaluatingDestructorRAII() { |
901 | if (DidInsert) |
902 | EI.ObjectsUnderConstruction.erase(Object); |
903 | } |
904 | }; |
905 | |
906 | ConstructionPhase |
907 | isEvaluatingCtorDtor(APValue::LValueBase Base, |
908 | ArrayRef<APValue::LValuePathEntry> Path) { |
909 | return ObjectsUnderConstruction.lookup({Base, Path}); |
910 | } |
911 | |
912 | /// If we're currently speculatively evaluating, the outermost call stack |
913 | /// depth at which we can mutate state, otherwise 0. |
914 | unsigned SpeculativeEvaluationDepth = 0; |
915 | |
916 | /// The current array initialization index, if we're performing array |
917 | /// initialization. |
918 | uint64_t ArrayInitIndex = -1; |
919 | |
920 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further |
921 | /// notes attached to it will also be stored, otherwise they will not be. |
922 | bool HasActiveDiagnostic; |
923 | |
924 | /// Have we emitted a diagnostic explaining why we couldn't constant |
925 | /// fold (not just why it's not strictly a constant expression)? |
926 | bool HasFoldFailureDiagnostic; |
927 | |
928 | /// Whether we're checking that an expression is a potential constant |
929 | /// expression. If so, do not fail on constructs that could become constant |
930 | /// later on (such as a use of an undefined global). |
931 | bool CheckingPotentialConstantExpression = false; |
932 | |
933 | /// Whether we're checking for an expression that has undefined behavior. |
934 | /// If so, we will produce warnings if we encounter an operation that is |
935 | /// always undefined. |
936 | /// |
937 | /// Note that we still need to evaluate the expression normally when this |
938 | /// is set; this is used when evaluating ICEs in C. |
939 | bool CheckingForUndefinedBehavior = false; |
940 | |
941 | enum EvaluationMode { |
942 | /// Evaluate as a constant expression. Stop if we find that the expression |
943 | /// is not a constant expression. |
944 | EM_ConstantExpression, |
945 | |
946 | /// Evaluate as a constant expression. Stop if we find that the expression |
947 | /// is not a constant expression. Some expressions can be retried in the |
948 | /// optimizer if we don't constant fold them here, but in an unevaluated |
949 | /// context we try to fold them immediately since the optimizer never |
950 | /// gets a chance to look at it. |
951 | EM_ConstantExpressionUnevaluated, |
952 | |
953 | /// Fold the expression to a constant. Stop if we hit a side-effect that |
954 | /// we can't model. |
955 | EM_ConstantFold, |
956 | |
957 | /// Evaluate in any way we know how. Don't worry about side-effects that |
958 | /// can't be modeled. |
959 | EM_IgnoreSideEffects, |
960 | } EvalMode; |
961 | |
962 | /// Are we checking whether the expression is a potential constant |
963 | /// expression? |
964 | bool checkingPotentialConstantExpression() const override { |
965 | return CheckingPotentialConstantExpression; |
966 | } |
967 | |
968 | /// Are we checking an expression for overflow? |
969 | // FIXME: We should check for any kind of undefined or suspicious behavior |
970 | // in such constructs, not just overflow. |
971 | bool checkingForUndefinedBehavior() const override { |
972 | return CheckingForUndefinedBehavior; |
973 | } |
974 | |
975 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) |
976 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), |
977 | CallStackDepth(0), NextCallIndex(1), |
978 | StepsLeft(C.getLangOpts().ConstexprStepLimit), |
979 | EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), |
980 | BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), |
981 | EvaluatingDecl((const ValueDecl *)nullptr), |
982 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), |
983 | HasFoldFailureDiagnostic(false), EvalMode(Mode) {} |
984 | |
985 | ~EvalInfo() { |
986 | discardCleanups(); |
987 | } |
988 | |
989 | ASTContext &getCtx() const override { return Ctx; } |
990 | |
991 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, |
992 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { |
993 | EvaluatingDecl = Base; |
994 | IsEvaluatingDecl = EDK; |
995 | EvaluatingDeclValue = &Value; |
996 | } |
997 | |
998 | bool CheckCallLimit(SourceLocation Loc) { |
999 | // Don't perform any constexpr calls (other than the call we're checking) |
1000 | // when checking a potential constant expression. |
1001 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) |
1002 | return false; |
1003 | if (NextCallIndex == 0) { |
1004 | // NextCallIndex has wrapped around. |
1005 | FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); |
1006 | return false; |
1007 | } |
1008 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) |
1009 | return true; |
1010 | FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) |
1011 | << getLangOpts().ConstexprCallDepth; |
1012 | return false; |
1013 | } |
1014 | |
1015 | std::pair<CallStackFrame *, unsigned> |
1016 | getCallFrameAndDepth(unsigned CallIndex) { |
1017 | assert(CallIndex && "no call index in getCallFrameAndDepth")(static_cast <bool> (CallIndex && "no call index in getCallFrameAndDepth" ) ? void (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\"" , "clang/lib/AST/ExprConstant.cpp", 1017, __extension__ __PRETTY_FUNCTION__ )); |
1018 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't |
1019 | // be null in this loop. |
1020 | unsigned Depth = CallStackDepth; |
1021 | CallStackFrame *Frame = CurrentCall; |
1022 | while (Frame->Index > CallIndex) { |
1023 | Frame = Frame->Caller; |
1024 | --Depth; |
1025 | } |
1026 | if (Frame->Index == CallIndex) |
1027 | return {Frame, Depth}; |
1028 | return {nullptr, 0}; |
1029 | } |
1030 | |
1031 | bool nextStep(const Stmt *S) { |
1032 | if (!StepsLeft) { |
1033 | FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); |
1034 | return false; |
1035 | } |
1036 | --StepsLeft; |
1037 | return true; |
1038 | } |
1039 | |
1040 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); |
1041 | |
1042 | std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) { |
1043 | std::optional<DynAlloc *> Result; |
1044 | auto It = HeapAllocs.find(DA); |
1045 | if (It != HeapAllocs.end()) |
1046 | Result = &It->second; |
1047 | return Result; |
1048 | } |
1049 | |
1050 | /// Get the allocated storage for the given parameter of the given call. |
1051 | APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { |
1052 | CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; |
1053 | return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) |
1054 | : nullptr; |
1055 | } |
1056 | |
1057 | /// Information about a stack frame for std::allocator<T>::[de]allocate. |
1058 | struct StdAllocatorCaller { |
1059 | unsigned FrameIndex; |
1060 | QualType ElemType; |
1061 | explicit operator bool() const { return FrameIndex != 0; }; |
1062 | }; |
1063 | |
1064 | StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { |
1065 | for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; |
1066 | Call = Call->Caller) { |
1067 | const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); |
1068 | if (!MD) |
1069 | continue; |
1070 | const IdentifierInfo *FnII = MD->getIdentifier(); |
1071 | if (!FnII || !FnII->isStr(FnName)) |
1072 | continue; |
1073 | |
1074 | const auto *CTSD = |
1075 | dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); |
1076 | if (!CTSD) |
1077 | continue; |
1078 | |
1079 | const IdentifierInfo *ClassII = CTSD->getIdentifier(); |
1080 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); |
1081 | if (CTSD->isInStdNamespace() && ClassII && |
1082 | ClassII->isStr("allocator") && TAL.size() >= 1 && |
1083 | TAL[0].getKind() == TemplateArgument::Type) |
1084 | return {Call->Index, TAL[0].getAsType()}; |
1085 | } |
1086 | |
1087 | return {}; |
1088 | } |
1089 | |
1090 | void performLifetimeExtension() { |
1091 | // Disable the cleanups for lifetime-extended temporaries. |
1092 | llvm::erase_if(CleanupStack, [](Cleanup &C) { |
1093 | return !C.isDestroyedAtEndOf(ScopeKind::FullExpression); |
1094 | }); |
1095 | } |
1096 | |
1097 | /// Throw away any remaining cleanups at the end of evaluation. If any |
1098 | /// cleanups would have had a side-effect, note that as an unmodeled |
1099 | /// side-effect and return false. Otherwise, return true. |
1100 | bool discardCleanups() { |
1101 | for (Cleanup &C : CleanupStack) { |
1102 | if (C.hasSideEffect() && !noteSideEffect()) { |
1103 | CleanupStack.clear(); |
1104 | return false; |
1105 | } |
1106 | } |
1107 | CleanupStack.clear(); |
1108 | return true; |
1109 | } |
1110 | |
1111 | private: |
1112 | interp::Frame *getCurrentFrame() override { return CurrentCall; } |
1113 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } |
1114 | |
1115 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } |
1116 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } |
1117 | |
1118 | void setFoldFailureDiagnostic(bool Flag) override { |
1119 | HasFoldFailureDiagnostic = Flag; |
1120 | } |
1121 | |
1122 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } |
1123 | |
1124 | // If we have a prior diagnostic, it will be noting that the expression |
1125 | // isn't a constant expression. This diagnostic is more important, |
1126 | // unless we require this evaluation to produce a constant expression. |
1127 | // |
1128 | // FIXME: We might want to show both diagnostics to the user in |
1129 | // EM_ConstantFold mode. |
1130 | bool hasPriorDiagnostic() override { |
1131 | if (!EvalStatus.Diag->empty()) { |
1132 | switch (EvalMode) { |
1133 | case EM_ConstantFold: |
1134 | case EM_IgnoreSideEffects: |
1135 | if (!HasFoldFailureDiagnostic) |
1136 | break; |
1137 | // We've already failed to fold something. Keep that diagnostic. |
1138 | [[fallthrough]]; |
1139 | case EM_ConstantExpression: |
1140 | case EM_ConstantExpressionUnevaluated: |
1141 | setActiveDiagnostic(false); |
1142 | return true; |
1143 | } |
1144 | } |
1145 | return false; |
1146 | } |
1147 | |
1148 | unsigned getCallStackDepth() override { return CallStackDepth; } |
1149 | |
1150 | public: |
1151 | /// Should we continue evaluation after encountering a side-effect that we |
1152 | /// couldn't model? |
1153 | bool keepEvaluatingAfterSideEffect() { |
1154 | switch (EvalMode) { |
1155 | case EM_IgnoreSideEffects: |
1156 | return true; |
1157 | |
1158 | case EM_ConstantExpression: |
1159 | case EM_ConstantExpressionUnevaluated: |
1160 | case EM_ConstantFold: |
1161 | // By default, assume any side effect might be valid in some other |
1162 | // evaluation of this expression from a different context. |
1163 | return checkingPotentialConstantExpression() || |
1164 | checkingForUndefinedBehavior(); |
1165 | } |
1166 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1166); |
1167 | } |
1168 | |
1169 | /// Note that we have had a side-effect, and determine whether we should |
1170 | /// keep evaluating. |
1171 | bool noteSideEffect() { |
1172 | EvalStatus.HasSideEffects = true; |
1173 | return keepEvaluatingAfterSideEffect(); |
1174 | } |
1175 | |
1176 | /// Should we continue evaluation after encountering undefined behavior? |
1177 | bool keepEvaluatingAfterUndefinedBehavior() { |
1178 | switch (EvalMode) { |
1179 | case EM_IgnoreSideEffects: |
1180 | case EM_ConstantFold: |
1181 | return true; |
1182 | |
1183 | case EM_ConstantExpression: |
1184 | case EM_ConstantExpressionUnevaluated: |
1185 | return checkingForUndefinedBehavior(); |
1186 | } |
1187 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1187); |
1188 | } |
1189 | |
1190 | /// Note that we hit something that was technically undefined behavior, but |
1191 | /// that we can evaluate past it (such as signed overflow or floating-point |
1192 | /// division by zero.) |
1193 | bool noteUndefinedBehavior() override { |
1194 | EvalStatus.HasUndefinedBehavior = true; |
1195 | return keepEvaluatingAfterUndefinedBehavior(); |
1196 | } |
1197 | |
1198 | /// Should we continue evaluation as much as possible after encountering a |
1199 | /// construct which can't be reduced to a value? |
1200 | bool keepEvaluatingAfterFailure() const override { |
1201 | if (!StepsLeft) |
1202 | return false; |
1203 | |
1204 | switch (EvalMode) { |
1205 | case EM_ConstantExpression: |
1206 | case EM_ConstantExpressionUnevaluated: |
1207 | case EM_ConstantFold: |
1208 | case EM_IgnoreSideEffects: |
1209 | return checkingPotentialConstantExpression() || |
1210 | checkingForUndefinedBehavior(); |
1211 | } |
1212 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "clang/lib/AST/ExprConstant.cpp" , 1212); |
1213 | } |
1214 | |
1215 | /// Notes that we failed to evaluate an expression that other expressions |
1216 | /// directly depend on, and determine if we should keep evaluating. This |
1217 | /// should only be called if we actually intend to keep evaluating. |
1218 | /// |
1219 | /// Call noteSideEffect() instead if we may be able to ignore the value that |
1220 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: |
1221 | /// |
1222 | /// (Foo(), 1) // use noteSideEffect |
1223 | /// (Foo() || true) // use noteSideEffect |
1224 | /// Foo() + 1 // use noteFailure |
1225 | [[nodiscard]] bool noteFailure() { |
1226 | // Failure when evaluating some expression often means there is some |
1227 | // subexpression whose evaluation was skipped. Therefore, (because we |
1228 | // don't track whether we skipped an expression when unwinding after an |
1229 | // evaluation failure) every evaluation failure that bubbles up from a |
1230 | // subexpression implies that a side-effect has potentially happened. We |
1231 | // skip setting the HasSideEffects flag to true until we decide to |
1232 | // continue evaluating after that point, which happens here. |
1233 | bool KeepGoing = keepEvaluatingAfterFailure(); |
1234 | EvalStatus.HasSideEffects |= KeepGoing; |
1235 | return KeepGoing; |
1236 | } |
1237 | |
1238 | class ArrayInitLoopIndex { |
1239 | EvalInfo &Info; |
1240 | uint64_t OuterIndex; |
1241 | |
1242 | public: |
1243 | ArrayInitLoopIndex(EvalInfo &Info) |
1244 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { |
1245 | Info.ArrayInitIndex = 0; |
1246 | } |
1247 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } |
1248 | |
1249 | operator uint64_t&() { return Info.ArrayInitIndex; } |
1250 | }; |
1251 | }; |
1252 | |
1253 | /// Object used to treat all foldable expressions as constant expressions. |
1254 | struct FoldConstant { |
1255 | EvalInfo &Info; |
1256 | bool Enabled; |
1257 | bool HadNoPriorDiags; |
1258 | EvalInfo::EvaluationMode OldMode; |
1259 | |
1260 | explicit FoldConstant(EvalInfo &Info, bool Enabled) |
1261 | : Info(Info), |
1262 | Enabled(Enabled), |
1263 | HadNoPriorDiags(Info.EvalStatus.Diag && |
1264 | Info.EvalStatus.Diag->empty() && |
1265 | !Info.EvalStatus.HasSideEffects), |
1266 | OldMode(Info.EvalMode) { |
1267 | if (Enabled) |
1268 | Info.EvalMode = EvalInfo::EM_ConstantFold; |
1269 | } |
1270 | void keepDiagnostics() { Enabled = false; } |
1271 | ~FoldConstant() { |
1272 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && |
1273 | !Info.EvalStatus.HasSideEffects) |
1274 | Info.EvalStatus.Diag->clear(); |
1275 | Info.EvalMode = OldMode; |
1276 | } |
1277 | }; |
1278 | |
1279 | /// RAII object used to set the current evaluation mode to ignore |
1280 | /// side-effects. |
1281 | struct IgnoreSideEffectsRAII { |
1282 | EvalInfo &Info; |
1283 | EvalInfo::EvaluationMode OldMode; |
1284 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) |
1285 | : Info(Info), OldMode(Info.EvalMode) { |
1286 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; |
1287 | } |
1288 | |
1289 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } |
1290 | }; |
1291 | |
1292 | /// RAII object used to optionally suppress diagnostics and side-effects from |
1293 | /// a speculative evaluation. |
1294 | class SpeculativeEvaluationRAII { |
1295 | EvalInfo *Info = nullptr; |
1296 | Expr::EvalStatus OldStatus; |
1297 | unsigned OldSpeculativeEvaluationDepth; |
1298 | |
1299 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { |
1300 | Info = Other.Info; |
1301 | OldStatus = Other.OldStatus; |
1302 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; |
1303 | Other.Info = nullptr; |
1304 | } |
1305 | |
1306 | void maybeRestoreState() { |
1307 | if (!Info) |
1308 | return; |
1309 | |
1310 | Info->EvalStatus = OldStatus; |
1311 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; |
1312 | } |
1313 | |
1314 | public: |
1315 | SpeculativeEvaluationRAII() = default; |
1316 | |
1317 | SpeculativeEvaluationRAII( |
1318 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) |
1319 | : Info(&Info), OldStatus(Info.EvalStatus), |
1320 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { |
1321 | Info.EvalStatus.Diag = NewDiag; |
1322 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; |
1323 | } |
1324 | |
1325 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; |
1326 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { |
1327 | moveFromAndCancel(std::move(Other)); |
1328 | } |
1329 | |
1330 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { |
1331 | maybeRestoreState(); |
1332 | moveFromAndCancel(std::move(Other)); |
1333 | return *this; |
1334 | } |
1335 | |
1336 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } |
1337 | }; |
1338 | |
1339 | /// RAII object wrapping a full-expression or block scope, and handling |
1340 | /// the ending of the lifetime of temporaries created within it. |
1341 | template<ScopeKind Kind> |
1342 | class ScopeRAII { |
1343 | EvalInfo &Info; |
1344 | unsigned OldStackSize; |
1345 | public: |
1346 | ScopeRAII(EvalInfo &Info) |
1347 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { |
1348 | // Push a new temporary version. This is needed to distinguish between |
1349 | // temporaries created in different iterations of a loop. |
1350 | Info.CurrentCall->pushTempVersion(); |
1351 | } |
1352 | bool destroy(bool RunDestructors = true) { |
1353 | bool OK = cleanup(Info, RunDestructors, OldStackSize); |
1354 | OldStackSize = -1U; |
1355 | return OK; |
1356 | } |
1357 | ~ScopeRAII() { |
1358 | if (OldStackSize != -1U) |
1359 | destroy(false); |
1360 | // Body moved to a static method to encourage the compiler to inline away |
1361 | // instances of this class. |
1362 | Info.CurrentCall->popTempVersion(); |
1363 | } |
1364 | private: |
1365 | static bool cleanup(EvalInfo &Info, bool RunDestructors, |
1366 | unsigned OldStackSize) { |
1367 | assert(OldStackSize <= Info.CleanupStack.size() &&(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "clang/lib/AST/ExprConstant.cpp", 1368, __extension__ __PRETTY_FUNCTION__ )) |
1368 | "running cleanups out of order?")(static_cast <bool> (OldStackSize <= Info.CleanupStack .size() && "running cleanups out of order?") ? void ( 0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "clang/lib/AST/ExprConstant.cpp", 1368, __extension__ __PRETTY_FUNCTION__ )); |
1369 | |
1370 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups |
1371 | // for a full-expression scope. |
1372 | bool Success = true; |
1373 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { |
1374 | if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { |
1375 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { |
1376 | Success = false; |
1377 | break; |
1378 | } |
1379 | } |
1380 | } |
1381 | |
1382 | // Compact any retained cleanups. |
1383 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; |
1384 | if (Kind != ScopeKind::Block) |
1385 | NewEnd = |
1386 | std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { |
1387 | return C.isDestroyedAtEndOf(Kind); |
1388 | }); |
1389 | Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); |
1390 | return Success; |
1391 | } |
1392 | }; |
1393 | typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; |
1394 | typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; |
1395 | typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; |
1396 | } |
1397 | |
1398 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, |
1399 | CheckSubobjectKind CSK) { |
1400 | if (Invalid) |
1401 | return false; |
1402 | if (isOnePastTheEnd()) { |
1403 | Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) |
1404 | << CSK; |
1405 | setInvalid(); |
1406 | return false; |
1407 | } |
1408 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there |
1409 | // must actually be at least one array element; even a VLA cannot have a |
1410 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. |
1411 | return true; |
1412 | } |
1413 | |
1414 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, |
1415 | const Expr *E) { |
1416 | Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); |
1417 | // Do not set the designator as invalid: we can represent this situation, |
1418 | // and correct handling of __builtin_object_size requires us to do so. |
1419 | } |
1420 | |
1421 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, |
1422 | const Expr *E, |
1423 | const APSInt &N) { |
1424 | // If we're complaining, we must be able to statically determine the size of |
1425 | // the most derived array. |
1426 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) |
1427 | Info.CCEDiag(E, diag::note_constexpr_array_index) |
1428 | << N << /*array*/ 0 |
1429 | << static_cast<unsigned>(getMostDerivedArraySize()); |
1430 | else |
1431 | Info.CCEDiag(E, diag::note_constexpr_array_index) |
1432 | << N << /*non-array*/ 1; |
1433 | setInvalid(); |
1434 | } |
1435 | |
1436 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, |
1437 | const FunctionDecl *Callee, const LValue *This, |
1438 | CallRef Call) |
1439 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), |
1440 | Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { |
1441 | Info.CurrentCall = this; |
1442 | ++Info.CallStackDepth; |
1443 | } |
1444 | |
1445 | CallStackFrame::~CallStackFrame() { |
1446 | assert(Info.CurrentCall == this && "calls retired out of order")(static_cast <bool> (Info.CurrentCall == this && "calls retired out of order") ? void (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\"" , "clang/lib/AST/ExprConstant.cpp", 1446, __extension__ __PRETTY_FUNCTION__ )); |
1447 | --Info.CallStackDepth; |
1448 | Info.CurrentCall = Caller; |
1449 | } |
1450 | |
1451 | static bool isRead(AccessKinds AK) { |
1452 | return AK == AK_Read || AK == AK_ReadObjectRepresentation; |
1453 | } |
1454 | |
1455 | static bool isModification(AccessKinds AK) { |
1456 | switch (AK) { |
1457 | case AK_Read: |
1458 | case AK_ReadObjectRepresentation: |
1459 | case AK_MemberCall: |
1460 | case AK_DynamicCast: |
1461 | case AK_TypeId: |
1462 | return false; |
1463 | case AK_Assign: |
1464 | case AK_Increment: |
1465 | case AK_Decrement: |
1466 | case AK_Construct: |
1467 | case AK_Destroy: |
1468 | return true; |
1469 | } |
1470 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp" , 1470); |
1471 | } |
1472 | |
1473 | static bool isAnyAccess(AccessKinds AK) { |
1474 | return isRead(AK) || isModification(AK); |
1475 | } |
1476 | |
1477 | /// Is this an access per the C++ definition? |
1478 | static bool isFormalAccess(AccessKinds AK) { |
1479 | return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; |
1480 | } |
1481 | |
1482 | /// Is this kind of axcess valid on an indeterminate object value? |
1483 | static bool isValidIndeterminateAccess(AccessKinds AK) { |
1484 | switch (AK) { |
1485 | case AK_Read: |
1486 | case AK_Increment: |
1487 | case AK_Decrement: |
1488 | // These need the object's value. |
1489 | return false; |
1490 | |
1491 | case AK_ReadObjectRepresentation: |
1492 | case AK_Assign: |
1493 | case AK_Construct: |
1494 | case AK_Destroy: |
1495 | // Construction and destruction don't need the value. |
1496 | return true; |
1497 | |
1498 | case AK_MemberCall: |
1499 | case AK_DynamicCast: |
1500 | case AK_TypeId: |
1501 | // These aren't really meaningful on scalars. |
1502 | return true; |
1503 | } |
1504 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "clang/lib/AST/ExprConstant.cpp" , 1504); |
1505 | } |
1506 | |
1507 | namespace { |
1508 | struct ComplexValue { |
1509 | private: |
1510 | bool IsInt; |
1511 | |
1512 | public: |
1513 | APSInt IntReal, IntImag; |
1514 | APFloat FloatReal, FloatImag; |
1515 | |
1516 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} |
1517 | |
1518 | void makeComplexFloat() { IsInt = false; } |
1519 | bool isComplexFloat() const { return !IsInt; } |
1520 | APFloat &getComplexFloatReal() { return FloatReal; } |
1521 | APFloat &getComplexFloatImag() { return FloatImag; } |
1522 | |
1523 | void makeComplexInt() { IsInt = true; } |
1524 | bool isComplexInt() const { return IsInt; } |
1525 | APSInt &getComplexIntReal() { return IntReal; } |
1526 | APSInt &getComplexIntImag() { return IntImag; } |
1527 | |
1528 | void moveInto(APValue &v) const { |
1529 | if (isComplexFloat()) |
1530 | v = APValue(FloatReal, FloatImag); |
1531 | else |
1532 | v = APValue(IntReal, IntImag); |
1533 | } |
1534 | void setFrom(const APValue &v) { |
1535 | assert(v.isComplexFloat() || v.isComplexInt())(static_cast <bool> (v.isComplexFloat() || v.isComplexInt ()) ? void (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()" , "clang/lib/AST/ExprConstant.cpp", 1535, __extension__ __PRETTY_FUNCTION__ )); |
1536 | if (v.isComplexFloat()) { |
1537 | makeComplexFloat(); |
1538 | FloatReal = v.getComplexFloatReal(); |
1539 | FloatImag = v.getComplexFloatImag(); |
1540 | } else { |
1541 | makeComplexInt(); |
1542 | IntReal = v.getComplexIntReal(); |
1543 | IntImag = v.getComplexIntImag(); |
1544 | } |
1545 | } |
1546 | }; |
1547 | |
1548 | struct LValue { |
1549 | APValue::LValueBase Base; |
1550 | CharUnits Offset; |
1551 | SubobjectDesignator Designator; |
1552 | bool IsNullPtr : 1; |
1553 | bool InvalidBase : 1; |
1554 | |
1555 | const APValue::LValueBase getLValueBase() const { return Base; } |
1556 | CharUnits &getLValueOffset() { return Offset; } |
1557 | const CharUnits &getLValueOffset() const { return Offset; } |
1558 | SubobjectDesignator &getLValueDesignator() { return Designator; } |
1559 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} |
1560 | bool isNullPointer() const { return IsNullPtr;} |
1561 | |
1562 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } |
1563 | unsigned getLValueVersion() const { return Base.getVersion(); } |
1564 | |
1565 | void moveInto(APValue &V) const { |
1566 | if (Designator.Invalid) |
1567 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); |
1568 | else { |
1569 | assert(!InvalidBase && "APValues can't handle invalid LValue bases")(static_cast <bool> (!InvalidBase && "APValues can't handle invalid LValue bases" ) ? void (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\"" , "clang/lib/AST/ExprConstant.cpp", 1569, __extension__ __PRETTY_FUNCTION__ )); |
1570 | V = APValue(Base, Offset, Designator.Entries, |
1571 | Designator.IsOnePastTheEnd, IsNullPtr); |
1572 | } |
1573 | } |
1574 | void setFrom(ASTContext &Ctx, const APValue &V) { |
1575 | assert(V.isLValue() && "Setting LValue from a non-LValue?")(static_cast <bool> (V.isLValue() && "Setting LValue from a non-LValue?" ) ? void (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\"" , "clang/lib/AST/ExprConstant.cpp", 1575, __extension__ __PRETTY_FUNCTION__ )); |
1576 | Base = V.getLValueBase(); |
1577 | Offset = V.getLValueOffset(); |
1578 | InvalidBase = false; |
1579 | Designator = SubobjectDesignator(Ctx, V); |
1580 | IsNullPtr = V.isNullPointer(); |
1581 | } |
1582 | |
1583 | void set(APValue::LValueBase B, bool BInvalid = false) { |
1584 | #ifndef NDEBUG |
1585 | // We only allow a few types of invalid bases. Enforce that here. |
1586 | if (BInvalid) { |
1587 | const auto *E = B.get<const Expr *>(); |
1588 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "clang/lib/AST/ExprConstant.cpp", 1589, __extension__ __PRETTY_FUNCTION__ )) |
1589 | "Unexpected type of invalid base")(static_cast <bool> ((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall (E)) && "Unexpected type of invalid base") ? void (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "clang/lib/AST/ExprConstant.cpp", 1589, __extension__ __PRETTY_FUNCTION__ )); |
1590 | } |
1591 | #endif |
1592 | |
1593 | Base = B; |
1594 | Offset = CharUnits::fromQuantity(0); |
1595 | InvalidBase = BInvalid; |
1596 | Designator = SubobjectDesignator(getType(B)); |
1597 | IsNullPtr = false; |
1598 | } |
1599 | |
1600 | void setNull(ASTContext &Ctx, QualType PointerTy) { |
1601 | Base = (const ValueDecl *)nullptr; |
1602 | Offset = |
1603 | CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); |
1604 | InvalidBase = false; |
1605 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); |
1606 | IsNullPtr = true; |
1607 | } |
1608 | |
1609 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { |
1610 | set(B, true); |
1611 | } |
1612 | |
1613 | std::string toString(ASTContext &Ctx, QualType T) const { |
1614 | APValue Printable; |
1615 | moveInto(Printable); |
1616 | return Printable.getAsString(Ctx, T); |
1617 | } |
1618 | |
1619 | private: |
1620 | // Check that this LValue is not based on a null pointer. If it is, produce |
1621 | // a diagnostic and mark the designator as invalid. |
1622 | template <typename GenDiagType> |
1623 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { |
1624 | if (Designator.Invalid) |
1625 | return false; |
1626 | if (IsNullPtr) { |
1627 | GenDiag(); |
1628 | Designator.setInvalid(); |
1629 | return false; |
1630 | } |
1631 | return true; |
1632 | } |
1633 | |
1634 | public: |
1635 | bool checkNullPointer(EvalInfo &Info, const Expr *E, |
1636 | CheckSubobjectKind CSK) { |
1637 | return checkNullPointerDiagnosingWith([&Info, E, CSK] { |
1638 | Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; |
1639 | }); |
1640 | } |
1641 | |
1642 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, |
1643 | AccessKinds AK) { |
1644 | return checkNullPointerDiagnosingWith([&Info, E, AK] { |
1645 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; |
1646 | }); |
1647 | } |
1648 | |
1649 | // Check this LValue refers to an object. If not, set the designator to be |
1650 | // invalid and emit a diagnostic. |
1651 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { |
1652 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && |
1653 | Designator.checkSubobject(Info, E, CSK); |
1654 | } |
1655 | |
1656 | void addDecl(EvalInfo &Info, const Expr *E, |
1657 | const Decl *D, bool Virtual = false) { |
1658 | if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) |
1659 | Designator.addDeclUnchecked(D, Virtual); |
1660 | } |
1661 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { |
1662 | if (!Designator.Entries.empty()) { |
1663 | Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); |
1664 | Designator.setInvalid(); |
1665 | return; |
1666 | } |
1667 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) { |
1668 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())(static_cast <bool> (getType(Base)->isPointerType() || getType(Base)->isArrayType()) ? void (0) : __assert_fail ( "getType(Base)->isPointerType() || getType(Base)->isArrayType()" , "clang/lib/AST/ExprConstant.cpp", 1668, __extension__ __PRETTY_FUNCTION__ )); |
1669 | Designator.FirstEntryIsAnUnsizedArray = true; |
1670 | Designator.addUnsizedArrayUnchecked(ElemTy); |
1671 | } |
1672 | } |
1673 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { |
1674 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) |
1675 | Designator.addArrayUnchecked(CAT); |
1676 | } |
1677 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { |
1678 | if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) |
1679 | Designator.addComplexUnchecked(EltTy, Imag); |
1680 | } |
1681 | void clearIsNullPointer() { |
1682 | IsNullPtr = false; |
1683 | } |
1684 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, |
1685 | const APSInt &Index, CharUnits ElementSize) { |
1686 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, |
1687 | // but we're not required to diagnose it and it's valid in C++.) |
1688 | if (!Index) |
1689 | return; |
1690 | |
1691 | // Compute the new offset in the appropriate width, wrapping at 64 bits. |
1692 | // FIXME: When compiling for a 32-bit target, we should use 32-bit |
1693 | // offsets. |
1694 | uint64_t Offset64 = Offset.getQuantity(); |
1695 | uint64_t ElemSize64 = ElementSize.getQuantity(); |
1696 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); |
1697 | Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); |
1698 | |
1699 | if (checkNullPointer(Info, E, CSK_ArrayIndex)) |
1700 | Designator.adjustIndex(Info, E, Index); |
1701 | clearIsNullPointer(); |
1702 | } |
1703 | void adjustOffset(CharUnits N) { |
1704 | Offset += N; |
1705 | if (N.getQuantity()) |
1706 | clearIsNullPointer(); |
1707 | } |
1708 | }; |
1709 | |
1710 | struct MemberPtr { |
1711 | MemberPtr() {} |
1712 | explicit MemberPtr(const ValueDecl *Decl) |
1713 | : DeclAndIsDerivedMember(Decl, false) {} |
1714 | |
1715 | /// The member or (direct or indirect) field referred to by this member |
1716 | /// pointer, or 0 if this is a null member pointer. |
1717 | const ValueDecl *getDecl() const { |
1718 | return DeclAndIsDerivedMember.getPointer(); |
1719 | } |
1720 | /// Is this actually a member of some type derived from the relevant class? |
1721 | bool isDerivedMember() const { |
1722 | return DeclAndIsDerivedMember.getInt(); |
1723 | } |
1724 | /// Get the class which the declaration actually lives in. |
1725 | const CXXRecordDecl *getContainingRecord() const { |
1726 | return cast<CXXRecordDecl>( |
1727 | DeclAndIsDerivedMember.getPointer()->getDeclContext()); |
1728 | } |
1729 | |
1730 | void moveInto(APValue &V) const { |
1731 | V = APValue(getDecl(), isDerivedMember(), Path); |
1732 | } |
1733 | void setFrom(const APValue &V) { |
1734 | assert(V.isMemberPointer())(static_cast <bool> (V.isMemberPointer()) ? void (0) : __assert_fail ("V.isMemberPointer()", "clang/lib/AST/ExprConstant.cpp", 1734 , __extension__ __PRETTY_FUNCTION__)); |
1735 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); |
1736 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); |
1737 | Path.clear(); |
1738 | ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); |
1739 | Path.insert(Path.end(), P.begin(), P.end()); |
1740 | } |
1741 | |
1742 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating |
1743 | /// whether the member is a member of some class derived from the class type |
1744 | /// of the member pointer. |
1745 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; |
1746 | /// Path - The path of base/derived classes from the member declaration's |
1747 | /// class (exclusive) to the class type of the member pointer (inclusive). |
1748 | SmallVector<const CXXRecordDecl*, 4> Path; |
1749 | |
1750 | /// Perform a cast towards the class of the Decl (either up or down the |
1751 | /// hierarchy). |
1752 | bool castBack(const CXXRecordDecl *Class) { |
1753 | assert(!Path.empty())(static_cast <bool> (!Path.empty()) ? void (0) : __assert_fail ("!Path.empty()", "clang/lib/AST/ExprConstant.cpp", 1753, __extension__ __PRETTY_FUNCTION__)); |
1754 | const CXXRecordDecl *Expected; |
1755 | if (Path.size() >= 2) |
1756 | Expected = Path[Path.size() - 2]; |
1757 | else |
1758 | Expected = getContainingRecord(); |
1759 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { |
1760 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), |
1761 | // if B does not contain the original member and is not a base or |
1762 | // derived class of the class containing the original member, the result |
1763 | // of the cast is undefined. |
1764 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to |
1765 | // (D::*). We consider that to be a language defect. |
1766 | return false; |
1767 | } |
1768 | Path.pop_back(); |
1769 | return true; |
1770 | } |
1771 | /// Perform a base-to-derived member pointer cast. |
1772 | bool castToDerived(const CXXRecordDecl *Derived) { |
1773 | if (!getDecl()) |
1774 | return true; |
1775 | if (!isDerivedMember()) { |
1776 | Path.push_back(Derived); |
1777 | return true; |
1778 | } |
1779 | if (!castBack(Derived)) |
1780 | return false; |
1781 | if (Path.empty()) |
1782 | DeclAndIsDerivedMember.setInt(false); |
1783 | return true; |
1784 | } |
1785 | /// Perform a derived-to-base member pointer cast. |
1786 | bool castToBase(const CXXRecordDecl *Base) { |
1787 | if (!getDecl()) |
1788 | return true; |
1789 | if (Path.empty()) |
1790 | DeclAndIsDerivedMember.setInt(true); |
1791 | if (isDerivedMember()) { |
1792 | Path.push_back(Base); |
1793 | return true; |
1794 | } |
1795 | return castBack(Base); |
1796 | } |
1797 | }; |
1798 | |
1799 | /// Compare two member pointers, which are assumed to be of the same type. |
1800 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { |
1801 | if (!LHS.getDecl() || !RHS.getDecl()) |
1802 | return !LHS.getDecl() && !RHS.getDecl(); |
1803 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) |
1804 | return false; |
1805 | return LHS.Path == RHS.Path; |
1806 | } |
1807 | } |
1808 | |
1809 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); |
1810 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, |
1811 | const LValue &This, const Expr *E, |
1812 | bool AllowNonLiteralTypes = false); |
1813 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, |
1814 | bool InvalidBaseOK = false); |
1815 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, |
1816 | bool InvalidBaseOK = false); |
1817 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, |
1818 | EvalInfo &Info); |
1819 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); |
1820 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); |
1821 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, |
1822 | EvalInfo &Info); |
1823 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); |
1824 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); |
1825 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, |
1826 | EvalInfo &Info); |
1827 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); |
1828 | static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, |
1829 | EvalInfo &Info); |
1830 | |
1831 | /// Evaluate an integer or fixed point expression into an APResult. |
1832 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, |
1833 | EvalInfo &Info); |
1834 | |
1835 | /// Evaluate only a fixed point expression into an APResult. |
1836 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, |
1837 | EvalInfo &Info); |
1838 | |
1839 | //===----------------------------------------------------------------------===// |
1840 | // Misc utilities |
1841 | //===----------------------------------------------------------------------===// |
1842 | |
1843 | /// Negate an APSInt in place, converting it to a signed form if necessary, and |
1844 | /// preserving its value (by extending by up to one bit as needed). |
1845 | static void negateAsSigned(APSInt &Int) { |
1846 | if (Int.isUnsigned() || Int.isMinSignedValue()) { |
1847 | Int = Int.extend(Int.getBitWidth() + 1); |
1848 | Int.setIsSigned(true); |
1849 | } |
1850 | Int = -Int; |
1851 | } |
1852 | |
1853 | template<typename KeyT> |
1854 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, |
1855 | ScopeKind Scope, LValue &LV) { |
1856 | unsigned Version = getTempVersion(); |
1857 | APValue::LValueBase Base(Key, Index, Version); |
1858 | LV.set(Base); |
1859 | return createLocal(Base, Key, T, Scope); |
1860 | } |
1861 | |
1862 | /// Allocate storage for a parameter of a function call made in this frame. |
1863 | APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, |
1864 | LValue &LV) { |
1865 | assert(Args.CallIndex == Index && "creating parameter in wrong frame")(static_cast <bool> (Args.CallIndex == Index && "creating parameter in wrong frame") ? void (0) : __assert_fail ("Args.CallIndex == Index && \"creating parameter in wrong frame\"" , "clang/lib/AST/ExprConstant.cpp", 1865, __extension__ __PRETTY_FUNCTION__ )); |
1866 | APValue::LValueBase Base(PVD, Index, Args.Version); |
1867 | LV.set(Base); |
1868 | // We always destroy parameters at the end of the call, even if we'd allow |
1869 | // them to live to the end of the full-expression at runtime, in order to |
1870 | // give portable results and match other compilers. |
1871 | return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); |
1872 | } |
1873 | |
1874 | APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, |
1875 | QualType T, ScopeKind Scope) { |
1876 | assert(Base.getCallIndex() == Index && "lvalue for wrong frame")(static_cast <bool> (Base.getCallIndex() == Index && "lvalue for wrong frame") ? void (0) : __assert_fail ("Base.getCallIndex() == Index && \"lvalue for wrong frame\"" , "clang/lib/AST/ExprConstant.cpp", 1876, __extension__ __PRETTY_FUNCTION__ )); |
1877 | unsigned Version = Base.getVersion(); |
1878 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; |
1879 | assert(Result.isAbsent() && "local created multiple times")(static_cast <bool> (Result.isAbsent() && "local created multiple times" ) ? void (0) : __assert_fail ("Result.isAbsent() && \"local created multiple times\"" , "clang/lib/AST/ExprConstant.cpp", 1879, __extension__ __PRETTY_FUNCTION__ )); |
1880 | |
1881 | // If we're creating a local immediately in the operand of a speculative |
1882 | // evaluation, don't register a cleanup to be run outside the speculative |
1883 | // evaluation context, since we won't actually be able to initialize this |
1884 | // object. |
1885 | if (Index <= Info.SpeculativeEvaluationDepth) { |
1886 | if (T.isDestructedType()) |
1887 | Info.noteSideEffect(); |
1888 | } else { |
1889 | Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); |
1890 | } |
1891 | return Result; |
1892 | } |
1893 | |
1894 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { |
1895 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { |
1896 | FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); |
1897 | return nullptr; |
1898 | } |
1899 | |
1900 | DynamicAllocLValue DA(NumHeapAllocs++); |
1901 | LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); |
1902 | auto Result = HeapAllocs.emplace(std::piecewise_construct, |
1903 | std::forward_as_tuple(DA), std::tuple<>()); |
1904 | assert(Result.second && "reused a heap alloc index?")(static_cast <bool> (Result.second && "reused a heap alloc index?" ) ? void (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\"" , "clang/lib/AST/ExprConstant.cpp", 1904, __extension__ __PRETTY_FUNCTION__ )); |
1905 | Result.first->second.AllocExpr = E; |
1906 | return &Result.first->second.Value; |
1907 | } |
1908 | |
1909 | /// Produce a string describing the given constexpr call. |
1910 | void CallStackFrame::describe(raw_ostream &Out) { |
1911 | unsigned ArgIndex = 0; |
1912 | bool IsMemberCall = isa<CXXMethodDecl>(Callee) && |
1913 | !isa<CXXConstructorDecl>(Callee) && |
1914 | cast<CXXMethodDecl>(Callee)->isInstance(); |
1915 | |
1916 | if (!IsMemberCall) |
1917 | Out << *Callee << '('; |
1918 | |
1919 | if (This && IsMemberCall) { |
1920 | APValue Val; |
1921 | This->moveInto(Val); |
1922 | Val.printPretty(Out, Info.Ctx, |
1923 | This->Designator.MostDerivedType); |
1924 | // FIXME: Add parens around Val if needed. |
1925 | Out << "->" << *Callee << '('; |
1926 | IsMemberCall = false; |
1927 | } |
1928 | |
1929 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), |
1930 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { |
1931 | if (ArgIndex > (unsigned)IsMemberCall) |
1932 | Out << ", "; |
1933 | |
1934 | const ParmVarDecl *Param = *I; |
1935 | APValue *V = Info.getParamSlot(Arguments, Param); |
1936 | if (V) |
1937 | V->printPretty(Out, Info.Ctx, Param->getType()); |
1938 | else |
1939 | Out << "<...>"; |
1940 | |
1941 | if (ArgIndex == 0 && IsMemberCall) |
1942 | Out << "->" << *Callee << '('; |
1943 | } |
1944 | |
1945 | Out << ')'; |
1946 | } |
1947 | |
1948 | /// Evaluate an expression to see if it had side-effects, and discard its |
1949 | /// result. |
1950 | /// \return \c true if the caller should keep evaluating. |
1951 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { |
1952 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 1952, __extension__ __PRETTY_FUNCTION__)); |
1953 | APValue Scratch; |
1954 | if (!Evaluate(Scratch, Info, E)) |
1955 | // We don't need the value, but we might have skipped a side effect here. |
1956 | return Info.noteSideEffect(); |
1957 | return true; |
1958 | } |
1959 | |
1960 | /// Should this call expression be treated as a no-op? |
1961 | static bool IsNoOpCall(const CallExpr *E) { |
1962 | unsigned Builtin = E->getBuiltinCallee(); |
1963 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || |
1964 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString || |
1965 | Builtin == Builtin::BI__builtin_function_start); |
1966 | } |
1967 | |
1968 | static bool IsGlobalLValue(APValue::LValueBase B) { |
1969 | // C++11 [expr.const]p3 An address constant expression is a prvalue core |
1970 | // constant expression of pointer type that evaluates to... |
1971 | |
1972 | // ... a null pointer value, or a prvalue core constant expression of type |
1973 | // std::nullptr_t. |
1974 | if (!B) return true; |
1975 | |
1976 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { |
1977 | // ... the address of an object with static storage duration, |
1978 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) |
1979 | return VD->hasGlobalStorage(); |
1980 | if (isa<TemplateParamObjectDecl>(D)) |
1981 | return true; |
1982 | // ... the address of a function, |
1983 | // ... the address of a GUID [MS extension], |
1984 | // ... the address of an unnamed global constant |
1985 | return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D); |
1986 | } |
1987 | |
1988 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) |
1989 | return true; |
1990 | |
1991 | const Expr *E = B.get<const Expr*>(); |
1992 | switch (E->getStmtClass()) { |
1993 | default: |
1994 | return false; |
1995 | case Expr::CompoundLiteralExprClass: { |
1996 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); |
1997 | return CLE->isFileScope() && CLE->isLValue(); |
1998 | } |
1999 | case Expr::MaterializeTemporaryExprClass: |
2000 | // A materialized temporary might have been lifetime-extended to static |
2001 | // storage duration. |
2002 | return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; |
2003 | // A string literal has static storage duration. |
2004 | case Expr::StringLiteralClass: |
2005 | case Expr::PredefinedExprClass: |
2006 | case Expr::ObjCStringLiteralClass: |
2007 | case Expr::ObjCEncodeExprClass: |
2008 | return true; |
2009 | case Expr::ObjCBoxedExprClass: |
2010 | return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); |
2011 | case Expr::CallExprClass: |
2012 | return IsNoOpCall(cast<CallExpr>(E)); |
2013 | // For GCC compatibility, &&label has static storage duration. |
2014 | case Expr::AddrLabelExprClass: |
2015 | return true; |
2016 | // A Block literal expression may be used as the initialization value for |
2017 | // Block variables at global or local static scope. |
2018 | case Expr::BlockExprClass: |
2019 | return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); |
2020 | // The APValue generated from a __builtin_source_location will be emitted as a |
2021 | // literal. |
2022 | case Expr::SourceLocExprClass: |
2023 | return true; |
2024 | case Expr::ImplicitValueInitExprClass: |
2025 | // FIXME: |
2026 | // We can never form an lvalue with an implicit value initialization as its |
2027 | // base through expression evaluation, so these only appear in one case: the |
2028 | // implicit variable declaration we invent when checking whether a constexpr |
2029 | // constructor can produce a constant expression. We must assume that such |
2030 | // an expression might be a global lvalue. |
2031 | return true; |
2032 | } |
2033 | } |
2034 | |
2035 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { |
2036 | return LVal.Base.dyn_cast<const ValueDecl*>(); |
2037 | } |
2038 | |
2039 | static bool IsLiteralLValue(const LValue &Value) { |
2040 | if (Value.getLValueCallIndex()) |
2041 | return false; |
2042 | const Expr *E = Value.Base.dyn_cast<const Expr*>(); |
2043 | return E && !isa<MaterializeTemporaryExpr>(E); |
2044 | } |
2045 | |
2046 | static bool IsWeakLValue(const LValue &Value) { |
2047 | const ValueDecl *Decl = GetLValueBaseDecl(Value); |
2048 | return Decl && Decl->isWeak(); |
2049 | } |
2050 | |
2051 | static bool isZeroSized(const LValue &Value) { |
2052 | const ValueDecl *Decl = GetLValueBaseDecl(Value); |
2053 | if (Decl && isa<VarDecl>(Decl)) { |
2054 | QualType Ty = Decl->getType(); |
2055 | if (Ty->isArrayType()) |
2056 | return Ty->isIncompleteType() || |
2057 | Decl->getASTContext().getTypeSize(Ty) == 0; |
2058 | } |
2059 | return false; |
2060 | } |
2061 | |
2062 | static bool HasSameBase(const LValue &A, const LValue &B) { |
2063 | if (!A.getLValueBase()) |
2064 | return !B.getLValueBase(); |
2065 | if (!B.getLValueBase()) |
2066 | return false; |
2067 | |
2068 | if (A.getLValueBase().getOpaqueValue() != |
2069 | B.getLValueBase().getOpaqueValue()) |
2070 | return false; |
2071 | |
2072 | return A.getLValueCallIndex() == B.getLValueCallIndex() && |
2073 | A.getLValueVersion() == B.getLValueVersion(); |
2074 | } |
2075 | |
2076 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { |
2077 | assert(Base && "no location for a null lvalue")(static_cast <bool> (Base && "no location for a null lvalue" ) ? void (0) : __assert_fail ("Base && \"no location for a null lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2077, __extension__ __PRETTY_FUNCTION__ )); |
2078 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); |
2079 | |
2080 | // For a parameter, find the corresponding call stack frame (if it still |
2081 | // exists), and point at the parameter of the function definition we actually |
2082 | // invoked. |
2083 | if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { |
2084 | unsigned Idx = PVD->getFunctionScopeIndex(); |
2085 | for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { |
2086 | if (F->Arguments.CallIndex == Base.getCallIndex() && |
2087 | F->Arguments.Version == Base.getVersion() && F->Callee && |
2088 | Idx < F->Callee->getNumParams()) { |
2089 | VD = F->Callee->getParamDecl(Idx); |
2090 | break; |
2091 | } |
2092 | } |
2093 | } |
2094 | |
2095 | if (VD) |
2096 | Info.Note(VD->getLocation(), diag::note_declared_at); |
2097 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) |
2098 | Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); |
2099 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { |
2100 | // FIXME: Produce a note for dangling pointers too. |
2101 | if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA)) |
2102 | Info.Note((*Alloc)->AllocExpr->getExprLoc(), |
2103 | diag::note_constexpr_dynamic_alloc_here); |
2104 | } |
2105 | // We have no information to show for a typeid(T) object. |
2106 | } |
2107 | |
2108 | enum class CheckEvaluationResultKind { |
2109 | ConstantExpression, |
2110 | FullyInitialized, |
2111 | }; |
2112 | |
2113 | /// Materialized temporaries that we've already checked to determine if they're |
2114 | /// initializsed by a constant expression. |
2115 | using CheckedTemporaries = |
2116 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; |
2117 | |
2118 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, |
2119 | EvalInfo &Info, SourceLocation DiagLoc, |
2120 | QualType Type, const APValue &Value, |
2121 | ConstantExprKind Kind, |
2122 | SourceLocation SubobjectLoc, |
2123 | CheckedTemporaries &CheckedTemps); |
2124 | |
2125 | /// Check that this reference or pointer core constant expression is a valid |
2126 | /// value for an address or reference constant expression. Return true if we |
2127 | /// can fold this expression, whether or not it's a constant expression. |
2128 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, |
2129 | QualType Type, const LValue &LVal, |
2130 | ConstantExprKind Kind, |
2131 | CheckedTemporaries &CheckedTemps) { |
2132 | bool IsReferenceType = Type->isReferenceType(); |
2133 | |
2134 | APValue::LValueBase Base = LVal.getLValueBase(); |
2135 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); |
2136 | |
2137 | const Expr *BaseE = Base.dyn_cast<const Expr *>(); |
2138 | const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); |
2139 | |
2140 | // Additional restrictions apply in a template argument. We only enforce the |
2141 | // C++20 restrictions here; additional syntactic and semantic restrictions |
2142 | // are applied elsewhere. |
2143 | if (isTemplateArgument(Kind)) { |
2144 | int InvalidBaseKind = -1; |
2145 | StringRef Ident; |
2146 | if (Base.is<TypeInfoLValue>()) |
2147 | InvalidBaseKind = 0; |
2148 | else if (isa_and_nonnull<StringLiteral>(BaseE)) |
2149 | InvalidBaseKind = 1; |
2150 | else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || |
2151 | isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) |
2152 | InvalidBaseKind = 2; |
2153 | else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { |
2154 | InvalidBaseKind = 3; |
2155 | Ident = PE->getIdentKindName(); |
2156 | } |
2157 | |
2158 | if (InvalidBaseKind != -1) { |
2159 | Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) |
2160 | << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind |
2161 | << Ident; |
2162 | return false; |
2163 | } |
2164 | } |
2165 | |
2166 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { |
2167 | if (FD->isConsteval()) { |
2168 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) |
2169 | << !Type->isAnyPointerType(); |
2170 | Info.Note(FD->getLocation(), diag::note_declared_at); |
2171 | return false; |
2172 | } |
2173 | } |
2174 | |
2175 | // Check that the object is a global. Note that the fake 'this' object we |
2176 | // manufacture when checking potential constant expressions is conservatively |
2177 | // assumed to be global here. |
2178 | if (!IsGlobalLValue(Base)) { |
2179 | if (Info.getLangOpts().CPlusPlus11) { |
2180 | Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) |
2181 | << IsReferenceType << !Designator.Entries.empty() << !!BaseVD |
2182 | << BaseVD; |
2183 | auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD); |
2184 | if (VarD && VarD->isConstexpr()) { |
2185 | // Non-static local constexpr variables have unintuitive semantics: |
2186 | // constexpr int a = 1; |
2187 | // constexpr const int *p = &a; |
2188 | // ... is invalid because the address of 'a' is not constant. Suggest |
2189 | // adding a 'static' in this case. |
2190 | Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) |
2191 | << VarD |
2192 | << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); |
2193 | } else { |
2194 | NoteLValueLocation(Info, Base); |
2195 | } |
2196 | } else { |
2197 | Info.FFDiag(Loc); |
2198 | } |
2199 | // Don't allow references to temporaries to escape. |
2200 | return false; |
2201 | } |
2202 | assert((Info.checkingPotentialConstantExpression() ||(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__ )) |
2203 | LVal.getLValueCallIndex() == 0) &&(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__ )) |
2204 | "have call index for global lvalue")(static_cast <bool> ((Info.checkingPotentialConstantExpression () || LVal.getLValueCallIndex() == 0) && "have call index for global lvalue" ) ? void (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "clang/lib/AST/ExprConstant.cpp", 2204, __extension__ __PRETTY_FUNCTION__ )); |
2205 | |
2206 | if (Base.is<DynamicAllocLValue>()) { |
2207 | Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) |
2208 | << IsReferenceType << !Designator.Entries.empty(); |
2209 | NoteLValueLocation(Info, Base); |
2210 | return false; |
2211 | } |
2212 | |
2213 | if (BaseVD) { |
2214 | if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { |
2215 | // Check if this is a thread-local variable. |
2216 | if (Var->getTLSKind()) |
2217 | // FIXME: Diagnostic! |
2218 | return false; |
2219 | |
2220 | // A dllimport variable never acts like a constant, unless we're |
2221 | // evaluating a value for use only in name mangling. |
2222 | if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) |
2223 | // FIXME: Diagnostic! |
2224 | return false; |
2225 | |
2226 | // In CUDA/HIP device compilation, only device side variables have |
2227 | // constant addresses. |
2228 | if (Info.getCtx().getLangOpts().CUDA && |
2229 | Info.getCtx().getLangOpts().CUDAIsDevice && |
2230 | Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) { |
2231 | if ((!Var->hasAttr<CUDADeviceAttr>() && |
2232 | !Var->hasAttr<CUDAConstantAttr>() && |
2233 | !Var->getType()->isCUDADeviceBuiltinSurfaceType() && |
2234 | !Var->getType()->isCUDADeviceBuiltinTextureType()) || |
2235 | Var->hasAttr<HIPManagedAttr>()) |
2236 | return false; |
2237 | } |
2238 | } |
2239 | if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { |
2240 | // __declspec(dllimport) must be handled very carefully: |
2241 | // We must never initialize an expression with the thunk in C++. |
2242 | // Doing otherwise would allow the same id-expression to yield |
2243 | // different addresses for the same function in different translation |
2244 | // units. However, this means that we must dynamically initialize the |
2245 | // expression with the contents of the import address table at runtime. |
2246 | // |
2247 | // The C language has no notion of ODR; furthermore, it has no notion of |
2248 | // dynamic initialization. This means that we are permitted to |
2249 | // perform initialization with the address of the thunk. |
2250 | if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && |
2251 | FD->hasAttr<DLLImportAttr>()) |
2252 | // FIXME: Diagnostic! |
2253 | return false; |
2254 | } |
2255 | } else if (const auto *MTE = |
2256 | dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { |
2257 | if (CheckedTemps.insert(MTE).second) { |
2258 | QualType TempType = getType(Base); |
2259 | if (TempType.isDestructedType()) { |
2260 | Info.FFDiag(MTE->getExprLoc(), |
2261 | diag::note_constexpr_unsupported_temporary_nontrivial_dtor) |
2262 | << TempType; |
2263 | return false; |
2264 | } |
2265 | |
2266 | APValue *V = MTE->getOrCreateValue(false); |
2267 | assert(V && "evasluation result refers to uninitialised temporary")(static_cast <bool> (V && "evasluation result refers to uninitialised temporary" ) ? void (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\"" , "clang/lib/AST/ExprConstant.cpp", 2267, __extension__ __PRETTY_FUNCTION__ )); |
2268 | if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, |
2269 | Info, MTE->getExprLoc(), TempType, *V, |
2270 | Kind, SourceLocation(), CheckedTemps)) |
2271 | return false; |
2272 | } |
2273 | } |
2274 | |
2275 | // Allow address constant expressions to be past-the-end pointers. This is |
2276 | // an extension: the standard requires them to point to an object. |
2277 | if (!IsReferenceType) |
2278 | return true; |
2279 | |
2280 | // A reference constant expression must refer to an object. |
2281 | if (!Base) { |
2282 | // FIXME: diagnostic |
2283 | Info.CCEDiag(Loc); |
2284 | return true; |
2285 | } |
2286 | |
2287 | // Does this refer one past the end of some object? |
2288 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { |
2289 | Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) |
2290 | << !Designator.Entries.empty() << !!BaseVD << BaseVD; |
2291 | NoteLValueLocation(Info, Base); |
2292 | } |
2293 | |
2294 | return true; |
2295 | } |
2296 | |
2297 | /// Member pointers are constant expressions unless they point to a |
2298 | /// non-virtual dllimport member function. |
2299 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, |
2300 | SourceLocation Loc, |
2301 | QualType Type, |
2302 | const APValue &Value, |
2303 | ConstantExprKind Kind) { |
2304 | const ValueDecl *Member = Value.getMemberPointerDecl(); |
2305 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); |
2306 | if (!FD) |
2307 | return true; |
2308 | if (FD->isConsteval()) { |
2309 | Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; |
2310 | Info.Note(FD->getLocation(), diag::note_declared_at); |
2311 | return false; |
2312 | } |
2313 | return isForManglingOnly(Kind) || FD->isVirtual() || |
2314 | !FD->hasAttr<DLLImportAttr>(); |
2315 | } |
2316 | |
2317 | /// Check that this core constant expression is of literal type, and if not, |
2318 | /// produce an appropriate diagnostic. |
2319 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, |
2320 | const LValue *This = nullptr) { |
2321 | if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) |
2322 | return true; |
2323 | |
2324 | // C++1y: A constant initializer for an object o [...] may also invoke |
2325 | // constexpr constructors for o and its subobjects even if those objects |
2326 | // are of non-literal class types. |
2327 | // |
2328 | // C++11 missed this detail for aggregates, so classes like this: |
2329 | // struct foo_t { union { int i; volatile int j; } u; }; |
2330 | // are not (obviously) initializable like so: |
2331 | // __attribute__((__require_constant_initialization__)) |
2332 | // static const foo_t x = {{0}}; |
2333 | // because "i" is a subobject with non-literal initialization (due to the |
2334 | // volatile member of the union). See: |
2335 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 |
2336 | // Therefore, we use the C++1y behavior. |
2337 | if (This && Info.EvaluatingDecl == This->getLValueBase()) |
2338 | return true; |
2339 | |
2340 | // Prvalue constant expressions must be of literal types. |
2341 | if (Info.getLangOpts().CPlusPlus11) |
2342 | Info.FFDiag(E, diag::note_constexpr_nonliteral) |
2343 | << E->getType(); |
2344 | else |
2345 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); |
2346 | return false; |
2347 | } |
2348 | |
2349 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, |
2350 | EvalInfo &Info, SourceLocation DiagLoc, |
2351 | QualType Type, const APValue &Value, |
2352 | ConstantExprKind Kind, |
2353 | SourceLocation SubobjectLoc, |
2354 | CheckedTemporaries &CheckedTemps) { |
2355 | if (!Value.hasValue()) { |
2356 | Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) |
2357 | << true << Type; |
2358 | if (SubobjectLoc.isValid()) |
2359 | Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); |
2360 | return false; |
2361 | } |
2362 | |
2363 | // We allow _Atomic(T) to be initialized from anything that T can be |
2364 | // initialized from. |
2365 | if (const AtomicType *AT = Type->getAs<AtomicType>()) |
2366 | Type = AT->getValueType(); |
2367 | |
2368 | // Core issue 1454: For a literal constant expression of array or class type, |
2369 | // each subobject of its value shall have been initialized by a constant |
2370 | // expression. |
2371 | if (Value.isArray()) { |
2372 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); |
2373 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { |
2374 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, |
2375 | Value.getArrayInitializedElt(I), Kind, |
2376 | SubobjectLoc, CheckedTemps)) |
2377 | return false; |
2378 | } |
2379 | if (!Value.hasArrayFiller()) |
2380 | return true; |
2381 | return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, |
2382 | Value.getArrayFiller(), Kind, SubobjectLoc, |
2383 | CheckedTemps); |
2384 | } |
2385 | if (Value.isUnion() && Value.getUnionField()) { |
2386 | return CheckEvaluationResult( |
2387 | CERK, Info, DiagLoc, Value.getUnionField()->getType(), |
2388 | Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), |
2389 | CheckedTemps); |
2390 | } |
2391 | if (Value.isStruct()) { |
2392 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); |
2393 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { |
2394 | unsigned BaseIndex = 0; |
2395 | for (const CXXBaseSpecifier &BS : CD->bases()) { |
2396 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), |
2397 | Value.getStructBase(BaseIndex), Kind, |
2398 | BS.getBeginLoc(), CheckedTemps)) |
2399 | return false; |
2400 | ++BaseIndex; |
2401 | } |
2402 | } |
2403 | for (const auto *I : RD->fields()) { |
2404 | if (I->isUnnamedBitfield()) |
2405 | continue; |
2406 | |
2407 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), |
2408 | Value.getStructField(I->getFieldIndex()), |
2409 | Kind, I->getLocation(), CheckedTemps)) |
2410 | return false; |
2411 | } |
2412 | } |
2413 | |
2414 | if (Value.isLValue() && |
2415 | CERK == CheckEvaluationResultKind::ConstantExpression) { |
2416 | LValue LVal; |
2417 | LVal.setFrom(Info.Ctx, Value); |
2418 | return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, |
2419 | CheckedTemps); |
2420 | } |
2421 | |
2422 | if (Value.isMemberPointer() && |
2423 | CERK == CheckEvaluationResultKind::ConstantExpression) |
2424 | return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); |
2425 | |
2426 | // Everything else is fine. |
2427 | return true; |
2428 | } |
2429 | |
2430 | /// Check that this core constant expression value is a valid value for a |
2431 | /// constant expression. If not, report an appropriate diagnostic. Does not |
2432 | /// check that the expression is of literal type. |
2433 | static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, |
2434 | QualType Type, const APValue &Value, |
2435 | ConstantExprKind Kind) { |
2436 | // Nothing to check for a constant expression of type 'cv void'. |
2437 | if (Type->isVoidType()) |
2438 | return true; |
2439 | |
2440 | CheckedTemporaries CheckedTemps; |
2441 | return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, |
2442 | Info, DiagLoc, Type, Value, Kind, |
2443 | SourceLocation(), CheckedTemps); |
2444 | } |
2445 | |
2446 | /// Check that this evaluated value is fully-initialized and can be loaded by |
2447 | /// an lvalue-to-rvalue conversion. |
2448 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, |
2449 | QualType Type, const APValue &Value) { |
2450 | CheckedTemporaries CheckedTemps; |
2451 | return CheckEvaluationResult( |
2452 | CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, |
2453 | ConstantExprKind::Normal, SourceLocation(), CheckedTemps); |
2454 | } |
2455 | |
2456 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless |
2457 | /// "the allocated storage is deallocated within the evaluation". |
2458 | static bool CheckMemoryLeaks(EvalInfo &Info) { |
2459 | if (!Info.HeapAllocs.empty()) { |
2460 | // We can still fold to a constant despite a compile-time memory leak, |
2461 | // so long as the heap allocation isn't referenced in the result (we check |
2462 | // that in CheckConstantExpression). |
2463 | Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, |
2464 | diag::note_constexpr_memory_leak) |
2465 | << unsigned(Info.HeapAllocs.size() - 1); |
2466 | } |
2467 | return true; |
2468 | } |
2469 | |
2470 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { |
2471 | // A null base expression indicates a null pointer. These are always |
2472 | // evaluatable, and they are false unless the offset is zero. |
2473 | if (!Value.getLValueBase()) { |
2474 | // TODO: Should a non-null pointer with an offset of zero evaluate to true? |
2475 | Result = !Value.getLValueOffset().isZero(); |
2476 | return true; |
2477 | } |
2478 | |
2479 | // We have a non-null base. These are generally known to be true, but if it's |
2480 | // a weak declaration it can be null at runtime. |
2481 | Result = true; |
2482 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); |
2483 | return !Decl || !Decl->isWeak(); |
2484 | } |
2485 | |
2486 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { |
2487 | // TODO: This function should produce notes if it fails. |
2488 | switch (Val.getKind()) { |
2489 | case APValue::None: |
2490 | case APValue::Indeterminate: |
2491 | return false; |
2492 | case APValue::Int: |
2493 | Result = Val.getInt().getBoolValue(); |
2494 | return true; |
2495 | case APValue::FixedPoint: |
2496 | Result = Val.getFixedPoint().getBoolValue(); |
2497 | return true; |
2498 | case APValue::Float: |
2499 | Result = !Val.getFloat().isZero(); |
2500 | return true; |
2501 | case APValue::ComplexInt: |
2502 | Result = Val.getComplexIntReal().getBoolValue() || |
2503 | Val.getComplexIntImag().getBoolValue(); |
2504 | return true; |
2505 | case APValue::ComplexFloat: |
2506 | Result = !Val.getComplexFloatReal().isZero() || |
2507 | !Val.getComplexFloatImag().isZero(); |
2508 | return true; |
2509 | case APValue::LValue: |
2510 | return EvalPointerValueAsBool(Val, Result); |
2511 | case APValue::MemberPointer: |
2512 | if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) { |
2513 | return false; |
2514 | } |
2515 | Result = Val.getMemberPointerDecl(); |
2516 | return true; |
2517 | case APValue::Vector: |
2518 | case APValue::Array: |
2519 | case APValue::Struct: |
2520 | case APValue::Union: |
2521 | case APValue::AddrLabelDiff: |
2522 | return false; |
2523 | } |
2524 | |
2525 | llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "clang/lib/AST/ExprConstant.cpp" , 2525); |
2526 | } |
2527 | |
2528 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, |
2529 | EvalInfo &Info) { |
2530 | assert(!E->isValueDependent())(static_cast <bool> (!E->isValueDependent()) ? void ( 0) : __assert_fail ("!E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 2530, __extension__ __PRETTY_FUNCTION__)); |
2531 | assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition")(static_cast <bool> (E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition" ) ? void (0) : __assert_fail ("E->isPRValue() && \"missing lvalue-to-rvalue conv in bool condition\"" , "clang/lib/AST/ExprConstant.cpp", 2531, __extension__ __PRETTY_FUNCTION__ )); |
2532 | APValue Val; |
2533 | if (!Evaluate(Val, Info, E)) |
2534 | return false; |
2535 | return HandleConversionToBool(Val, Result); |
2536 | } |
2537 | |
2538 | template<typename T> |
2539 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, |
2540 | const T &SrcValue, QualType DestType) { |
2541 | Info.CCEDiag(E, diag::note_constexpr_overflow) |
2542 | << SrcValue << DestType; |
2543 | return Info.noteUndefinedBehavior(); |
2544 | } |
2545 | |
2546 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, |
2547 | QualType SrcType, const APFloat &Value, |
2548 | QualType DestType, APSInt &Result) { |
2549 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); |
2550 | // Determine whether we are converting to unsigned or signed. |
2551 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); |
2552 | |
2553 | Result = APSInt(DestWidth, !DestSigned); |
2554 | bool ignored; |
2555 | if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) |
2556 | & APFloat::opInvalidOp) |
2557 | return HandleOverflow(Info, E, Value, DestType); |
2558 | return true; |
2559 | } |
2560 | |
2561 | /// Get rounding mode to use in evaluation of the specified expression. |
2562 | /// |
2563 | /// If rounding mode is unknown at compile time, still try to evaluate the |
2564 | /// expression. If the result is exact, it does not depend on rounding mode. |
2565 | /// So return "tonearest" mode instead of "dynamic". |
2566 | static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) { |
2567 | llvm::RoundingMode RM = |
2568 | E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); |
2569 | if (RM == llvm::RoundingMode::Dynamic) |
2570 | RM = llvm::RoundingMode::NearestTiesToEven; |
2571 | return RM; |
2572 | } |
2573 | |
2574 | /// Check if the given evaluation result is allowed for constant evaluation. |
2575 | static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, |
2576 | APFloat::opStatus St) { |
2577 | // In a constant context, assume that any dynamic rounding mode or FP |
2578 | // exception state matches the default floating-point environment. |
2579 | if (Info.InConstantContext) |
2580 | return true; |
2581 | |
2582 | FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); |
2583 | if ((St & APFloat::opInexact) && |
2584 | FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { |
2585 | // Inexact result means that it depends on rounding mode. If the requested |
2586 | // mode is dynamic, the evaluation cannot be made in compile time. |
2587 | Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); |
2588 | return false; |
2589 | } |
2590 | |
2591 | if ((St != APFloat::opOK) && |
2592 | (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || |
2593 | FPO.getExceptionMode() != LangOptions::FPE_Ignore || |
2594 | FPO.getAllowFEnvAccess())) { |
2595 | Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); |
2596 | return false; |
2597 | } |
2598 | |
2599 | if ((St & APFloat::opStatus::opInvalidOp) && |
2600 | FPO.getExceptionMode() != LangOptions::FPE_Ignore) { |
2601 | // There is no usefully definable result. |
2602 | Info.FFDiag(E); |
2603 | return false; |
2604 | } |
2605 | |
2606 | // FIXME: if: |
2607 | // - evaluation triggered other FP exception, and |
2608 | // - exception mode is not "ignore", and |
2609 | // - the expression being evaluated is not a part of global variable |
2610 | // initializer, |
2611 | // the evaluation probably need to be rejected. |
2612 | return true; |
2613 | } |
2614 | |
2615 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, |
2616 | QualType SrcType, QualType DestType, |
2617 | APFloat &Result) { |
2618 | assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E))(static_cast <bool> (isa<CastExpr>(E) || isa<CompoundAssignOperator >(E)) ? void (0) : __assert_fail ("isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)" , "clang/lib/AST/ExprConstant.cpp", 2618, __extension__ __PRETTY_FUNCTION__ )); |
2619 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
2620 | APFloat::opStatus St; |
2621 | APFloat Value = Result; |
2622 | bool ignored; |
2623 | St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); |
2624 | return checkFloatingPointResult(Info, E, St); |
2625 | } |
2626 | |
2627 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, |
2628 | QualType DestType, QualType SrcType, |
2629 | const APSInt &Value) { |
2630 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); |
2631 | // Figure out if this is a truncate, extend or noop cast. |
2632 | // If the input is signed, do a sign extend, noop, or truncate. |
2633 | APSInt Result = Value.extOrTrunc(DestWidth); |
2634 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); |
2635 | if (DestType->isBooleanType()) |
2636 | Result = Value.getBoolValue(); |
2637 | return Result; |
2638 | } |
2639 | |
2640 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, |
2641 | const FPOptions FPO, |
2642 | QualType SrcType, const APSInt &Value, |
2643 | QualType DestType, APFloat &Result) { |
2644 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); |
2645 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
2646 | APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM); |
2647 | return checkFloatingPointResult(Info, E, St); |
2648 | } |
2649 | |
2650 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, |
2651 | APValue &Value, const FieldDecl *FD) { |
2652 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")(static_cast <bool> (FD->isBitField() && "truncateBitfieldValue on non-bitfield" ) ? void (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\"" , "clang/lib/AST/ExprConstant.cpp", 2652, __extension__ __PRETTY_FUNCTION__ )); |
2653 | |
2654 | if (!Value.isInt()) { |
2655 | // Trying to store a pointer-cast-to-integer into a bitfield. |
2656 | // FIXME: In this case, we should provide the diagnostic for casting |
2657 | // a pointer to an integer. |
2658 | assert(Value.isLValue() && "integral value neither int nor lvalue?")(static_cast <bool> (Value.isLValue() && "integral value neither int nor lvalue?" ) ? void (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\"" , "clang/lib/AST/ExprConstant.cpp", 2658, __extension__ __PRETTY_FUNCTION__ )); |
2659 | Info.FFDiag(E); |
2660 | return false; |
2661 | } |
2662 | |
2663 | APSInt &Int = Value.getInt(); |
2664 | unsigned OldBitWidth = Int.getBitWidth(); |
2665 | unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); |
2666 | if (NewBitWidth < OldBitWidth) |
2667 | Int = Int.trunc(NewBitWidth).extend(OldBitWidth); |
2668 | return true; |
2669 | } |
2670 | |
2671 | static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, |
2672 | llvm::APInt &Res) { |
2673 | APValue SVal; |
2674 | if (!Evaluate(SVal, Info, E)) |
2675 | return false; |
2676 | if (SVal.isInt()) { |
2677 | Res = SVal.getInt(); |
2678 | return true; |
2679 | } |
2680 | if (SVal.isFloat()) { |
2681 | Res = SVal.getFloat().bitcastToAPInt(); |
2682 | return true; |
2683 | } |
2684 | if (SVal.isVector()) { |
2685 | QualType VecTy = E->getType(); |
2686 | unsigned VecSize = Info.Ctx.getTypeSize(VecTy); |
2687 | QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); |
2688 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); |
2689 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); |
2690 | Res = llvm::APInt::getZero(VecSize); |
2691 | for (unsigned i = 0; i < SVal.getVectorLength(); i++) { |
2692 | APValue &Elt = SVal.getVectorElt(i); |
2693 | llvm::APInt EltAsInt; |
2694 | if (Elt.isInt()) { |
2695 | EltAsInt = Elt.getInt(); |
2696 | } else if (Elt.isFloat()) { |
2697 | EltAsInt = Elt.getFloat().bitcastToAPInt(); |
2698 | } else { |
2699 | // Don't try to handle vectors of anything other than int or float |
2700 | // (not sure if it's possible to hit this case). |
2701 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); |
2702 | return false; |
2703 | } |
2704 | unsigned BaseEltSize = EltAsInt.getBitWidth(); |
2705 | if (BigEndian) |
2706 | Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); |
2707 | else |
2708 | Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); |
2709 | } |
2710 | return true; |
2711 | } |
2712 | // Give up if the input isn't an int, float, or vector. For example, we |
2713 | // reject "(v4i16)(intptr_t)&a". |
2714 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); |
2715 | return false; |
2716 | } |
2717 | |
2718 | /// Perform the given integer operation, which is known to need at most BitWidth |
2719 | /// bits, and check for overflow in the original type (if that type was not an |
2720 | /// unsigned type). |
2721 | template<typename Operation> |
2722 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, |
2723 | const APSInt &LHS, const APSInt &RHS, |
2724 | unsigned BitWidth, Operation Op, |
2725 | APSInt &Result) { |
2726 | if (LHS.isUnsigned()) { |
2727 | Result = Op(LHS, RHS); |
2728 | return true; |
2729 | } |
2730 | |
2731 | APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); |
2732 | Result = Value.trunc(LHS.getBitWidth()); |
2733 | if (Result.extend(BitWidth) != Value) { |
2734 | if (Info.checkingForUndefinedBehavior()) |
2735 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), |
2736 | diag::warn_integer_constant_overflow) |
2737 | << toString(Result, 10) << E->getType(); |
2738 | return HandleOverflow(Info, E, Value, E->getType()); |
2739 | } |
2740 | return true; |
2741 | } |
2742 | |
2743 | /// Perform the given binary integer operation. |
2744 | static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, |
2745 | BinaryOperatorKind Opcode, APSInt RHS, |
2746 | APSInt &Result) { |
2747 | bool HandleOverflowResult = true; |
2748 | switch (Opcode) { |
2749 | default: |
2750 | Info.FFDiag(E); |
2751 | return false; |
2752 | case BO_Mul: |
2753 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, |
2754 | std::multiplies<APSInt>(), Result); |
2755 | case BO_Add: |
2756 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, |
2757 | std::plus<APSInt>(), Result); |
2758 | case BO_Sub: |
2759 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, |
2760 | std::minus<APSInt>(), Result); |
2761 | case BO_And: Result = LHS & RHS; return true; |
2762 | case BO_Xor: Result = LHS ^ RHS; return true; |
2763 | case BO_Or: Result = LHS | RHS; return true; |
2764 | case BO_Div: |
2765 | case BO_Rem: |
2766 | if (RHS == 0) { |
2767 | Info.FFDiag(E, diag::note_expr_divide_by_zero); |
2768 | return false; |
2769 | } |
2770 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports |
2771 | // this operation and gives the two's complement result. |
2772 | if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() && |
2773 | LHS.isMinSignedValue()) |
2774 | HandleOverflowResult = HandleOverflow( |
2775 | Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); |
2776 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); |
2777 | return HandleOverflowResult; |
2778 | case BO_Shl: { |
2779 | if (Info.getLangOpts().OpenCL) |
2780 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
2781 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), |
2782 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), |
2783 | RHS.isUnsigned()); |
2784 | else if (RHS.isSigned() && RHS.isNegative()) { |
2785 | // During constant-folding, a negative shift is an opposite shift. Such |
2786 | // a shift is not a constant expression. |
2787 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; |
2788 | RHS = -RHS; |
2789 | goto shift_right; |
2790 | } |
2791 | shift_left: |
2792 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of |
2793 | // the shifted type. |
2794 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); |
2795 | if (SA != RHS) { |
2796 | Info.CCEDiag(E, diag::note_constexpr_large_shift) |
2797 | << RHS << E->getType() << LHS.getBitWidth(); |
2798 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { |
2799 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative |
2800 | // operand, and must not overflow the corresponding unsigned type. |
2801 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to |
2802 | // E1 x 2^E2 module 2^N. |
2803 | if (LHS.isNegative()) |
2804 | Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; |
2805 | else if (LHS.countl_zero() < SA) |
2806 | Info.CCEDiag(E, diag::note_constexpr_lshift_discards); |
2807 | } |
2808 | Result = LHS << SA; |
2809 | return true; |
2810 | } |
2811 | case BO_Shr: { |
2812 | if (Info.getLangOpts().OpenCL) |
2813 | // OpenCL 6.3j: shift values are effectively % word size of LHS. |
2814 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), |
2815 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), |
2816 | RHS.isUnsigned()); |
2817 | else if (RHS.isSigned() && RHS.isNegative()) { |
2818 | // During constant-folding, a negative shift is an opposite shift. Such a |
2819 | // shift is not a constant expression. |
2820 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; |
2821 | RHS = -RHS; |
2822 | goto shift_left; |
2823 | } |
2824 | shift_right: |
2825 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the |
2826 | // shifted type. |
2827 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); |
2828 | if (SA != RHS) |
2829 | Info.CCEDiag(E, diag::note_constexpr_large_shift) |
2830 | << RHS << E->getType() << LHS.getBitWidth(); |
2831 | Result = LHS >> SA; |
2832 | return true; |
2833 | } |
2834 | |
2835 | case BO_LT: Result = LHS < RHS; return true; |
2836 | case BO_GT: Result = LHS > RHS; return true; |
2837 | case BO_LE: Result = LHS <= RHS; return true; |
2838 | case BO_GE: Result = LHS >= RHS; return true; |
2839 | case BO_EQ: Result = LHS == RHS; return true; |
2840 | case BO_NE: Result = LHS != RHS; return true; |
2841 | case BO_Cmp: |
2842 | llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere" , "clang/lib/AST/ExprConstant.cpp", 2842); |
2843 | } |
2844 | } |
2845 | |
2846 | /// Perform the given binary floating-point operation, in-place, on LHS. |
2847 | static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, |
2848 | APFloat &LHS, BinaryOperatorKind Opcode, |
2849 | const APFloat &RHS) { |
2850 | llvm::RoundingMode RM = getActiveRoundingMode(Info, E); |
2851 | APFloat::opStatus St; |
2852 | switch (Opcode) { |
2853 | default: |
2854 | Info.FFDiag(E); |
2855 | return false; |
2856 | case BO_Mul: |
2857 | St = LHS.multiply(RHS, RM); |
2858 | break; |
2859 | case BO_Add: |
2860 | St = LHS.add(RHS, RM); |
2861 | break; |
2862 | case BO_Sub: |
2863 | St = LHS.subtract(RHS, RM); |
2864 | break; |
2865 | case BO_Div: |
2866 | // [expr.mul]p4: |
2867 | // If the second operand of / or % is zero the behavior is undefined. |
2868 | if (RHS.isZero()) |
2869 | Info.CCEDiag(E, diag::note_expr_divide_by_zero); |
2870 | St = LHS.divide(RHS, RM); |
2871 | break; |
2872 | } |
2873 | |
2874 | // [expr.pre]p4: |
2875 | // If during the evaluation of an expression, the result is not |
2876 | // mathematically defined [...], the behavior is undefined. |
2877 | // FIXME: C++ rules require us to not conform to IEEE 754 here. |
2878 | if (LHS.isNaN()) { |
2879 | Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); |
2880 | return Info.noteUndefinedBehavior(); |
2881 | } |
2882 | |
2883 | return checkFloatingPointResult(Info, E, St); |
2884 | } |
2885 | |
2886 | static bool handleLogicalOpForVector(const APInt &LHSValue, |
2887 | BinaryOperatorKind Opcode, |
2888 | const APInt &RHSValue, APInt &Result) { |
2889 | bool LHS = (LHSValue != 0); |
2890 | bool RHS = (RHSValue != 0); |
2891 | |
2892 | if (Opcode == BO_LAnd) |
2893 | Result = LHS && RHS; |
2894 | else |
2895 | Result = LHS || RHS; |
2896 | return true; |
2897 | } |
2898 | static bool handleLogicalOpForVector(const APFloat &LHSValue, |
2899 | BinaryOperatorKind Opcode, |
2900 | const APFloat &RHSValue, APInt &Result) { |
2901 | bool LHS = !LHSValue.isZero(); |
2902 | bool RHS = !RHSValue.isZero(); |
2903 | |
2904 | if (Opcode == BO_LAnd) |
2905 | Result = LHS && RHS; |
2906 | else |
2907 | Result = LHS || RHS; |
2908 | return true; |
2909 | } |
2910 | |
2911 | static bool handleLogicalOpForVector(const APValue &LHSValue, |
2912 | BinaryOperatorKind Opcode, |
2913 | const APValue &RHSValue, APInt &Result) { |
2914 | // The result is always an int type, however operands match the first. |
2915 | if (LHSValue.getKind() == APValue::Int) |
2916 | return handleLogicalOpForVector(LHSValue.getInt(), Opcode, |
2917 | RHSValue.getInt(), Result); |
2918 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "clang/lib/AST/ExprConstant.cpp", 2918, __extension__ __PRETTY_FUNCTION__ )); |
2919 | return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, |
2920 | RHSValue.getFloat(), Result); |
2921 | } |
2922 | |
2923 | template <typename APTy> |
2924 | static bool |
2925 | handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, |
2926 | const APTy &RHSValue, APInt &Result) { |
2927 | switch (Opcode) { |
2928 | default: |
2929 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "clang/lib/AST/ExprConstant.cpp", 2929); |
2930 | case BO_EQ: |
2931 | Result = (LHSValue == RHSValue); |
2932 | break; |
2933 | case BO_NE: |
2934 | Result = (LHSValue != RHSValue); |
2935 | break; |
2936 | case BO_LT: |
2937 | Result = (LHSValue < RHSValue); |
2938 | break; |
2939 | case BO_GT: |
2940 | Result = (LHSValue > RHSValue); |
2941 | break; |
2942 | case BO_LE: |
2943 | Result = (LHSValue <= RHSValue); |
2944 | break; |
2945 | case BO_GE: |
2946 | Result = (LHSValue >= RHSValue); |
2947 | break; |
2948 | } |
2949 | |
2950 | // The boolean operations on these vector types use an instruction that |
2951 | // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1 |
2952 | // to -1 to make sure that we produce the correct value. |
2953 | Result.negate(); |
2954 | |
2955 | return true; |
2956 | } |
2957 | |
2958 | static bool handleCompareOpForVector(const APValue &LHSValue, |
2959 | BinaryOperatorKind Opcode, |
2960 | const APValue &RHSValue, APInt &Result) { |
2961 | // The result is always an int type, however operands match the first. |
2962 | if (LHSValue.getKind() == APValue::Int) |
2963 | return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, |
2964 | RHSValue.getInt(), Result); |
2965 | assert(LHSValue.getKind() == APValue::Float && "Should be no other options")(static_cast <bool> (LHSValue.getKind() == APValue::Float && "Should be no other options") ? void (0) : __assert_fail ("LHSValue.getKind() == APValue::Float && \"Should be no other options\"" , "clang/lib/AST/ExprConstant.cpp", 2965, __extension__ __PRETTY_FUNCTION__ )); |
2966 | return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, |
2967 | RHSValue.getFloat(), Result); |
2968 | } |
2969 | |
2970 | // Perform binary operations for vector types, in place on the LHS. |
2971 | static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, |
2972 | BinaryOperatorKind Opcode, |
2973 | APValue &LHSValue, |
2974 | const APValue &RHSValue) { |
2975 | assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 2976, __extension__ __PRETTY_FUNCTION__ )) |
2976 | "Operation not supported on vector types")(static_cast <bool> (Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types" ) ? void (0) : __assert_fail ("Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && \"Operation not supported on vector types\"" , "clang/lib/AST/ExprConstant.cpp", 2976, __extension__ __PRETTY_FUNCTION__ )); |
2977 | |
2978 | const auto *VT = E->getType()->castAs<VectorType>(); |
2979 | unsigned NumElements = VT->getNumElements(); |
2980 | QualType EltTy = VT->getElementType(); |
2981 | |
2982 | // In the cases (typically C as I've observed) where we aren't evaluating |
2983 | // constexpr but are checking for cases where the LHS isn't yet evaluatable, |
2984 | // just give up. |
2985 | if (!LHSValue.isVector()) { |
2986 | assert(LHSValue.isLValue() &&(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "clang/lib/AST/ExprConstant.cpp", 2987, __extension__ __PRETTY_FUNCTION__ )) |
2987 | "A vector result that isn't a vector OR uncalculated LValue")(static_cast <bool> (LHSValue.isLValue() && "A vector result that isn't a vector OR uncalculated LValue" ) ? void (0) : __assert_fail ("LHSValue.isLValue() && \"A vector result that isn't a vector OR uncalculated LValue\"" , "clang/lib/AST/ExprConstant.cpp", 2987, __extension__ __PRETTY_FUNCTION__ )); |
2988 | Info.FFDiag(E); |
2989 | return false; |
2990 | } |
2991 | |
2992 | assert(LHSValue.getVectorLength() == NumElements &&(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "clang/lib/AST/ExprConstant.cpp", 2993, __extension__ __PRETTY_FUNCTION__ )) |
2993 | RHSValue.getVectorLength() == NumElements && "Different vector sizes")(static_cast <bool> (LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && "Different vector sizes") ? void (0) : __assert_fail ("LHSValue.getVectorLength() == NumElements && RHSValue.getVectorLength() == NumElements && \"Different vector sizes\"" , "clang/lib/AST/ExprConstant.cpp", 2993, __extension__ __PRETTY_FUNCTION__ )); |
2994 | |
2995 | SmallVector<APValue, 4> ResultElements; |
2996 | |
2997 | for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { |
2998 | APValue LHSElt = LHSValue.getVectorElt(EltNum); |
2999 | APValue RHSElt = RHSValue.getVectorElt(EltNum); |
3000 | |
3001 | if (EltTy->isIntegerType()) { |
3002 | APSInt EltResult{Info.Ctx.getIntWidth(EltTy), |
3003 | EltTy->isUnsignedIntegerType()}; |
3004 | bool Success = true; |
3005 | |
3006 | if (BinaryOperator::isLogicalOp(Opcode)) |
3007 | Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); |
3008 | else if (BinaryOperator::isComparisonOp(Opcode)) |
3009 | Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); |
3010 | else |
3011 | Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, |
3012 | RHSElt.getInt(), EltResult); |
3013 | |
3014 | if (!Success) { |
3015 | Info.FFDiag(E); |
3016 | return false; |
3017 | } |
3018 | ResultElements.emplace_back(EltResult); |
3019 | |
3020 | } else if (EltTy->isFloatingType()) { |
3021 | assert(LHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__ )) |
3022 | RHSElt.getKind() == APValue::Float &&(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__ )) |
3023 | "Mismatched LHS/RHS/Result Type")(static_cast <bool> (LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && "Mismatched LHS/RHS/Result Type" ) ? void (0) : __assert_fail ("LHSElt.getKind() == APValue::Float && RHSElt.getKind() == APValue::Float && \"Mismatched LHS/RHS/Result Type\"" , "clang/lib/AST/ExprConstant.cpp", 3023, __extension__ __PRETTY_FUNCTION__ )); |
3024 | APFloat LHSFloat = LHSElt.getFloat(); |
3025 | |
3026 | if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, |
3027 | RHSElt.getFloat())) { |
3028 | Info.FFDiag(E); |
3029 | return false; |
3030 | } |
3031 | |
3032 | ResultElements.emplace_back(LHSFloat); |
3033 | } |
3034 | } |
3035 | |
3036 | LHSValue = APValue(ResultElements.data(), ResultElements.size()); |
3037 | return true; |
3038 | } |
3039 | |
3040 | /// Cast an lvalue referring to a base subobject to a derived class, by |
3041 | /// truncating the lvalue's path to the given length. |
3042 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, |
3043 | const RecordDecl *TruncatedType, |
3044 | unsigned TruncatedElements) { |
3045 | SubobjectDesignator &D = Result.Designator; |
3046 | |
3047 | // Check we actually point to a derived class object. |
3048 | if (TruncatedElements == D.Entries.size()) |
3049 | return true; |
3050 | assert(TruncatedElements >= D.MostDerivedPathLength &&(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "clang/lib/AST/ExprConstant.cpp", 3051, __extension__ __PRETTY_FUNCTION__ )) |
3051 | "not casting to a derived class")(static_cast <bool> (TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class") ? void (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "clang/lib/AST/ExprConstant.cpp", 3051, __extension__ __PRETTY_FUNCTION__ )); |
3052 | if (!Result.checkSubobject(Info, E, CSK_Derived)) |
3053 | return false; |
3054 | |
3055 | // Truncate the path to the subobject, and remove any derived-to-base offsets. |
3056 | const RecordDecl *RD = TruncatedType; |
3057 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { |
3058 | if (RD->isInvalidDecl()) return false; |
3059 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); |
3060 | const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); |
3061 | if (isVirtualBaseClass(D.Entries[I])) |
3062 | Result.Offset -= Layout.getVBaseClassOffset(Base); |
3063 | else |
3064 | Result.Offset -= Layout.getBaseClassOffset(Base); |
3065 | RD = Base; |
3066 | } |
3067 | D.Entries.resize(TruncatedElements); |
3068 | return true; |
3069 | } |
3070 | |
3071 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, |
3072 | const CXXRecordDecl *Derived, |
3073 | const CXXRecordDecl *Base, |
3074 | const ASTRecordLayout *RL = nullptr) { |
3075 | if (!RL) { |
3076 | if (Derived->isInvalidDecl()) return false; |
3077 | RL = &Info.Ctx.getASTRecordLayout(Derived); |
3078 | } |
3079 | |
3080 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); |
3081 | Obj.addDecl(Info, E, Base, /*Virtual*/ false); |
3082 | return true; |
3083 | } |
3084 | |
3085 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, |
3086 | const CXXRecordDecl *DerivedDecl, |
3087 | const CXXBaseSpecifier *Base) { |
3088 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); |
3089 | |
3090 | if (!Base->isVirtual()) |
3091 | return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); |
3092 | |
3093 | SubobjectDesignator &D = Obj.Designator; |
3094 | if (D.Invalid) |
3095 | return false; |
3096 | |
3097 | // Extract most-derived object and corresponding type. |
3098 | DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); |
3099 | if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) |
3100 | return false; |
3101 | |
3102 | // Find the virtual base class. |
3103 | if (DerivedDecl->isInvalidDecl()) return false; |
3104 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); |
3105 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); |
3106 | Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); |
3107 | return true; |
3108 | } |
3109 | |
3110 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, |
3111 | QualType Type, LValue &Result) { |
3112 | for (CastExpr::path_const_iterator PathI = E->path_begin(), |
3113 | PathE = E->path_end(); |
3114 | PathI != PathE; ++PathI) { |
3115 | if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), |
3116 | *PathI)) |
3117 | return false; |
3118 | Type = (*PathI)->getType(); |
3119 | } |
3120 | return true; |
3121 | } |
3122 | |
3123 | /// Cast an lvalue referring to a derived class to a known base subobject. |
3124 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, |
3125 | const CXXRecordDecl *DerivedRD, |
3126 | const CXXRecordDecl *BaseRD) { |
3127 | CXXBasePaths Paths(/*FindAmbiguities=*/false, |
3128 | /*RecordPaths=*/true, /*DetectVirtual=*/false); |
3129 | if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) |
3130 | llvm_unreachable("Class must be derived from the passed in base class!")::llvm::llvm_unreachable_internal("Class must be derived from the passed in base class!" , "clang/lib/AST/ExprConstant.cpp", 3130); |
3131 | |
3132 | for (CXXBasePathElement &Elem : Paths.front()) |
3133 | if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) |
3134 | return false; |
3135 | return true; |
3136 | } |
3137 | |
3138 | /// Update LVal to refer to the given field, which must be a member of the type |
3139 | /// currently described by LVal. |
3140 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, |
3141 | const FieldDecl *FD, |
3142 | const ASTRecordLayout *RL = nullptr) { |
3143 | if (!RL) { |
3144 | if (FD->getParent()->isInvalidDecl()) return false; |
3145 | RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); |
3146 | } |
3147 | |
3148 | unsigned I = FD->getFieldIndex(); |
3149 | LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); |
3150 | LVal.addDecl(Info, E, FD); |
3151 | return true; |
3152 | } |
3153 | |
3154 | /// Update LVal to refer to the given indirect field. |
3155 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, |
3156 | LValue &LVal, |
3157 | const IndirectFieldDecl *IFD) { |
3158 | for (const auto *C : IFD->chain()) |
3159 | if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) |
3160 | return false; |
3161 | return true; |
3162 | } |
3163 | |
3164 | /// Get the size of the given type in char units. |
3165 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, |
3166 | QualType Type, CharUnits &Size) { |
3167 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc |
3168 | // extension. |
3169 | if (Type->isVoidType() || Type->isFunctionType()) { |
3170 | Size = CharUnits::One(); |
3171 | return true; |
3172 | } |
3173 | |
3174 | if (Type->isDependentType()) { |
3175 | Info.FFDiag(Loc); |
3176 | return false; |
3177 | } |
3178 | |
3179 | if (!Type->isConstantSizeType()) { |
3180 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. |
3181 | // FIXME: Better diagnostic. |
3182 | Info.FFDiag(Loc); |
3183 | return false; |
3184 | } |
3185 | |
3186 | Size = Info.Ctx.getTypeSizeInChars(Type); |
3187 | return true; |
3188 | } |
3189 | |
3190 | /// Update a pointer value to model pointer arithmetic. |
3191 | /// \param Info - Information about the ongoing evaluation. |
3192 | /// \param E - The expression being evaluated, for diagnostic purposes. |
3193 | /// \param LVal - The pointer value to be updated. |
3194 | /// \param EltTy - The pointee type represented by LVal. |
3195 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. |
3196 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, |
3197 | LValue &LVal, QualType EltTy, |
3198 | APSInt Adjustment) { |
3199 | CharUnits SizeOfPointee; |
3200 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) |
3201 | return false; |
3202 | |
3203 | LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); |
3204 | return true; |
3205 | } |
3206 | |
3207 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, |
3208 | LValue &LVal, QualType EltTy, |
3209 | int64_t Adjustment) { |
3210 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, |
3211 | APSInt::get(Adjustment)); |
3212 | } |
3213 | |
3214 | /// Update an lvalue to refer to a component of a complex number. |
3215 | /// \param Info - Information about the ongoing evaluation. |
3216 | /// \param LVal - The lvalue to be updated. |
3217 | /// \param EltTy - The complex number's component type. |
3218 | /// \param Imag - False for the real component, true for the imaginary. |
3219 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, |
3220 | LValue &LVal, QualType EltTy, |
3221 | bool Imag) { |
3222 | if (Imag) { |
3223 | CharUnits SizeOfComponent; |
3224 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) |
3225 | return false; |
3226 | LVal.Offset += SizeOfComponent; |
3227 | } |
3228 | LVal.addComplex(Info, E, EltTy, Imag); |
3229 | return true; |
3230 | } |
3231 | |
3232 | /// Try to evaluate the initializer for a variable declaration. |
3233 | /// |
3234 | /// \param Info Information about the ongoing evaluation. |
3235 | /// \param E An expression to be used when printing diagnostics. |
3236 | /// \param VD The variable whose initializer should be obtained. |
3237 | /// \param Version The version of the variable within the frame. |
3238 | /// \param Frame The frame in which the variable was created. Must be null |
3239 | /// if this variable is not local to the evaluation. |
3240 | /// \param Result Filled in with a pointer to the value of the variable. |
3241 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, |
3242 | const VarDecl *VD, CallStackFrame *Frame, |
3243 | unsigned Version, APValue *&Result) { |
3244 | APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); |
3245 | |
3246 | // If this is a local variable, dig out its value. |
3247 | if (Frame) { |
3248 | Result = Frame->getTemporary(VD, Version); |
3249 | if (Result) |
3250 | return true; |
3251 | |
3252 | if (!isa<ParmVarDecl>(VD)) { |
3253 | // Assume variables referenced within a lambda's call operator that were |
3254 | // not declared within the call operator are captures and during checking |
3255 | // of a potential constant expression, assume they are unknown constant |
3256 | // expressions. |
3257 | assert(isLambdaCallOperator(Frame->Callee) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__ )) |
3258 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__ )) |
3259 | "missing value for local variable")(static_cast <bool> (isLambdaCallOperator(Frame->Callee ) && (VD->getDeclContext() != Frame->Callee || VD ->isInitCapture()) && "missing value for local variable" ) ? void (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "clang/lib/AST/ExprConstant.cpp", 3259, __extension__ __PRETTY_FUNCTION__ )); |
3260 | if (Info.checkingPotentialConstantExpression()) |
3261 | return false; |
3262 | // FIXME: This diagnostic is bogus; we do support captures. Is this code |
3263 | // still reachable at all? |
3264 | Info.FFDiag(E->getBeginLoc(), |
3265 | diag::note_unimplemented_constexpr_lambda_feature_ast) |
3266 | << "captures not currently allowed"; |
3267 | return false; |
3268 | } |
3269 | } |
3270 | |
3271 | // If we're currently evaluating the initializer of this declaration, use that |
3272 | // in-flight value. |
3273 | if (Info.EvaluatingDecl == Base) { |
3274 | Result = Info.EvaluatingDeclValue; |
3275 | return true; |
3276 | } |
3277 | |
3278 | if (isa<ParmVarDecl>(VD)) { |
3279 | // Assume parameters of a potential constant expression are usable in |
3280 | // constant expressions. |
3281 | if (!Info.checkingPotentialConstantExpression() || |
3282 | !Info.CurrentCall->Callee || |
3283 | !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { |
3284 | if (Info.getLangOpts().CPlusPlus11) { |
3285 | Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) |
3286 | << VD; |
3287 | NoteLValueLocation(Info, Base); |
3288 | } else { |
3289 | Info.FFDiag(E); |
3290 | } |
3291 | } |
3292 | return false; |
3293 | } |
3294 | |
3295 | // Dig out the initializer, and use the declaration which it's attached to. |
3296 | // FIXME: We should eventually check whether the variable has a reachable |
3297 | // initializing declaration. |
3298 | const Expr *Init = VD->getAnyInitializer(VD); |
3299 | if (!Init) { |
3300 | // Don't diagnose during potential constant expression checking; an |
3301 | // initializer might be added later. |
3302 | if (!Info.checkingPotentialConstantExpression()) { |
3303 | Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) |
3304 | << VD; |
3305 | NoteLValueLocation(Info, Base); |
3306 | } |
3307 | return false; |
3308 | } |
3309 | |
3310 | if (Init->isValueDependent()) { |
3311 | // The DeclRefExpr is not value-dependent, but the variable it refers to |
3312 | // has a value-dependent initializer. This should only happen in |
3313 | // constant-folding cases, where the variable is not actually of a suitable |
3314 | // type for use in a constant expression (otherwise the DeclRefExpr would |
3315 | // have been value-dependent too), so diagnose that. |
3316 | assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx))(static_cast <bool> (!VD->mightBeUsableInConstantExpressions (Info.Ctx)) ? void (0) : __assert_fail ("!VD->mightBeUsableInConstantExpressions(Info.Ctx)" , "clang/lib/AST/ExprConstant.cpp", 3316, __extension__ __PRETTY_FUNCTION__ )); |
3317 | if (!Info.checkingPotentialConstantExpression()) { |
3318 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 |
3319 | ? diag::note_constexpr_ltor_non_constexpr |
3320 | : diag::note_constexpr_ltor_non_integral, 1) |
3321 | << VD << VD->getType(); |
3322 | NoteLValueLocation(Info, Base); |
3323 | } |
3324 | return false; |
3325 | } |
3326 | |
3327 | // Check that we can fold the initializer. In C++, we will have already done |
3328 | // this in the cases where it matters for conformance. |
3329 | if (!VD->evaluateValue()) { |
3330 | Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; |
3331 | NoteLValueLocation(Info, Base); |
3332 | return false; |
3333 | } |
3334 | |
3335 | // Check that the variable is actually usable in constant expressions. For a |
3336 | // const integral variable or a reference, we might have a non-constant |
3337 | // initializer that we can nonetheless evaluate the initializer for. Such |
3338 | // variables are not usable in constant expressions. In C++98, the |
3339 | // initializer also syntactically needs to be an ICE. |
3340 | // |
3341 | // FIXME: We don't diagnose cases that aren't potentially usable in constant |
3342 | // expressions here; doing so would regress diagnostics for things like |
3343 | // reading from a volatile constexpr variable. |
3344 | if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && |
3345 | VD->mightBeUsableInConstantExpressions(Info.Ctx)) || |
3346 | ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && |
3347 | !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { |
3348 | Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; |
3349 | NoteLValueLocation(Info, Base); |
3350 | } |
3351 | |
3352 | // Never use the initializer of a weak variable, not even for constant |
3353 | // folding. We can't be sure that this is the definition that will be used. |
3354 | if (VD->isWeak()) { |
3355 | Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; |
3356 | NoteLValueLocation(Info, Base); |
3357 | return false; |
3358 | } |
3359 | |
3360 | Result = VD->getEvaluatedValue(); |
3361 | return true; |
3362 | } |
3363 | |
3364 | /// Get the base index of the given base class within an APValue representing |
3365 | /// the given derived class. |
3366 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, |
3367 | const CXXRecordDecl *Base) { |
3368 | Base = Base->getCanonicalDecl(); |
3369 | unsigned Index = 0; |
3370 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), |
3371 | E = Derived->bases_end(); I != E; ++I, ++Index) { |
3372 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) |
3373 | return Index; |
3374 | } |
3375 | |
3376 | llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list" , "clang/lib/AST/ExprConstant.cpp", 3376); |
3377 | } |
3378 | |
3379 | /// Extract the value of a character from a string literal. |
3380 | static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, |
3381 | uint64_t Index) { |
3382 | assert(!isa<SourceLocExpr>(Lit) &&(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "clang/lib/AST/ExprConstant.cpp", 3383, __extension__ __PRETTY_FUNCTION__ )) |
3383 | "SourceLocExpr should have already been converted to a StringLiteral")(static_cast <bool> (!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? void (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "clang/lib/AST/ExprConstant.cpp", 3383, __extension__ __PRETTY_FUNCTION__ )); |
3384 | |
3385 | // FIXME: Support MakeStringConstant |
3386 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { |
3387 | std::string Str; |
3388 | Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); |
3389 | assert(Index <= Str.size() && "Index too large")(static_cast <bool> (Index <= Str.size() && "Index too large" ) ? void (0) : __assert_fail ("Index <= Str.size() && \"Index too large\"" , "clang/lib/AST/ExprConstant.cpp", 3389, __extension__ __PRETTY_FUNCTION__ )); |
3390 | return APSInt::getUnsigned(Str.c_str()[Index]); |
3391 | } |
3392 | |
3393 | if (auto PE = dyn_cast<PredefinedExpr>(Lit)) |
3394 | Lit = PE->getFunctionName(); |
3395 | const StringLiteral *S = cast<StringLiteral>(Lit); |
3396 | const ConstantArrayType *CAT = |
3397 | Info.Ctx.getAsConstantArrayType(S->getType()); |
3398 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "clang/lib/AST/ExprConstant.cpp", 3398, __extension__ __PRETTY_FUNCTION__ )); |
3399 | QualType CharType = CAT->getElementType(); |
3400 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "clang/lib/AST/ExprConstant.cpp", 3400, __extension__ __PRETTY_FUNCTION__ )); |
3401 | |
3402 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), |
3403 | CharType->isUnsignedIntegerType()); |
3404 | if (Index < S->getLength()) |
3405 | Value = S->getCodeUnit(Index); |
3406 | return Value; |
3407 | } |
3408 | |
3409 | // Expand a string literal into an array of characters. |
3410 | // |
3411 | // FIXME: This is inefficient; we should probably introduce something similar |
3412 | // to the LLVM ConstantDataArray to make this cheaper. |
3413 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, |
3414 | APValue &Result, |
3415 | QualType AllocType = QualType()) { |
3416 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( |
3417 | AllocType.isNull() ? S->getType() : AllocType); |
3418 | assert(CAT && "string literal isn't an array")(static_cast <bool> (CAT && "string literal isn't an array" ) ? void (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "clang/lib/AST/ExprConstant.cpp", 3418, __extension__ __PRETTY_FUNCTION__ )); |
3419 | QualType CharType = CAT->getElementType(); |
3420 | assert(CharType->isIntegerType() && "unexpected character type")(static_cast <bool> (CharType->isIntegerType() && "unexpected character type") ? void (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "clang/lib/AST/ExprConstant.cpp", 3420, __extension__ __PRETTY_FUNCTION__ )); |
3421 | |
3422 | unsigned Elts = CAT->getSize().getZExtValue(); |
3423 | Result = APValue(APValue::UninitArray(), |
3424 | std::min(S->getLength(), Elts), Elts); |
3425 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), |
3426 | CharType->isUnsignedIntegerType()); |
3427 | if (Result.hasArrayFiller()) |
3428 | Result.getArrayFiller() = APValue(Value); |
3429 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { |
3430 | Value = S->getCodeUnit(I); |
3431 | Result.getArrayInitializedElt(I) = APValue(Value); |
3432 | } |
3433 | } |
3434 | |
3435 | // Expand an array so that it has more than Index filled elements. |
3436 | static void expandArray(APValue &Array, unsigned Index) { |
3437 | unsigned Size = Array.getArraySize(); |
3438 | assert(Index < Size)(static_cast <bool> (Index < Size) ? void (0) : __assert_fail ("Index < Size", "clang/lib/AST/ExprConstant.cpp", 3438, __extension__ __PRETTY_FUNCTION__)); |
3439 | |
3440 | // Always at least double the number of elements for which we store a value. |
3441 | unsigned OldElts = Array.getArrayInitializedElts(); |
3442 | unsigned NewElts = std::max(Index+1, OldElts * 2); |
3443 | NewElts = std::min(Size, std::max(NewElts, 8u)); |
3444 | |
3445 | // Copy the data across. |
3446 | APValue NewValue(APValue::UninitArray(), NewElts, Size); |
3447 | for (unsigned I = 0; I != OldElts; ++I) |
3448 | NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); |
3449 | for (unsigned I = OldElts; I != NewElts; ++I) |
3450 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); |
3451 | if (NewValue.hasArrayFiller()) |
3452 | NewValue.getArrayFiller() = Array.getArrayFiller(); |
3453 | Array.swap(NewValue); |
3454 | } |
3455 | |
3456 | /// Determine whether a type would actually be read by an lvalue-to-rvalue |
3457 | /// conversion. If it's of class type, we may assume that the copy operation |
3458 | /// is trivial. Note that this is never true for a union type with fields |
3459 | /// (because the copy always "reads" the active member) and always true for |
3460 | /// a non-class type. |
3461 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); |
3462 | static bool isReadByLvalueToRvalueConversion(QualType T) { |
3463 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
3464 | return !RD || isReadByLvalueToRvalueConversion(RD); |
3465 | } |
3466 | static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { |
3467 | // FIXME: A trivial copy of a union copies the object representation, even if |
3468 | // the union is empty. |
3469 | if (RD->isUnion()) |
3470 | return !RD->field_empty(); |
3471 | if (RD->isEmpty()) |
3472 | return false; |
3473 | |
3474 | for (auto *Field : RD->fields()) |
3475 | if (!Field->isUnnamedBitfield() && |
3476 | isReadByLvalueToRvalueConversion(Field->getType())) |
3477 | return true; |
3478 | |
3479 | for (auto &BaseSpec : RD->bases()) |
3480 | if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) |
3481 | return true; |
3482 | |
3483 | return false; |
3484 | } |
3485 | |
3486 | /// Diagnose an attempt to read from any unreadable field within the specified |
3487 | /// type, which might be a class type. |
3488 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, |
3489 | QualType T) { |
3490 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
3491 | if (!RD) |
3492 | return false; |
3493 | |
3494 | if (!RD->hasMutableFields()) |
3495 | return false; |
3496 | |
3497 | for (auto *Field : RD->fields()) { |
3498 | // If we're actually going to read this field in some way, then it can't |
3499 | // be mutable. If we're in a union, then assigning to a mutable field |
3500 | // (even an empty one) can change the active member, so that's not OK. |
3501 | // FIXME: Add core issue number for the union case. |
3502 | if (Field->isMutable() && |
3503 | (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { |
3504 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; |
3505 | Info.Note(Field->getLocation(), diag::note_declared_at); |
3506 | return true; |
3507 | } |
3508 | |
3509 | if (diagnoseMutableFields(Info, E, AK, Field->getType())) |
3510 | return true; |
3511 | } |
3512 | |
3513 | for (auto &BaseSpec : RD->bases()) |
3514 | if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) |
3515 | return true; |
3516 | |
3517 | // All mutable fields were empty, and thus not actually read. |
3518 | return false; |
3519 | } |
3520 | |
3521 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, |
3522 | APValue::LValueBase Base, |
3523 | bool MutableSubobject = false) { |
3524 | // A temporary or transient heap allocation we created. |
3525 | if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) |
3526 | return true; |
3527 | |
3528 | switch (Info.IsEvaluatingDecl) { |
3529 | case EvalInfo::EvaluatingDeclKind::None: |
3530 | return false; |
3531 | |
3532 | case EvalInfo::EvaluatingDeclKind::Ctor: |
3533 | // The variable whose initializer we're evaluating. |
3534 | if (Info.EvaluatingDecl == Base) |
3535 | return true; |
3536 | |
3537 | // A temporary lifetime-extended by the variable whose initializer we're |
3538 | // evaluating. |
3539 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) |
3540 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) |
3541 | return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); |
3542 | return false; |
3543 | |
3544 | case EvalInfo::EvaluatingDeclKind::Dtor: |
3545 | // C++2a [expr.const]p6: |
3546 | // [during constant destruction] the lifetime of a and its non-mutable |
3547 | // subobjects (but not its mutable subobjects) [are] considered to start |
3548 | // within e. |
3549 | if (MutableSubobject || Base != Info.EvaluatingDecl) |
3550 | return false; |
3551 | // FIXME: We can meaningfully extend this to cover non-const objects, but |
3552 | // we will need special handling: we should be able to access only |
3553 | // subobjects of such objects that are themselves declared const. |
3554 | QualType T = getType(Base); |
3555 | return T.isConstQualified() || T->isReferenceType(); |
3556 | } |
3557 | |
3558 | llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind" , "clang/lib/AST/ExprConstant.cpp", 3558); |
3559 | } |
3560 | |
3561 | namespace { |
3562 | /// A handle to a complete object (an object that is not a subobject of |
3563 | /// another object). |
3564 | struct CompleteObject { |
3565 | /// The identity of the object. |
3566 | APValue::LValueBase Base; |
3567 | /// The value of the complete object. |
3568 | APValue *Value; |
3569 | /// The type of the complete object. |
3570 | QualType Type; |
3571 | |
3572 | CompleteObject() : Value(nullptr) {} |
3573 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) |
3574 | : Base(Base), Value(Value), Type(Type) {} |
3575 | |
3576 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { |
3577 | // If this isn't a "real" access (eg, if it's just accessing the type |
3578 | // info), allow it. We assume the type doesn't change dynamically for |
3579 | // subobjects of constexpr objects (even though we'd hit UB here if it |
3580 | // did). FIXME: Is this right? |
3581 | if (!isAnyAccess(AK)) |
3582 | return true; |
3583 | |
3584 | // In C++14 onwards, it is permitted to read a mutable member whose |
3585 | // lifetime began within the evaluation. |
3586 | // FIXME: Should we also allow this in C++11? |
3587 | if (!Info.getLangOpts().CPlusPlus14) |
3588 | return false; |
3589 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); |
3590 | } |
3591 | |
3592 | explicit operator bool() const { return !Type.isNull(); } |
3593 | }; |
3594 | } // end anonymous namespace |
3595 | |
3596 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, |
3597 | bool IsMutable = false) { |
3598 | // C++ [basic.type.qualifier]p1: |
3599 | // - A const object is an object of type const T or a non-mutable subobject |
3600 | // of a const object. |
3601 | if (ObjType.isConstQualified() && !IsMutable) |
3602 | SubobjType.addConst(); |
3603 | // - A volatile object is an object of type const T or a subobject of a |
3604 | // volatile object. |
3605 | if (ObjType.isVolatileQualified()) |
3606 | SubobjType.addVolatile(); |
3607 | return SubobjType; |
3608 | } |
3609 | |
3610 | /// Find the designated sub-object of an rvalue. |
3611 | template<typename SubobjectHandler> |
3612 | typename SubobjectHandler::result_type |
3613 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, |
3614 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { |
3615 | if (Sub.Invalid) |
3616 | // A diagnostic will have already been produced. |
3617 | return handler.failed(); |
3618 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { |
3619 | if (Info.getLangOpts().CPlusPlus11) |
3620 | Info.FFDiag(E, Sub.isOnePastTheEnd() |
3621 | ? diag::note_constexpr_access_past_end |
3622 | : diag::note_constexpr_access_unsized_array) |
3623 | << handler.AccessKind; |
3624 | else |
3625 | Info.FFDiag(E); |
3626 | return handler.failed(); |
3627 | } |
3628 | |
3629 | APValue *O = Obj.Value; |
3630 | QualType ObjType = Obj.Type; |
3631 | const FieldDecl *LastField = nullptr; |
3632 | const FieldDecl *VolatileField = nullptr; |
3633 | |
3634 | // Walk the designator's path to find the subobject. |
3635 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { |
3636 | // Reading an indeterminate value is undefined, but assigning over one is OK. |
3637 | if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || |
3638 | (O->isIndeterminate() && |
3639 | !isValidIndeterminateAccess(handler.AccessKind))) { |
3640 | if (!Info.checkingPotentialConstantExpression()) |
3641 | Info.FFDiag(E, diag::note_constexpr_access_uninit) |
3642 | << handler.AccessKind << O->isIndeterminate(); |
3643 | return handler.failed(); |
3644 | } |
3645 | |
3646 | // C++ [class.ctor]p5, C++ [class.dtor]p5: |
3647 | // const and volatile semantics are not applied on an object under |
3648 | // {con,de}struction. |
3649 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && |
3650 | ObjType->isRecordType() && |
3651 | Info.isEvaluatingCtorDtor( |
3652 | Obj.Base, |
3653 | llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != |
3654 | ConstructionPhase::None) { |
3655 | ObjType = Info.Ctx.getCanonicalType(ObjType); |
3656 | ObjType.removeLocalConst(); |
3657 | ObjType.removeLocalVolatile(); |
3658 | } |
3659 | |
3660 | // If this is our last pass, check that the final object type is OK. |
3661 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { |
3662 | // Accesses to volatile objects are prohibited. |
3663 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { |
3664 | if (Info.getLangOpts().CPlusPlus) { |
3665 | int DiagKind; |
3666 | SourceLocation Loc; |
3667 | const NamedDecl *Decl = nullptr; |
3668 | if (VolatileField) { |
3669 | DiagKind = 2; |
3670 | Loc = VolatileField->getLocation(); |
3671 | Decl = VolatileField; |
3672 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { |
3673 | DiagKind = 1; |
3674 | Loc = VD->getLocation(); |
3675 | Decl = VD; |
3676 | } else { |
3677 | DiagKind = 0; |
3678 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) |
3679 | Loc = E->getExprLoc(); |
3680 | } |
3681 | Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) |
3682 | << handler.AccessKind << DiagKind << Decl; |
3683 | Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; |
3684 | } else { |
3685 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); |
3686 | } |
3687 | return handler.failed(); |
3688 | } |
3689 | |
3690 | // If we are reading an object of class type, there may still be more |
3691 | // things we need to check: if there are any mutable subobjects, we |
3692 | // cannot perform this read. (This only happens when performing a trivial |
3693 | // copy or assignment.) |
3694 | if (ObjType->isRecordType() && |
3695 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && |
3696 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) |
3697 | return handler.failed(); |
3698 | } |
3699 | |
3700 | if (I == N) { |
3701 | if (!handler.found(*O, ObjType)) |
3702 | return false; |
3703 | |
3704 | // If we modified a bit-field, truncate it to the right width. |
3705 | if (isModification(handler.AccessKind) && |
3706 | LastField && LastField->isBitField() && |
3707 | !truncateBitfieldValue(Info, E, *O, LastField)) |
3708 | return false; |
3709 | |
3710 | return true; |
3711 | } |
3712 | |
3713 | LastField = nullptr; |
3714 | if (ObjType->isArrayType()) { |
3715 | // Next subobject is an array element. |
3716 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); |
3717 | assert(CAT && "vla in literal type?")(static_cast <bool> (CAT && "vla in literal type?" ) ? void (0) : __assert_fail ("CAT && \"vla in literal type?\"" , "clang/lib/AST/ExprConstant.cpp", 3717, __extension__ __PRETTY_FUNCTION__ )); |
3718 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); |
3719 | if (CAT->getSize().ule(Index)) { |
3720 | // Note, it should not be possible to form a pointer with a valid |
3721 | // designator which points more than one past the end of the array. |
3722 | if (Info.getLangOpts().CPlusPlus11) |
3723 | Info.FFDiag(E, diag::note_constexpr_access_past_end) |
3724 | << handler.AccessKind; |
3725 | else |
3726 | Info.FFDiag(E); |
3727 | return handler.failed(); |
3728 | } |
3729 | |
3730 | ObjType = CAT->getElementType(); |
3731 | |
3732 | if (O->getArrayInitializedElts() > Index) |
3733 | O = &O->getArrayInitializedElt(Index); |
3734 | else if (!isRead(handler.AccessKind)) { |
3735 | expandArray(*O, Index); |
3736 | O = &O->getArrayInitializedElt(Index); |
3737 | } else |
3738 | O = &O->getArrayFiller(); |
3739 | } else if (ObjType->isAnyComplexType()) { |
3740 | // Next subobject is a complex number. |
3741 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); |
3742 | if (Index > 1) { |
3743 | if (Info.getLangOpts().CPlusPlus11) |
3744 | Info.FFDiag(E, diag::note_constexpr_access_past_end) |
3745 | << handler.AccessKind; |
3746 | else |
3747 | Info.FFDiag(E); |
3748 | return handler.failed(); |
3749 | } |
3750 | |
3751 | ObjType = getSubobjectType( |
3752 | ObjType, ObjType->castAs<ComplexType>()->getElementType()); |
3753 | |
3754 | assert(I == N - 1 && "extracting subobject of scalar?")(static_cast <bool> (I == N - 1 && "extracting subobject of scalar?" ) ? void (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\"" , "clang/lib/AST/ExprConstant.cpp", 3754, __extension__ __PRETTY_FUNCTION__ )); |
3755 | if (O->isComplexInt()) { |
3756 | return handler.found(Index ? O->getComplexIntImag() |
3757 | : O->getComplexIntReal(), ObjType); |
3758 | } else { |
3759 | assert(O->isComplexFloat())(static_cast <bool> (O->isComplexFloat()) ? void (0) : __assert_fail ("O->isComplexFloat()", "clang/lib/AST/ExprConstant.cpp" , 3759, __extension__ __PRETTY_FUNCTION__)); |
3760 | return handler.found(Index ? O->getComplexFloatImag() |
3761 | : O->getComplexFloatReal(), ObjType); |
3762 | } |
3763 | } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { |
3764 | if (Field->isMutable() && |
3765 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { |
3766 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) |
3767 | << handler.AccessKind << Field; |
3768 | Info.Note(Field->getLocation(), diag::note_declared_at); |
3769 | return handler.failed(); |
3770 | } |
3771 | |
3772 | // Next subobject is a class, struct or union field. |
3773 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); |
3774 | if (RD->isUnion()) { |
3775 | const FieldDecl *UnionField = O->getUnionField(); |
3776 | if (!UnionField || |
3777 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { |
3778 | if (I == N - 1 && handler.AccessKind == AK_Construct) { |
3779 | // Placement new onto an inactive union member makes it active. |
3780 | O->setUnion(Field, APValue()); |
3781 | } else { |
3782 | // FIXME: If O->getUnionValue() is absent, report that there's no |
3783 | // active union member rather than reporting the prior active union |
3784 | // member. We'll need to fix nullptr_t to not use APValue() as its |
3785 | // representation first. |
3786 | Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) |
3787 | << handler.AccessKind << Field << !UnionField << UnionField; |
3788 | return handler.failed(); |
3789 | } |
3790 | } |
3791 | O = &O->getUnionValue(); |
3792 | } else |
3793 | O = &O->getStructField(Field->getFieldIndex()); |
3794 | |
3795 | ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); |
3796 | LastField = Field; |
3797 | if (Field->getType().isVolatileQualified()) |
3798 | VolatileField = Field; |
3799 | } else { |
3800 | // Next subobject is a base class. |
3801 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); |
3802 | const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); |
3803 | O = &O->getStructBase(getBaseIndex(Derived, Base)); |
3804 | |
3805 | ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); |
3806 | } |
3807 | } |
3808 | } |
3809 | |
3810 | namespace { |
3811 | struct ExtractSubobjectHandler { |
3812 | EvalInfo &Info; |
3813 | const Expr *E; |
3814 | APValue &Result; |
3815 | const AccessKinds AccessKind; |
3816 | |
3817 | typedef bool result_type; |
3818 | bool failed() { return false; } |
3819 | bool found(APValue &Subobj, QualType SubobjType) { |
3820 | Result = Subobj; |
3821 | if (AccessKind == AK_ReadObjectRepresentation) |
3822 | return true; |
3823 | return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); |
3824 | } |
3825 | bool found(APSInt &Value, QualType SubobjType) { |
3826 | Result = APValue(Value); |
3827 | return true; |
3828 | } |
3829 | bool found(APFloat &Value, QualType SubobjType) { |
3830 | Result = APValue(Value); |
3831 | return true; |
3832 | } |
3833 | }; |
3834 | } // end anonymous namespace |
3835 | |
3836 | /// Extract the designated sub-object of an rvalue. |
3837 | static bool extractSubobject(EvalInfo &Info, const Expr *E, |
3838 | const CompleteObject &Obj, |
3839 | const SubobjectDesignator &Sub, APValue &Result, |
3840 | AccessKinds AK = AK_Read) { |
3841 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)(static_cast <bool> (AK == AK_Read || AK == AK_ReadObjectRepresentation ) ? void (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation" , "clang/lib/AST/ExprConstant.cpp", 3841, __extension__ __PRETTY_FUNCTION__ )); |
3842 | ExtractSubobjectHandler Handler = {Info, E, Result, AK}; |
3843 | return findSubobject(Info, E, Obj, Sub, Handler); |
3844 | } |
3845 | |
3846 | namespace { |
3847 | struct ModifySubobjectHandler { |
3848 | EvalInfo &Info; |
3849 | APValue &NewVal; |
3850 | const Expr *E; |
3851 | |
3852 | typedef bool result_type; |
3853 | static const AccessKinds AccessKind = AK_Assign; |
3854 | |
3855 | bool checkConst(QualType QT) { |
3856 | // Assigning to a const object has undefined behavior. |
3857 | if (QT.isConstQualified()) { |
3858 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; |
3859 | return false; |
3860 | } |
3861 | return true; |
3862 | } |
3863 | |
3864 | bool failed() { return false; } |
3865 | bool found(APValue &Subobj, QualType SubobjType) { |
3866 | if (!checkConst(SubobjType)) |
3867 | return false; |
3868 | // We've been given ownership of NewVal, so just swap it in. |
3869 | Subobj.swap(NewVal); |
3870 | return true; |
3871 | } |
3872 | bool found(APSInt &Value, QualType SubobjType) { |
3873 | if (!checkConst(SubobjType)) |
3874 | return false; |
3875 | if (!NewVal.isInt()) { |
3876 | // Maybe trying to write a cast pointer value into a complex? |
3877 | Info.FFDiag(E); |
3878 | return false; |
3879 | } |
3880 | Value = NewVal.getInt(); |
3881 | return true; |
3882 | } |
3883 | bool found(APFloat &Value, QualType SubobjType) { |
3884 | if (!checkConst(SubobjType)) |
3885 | return false; |
3886 | Value = NewVal.getFloat(); |
3887 | return true; |
3888 | } |
3889 | }; |
3890 | } // end anonymous namespace |
3891 | |
3892 | const AccessKinds ModifySubobjectHandler::AccessKind; |
3893 | |
3894 | /// Update the designated sub-object of an rvalue to the given value. |
3895 | static bool modifySubobject(EvalInfo &Info, const Expr *E, |
3896 | const CompleteObject &Obj, |
3897 | const SubobjectDesignator &Sub, |
3898 | APValue &NewVal) { |
3899 | ModifySubobjectHandler Handler = { Info, NewVal, E }; |
3900 | return findSubobject(Info, E, Obj, Sub, Handler); |
3901 | } |
3902 | |
3903 | /// Find the position where two subobject designators diverge, or equivalently |
3904 | /// the length of the common initial subsequence. |
3905 | static unsigned FindDesignatorMismatch(QualType ObjType, |
3906 | const SubobjectDesignator &A, |
3907 | const SubobjectDesignator &B, |
3908 | bool &WasArrayIndex) { |
3909 | unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); |
3910 | for (/**/; I != N; ++I) { |
3911 | if (!ObjType.isNull() && |
3912 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { |
3913 | // Next subobject is an array element. |
3914 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { |
3915 | WasArrayIndex = true; |
3916 | return I; |
3917 | } |
3918 | if (ObjType->isAnyComplexType()) |
3919 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); |
3920 | else |
3921 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); |
3922 | } else { |
3923 | if (A.Entries[I].getAsBaseOrMember() != |
3924 | B.Entries[I].getAsBaseOrMember()) { |
3925 | WasArrayIndex = false; |
3926 | return I; |
3927 | } |
3928 | if (const FieldDecl *FD = getAsField(A.Entries[I])) |
3929 | // Next subobject is a field. |
3930 | ObjType = FD->getType(); |
3931 | else |
3932 | // Next subobject is a base class. |
3933 | ObjType = QualType(); |
3934 | } |
3935 | } |
3936 | WasArrayIndex = false; |
3937 | return I; |
3938 | } |
3939 | |
3940 | /// Determine whether the given subobject designators refer to elements of the |
3941 | /// same array object. |
3942 | static bool AreElementsOfSameArray(QualType ObjType, |
3943 | const SubobjectDesignator &A, |
3944 | const SubobjectDesignator &B) { |
3945 | if (A.Entries.size() != B.Entries.size()) |
3946 | return false; |
3947 | |
3948 | bool IsArray = A.MostDerivedIsArrayElement; |
3949 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) |
3950 | // A is a subobject of the array element. |
3951 | return false; |
3952 | |
3953 | // If A (and B) designates an array element, the last entry will be the array |
3954 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array |
3955 | // of length 1' case, and the entire path must match. |
3956 | bool WasArrayIndex; |
3957 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); |
3958 | return CommonLength >= A.Entries.size() - IsArray; |
3959 | } |
3960 | |
3961 | /// Find the complete object to which an LValue refers. |
3962 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, |
3963 | AccessKinds AK, const LValue &LVal, |
3964 | QualType LValType) { |
3965 | if (LVal.InvalidBase) { |
3966 | Info.FFDiag(E); |
3967 | return CompleteObject(); |
3968 | } |
3969 | |
3970 | if (!LVal.Base) { |
3971 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; |
3972 | return CompleteObject(); |
3973 | } |
3974 | |
3975 | CallStackFrame *Frame = nullptr; |
3976 | unsigned Depth = 0; |
3977 | if (LVal.getLValueCallIndex()) { |
3978 | std::tie(Frame, Depth) = |
3979 | Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); |
3980 | if (!Frame) { |
3981 | Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) |
3982 | << AK << LVal.Base.is<const ValueDecl*>(); |
3983 | NoteLValueLocation(Info, LVal.Base); |
3984 | return CompleteObject(); |
3985 | } |
3986 | } |
3987 | |
3988 | bool IsAccess = isAnyAccess(AK); |
3989 | |
3990 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type |
3991 | // is not a constant expression (even if the object is non-volatile). We also |
3992 | // apply this rule to C++98, in order to conform to the expected 'volatile' |
3993 | // semantics. |
3994 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { |
3995 | if (Info.getLangOpts().CPlusPlus) |
3996 | Info.FFDiag(E, diag::note_constexpr_access_volatile_type) |
3997 | << AK << LValType; |
3998 | else |
3999 | Info.FFDiag(E); |
4000 | return CompleteObject(); |
4001 | } |
4002 | |
4003 | // Compute value storage location and type of base object. |
4004 | APValue *BaseVal = nullptr; |
4005 | QualType BaseType = getType(LVal.Base); |
4006 | |
4007 | if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && |
4008 | lifetimeStartedInEvaluation(Info, LVal.Base)) { |
4009 | // This is the object whose initializer we're evaluating, so its lifetime |
4010 | // started in the current evaluation. |
4011 | BaseVal = Info.EvaluatingDeclValue; |
4012 | } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { |
4013 | // Allow reading from a GUID declaration. |
4014 | if (auto *GD = dyn_cast<MSGuidDecl>(D)) { |
4015 | if (isModification(AK)) { |
4016 | // All the remaining cases do not permit modification of the object. |
4017 | Info.FFDiag(E, diag::note_constexpr_modify_global); |
4018 | return CompleteObject(); |
4019 | } |
4020 | APValue &V = GD->getAsAPValue(); |
4021 | if (V.isAbsent()) { |
4022 | Info.FFDiag(E, diag::note_constexpr_unsupported_layout) |
4023 | << GD->getType(); |
4024 | return CompleteObject(); |
4025 | } |
4026 | return CompleteObject(LVal.Base, &V, GD->getType()); |
4027 | } |
4028 | |
4029 | // Allow reading the APValue from an UnnamedGlobalConstantDecl. |
4030 | if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) { |
4031 | if (isModification(AK)) { |
4032 | Info.FFDiag(E, diag::note_constexpr_modify_global); |
4033 | return CompleteObject(); |
4034 | } |
4035 | return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()), |
4036 | GCD->getType()); |
4037 | } |
4038 | |
4039 | // Allow reading from template parameter objects. |
4040 | if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { |
4041 | if (isModification(AK)) { |
4042 | Info.FFDiag(E, diag::note_constexpr_modify_global); |
4043 | return CompleteObject(); |
4044 | } |
4045 | return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), |
4046 | TPO->getType()); |
4047 | } |
4048 | |
4049 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. |
4050 | // In C++11, constexpr, non-volatile variables initialized with constant |
4051 | // expressions are constant expressions too. Inside constexpr functions, |
4052 | // parameters are constant expressions even if they're non-const. |
4053 | // In C++1y, objects local to a constant expression (those with a Frame) are |
4054 | // both readable and writable inside constant expressions. |
4055 | // In C, such things can also be folded, although they are not ICEs. |
4056 | const VarDecl *VD = dyn_cast<VarDecl>(D); |
4057 | if (VD) { |
4058 | if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) |
4059 | VD = VDef; |
4060 | } |
4061 | if (!VD || VD->isInvalidDecl()) { |
4062 | Info.FFDiag(E); |
4063 | return CompleteObject(); |
4064 | } |
4065 | |
4066 | bool IsConstant = BaseType.isConstant(Info.Ctx); |
4067 | |
4068 | // Unless we're looking at a local variable or argument in a constexpr call, |
4069 | // the variable we're reading must be const. |
4070 | if (!Frame) { |
4071 | if (IsAccess && isa<ParmVarDecl>(VD)) { |
4072 | // Access of a parameter that's not associated with a frame isn't going |
4073 | // to work out, but we can leave it to evaluateVarDeclInit to provide a |
4074 | // suitable diagnostic. |
4075 | } else if (Info.getLangOpts().CPlusPlus14 && |
4076 | lifetimeStartedInEvaluation(Info, LVal.Base)) { |
4077 | // OK, we can read and modify an object if we're in the process of |
4078 | // evaluating its initializer, because its lifetime began in this |
4079 | // evaluation. |
4080 | } else if (isModification(AK)) { |
4081 | // All the remaining cases do not permit modification of the object. |
4082 | Info.FFDiag(E, diag::note_constexpr_modify_global); |
4083 | return CompleteObject(); |
4084 | } else if (VD->isConstexpr()) { |
4085 | // OK, we can read this variable. |
4086 | } else if (BaseType->isIntegralOrEnumerationType()) { |
4087 | if (!IsConstant) { |
4088 | if (!IsAccess) |
4089 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
4090 | if (Info.getLangOpts().CPlusPlus) { |
4091 | Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; |
4092 | Info.Note(VD->getLocation(), diag::note_declared_at); |
4093 | } else { |
4094 | Info.FFDiag(E); |
4095 | } |
4096 | return CompleteObject(); |
4097 | } |
4098 | } else if (!IsAccess) { |
4099 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
4100 | } else if (IsConstant && Info.checkingPotentialConstantExpression() && |
4101 | BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { |
4102 | // This variable might end up being constexpr. Don't diagnose it yet. |
4103 | } else if (IsConstant) { |
4104 | // Keep evaluating to see what we can do. In particular, we support |
4105 | // folding of const floating-point types, in order to make static const |
4106 | // data members of such types (supported as an extension) more useful. |
4107 | if (Info.getLangOpts().CPlusPlus) { |
4108 | Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 |
4109 | ? diag::note_constexpr_ltor_non_constexpr |
4110 | : diag::note_constexpr_ltor_non_integral, 1) |
4111 | << VD << BaseType; |
4112 | Info.Note(VD->getLocation(), diag::note_declared_at); |
4113 | } else { |
4114 | Info.CCEDiag(E); |
4115 | } |
4116 | } else { |
4117 | // Never allow reading a non-const value. |
4118 | if (Info.getLangOpts().CPlusPlus) { |
4119 | Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 |
4120 | ? diag::note_constexpr_ltor_non_constexpr |
4121 | : diag::note_constexpr_ltor_non_integral, 1) |
4122 | << VD << BaseType; |
4123 | Info.Note(VD->getLocation(), diag::note_declared_at); |
4124 | } else { |
4125 | Info.FFDiag(E); |
4126 | } |
4127 | return CompleteObject(); |
4128 | } |
4129 | } |
4130 | |
4131 | if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) |
4132 | return CompleteObject(); |
4133 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { |
4134 | std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); |
4135 | if (!Alloc) { |
4136 | Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; |
4137 | return CompleteObject(); |
4138 | } |
4139 | return CompleteObject(LVal.Base, &(*Alloc)->Value, |
4140 | LVal.Base.getDynamicAllocType()); |
4141 | } else { |
4142 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); |
4143 | |
4144 | if (!Frame) { |
4145 | if (const MaterializeTemporaryExpr *MTE = |
4146 | dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { |
4147 | assert(MTE->getStorageDuration() == SD_Static &&(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4148, __extension__ __PRETTY_FUNCTION__ )) |
4148 | "should have a frame for a non-global materialized temporary")(static_cast <bool> (MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? void (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4148, __extension__ __PRETTY_FUNCTION__ )); |
4149 | |
4150 | // C++20 [expr.const]p4: [DR2126] |
4151 | // An object or reference is usable in constant expressions if it is |
4152 | // - a temporary object of non-volatile const-qualified literal type |
4153 | // whose lifetime is extended to that of a variable that is usable |
4154 | // in constant expressions |
4155 | // |
4156 | // C++20 [expr.const]p5: |
4157 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] |
4158 | // - a non-volatile glvalue that refers to an object that is usable |
4159 | // in constant expressions, or |
4160 | // - a non-volatile glvalue of literal type that refers to a |
4161 | // non-volatile object whose lifetime began within the evaluation |
4162 | // of E; |
4163 | // |
4164 | // C++11 misses the 'began within the evaluation of e' check and |
4165 | // instead allows all temporaries, including things like: |
4166 | // int &&r = 1; |
4167 | // int x = ++r; |
4168 | // constexpr int k = r; |
4169 | // Therefore we use the C++14-onwards rules in C++11 too. |
4170 | // |
4171 | // Note that temporaries whose lifetimes began while evaluating a |
4172 | // variable's constructor are not usable while evaluating the |
4173 | // corresponding destructor, not even if they're of const-qualified |
4174 | // types. |
4175 | if (!MTE->isUsableInConstantExpressions(Info.Ctx) && |
4176 | !lifetimeStartedInEvaluation(Info, LVal.Base)) { |
4177 | if (!IsAccess) |
4178 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
4179 | Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; |
4180 | Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); |
4181 | return CompleteObject(); |
4182 | } |
4183 | |
4184 | BaseVal = MTE->getOrCreateValue(false); |
4185 | assert(BaseVal && "got reference to unevaluated temporary")(static_cast <bool> (BaseVal && "got reference to unevaluated temporary" ) ? void (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4185, __extension__ __PRETTY_FUNCTION__ )); |
4186 | } else { |
4187 | if (!IsAccess) |
4188 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); |
4189 | APValue Val; |
4190 | LVal.moveInto(Val); |
4191 | Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) |
4192 | << AK |
4193 | << Val.getAsString(Info.Ctx, |
4194 | Info.Ctx.getLValueReferenceType(LValType)); |
4195 | NoteLValueLocation(Info, LVal.Base); |
4196 | return CompleteObject(); |
4197 | } |
4198 | } else { |
4199 | BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); |
4200 | assert(BaseVal && "missing value for temporary")(static_cast <bool> (BaseVal && "missing value for temporary" ) ? void (0) : __assert_fail ("BaseVal && \"missing value for temporary\"" , "clang/lib/AST/ExprConstant.cpp", 4200, __extension__ __PRETTY_FUNCTION__ )); |
4201 | } |
4202 | } |
4203 | |
4204 | // In C++14, we can't safely access any mutable state when we might be |
4205 | // evaluating after an unmodeled side effect. Parameters are modeled as state |
4206 | // in the caller, but aren't visible once the call returns, so they can be |
4207 | // modified in a speculatively-evaluated call. |
4208 | // |
4209 | // FIXME: Not all local state is mutable. Allow local constant subobjects |
4210 | // to be read here (but take care with 'mutable' fields). |
4211 | unsigned VisibleDepth = Depth; |
4212 | if (llvm::isa_and_nonnull<ParmVarDecl>( |
4213 | LVal.Base.dyn_cast<const ValueDecl *>())) |
4214 | ++VisibleDepth; |
4215 | if ((Frame && Info.getLangOpts().CPlusPlus14 && |
4216 | Info.EvalStatus.HasSideEffects) || |
4217 | (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) |
4218 | return CompleteObject(); |
4219 | |
4220 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); |
4221 | } |
4222 | |
4223 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This |
4224 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the |
4225 | /// glvalue referred to by an entity of reference type. |
4226 | /// |
4227 | /// \param Info - Information about the ongoing evaluation. |
4228 | /// \param Conv - The expression for which we are performing the conversion. |
4229 | /// Used for diagnostics. |
4230 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the |
4231 | /// case of a non-class type). |
4232 | /// \param LVal - The glvalue on which we are attempting to perform this action. |
4233 | /// \param RVal - The produced value will be placed here. |
4234 | /// \param WantObjectRepresentation - If true, we're looking for the object |
4235 | /// representation rather than the value, and in particular, |
4236 | /// there is no requirement that the result be fully initialized. |
4237 | static bool |
4238 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, |
4239 | const LValue &LVal, APValue &RVal, |
4240 | bool WantObjectRepresentation = false) { |
4241 | if (LVal.Designator.Invalid) |
4242 | return false; |
4243 | |
4244 | // Check for special cases where there is no existing APValue to look at. |
4245 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); |
4246 | |
4247 | AccessKinds AK = |
4248 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; |
4249 | |
4250 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { |
4251 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { |
4252 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the |
4253 | // initializer until now for such expressions. Such an expression can't be |
4254 | // an ICE in C, so this only matters for fold. |
4255 | if (Type.isVolatileQualified()) { |
4256 | Info.FFDiag(Conv); |
4257 | return false; |
4258 | } |
4259 | |
4260 | APValue Lit; |
4261 | if (!Evaluate(Lit, Info, CLE->getInitializer())) |
4262 | return false; |
4263 | |
4264 | // According to GCC info page: |
4265 | // |
4266 | // 6.28 Compound Literals |
4267 | // |
4268 | // As an optimization, G++ sometimes gives array compound literals longer |
4269 | // lifetimes: when the array either appears outside a function or has a |
4270 | // const-qualified type. If foo and its initializer had elements of type |
4271 | // char *const rather than char *, or if foo were a global variable, the |
4272 | // array would have static storage duration. But it is probably safest |
4273 | // just to avoid the use of array compound literals in C++ code. |
4274 | // |
4275 | // Obey that rule by checking constness for converted array types. |
4276 | |
4277 | QualType CLETy = CLE->getType(); |
4278 | if (CLETy->isArrayType() && !Type->isArrayType()) { |
4279 | if (!CLETy.isConstant(Info.Ctx)) { |
4280 | Info.FFDiag(Conv); |
4281 | Info.Note(CLE->getExprLoc(), diag::note_declared_at); |
4282 | return false; |
4283 | } |
4284 | } |
4285 | |
4286 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); |
4287 | return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); |
4288 | } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { |
4289 | // Special-case character extraction so we don't have to construct an |
4290 | // APValue for the whole string. |
4291 | assert(LVal.Designator.Entries.size() <= 1 &&(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "clang/lib/AST/ExprConstant.cpp", 4292, __extension__ __PRETTY_FUNCTION__ )) |
4292 | "Can only read characters from string literals")(static_cast <bool> (LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? void (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "clang/lib/AST/ExprConstant.cpp", 4292, __extension__ __PRETTY_FUNCTION__ )); |
4293 | if (LVal.Designator.Entries.empty()) { |
4294 | // Fail for now for LValue to RValue conversion of an array. |
4295 | // (This shouldn't show up in C/C++, but it could be triggered by a |
4296 | // weird EvaluateAsRValue call from a tool.) |
4297 | Info.FFDiag(Conv); |
4298 | return false; |
4299 | } |
4300 | if (LVal.Designator.isOnePastTheEnd()) { |
4301 | if (Info.getLangOpts().CPlusPlus11) |
4302 | Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; |
4303 | else |
4304 | Info.FFDiag(Conv); |
4305 | return false; |
4306 | } |
4307 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); |
4308 | RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); |
4309 | return true; |
4310 | } |
4311 | } |
4312 | |
4313 | CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); |
4314 | return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); |
4315 | } |
4316 | |
4317 | /// Perform an assignment of Val to LVal. Takes ownership of Val. |
4318 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, |
4319 | QualType LValType, APValue &Val) { |
4320 | if (LVal.Designator.Invalid) |
4321 | return false; |
4322 | |
4323 | if (!Info.getLangOpts().CPlusPlus14) { |
4324 | Info.FFDiag(E); |
4325 | return false; |
4326 | } |
4327 | |
4328 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); |
4329 | return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); |
4330 | } |
4331 | |
4332 | namespace { |
4333 | struct CompoundAssignSubobjectHandler { |
4334 | EvalInfo &Info; |
4335 | const CompoundAssignOperator *E; |
4336 | QualType PromotedLHSType; |
4337 | BinaryOperatorKind Opcode; |
4338 | const APValue &RHS; |
4339 | |
4340 | static const AccessKinds AccessKind = AK_Assign; |
4341 | |
4342 | typedef bool result_type; |
4343 | |
4344 | bool checkConst(QualType QT) { |
4345 | // Assigning to a const object has undefined behavior. |
4346 | if (QT.isConstQualified()) { |
4347 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; |
4348 | return false; |
4349 | } |
4350 | return true; |
4351 | } |
4352 | |
4353 | bool failed() { return false; } |
4354 | bool found(APValue &Subobj, QualType SubobjType) { |
4355 | switch (Subobj.getKind()) { |
4356 | case APValue::Int: |
4357 | return found(Subobj.getInt(), SubobjType); |
4358 | case APValue::Float: |
4359 | return found(Subobj.getFloat(), SubobjType); |
4360 | case APValue::ComplexInt: |
4361 | case APValue::ComplexFloat: |
4362 | // FIXME: Implement complex compound assignment. |
4363 | Info.FFDiag(E); |
4364 | return false; |
4365 | case APValue::LValue: |
4366 | return foundPointer(Subobj, SubobjType); |
4367 | case APValue::Vector: |
4368 | return foundVector(Subobj, SubobjType); |
4369 | default: |
4370 | // FIXME: can this happen? |
4371 | Info.FFDiag(E); |
4372 | return false; |
4373 | } |
4374 | } |
4375 | |
4376 | bool foundVector(APValue &Value, QualType SubobjType) { |
4377 | if (!checkConst(SubobjType)) |
4378 | return false; |
4379 | |
4380 | if (!SubobjType->isVectorType()) { |
4381 | Info.FFDiag(E); |
4382 | return false; |
4383 | } |
4384 | return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); |
4385 | } |
4386 | |
4387 | bool found(APSInt &Value, QualType SubobjType) { |
4388 | if (!checkConst(SubobjType)) |
4389 | return false; |
4390 | |
4391 | if (!SubobjType->isIntegerType()) { |
4392 | // We don't support compound assignment on integer-cast-to-pointer |
4393 | // values. |
4394 | Info.FFDiag(E); |
4395 | return false; |
4396 | } |
4397 | |
4398 | if (RHS.isInt()) { |
4399 | APSInt LHS = |
4400 | HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); |
4401 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) |
4402 | return false; |
4403 | Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); |
4404 | return true; |
4405 | } else if (RHS.isFloat()) { |
4406 | const FPOptions FPO = E->getFPFeaturesInEffect( |
4407 | Info.Ctx.getLangOpts()); |
4408 | APFloat FValue(0.0); |
4409 | return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, |
4410 | PromotedLHSType, FValue) && |
4411 | handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && |
4412 | HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, |
4413 | Value); |
4414 | } |
4415 | |
4416 | Info.FFDiag(E); |
4417 | return false; |
4418 | } |
4419 | bool found(APFloat &Value, QualType SubobjType) { |
4420 | return checkConst(SubobjType) && |
4421 | HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, |
4422 | Value) && |
4423 | handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && |
4424 | HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); |
4425 | } |
4426 | bool foundPointer(APValue &Subobj, QualType SubobjType) { |
4427 | if (!checkConst(SubobjType)) |
4428 | return false; |
4429 | |
4430 | QualType PointeeType; |
4431 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) |
4432 | PointeeType = PT->getPointeeType(); |
4433 | |
4434 | if (PointeeType.isNull() || !RHS.isInt() || |
4435 | (Opcode != BO_Add && Opcode != BO_Sub)) { |
4436 | Info.FFDiag(E); |
4437 | return false; |
4438 | } |
4439 | |
4440 | APSInt Offset = RHS.getInt(); |
4441 | if (Opcode == BO_Sub) |
4442 | negateAsSigned(Offset); |
4443 | |
4444 | LValue LVal; |
4445 | LVal.setFrom(Info.Ctx, Subobj); |
4446 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) |
4447 | return false; |
4448 | LVal.moveInto(Subobj); |
4449 | return true; |
4450 | } |
4451 | }; |
4452 | } // end anonymous namespace |
4453 | |
4454 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; |
4455 | |
4456 | /// Perform a compound assignment of LVal <op>= RVal. |
4457 | static bool handleCompoundAssignment(EvalInfo &Info, |
4458 | const CompoundAssignOperator *E, |
4459 | const LValue &LVal, QualType LValType, |
4460 | QualType PromotedLValType, |
4461 | BinaryOperatorKind Opcode, |
4462 | const APValue &RVal) { |
4463 | if (LVal.Designator.Invalid) |
4464 | return false; |
4465 | |
4466 | if (!Info.getLangOpts().CPlusPlus14) { |
4467 | Info.FFDiag(E); |
4468 | return false; |
4469 | } |
4470 | |
4471 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); |
4472 | CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, |
4473 | RVal }; |
4474 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); |
4475 | } |
4476 | |
4477 | namespace { |
4478 | struct IncDecSubobjectHandler { |
4479 | EvalInfo &Info; |
4480 | const UnaryOperator *E; |
4481 | AccessKinds AccessKind; |
4482 | APValue *Old; |
4483 | |
4484 | typedef bool result_type; |
4485 | |
4486 | bool checkConst(QualType QT) { |
4487 | // Assigning to a const object has undefined behavior. |
4488 | if (QT.isConstQualified()) { |
4489 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; |
4490 | return false; |
4491 | } |
4492 | return true; |
4493 | } |
4494 | |
4495 | bool failed() { return false; } |
4496 | bool found(APValue &Subobj, QualType SubobjType) { |
4497 | // Stash the old value. Also clear Old, so we don't clobber it later |
4498 | // if we're post-incrementing a complex. |
4499 | if (Old) { |
4500 | *Old = Subobj; |
4501 | Old = nullptr; |
4502 | } |
4503 | |
4504 | switch (Subobj.getKind()) { |
4505 | case APValue::Int: |
4506 | return found(Subobj.getInt(), SubobjType); |
4507 | case APValue::Float: |
4508 | return found(Subobj.getFloat(), SubobjType); |
4509 | case APValue::ComplexInt: |
4510 | return found(Subobj.getComplexIntReal(), |
4511 | SubobjType->castAs<ComplexType>()->getElementType() |
4512 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); |
4513 | case APValue::ComplexFloat: |
4514 | return found(Subobj.getComplexFloatReal(), |
4515 | SubobjType->castAs<ComplexType>()->getElementType() |
4516 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); |
4517 | case APValue::LValue: |
4518 | return foundPointer(Subobj, SubobjType); |
4519 | default: |
4520 | // FIXME: can this happen? |
4521 | Info.FFDiag(E); |
4522 | return false; |
4523 | } |
4524 | } |
4525 | bool found(APSInt &Value, QualType SubobjType) { |
4526 | if (!checkConst(SubobjType)) |
4527 | return false; |
4528 | |
4529 | if (!SubobjType->isIntegerType()) { |
4530 | // We don't support increment / decrement on integer-cast-to-pointer |
4531 | // values. |
4532 | Info.FFDiag(E); |
4533 | return false; |
4534 | } |
4535 | |
4536 | if (Old) *Old = APValue(Value); |
4537 | |
4538 | // bool arithmetic promotes to int, and the conversion back to bool |
4539 | // doesn't reduce mod 2^n, so special-case it. |
4540 | if (SubobjType->isBooleanType()) { |
4541 | if (AccessKind == AK_Increment) |
4542 | Value = 1; |
4543 | else |
4544 | Value = !Value; |
4545 | return true; |
4546 | } |
4547 | |
4548 | bool WasNegative = Value.isNegative(); |
4549 | if (AccessKind == AK_Increment) { |
4550 | ++Value; |
4551 | |
4552 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { |
4553 | APSInt ActualValue(Value, /*IsUnsigned*/true); |
4554 | return HandleOverflow(Info, E, ActualValue, SubobjType); |
4555 | } |
4556 | } else { |
4557 | --Value; |
4558 | |
4559 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { |
4560 | unsigned BitWidth = Value.getBitWidth(); |
4561 | APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); |
4562 | ActualValue.setBit(BitWidth); |
4563 | return HandleOverflow(Info, E, ActualValue, SubobjType); |
4564 | } |
4565 | } |
4566 | return true; |
4567 | } |
4568 | bool found(APFloat &Value, QualType SubobjType) { |
4569 | if (!checkConst(SubobjType)) |
4570 | return false; |
4571 | |
4572 | if (Old) *Old = APValue(Value); |
4573 | |
4574 | APFloat One(Value.getSemantics(), 1); |
4575 | if (AccessKind == AK_Increment) |
4576 | Value.add(One, APFloat::rmNearestTiesToEven); |
4577 | else |
4578 | Value.subtract(One, APFloat::rmNearestTiesToEven); |
4579 | return true; |
4580 | } |
4581 | bool foundPointer(APValue &Subobj, QualType SubobjType) { |
4582 | if (!checkConst(SubobjType)) |
4583 | return false; |
4584 | |
4585 | QualType PointeeType; |
4586 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) |
4587 | PointeeType = PT->getPointeeType(); |
4588 | else { |
4589 | Info.FFDiag(E); |
4590 | return false; |
4591 | } |
4592 | |
4593 | LValue LVal; |
4594 | LVal.setFrom(Info.Ctx, Subobj); |
4595 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, |
4596 | AccessKind == AK_Increment ? 1 : -1)) |
4597 | return false; |
4598 | LVal.moveInto(Subobj); |
4599 | return true; |
4600 | } |
4601 | }; |
4602 | } // end anonymous namespace |
4603 | |
4604 | /// Perform an increment or decrement on LVal. |
4605 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, |
4606 | QualType LValType, bool IsIncrement, APValue *Old) { |
4607 | if (LVal.Designator.Invalid) |
4608 | return false; |
4609 | |
4610 | if (!Info.getLangOpts().CPlusPlus14) { |
4611 | Info.FFDiag(E); |
4612 | return false; |
4613 | } |
4614 | |
4615 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; |
4616 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); |
4617 | IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; |
4618 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); |
4619 | } |
4620 | |
4621 | /// Build an lvalue for the object argument of a member function call. |
4622 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, |
4623 | LValue &This) { |
4624 | if (Object->getType()->isPointerType() && Object->isPRValue()) |
4625 | return EvaluatePointer(Object, This, Info); |
4626 | |
4627 | if (Object->isGLValue()) |
4628 | return EvaluateLValue(Object, This, Info); |
4629 | |
4630 | if (Object->getType()->isLiteralType(Info.Ctx)) |
4631 | return EvaluateTemporary(Object, This, Info); |
4632 | |
4633 | Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); |
4634 | return false; |
4635 | } |
4636 | |
4637 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an |
4638 | /// lvalue referring to the result. |
4639 | /// |
4640 | /// \param Info - Information about the ongoing evaluation. |
4641 | /// \param LV - An lvalue referring to the base of the member pointer. |
4642 | /// \param RHS - The member pointer expression. |
4643 | /// \param IncludeMember - Specifies whether the member itself is included in |
4644 | /// the resulting LValue subobject designator. This is not possible when |
4645 | /// creating a bound member function. |
4646 | /// \return The field or method declaration to which the member pointer refers, |
4647 | /// or 0 if evaluation fails. |
4648 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, |
4649 | QualType LVType, |
4650 | LValue &LV, |
4651 | const Expr *RHS, |
4652 | bool IncludeMember = true) { |
4653 | MemberPtr MemPtr; |
4654 | if (!EvaluateMemberPointer(RHS, MemPtr, Info)) |
4655 | return nullptr; |
4656 | |
4657 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to |
4658 | // member value, the behavior is undefined. |
4659 | if (!MemPtr.getDecl()) { |
4660 | // FIXME: Specific diagnostic. |
4661 | Info.FFDiag(RHS); |
4662 | return nullptr; |
4663 | } |
4664 | |
4665 | if (MemPtr.isDerivedMember()) { |
4666 | // This is a member of some derived class. Truncate LV appropriately. |
4667 | // The end of the derived-to-base path for the base object must match the |
4668 | // derived-to-base path for the member pointer. |
4669 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > |
4670 | LV.Designator.Entries.size()) { |
4671 | Info.FFDiag(RHS); |
4672 | return nullptr; |
4673 | } |
4674 | unsigned PathLengthToMember = |
4675 | LV.Designator.Entries.size() - MemPtr.Path.size(); |
4676 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { |
4677 | const CXXRecordDecl *LVDecl = getAsBaseClass( |
4678 | LV.Designator.Entries[PathLengthToMember + I]); |
4679 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; |
4680 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { |
4681 | Info.FFDiag(RHS); |
4682 | return nullptr; |
4683 | } |
4684 | } |
4685 | |
4686 | // Truncate the lvalue to the appropriate derived class. |
4687 | if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), |
4688 | PathLengthToMember)) |
4689 | return nullptr; |
4690 | } else if (!MemPtr.Path.empty()) { |
4691 | // Extend the LValue path with the member pointer's path. |
4692 | LV.Designator.Entries.reserve(LV.Designator.Entries.size() + |
4693 | MemPtr.Path.size() + IncludeMember); |
4694 | |
4695 | // Walk down to the appropriate base class. |
4696 | if (const PointerType *PT = LVType->getAs<PointerType>()) |
4697 | LVType = PT->getPointeeType(); |
4698 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); |
4699 | assert(RD && "member pointer access on non-class-type expression")(static_cast <bool> (RD && "member pointer access on non-class-type expression" ) ? void (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\"" , "clang/lib/AST/ExprConstant.cpp", 4699, __extension__ __PRETTY_FUNCTION__ )); |
4700 | // The first class in the path is that of the lvalue. |
4701 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { |
4702 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; |
4703 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) |
4704 | return nullptr; |
4705 | RD = Base; |
4706 | } |
4707 | // Finally cast to the class containing the member. |
4708 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, |
4709 | MemPtr.getContainingRecord())) |
4710 | return nullptr; |
4711 | } |
4712 | |
4713 | // Add the member. Note that we cannot build bound member functions here. |
4714 | if (IncludeMember) { |
4715 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { |
4716 | if (!HandleLValueMember(Info, RHS, LV, FD)) |
4717 | return nullptr; |
4718 | } else if (const IndirectFieldDecl *IFD = |
4719 | dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { |
4720 | if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) |
4721 | return nullptr; |
4722 | } else { |
4723 | llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function" , "clang/lib/AST/ExprConstant.cpp", 4723); |
4724 | } |
4725 | } |
4726 | |
4727 | return MemPtr.getDecl(); |
4728 | } |
4729 | |
4730 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, |
4731 | const BinaryOperator *BO, |
4732 | LValue &LV, |
4733 | bool IncludeMember = true) { |
4734 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)(static_cast <bool> (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI" , "clang/lib/AST/ExprConstant.cpp", 4734, __extension__ __PRETTY_FUNCTION__ )); |
4735 | |
4736 | if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { |
4737 | if (Info.noteFailure()) { |
4738 | MemberPtr MemPtr; |
4739 | EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); |
4740 | } |
4741 | return nullptr; |
4742 | } |
4743 | |
4744 | return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, |
4745 | BO->getRHS(), IncludeMember); |
4746 | } |
4747 | |
4748 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on |
4749 | /// the provided lvalue, which currently refers to the base object. |
4750 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, |
4751 | LValue &Result) { |
4752 | SubobjectDesignator &D = Result.Designator; |
4753 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) |
4754 | return false; |
4755 | |
4756 | QualType TargetQT = E->getType(); |
4757 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) |
4758 | TargetQT = PT->getPointeeType(); |
4759 | |
4760 | // Check this cast lands within the final derived-to-base subobject path. |
4761 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { |
4762 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) |
4763 | << D.MostDerivedType << TargetQT; |
4764 | return false; |
4765 | } |
4766 | |
4767 | // Check the type of the final cast. We don't need to check the path, |
4768 | // since a cast can only be formed if the path is unique. |
4769 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); |
4770 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); |
4771 | const CXXRecordDecl *FinalType; |
4772 | if (NewEntriesSize == D.MostDerivedPathLength) |
4773 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); |
4774 | else |
4775 | FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); |
4776 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { |
4777 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) |
4778 | << D.MostDerivedType << TargetQT; |
4779 | return false; |
4780 | } |
4781 | |
4782 | // Truncate the lvalue to the appropriate derived class. |
4783 | return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); |
4784 | } |
4785 | |
4786 | /// Get the value to use for a default-initialized object of type T. |
4787 | /// Return false if it encounters something invalid. |
4788 | static bool getDefaultInitValue(QualType T, APValue &Result) { |
4789 | bool Success = true; |
4790 | if (auto *RD = T->getAsCXXRecordDecl()) { |
4791 | if (RD->isInvalidDecl()) { |
4792 | Result = APValue(); |
4793 | return false; |
4794 | } |
4795 | if (RD->isUnion()) { |
4796 | Result = APValue((const FieldDecl *)nullptr); |
4797 | return true; |
4798 | } |
4799 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), |
4800 | std::distance(RD->field_begin(), RD->field_end())); |
4801 | |
4802 | unsigned Index = 0; |
4803 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), |
4804 | End = RD->bases_end(); |
4805 | I != End; ++I, ++Index) |
4806 | Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); |
4807 | |
4808 | for (const auto *I : RD->fields()) { |
4809 | if (I->isUnnamedBitfield()) |
4810 | continue; |
4811 | Success &= getDefaultInitValue(I->getType(), |
4812 | Result.getStructField(I->getFieldIndex())); |
4813 | } |
4814 | return Success; |
4815 | } |
4816 | |
4817 | if (auto *AT = |
4818 | dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { |
4819 | Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); |
4820 | if (Result.hasArrayFiller()) |
4821 | Success &= |
4822 | getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); |
4823 | |
4824 | return Success; |
4825 | } |
4826 | |
4827 | Result = APValue::IndeterminateValue(); |
4828 | return true; |
4829 | } |
4830 | |
4831 | namespace { |
4832 | enum EvalStmtResult { |
4833 | /// Evaluation failed. |
4834 | ESR_Failed, |
4835 | /// Hit a 'return' statement. |
4836 | ESR_Returned, |
4837 | /// Evaluation succeeded. |
4838 | ESR_Succeeded, |
4839 | /// Hit a 'continue' statement. |
4840 | ESR_Continue, |
4841 | /// Hit a 'break' statement. |
4842 | ESR_Break, |
4843 | /// Still scanning for 'case' or 'default' statement. |
4844 | ESR_CaseNotFound |
4845 | }; |
4846 | } |
4847 | |
4848 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { |
4849 | if (VD->isInvalidDecl()) |
4850 | return false; |
4851 | // We don't need to evaluate the initializer for a static local. |
4852 | if (!VD->hasLocalStorage()) |
4853 | return true; |
4854 | |
4855 | LValue Result; |
4856 | APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), |
4857 | ScopeKind::Block, Result); |
4858 | |
4859 | const Expr *InitE = VD->getInit(); |
4860 | if (!InitE) { |
4861 | if (VD->getType()->isDependentType()) |
4862 | return Info.noteSideEffect(); |
4863 | return getDefaultInitValue(VD->getType(), Val); |
4864 | } |
4865 | if (InitE->isValueDependent()) |
4866 | return false; |
4867 | |
4868 | if (!EvaluateInPlace(Val, Info, Result, InitE)) { |
4869 | // Wipe out any partially-computed value, to allow tracking that this |
4870 | // evaluation failed. |
4871 | Val = APValue(); |
4872 | return false; |
4873 | } |
4874 | |
4875 | return true; |
4876 | } |
4877 | |
4878 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { |
4879 | bool OK = true; |
4880 | |
4881 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) |
4882 | OK &= EvaluateVarDecl(Info, VD); |
4883 | |
4884 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) |
4885 | for (auto *BD : DD->bindings()) |
4886 | if (auto *VD = BD->getHoldingVar()) |
4887 | OK &= EvaluateDecl(Info, VD); |
4888 | |
4889 | return OK; |
4890 | } |
4891 | |
4892 | static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { |
4893 | assert(E->isValueDependent())(static_cast <bool> (E->isValueDependent()) ? void ( 0) : __assert_fail ("E->isValueDependent()", "clang/lib/AST/ExprConstant.cpp" , 4893, __extension__ __PRETTY_FUNCTION__)); |
4894 | if (Info.noteSideEffect()) |
4895 | return true; |
4896 | assert(E->containsErrors() && "valid value-dependent expression should never "(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "clang/lib/AST/ExprConstant.cpp", 4897, __extension__ __PRETTY_FUNCTION__ )) |
4897 | "reach invalid code path.")(static_cast <bool> (E->containsErrors() && "valid value-dependent expression should never " "reach invalid code path.") ? void (0) : __assert_fail ("E->containsErrors() && \"valid value-dependent expression should never \" \"reach invalid code path.\"" , "clang/lib/AST/ExprConstant.cpp", 4897, __extension__ __PRETTY_FUNCTION__ )); |
4898 | return false; |
4899 | } |
4900 | |
4901 | /// Evaluate a condition (either a variable declaration or an expression). |
4902 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, |
4903 | const Expr *Cond, bool &Result) { |
4904 | if (Cond->isValueDependent()) |
4905 | return false; |
4906 | FullExpressionRAII Scope(Info); |
4907 | if (CondDecl && !EvaluateDecl(Info, CondDecl)) |
4908 | return false; |
4909 | if (!EvaluateAsBooleanCondition(Cond, Result, Info)) |
4910 | return false; |
4911 | return Scope.destroy(); |
4912 | } |
4913 | |
4914 | namespace { |
4915 | /// A location where the result (returned value) of evaluating a |
4916 | /// statement should be stored. |
4917 | struct StmtResult { |
4918 | /// The APValue that should be filled in with the returned value. |
4919 | APValue &Value; |
4920 | /// The location containing the result, if any (used to support RVO). |
4921 | const LValue *Slot; |
4922 | }; |
4923 | |
4924 | struct TempVersionRAII { |
4925 | CallStackFrame &Frame; |
4926 | |
4927 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { |
4928 | Frame.pushTempVersion(); |
4929 | } |
4930 | |
4931 | ~TempVersionRAII() { |
4932 | Frame.popTempVersion(); |
4933 | } |
4934 | }; |
4935 | |
4936 | } |
4937 | |
4938 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, |
4939 | const Stmt *S, |
4940 | const SwitchCase *SC = nullptr); |
4941 | |
4942 | /// Evaluate the body of a loop, and translate the result as appropriate. |
4943 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, |
4944 | const Stmt *Body, |
4945 | const SwitchCase *Case = nullptr) { |
4946 | BlockScopeRAII Scope(Info); |
4947 | |
4948 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); |
4949 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) |
4950 | ESR = ESR_Failed; |
4951 | |
4952 | switch (ESR) { |
4953 | case ESR_Break: |
4954 | return ESR_Succeeded; |
4955 | case ESR_Succeeded: |
4956 | case ESR_Continue: |
4957 | return ESR_Continue; |
4958 | case ESR_Failed: |
4959 | case ESR_Returned: |
4960 | case ESR_CaseNotFound: |
4961 | return ESR; |
4962 | } |
4963 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp" , 4963); |
4964 | } |
4965 | |
4966 | /// Evaluate a switch statement. |
4967 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, |
4968 | const SwitchStmt *SS) { |
4969 | BlockScopeRAII Scope(Info); |
4970 | |
4971 | // Evaluate the switch condition. |
4972 | APSInt Value; |
4973 | { |
4974 | if (const Stmt *Init = SS->getInit()) { |
4975 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); |
4976 | if (ESR != ESR_Succeeded) { |
4977 | if (ESR != ESR_Failed && !Scope.destroy()) |
4978 | ESR = ESR_Failed; |
4979 | return ESR; |
4980 | } |
4981 | } |
4982 | |
4983 | FullExpressionRAII CondScope(Info); |
4984 | if (SS->getConditionVariable() && |
4985 | !EvaluateDecl(Info, SS->getConditionVariable())) |
4986 | return ESR_Failed; |
4987 | if (SS->getCond()->isValueDependent()) { |
4988 | if (!EvaluateDependentExpr(SS->getCond(), Info)) |
4989 | return ESR_Failed; |
4990 | } else { |
4991 | if (!EvaluateInteger(SS->getCond(), Value, Info)) |
4992 | return ESR_Failed; |
4993 | } |
4994 | if (!CondScope.destroy()) |
4995 | return ESR_Failed; |
4996 | } |
4997 | |
4998 | // Find the switch case corresponding to the value of the condition. |
4999 | // FIXME: Cache this lookup. |
5000 | const SwitchCase *Found = nullptr; |
5001 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; |
5002 | SC = SC->getNextSwitchCase()) { |
5003 | if (isa<DefaultStmt>(SC)) { |
5004 | Found = SC; |
5005 | continue; |
5006 | } |
5007 | |
5008 | const CaseStmt *CS = cast<CaseStmt>(SC); |
5009 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); |
5010 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) |
5011 | : LHS; |
5012 | if (LHS <= Value && Value <= RHS) { |
5013 | Found = SC; |
5014 | break; |
5015 | } |
5016 | } |
5017 | |
5018 | if (!Found) |
5019 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
5020 | |
5021 | // Search the switch body for the switch case and evaluate it from there. |
5022 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); |
5023 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) |
5024 | return ESR_Failed; |
5025 | |
5026 | switch (ESR) { |
5027 | case ESR_Break: |
5028 | return ESR_Succeeded; |
5029 | case ESR_Succeeded: |
5030 | case ESR_Continue: |
5031 | case ESR_Failed: |
5032 | case ESR_Returned: |
5033 | return ESR; |
5034 | case ESR_CaseNotFound: |
5035 | // This can only happen if the switch case is nested within a statement |
5036 | // expression. We have no intention of supporting that. |
5037 | Info.FFDiag(Found->getBeginLoc(), |
5038 | diag::note_constexpr_stmt_expr_unsupported); |
5039 | return ESR_Failed; |
5040 | } |
5041 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "clang/lib/AST/ExprConstant.cpp" , 5041); |
5042 | } |
5043 | |
5044 | static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) { |
5045 | // An expression E is a core constant expression unless the evaluation of E |
5046 | // would evaluate one of the following: [C++2b] - a control flow that passes |
5047 | // through a declaration of a variable with static or thread storage duration |
5048 | // unless that variable is usable in constant expressions. |
5049 | if (VD->isLocalVarDecl() && VD->isStaticLocal() && |
5050 | !VD->isUsableInConstantExpressions(Info.Ctx)) { |
5051 | Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local) |
5052 | << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD; |
5053 | return false; |
5054 | } |
5055 | return true; |
5056 | } |
5057 | |
5058 | // Evaluate a statement. |
5059 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, |
5060 | const Stmt *S, const SwitchCase *Case) { |
5061 | if (!Info.nextStep(S)) |
5062 | return ESR_Failed; |
5063 | |
5064 | // If we're hunting down a 'case' or 'default' label, recurse through |
5065 | // substatements until we hit the label. |
5066 | if (Case) { |
5067 | switch (S->getStmtClass()) { |
5068 | case Stmt::CompoundStmtClass: |
5069 | // FIXME: Precompute which substatement of a compound statement we |
5070 | // would jump to, and go straight there rather than performing a |
5071 | // linear scan each time. |
5072 | case Stmt::LabelStmtClass: |
5073 | case Stmt::AttributedStmtClass: |
5074 | case Stmt::DoStmtClass: |
5075 | break; |
5076 | |
5077 | case Stmt::CaseStmtClass: |
5078 | case Stmt::DefaultStmtClass: |
5079 | if (Case == S) |
5080 | Case = nullptr; |
5081 | break; |
5082 | |
5083 | case Stmt::IfStmtClass: { |
5084 | // FIXME: Precompute which side of an 'if' we would jump to, and go |
5085 | // straight there rather than scanning both sides. |
5086 | const IfStmt *IS = cast<IfStmt>(S); |
5087 | |
5088 | // Wrap the evaluation in a block scope, in case it's a DeclStmt |
5089 | // preceded by our switch label. |
5090 | BlockScopeRAII Scope(Info); |
5091 | |
5092 | // Step into the init statement in case it brings an (uninitialized) |
5093 | // variable into scope. |
5094 | if (const Stmt *Init = IS->getInit()) { |
5095 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); |
5096 | if (ESR != ESR_CaseNotFound) { |
5097 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp" , 5097, __extension__ __PRETTY_FUNCTION__)); |
5098 | return ESR; |
5099 | } |
5100 | } |
5101 | |
5102 | // Condition variable must be initialized if it exists. |
5103 | // FIXME: We can skip evaluating the body if there's a condition |
5104 | // variable, as there can't be any case labels within it. |
5105 | // (The same is true for 'for' statements.) |
5106 | |
5107 | EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); |
5108 | if (ESR == ESR_Failed) |
5109 | return ESR; |
5110 | if (ESR != ESR_CaseNotFound) |
5111 | return Scope.destroy() ? ESR : ESR_Failed; |
5112 | if (!IS->getElse()) |
5113 | return ESR_CaseNotFound; |
5114 | |
5115 | ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); |
5116 | if (ESR == ESR_Failed) |
5117 | return ESR; |
5118 | if (ESR != ESR_CaseNotFound) |
5119 | return Scope.destroy() ? ESR : ESR_Failed; |
5120 | return ESR_CaseNotFound; |
5121 | } |
5122 | |
5123 | case Stmt::WhileStmtClass: { |
5124 | EvalStmtResult ESR = |
5125 | EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); |
5126 | if (ESR != ESR_Continue) |
5127 | return ESR; |
5128 | break; |
5129 | } |
5130 | |
5131 | case Stmt::ForStmtClass: { |
5132 | const ForStmt *FS = cast<ForStmt>(S); |
5133 | BlockScopeRAII Scope(Info); |
5134 | |
5135 | // Step into the init statement in case it brings an (uninitialized) |
5136 | // variable into scope. |
5137 | if (const Stmt *Init = FS->getInit()) { |
5138 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); |
5139 | if (ESR != ESR_CaseNotFound) { |
5140 | assert(ESR != ESR_Succeeded)(static_cast <bool> (ESR != ESR_Succeeded) ? void (0) : __assert_fail ("ESR != ESR_Succeeded", "clang/lib/AST/ExprConstant.cpp" , 5140, __extension__ __PRETTY_FUNCTION__)); |
5141 | return ESR; |
5142 | } |
5143 | } |
5144 | |
5145 | EvalStmtResult ESR = |
5146 | EvaluateLoopBody(Result, Info, FS->getBody(), Case); |
5147 | if (ESR != ESR_Continue) |
5148 | return ESR; |
5149 | if (const auto *Inc = FS->getInc()) { |
5150 | if (Inc->isValueDependent()) { |
5151 | if (!EvaluateDependentExpr(Inc, Info)) |
5152 | return ESR_Failed; |
5153 | } else { |
5154 | FullExpressionRAII IncScope(Info); |
5155 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) |
5156 | return ESR_Failed; |
5157 | } |
5158 | } |
5159 | break; |
5160 | } |
5161 | |
5162 | case Stmt::DeclStmtClass: { |
5163 | // Start the lifetime of any uninitialized variables we encounter. They |
5164 | // might be used by the selected branch of the switch. |
5165 | const DeclStmt *DS = cast<DeclStmt>(S); |
5166 | for (const auto *D : DS->decls()) { |
5167 | if (const auto *VD = dyn_cast<VarDecl>(D)) { |
5168 | if (!CheckLocalVariableDeclaration(Info, VD)) |
5169 | return ESR_Failed; |
5170 | if (VD->hasLocalStorage() && !VD->getInit()) |
5171 | if (!EvaluateVarDecl(Info, VD)) |
5172 | return ESR_Failed; |
5173 | // FIXME: If the variable has initialization that can't be jumped |
5174 | // over, bail out of any immediately-surrounding compound-statement |
5175 | // too. There can't be any case labels here. |
5176 | } |
5177 | } |
5178 | return ESR_CaseNotFound; |
5179 | } |
5180 | |
5181 | default: |
5182 | return ESR_CaseNotFound; |
5183 | } |
5184 | } |
5185 | |
5186 | switch (S->getStmtClass()) { |
5187 | default: |
5188 | if (const Expr *E = dyn_cast<Expr>(S)) { |
5189 | if (E->isValueDependent()) { |
5190 | if (!EvaluateDependentExpr(E, Info)) |
5191 | return ESR_Failed; |
5192 | } else { |
5193 | // Don't bother evaluating beyond an expression-statement which couldn't |
5194 | // be evaluated. |
5195 | // FIXME: Do we need the FullExpressionRAII object here? |
5196 | // VisitExprWithCleanups should create one when necessary. |
5197 | FullExpressionRAII Scope(Info); |
5198 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) |
5199 | return ESR_Failed; |
5200 | } |
5201 | return ESR_Succeeded; |
5202 | } |
5203 | |
5204 | Info.FFDiag(S->getBeginLoc()); |
5205 | return ESR_Failed; |
5206 | |
5207 | case Stmt::NullStmtClass: |
5208 | return ESR_Succeeded; |
5209 | |
5210 | case Stmt::DeclStmtClass: { |
5211 | const DeclStmt *DS = cast<DeclStmt>(S); |
5212 | for (const auto *D : DS->decls()) { |
5213 | const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); |
5214 | if (VD && !CheckLocalVariableDeclaration(Info, VD)) |
5215 | return ESR_Failed; |
5216 | // Each declaration initialization is its own full-expression. |
5217 | FullExpressionRAII Scope(Info); |
5218 | if (!EvaluateDecl(Info, D) && !Info.noteFailure()) |
5219 | return ESR_Failed; |
5220 | if (!Scope.destroy()) |
5221 | return ESR_Failed; |
5222 | } |
5223 | return ESR_Succeeded; |
5224 | } |
5225 | |
5226 | case Stmt::ReturnStmtClass: { |
5227 | const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); |
5228 | FullExpressionRAII Scope(Info); |
5229 | if (RetExpr && RetExpr->isValueDependent()) { |
5230 | EvaluateDependentExpr(RetExpr, Info); |
5231 | // We know we returned, but we don't know what the value is. |
5232 | return ESR_Failed; |
5233 | } |
5234 | if (RetExpr && |
5235 | !(Result.Slot |
5236 | ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) |
5237 | : Evaluate(Result.Value, Info, RetExpr))) |
5238 | return ESR_Failed; |
5239 | return Scope.destroy() ? ESR_Returned : ESR_Failed; |
5240 | } |
5241 | |
5242 | case Stmt::CompoundStmtClass: { |
5243 | BlockScopeRAII Scope(Info); |
5244 | |
5245 | const CompoundStmt *CS = cast<CompoundStmt>(S); |
5246 | for (const auto *BI : CS->body()) { |
5247 | EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); |
5248 | if (ESR == ESR_Succeeded) |
5249 | Case = nullptr; |
5250 | else if (ESR != ESR_CaseNotFound) { |
5251 | if (ESR != ESR_Failed && !Scope.destroy()) |
5252 | return ESR_Failed; |
5253 | return ESR; |
5254 | } |
5255 | } |
5256 | if (Case) |
5257 | return ESR_CaseNotFound; |
5258 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
5259 | } |
5260 | |
5261 | case Stmt::IfStmtClass: { |
5262 | const IfStmt *IS = cast<IfStmt>(S); |
5263 | |
5264 | // Evaluate the condition, as either a var decl or as an expression. |
5265 | BlockScopeRAII Scope(Info); |
5266 | if (const Stmt *Init = IS->getInit()) { |
5267 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); |
5268 | if (ESR != ESR_Succeeded) { |
5269 | if (ESR != ESR_Failed && !Scope.destroy()) |
5270 | return ESR_Failed; |
5271 | return ESR; |
5272 | } |
5273 | } |
5274 | bool Cond; |
5275 | if (IS->isConsteval()) { |
5276 | Cond = IS->isNonNegatedConsteval(); |
5277 | // If we are not in a constant context, if consteval should not evaluate |
5278 | // to true. |
5279 | if (!Info.InConstantContext) |
5280 | Cond = !Cond; |
5281 | } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), |
5282 | Cond)) |
5283 | return ESR_Failed; |
5284 | |
5285 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { |
5286 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); |
5287 | if (ESR != ESR_Succeeded) { |
5288 | if (ESR != ESR_Failed && !Scope.destroy()) |
5289 | return ESR_Failed; |
5290 | return ESR; |
5291 | } |
5292 | } |
5293 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
5294 | } |
5295 | |
5296 | case Stmt::WhileStmtClass: { |
5297 | const WhileStmt *WS = cast<WhileStmt>(S); |
5298 | while (true) { |
5299 | BlockScopeRAII Scope(Info); |
5300 | bool Continue; |
5301 | if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), |
5302 | Continue)) |
5303 | return ESR_Failed; |
5304 | if (!Continue) |
5305 | break; |
5306 | |
5307 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); |
5308 | if (ESR != ESR_Continue) { |
5309 | if (ESR != ESR_Failed && !Scope.destroy()) |
5310 | return ESR_Failed; |
5311 | return ESR; |
5312 | } |
5313 | if (!Scope.destroy()) |
5314 | return ESR_Failed; |
5315 | } |
5316 | return ESR_Succeeded; |
5317 | } |
5318 | |
5319 | case Stmt::DoStmtClass: { |
5320 | const DoStmt *DS = cast<DoStmt>(S); |
5321 | bool Continue; |
5322 | do { |
5323 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); |
5324 | if (ESR != ESR_Continue) |
5325 | return ESR; |
5326 | Case = nullptr; |
5327 | |
5328 | if (DS->getCond()->isValueDependent()) { |
5329 | EvaluateDependentExpr(DS->getCond(), Info); |
5330 | // Bailout as we don't know whether to keep going or terminate the loop. |
5331 | return ESR_Failed; |
5332 | } |
5333 | FullExpressionRAII CondScope(Info); |
5334 | if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || |
5335 | !CondScope.destroy()) |
5336 | return ESR_Failed; |
5337 | } while (Continue); |
5338 | return ESR_Succeeded; |
5339 | } |
5340 | |
5341 | case Stmt::ForStmtClass: { |
5342 | const ForStmt *FS = cast<ForStmt>(S); |
5343 | BlockScopeRAII ForScope(Info); |
5344 | if (FS->getInit()) { |
5345 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); |
5346 | if (ESR != ESR_Succeeded) { |
5347 | if (ESR != ESR_Failed && !ForScope.destroy()) |
5348 | return ESR_Failed; |
5349 | return ESR; |
5350 | } |
5351 | } |
5352 | while (true) { |
5353 | BlockScopeRAII IterScope(Info); |
5354 | bool Continue = true; |
5355 | if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), |
5356 | FS->getCond(), Continue)) |
5357 | return ESR_Failed; |
5358 | if (!Continue) |
5359 | break; |
5360 | |
5361 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); |
5362 | if (ESR != ESR_Continue) { |
5363 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) |
5364 | return ESR_Failed; |
5365 | return ESR; |
5366 | } |
5367 | |
5368 | if (const auto *Inc = FS->getInc()) { |
5369 | if (Inc->isValueDependent()) { |
5370 | if (!EvaluateDependentExpr(Inc, Info)) |
5371 | return ESR_Failed; |
5372 | } else { |
5373 | FullExpressionRAII IncScope(Info); |
5374 | if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) |
5375 | return ESR_Failed; |
5376 | } |
5377 | } |
5378 | |
5379 | if (!IterScope.destroy()) |
5380 | return ESR_Failed; |
5381 | } |
5382 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; |
5383 | } |
5384 | |
5385 | case Stmt::CXXForRangeStmtClass: { |
5386 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); |
5387 | BlockScopeRAII Scope(Info); |
5388 | |
5389 | // Evaluate the init-statement if present. |
5390 | if (FS->getInit()) { |
5391 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); |
5392 | if (ESR != ESR_Succeeded) { |
5393 | if (ESR != ESR_Failed && !Scope.destroy()) |
5394 | return ESR_Failed; |
5395 | return ESR; |
5396 | } |
5397 | } |
5398 | |
5399 | // Initialize the __range variable. |
5400 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); |
5401 | if (ESR != ESR_Succeeded) { |
5402 | if (ESR != ESR_Failed && !Scope.destroy()) |
5403 | return ESR_Failed; |
5404 | return ESR; |
5405 | } |
5406 | |
5407 | // In error-recovery cases it's possible to get here even if we failed to |
5408 | // synthesize the __begin and __end variables. |
5409 | if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond()) |
5410 | return ESR_Failed; |
5411 | |
5412 | // Create the __begin and __end iterators. |
5413 | ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); |
5414 | if (ESR != ESR_Succeeded) { |
5415 | if (ESR != ESR_Failed && !Scope.destroy()) |
5416 | return ESR_Failed; |
5417 | return ESR; |
5418 | } |
5419 | ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); |
5420 | if (ESR != ESR_Succeeded) { |
5421 | if (ESR != ESR_Failed && !Scope.destroy()) |
5422 | return ESR_Failed; |
5423 | return ESR; |
5424 | } |
5425 | |
5426 | while (true) { |
5427 | // Condition: __begin != __end. |
5428 | { |
5429 | if (FS->getCond()->isValueDependent()) { |
5430 | EvaluateDependentExpr(FS->getCond(), Info); |
5431 | // We don't know whether to keep going or terminate the loop. |
5432 | return ESR_Failed; |
5433 | } |
5434 | bool Continue = true; |
5435 | FullExpressionRAII CondExpr(Info); |
5436 | if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) |
5437 | return ESR_Failed; |
5438 | if (!Continue) |
5439 | break; |
5440 | } |
5441 | |
5442 | // User's variable declaration, initialized by *__begin. |
5443 | BlockScopeRAII InnerScope(Info); |
5444 | ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); |
5445 | if (ESR != ESR_Succeeded) { |
5446 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) |
5447 | return ESR_Failed; |
5448 | return ESR; |
5449 | } |
5450 | |
5451 | // Loop body. |
5452 | ESR = EvaluateLoopBody(Result, Info, FS->getBody()); |
5453 | if (ESR != ESR_Continue) { |
5454 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) |
5455 | return ESR_Failed; |
5456 | return ESR; |
5457 | } |
5458 | if (FS->getInc()->isValueDependent()) { |
5459 | if (!EvaluateDependentExpr(FS->getInc(), Info)) |
5460 | return ESR_Failed; |
5461 | } else { |
5462 | // Increment: ++__begin |
5463 | if (!EvaluateIgnoredValue(Info, FS->getInc())) |
5464 | return ESR_Failed; |
5465 | } |
5466 | |
5467 | if (!InnerScope.destroy()) |
5468 | return ESR_Failed; |
5469 | } |
5470 | |
5471 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; |
5472 | } |
5473 | |
5474 | case Stmt::SwitchStmtClass: |
5475 | return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); |
5476 | |
5477 | case Stmt::ContinueStmtClass: |
5478 | return ESR_Continue; |
5479 | |
5480 | case Stmt::BreakStmtClass: |
5481 | return ESR_Break; |
5482 | |
5483 | case Stmt::LabelStmtClass: |
5484 | return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); |
5485 | |
5486 | case Stmt::AttributedStmtClass: |
5487 | // As a general principle, C++11 attributes can be ignored without |
5488 | // any semantic impact. |
5489 | return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), |
5490 | Case); |
5491 | |
5492 | case Stmt::CaseStmtClass: |
5493 | case Stmt::DefaultStmtClass: |
5494 | return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); |
5495 | case Stmt::CXXTryStmtClass: |
5496 | // Evaluate try blocks by evaluating all sub statements. |
5497 | return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); |
5498 | } |
5499 | } |
5500 | |
5501 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial |
5502 | /// default constructor. If so, we'll fold it whether or not it's marked as |
5503 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, |
5504 | /// so we need special handling. |
5505 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, |
5506 | const CXXConstructorDecl *CD, |
5507 | bool IsValueInitialization) { |
5508 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) |
5509 | return false; |
5510 | |
5511 | // Value-initialization does not call a trivial default constructor, so such a |
5512 | // call is a core constant expression whether or not the constructor is |
5513 | // constexpr. |
5514 | if (!CD->isConstexpr() && !IsValueInitialization) { |
5515 | if (Info.getLangOpts().CPlusPlus11) { |
5516 | // FIXME: If DiagDecl is an implicitly-declared special member function, |
5517 | // we should be much more explicit about why it's not constexpr. |
5518 | Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) |
5519 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; |
5520 | Info.Note(CD->getLocation(), diag::note_declared_at); |
5521 | } else { |
5522 | Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); |
5523 | } |
5524 | } |
5525 | return true; |
5526 | } |
5527 | |
5528 | /// CheckConstexprFunction - Check that a function can be called in a constant |
5529 | /// expression. |
5530 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, |
5531 | const FunctionDecl *Declaration, |
5532 | const FunctionDecl *Definition, |
5533 | const Stmt *Body) { |
5534 | // Potential constant expressions can contain calls to declared, but not yet |
5535 | // defined, constexpr functions. |
5536 | if (Info.checkingPotentialConstantExpression() && !Definition && |
5537 | Declaration->isConstexpr()) |
5538 | return false; |
5539 | |
5540 | // Bail out if the function declaration itself is invalid. We will |
5541 | // have produced a relevant diagnostic while parsing it, so just |
5542 | // note the problematic sub-expression. |
5543 | if (Declaration->isInvalidDecl()) { |
5544 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); |
5545 | return false; |
5546 | } |
5547 | |
5548 | // DR1872: An instantiated virtual constexpr function can't be called in a |
5549 | // constant expression (prior to C++20). We can still constant-fold such a |
5550 | // call. |
5551 | if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && |
5552 | cast<CXXMethodDecl>(Declaration)->isVirtual()) |
5553 | Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); |
5554 | |
5555 | if (Definition && Definition->isInvalidDecl()) { |
5556 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); |
5557 | return false; |
5558 | } |
5559 | |
5560 | // Can we evaluate this function call? |
5561 | if (Definition && Definition->isConstexpr() && Body) |
5562 | return true; |
5563 | |
5564 | if (Info.getLangOpts().CPlusPlus11) { |
5565 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; |
5566 | |
5567 | // If this function is not constexpr because it is an inherited |
5568 | // non-constexpr constructor, diagnose that directly. |
5569 | auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); |
5570 | if (CD && CD->isInheritingConstructor()) { |
5571 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); |
5572 | if (!Inherited->isConstexpr()) |
5573 | DiagDecl = CD = Inherited; |
5574 | } |
5575 | |
5576 | // FIXME: If DiagDecl is an implicitly-declared special member function |
5577 | // or an inheriting constructor, we should be much more explicit about why |
5578 | // it's not constexpr. |
5579 | if (CD && CD->isInheritingConstructor()) |
5580 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) |
5581 | << CD->getInheritedConstructor().getConstructor()->getParent(); |
5582 | else |
5583 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) |
5584 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; |
5585 | Info.Note(DiagDecl->getLocation(), diag::note_declared_at); |
5586 | } else { |
5587 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); |
5588 | } |
5589 | return false; |
5590 | } |
5591 | |
5592 | namespace { |
5593 | struct CheckDynamicTypeHandler { |
5594 | AccessKinds AccessKind; |
5595 | typedef bool result_type; |
5596 | bool failed() { return false; } |
5597 | bool found(APValue &Subobj, QualType SubobjType) { return true; } |
5598 | bool found(APSInt &Value, QualType SubobjType) { return true; } |
5599 | bool found(APFloat &Value, QualType SubobjType) { return true; } |
5600 | }; |
5601 | } // end anonymous namespace |
5602 | |
5603 | /// Check that we can access the notional vptr of an object / determine its |
5604 | /// dynamic type. |
5605 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, |
5606 | AccessKinds AK, bool Polymorphic) { |
5607 | if (This.Designator.Invalid) |
5608 | return false; |
5609 | |
5610 | CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); |
5611 | |
5612 | if (!Obj) |
5613 | return false; |
5614 | |
5615 | if (!Obj.Value) { |
5616 | // The object is not usable in constant expressions, so we can't inspect |
5617 | // its value to see if it's in-lifetime or what the active union members |
5618 | // are. We can still check for a one-past-the-end lvalue. |
5619 | if (This.Designator.isOnePastTheEnd() || |
5620 | This.Designator.isMostDerivedAnUnsizedArray()) { |
5621 | Info.FFDiag(E, This.Designator.isOnePastTheEnd() |
5622 | ? diag::note_constexpr_access_past_end |
5623 | : diag::note_constexpr_access_unsized_array) |
5624 | << AK; |
5625 | return false; |
5626 | } else if (Polymorphic) { |
5627 | // Conservatively refuse to perform a polymorphic operation if we would |
5628 | // not be able to read a notional 'vptr' value. |
5629 | APValue Val; |
5630 | This.moveInto(Val); |
5631 | QualType StarThisType = |
5632 | Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); |
5633 | Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) |
5634 | << AK << Val.getAsString(Info.Ctx, StarThisType); |
5635 | return false; |
5636 | } |
5637 | return true; |
5638 | } |
5639 | |
5640 | CheckDynamicTypeHandler Handler{AK}; |
5641 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); |
5642 | } |
5643 | |
5644 | /// Check that the pointee of the 'this' pointer in a member function call is |
5645 | /// either within its lifetime or in its period of construction or destruction. |
5646 | static bool |
5647 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, |
5648 | const LValue &This, |
5649 | const CXXMethodDecl *NamedMember) { |
5650 | return checkDynamicType( |
5651 | Info, E, This, |
5652 | isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); |
5653 | } |
5654 | |
5655 | struct DynamicType { |
5656 | /// The dynamic class type of the object. |
5657 | const CXXRecordDecl *Type; |
5658 | /// The corresponding path length in the lvalue. |
5659 | unsigned PathLength; |
5660 | }; |
5661 | |
5662 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, |
5663 | unsigned PathLength) { |
5664 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "clang/lib/AST/ExprConstant.cpp", 5665, __extension__ __PRETTY_FUNCTION__ )) |
5665 | Designator.Entries.size() && "invalid path length")(static_cast <bool> (PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length") ? void (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "clang/lib/AST/ExprConstant.cpp", 5665, __extension__ __PRETTY_FUNCTION__ )); |
5666 | return (PathLength == Designator.MostDerivedPathLength) |
5667 | ? Designator.MostDerivedType->getAsCXXRecordDecl() |
5668 | : getAsBaseClass(Designator.Entries[PathLength - 1]); |
5669 | } |
5670 | |
5671 | /// Determine the dynamic type of an object. |
5672 | static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info, |
5673 | const Expr *E, |
5674 | LValue &This, |
5675 | AccessKinds AK) { |
5676 | // If we don't have an lvalue denoting an object of class type, there is no |
5677 | // meaningful dynamic type. (We consider objects of non-class type to have no |
5678 | // dynamic type.) |
5679 | if (!checkDynamicType(Info, E, This, AK, true)) |
5680 | return std::nullopt; |
5681 | |
5682 | // Refuse to compute a dynamic type in the presence of virtual bases. This |
5683 | // shouldn't happen other than in constant-folding situations, since literal |
5684 | // types can't have virtual bases. |
5685 | // |
5686 | // Note that consumers of DynamicType assume that the type has no virtual |
5687 | // bases, and will need modifications if this restriction is relaxed. |
5688 | const CXXRecordDecl *Class = |
5689 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); |
5690 | if (!Class || Class->getNumVBases()) { |
5691 | Info.FFDiag(E); |
5692 | return std::nullopt; |
5693 | } |
5694 | |
5695 | // FIXME: For very deep class hierarchies, it might be beneficial to use a |
5696 | // binary search here instead. But the overwhelmingly common case is that |
5697 | // we're not in the middle of a constructor, so it probably doesn't matter |
5698 | // in practice. |
5699 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; |
5700 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; |
5701 | PathLength <= Path.size(); ++PathLength) { |
5702 | switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), |
5703 | Path.slice(0, PathLength))) { |
5704 | case ConstructionPhase::Bases: |
5705 | case ConstructionPhase::DestroyingBases: |
5706 | // We're constructing or destroying a base class. This is not the dynamic |
5707 | // type. |
5708 | break; |
5709 | |
5710 | case ConstructionPhase::None: |
5711 | case ConstructionPhase::AfterBases: |
5712 | case ConstructionPhase::AfterFields: |
5713 | case ConstructionPhase::Destroying: |
5714 | // We've finished constructing the base classes and not yet started |
5715 | // destroying them again, so this is the dynamic type. |
5716 | return DynamicType{getBaseClassType(This.Designator, PathLength), |
5717 | PathLength}; |
5718 | } |
5719 | } |
5720 | |
5721 | // CWG issue 1517: we're constructing a base class of the object described by |
5722 | // 'This', so that object has not yet begun its period of construction and |
5723 | // any polymorphic operation on it results in undefined behavior. |
5724 | Info.FFDiag(E); |
5725 | return std::nullopt; |
5726 | } |
5727 | |
5728 | /// Perform virtual dispatch. |
5729 | static const CXXMethodDecl *HandleVirtualDispatch( |
5730 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, |
5731 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { |
5732 | std::optional<DynamicType> DynType = ComputeDynamicType( |
5733 | Info, E, This, |
5734 | isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); |
5735 | if (!DynType) |
5736 | return nullptr; |
5737 | |
5738 | // Find the final overrider. It must be declared in one of the classes on the |
5739 | // path from the dynamic type to the static type. |
5740 | // FIXME: If we ever allow literal types to have virtual base classes, that |
5741 | // won't be true. |
5742 | const CXXMethodDecl *Callee = Found; |
5743 | unsigned PathLength = DynType->PathLength; |
5744 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { |
5745 | const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); |
5746 | const CXXMethodDecl *Overrider = |
5747 | Found->getCorrespondingMethodDeclaredInClass(Class, false); |
5748 | if (Overrider) { |
5749 | Callee = Overrider; |
5750 | break; |
5751 | } |
5752 | } |
5753 | |
5754 | // C++2a [class.abstract]p6: |
5755 | // the effect of making a virtual call to a pure virtual function [...] is |
5756 | // undefined |
5757 | if (Callee->isPure()) { |
5758 | Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; |
5759 | Info.Note(Callee->getLocation(), diag::note_declared_at); |
5760 | return nullptr; |
5761 | } |
5762 | |
5763 | // If necessary, walk the rest of the path to determine the sequence of |
5764 | // covariant adjustment steps to apply. |
5765 | if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), |
5766 | Found->getReturnType())) { |
5767 | CovariantAdjustmentPath.push_back(Callee->getReturnType()); |
5768 | for (unsigned CovariantPathLength = PathLength + 1; |
5769 | CovariantPathLength != This.Designator.Entries.size(); |
5770 | ++CovariantPathLength) { |
5771 | const CXXRecordDecl *NextClass = |
5772 | getBaseClassType(This.Designator, CovariantPathLength); |
5773 | const CXXMethodDecl *Next = |
5774 | Found->getCorrespondingMethodDeclaredInClass(NextClass, false); |
5775 | if (Next && !Info.Ctx.hasSameUnqualifiedType( |
5776 | Next->getReturnType(), CovariantAdjustmentPath.back())) |
5777 | CovariantAdjustmentPath.push_back(Next->getReturnType()); |
5778 | } |
5779 | if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), |
5780 | CovariantAdjustmentPath.back())) |
5781 | CovariantAdjustmentPath.push_back(Found->getReturnType()); |
5782 | } |
5783 | |
5784 | // Perform 'this' adjustment. |
5785 | if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) |
5786 | return nullptr; |
5787 | |
5788 | return Callee; |
5789 | } |
5790 | |
5791 | /// Perform the adjustment from a value returned by a virtual function to |
5792 | /// a value of the statically expected type, which may be a pointer or |
5793 | /// reference to a base class of the returned type. |
5794 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, |
5795 | APValue &Result, |
5796 | ArrayRef<QualType> Path) { |
5797 | assert(Result.isLValue() &&(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5798, __extension__ __PRETTY_FUNCTION__ )) |
5798 | "unexpected kind of APValue for covariant return")(static_cast <bool> (Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? void (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5798, __extension__ __PRETTY_FUNCTION__ )); |
5799 | if (Result.isNullPointer()) |
5800 | return true; |
5801 | |
5802 | LValue LVal; |
5803 | LVal.setFrom(Info.Ctx, Result); |
5804 | |
5805 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); |
5806 | for (unsigned I = 1; I != Path.size(); ++I) { |
5807 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); |
5808 | assert(OldClass && NewClass && "unexpected kind of covariant return")(static_cast <bool> (OldClass && NewClass && "unexpected kind of covariant return") ? void (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\"" , "clang/lib/AST/ExprConstant.cpp", 5808, __extension__ __PRETTY_FUNCTION__ )); |
5809 | if (OldClass != NewClass && |
5810 | !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) |
5811 | return false; |
5812 | OldClass = NewClass; |
5813 | } |
5814 | |
5815 | LVal.moveInto(Result); |
5816 | return true; |
5817 | } |
5818 | |
5819 | /// Determine whether \p Base, which is known to be a direct base class of |
5820 | /// \p Derived, is a public base class. |
5821 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, |
5822 | const CXXRecordDecl *Base) { |
5823 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { |
5824 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); |
5825 | if (BaseClass && declaresSameEntity(BaseClass, Base)) |
5826 | return BaseSpec.getAccessSpecifier() == AS_public; |
5827 | } |
5828 | llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived" , "clang/lib/AST/ExprConstant.cpp", 5828); |
5829 | } |
5830 | |
5831 | /// Apply the given dynamic cast operation on the provided lvalue. |
5832 | /// |
5833 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" |
5834 | /// to find a suitable target subobject. |
5835 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, |
5836 | LValue &Ptr) { |
5837 | // We can't do anything with a non-symbolic pointer value. |
5838 | SubobjectDesignator &D = Ptr.Designator; |
5839 | if (D.Invalid) |
5840 | return false; |
5841 | |
5842 | // C++ [expr.dynamic.cast]p6: |
5843 | // If v is a null pointer value, the result is a null pointer value. |
5844 | if (Ptr.isNullPointer() && !E->isGLValue()) |
5845 | return true; |
5846 | |
5847 | // For all the other cases, we need the pointer to point to an object within |
5848 | // its lifetime / period of construction / destruction, and we need to know |
5849 | // its dynamic type. |
5850 | std::optional<DynamicType> DynType = |
5851 | ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); |
5852 | if (!DynType) |
5853 | return false; |
5854 | |
5855 | // C++ [expr.dynamic.cast]p7: |
5856 | // If T is "pointer to cv void", then the result is a pointer to the most |
5857 | // derived object |
5858 | if (E->getType()->isVoidPointerType()) |
5859 | return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); |
5860 | |
5861 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); |
5862 | assert(C && "dynamic_cast target is not void pointer nor class")(static_cast <bool> (C && "dynamic_cast target is not void pointer nor class" ) ? void (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\"" , "clang/lib/AST/ExprConstant.cpp", 5862, __extension__ __PRETTY_FUNCTION__ )); |
5863 | CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); |
5864 | |
5865 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { |
5866 | // C++ [expr.dynamic.cast]p9: |
5867 | if (!E->isGLValue()) { |
5868 | // The value of a failed cast to pointer type is the null pointer value |
5869 | // of the required result type. |
5870 | Ptr.setNull(Info.Ctx, E->getType()); |
5871 | return true; |
5872 | } |
5873 | |
5874 | // A failed cast to reference type throws [...] std::bad_cast. |
5875 | unsigned DiagKind; |
5876 | if (!Paths && (declaresSameEntity(DynType->Type, C) || |
5877 | DynType->Type->isDerivedFrom(C))) |
5878 | DiagKind = 0; |
5879 | else if (!Paths || Paths->begin() == Paths->end()) |
5880 | DiagKind = 1; |
5881 | else if (Paths->isAmbiguous(CQT)) |
5882 | DiagKind = 2; |
5883 | else { |
5884 | assert(Paths->front().Access != AS_public && "why did the cast fail?")(static_cast <bool> (Paths->front().Access != AS_public && "why did the cast fail?") ? void (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\"" , "clang/lib/AST/ExprConstant.cpp", 5884, __extension__ __PRETTY_FUNCTION__ )); |
5885 | DiagKind = 3; |
5886 | } |
5887 | Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) |
5888 | << DiagKind << Ptr.Designator.getType(Info.Ctx) |
5889 | << Info.Ctx.getRecordType(DynType->Type) |
5890 | << E->getType().getUnqualifiedType(); |
5891 | return false; |
5892 | }; |
5893 | |
5894 | // Runtime check, phase 1: |
5895 | // Walk from the base subobject towards the derived object looking for the |
5896 | // target type. |
5897 |