File: | tools/clang/lib/AST/ExprConstant.cpp |
Warning: | line 6975, column 7 Called C++ object pointer is null |
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 <cstring> | ||||
36 | #include <functional> | ||||
37 | #include "Interp/Context.h" | ||||
38 | #include "Interp/Frame.h" | ||||
39 | #include "Interp/State.h" | ||||
40 | #include "clang/AST/APValue.h" | ||||
41 | #include "clang/AST/ASTContext.h" | ||||
42 | #include "clang/AST/ASTDiagnostic.h" | ||||
43 | #include "clang/AST/ASTLambda.h" | ||||
44 | #include "clang/AST/CXXInheritance.h" | ||||
45 | #include "clang/AST/CharUnits.h" | ||||
46 | #include "clang/AST/CurrentSourceLocExprScope.h" | ||||
47 | #include "clang/AST/Expr.h" | ||||
48 | #include "clang/AST/OSLog.h" | ||||
49 | #include "clang/AST/OptionalDiagnostic.h" | ||||
50 | #include "clang/AST/RecordLayout.h" | ||||
51 | #include "clang/AST/StmtVisitor.h" | ||||
52 | #include "clang/AST/TypeLoc.h" | ||||
53 | #include "clang/Basic/Builtins.h" | ||||
54 | #include "clang/Basic/FixedPoint.h" | ||||
55 | #include "clang/Basic/TargetInfo.h" | ||||
56 | #include "llvm/ADT/Optional.h" | ||||
57 | #include "llvm/ADT/SmallBitVector.h" | ||||
58 | #include "llvm/Support/SaveAndRestore.h" | ||||
59 | #include "llvm/Support/raw_ostream.h" | ||||
60 | |||||
61 | #define DEBUG_TYPE"exprconstant" "exprconstant" | ||||
62 | |||||
63 | using namespace clang; | ||||
64 | using llvm::APInt; | ||||
65 | using llvm::APSInt; | ||||
66 | using llvm::APFloat; | ||||
67 | using llvm::Optional; | ||||
68 | |||||
69 | namespace { | ||||
70 | struct LValue; | ||||
71 | class CallStackFrame; | ||||
72 | class EvalInfo; | ||||
73 | |||||
74 | using SourceLocExprScopeGuard = | ||||
75 | CurrentSourceLocExprScope::SourceLocExprScopeGuard; | ||||
76 | |||||
77 | static QualType getType(APValue::LValueBase B) { | ||||
78 | if (!B) return QualType(); | ||||
79 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||
80 | // FIXME: It's unclear where we're supposed to take the type from, and | ||||
81 | // this actually matters for arrays of unknown bound. Eg: | ||||
82 | // | ||||
83 | // extern int arr[]; void f() { extern int arr[3]; }; | ||||
84 | // constexpr int *p = &arr[1]; // valid? | ||||
85 | // | ||||
86 | // For now, we take the array bound from the most recent declaration. | ||||
87 | for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; | ||||
88 | Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { | ||||
89 | QualType T = Redecl->getType(); | ||||
90 | if (!T->isIncompleteArrayType()) | ||||
91 | return T; | ||||
92 | } | ||||
93 | return D->getType(); | ||||
94 | } | ||||
95 | |||||
96 | if (B.is<TypeInfoLValue>()) | ||||
97 | return B.getTypeInfoType(); | ||||
98 | |||||
99 | if (B.is<DynamicAllocLValue>()) | ||||
100 | return B.getDynamicAllocType(); | ||||
101 | |||||
102 | const Expr *Base = B.get<const Expr*>(); | ||||
103 | |||||
104 | // For a materialized temporary, the type of the temporary we materialized | ||||
105 | // may not be the type of the expression. | ||||
106 | if (const MaterializeTemporaryExpr *MTE = | ||||
107 | dyn_cast<MaterializeTemporaryExpr>(Base)) { | ||||
108 | SmallVector<const Expr *, 2> CommaLHSs; | ||||
109 | SmallVector<SubobjectAdjustment, 2> Adjustments; | ||||
110 | const Expr *Temp = MTE->GetTemporaryExpr(); | ||||
111 | const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, | ||||
112 | Adjustments); | ||||
113 | // Keep any cv-qualifiers from the reference if we generated a temporary | ||||
114 | // for it directly. Otherwise use the type after adjustment. | ||||
115 | if (!Adjustments.empty()) | ||||
116 | return Inner->getType(); | ||||
117 | } | ||||
118 | |||||
119 | return Base->getType(); | ||||
120 | } | ||||
121 | |||||
122 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||
123 | /// field declaration. | ||||
124 | static const FieldDecl *getAsField(APValue::LValuePathEntry E) { | ||||
125 | return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); | ||||
126 | } | ||||
127 | /// Get an LValue path entry, which is known to not be an array index, as a | ||||
128 | /// base class declaration. | ||||
129 | static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { | ||||
130 | return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); | ||||
131 | } | ||||
132 | /// Determine whether this LValue path entry for a base class names a virtual | ||||
133 | /// base class. | ||||
134 | static bool isVirtualBaseClass(APValue::LValuePathEntry E) { | ||||
135 | return E.getAsBaseOrMember().getInt(); | ||||
136 | } | ||||
137 | |||||
138 | /// Given an expression, determine the type used to store the result of | ||||
139 | /// evaluating that expression. | ||||
140 | static QualType getStorageType(ASTContext &Ctx, Expr *E) { | ||||
141 | if (E->isRValue()) | ||||
142 | return E->getType(); | ||||
143 | return Ctx.getLValueReferenceType(E->getType()); | ||||
144 | } | ||||
145 | |||||
146 | /// Given a CallExpr, try to get the alloc_size attribute. May return null. | ||||
147 | static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { | ||||
148 | const FunctionDecl *Callee = CE->getDirectCallee(); | ||||
149 | return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; | ||||
150 | } | ||||
151 | |||||
152 | /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. | ||||
153 | /// This will look through a single cast. | ||||
154 | /// | ||||
155 | /// Returns null if we couldn't unwrap a function with alloc_size. | ||||
156 | static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { | ||||
157 | if (!E->getType()->isPointerType()) | ||||
158 | return nullptr; | ||||
159 | |||||
160 | E = E->IgnoreParens(); | ||||
161 | // If we're doing a variable assignment from e.g. malloc(N), there will | ||||
162 | // probably be a cast of some kind. In exotic cases, we might also see a | ||||
163 | // top-level ExprWithCleanups. Ignore them either way. | ||||
164 | if (const auto *FE = dyn_cast<FullExpr>(E)) | ||||
165 | E = FE->getSubExpr()->IgnoreParens(); | ||||
166 | |||||
167 | if (const auto *Cast = dyn_cast<CastExpr>(E)) | ||||
168 | E = Cast->getSubExpr()->IgnoreParens(); | ||||
169 | |||||
170 | if (const auto *CE = dyn_cast<CallExpr>(E)) | ||||
171 | return getAllocSizeAttr(CE) ? CE : nullptr; | ||||
172 | return nullptr; | ||||
173 | } | ||||
174 | |||||
175 | /// Determines whether or not the given Base contains a call to a function | ||||
176 | /// with the alloc_size attribute. | ||||
177 | static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { | ||||
178 | const auto *E = Base.dyn_cast<const Expr *>(); | ||||
179 | return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); | ||||
180 | } | ||||
181 | |||||
182 | /// The bound to claim that an array of unknown bound has. | ||||
183 | /// The value in MostDerivedArraySize is undefined in this case. So, set it | ||||
184 | /// to an arbitrary value that's likely to loudly break things if it's used. | ||||
185 | static const uint64_t AssumedSizeForUnsizedArray = | ||||
186 | std::numeric_limits<uint64_t>::max() / 2; | ||||
187 | |||||
188 | /// Determines if an LValue with the given LValueBase will have an unsized | ||||
189 | /// array in its designator. | ||||
190 | /// Find the path length and type of the most-derived subobject in the given | ||||
191 | /// path, and find the size of the containing array, if any. | ||||
192 | static unsigned | ||||
193 | findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, | ||||
194 | ArrayRef<APValue::LValuePathEntry> Path, | ||||
195 | uint64_t &ArraySize, QualType &Type, bool &IsArray, | ||||
196 | bool &FirstEntryIsUnsizedArray) { | ||||
197 | // This only accepts LValueBases from APValues, and APValues don't support | ||||
198 | // arrays that lack size info. | ||||
199 | assert(!isBaseAnAllocSizeCall(Base) &&((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here" ) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 200, __PRETTY_FUNCTION__)) | ||||
200 | "Unsized arrays shouldn't appear here")((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here" ) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 200, __PRETTY_FUNCTION__)); | ||||
201 | unsigned MostDerivedLength = 0; | ||||
202 | Type = getType(Base); | ||||
203 | |||||
204 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { | ||||
205 | if (Type->isArrayType()) { | ||||
206 | const ArrayType *AT = Ctx.getAsArrayType(Type); | ||||
207 | Type = AT->getElementType(); | ||||
208 | MostDerivedLength = I + 1; | ||||
209 | IsArray = true; | ||||
210 | |||||
211 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { | ||||
212 | ArraySize = CAT->getSize().getZExtValue(); | ||||
213 | } else { | ||||
214 | assert(I == 0 && "unexpected unsized array designator")((I == 0 && "unexpected unsized array designator") ? static_cast <void> (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 214, __PRETTY_FUNCTION__)); | ||||
215 | FirstEntryIsUnsizedArray = true; | ||||
216 | ArraySize = AssumedSizeForUnsizedArray; | ||||
217 | } | ||||
218 | } else if (Type->isAnyComplexType()) { | ||||
219 | const ComplexType *CT = Type->castAs<ComplexType>(); | ||||
220 | Type = CT->getElementType(); | ||||
221 | ArraySize = 2; | ||||
222 | MostDerivedLength = I + 1; | ||||
223 | IsArray = true; | ||||
224 | } else if (const FieldDecl *FD = getAsField(Path[I])) { | ||||
225 | Type = FD->getType(); | ||||
226 | ArraySize = 0; | ||||
227 | MostDerivedLength = I + 1; | ||||
228 | IsArray = false; | ||||
229 | } else { | ||||
230 | // Path[I] describes a base class. | ||||
231 | ArraySize = 0; | ||||
232 | IsArray = false; | ||||
233 | } | ||||
234 | } | ||||
235 | return MostDerivedLength; | ||||
236 | } | ||||
237 | |||||
238 | /// A path from a glvalue to a subobject of that glvalue. | ||||
239 | struct SubobjectDesignator { | ||||
240 | /// True if the subobject was named in a manner not supported by C++11. Such | ||||
241 | /// lvalues can still be folded, but they are not core constant expressions | ||||
242 | /// and we cannot perform lvalue-to-rvalue conversions on them. | ||||
243 | unsigned Invalid : 1; | ||||
244 | |||||
245 | /// Is this a pointer one past the end of an object? | ||||
246 | unsigned IsOnePastTheEnd : 1; | ||||
247 | |||||
248 | /// Indicator of whether the first entry is an unsized array. | ||||
249 | unsigned FirstEntryIsAnUnsizedArray : 1; | ||||
250 | |||||
251 | /// Indicator of whether the most-derived object is an array element. | ||||
252 | unsigned MostDerivedIsArrayElement : 1; | ||||
253 | |||||
254 | /// The length of the path to the most-derived object of which this is a | ||||
255 | /// subobject. | ||||
256 | unsigned MostDerivedPathLength : 28; | ||||
257 | |||||
258 | /// The size of the array of which the most-derived object is an element. | ||||
259 | /// This will always be 0 if the most-derived object is not an array | ||||
260 | /// element. 0 is not an indicator of whether or not the most-derived object | ||||
261 | /// is an array, however, because 0-length arrays are allowed. | ||||
262 | /// | ||||
263 | /// If the current array is an unsized array, the value of this is | ||||
264 | /// undefined. | ||||
265 | uint64_t MostDerivedArraySize; | ||||
266 | |||||
267 | /// The type of the most derived object referred to by this address. | ||||
268 | QualType MostDerivedType; | ||||
269 | |||||
270 | typedef APValue::LValuePathEntry PathEntry; | ||||
271 | |||||
272 | /// The entries on the path from the glvalue to the designated subobject. | ||||
273 | SmallVector<PathEntry, 8> Entries; | ||||
274 | |||||
275 | SubobjectDesignator() : Invalid(true) {} | ||||
276 | |||||
277 | explicit SubobjectDesignator(QualType T) | ||||
278 | : Invalid(false), IsOnePastTheEnd(false), | ||||
279 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||
280 | MostDerivedPathLength(0), MostDerivedArraySize(0), | ||||
281 | MostDerivedType(T) {} | ||||
282 | |||||
283 | SubobjectDesignator(ASTContext &Ctx, const APValue &V) | ||||
284 | : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), | ||||
285 | FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), | ||||
286 | MostDerivedPathLength(0), MostDerivedArraySize(0) { | ||||
287 | assert(V.isLValue() && "Non-LValue used to make an LValue designator?")((V.isLValue() && "Non-LValue used to make an LValue designator?" ) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 287, __PRETTY_FUNCTION__)); | ||||
288 | if (!Invalid) { | ||||
289 | IsOnePastTheEnd = V.isLValueOnePastTheEnd(); | ||||
290 | ArrayRef<PathEntry> VEntries = V.getLValuePath(); | ||||
291 | Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); | ||||
292 | if (V.getLValueBase()) { | ||||
293 | bool IsArray = false; | ||||
294 | bool FirstIsUnsizedArray = false; | ||||
295 | MostDerivedPathLength = findMostDerivedSubobject( | ||||
296 | Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, | ||||
297 | MostDerivedType, IsArray, FirstIsUnsizedArray); | ||||
298 | MostDerivedIsArrayElement = IsArray; | ||||
299 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||
300 | } | ||||
301 | } | ||||
302 | } | ||||
303 | |||||
304 | void truncate(ASTContext &Ctx, APValue::LValueBase Base, | ||||
305 | unsigned NewLength) { | ||||
306 | if (Invalid) | ||||
307 | return; | ||||
308 | |||||
309 | assert(Base && "cannot truncate path for null pointer")((Base && "cannot truncate path for null pointer") ? static_cast <void> (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 309, __PRETTY_FUNCTION__)); | ||||
310 | assert(NewLength <= Entries.size() && "not a truncation")((NewLength <= Entries.size() && "not a truncation" ) ? static_cast<void> (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 310, __PRETTY_FUNCTION__)); | ||||
311 | |||||
312 | if (NewLength == Entries.size()) | ||||
313 | return; | ||||
314 | Entries.resize(NewLength); | ||||
315 | |||||
316 | bool IsArray = false; | ||||
317 | bool FirstIsUnsizedArray = false; | ||||
318 | MostDerivedPathLength = findMostDerivedSubobject( | ||||
319 | Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, | ||||
320 | FirstIsUnsizedArray); | ||||
321 | MostDerivedIsArrayElement = IsArray; | ||||
322 | FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; | ||||
323 | } | ||||
324 | |||||
325 | void setInvalid() { | ||||
326 | Invalid = true; | ||||
327 | Entries.clear(); | ||||
328 | } | ||||
329 | |||||
330 | /// Determine whether the most derived subobject is an array without a | ||||
331 | /// known bound. | ||||
332 | bool isMostDerivedAnUnsizedArray() const { | ||||
333 | assert(!Invalid && "Calling this makes no sense on invalid designators")((!Invalid && "Calling this makes no sense on invalid designators" ) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 333, __PRETTY_FUNCTION__)); | ||||
334 | return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; | ||||
335 | } | ||||
336 | |||||
337 | /// Determine what the most derived array's size is. Results in an assertion | ||||
338 | /// failure if the most derived array lacks a size. | ||||
339 | uint64_t getMostDerivedArraySize() const { | ||||
340 | assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")((!isMostDerivedAnUnsizedArray() && "Unsized array has no size" ) ? static_cast<void> (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 340, __PRETTY_FUNCTION__)); | ||||
341 | return MostDerivedArraySize; | ||||
342 | } | ||||
343 | |||||
344 | /// Determine whether this is a one-past-the-end pointer. | ||||
345 | bool isOnePastTheEnd() const { | ||||
346 | assert(!Invalid)((!Invalid) ? static_cast<void> (0) : __assert_fail ("!Invalid" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 346, __PRETTY_FUNCTION__)); | ||||
347 | if (IsOnePastTheEnd) | ||||
348 | return true; | ||||
349 | if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && | ||||
350 | Entries[MostDerivedPathLength - 1].getAsArrayIndex() == | ||||
351 | MostDerivedArraySize) | ||||
352 | return true; | ||||
353 | return false; | ||||
354 | } | ||||
355 | |||||
356 | /// Get the range of valid index adjustments in the form | ||||
357 | /// {maximum value that can be subtracted from this pointer, | ||||
358 | /// maximum value that can be added to this pointer} | ||||
359 | std::pair<uint64_t, uint64_t> validIndexAdjustments() { | ||||
360 | if (Invalid || isMostDerivedAnUnsizedArray()) | ||||
361 | return {0, 0}; | ||||
362 | |||||
363 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||
364 | // nonarray object behaves the same as a pointer to the first element of | ||||
365 | // an array of length one with the type of the object as its element type. | ||||
366 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||
367 | MostDerivedIsArrayElement; | ||||
368 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||
369 | : (uint64_t)IsOnePastTheEnd; | ||||
370 | uint64_t ArraySize = | ||||
371 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||
372 | return {ArrayIndex, ArraySize - ArrayIndex}; | ||||
373 | } | ||||
374 | |||||
375 | /// Check that this refers to a valid subobject. | ||||
376 | bool isValidSubobject() const { | ||||
377 | if (Invalid) | ||||
378 | return false; | ||||
379 | return !isOnePastTheEnd(); | ||||
380 | } | ||||
381 | /// Check that this refers to a valid subobject, and if not, produce a | ||||
382 | /// relevant diagnostic and set the designator as invalid. | ||||
383 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); | ||||
384 | |||||
385 | /// Get the type of the designated object. | ||||
386 | QualType getType(ASTContext &Ctx) const { | ||||
387 | assert(!Invalid && "invalid designator has no subobject type")((!Invalid && "invalid designator has no subobject type" ) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 387, __PRETTY_FUNCTION__)); | ||||
388 | return MostDerivedPathLength == Entries.size() | ||||
389 | ? MostDerivedType | ||||
390 | : Ctx.getRecordType(getAsBaseClass(Entries.back())); | ||||
391 | } | ||||
392 | |||||
393 | /// Update this designator to refer to the first element within this array. | ||||
394 | void addArrayUnchecked(const ConstantArrayType *CAT) { | ||||
395 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||
396 | |||||
397 | // This is a most-derived object. | ||||
398 | MostDerivedType = CAT->getElementType(); | ||||
399 | MostDerivedIsArrayElement = true; | ||||
400 | MostDerivedArraySize = CAT->getSize().getZExtValue(); | ||||
401 | MostDerivedPathLength = Entries.size(); | ||||
402 | } | ||||
403 | /// Update this designator to refer to the first element within the array of | ||||
404 | /// elements of type T. This is an array of unknown size. | ||||
405 | void addUnsizedArrayUnchecked(QualType ElemTy) { | ||||
406 | Entries.push_back(PathEntry::ArrayIndex(0)); | ||||
407 | |||||
408 | MostDerivedType = ElemTy; | ||||
409 | MostDerivedIsArrayElement = true; | ||||
410 | // The value in MostDerivedArraySize is undefined in this case. So, set it | ||||
411 | // to an arbitrary value that's likely to loudly break things if it's | ||||
412 | // used. | ||||
413 | MostDerivedArraySize = AssumedSizeForUnsizedArray; | ||||
414 | MostDerivedPathLength = Entries.size(); | ||||
415 | } | ||||
416 | /// Update this designator to refer to the given base or member of this | ||||
417 | /// object. | ||||
418 | void addDeclUnchecked(const Decl *D, bool Virtual = false) { | ||||
419 | Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); | ||||
420 | |||||
421 | // If this isn't a base class, it's a new most-derived object. | ||||
422 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { | ||||
423 | MostDerivedType = FD->getType(); | ||||
424 | MostDerivedIsArrayElement = false; | ||||
425 | MostDerivedArraySize = 0; | ||||
426 | MostDerivedPathLength = Entries.size(); | ||||
427 | } | ||||
428 | } | ||||
429 | /// Update this designator to refer to the given complex component. | ||||
430 | void addComplexUnchecked(QualType EltTy, bool Imag) { | ||||
431 | Entries.push_back(PathEntry::ArrayIndex(Imag)); | ||||
432 | |||||
433 | // This is technically a most-derived object, though in practice this | ||||
434 | // is unlikely to matter. | ||||
435 | MostDerivedType = EltTy; | ||||
436 | MostDerivedIsArrayElement = true; | ||||
437 | MostDerivedArraySize = 2; | ||||
438 | MostDerivedPathLength = Entries.size(); | ||||
439 | } | ||||
440 | void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); | ||||
441 | void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, | ||||
442 | const APSInt &N); | ||||
443 | /// Add N to the address of this subobject. | ||||
444 | void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { | ||||
445 | if (Invalid || !N) return; | ||||
446 | uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); | ||||
447 | if (isMostDerivedAnUnsizedArray()) { | ||||
448 | diagnoseUnsizedArrayPointerArithmetic(Info, E); | ||||
449 | // Can't verify -- trust that the user is doing the right thing (or if | ||||
450 | // not, trust that the caller will catch the bad behavior). | ||||
451 | // FIXME: Should we reject if this overflows, at least? | ||||
452 | Entries.back() = PathEntry::ArrayIndex( | ||||
453 | Entries.back().getAsArrayIndex() + TruncatedN); | ||||
454 | return; | ||||
455 | } | ||||
456 | |||||
457 | // [expr.add]p4: For the purposes of these operators, a pointer to a | ||||
458 | // nonarray object behaves the same as a pointer to the first element of | ||||
459 | // an array of length one with the type of the object as its element type. | ||||
460 | bool IsArray = MostDerivedPathLength == Entries.size() && | ||||
461 | MostDerivedIsArrayElement; | ||||
462 | uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() | ||||
463 | : (uint64_t)IsOnePastTheEnd; | ||||
464 | uint64_t ArraySize = | ||||
465 | IsArray ? getMostDerivedArraySize() : (uint64_t)1; | ||||
466 | |||||
467 | if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { | ||||
468 | // Calculate the actual index in a wide enough type, so we can include | ||||
469 | // it in the note. | ||||
470 | N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); | ||||
471 | (llvm::APInt&)N += ArrayIndex; | ||||
472 | assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")((N.ugt(ArraySize) && "bounds check failed for in-bounds index" ) ? static_cast<void> (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 472, __PRETTY_FUNCTION__)); | ||||
473 | diagnosePointerArithmetic(Info, E, N); | ||||
474 | setInvalid(); | ||||
475 | return; | ||||
476 | } | ||||
477 | |||||
478 | ArrayIndex += TruncatedN; | ||||
479 | assert(ArrayIndex <= ArraySize &&((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index" ) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 480, __PRETTY_FUNCTION__)) | ||||
480 | "bounds check succeeded for out-of-bounds index")((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index" ) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 480, __PRETTY_FUNCTION__)); | ||||
481 | |||||
482 | if (IsArray) | ||||
483 | Entries.back() = PathEntry::ArrayIndex(ArrayIndex); | ||||
484 | else | ||||
485 | IsOnePastTheEnd = (ArrayIndex != 0); | ||||
486 | } | ||||
487 | }; | ||||
488 | |||||
489 | /// A stack frame in the constexpr call stack. | ||||
490 | class CallStackFrame : public interp::Frame { | ||||
491 | public: | ||||
492 | EvalInfo &Info; | ||||
493 | |||||
494 | /// Parent - The caller of this stack frame. | ||||
495 | CallStackFrame *Caller; | ||||
496 | |||||
497 | /// Callee - The function which was called. | ||||
498 | const FunctionDecl *Callee; | ||||
499 | |||||
500 | /// This - The binding for the this pointer in this call, if any. | ||||
501 | const LValue *This; | ||||
502 | |||||
503 | /// Arguments - Parameter bindings for this function call, indexed by | ||||
504 | /// parameters' function scope indices. | ||||
505 | APValue *Arguments; | ||||
506 | |||||
507 | /// Source location information about the default argument or default | ||||
508 | /// initializer expression we're evaluating, if any. | ||||
509 | CurrentSourceLocExprScope CurSourceLocExprScope; | ||||
510 | |||||
511 | // Note that we intentionally use std::map here so that references to | ||||
512 | // values are stable. | ||||
513 | typedef std::pair<const void *, unsigned> MapKeyTy; | ||||
514 | typedef std::map<MapKeyTy, APValue> MapTy; | ||||
515 | /// Temporaries - Temporary lvalues materialized within this stack frame. | ||||
516 | MapTy Temporaries; | ||||
517 | |||||
518 | /// CallLoc - The location of the call expression for this call. | ||||
519 | SourceLocation CallLoc; | ||||
520 | |||||
521 | /// Index - The call index of this call. | ||||
522 | unsigned Index; | ||||
523 | |||||
524 | /// The stack of integers for tracking version numbers for temporaries. | ||||
525 | SmallVector<unsigned, 2> TempVersionStack = {1}; | ||||
526 | unsigned CurTempVersion = TempVersionStack.back(); | ||||
527 | |||||
528 | unsigned getTempVersion() const { return TempVersionStack.back(); } | ||||
529 | |||||
530 | void pushTempVersion() { | ||||
531 | TempVersionStack.push_back(++CurTempVersion); | ||||
532 | } | ||||
533 | |||||
534 | void popTempVersion() { | ||||
535 | TempVersionStack.pop_back(); | ||||
536 | } | ||||
537 | |||||
538 | // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact | ||||
539 | // on the overall stack usage of deeply-recursing constexpr evaluations. | ||||
540 | // (We should cache this map rather than recomputing it repeatedly.) | ||||
541 | // But let's try this and see how it goes; we can look into caching the map | ||||
542 | // as a later change. | ||||
543 | |||||
544 | /// LambdaCaptureFields - Mapping from captured variables/this to | ||||
545 | /// corresponding data members in the closure class. | ||||
546 | llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; | ||||
547 | FieldDecl *LambdaThisCaptureField; | ||||
548 | |||||
549 | CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||
550 | const FunctionDecl *Callee, const LValue *This, | ||||
551 | APValue *Arguments); | ||||
552 | ~CallStackFrame(); | ||||
553 | |||||
554 | // Return the temporary for Key whose version number is Version. | ||||
555 | APValue *getTemporary(const void *Key, unsigned Version) { | ||||
556 | MapKeyTy KV(Key, Version); | ||||
557 | auto LB = Temporaries.lower_bound(KV); | ||||
558 | if (LB != Temporaries.end() && LB->first == KV) | ||||
559 | return &LB->second; | ||||
560 | // Pair (Key,Version) wasn't found in the map. Check that no elements | ||||
561 | // in the map have 'Key' as their key. | ||||
562 | assert((LB == Temporaries.end() || LB->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)) | ||||
563 | (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)) | ||||
564 | "Element with key 'Key' found in map")(((LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && "Element with key 'Key' found in map") ? static_cast <void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 564, __PRETTY_FUNCTION__)); | ||||
565 | return nullptr; | ||||
566 | } | ||||
567 | |||||
568 | // Return the current temporary for Key in the map. | ||||
569 | APValue *getCurrentTemporary(const void *Key) { | ||||
570 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||
571 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||
572 | return &std::prev(UB)->second; | ||||
573 | return nullptr; | ||||
574 | } | ||||
575 | |||||
576 | // Return the version number of the current temporary for Key. | ||||
577 | unsigned getCurrentTemporaryVersion(const void *Key) const { | ||||
578 | auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U))); | ||||
579 | if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) | ||||
580 | return std::prev(UB)->first.second; | ||||
581 | return 0; | ||||
582 | } | ||||
583 | |||||
584 | /// Allocate storage for an object of type T in this stack frame. | ||||
585 | /// Populates LV with a handle to the created object. Key identifies | ||||
586 | /// the temporary within the stack frame, and must not be reused without | ||||
587 | /// bumping the temporary version number. | ||||
588 | template<typename KeyT> | ||||
589 | APValue &createTemporary(const KeyT *Key, QualType T, | ||||
590 | bool IsLifetimeExtended, LValue &LV); | ||||
591 | |||||
592 | void describe(llvm::raw_ostream &OS) override; | ||||
593 | |||||
594 | Frame *getCaller() const override { return Caller; } | ||||
595 | SourceLocation getCallLocation() const override { return CallLoc; } | ||||
596 | const FunctionDecl *getCallee() const override { return Callee; } | ||||
597 | }; | ||||
598 | |||||
599 | /// Temporarily override 'this'. | ||||
600 | class ThisOverrideRAII { | ||||
601 | public: | ||||
602 | ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) | ||||
603 | : Frame(Frame), OldThis(Frame.This) { | ||||
604 | if (Enable) | ||||
605 | Frame.This = NewThis; | ||||
606 | } | ||||
607 | ~ThisOverrideRAII() { | ||||
608 | Frame.This = OldThis; | ||||
609 | } | ||||
610 | private: | ||||
611 | CallStackFrame &Frame; | ||||
612 | const LValue *OldThis; | ||||
613 | }; | ||||
614 | } | ||||
615 | |||||
616 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||
617 | const LValue &This, QualType ThisType); | ||||
618 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||
619 | APValue::LValueBase LVBase, APValue &Value, | ||||
620 | QualType T); | ||||
621 | |||||
622 | namespace { | ||||
623 | /// A cleanup, and a flag indicating whether it is lifetime-extended. | ||||
624 | class Cleanup { | ||||
625 | llvm::PointerIntPair<APValue*, 1, bool> Value; | ||||
626 | APValue::LValueBase Base; | ||||
627 | QualType T; | ||||
628 | |||||
629 | public: | ||||
630 | Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, | ||||
631 | bool IsLifetimeExtended) | ||||
632 | : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} | ||||
633 | |||||
634 | bool isLifetimeExtended() const { return Value.getInt(); } | ||||
635 | bool endLifetime(EvalInfo &Info, bool RunDestructors) { | ||||
636 | if (RunDestructors) { | ||||
637 | SourceLocation Loc; | ||||
638 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) | ||||
639 | Loc = VD->getLocation(); | ||||
640 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||
641 | Loc = E->getExprLoc(); | ||||
642 | return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); | ||||
643 | } | ||||
644 | *Value.getPointer() = APValue(); | ||||
645 | return true; | ||||
646 | } | ||||
647 | |||||
648 | bool hasSideEffect() { | ||||
649 | return T.isDestructedType(); | ||||
650 | } | ||||
651 | }; | ||||
652 | |||||
653 | /// A reference to an object whose construction we are currently evaluating. | ||||
654 | struct ObjectUnderConstruction { | ||||
655 | APValue::LValueBase Base; | ||||
656 | ArrayRef<APValue::LValuePathEntry> Path; | ||||
657 | friend bool operator==(const ObjectUnderConstruction &LHS, | ||||
658 | const ObjectUnderConstruction &RHS) { | ||||
659 | return LHS.Base == RHS.Base && LHS.Path == RHS.Path; | ||||
660 | } | ||||
661 | friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { | ||||
662 | return llvm::hash_combine(Obj.Base, Obj.Path); | ||||
663 | } | ||||
664 | }; | ||||
665 | enum class ConstructionPhase { | ||||
666 | None, | ||||
667 | Bases, | ||||
668 | AfterBases, | ||||
669 | Destroying, | ||||
670 | DestroyingBases | ||||
671 | }; | ||||
672 | } | ||||
673 | |||||
674 | namespace llvm { | ||||
675 | template<> struct DenseMapInfo<ObjectUnderConstruction> { | ||||
676 | using Base = DenseMapInfo<APValue::LValueBase>; | ||||
677 | static ObjectUnderConstruction getEmptyKey() { | ||||
678 | return {Base::getEmptyKey(), {}}; } | ||||
679 | static ObjectUnderConstruction getTombstoneKey() { | ||||
680 | return {Base::getTombstoneKey(), {}}; | ||||
681 | } | ||||
682 | static unsigned getHashValue(const ObjectUnderConstruction &Object) { | ||||
683 | return hash_value(Object); | ||||
684 | } | ||||
685 | static bool isEqual(const ObjectUnderConstruction &LHS, | ||||
686 | const ObjectUnderConstruction &RHS) { | ||||
687 | return LHS == RHS; | ||||
688 | } | ||||
689 | }; | ||||
690 | } | ||||
691 | |||||
692 | namespace { | ||||
693 | /// EvalInfo - This is a private struct used by the evaluator to capture | ||||
694 | /// information about a subexpression as it is folded. It retains information | ||||
695 | /// about the AST context, but also maintains information about the folded | ||||
696 | /// expression. | ||||
697 | /// | ||||
698 | /// If an expression could be evaluated, it is still possible it is not a C | ||||
699 | /// "integer constant expression" or constant expression. If not, this struct | ||||
700 | /// captures information about how and why not. | ||||
701 | /// | ||||
702 | /// One bit of information passed *into* the request for constant folding | ||||
703 | /// indicates whether the subexpression is "evaluated" or not according to C | ||||
704 | /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can | ||||
705 | /// evaluate the expression regardless of what the RHS is, but C only allows | ||||
706 | /// certain things in certain situations. | ||||
707 | class EvalInfo : public interp::State { | ||||
708 | public: | ||||
709 | ASTContext &Ctx; | ||||
710 | |||||
711 | /// EvalStatus - Contains information about the evaluation. | ||||
712 | Expr::EvalStatus &EvalStatus; | ||||
713 | |||||
714 | /// CurrentCall - The top of the constexpr call stack. | ||||
715 | CallStackFrame *CurrentCall; | ||||
716 | |||||
717 | /// CallStackDepth - The number of calls in the call stack right now. | ||||
718 | unsigned CallStackDepth; | ||||
719 | |||||
720 | /// NextCallIndex - The next call index to assign. | ||||
721 | unsigned NextCallIndex; | ||||
722 | |||||
723 | /// StepsLeft - The remaining number of evaluation steps we're permitted | ||||
724 | /// to perform. This is essentially a limit for the number of statements | ||||
725 | /// we will evaluate. | ||||
726 | unsigned StepsLeft; | ||||
727 | |||||
728 | /// Force the use of the experimental new constant interpreter, bailing out | ||||
729 | /// with an error if a feature is not supported. | ||||
730 | bool ForceNewConstInterp; | ||||
731 | |||||
732 | /// Enable the experimental new constant interpreter. | ||||
733 | bool EnableNewConstInterp; | ||||
734 | |||||
735 | /// BottomFrame - The frame in which evaluation started. This must be | ||||
736 | /// initialized after CurrentCall and CallStackDepth. | ||||
737 | CallStackFrame BottomFrame; | ||||
738 | |||||
739 | /// A stack of values whose lifetimes end at the end of some surrounding | ||||
740 | /// evaluation frame. | ||||
741 | llvm::SmallVector<Cleanup, 16> CleanupStack; | ||||
742 | |||||
743 | /// EvaluatingDecl - This is the declaration whose initializer is being | ||||
744 | /// evaluated, if any. | ||||
745 | APValue::LValueBase EvaluatingDecl; | ||||
746 | |||||
747 | enum class EvaluatingDeclKind { | ||||
748 | None, | ||||
749 | /// We're evaluating the construction of EvaluatingDecl. | ||||
750 | Ctor, | ||||
751 | /// We're evaluating the destruction of EvaluatingDecl. | ||||
752 | Dtor, | ||||
753 | }; | ||||
754 | EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; | ||||
755 | |||||
756 | /// EvaluatingDeclValue - This is the value being constructed for the | ||||
757 | /// declaration whose initializer is being evaluated, if any. | ||||
758 | APValue *EvaluatingDeclValue; | ||||
759 | |||||
760 | /// Set of objects that are currently being constructed. | ||||
761 | llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> | ||||
762 | ObjectsUnderConstruction; | ||||
763 | |||||
764 | /// A dynamically-allocated heap object. | ||||
765 | struct DynAlloc { | ||||
766 | /// The value of this heap-allocated object. | ||||
767 | APValue Value; | ||||
768 | /// The allocating expression; used for diagnostics. | ||||
769 | const Expr *AllocExpr = nullptr; | ||||
770 | }; | ||||
771 | |||||
772 | struct DynAllocOrder { | ||||
773 | bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { | ||||
774 | return L.getIndex() < R.getIndex(); | ||||
775 | } | ||||
776 | }; | ||||
777 | |||||
778 | /// Current heap allocations, along with the location where each was | ||||
779 | /// allocated. We use std::map here because we need stable addresses | ||||
780 | /// for the stored APValues. | ||||
781 | std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; | ||||
782 | |||||
783 | /// The number of heap allocations performed so far in this evaluation. | ||||
784 | unsigned NumHeapAllocs = 0; | ||||
785 | |||||
786 | struct EvaluatingConstructorRAII { | ||||
787 | EvalInfo &EI; | ||||
788 | ObjectUnderConstruction Object; | ||||
789 | bool DidInsert; | ||||
790 | EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, | ||||
791 | bool HasBases) | ||||
792 | : EI(EI), Object(Object) { | ||||
793 | DidInsert = | ||||
794 | EI.ObjectsUnderConstruction | ||||
795 | .insert({Object, HasBases ? ConstructionPhase::Bases | ||||
796 | : ConstructionPhase::AfterBases}) | ||||
797 | .second; | ||||
798 | } | ||||
799 | void finishedConstructingBases() { | ||||
800 | EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; | ||||
801 | } | ||||
802 | ~EvaluatingConstructorRAII() { | ||||
803 | if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); | ||||
804 | } | ||||
805 | }; | ||||
806 | |||||
807 | struct EvaluatingDestructorRAII { | ||||
808 | EvalInfo &EI; | ||||
809 | ObjectUnderConstruction Object; | ||||
810 | bool DidInsert; | ||||
811 | EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) | ||||
812 | : EI(EI), Object(Object) { | ||||
813 | DidInsert = EI.ObjectsUnderConstruction | ||||
814 | .insert({Object, ConstructionPhase::Destroying}) | ||||
815 | .second; | ||||
816 | } | ||||
817 | void startedDestroyingBases() { | ||||
818 | EI.ObjectsUnderConstruction[Object] = | ||||
819 | ConstructionPhase::DestroyingBases; | ||||
820 | } | ||||
821 | ~EvaluatingDestructorRAII() { | ||||
822 | if (DidInsert) | ||||
823 | EI.ObjectsUnderConstruction.erase(Object); | ||||
824 | } | ||||
825 | }; | ||||
826 | |||||
827 | ConstructionPhase | ||||
828 | isEvaluatingCtorDtor(APValue::LValueBase Base, | ||||
829 | ArrayRef<APValue::LValuePathEntry> Path) { | ||||
830 | return ObjectsUnderConstruction.lookup({Base, Path}); | ||||
831 | } | ||||
832 | |||||
833 | /// If we're currently speculatively evaluating, the outermost call stack | ||||
834 | /// depth at which we can mutate state, otherwise 0. | ||||
835 | unsigned SpeculativeEvaluationDepth = 0; | ||||
836 | |||||
837 | /// The current array initialization index, if we're performing array | ||||
838 | /// initialization. | ||||
839 | uint64_t ArrayInitIndex = -1; | ||||
840 | |||||
841 | /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further | ||||
842 | /// notes attached to it will also be stored, otherwise they will not be. | ||||
843 | bool HasActiveDiagnostic; | ||||
844 | |||||
845 | /// Have we emitted a diagnostic explaining why we couldn't constant | ||||
846 | /// fold (not just why it's not strictly a constant expression)? | ||||
847 | bool HasFoldFailureDiagnostic; | ||||
848 | |||||
849 | /// Whether or not we're in a context where the front end requires a | ||||
850 | /// constant value. | ||||
851 | bool InConstantContext; | ||||
852 | |||||
853 | /// Whether we're checking that an expression is a potential constant | ||||
854 | /// expression. If so, do not fail on constructs that could become constant | ||||
855 | /// later on (such as a use of an undefined global). | ||||
856 | bool CheckingPotentialConstantExpression = false; | ||||
857 | |||||
858 | /// Whether we're checking for an expression that has undefined behavior. | ||||
859 | /// If so, we will produce warnings if we encounter an operation that is | ||||
860 | /// always undefined. | ||||
861 | bool CheckingForUndefinedBehavior = false; | ||||
862 | |||||
863 | enum EvaluationMode { | ||||
864 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||
865 | /// is not a constant expression. | ||||
866 | EM_ConstantExpression, | ||||
867 | |||||
868 | /// Evaluate as a constant expression. Stop if we find that the expression | ||||
869 | /// is not a constant expression. Some expressions can be retried in the | ||||
870 | /// optimizer if we don't constant fold them here, but in an unevaluated | ||||
871 | /// context we try to fold them immediately since the optimizer never | ||||
872 | /// gets a chance to look at it. | ||||
873 | EM_ConstantExpressionUnevaluated, | ||||
874 | |||||
875 | /// Fold the expression to a constant. Stop if we hit a side-effect that | ||||
876 | /// we can't model. | ||||
877 | EM_ConstantFold, | ||||
878 | |||||
879 | /// Evaluate in any way we know how. Don't worry about side-effects that | ||||
880 | /// can't be modeled. | ||||
881 | EM_IgnoreSideEffects, | ||||
882 | } EvalMode; | ||||
883 | |||||
884 | /// Are we checking whether the expression is a potential constant | ||||
885 | /// expression? | ||||
886 | bool checkingPotentialConstantExpression() const override { | ||||
887 | return CheckingPotentialConstantExpression; | ||||
888 | } | ||||
889 | |||||
890 | /// Are we checking an expression for overflow? | ||||
891 | // FIXME: We should check for any kind of undefined or suspicious behavior | ||||
892 | // in such constructs, not just overflow. | ||||
893 | bool checkingForUndefinedBehavior() const override { | ||||
894 | return CheckingForUndefinedBehavior; | ||||
895 | } | ||||
896 | |||||
897 | EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) | ||||
898 | : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), | ||||
899 | CallStackDepth(0), NextCallIndex(1), | ||||
900 | StepsLeft(getLangOpts().ConstexprStepLimit), | ||||
901 | ForceNewConstInterp(getLangOpts().ForceNewConstInterp), | ||||
902 | EnableNewConstInterp(ForceNewConstInterp || | ||||
903 | getLangOpts().EnableNewConstInterp), | ||||
904 | BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), | ||||
905 | EvaluatingDecl((const ValueDecl *)nullptr), | ||||
906 | EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), | ||||
907 | HasFoldFailureDiagnostic(false), InConstantContext(false), | ||||
908 | EvalMode(Mode) {} | ||||
909 | |||||
910 | ~EvalInfo() { | ||||
911 | discardCleanups(); | ||||
912 | } | ||||
913 | |||||
914 | void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, | ||||
915 | EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { | ||||
916 | EvaluatingDecl = Base; | ||||
917 | IsEvaluatingDecl = EDK; | ||||
918 | EvaluatingDeclValue = &Value; | ||||
919 | } | ||||
920 | |||||
921 | bool CheckCallLimit(SourceLocation Loc) { | ||||
922 | // Don't perform any constexpr calls (other than the call we're checking) | ||||
923 | // when checking a potential constant expression. | ||||
924 | if (checkingPotentialConstantExpression() && CallStackDepth > 1) | ||||
925 | return false; | ||||
926 | if (NextCallIndex == 0) { | ||||
927 | // NextCallIndex has wrapped around. | ||||
928 | FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); | ||||
929 | return false; | ||||
930 | } | ||||
931 | if (CallStackDepth <= getLangOpts().ConstexprCallDepth) | ||||
932 | return true; | ||||
933 | FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) | ||||
934 | << getLangOpts().ConstexprCallDepth; | ||||
935 | return false; | ||||
936 | } | ||||
937 | |||||
938 | std::pair<CallStackFrame *, unsigned> | ||||
939 | getCallFrameAndDepth(unsigned CallIndex) { | ||||
940 | assert(CallIndex && "no call index in getCallFrameAndDepth")((CallIndex && "no call index in getCallFrameAndDepth" ) ? static_cast<void> (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 940, __PRETTY_FUNCTION__)); | ||||
941 | // We will eventually hit BottomFrame, which has Index 1, so Frame can't | ||||
942 | // be null in this loop. | ||||
943 | unsigned Depth = CallStackDepth; | ||||
944 | CallStackFrame *Frame = CurrentCall; | ||||
945 | while (Frame->Index > CallIndex) { | ||||
946 | Frame = Frame->Caller; | ||||
947 | --Depth; | ||||
948 | } | ||||
949 | if (Frame->Index == CallIndex) | ||||
950 | return {Frame, Depth}; | ||||
951 | return {nullptr, 0}; | ||||
952 | } | ||||
953 | |||||
954 | bool nextStep(const Stmt *S) { | ||||
955 | if (!StepsLeft) { | ||||
956 | FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); | ||||
957 | return false; | ||||
958 | } | ||||
959 | --StepsLeft; | ||||
960 | return true; | ||||
961 | } | ||||
962 | |||||
963 | APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); | ||||
964 | |||||
965 | Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { | ||||
966 | Optional<DynAlloc*> Result; | ||||
967 | auto It = HeapAllocs.find(DA); | ||||
968 | if (It != HeapAllocs.end()) | ||||
969 | Result = &It->second; | ||||
970 | return Result; | ||||
971 | } | ||||
972 | |||||
973 | void performLifetimeExtension() { | ||||
974 | // Disable the cleanups for lifetime-extended temporaries. | ||||
975 | CleanupStack.erase( | ||||
976 | std::remove_if(CleanupStack.begin(), CleanupStack.end(), | ||||
977 | [](Cleanup &C) { return C.isLifetimeExtended(); }), | ||||
978 | CleanupStack.end()); | ||||
979 | } | ||||
980 | |||||
981 | /// Throw away any remaining cleanups at the end of evaluation. If any | ||||
982 | /// cleanups would have had a side-effect, note that as an unmodeled | ||||
983 | /// side-effect and return false. Otherwise, return true. | ||||
984 | bool discardCleanups() { | ||||
985 | for (Cleanup &C : CleanupStack) | ||||
986 | if (C.hasSideEffect()) | ||||
987 | if (!noteSideEffect()) | ||||
988 | return false; | ||||
989 | return true; | ||||
990 | } | ||||
991 | |||||
992 | private: | ||||
993 | interp::Frame *getCurrentFrame() override { return CurrentCall; } | ||||
994 | const interp::Frame *getBottomFrame() const override { return &BottomFrame; } | ||||
995 | |||||
996 | bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } | ||||
997 | void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } | ||||
998 | |||||
999 | void setFoldFailureDiagnostic(bool Flag) override { | ||||
1000 | HasFoldFailureDiagnostic = Flag; | ||||
1001 | } | ||||
1002 | |||||
1003 | Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } | ||||
1004 | |||||
1005 | ASTContext &getCtx() const override { return Ctx; } | ||||
1006 | |||||
1007 | // If we have a prior diagnostic, it will be noting that the expression | ||||
1008 | // isn't a constant expression. This diagnostic is more important, | ||||
1009 | // unless we require this evaluation to produce a constant expression. | ||||
1010 | // | ||||
1011 | // FIXME: We might want to show both diagnostics to the user in | ||||
1012 | // EM_ConstantFold mode. | ||||
1013 | bool hasPriorDiagnostic() override { | ||||
1014 | if (!EvalStatus.Diag->empty()) { | ||||
1015 | switch (EvalMode) { | ||||
1016 | case EM_ConstantFold: | ||||
1017 | case EM_IgnoreSideEffects: | ||||
1018 | if (!HasFoldFailureDiagnostic) | ||||
1019 | break; | ||||
1020 | // We've already failed to fold something. Keep that diagnostic. | ||||
1021 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
1022 | case EM_ConstantExpression: | ||||
1023 | case EM_ConstantExpressionUnevaluated: | ||||
1024 | setActiveDiagnostic(false); | ||||
1025 | return true; | ||||
1026 | } | ||||
1027 | } | ||||
1028 | return false; | ||||
1029 | } | ||||
1030 | |||||
1031 | unsigned getCallStackDepth() override { return CallStackDepth; } | ||||
1032 | |||||
1033 | public: | ||||
1034 | /// Should we continue evaluation after encountering a side-effect that we | ||||
1035 | /// couldn't model? | ||||
1036 | bool keepEvaluatingAfterSideEffect() { | ||||
1037 | switch (EvalMode) { | ||||
1038 | case EM_IgnoreSideEffects: | ||||
1039 | return true; | ||||
1040 | |||||
1041 | case EM_ConstantExpression: | ||||
1042 | case EM_ConstantExpressionUnevaluated: | ||||
1043 | case EM_ConstantFold: | ||||
1044 | // By default, assume any side effect might be valid in some other | ||||
1045 | // evaluation of this expression from a different context. | ||||
1046 | return checkingPotentialConstantExpression() || | ||||
1047 | checkingForUndefinedBehavior(); | ||||
1048 | } | ||||
1049 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1049); | ||||
1050 | } | ||||
1051 | |||||
1052 | /// Note that we have had a side-effect, and determine whether we should | ||||
1053 | /// keep evaluating. | ||||
1054 | bool noteSideEffect() { | ||||
1055 | EvalStatus.HasSideEffects = true; | ||||
1056 | return keepEvaluatingAfterSideEffect(); | ||||
1057 | } | ||||
1058 | |||||
1059 | /// Should we continue evaluation after encountering undefined behavior? | ||||
1060 | bool keepEvaluatingAfterUndefinedBehavior() { | ||||
1061 | switch (EvalMode) { | ||||
1062 | case EM_IgnoreSideEffects: | ||||
1063 | case EM_ConstantFold: | ||||
1064 | return true; | ||||
1065 | |||||
1066 | case EM_ConstantExpression: | ||||
1067 | case EM_ConstantExpressionUnevaluated: | ||||
1068 | return checkingForUndefinedBehavior(); | ||||
1069 | } | ||||
1070 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1070); | ||||
1071 | } | ||||
1072 | |||||
1073 | /// Note that we hit something that was technically undefined behavior, but | ||||
1074 | /// that we can evaluate past it (such as signed overflow or floating-point | ||||
1075 | /// division by zero.) | ||||
1076 | bool noteUndefinedBehavior() override { | ||||
1077 | EvalStatus.HasUndefinedBehavior = true; | ||||
1078 | return keepEvaluatingAfterUndefinedBehavior(); | ||||
1079 | } | ||||
1080 | |||||
1081 | /// Should we continue evaluation as much as possible after encountering a | ||||
1082 | /// construct which can't be reduced to a value? | ||||
1083 | bool keepEvaluatingAfterFailure() const override { | ||||
1084 | if (!StepsLeft) | ||||
1085 | return false; | ||||
1086 | |||||
1087 | switch (EvalMode) { | ||||
1088 | case EM_ConstantExpression: | ||||
1089 | case EM_ConstantExpressionUnevaluated: | ||||
1090 | case EM_ConstantFold: | ||||
1091 | case EM_IgnoreSideEffects: | ||||
1092 | return checkingPotentialConstantExpression() || | ||||
1093 | checkingForUndefinedBehavior(); | ||||
1094 | } | ||||
1095 | llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1095); | ||||
1096 | } | ||||
1097 | |||||
1098 | /// Notes that we failed to evaluate an expression that other expressions | ||||
1099 | /// directly depend on, and determine if we should keep evaluating. This | ||||
1100 | /// should only be called if we actually intend to keep evaluating. | ||||
1101 | /// | ||||
1102 | /// Call noteSideEffect() instead if we may be able to ignore the value that | ||||
1103 | /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: | ||||
1104 | /// | ||||
1105 | /// (Foo(), 1) // use noteSideEffect | ||||
1106 | /// (Foo() || true) // use noteSideEffect | ||||
1107 | /// Foo() + 1 // use noteFailure | ||||
1108 | LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() { | ||||
1109 | // Failure when evaluating some expression often means there is some | ||||
1110 | // subexpression whose evaluation was skipped. Therefore, (because we | ||||
1111 | // don't track whether we skipped an expression when unwinding after an | ||||
1112 | // evaluation failure) every evaluation failure that bubbles up from a | ||||
1113 | // subexpression implies that a side-effect has potentially happened. We | ||||
1114 | // skip setting the HasSideEffects flag to true until we decide to | ||||
1115 | // continue evaluating after that point, which happens here. | ||||
1116 | bool KeepGoing = keepEvaluatingAfterFailure(); | ||||
1117 | EvalStatus.HasSideEffects |= KeepGoing; | ||||
1118 | return KeepGoing; | ||||
1119 | } | ||||
1120 | |||||
1121 | class ArrayInitLoopIndex { | ||||
1122 | EvalInfo &Info; | ||||
1123 | uint64_t OuterIndex; | ||||
1124 | |||||
1125 | public: | ||||
1126 | ArrayInitLoopIndex(EvalInfo &Info) | ||||
1127 | : Info(Info), OuterIndex(Info.ArrayInitIndex) { | ||||
1128 | Info.ArrayInitIndex = 0; | ||||
1129 | } | ||||
1130 | ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } | ||||
1131 | |||||
1132 | operator uint64_t&() { return Info.ArrayInitIndex; } | ||||
1133 | }; | ||||
1134 | }; | ||||
1135 | |||||
1136 | /// Object used to treat all foldable expressions as constant expressions. | ||||
1137 | struct FoldConstant { | ||||
1138 | EvalInfo &Info; | ||||
1139 | bool Enabled; | ||||
1140 | bool HadNoPriorDiags; | ||||
1141 | EvalInfo::EvaluationMode OldMode; | ||||
1142 | |||||
1143 | explicit FoldConstant(EvalInfo &Info, bool Enabled) | ||||
1144 | : Info(Info), | ||||
1145 | Enabled(Enabled), | ||||
1146 | HadNoPriorDiags(Info.EvalStatus.Diag && | ||||
1147 | Info.EvalStatus.Diag->empty() && | ||||
1148 | !Info.EvalStatus.HasSideEffects), | ||||
1149 | OldMode(Info.EvalMode) { | ||||
1150 | if (Enabled) | ||||
1151 | Info.EvalMode = EvalInfo::EM_ConstantFold; | ||||
1152 | } | ||||
1153 | void keepDiagnostics() { Enabled = false; } | ||||
1154 | ~FoldConstant() { | ||||
1155 | if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && | ||||
1156 | !Info.EvalStatus.HasSideEffects) | ||||
1157 | Info.EvalStatus.Diag->clear(); | ||||
1158 | Info.EvalMode = OldMode; | ||||
1159 | } | ||||
1160 | }; | ||||
1161 | |||||
1162 | /// RAII object used to set the current evaluation mode to ignore | ||||
1163 | /// side-effects. | ||||
1164 | struct IgnoreSideEffectsRAII { | ||||
1165 | EvalInfo &Info; | ||||
1166 | EvalInfo::EvaluationMode OldMode; | ||||
1167 | explicit IgnoreSideEffectsRAII(EvalInfo &Info) | ||||
1168 | : Info(Info), OldMode(Info.EvalMode) { | ||||
1169 | Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; | ||||
1170 | } | ||||
1171 | |||||
1172 | ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } | ||||
1173 | }; | ||||
1174 | |||||
1175 | /// RAII object used to optionally suppress diagnostics and side-effects from | ||||
1176 | /// a speculative evaluation. | ||||
1177 | class SpeculativeEvaluationRAII { | ||||
1178 | EvalInfo *Info = nullptr; | ||||
1179 | Expr::EvalStatus OldStatus; | ||||
1180 | unsigned OldSpeculativeEvaluationDepth; | ||||
1181 | |||||
1182 | void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { | ||||
1183 | Info = Other.Info; | ||||
1184 | OldStatus = Other.OldStatus; | ||||
1185 | OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; | ||||
1186 | Other.Info = nullptr; | ||||
1187 | } | ||||
1188 | |||||
1189 | void maybeRestoreState() { | ||||
1190 | if (!Info) | ||||
1191 | return; | ||||
1192 | |||||
1193 | Info->EvalStatus = OldStatus; | ||||
1194 | Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; | ||||
1195 | } | ||||
1196 | |||||
1197 | public: | ||||
1198 | SpeculativeEvaluationRAII() = default; | ||||
1199 | |||||
1200 | SpeculativeEvaluationRAII( | ||||
1201 | EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) | ||||
1202 | : Info(&Info), OldStatus(Info.EvalStatus), | ||||
1203 | OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { | ||||
1204 | Info.EvalStatus.Diag = NewDiag; | ||||
1205 | Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; | ||||
1206 | } | ||||
1207 | |||||
1208 | SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; | ||||
1209 | SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { | ||||
1210 | moveFromAndCancel(std::move(Other)); | ||||
1211 | } | ||||
1212 | |||||
1213 | SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { | ||||
1214 | maybeRestoreState(); | ||||
1215 | moveFromAndCancel(std::move(Other)); | ||||
1216 | return *this; | ||||
1217 | } | ||||
1218 | |||||
1219 | ~SpeculativeEvaluationRAII() { maybeRestoreState(); } | ||||
1220 | }; | ||||
1221 | |||||
1222 | /// RAII object wrapping a full-expression or block scope, and handling | ||||
1223 | /// the ending of the lifetime of temporaries created within it. | ||||
1224 | template<bool IsFullExpression> | ||||
1225 | class ScopeRAII { | ||||
1226 | EvalInfo &Info; | ||||
1227 | unsigned OldStackSize; | ||||
1228 | public: | ||||
1229 | ScopeRAII(EvalInfo &Info) | ||||
1230 | : Info(Info), OldStackSize(Info.CleanupStack.size()) { | ||||
1231 | // Push a new temporary version. This is needed to distinguish between | ||||
1232 | // temporaries created in different iterations of a loop. | ||||
1233 | Info.CurrentCall->pushTempVersion(); | ||||
1234 | } | ||||
1235 | bool destroy(bool RunDestructors = true) { | ||||
1236 | bool OK = cleanup(Info, RunDestructors, OldStackSize); | ||||
1237 | OldStackSize = -1U; | ||||
1238 | return OK; | ||||
1239 | } | ||||
1240 | ~ScopeRAII() { | ||||
1241 | if (OldStackSize != -1U) | ||||
1242 | destroy(false); | ||||
1243 | // Body moved to a static method to encourage the compiler to inline away | ||||
1244 | // instances of this class. | ||||
1245 | Info.CurrentCall->popTempVersion(); | ||||
1246 | } | ||||
1247 | private: | ||||
1248 | static bool cleanup(EvalInfo &Info, bool RunDestructors, | ||||
1249 | unsigned OldStackSize) { | ||||
1250 | assert(OldStackSize <= Info.CleanupStack.size() &&((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?" ) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1251, __PRETTY_FUNCTION__)) | ||||
1251 | "running cleanups out of order?")((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?" ) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1251, __PRETTY_FUNCTION__)); | ||||
1252 | |||||
1253 | // Run all cleanups for a block scope, and non-lifetime-extended cleanups | ||||
1254 | // for a full-expression scope. | ||||
1255 | bool Success = true; | ||||
1256 | for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { | ||||
1257 | if (!(IsFullExpression && | ||||
1258 | Info.CleanupStack[I - 1].isLifetimeExtended())) { | ||||
1259 | if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { | ||||
1260 | Success = false; | ||||
1261 | break; | ||||
1262 | } | ||||
1263 | } | ||||
1264 | } | ||||
1265 | |||||
1266 | // Compact lifetime-extended cleanups. | ||||
1267 | auto NewEnd = Info.CleanupStack.begin() + OldStackSize; | ||||
1268 | if (IsFullExpression) | ||||
1269 | NewEnd = | ||||
1270 | std::remove_if(NewEnd, Info.CleanupStack.end(), | ||||
1271 | [](Cleanup &C) { return !C.isLifetimeExtended(); }); | ||||
1272 | Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); | ||||
1273 | return Success; | ||||
1274 | } | ||||
1275 | }; | ||||
1276 | typedef ScopeRAII<false> BlockScopeRAII; | ||||
1277 | typedef ScopeRAII<true> FullExpressionRAII; | ||||
1278 | } | ||||
1279 | |||||
1280 | bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, | ||||
1281 | CheckSubobjectKind CSK) { | ||||
1282 | if (Invalid) | ||||
1283 | return false; | ||||
1284 | if (isOnePastTheEnd()) { | ||||
1285 | Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) | ||||
1286 | << CSK; | ||||
1287 | setInvalid(); | ||||
1288 | return false; | ||||
1289 | } | ||||
1290 | // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there | ||||
1291 | // must actually be at least one array element; even a VLA cannot have a | ||||
1292 | // bound of zero. And if our index is nonzero, we already had a CCEDiag. | ||||
1293 | return true; | ||||
1294 | } | ||||
1295 | |||||
1296 | void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, | ||||
1297 | const Expr *E) { | ||||
1298 | Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); | ||||
1299 | // Do not set the designator as invalid: we can represent this situation, | ||||
1300 | // and correct handling of __builtin_object_size requires us to do so. | ||||
1301 | } | ||||
1302 | |||||
1303 | void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, | ||||
1304 | const Expr *E, | ||||
1305 | const APSInt &N) { | ||||
1306 | // If we're complaining, we must be able to statically determine the size of | ||||
1307 | // the most derived array. | ||||
1308 | if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) | ||||
1309 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||
1310 | << N << /*array*/ 0 | ||||
1311 | << static_cast<unsigned>(getMostDerivedArraySize()); | ||||
1312 | else | ||||
1313 | Info.CCEDiag(E, diag::note_constexpr_array_index) | ||||
1314 | << N << /*non-array*/ 1; | ||||
1315 | setInvalid(); | ||||
1316 | } | ||||
1317 | |||||
1318 | CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, | ||||
1319 | const FunctionDecl *Callee, const LValue *This, | ||||
1320 | APValue *Arguments) | ||||
1321 | : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), | ||||
1322 | Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { | ||||
1323 | Info.CurrentCall = this; | ||||
1324 | ++Info.CallStackDepth; | ||||
1325 | } | ||||
1326 | |||||
1327 | CallStackFrame::~CallStackFrame() { | ||||
1328 | assert(Info.CurrentCall == this && "calls retired out of order")((Info.CurrentCall == this && "calls retired out of order" ) ? static_cast<void> (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1328, __PRETTY_FUNCTION__)); | ||||
1329 | --Info.CallStackDepth; | ||||
1330 | Info.CurrentCall = Caller; | ||||
1331 | } | ||||
1332 | |||||
1333 | static bool isRead(AccessKinds AK) { | ||||
1334 | return AK == AK_Read || AK == AK_ReadObjectRepresentation; | ||||
1335 | } | ||||
1336 | |||||
1337 | static bool isModification(AccessKinds AK) { | ||||
1338 | switch (AK) { | ||||
1339 | case AK_Read: | ||||
1340 | case AK_ReadObjectRepresentation: | ||||
1341 | case AK_MemberCall: | ||||
1342 | case AK_DynamicCast: | ||||
1343 | case AK_TypeId: | ||||
1344 | return false; | ||||
1345 | case AK_Assign: | ||||
1346 | case AK_Increment: | ||||
1347 | case AK_Decrement: | ||||
1348 | case AK_Destroy: | ||||
1349 | return true; | ||||
1350 | } | ||||
1351 | llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1351); | ||||
1352 | } | ||||
1353 | |||||
1354 | static bool isAnyAccess(AccessKinds AK) { | ||||
1355 | return isRead(AK) || isModification(AK); | ||||
1356 | } | ||||
1357 | |||||
1358 | /// Is this an access per the C++ definition? | ||||
1359 | static bool isFormalAccess(AccessKinds AK) { | ||||
1360 | return isAnyAccess(AK) && AK != AK_Destroy; | ||||
1361 | } | ||||
1362 | |||||
1363 | namespace { | ||||
1364 | struct ComplexValue { | ||||
1365 | private: | ||||
1366 | bool IsInt; | ||||
1367 | |||||
1368 | public: | ||||
1369 | APSInt IntReal, IntImag; | ||||
1370 | APFloat FloatReal, FloatImag; | ||||
1371 | |||||
1372 | ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} | ||||
1373 | |||||
1374 | void makeComplexFloat() { IsInt = false; } | ||||
1375 | bool isComplexFloat() const { return !IsInt; } | ||||
1376 | APFloat &getComplexFloatReal() { return FloatReal; } | ||||
1377 | APFloat &getComplexFloatImag() { return FloatImag; } | ||||
1378 | |||||
1379 | void makeComplexInt() { IsInt = true; } | ||||
1380 | bool isComplexInt() const { return IsInt; } | ||||
1381 | APSInt &getComplexIntReal() { return IntReal; } | ||||
1382 | APSInt &getComplexIntImag() { return IntImag; } | ||||
1383 | |||||
1384 | void moveInto(APValue &v) const { | ||||
1385 | if (isComplexFloat()) | ||||
1386 | v = APValue(FloatReal, FloatImag); | ||||
1387 | else | ||||
1388 | v = APValue(IntReal, IntImag); | ||||
1389 | } | ||||
1390 | void setFrom(const APValue &v) { | ||||
1391 | assert(v.isComplexFloat() || v.isComplexInt())((v.isComplexFloat() || v.isComplexInt()) ? static_cast<void > (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1391, __PRETTY_FUNCTION__)); | ||||
1392 | if (v.isComplexFloat()) { | ||||
1393 | makeComplexFloat(); | ||||
1394 | FloatReal = v.getComplexFloatReal(); | ||||
1395 | FloatImag = v.getComplexFloatImag(); | ||||
1396 | } else { | ||||
1397 | makeComplexInt(); | ||||
1398 | IntReal = v.getComplexIntReal(); | ||||
1399 | IntImag = v.getComplexIntImag(); | ||||
1400 | } | ||||
1401 | } | ||||
1402 | }; | ||||
1403 | |||||
1404 | struct LValue { | ||||
1405 | APValue::LValueBase Base; | ||||
1406 | CharUnits Offset; | ||||
1407 | SubobjectDesignator Designator; | ||||
1408 | bool IsNullPtr : 1; | ||||
1409 | bool InvalidBase : 1; | ||||
1410 | |||||
1411 | const APValue::LValueBase getLValueBase() const { return Base; } | ||||
1412 | CharUnits &getLValueOffset() { return Offset; } | ||||
1413 | const CharUnits &getLValueOffset() const { return Offset; } | ||||
1414 | SubobjectDesignator &getLValueDesignator() { return Designator; } | ||||
1415 | const SubobjectDesignator &getLValueDesignator() const { return Designator;} | ||||
1416 | bool isNullPointer() const { return IsNullPtr;} | ||||
1417 | |||||
1418 | unsigned getLValueCallIndex() const { return Base.getCallIndex(); } | ||||
1419 | unsigned getLValueVersion() const { return Base.getVersion(); } | ||||
1420 | |||||
1421 | void moveInto(APValue &V) const { | ||||
1422 | if (Designator.Invalid) | ||||
1423 | V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); | ||||
1424 | else { | ||||
1425 | assert(!InvalidBase && "APValues can't handle invalid LValue bases")((!InvalidBase && "APValues can't handle invalid LValue bases" ) ? static_cast<void> (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1425, __PRETTY_FUNCTION__)); | ||||
1426 | V = APValue(Base, Offset, Designator.Entries, | ||||
1427 | Designator.IsOnePastTheEnd, IsNullPtr); | ||||
1428 | } | ||||
1429 | } | ||||
1430 | void setFrom(ASTContext &Ctx, const APValue &V) { | ||||
1431 | assert(V.isLValue() && "Setting LValue from a non-LValue?")((V.isLValue() && "Setting LValue from a non-LValue?" ) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1431, __PRETTY_FUNCTION__)); | ||||
1432 | Base = V.getLValueBase(); | ||||
1433 | Offset = V.getLValueOffset(); | ||||
1434 | InvalidBase = false; | ||||
1435 | Designator = SubobjectDesignator(Ctx, V); | ||||
1436 | IsNullPtr = V.isNullPointer(); | ||||
1437 | } | ||||
1438 | |||||
1439 | void set(APValue::LValueBase B, bool BInvalid = false) { | ||||
1440 | #ifndef NDEBUG | ||||
1441 | // We only allow a few types of invalid bases. Enforce that here. | ||||
1442 | if (BInvalid) { | ||||
1443 | const auto *E = B.get<const Expr *>(); | ||||
1444 | assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && "Unexpected type of invalid base") ? static_cast<void> (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1445, __PRETTY_FUNCTION__)) | ||||
1445 | "Unexpected type of invalid base")(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && "Unexpected type of invalid base") ? static_cast<void> (0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1445, __PRETTY_FUNCTION__)); | ||||
1446 | } | ||||
1447 | #endif | ||||
1448 | |||||
1449 | Base = B; | ||||
1450 | Offset = CharUnits::fromQuantity(0); | ||||
1451 | InvalidBase = BInvalid; | ||||
1452 | Designator = SubobjectDesignator(getType(B)); | ||||
1453 | IsNullPtr = false; | ||||
1454 | } | ||||
1455 | |||||
1456 | void setNull(QualType PointerTy, uint64_t TargetVal) { | ||||
1457 | Base = (Expr *)nullptr; | ||||
1458 | Offset = CharUnits::fromQuantity(TargetVal); | ||||
1459 | InvalidBase = false; | ||||
1460 | Designator = SubobjectDesignator(PointerTy->getPointeeType()); | ||||
1461 | IsNullPtr = true; | ||||
1462 | } | ||||
1463 | |||||
1464 | void setInvalid(APValue::LValueBase B, unsigned I = 0) { | ||||
1465 | set(B, true); | ||||
1466 | } | ||||
1467 | |||||
1468 | private: | ||||
1469 | // Check that this LValue is not based on a null pointer. If it is, produce | ||||
1470 | // a diagnostic and mark the designator as invalid. | ||||
1471 | template <typename GenDiagType> | ||||
1472 | bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { | ||||
1473 | if (Designator.Invalid) | ||||
1474 | return false; | ||||
1475 | if (IsNullPtr) { | ||||
1476 | GenDiag(); | ||||
1477 | Designator.setInvalid(); | ||||
1478 | return false; | ||||
1479 | } | ||||
1480 | return true; | ||||
1481 | } | ||||
1482 | |||||
1483 | public: | ||||
1484 | bool checkNullPointer(EvalInfo &Info, const Expr *E, | ||||
1485 | CheckSubobjectKind CSK) { | ||||
1486 | return checkNullPointerDiagnosingWith([&Info, E, CSK] { | ||||
1487 | Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; | ||||
1488 | }); | ||||
1489 | } | ||||
1490 | |||||
1491 | bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, | ||||
1492 | AccessKinds AK) { | ||||
1493 | return checkNullPointerDiagnosingWith([&Info, E, AK] { | ||||
1494 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||
1495 | }); | ||||
1496 | } | ||||
1497 | |||||
1498 | // Check this LValue refers to an object. If not, set the designator to be | ||||
1499 | // invalid and emit a diagnostic. | ||||
1500 | bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { | ||||
1501 | return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && | ||||
1502 | Designator.checkSubobject(Info, E, CSK); | ||||
1503 | } | ||||
1504 | |||||
1505 | void addDecl(EvalInfo &Info, const Expr *E, | ||||
1506 | const Decl *D, bool Virtual = false) { | ||||
1507 | if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) | ||||
1508 | Designator.addDeclUnchecked(D, Virtual); | ||||
1509 | } | ||||
1510 | void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { | ||||
1511 | if (!Designator.Entries.empty()) { | ||||
1512 | Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); | ||||
1513 | Designator.setInvalid(); | ||||
1514 | return; | ||||
1515 | } | ||||
1516 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) { | ||||
1517 | assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())((getType(Base)->isPointerType() || getType(Base)->isArrayType ()) ? static_cast<void> (0) : __assert_fail ("getType(Base)->isPointerType() || getType(Base)->isArrayType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1517, __PRETTY_FUNCTION__)); | ||||
1518 | Designator.FirstEntryIsAnUnsizedArray = true; | ||||
1519 | Designator.addUnsizedArrayUnchecked(ElemTy); | ||||
1520 | } | ||||
1521 | } | ||||
1522 | void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { | ||||
1523 | if (checkSubobject(Info, E, CSK_ArrayToPointer)) | ||||
1524 | Designator.addArrayUnchecked(CAT); | ||||
1525 | } | ||||
1526 | void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { | ||||
1527 | if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) | ||||
1528 | Designator.addComplexUnchecked(EltTy, Imag); | ||||
1529 | } | ||||
1530 | void clearIsNullPointer() { | ||||
1531 | IsNullPtr = false; | ||||
1532 | } | ||||
1533 | void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, | ||||
1534 | const APSInt &Index, CharUnits ElementSize) { | ||||
1535 | // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, | ||||
1536 | // but we're not required to diagnose it and it's valid in C++.) | ||||
1537 | if (!Index) | ||||
1538 | return; | ||||
1539 | |||||
1540 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||
1541 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||
1542 | // offsets. | ||||
1543 | uint64_t Offset64 = Offset.getQuantity(); | ||||
1544 | uint64_t ElemSize64 = ElementSize.getQuantity(); | ||||
1545 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||
1546 | Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); | ||||
1547 | |||||
1548 | if (checkNullPointer(Info, E, CSK_ArrayIndex)) | ||||
1549 | Designator.adjustIndex(Info, E, Index); | ||||
1550 | clearIsNullPointer(); | ||||
1551 | } | ||||
1552 | void adjustOffset(CharUnits N) { | ||||
1553 | Offset += N; | ||||
1554 | if (N.getQuantity()) | ||||
1555 | clearIsNullPointer(); | ||||
1556 | } | ||||
1557 | }; | ||||
1558 | |||||
1559 | struct MemberPtr { | ||||
1560 | MemberPtr() {} | ||||
1561 | explicit MemberPtr(const ValueDecl *Decl) : | ||||
1562 | DeclAndIsDerivedMember(Decl, false), Path() {} | ||||
1563 | |||||
1564 | /// The member or (direct or indirect) field referred to by this member | ||||
1565 | /// pointer, or 0 if this is a null member pointer. | ||||
1566 | const ValueDecl *getDecl() const { | ||||
1567 | return DeclAndIsDerivedMember.getPointer(); | ||||
1568 | } | ||||
1569 | /// Is this actually a member of some type derived from the relevant class? | ||||
1570 | bool isDerivedMember() const { | ||||
1571 | return DeclAndIsDerivedMember.getInt(); | ||||
1572 | } | ||||
1573 | /// Get the class which the declaration actually lives in. | ||||
1574 | const CXXRecordDecl *getContainingRecord() const { | ||||
1575 | return cast<CXXRecordDecl>( | ||||
1576 | DeclAndIsDerivedMember.getPointer()->getDeclContext()); | ||||
1577 | } | ||||
1578 | |||||
1579 | void moveInto(APValue &V) const { | ||||
1580 | V = APValue(getDecl(), isDerivedMember(), Path); | ||||
1581 | } | ||||
1582 | void setFrom(const APValue &V) { | ||||
1583 | assert(V.isMemberPointer())((V.isMemberPointer()) ? static_cast<void> (0) : __assert_fail ("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1583, __PRETTY_FUNCTION__)); | ||||
1584 | DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); | ||||
1585 | DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); | ||||
1586 | Path.clear(); | ||||
1587 | ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); | ||||
1588 | Path.insert(Path.end(), P.begin(), P.end()); | ||||
1589 | } | ||||
1590 | |||||
1591 | /// DeclAndIsDerivedMember - The member declaration, and a flag indicating | ||||
1592 | /// whether the member is a member of some class derived from the class type | ||||
1593 | /// of the member pointer. | ||||
1594 | llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; | ||||
1595 | /// Path - The path of base/derived classes from the member declaration's | ||||
1596 | /// class (exclusive) to the class type of the member pointer (inclusive). | ||||
1597 | SmallVector<const CXXRecordDecl*, 4> Path; | ||||
1598 | |||||
1599 | /// Perform a cast towards the class of the Decl (either up or down the | ||||
1600 | /// hierarchy). | ||||
1601 | bool castBack(const CXXRecordDecl *Class) { | ||||
1602 | assert(!Path.empty())((!Path.empty()) ? static_cast<void> (0) : __assert_fail ("!Path.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1602, __PRETTY_FUNCTION__)); | ||||
1603 | const CXXRecordDecl *Expected; | ||||
1604 | if (Path.size() >= 2) | ||||
1605 | Expected = Path[Path.size() - 2]; | ||||
1606 | else | ||||
1607 | Expected = getContainingRecord(); | ||||
1608 | if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { | ||||
1609 | // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), | ||||
1610 | // if B does not contain the original member and is not a base or | ||||
1611 | // derived class of the class containing the original member, the result | ||||
1612 | // of the cast is undefined. | ||||
1613 | // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to | ||||
1614 | // (D::*). We consider that to be a language defect. | ||||
1615 | return false; | ||||
1616 | } | ||||
1617 | Path.pop_back(); | ||||
1618 | return true; | ||||
1619 | } | ||||
1620 | /// Perform a base-to-derived member pointer cast. | ||||
1621 | bool castToDerived(const CXXRecordDecl *Derived) { | ||||
1622 | if (!getDecl()) | ||||
1623 | return true; | ||||
1624 | if (!isDerivedMember()) { | ||||
1625 | Path.push_back(Derived); | ||||
1626 | return true; | ||||
1627 | } | ||||
1628 | if (!castBack(Derived)) | ||||
1629 | return false; | ||||
1630 | if (Path.empty()) | ||||
1631 | DeclAndIsDerivedMember.setInt(false); | ||||
1632 | return true; | ||||
1633 | } | ||||
1634 | /// Perform a derived-to-base member pointer cast. | ||||
1635 | bool castToBase(const CXXRecordDecl *Base) { | ||||
1636 | if (!getDecl()) | ||||
1637 | return true; | ||||
1638 | if (Path.empty()) | ||||
1639 | DeclAndIsDerivedMember.setInt(true); | ||||
1640 | if (isDerivedMember()) { | ||||
1641 | Path.push_back(Base); | ||||
1642 | return true; | ||||
1643 | } | ||||
1644 | return castBack(Base); | ||||
1645 | } | ||||
1646 | }; | ||||
1647 | |||||
1648 | /// Compare two member pointers, which are assumed to be of the same type. | ||||
1649 | static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { | ||||
1650 | if (!LHS.getDecl() || !RHS.getDecl()) | ||||
1651 | return !LHS.getDecl() && !RHS.getDecl(); | ||||
1652 | if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) | ||||
1653 | return false; | ||||
1654 | return LHS.Path == RHS.Path; | ||||
1655 | } | ||||
1656 | } | ||||
1657 | |||||
1658 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); | ||||
1659 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, | ||||
1660 | const LValue &This, const Expr *E, | ||||
1661 | bool AllowNonLiteralTypes = false); | ||||
1662 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
1663 | bool InvalidBaseOK = false); | ||||
1664 | static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
1665 | bool InvalidBaseOK = false); | ||||
1666 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||
1667 | EvalInfo &Info); | ||||
1668 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); | ||||
1669 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); | ||||
1670 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||
1671 | EvalInfo &Info); | ||||
1672 | static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); | ||||
1673 | static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); | ||||
1674 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||
1675 | EvalInfo &Info); | ||||
1676 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); | ||||
1677 | |||||
1678 | /// Evaluate an integer or fixed point expression into an APResult. | ||||
1679 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||
1680 | EvalInfo &Info); | ||||
1681 | |||||
1682 | /// Evaluate only a fixed point expression into an APResult. | ||||
1683 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||
1684 | EvalInfo &Info); | ||||
1685 | |||||
1686 | //===----------------------------------------------------------------------===// | ||||
1687 | // Misc utilities | ||||
1688 | //===----------------------------------------------------------------------===// | ||||
1689 | |||||
1690 | /// Negate an APSInt in place, converting it to a signed form if necessary, and | ||||
1691 | /// preserving its value (by extending by up to one bit as needed). | ||||
1692 | static void negateAsSigned(APSInt &Int) { | ||||
1693 | if (Int.isUnsigned() || Int.isMinSignedValue()) { | ||||
1694 | Int = Int.extend(Int.getBitWidth() + 1); | ||||
1695 | Int.setIsSigned(true); | ||||
1696 | } | ||||
1697 | Int = -Int; | ||||
1698 | } | ||||
1699 | |||||
1700 | template<typename KeyT> | ||||
1701 | APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, | ||||
1702 | bool IsLifetimeExtended, LValue &LV) { | ||||
1703 | unsigned Version = getTempVersion(); | ||||
1704 | APValue::LValueBase Base(Key, Index, Version); | ||||
1705 | LV.set(Base); | ||||
1706 | APValue &Result = Temporaries[MapKeyTy(Key, Version)]; | ||||
1707 | assert(Result.isAbsent() && "temporary created multiple times")((Result.isAbsent() && "temporary created multiple times" ) ? static_cast<void> (0) : __assert_fail ("Result.isAbsent() && \"temporary created multiple times\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1707, __PRETTY_FUNCTION__)); | ||||
1708 | |||||
1709 | // If we're creating a temporary immediately in the operand of a speculative | ||||
1710 | // evaluation, don't register a cleanup to be run outside the speculative | ||||
1711 | // evaluation context, since we won't actually be able to initialize this | ||||
1712 | // object. | ||||
1713 | if (Index <= Info.SpeculativeEvaluationDepth) { | ||||
1714 | if (T.isDestructedType()) | ||||
1715 | Info.noteSideEffect(); | ||||
1716 | } else { | ||||
1717 | Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); | ||||
1718 | } | ||||
1719 | return Result; | ||||
1720 | } | ||||
1721 | |||||
1722 | APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { | ||||
1723 | if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { | ||||
1724 | FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); | ||||
1725 | return nullptr; | ||||
1726 | } | ||||
1727 | |||||
1728 | DynamicAllocLValue DA(NumHeapAllocs++); | ||||
1729 | LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); | ||||
1730 | auto Result = HeapAllocs.emplace(std::piecewise_construct, | ||||
1731 | std::forward_as_tuple(DA), std::tuple<>()); | ||||
1732 | assert(Result.second && "reused a heap alloc index?")((Result.second && "reused a heap alloc index?") ? static_cast <void> (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1732, __PRETTY_FUNCTION__)); | ||||
1733 | Result.first->second.AllocExpr = E; | ||||
1734 | return &Result.first->second.Value; | ||||
1735 | } | ||||
1736 | |||||
1737 | /// Produce a string describing the given constexpr call. | ||||
1738 | void CallStackFrame::describe(raw_ostream &Out) { | ||||
1739 | unsigned ArgIndex = 0; | ||||
1740 | bool IsMemberCall = isa<CXXMethodDecl>(Callee) && | ||||
1741 | !isa<CXXConstructorDecl>(Callee) && | ||||
1742 | cast<CXXMethodDecl>(Callee)->isInstance(); | ||||
1743 | |||||
1744 | if (!IsMemberCall) | ||||
1745 | Out << *Callee << '('; | ||||
1746 | |||||
1747 | if (This && IsMemberCall) { | ||||
1748 | APValue Val; | ||||
1749 | This->moveInto(Val); | ||||
1750 | Val.printPretty(Out, Info.Ctx, | ||||
1751 | This->Designator.MostDerivedType); | ||||
1752 | // FIXME: Add parens around Val if needed. | ||||
1753 | Out << "->" << *Callee << '('; | ||||
1754 | IsMemberCall = false; | ||||
1755 | } | ||||
1756 | |||||
1757 | for (FunctionDecl::param_const_iterator I = Callee->param_begin(), | ||||
1758 | E = Callee->param_end(); I != E; ++I, ++ArgIndex) { | ||||
1759 | if (ArgIndex > (unsigned)IsMemberCall) | ||||
1760 | Out << ", "; | ||||
1761 | |||||
1762 | const ParmVarDecl *Param = *I; | ||||
1763 | const APValue &Arg = Arguments[ArgIndex]; | ||||
1764 | Arg.printPretty(Out, Info.Ctx, Param->getType()); | ||||
1765 | |||||
1766 | if (ArgIndex == 0 && IsMemberCall) | ||||
1767 | Out << "->" << *Callee << '('; | ||||
1768 | } | ||||
1769 | |||||
1770 | Out << ')'; | ||||
1771 | } | ||||
1772 | |||||
1773 | /// Evaluate an expression to see if it had side-effects, and discard its | ||||
1774 | /// result. | ||||
1775 | /// \return \c true if the caller should keep evaluating. | ||||
1776 | static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { | ||||
1777 | APValue Scratch; | ||||
1778 | if (!Evaluate(Scratch, Info, E)) | ||||
1779 | // We don't need the value, but we might have skipped a side effect here. | ||||
1780 | return Info.noteSideEffect(); | ||||
1781 | return true; | ||||
1782 | } | ||||
1783 | |||||
1784 | /// Should this call expression be treated as a string literal? | ||||
1785 | static bool IsStringLiteralCall(const CallExpr *E) { | ||||
1786 | unsigned Builtin = E->getBuiltinCallee(); | ||||
1787 | return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || | ||||
1788 | Builtin == Builtin::BI__builtin___NSStringMakeConstantString); | ||||
1789 | } | ||||
1790 | |||||
1791 | static bool IsGlobalLValue(APValue::LValueBase B) { | ||||
1792 | // C++11 [expr.const]p3 An address constant expression is a prvalue core | ||||
1793 | // constant expression of pointer type that evaluates to... | ||||
1794 | |||||
1795 | // ... a null pointer value, or a prvalue core constant expression of type | ||||
1796 | // std::nullptr_t. | ||||
1797 | if (!B) return true; | ||||
1798 | |||||
1799 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||
1800 | // ... the address of an object with static storage duration, | ||||
1801 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
1802 | return VD->hasGlobalStorage(); | ||||
1803 | // ... the address of a function, | ||||
1804 | return isa<FunctionDecl>(D); | ||||
1805 | } | ||||
1806 | |||||
1807 | if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) | ||||
1808 | return true; | ||||
1809 | |||||
1810 | const Expr *E = B.get<const Expr*>(); | ||||
1811 | switch (E->getStmtClass()) { | ||||
1812 | default: | ||||
1813 | return false; | ||||
1814 | case Expr::CompoundLiteralExprClass: { | ||||
1815 | const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); | ||||
1816 | return CLE->isFileScope() && CLE->isLValue(); | ||||
1817 | } | ||||
1818 | case Expr::MaterializeTemporaryExprClass: | ||||
1819 | // A materialized temporary might have been lifetime-extended to static | ||||
1820 | // storage duration. | ||||
1821 | return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; | ||||
1822 | // A string literal has static storage duration. | ||||
1823 | case Expr::StringLiteralClass: | ||||
1824 | case Expr::PredefinedExprClass: | ||||
1825 | case Expr::ObjCStringLiteralClass: | ||||
1826 | case Expr::ObjCEncodeExprClass: | ||||
1827 | case Expr::CXXUuidofExprClass: | ||||
1828 | return true; | ||||
1829 | case Expr::ObjCBoxedExprClass: | ||||
1830 | return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); | ||||
1831 | case Expr::CallExprClass: | ||||
1832 | return IsStringLiteralCall(cast<CallExpr>(E)); | ||||
1833 | // For GCC compatibility, &&label has static storage duration. | ||||
1834 | case Expr::AddrLabelExprClass: | ||||
1835 | return true; | ||||
1836 | // A Block literal expression may be used as the initialization value for | ||||
1837 | // Block variables at global or local static scope. | ||||
1838 | case Expr::BlockExprClass: | ||||
1839 | return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); | ||||
1840 | case Expr::ImplicitValueInitExprClass: | ||||
1841 | // FIXME: | ||||
1842 | // We can never form an lvalue with an implicit value initialization as its | ||||
1843 | // base through expression evaluation, so these only appear in one case: the | ||||
1844 | // implicit variable declaration we invent when checking whether a constexpr | ||||
1845 | // constructor can produce a constant expression. We must assume that such | ||||
1846 | // an expression might be a global lvalue. | ||||
1847 | return true; | ||||
1848 | } | ||||
1849 | } | ||||
1850 | |||||
1851 | static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { | ||||
1852 | return LVal.Base.dyn_cast<const ValueDecl*>(); | ||||
1853 | } | ||||
1854 | |||||
1855 | static bool IsLiteralLValue(const LValue &Value) { | ||||
1856 | if (Value.getLValueCallIndex()) | ||||
1857 | return false; | ||||
1858 | const Expr *E = Value.Base.dyn_cast<const Expr*>(); | ||||
1859 | return E && !isa<MaterializeTemporaryExpr>(E); | ||||
1860 | } | ||||
1861 | |||||
1862 | static bool IsWeakLValue(const LValue &Value) { | ||||
1863 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||
1864 | return Decl && Decl->isWeak(); | ||||
1865 | } | ||||
1866 | |||||
1867 | static bool isZeroSized(const LValue &Value) { | ||||
1868 | const ValueDecl *Decl = GetLValueBaseDecl(Value); | ||||
1869 | if (Decl && isa<VarDecl>(Decl)) { | ||||
1870 | QualType Ty = Decl->getType(); | ||||
1871 | if (Ty->isArrayType()) | ||||
1872 | return Ty->isIncompleteType() || | ||||
1873 | Decl->getASTContext().getTypeSize(Ty) == 0; | ||||
1874 | } | ||||
1875 | return false; | ||||
1876 | } | ||||
1877 | |||||
1878 | static bool HasSameBase(const LValue &A, const LValue &B) { | ||||
1879 | if (!A.getLValueBase()) | ||||
1880 | return !B.getLValueBase(); | ||||
1881 | if (!B.getLValueBase()) | ||||
1882 | return false; | ||||
1883 | |||||
1884 | if (A.getLValueBase().getOpaqueValue() != | ||||
1885 | B.getLValueBase().getOpaqueValue()) { | ||||
1886 | const Decl *ADecl = GetLValueBaseDecl(A); | ||||
1887 | if (!ADecl) | ||||
1888 | return false; | ||||
1889 | const Decl *BDecl = GetLValueBaseDecl(B); | ||||
1890 | if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) | ||||
1891 | return false; | ||||
1892 | } | ||||
1893 | |||||
1894 | return IsGlobalLValue(A.getLValueBase()) || | ||||
1895 | (A.getLValueCallIndex() == B.getLValueCallIndex() && | ||||
1896 | A.getLValueVersion() == B.getLValueVersion()); | ||||
1897 | } | ||||
1898 | |||||
1899 | static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { | ||||
1900 | assert(Base && "no location for a null lvalue")((Base && "no location for a null lvalue") ? static_cast <void> (0) : __assert_fail ("Base && \"no location for a null lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1900, __PRETTY_FUNCTION__)); | ||||
1901 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||
1902 | if (VD) | ||||
1903 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
1904 | else if (const Expr *E = Base.dyn_cast<const Expr*>()) | ||||
1905 | Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); | ||||
1906 | else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { | ||||
1907 | // FIXME: Produce a note for dangling pointers too. | ||||
1908 | if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) | ||||
1909 | Info.Note((*Alloc)->AllocExpr->getExprLoc(), | ||||
1910 | diag::note_constexpr_dynamic_alloc_here); | ||||
1911 | } | ||||
1912 | // We have no information to show for a typeid(T) object. | ||||
1913 | } | ||||
1914 | |||||
1915 | enum class CheckEvaluationResultKind { | ||||
1916 | ConstantExpression, | ||||
1917 | FullyInitialized, | ||||
1918 | }; | ||||
1919 | |||||
1920 | /// Materialized temporaries that we've already checked to determine if they're | ||||
1921 | /// initializsed by a constant expression. | ||||
1922 | using CheckedTemporaries = | ||||
1923 | llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; | ||||
1924 | |||||
1925 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||
1926 | EvalInfo &Info, SourceLocation DiagLoc, | ||||
1927 | QualType Type, const APValue &Value, | ||||
1928 | Expr::ConstExprUsage Usage, | ||||
1929 | SourceLocation SubobjectLoc, | ||||
1930 | CheckedTemporaries &CheckedTemps); | ||||
1931 | |||||
1932 | /// Check that this reference or pointer core constant expression is a valid | ||||
1933 | /// value for an address or reference constant expression. Return true if we | ||||
1934 | /// can fold this expression, whether or not it's a constant expression. | ||||
1935 | static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, | ||||
1936 | QualType Type, const LValue &LVal, | ||||
1937 | Expr::ConstExprUsage Usage, | ||||
1938 | CheckedTemporaries &CheckedTemps) { | ||||
1939 | bool IsReferenceType = Type->isReferenceType(); | ||||
1940 | |||||
1941 | APValue::LValueBase Base = LVal.getLValueBase(); | ||||
1942 | const SubobjectDesignator &Designator = LVal.getLValueDesignator(); | ||||
1943 | |||||
1944 | // Check that the object is a global. Note that the fake 'this' object we | ||||
1945 | // manufacture when checking potential constant expressions is conservatively | ||||
1946 | // assumed to be global here. | ||||
1947 | if (!IsGlobalLValue(Base)) { | ||||
1948 | if (Info.getLangOpts().CPlusPlus11) { | ||||
1949 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||
1950 | Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) | ||||
1951 | << IsReferenceType << !Designator.Entries.empty() | ||||
1952 | << !!VD << VD; | ||||
1953 | NoteLValueLocation(Info, Base); | ||||
1954 | } else { | ||||
1955 | Info.FFDiag(Loc); | ||||
1956 | } | ||||
1957 | // Don't allow references to temporaries to escape. | ||||
1958 | return false; | ||||
1959 | } | ||||
1960 | assert((Info.checkingPotentialConstantExpression() ||(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)) | ||||
1961 | LVal.getLValueCallIndex() == 0) &&(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)) | ||||
1962 | "have call index for global lvalue")(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex () == 0) && "have call index for global lvalue") ? static_cast <void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 1962, __PRETTY_FUNCTION__)); | ||||
1963 | |||||
1964 | if (Base.is<DynamicAllocLValue>()) { | ||||
1965 | Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) | ||||
1966 | << IsReferenceType << !Designator.Entries.empty(); | ||||
1967 | NoteLValueLocation(Info, Base); | ||||
1968 | return false; | ||||
1969 | } | ||||
1970 | |||||
1971 | if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { | ||||
1972 | if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { | ||||
1973 | // Check if this is a thread-local variable. | ||||
1974 | if (Var->getTLSKind()) | ||||
1975 | // FIXME: Diagnostic! | ||||
1976 | return false; | ||||
1977 | |||||
1978 | // A dllimport variable never acts like a constant. | ||||
1979 | if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) | ||||
1980 | // FIXME: Diagnostic! | ||||
1981 | return false; | ||||
1982 | } | ||||
1983 | if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { | ||||
1984 | // __declspec(dllimport) must be handled very carefully: | ||||
1985 | // We must never initialize an expression with the thunk in C++. | ||||
1986 | // Doing otherwise would allow the same id-expression to yield | ||||
1987 | // different addresses for the same function in different translation | ||||
1988 | // units. However, this means that we must dynamically initialize the | ||||
1989 | // expression with the contents of the import address table at runtime. | ||||
1990 | // | ||||
1991 | // The C language has no notion of ODR; furthermore, it has no notion of | ||||
1992 | // dynamic initialization. This means that we are permitted to | ||||
1993 | // perform initialization with the address of the thunk. | ||||
1994 | if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && | ||||
1995 | FD->hasAttr<DLLImportAttr>()) | ||||
1996 | // FIXME: Diagnostic! | ||||
1997 | return false; | ||||
1998 | } | ||||
1999 | } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( | ||||
2000 | Base.dyn_cast<const Expr *>())) { | ||||
2001 | if (CheckedTemps.insert(MTE).second) { | ||||
2002 | QualType TempType = getType(Base); | ||||
2003 | if (TempType.isDestructedType()) { | ||||
2004 | Info.FFDiag(MTE->getExprLoc(), | ||||
2005 | diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) | ||||
2006 | << TempType; | ||||
2007 | return false; | ||||
2008 | } | ||||
2009 | |||||
2010 | APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false); | ||||
2011 | assert(V && "evasluation result refers to uninitialised temporary")((V && "evasluation result refers to uninitialised temporary" ) ? static_cast<void> (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2011, __PRETTY_FUNCTION__)); | ||||
2012 | if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||
2013 | Info, MTE->getExprLoc(), TempType, *V, | ||||
2014 | Usage, SourceLocation(), CheckedTemps)) | ||||
2015 | return false; | ||||
2016 | } | ||||
2017 | } | ||||
2018 | |||||
2019 | // Allow address constant expressions to be past-the-end pointers. This is | ||||
2020 | // an extension: the standard requires them to point to an object. | ||||
2021 | if (!IsReferenceType) | ||||
2022 | return true; | ||||
2023 | |||||
2024 | // A reference constant expression must refer to an object. | ||||
2025 | if (!Base) { | ||||
2026 | // FIXME: diagnostic | ||||
2027 | Info.CCEDiag(Loc); | ||||
2028 | return true; | ||||
2029 | } | ||||
2030 | |||||
2031 | // Does this refer one past the end of some object? | ||||
2032 | if (!Designator.Invalid && Designator.isOnePastTheEnd()) { | ||||
2033 | const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); | ||||
2034 | Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) | ||||
2035 | << !Designator.Entries.empty() << !!VD << VD; | ||||
2036 | NoteLValueLocation(Info, Base); | ||||
2037 | } | ||||
2038 | |||||
2039 | return true; | ||||
2040 | } | ||||
2041 | |||||
2042 | /// Member pointers are constant expressions unless they point to a | ||||
2043 | /// non-virtual dllimport member function. | ||||
2044 | static bool CheckMemberPointerConstantExpression(EvalInfo &Info, | ||||
2045 | SourceLocation Loc, | ||||
2046 | QualType Type, | ||||
2047 | const APValue &Value, | ||||
2048 | Expr::ConstExprUsage Usage) { | ||||
2049 | const ValueDecl *Member = Value.getMemberPointerDecl(); | ||||
2050 | const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); | ||||
2051 | if (!FD) | ||||
2052 | return true; | ||||
2053 | return Usage == Expr::EvaluateForMangling || FD->isVirtual() || | ||||
2054 | !FD->hasAttr<DLLImportAttr>(); | ||||
2055 | } | ||||
2056 | |||||
2057 | /// Check that this core constant expression is of literal type, and if not, | ||||
2058 | /// produce an appropriate diagnostic. | ||||
2059 | static bool CheckLiteralType(EvalInfo &Info, const Expr *E, | ||||
2060 | const LValue *This = nullptr) { | ||||
2061 | if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) | ||||
2062 | return true; | ||||
2063 | |||||
2064 | // C++1y: A constant initializer for an object o [...] may also invoke | ||||
2065 | // constexpr constructors for o and its subobjects even if those objects | ||||
2066 | // are of non-literal class types. | ||||
2067 | // | ||||
2068 | // C++11 missed this detail for aggregates, so classes like this: | ||||
2069 | // struct foo_t { union { int i; volatile int j; } u; }; | ||||
2070 | // are not (obviously) initializable like so: | ||||
2071 | // __attribute__((__require_constant_initialization__)) | ||||
2072 | // static const foo_t x = {{0}}; | ||||
2073 | // because "i" is a subobject with non-literal initialization (due to the | ||||
2074 | // volatile member of the union). See: | ||||
2075 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 | ||||
2076 | // Therefore, we use the C++1y behavior. | ||||
2077 | if (This && Info.EvaluatingDecl == This->getLValueBase()) | ||||
2078 | return true; | ||||
2079 | |||||
2080 | // Prvalue constant expressions must be of literal types. | ||||
2081 | if (Info.getLangOpts().CPlusPlus11) | ||||
2082 | Info.FFDiag(E, diag::note_constexpr_nonliteral) | ||||
2083 | << E->getType(); | ||||
2084 | else | ||||
2085 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2086 | return false; | ||||
2087 | } | ||||
2088 | |||||
2089 | static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, | ||||
2090 | EvalInfo &Info, SourceLocation DiagLoc, | ||||
2091 | QualType Type, const APValue &Value, | ||||
2092 | Expr::ConstExprUsage Usage, | ||||
2093 | SourceLocation SubobjectLoc, | ||||
2094 | CheckedTemporaries &CheckedTemps) { | ||||
2095 | if (!Value.hasValue()) { | ||||
2096 | Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) | ||||
2097 | << true << Type; | ||||
2098 | if (SubobjectLoc.isValid()) | ||||
2099 | Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); | ||||
2100 | return false; | ||||
2101 | } | ||||
2102 | |||||
2103 | // We allow _Atomic(T) to be initialized from anything that T can be | ||||
2104 | // initialized from. | ||||
2105 | if (const AtomicType *AT = Type->getAs<AtomicType>()) | ||||
2106 | Type = AT->getValueType(); | ||||
2107 | |||||
2108 | // Core issue 1454: For a literal constant expression of array or class type, | ||||
2109 | // each subobject of its value shall have been initialized by a constant | ||||
2110 | // expression. | ||||
2111 | if (Value.isArray()) { | ||||
2112 | QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); | ||||
2113 | for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { | ||||
2114 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||
2115 | Value.getArrayInitializedElt(I), Usage, | ||||
2116 | SubobjectLoc, CheckedTemps)) | ||||
2117 | return false; | ||||
2118 | } | ||||
2119 | if (!Value.hasArrayFiller()) | ||||
2120 | return true; | ||||
2121 | return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, | ||||
2122 | Value.getArrayFiller(), Usage, SubobjectLoc, | ||||
2123 | CheckedTemps); | ||||
2124 | } | ||||
2125 | if (Value.isUnion() && Value.getUnionField()) { | ||||
2126 | return CheckEvaluationResult( | ||||
2127 | CERK, Info, DiagLoc, Value.getUnionField()->getType(), | ||||
2128 | Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), | ||||
2129 | CheckedTemps); | ||||
2130 | } | ||||
2131 | if (Value.isStruct()) { | ||||
2132 | RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); | ||||
2133 | if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
2134 | unsigned BaseIndex = 0; | ||||
2135 | for (const CXXBaseSpecifier &BS : CD->bases()) { | ||||
2136 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), | ||||
2137 | Value.getStructBase(BaseIndex), Usage, | ||||
2138 | BS.getBeginLoc(), CheckedTemps)) | ||||
2139 | return false; | ||||
2140 | ++BaseIndex; | ||||
2141 | } | ||||
2142 | } | ||||
2143 | for (const auto *I : RD->fields()) { | ||||
2144 | if (I->isUnnamedBitfield()) | ||||
2145 | continue; | ||||
2146 | |||||
2147 | if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), | ||||
2148 | Value.getStructField(I->getFieldIndex()), | ||||
2149 | Usage, I->getLocation(), CheckedTemps)) | ||||
2150 | return false; | ||||
2151 | } | ||||
2152 | } | ||||
2153 | |||||
2154 | if (Value.isLValue() && | ||||
2155 | CERK == CheckEvaluationResultKind::ConstantExpression) { | ||||
2156 | LValue LVal; | ||||
2157 | LVal.setFrom(Info.Ctx, Value); | ||||
2158 | return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, | ||||
2159 | CheckedTemps); | ||||
2160 | } | ||||
2161 | |||||
2162 | if (Value.isMemberPointer() && | ||||
2163 | CERK == CheckEvaluationResultKind::ConstantExpression) | ||||
2164 | return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); | ||||
2165 | |||||
2166 | // Everything else is fine. | ||||
2167 | return true; | ||||
2168 | } | ||||
2169 | |||||
2170 | /// Check that this core constant expression value is a valid value for a | ||||
2171 | /// constant expression. If not, report an appropriate diagnostic. Does not | ||||
2172 | /// check that the expression is of literal type. | ||||
2173 | static bool | ||||
2174 | CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, | ||||
2175 | const APValue &Value, | ||||
2176 | Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { | ||||
2177 | CheckedTemporaries CheckedTemps; | ||||
2178 | return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, | ||||
2179 | Info, DiagLoc, Type, Value, Usage, | ||||
2180 | SourceLocation(), CheckedTemps); | ||||
2181 | } | ||||
2182 | |||||
2183 | /// Check that this evaluated value is fully-initialized and can be loaded by | ||||
2184 | /// an lvalue-to-rvalue conversion. | ||||
2185 | static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, | ||||
2186 | QualType Type, const APValue &Value) { | ||||
2187 | CheckedTemporaries CheckedTemps; | ||||
2188 | return CheckEvaluationResult( | ||||
2189 | CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, | ||||
2190 | Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); | ||||
2191 | } | ||||
2192 | |||||
2193 | /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless | ||||
2194 | /// "the allocated storage is deallocated within the evaluation". | ||||
2195 | static bool CheckMemoryLeaks(EvalInfo &Info) { | ||||
2196 | if (!Info.HeapAllocs.empty()) { | ||||
2197 | // We can still fold to a constant despite a compile-time memory leak, | ||||
2198 | // so long as the heap allocation isn't referenced in the result (we check | ||||
2199 | // that in CheckConstantExpression). | ||||
2200 | Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, | ||||
2201 | diag::note_constexpr_memory_leak) | ||||
2202 | << unsigned(Info.HeapAllocs.size() - 1); | ||||
2203 | } | ||||
2204 | return true; | ||||
2205 | } | ||||
2206 | |||||
2207 | static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { | ||||
2208 | // A null base expression indicates a null pointer. These are always | ||||
2209 | // evaluatable, and they are false unless the offset is zero. | ||||
2210 | if (!Value.getLValueBase()) { | ||||
2211 | Result = !Value.getLValueOffset().isZero(); | ||||
2212 | return true; | ||||
2213 | } | ||||
2214 | |||||
2215 | // We have a non-null base. These are generally known to be true, but if it's | ||||
2216 | // a weak declaration it can be null at runtime. | ||||
2217 | Result = true; | ||||
2218 | const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); | ||||
2219 | return !Decl || !Decl->isWeak(); | ||||
2220 | } | ||||
2221 | |||||
2222 | static bool HandleConversionToBool(const APValue &Val, bool &Result) { | ||||
2223 | switch (Val.getKind()) { | ||||
2224 | case APValue::None: | ||||
2225 | case APValue::Indeterminate: | ||||
2226 | return false; | ||||
2227 | case APValue::Int: | ||||
2228 | Result = Val.getInt().getBoolValue(); | ||||
2229 | return true; | ||||
2230 | case APValue::FixedPoint: | ||||
2231 | Result = Val.getFixedPoint().getBoolValue(); | ||||
2232 | return true; | ||||
2233 | case APValue::Float: | ||||
2234 | Result = !Val.getFloat().isZero(); | ||||
2235 | return true; | ||||
2236 | case APValue::ComplexInt: | ||||
2237 | Result = Val.getComplexIntReal().getBoolValue() || | ||||
2238 | Val.getComplexIntImag().getBoolValue(); | ||||
2239 | return true; | ||||
2240 | case APValue::ComplexFloat: | ||||
2241 | Result = !Val.getComplexFloatReal().isZero() || | ||||
2242 | !Val.getComplexFloatImag().isZero(); | ||||
2243 | return true; | ||||
2244 | case APValue::LValue: | ||||
2245 | return EvalPointerValueAsBool(Val, Result); | ||||
2246 | case APValue::MemberPointer: | ||||
2247 | Result = Val.getMemberPointerDecl(); | ||||
2248 | return true; | ||||
2249 | case APValue::Vector: | ||||
2250 | case APValue::Array: | ||||
2251 | case APValue::Struct: | ||||
2252 | case APValue::Union: | ||||
2253 | case APValue::AddrLabelDiff: | ||||
2254 | return false; | ||||
2255 | } | ||||
2256 | |||||
2257 | llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2257); | ||||
2258 | } | ||||
2259 | |||||
2260 | static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, | ||||
2261 | EvalInfo &Info) { | ||||
2262 | assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition")((E->isRValue() && "missing lvalue-to-rvalue conv in bool condition" ) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && \"missing lvalue-to-rvalue conv in bool condition\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2262, __PRETTY_FUNCTION__)); | ||||
2263 | APValue Val; | ||||
2264 | if (!Evaluate(Val, Info, E)) | ||||
2265 | return false; | ||||
2266 | return HandleConversionToBool(Val, Result); | ||||
2267 | } | ||||
2268 | |||||
2269 | template<typename T> | ||||
2270 | static bool HandleOverflow(EvalInfo &Info, const Expr *E, | ||||
2271 | const T &SrcValue, QualType DestType) { | ||||
2272 | Info.CCEDiag(E, diag::note_constexpr_overflow) | ||||
2273 | << SrcValue << DestType; | ||||
2274 | return Info.noteUndefinedBehavior(); | ||||
2275 | } | ||||
2276 | |||||
2277 | static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, | ||||
2278 | QualType SrcType, const APFloat &Value, | ||||
2279 | QualType DestType, APSInt &Result) { | ||||
2280 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||
2281 | // Determine whether we are converting to unsigned or signed. | ||||
2282 | bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); | ||||
2283 | |||||
2284 | Result = APSInt(DestWidth, !DestSigned); | ||||
2285 | bool ignored; | ||||
2286 | if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) | ||||
2287 | & APFloat::opInvalidOp) | ||||
2288 | return HandleOverflow(Info, E, Value, DestType); | ||||
2289 | return true; | ||||
2290 | } | ||||
2291 | |||||
2292 | static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, | ||||
2293 | QualType SrcType, QualType DestType, | ||||
2294 | APFloat &Result) { | ||||
2295 | APFloat Value = Result; | ||||
2296 | bool ignored; | ||||
2297 | Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), | ||||
2298 | APFloat::rmNearestTiesToEven, &ignored); | ||||
2299 | return true; | ||||
2300 | } | ||||
2301 | |||||
2302 | static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, | ||||
2303 | QualType DestType, QualType SrcType, | ||||
2304 | const APSInt &Value) { | ||||
2305 | unsigned DestWidth = Info.Ctx.getIntWidth(DestType); | ||||
2306 | // Figure out if this is a truncate, extend or noop cast. | ||||
2307 | // If the input is signed, do a sign extend, noop, or truncate. | ||||
2308 | APSInt Result = Value.extOrTrunc(DestWidth); | ||||
2309 | Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); | ||||
2310 | if (DestType->isBooleanType()) | ||||
2311 | Result = Value.getBoolValue(); | ||||
2312 | return Result; | ||||
2313 | } | ||||
2314 | |||||
2315 | static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, | ||||
2316 | QualType SrcType, const APSInt &Value, | ||||
2317 | QualType DestType, APFloat &Result) { | ||||
2318 | Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); | ||||
2319 | Result.convertFromAPInt(Value, Value.isSigned(), | ||||
2320 | APFloat::rmNearestTiesToEven); | ||||
2321 | return true; | ||||
2322 | } | ||||
2323 | |||||
2324 | static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, | ||||
2325 | APValue &Value, const FieldDecl *FD) { | ||||
2326 | assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")((FD->isBitField() && "truncateBitfieldValue on non-bitfield" ) ? static_cast<void> (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2326, __PRETTY_FUNCTION__)); | ||||
2327 | |||||
2328 | if (!Value.isInt()) { | ||||
2329 | // Trying to store a pointer-cast-to-integer into a bitfield. | ||||
2330 | // FIXME: In this case, we should provide the diagnostic for casting | ||||
2331 | // a pointer to an integer. | ||||
2332 | assert(Value.isLValue() && "integral value neither int nor lvalue?")((Value.isLValue() && "integral value neither int nor lvalue?" ) ? static_cast<void> (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2332, __PRETTY_FUNCTION__)); | ||||
2333 | Info.FFDiag(E); | ||||
2334 | return false; | ||||
2335 | } | ||||
2336 | |||||
2337 | APSInt &Int = Value.getInt(); | ||||
2338 | unsigned OldBitWidth = Int.getBitWidth(); | ||||
2339 | unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); | ||||
2340 | if (NewBitWidth < OldBitWidth) | ||||
2341 | Int = Int.trunc(NewBitWidth).extend(OldBitWidth); | ||||
2342 | return true; | ||||
2343 | } | ||||
2344 | |||||
2345 | static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, | ||||
2346 | llvm::APInt &Res) { | ||||
2347 | APValue SVal; | ||||
2348 | if (!Evaluate(SVal, Info, E)) | ||||
2349 | return false; | ||||
2350 | if (SVal.isInt()) { | ||||
2351 | Res = SVal.getInt(); | ||||
2352 | return true; | ||||
2353 | } | ||||
2354 | if (SVal.isFloat()) { | ||||
2355 | Res = SVal.getFloat().bitcastToAPInt(); | ||||
2356 | return true; | ||||
2357 | } | ||||
2358 | if (SVal.isVector()) { | ||||
2359 | QualType VecTy = E->getType(); | ||||
2360 | unsigned VecSize = Info.Ctx.getTypeSize(VecTy); | ||||
2361 | QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); | ||||
2362 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||
2363 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||
2364 | Res = llvm::APInt::getNullValue(VecSize); | ||||
2365 | for (unsigned i = 0; i < SVal.getVectorLength(); i++) { | ||||
2366 | APValue &Elt = SVal.getVectorElt(i); | ||||
2367 | llvm::APInt EltAsInt; | ||||
2368 | if (Elt.isInt()) { | ||||
2369 | EltAsInt = Elt.getInt(); | ||||
2370 | } else if (Elt.isFloat()) { | ||||
2371 | EltAsInt = Elt.getFloat().bitcastToAPInt(); | ||||
2372 | } else { | ||||
2373 | // Don't try to handle vectors of anything other than int or float | ||||
2374 | // (not sure if it's possible to hit this case). | ||||
2375 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2376 | return false; | ||||
2377 | } | ||||
2378 | unsigned BaseEltSize = EltAsInt.getBitWidth(); | ||||
2379 | if (BigEndian) | ||||
2380 | Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); | ||||
2381 | else | ||||
2382 | Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); | ||||
2383 | } | ||||
2384 | return true; | ||||
2385 | } | ||||
2386 | // Give up if the input isn't an int, float, or vector. For example, we | ||||
2387 | // reject "(v4i16)(intptr_t)&a". | ||||
2388 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2389 | return false; | ||||
2390 | } | ||||
2391 | |||||
2392 | /// Perform the given integer operation, which is known to need at most BitWidth | ||||
2393 | /// bits, and check for overflow in the original type (if that type was not an | ||||
2394 | /// unsigned type). | ||||
2395 | template<typename Operation> | ||||
2396 | static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, | ||||
2397 | const APSInt &LHS, const APSInt &RHS, | ||||
2398 | unsigned BitWidth, Operation Op, | ||||
2399 | APSInt &Result) { | ||||
2400 | if (LHS.isUnsigned()) { | ||||
2401 | Result = Op(LHS, RHS); | ||||
2402 | return true; | ||||
2403 | } | ||||
2404 | |||||
2405 | APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); | ||||
2406 | Result = Value.trunc(LHS.getBitWidth()); | ||||
2407 | if (Result.extend(BitWidth) != Value) { | ||||
2408 | if (Info.checkingForUndefinedBehavior()) | ||||
2409 | Info.Ctx.getDiagnostics().Report(E->getExprLoc(), | ||||
2410 | diag::warn_integer_constant_overflow) | ||||
2411 | << Result.toString(10) << E->getType(); | ||||
2412 | else | ||||
2413 | return HandleOverflow(Info, E, Value, E->getType()); | ||||
2414 | } | ||||
2415 | return true; | ||||
2416 | } | ||||
2417 | |||||
2418 | /// Perform the given binary integer operation. | ||||
2419 | static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, | ||||
2420 | BinaryOperatorKind Opcode, APSInt RHS, | ||||
2421 | APSInt &Result) { | ||||
2422 | switch (Opcode) { | ||||
2423 | default: | ||||
2424 | Info.FFDiag(E); | ||||
2425 | return false; | ||||
2426 | case BO_Mul: | ||||
2427 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, | ||||
2428 | std::multiplies<APSInt>(), Result); | ||||
2429 | case BO_Add: | ||||
2430 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||
2431 | std::plus<APSInt>(), Result); | ||||
2432 | case BO_Sub: | ||||
2433 | return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, | ||||
2434 | std::minus<APSInt>(), Result); | ||||
2435 | case BO_And: Result = LHS & RHS; return true; | ||||
2436 | case BO_Xor: Result = LHS ^ RHS; return true; | ||||
2437 | case BO_Or: Result = LHS | RHS; return true; | ||||
2438 | case BO_Div: | ||||
2439 | case BO_Rem: | ||||
2440 | if (RHS == 0) { | ||||
2441 | Info.FFDiag(E, diag::note_expr_divide_by_zero); | ||||
2442 | return false; | ||||
2443 | } | ||||
2444 | Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); | ||||
2445 | // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports | ||||
2446 | // this operation and gives the two's complement result. | ||||
2447 | if (RHS.isNegative() && RHS.isAllOnesValue() && | ||||
2448 | LHS.isSigned() && LHS.isMinSignedValue()) | ||||
2449 | return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), | ||||
2450 | E->getType()); | ||||
2451 | return true; | ||||
2452 | case BO_Shl: { | ||||
2453 | if (Info.getLangOpts().OpenCL) | ||||
2454 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||
2455 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||
2456 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||
2457 | RHS.isUnsigned()); | ||||
2458 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||
2459 | // During constant-folding, a negative shift is an opposite shift. Such | ||||
2460 | // a shift is not a constant expression. | ||||
2461 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||
2462 | RHS = -RHS; | ||||
2463 | goto shift_right; | ||||
2464 | } | ||||
2465 | shift_left: | ||||
2466 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of | ||||
2467 | // the shifted type. | ||||
2468 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||
2469 | if (SA != RHS) { | ||||
2470 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||
2471 | << RHS << E->getType() << LHS.getBitWidth(); | ||||
2472 | } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { | ||||
2473 | // C++11 [expr.shift]p2: A signed left shift must have a non-negative | ||||
2474 | // operand, and must not overflow the corresponding unsigned type. | ||||
2475 | // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to | ||||
2476 | // E1 x 2^E2 module 2^N. | ||||
2477 | if (LHS.isNegative()) | ||||
2478 | Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; | ||||
2479 | else if (LHS.countLeadingZeros() < SA) | ||||
2480 | Info.CCEDiag(E, diag::note_constexpr_lshift_discards); | ||||
2481 | } | ||||
2482 | Result = LHS << SA; | ||||
2483 | return true; | ||||
2484 | } | ||||
2485 | case BO_Shr: { | ||||
2486 | if (Info.getLangOpts().OpenCL) | ||||
2487 | // OpenCL 6.3j: shift values are effectively % word size of LHS. | ||||
2488 | RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), | ||||
2489 | static_cast<uint64_t>(LHS.getBitWidth() - 1)), | ||||
2490 | RHS.isUnsigned()); | ||||
2491 | else if (RHS.isSigned() && RHS.isNegative()) { | ||||
2492 | // During constant-folding, a negative shift is an opposite shift. Such a | ||||
2493 | // shift is not a constant expression. | ||||
2494 | Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; | ||||
2495 | RHS = -RHS; | ||||
2496 | goto shift_left; | ||||
2497 | } | ||||
2498 | shift_right: | ||||
2499 | // C++11 [expr.shift]p1: Shift width must be less than the bit width of the | ||||
2500 | // shifted type. | ||||
2501 | unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); | ||||
2502 | if (SA != RHS) | ||||
2503 | Info.CCEDiag(E, diag::note_constexpr_large_shift) | ||||
2504 | << RHS << E->getType() << LHS.getBitWidth(); | ||||
2505 | Result = LHS >> SA; | ||||
2506 | return true; | ||||
2507 | } | ||||
2508 | |||||
2509 | case BO_LT: Result = LHS < RHS; return true; | ||||
2510 | case BO_GT: Result = LHS > RHS; return true; | ||||
2511 | case BO_LE: Result = LHS <= RHS; return true; | ||||
2512 | case BO_GE: Result = LHS >= RHS; return true; | ||||
2513 | case BO_EQ: Result = LHS == RHS; return true; | ||||
2514 | case BO_NE: Result = LHS != RHS; return true; | ||||
2515 | case BO_Cmp: | ||||
2516 | llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2516); | ||||
2517 | } | ||||
2518 | } | ||||
2519 | |||||
2520 | /// Perform the given binary floating-point operation, in-place, on LHS. | ||||
2521 | static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, | ||||
2522 | APFloat &LHS, BinaryOperatorKind Opcode, | ||||
2523 | const APFloat &RHS) { | ||||
2524 | switch (Opcode) { | ||||
2525 | default: | ||||
2526 | Info.FFDiag(E); | ||||
2527 | return false; | ||||
2528 | case BO_Mul: | ||||
2529 | LHS.multiply(RHS, APFloat::rmNearestTiesToEven); | ||||
2530 | break; | ||||
2531 | case BO_Add: | ||||
2532 | LHS.add(RHS, APFloat::rmNearestTiesToEven); | ||||
2533 | break; | ||||
2534 | case BO_Sub: | ||||
2535 | LHS.subtract(RHS, APFloat::rmNearestTiesToEven); | ||||
2536 | break; | ||||
2537 | case BO_Div: | ||||
2538 | // [expr.mul]p4: | ||||
2539 | // If the second operand of / or % is zero the behavior is undefined. | ||||
2540 | if (RHS.isZero()) | ||||
2541 | Info.CCEDiag(E, diag::note_expr_divide_by_zero); | ||||
2542 | LHS.divide(RHS, APFloat::rmNearestTiesToEven); | ||||
2543 | break; | ||||
2544 | } | ||||
2545 | |||||
2546 | // [expr.pre]p4: | ||||
2547 | // If during the evaluation of an expression, the result is not | ||||
2548 | // mathematically defined [...], the behavior is undefined. | ||||
2549 | // FIXME: C++ rules require us to not conform to IEEE 754 here. | ||||
2550 | if (LHS.isNaN()) { | ||||
2551 | Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); | ||||
2552 | return Info.noteUndefinedBehavior(); | ||||
2553 | } | ||||
2554 | return true; | ||||
2555 | } | ||||
2556 | |||||
2557 | /// Cast an lvalue referring to a base subobject to a derived class, by | ||||
2558 | /// truncating the lvalue's path to the given length. | ||||
2559 | static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||
2560 | const RecordDecl *TruncatedType, | ||||
2561 | unsigned TruncatedElements) { | ||||
2562 | SubobjectDesignator &D = Result.Designator; | ||||
2563 | |||||
2564 | // Check we actually point to a derived class object. | ||||
2565 | if (TruncatedElements == D.Entries.size()) | ||||
2566 | return true; | ||||
2567 | assert(TruncatedElements >= D.MostDerivedPathLength &&((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class" ) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2568, __PRETTY_FUNCTION__)) | ||||
2568 | "not casting to a derived class")((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class" ) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2568, __PRETTY_FUNCTION__)); | ||||
2569 | if (!Result.checkSubobject(Info, E, CSK_Derived)) | ||||
2570 | return false; | ||||
2571 | |||||
2572 | // Truncate the path to the subobject, and remove any derived-to-base offsets. | ||||
2573 | const RecordDecl *RD = TruncatedType; | ||||
2574 | for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { | ||||
2575 | if (RD->isInvalidDecl()) return false; | ||||
2576 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
2577 | const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); | ||||
2578 | if (isVirtualBaseClass(D.Entries[I])) | ||||
2579 | Result.Offset -= Layout.getVBaseClassOffset(Base); | ||||
2580 | else | ||||
2581 | Result.Offset -= Layout.getBaseClassOffset(Base); | ||||
2582 | RD = Base; | ||||
2583 | } | ||||
2584 | D.Entries.resize(TruncatedElements); | ||||
2585 | return true; | ||||
2586 | } | ||||
2587 | |||||
2588 | static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||
2589 | const CXXRecordDecl *Derived, | ||||
2590 | const CXXRecordDecl *Base, | ||||
2591 | const ASTRecordLayout *RL = nullptr) { | ||||
2592 | if (!RL) { | ||||
2593 | if (Derived->isInvalidDecl()) return false; | ||||
2594 | RL = &Info.Ctx.getASTRecordLayout(Derived); | ||||
2595 | } | ||||
2596 | |||||
2597 | Obj.getLValueOffset() += RL->getBaseClassOffset(Base); | ||||
2598 | Obj.addDecl(Info, E, Base, /*Virtual*/ false); | ||||
2599 | return true; | ||||
2600 | } | ||||
2601 | |||||
2602 | static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, | ||||
2603 | const CXXRecordDecl *DerivedDecl, | ||||
2604 | const CXXBaseSpecifier *Base) { | ||||
2605 | const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); | ||||
2606 | |||||
2607 | if (!Base->isVirtual()) | ||||
2608 | return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); | ||||
2609 | |||||
2610 | SubobjectDesignator &D = Obj.Designator; | ||||
2611 | if (D.Invalid) | ||||
2612 | return false; | ||||
2613 | |||||
2614 | // Extract most-derived object and corresponding type. | ||||
2615 | DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); | ||||
2616 | if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) | ||||
2617 | return false; | ||||
2618 | |||||
2619 | // Find the virtual base class. | ||||
2620 | if (DerivedDecl->isInvalidDecl()) return false; | ||||
2621 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); | ||||
2622 | Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); | ||||
2623 | Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); | ||||
2624 | return true; | ||||
2625 | } | ||||
2626 | |||||
2627 | static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, | ||||
2628 | QualType Type, LValue &Result) { | ||||
2629 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
2630 | PathE = E->path_end(); | ||||
2631 | PathI != PathE; ++PathI) { | ||||
2632 | if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), | ||||
2633 | *PathI)) | ||||
2634 | return false; | ||||
2635 | Type = (*PathI)->getType(); | ||||
2636 | } | ||||
2637 | return true; | ||||
2638 | } | ||||
2639 | |||||
2640 | /// Cast an lvalue referring to a derived class to a known base subobject. | ||||
2641 | static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, | ||||
2642 | const CXXRecordDecl *DerivedRD, | ||||
2643 | const CXXRecordDecl *BaseRD) { | ||||
2644 | CXXBasePaths Paths(/*FindAmbiguities=*/false, | ||||
2645 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||
2646 | if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) | ||||
2647 | 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!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2647); | ||||
2648 | |||||
2649 | for (CXXBasePathElement &Elem : Paths.front()) | ||||
2650 | if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) | ||||
2651 | return false; | ||||
2652 | return true; | ||||
2653 | } | ||||
2654 | |||||
2655 | /// Update LVal to refer to the given field, which must be a member of the type | ||||
2656 | /// currently described by LVal. | ||||
2657 | static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, | ||||
2658 | const FieldDecl *FD, | ||||
2659 | const ASTRecordLayout *RL = nullptr) { | ||||
2660 | if (!RL) { | ||||
2661 | if (FD->getParent()->isInvalidDecl()) return false; | ||||
2662 | RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); | ||||
2663 | } | ||||
2664 | |||||
2665 | unsigned I = FD->getFieldIndex(); | ||||
2666 | LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); | ||||
2667 | LVal.addDecl(Info, E, FD); | ||||
2668 | return true; | ||||
2669 | } | ||||
2670 | |||||
2671 | /// Update LVal to refer to the given indirect field. | ||||
2672 | static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, | ||||
2673 | LValue &LVal, | ||||
2674 | const IndirectFieldDecl *IFD) { | ||||
2675 | for (const auto *C : IFD->chain()) | ||||
2676 | if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) | ||||
2677 | return false; | ||||
2678 | return true; | ||||
2679 | } | ||||
2680 | |||||
2681 | /// Get the size of the given type in char units. | ||||
2682 | static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, | ||||
2683 | QualType Type, CharUnits &Size) { | ||||
2684 | // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc | ||||
2685 | // extension. | ||||
2686 | if (Type->isVoidType() || Type->isFunctionType()) { | ||||
2687 | Size = CharUnits::One(); | ||||
2688 | return true; | ||||
2689 | } | ||||
2690 | |||||
2691 | if (Type->isDependentType()) { | ||||
2692 | Info.FFDiag(Loc); | ||||
2693 | return false; | ||||
2694 | } | ||||
2695 | |||||
2696 | if (!Type->isConstantSizeType()) { | ||||
2697 | // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. | ||||
2698 | // FIXME: Better diagnostic. | ||||
2699 | Info.FFDiag(Loc); | ||||
2700 | return false; | ||||
2701 | } | ||||
2702 | |||||
2703 | Size = Info.Ctx.getTypeSizeInChars(Type); | ||||
2704 | return true; | ||||
2705 | } | ||||
2706 | |||||
2707 | /// Update a pointer value to model pointer arithmetic. | ||||
2708 | /// \param Info - Information about the ongoing evaluation. | ||||
2709 | /// \param E - The expression being evaluated, for diagnostic purposes. | ||||
2710 | /// \param LVal - The pointer value to be updated. | ||||
2711 | /// \param EltTy - The pointee type represented by LVal. | ||||
2712 | /// \param Adjustment - The adjustment, in objects of type EltTy, to add. | ||||
2713 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||
2714 | LValue &LVal, QualType EltTy, | ||||
2715 | APSInt Adjustment) { | ||||
2716 | CharUnits SizeOfPointee; | ||||
2717 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) | ||||
2718 | return false; | ||||
2719 | |||||
2720 | LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); | ||||
2721 | return true; | ||||
2722 | } | ||||
2723 | |||||
2724 | static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, | ||||
2725 | LValue &LVal, QualType EltTy, | ||||
2726 | int64_t Adjustment) { | ||||
2727 | return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, | ||||
2728 | APSInt::get(Adjustment)); | ||||
2729 | } | ||||
2730 | |||||
2731 | /// Update an lvalue to refer to a component of a complex number. | ||||
2732 | /// \param Info - Information about the ongoing evaluation. | ||||
2733 | /// \param LVal - The lvalue to be updated. | ||||
2734 | /// \param EltTy - The complex number's component type. | ||||
2735 | /// \param Imag - False for the real component, true for the imaginary. | ||||
2736 | static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, | ||||
2737 | LValue &LVal, QualType EltTy, | ||||
2738 | bool Imag) { | ||||
2739 | if (Imag) { | ||||
2740 | CharUnits SizeOfComponent; | ||||
2741 | if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) | ||||
2742 | return false; | ||||
2743 | LVal.Offset += SizeOfComponent; | ||||
2744 | } | ||||
2745 | LVal.addComplex(Info, E, EltTy, Imag); | ||||
2746 | return true; | ||||
2747 | } | ||||
2748 | |||||
2749 | /// Try to evaluate the initializer for a variable declaration. | ||||
2750 | /// | ||||
2751 | /// \param Info Information about the ongoing evaluation. | ||||
2752 | /// \param E An expression to be used when printing diagnostics. | ||||
2753 | /// \param VD The variable whose initializer should be obtained. | ||||
2754 | /// \param Frame The frame in which the variable was created. Must be null | ||||
2755 | /// if this variable is not local to the evaluation. | ||||
2756 | /// \param Result Filled in with a pointer to the value of the variable. | ||||
2757 | static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, | ||||
2758 | const VarDecl *VD, CallStackFrame *Frame, | ||||
2759 | APValue *&Result, const LValue *LVal) { | ||||
2760 | |||||
2761 | // If this is a parameter to an active constexpr function call, perform | ||||
2762 | // argument substitution. | ||||
2763 | if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { | ||||
2764 | // Assume arguments of a potential constant expression are unknown | ||||
2765 | // constant expressions. | ||||
2766 | if (Info.checkingPotentialConstantExpression()) | ||||
2767 | return false; | ||||
2768 | if (!Frame || !Frame->Arguments) { | ||||
2769 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2770 | return false; | ||||
2771 | } | ||||
2772 | Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; | ||||
2773 | return true; | ||||
2774 | } | ||||
2775 | |||||
2776 | // If this is a local variable, dig out its value. | ||||
2777 | if (Frame) { | ||||
2778 | Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) | ||||
2779 | : Frame->getCurrentTemporary(VD); | ||||
2780 | if (!Result) { | ||||
2781 | // Assume variables referenced within a lambda's call operator that were | ||||
2782 | // not declared within the call operator are captures and during checking | ||||
2783 | // of a potential constant expression, assume they are unknown constant | ||||
2784 | // expressions. | ||||
2785 | assert(isLambdaCallOperator(Frame->Callee) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)) | ||||
2786 | (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)) | ||||
2787 | "missing value for local variable")((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext () != Frame->Callee || VD->isInitCapture()) && "missing value for local variable" ) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2787, __PRETTY_FUNCTION__)); | ||||
2788 | if (Info.checkingPotentialConstantExpression()) | ||||
2789 | return false; | ||||
2790 | // FIXME: implement capture evaluation during constant expr evaluation. | ||||
2791 | Info.FFDiag(E->getBeginLoc(), | ||||
2792 | diag::note_unimplemented_constexpr_lambda_feature_ast) | ||||
2793 | << "captures not currently allowed"; | ||||
2794 | return false; | ||||
2795 | } | ||||
2796 | return true; | ||||
2797 | } | ||||
2798 | |||||
2799 | // Dig out the initializer, and use the declaration which it's attached to. | ||||
2800 | const Expr *Init = VD->getAnyInitializer(VD); | ||||
2801 | if (!Init || Init->isValueDependent()) { | ||||
2802 | // If we're checking a potential constant expression, the variable could be | ||||
2803 | // initialized later. | ||||
2804 | if (!Info.checkingPotentialConstantExpression()) | ||||
2805 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2806 | return false; | ||||
2807 | } | ||||
2808 | |||||
2809 | // If we're currently evaluating the initializer of this declaration, use that | ||||
2810 | // in-flight value. | ||||
2811 | if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { | ||||
2812 | Result = Info.EvaluatingDeclValue; | ||||
2813 | return true; | ||||
2814 | } | ||||
2815 | |||||
2816 | // Never evaluate the initializer of a weak variable. We can't be sure that | ||||
2817 | // this is the definition which will be used. | ||||
2818 | if (VD->isWeak()) { | ||||
2819 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
2820 | return false; | ||||
2821 | } | ||||
2822 | |||||
2823 | // Check that we can fold the initializer. In C++, we will have already done | ||||
2824 | // this in the cases where it matters for conformance. | ||||
2825 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
2826 | if (!VD->evaluateValue(Notes)) { | ||||
2827 | Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, | ||||
2828 | Notes.size() + 1) << VD; | ||||
2829 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
2830 | Info.addNotes(Notes); | ||||
2831 | return false; | ||||
2832 | } else if (!VD->checkInitIsICE()) { | ||||
2833 | Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, | ||||
2834 | Notes.size() + 1) << VD; | ||||
2835 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
2836 | Info.addNotes(Notes); | ||||
2837 | } | ||||
2838 | |||||
2839 | Result = VD->getEvaluatedValue(); | ||||
2840 | return true; | ||||
2841 | } | ||||
2842 | |||||
2843 | static bool IsConstNonVolatile(QualType T) { | ||||
2844 | Qualifiers Quals = T.getQualifiers(); | ||||
2845 | return Quals.hasConst() && !Quals.hasVolatile(); | ||||
2846 | } | ||||
2847 | |||||
2848 | /// Get the base index of the given base class within an APValue representing | ||||
2849 | /// the given derived class. | ||||
2850 | static unsigned getBaseIndex(const CXXRecordDecl *Derived, | ||||
2851 | const CXXRecordDecl *Base) { | ||||
2852 | Base = Base->getCanonicalDecl(); | ||||
2853 | unsigned Index = 0; | ||||
2854 | for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), | ||||
2855 | E = Derived->bases_end(); I != E; ++I, ++Index) { | ||||
2856 | if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) | ||||
2857 | return Index; | ||||
2858 | } | ||||
2859 | |||||
2860 | llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2860); | ||||
2861 | } | ||||
2862 | |||||
2863 | /// Extract the value of a character from a string literal. | ||||
2864 | static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, | ||||
2865 | uint64_t Index) { | ||||
2866 | assert(!isa<SourceLocExpr>(Lit) &&((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2867, __PRETTY_FUNCTION__)) | ||||
2867 | "SourceLocExpr should have already been converted to a StringLiteral")((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral" ) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2867, __PRETTY_FUNCTION__)); | ||||
2868 | |||||
2869 | // FIXME: Support MakeStringConstant | ||||
2870 | if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { | ||||
2871 | std::string Str; | ||||
2872 | Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); | ||||
2873 | assert(Index <= Str.size() && "Index too large")((Index <= Str.size() && "Index too large") ? static_cast <void> (0) : __assert_fail ("Index <= Str.size() && \"Index too large\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2873, __PRETTY_FUNCTION__)); | ||||
2874 | return APSInt::getUnsigned(Str.c_str()[Index]); | ||||
2875 | } | ||||
2876 | |||||
2877 | if (auto PE = dyn_cast<PredefinedExpr>(Lit)) | ||||
2878 | Lit = PE->getFunctionName(); | ||||
2879 | const StringLiteral *S = cast<StringLiteral>(Lit); | ||||
2880 | const ConstantArrayType *CAT = | ||||
2881 | Info.Ctx.getAsConstantArrayType(S->getType()); | ||||
2882 | assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast <void> (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2882, __PRETTY_FUNCTION__)); | ||||
2883 | QualType CharType = CAT->getElementType(); | ||||
2884 | assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type" ) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2884, __PRETTY_FUNCTION__)); | ||||
2885 | |||||
2886 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||
2887 | CharType->isUnsignedIntegerType()); | ||||
2888 | if (Index < S->getLength()) | ||||
2889 | Value = S->getCodeUnit(Index); | ||||
2890 | return Value; | ||||
2891 | } | ||||
2892 | |||||
2893 | // Expand a string literal into an array of characters. | ||||
2894 | // | ||||
2895 | // FIXME: This is inefficient; we should probably introduce something similar | ||||
2896 | // to the LLVM ConstantDataArray to make this cheaper. | ||||
2897 | static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, | ||||
2898 | APValue &Result, | ||||
2899 | QualType AllocType = QualType()) { | ||||
2900 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||
2901 | AllocType.isNull() ? S->getType() : AllocType); | ||||
2902 | assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast <void> (0) : __assert_fail ("CAT && \"string literal isn't an array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2902, __PRETTY_FUNCTION__)); | ||||
2903 | QualType CharType = CAT->getElementType(); | ||||
2904 | assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type" ) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2904, __PRETTY_FUNCTION__)); | ||||
2905 | |||||
2906 | unsigned Elts = CAT->getSize().getZExtValue(); | ||||
2907 | Result = APValue(APValue::UninitArray(), | ||||
2908 | std::min(S->getLength(), Elts), Elts); | ||||
2909 | APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), | ||||
2910 | CharType->isUnsignedIntegerType()); | ||||
2911 | if (Result.hasArrayFiller()) | ||||
2912 | Result.getArrayFiller() = APValue(Value); | ||||
2913 | for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { | ||||
2914 | Value = S->getCodeUnit(I); | ||||
2915 | Result.getArrayInitializedElt(I) = APValue(Value); | ||||
2916 | } | ||||
2917 | } | ||||
2918 | |||||
2919 | // Expand an array so that it has more than Index filled elements. | ||||
2920 | static void expandArray(APValue &Array, unsigned Index) { | ||||
2921 | unsigned Size = Array.getArraySize(); | ||||
2922 | assert(Index < Size)((Index < Size) ? static_cast<void> (0) : __assert_fail ("Index < Size", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 2922, __PRETTY_FUNCTION__)); | ||||
2923 | |||||
2924 | // Always at least double the number of elements for which we store a value. | ||||
2925 | unsigned OldElts = Array.getArrayInitializedElts(); | ||||
2926 | unsigned NewElts = std::max(Index+1, OldElts * 2); | ||||
2927 | NewElts = std::min(Size, std::max(NewElts, 8u)); | ||||
2928 | |||||
2929 | // Copy the data across. | ||||
2930 | APValue NewValue(APValue::UninitArray(), NewElts, Size); | ||||
2931 | for (unsigned I = 0; I != OldElts; ++I) | ||||
2932 | NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); | ||||
2933 | for (unsigned I = OldElts; I != NewElts; ++I) | ||||
2934 | NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); | ||||
2935 | if (NewValue.hasArrayFiller()) | ||||
2936 | NewValue.getArrayFiller() = Array.getArrayFiller(); | ||||
2937 | Array.swap(NewValue); | ||||
2938 | } | ||||
2939 | |||||
2940 | /// Determine whether a type would actually be read by an lvalue-to-rvalue | ||||
2941 | /// conversion. If it's of class type, we may assume that the copy operation | ||||
2942 | /// is trivial. Note that this is never true for a union type with fields | ||||
2943 | /// (because the copy always "reads" the active member) and always true for | ||||
2944 | /// a non-class type. | ||||
2945 | static bool isReadByLvalueToRvalueConversion(QualType T) { | ||||
2946 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
2947 | if (!RD || (RD->isUnion() && !RD->field_empty())) | ||||
2948 | return true; | ||||
2949 | if (RD->isEmpty()) | ||||
2950 | return false; | ||||
2951 | |||||
2952 | for (auto *Field : RD->fields()) | ||||
2953 | if (isReadByLvalueToRvalueConversion(Field->getType())) | ||||
2954 | return true; | ||||
2955 | |||||
2956 | for (auto &BaseSpec : RD->bases()) | ||||
2957 | if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) | ||||
2958 | return true; | ||||
2959 | |||||
2960 | return false; | ||||
2961 | } | ||||
2962 | |||||
2963 | /// Diagnose an attempt to read from any unreadable field within the specified | ||||
2964 | /// type, which might be a class type. | ||||
2965 | static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, | ||||
2966 | QualType T) { | ||||
2967 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
2968 | if (!RD) | ||||
2969 | return false; | ||||
2970 | |||||
2971 | if (!RD->hasMutableFields()) | ||||
2972 | return false; | ||||
2973 | |||||
2974 | for (auto *Field : RD->fields()) { | ||||
2975 | // If we're actually going to read this field in some way, then it can't | ||||
2976 | // be mutable. If we're in a union, then assigning to a mutable field | ||||
2977 | // (even an empty one) can change the active member, so that's not OK. | ||||
2978 | // FIXME: Add core issue number for the union case. | ||||
2979 | if (Field->isMutable() && | ||||
2980 | (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { | ||||
2981 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; | ||||
2982 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||
2983 | return true; | ||||
2984 | } | ||||
2985 | |||||
2986 | if (diagnoseMutableFields(Info, E, AK, Field->getType())) | ||||
2987 | return true; | ||||
2988 | } | ||||
2989 | |||||
2990 | for (auto &BaseSpec : RD->bases()) | ||||
2991 | if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) | ||||
2992 | return true; | ||||
2993 | |||||
2994 | // All mutable fields were empty, and thus not actually read. | ||||
2995 | return false; | ||||
2996 | } | ||||
2997 | |||||
2998 | static bool lifetimeStartedInEvaluation(EvalInfo &Info, | ||||
2999 | APValue::LValueBase Base, | ||||
3000 | bool MutableSubobject = false) { | ||||
3001 | // A temporary we created. | ||||
3002 | if (Base.getCallIndex()) | ||||
3003 | return true; | ||||
3004 | |||||
3005 | auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); | ||||
3006 | if (!Evaluating) | ||||
3007 | return false; | ||||
3008 | |||||
3009 | auto *BaseD = Base.dyn_cast<const ValueDecl*>(); | ||||
3010 | |||||
3011 | switch (Info.IsEvaluatingDecl) { | ||||
3012 | case EvalInfo::EvaluatingDeclKind::None: | ||||
3013 | return false; | ||||
3014 | |||||
3015 | case EvalInfo::EvaluatingDeclKind::Ctor: | ||||
3016 | // The variable whose initializer we're evaluating. | ||||
3017 | if (BaseD) | ||||
3018 | return declaresSameEntity(Evaluating, BaseD); | ||||
3019 | |||||
3020 | // A temporary lifetime-extended by the variable whose initializer we're | ||||
3021 | // evaluating. | ||||
3022 | if (auto *BaseE = Base.dyn_cast<const Expr *>()) | ||||
3023 | if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) | ||||
3024 | return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); | ||||
3025 | return false; | ||||
3026 | |||||
3027 | case EvalInfo::EvaluatingDeclKind::Dtor: | ||||
3028 | // C++2a [expr.const]p6: | ||||
3029 | // [during constant destruction] the lifetime of a and its non-mutable | ||||
3030 | // subobjects (but not its mutable subobjects) [are] considered to start | ||||
3031 | // within e. | ||||
3032 | // | ||||
3033 | // FIXME: We can meaningfully extend this to cover non-const objects, but | ||||
3034 | // we will need special handling: we should be able to access only | ||||
3035 | // subobjects of such objects that are themselves declared const. | ||||
3036 | if (!BaseD || | ||||
3037 | !(BaseD->getType().isConstQualified() || | ||||
3038 | BaseD->getType()->isReferenceType()) || | ||||
3039 | MutableSubobject) | ||||
3040 | return false; | ||||
3041 | return declaresSameEntity(Evaluating, BaseD); | ||||
3042 | } | ||||
3043 | |||||
3044 | llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3044); | ||||
3045 | } | ||||
3046 | |||||
3047 | namespace { | ||||
3048 | /// A handle to a complete object (an object that is not a subobject of | ||||
3049 | /// another object). | ||||
3050 | struct CompleteObject { | ||||
3051 | /// The identity of the object. | ||||
3052 | APValue::LValueBase Base; | ||||
3053 | /// The value of the complete object. | ||||
3054 | APValue *Value; | ||||
3055 | /// The type of the complete object. | ||||
3056 | QualType Type; | ||||
3057 | |||||
3058 | CompleteObject() : Value(nullptr) {} | ||||
3059 | CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) | ||||
3060 | : Base(Base), Value(Value), Type(Type) {} | ||||
3061 | |||||
3062 | bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { | ||||
3063 | // In C++14 onwards, it is permitted to read a mutable member whose | ||||
3064 | // lifetime began within the evaluation. | ||||
3065 | // FIXME: Should we also allow this in C++11? | ||||
3066 | if (!Info.getLangOpts().CPlusPlus14) | ||||
3067 | return false; | ||||
3068 | return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); | ||||
3069 | } | ||||
3070 | |||||
3071 | explicit operator bool() const { return !Type.isNull(); } | ||||
3072 | }; | ||||
3073 | } // end anonymous namespace | ||||
3074 | |||||
3075 | static QualType getSubobjectType(QualType ObjType, QualType SubobjType, | ||||
3076 | bool IsMutable = false) { | ||||
3077 | // C++ [basic.type.qualifier]p1: | ||||
3078 | // - A const object is an object of type const T or a non-mutable subobject | ||||
3079 | // of a const object. | ||||
3080 | if (ObjType.isConstQualified() && !IsMutable) | ||||
3081 | SubobjType.addConst(); | ||||
3082 | // - A volatile object is an object of type const T or a subobject of a | ||||
3083 | // volatile object. | ||||
3084 | if (ObjType.isVolatileQualified()) | ||||
3085 | SubobjType.addVolatile(); | ||||
3086 | return SubobjType; | ||||
3087 | } | ||||
3088 | |||||
3089 | /// Find the designated sub-object of an rvalue. | ||||
3090 | template<typename SubobjectHandler> | ||||
3091 | typename SubobjectHandler::result_type | ||||
3092 | findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, | ||||
3093 | const SubobjectDesignator &Sub, SubobjectHandler &handler) { | ||||
3094 | if (Sub.Invalid) | ||||
3095 | // A diagnostic will have already been produced. | ||||
3096 | return handler.failed(); | ||||
3097 | if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { | ||||
3098 | if (Info.getLangOpts().CPlusPlus11) | ||||
3099 | Info.FFDiag(E, Sub.isOnePastTheEnd() | ||||
3100 | ? diag::note_constexpr_access_past_end | ||||
3101 | : diag::note_constexpr_access_unsized_array) | ||||
3102 | << handler.AccessKind; | ||||
3103 | else | ||||
3104 | Info.FFDiag(E); | ||||
3105 | return handler.failed(); | ||||
3106 | } | ||||
3107 | |||||
3108 | APValue *O = Obj.Value; | ||||
3109 | QualType ObjType = Obj.Type; | ||||
3110 | const FieldDecl *LastField = nullptr; | ||||
3111 | const FieldDecl *VolatileField = nullptr; | ||||
3112 | |||||
3113 | // Walk the designator's path to find the subobject. | ||||
3114 | for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { | ||||
3115 | // Reading an indeterminate value is undefined, but assigning over one is OK. | ||||
3116 | if (O->isAbsent() || | ||||
3117 | (O->isIndeterminate() && handler.AccessKind != AK_Assign && | ||||
3118 | handler.AccessKind != AK_ReadObjectRepresentation)) { | ||||
3119 | if (!Info.checkingPotentialConstantExpression()) | ||||
3120 | Info.FFDiag(E, diag::note_constexpr_access_uninit) | ||||
3121 | << handler.AccessKind << O->isIndeterminate(); | ||||
3122 | return handler.failed(); | ||||
3123 | } | ||||
3124 | |||||
3125 | // C++ [class.ctor]p5, C++ [class.dtor]p5: | ||||
3126 | // const and volatile semantics are not applied on an object under | ||||
3127 | // {con,de}struction. | ||||
3128 | if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && | ||||
3129 | ObjType->isRecordType() && | ||||
3130 | Info.isEvaluatingCtorDtor( | ||||
3131 | Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), | ||||
3132 | Sub.Entries.begin() + I)) != | ||||
3133 | ConstructionPhase::None) { | ||||
3134 | ObjType = Info.Ctx.getCanonicalType(ObjType); | ||||
3135 | ObjType.removeLocalConst(); | ||||
3136 | ObjType.removeLocalVolatile(); | ||||
3137 | } | ||||
3138 | |||||
3139 | // If this is our last pass, check that the final object type is OK. | ||||
3140 | if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { | ||||
3141 | // Accesses to volatile objects are prohibited. | ||||
3142 | if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { | ||||
3143 | if (Info.getLangOpts().CPlusPlus) { | ||||
3144 | int DiagKind; | ||||
3145 | SourceLocation Loc; | ||||
3146 | const NamedDecl *Decl = nullptr; | ||||
3147 | if (VolatileField) { | ||||
3148 | DiagKind = 2; | ||||
3149 | Loc = VolatileField->getLocation(); | ||||
3150 | Decl = VolatileField; | ||||
3151 | } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { | ||||
3152 | DiagKind = 1; | ||||
3153 | Loc = VD->getLocation(); | ||||
3154 | Decl = VD; | ||||
3155 | } else { | ||||
3156 | DiagKind = 0; | ||||
3157 | if (auto *E = Obj.Base.dyn_cast<const Expr *>()) | ||||
3158 | Loc = E->getExprLoc(); | ||||
3159 | } | ||||
3160 | Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) | ||||
3161 | << handler.AccessKind << DiagKind << Decl; | ||||
3162 | Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; | ||||
3163 | } else { | ||||
3164 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
3165 | } | ||||
3166 | return handler.failed(); | ||||
3167 | } | ||||
3168 | |||||
3169 | // If we are reading an object of class type, there may still be more | ||||
3170 | // things we need to check: if there are any mutable subobjects, we | ||||
3171 | // cannot perform this read. (This only happens when performing a trivial | ||||
3172 | // copy or assignment.) | ||||
3173 | if (ObjType->isRecordType() && | ||||
3174 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && | ||||
3175 | diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) | ||||
3176 | return handler.failed(); | ||||
3177 | } | ||||
3178 | |||||
3179 | if (I == N) { | ||||
3180 | if (!handler.found(*O, ObjType)) | ||||
3181 | return false; | ||||
3182 | |||||
3183 | // If we modified a bit-field, truncate it to the right width. | ||||
3184 | if (isModification(handler.AccessKind) && | ||||
3185 | LastField && LastField->isBitField() && | ||||
3186 | !truncateBitfieldValue(Info, E, *O, LastField)) | ||||
3187 | return false; | ||||
3188 | |||||
3189 | return true; | ||||
3190 | } | ||||
3191 | |||||
3192 | LastField = nullptr; | ||||
3193 | if (ObjType->isArrayType()) { | ||||
3194 | // Next subobject is an array element. | ||||
3195 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); | ||||
3196 | assert(CAT && "vla in literal type?")((CAT && "vla in literal type?") ? static_cast<void > (0) : __assert_fail ("CAT && \"vla in literal type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3196, __PRETTY_FUNCTION__)); | ||||
3197 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||
3198 | if (CAT->getSize().ule(Index)) { | ||||
3199 | // Note, it should not be possible to form a pointer with a valid | ||||
3200 | // designator which points more than one past the end of the array. | ||||
3201 | if (Info.getLangOpts().CPlusPlus11) | ||||
3202 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||
3203 | << handler.AccessKind; | ||||
3204 | else | ||||
3205 | Info.FFDiag(E); | ||||
3206 | return handler.failed(); | ||||
3207 | } | ||||
3208 | |||||
3209 | ObjType = CAT->getElementType(); | ||||
3210 | |||||
3211 | if (O->getArrayInitializedElts() > Index) | ||||
3212 | O = &O->getArrayInitializedElt(Index); | ||||
3213 | else if (!isRead(handler.AccessKind)) { | ||||
3214 | expandArray(*O, Index); | ||||
3215 | O = &O->getArrayInitializedElt(Index); | ||||
3216 | } else | ||||
3217 | O = &O->getArrayFiller(); | ||||
3218 | } else if (ObjType->isAnyComplexType()) { | ||||
3219 | // Next subobject is a complex number. | ||||
3220 | uint64_t Index = Sub.Entries[I].getAsArrayIndex(); | ||||
3221 | if (Index > 1) { | ||||
3222 | if (Info.getLangOpts().CPlusPlus11) | ||||
3223 | Info.FFDiag(E, diag::note_constexpr_access_past_end) | ||||
3224 | << handler.AccessKind; | ||||
3225 | else | ||||
3226 | Info.FFDiag(E); | ||||
3227 | return handler.failed(); | ||||
3228 | } | ||||
3229 | |||||
3230 | ObjType = getSubobjectType( | ||||
3231 | ObjType, ObjType->castAs<ComplexType>()->getElementType()); | ||||
3232 | |||||
3233 | assert(I == N - 1 && "extracting subobject of scalar?")((I == N - 1 && "extracting subobject of scalar?") ? static_cast <void> (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3233, __PRETTY_FUNCTION__)); | ||||
3234 | if (O->isComplexInt()) { | ||||
3235 | return handler.found(Index ? O->getComplexIntImag() | ||||
3236 | : O->getComplexIntReal(), ObjType); | ||||
3237 | } else { | ||||
3238 | assert(O->isComplexFloat())((O->isComplexFloat()) ? static_cast<void> (0) : __assert_fail ("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3238, __PRETTY_FUNCTION__)); | ||||
3239 | return handler.found(Index ? O->getComplexFloatImag() | ||||
3240 | : O->getComplexFloatReal(), ObjType); | ||||
3241 | } | ||||
3242 | } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { | ||||
3243 | if (Field->isMutable() && | ||||
3244 | !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { | ||||
3245 | Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) | ||||
3246 | << handler.AccessKind << Field; | ||||
3247 | Info.Note(Field->getLocation(), diag::note_declared_at); | ||||
3248 | return handler.failed(); | ||||
3249 | } | ||||
3250 | |||||
3251 | // Next subobject is a class, struct or union field. | ||||
3252 | RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); | ||||
3253 | if (RD->isUnion()) { | ||||
3254 | const FieldDecl *UnionField = O->getUnionField(); | ||||
3255 | if (!UnionField || | ||||
3256 | UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { | ||||
3257 | // FIXME: If O->getUnionValue() is absent, report that there's no | ||||
3258 | // active union member rather than reporting the prior active union | ||||
3259 | // member. We'll need to fix nullptr_t to not use APValue() as its | ||||
3260 | // representation first. | ||||
3261 | Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) | ||||
3262 | << handler.AccessKind << Field << !UnionField << UnionField; | ||||
3263 | return handler.failed(); | ||||
3264 | } | ||||
3265 | O = &O->getUnionValue(); | ||||
3266 | } else | ||||
3267 | O = &O->getStructField(Field->getFieldIndex()); | ||||
3268 | |||||
3269 | ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); | ||||
3270 | LastField = Field; | ||||
3271 | if (Field->getType().isVolatileQualified()) | ||||
3272 | VolatileField = Field; | ||||
3273 | } else { | ||||
3274 | // Next subobject is a base class. | ||||
3275 | const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); | ||||
3276 | const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); | ||||
3277 | O = &O->getStructBase(getBaseIndex(Derived, Base)); | ||||
3278 | |||||
3279 | ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); | ||||
3280 | } | ||||
3281 | } | ||||
3282 | } | ||||
3283 | |||||
3284 | namespace { | ||||
3285 | struct ExtractSubobjectHandler { | ||||
3286 | EvalInfo &Info; | ||||
3287 | const Expr *E; | ||||
3288 | APValue &Result; | ||||
3289 | const AccessKinds AccessKind; | ||||
3290 | |||||
3291 | typedef bool result_type; | ||||
3292 | bool failed() { return false; } | ||||
3293 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3294 | Result = Subobj; | ||||
3295 | if (AccessKind == AK_ReadObjectRepresentation) | ||||
3296 | return true; | ||||
3297 | return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); | ||||
3298 | } | ||||
3299 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3300 | Result = APValue(Value); | ||||
3301 | return true; | ||||
3302 | } | ||||
3303 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3304 | Result = APValue(Value); | ||||
3305 | return true; | ||||
3306 | } | ||||
3307 | }; | ||||
3308 | } // end anonymous namespace | ||||
3309 | |||||
3310 | /// Extract the designated sub-object of an rvalue. | ||||
3311 | static bool extractSubobject(EvalInfo &Info, const Expr *E, | ||||
3312 | const CompleteObject &Obj, | ||||
3313 | const SubobjectDesignator &Sub, APValue &Result, | ||||
3314 | AccessKinds AK = AK_Read) { | ||||
3315 | assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)((AK == AK_Read || AK == AK_ReadObjectRepresentation) ? static_cast <void> (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3315, __PRETTY_FUNCTION__)); | ||||
3316 | ExtractSubobjectHandler Handler = {Info, E, Result, AK}; | ||||
3317 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||
3318 | } | ||||
3319 | |||||
3320 | namespace { | ||||
3321 | struct ModifySubobjectHandler { | ||||
3322 | EvalInfo &Info; | ||||
3323 | APValue &NewVal; | ||||
3324 | const Expr *E; | ||||
3325 | |||||
3326 | typedef bool result_type; | ||||
3327 | static const AccessKinds AccessKind = AK_Assign; | ||||
3328 | |||||
3329 | bool checkConst(QualType QT) { | ||||
3330 | // Assigning to a const object has undefined behavior. | ||||
3331 | if (QT.isConstQualified()) { | ||||
3332 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
3333 | return false; | ||||
3334 | } | ||||
3335 | return true; | ||||
3336 | } | ||||
3337 | |||||
3338 | bool failed() { return false; } | ||||
3339 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3340 | if (!checkConst(SubobjType)) | ||||
3341 | return false; | ||||
3342 | // We've been given ownership of NewVal, so just swap it in. | ||||
3343 | Subobj.swap(NewVal); | ||||
3344 | return true; | ||||
3345 | } | ||||
3346 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3347 | if (!checkConst(SubobjType)) | ||||
3348 | return false; | ||||
3349 | if (!NewVal.isInt()) { | ||||
3350 | // Maybe trying to write a cast pointer value into a complex? | ||||
3351 | Info.FFDiag(E); | ||||
3352 | return false; | ||||
3353 | } | ||||
3354 | Value = NewVal.getInt(); | ||||
3355 | return true; | ||||
3356 | } | ||||
3357 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3358 | if (!checkConst(SubobjType)) | ||||
3359 | return false; | ||||
3360 | Value = NewVal.getFloat(); | ||||
3361 | return true; | ||||
3362 | } | ||||
3363 | }; | ||||
3364 | } // end anonymous namespace | ||||
3365 | |||||
3366 | const AccessKinds ModifySubobjectHandler::AccessKind; | ||||
3367 | |||||
3368 | /// Update the designated sub-object of an rvalue to the given value. | ||||
3369 | static bool modifySubobject(EvalInfo &Info, const Expr *E, | ||||
3370 | const CompleteObject &Obj, | ||||
3371 | const SubobjectDesignator &Sub, | ||||
3372 | APValue &NewVal) { | ||||
3373 | ModifySubobjectHandler Handler = { Info, NewVal, E }; | ||||
3374 | return findSubobject(Info, E, Obj, Sub, Handler); | ||||
3375 | } | ||||
3376 | |||||
3377 | /// Find the position where two subobject designators diverge, or equivalently | ||||
3378 | /// the length of the common initial subsequence. | ||||
3379 | static unsigned FindDesignatorMismatch(QualType ObjType, | ||||
3380 | const SubobjectDesignator &A, | ||||
3381 | const SubobjectDesignator &B, | ||||
3382 | bool &WasArrayIndex) { | ||||
3383 | unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); | ||||
3384 | for (/**/; I != N; ++I) { | ||||
3385 | if (!ObjType.isNull() && | ||||
3386 | (ObjType->isArrayType() || ObjType->isAnyComplexType())) { | ||||
3387 | // Next subobject is an array element. | ||||
3388 | if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { | ||||
3389 | WasArrayIndex = true; | ||||
3390 | return I; | ||||
3391 | } | ||||
3392 | if (ObjType->isAnyComplexType()) | ||||
3393 | ObjType = ObjType->castAs<ComplexType>()->getElementType(); | ||||
3394 | else | ||||
3395 | ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); | ||||
3396 | } else { | ||||
3397 | if (A.Entries[I].getAsBaseOrMember() != | ||||
3398 | B.Entries[I].getAsBaseOrMember()) { | ||||
3399 | WasArrayIndex = false; | ||||
3400 | return I; | ||||
3401 | } | ||||
3402 | if (const FieldDecl *FD = getAsField(A.Entries[I])) | ||||
3403 | // Next subobject is a field. | ||||
3404 | ObjType = FD->getType(); | ||||
3405 | else | ||||
3406 | // Next subobject is a base class. | ||||
3407 | ObjType = QualType(); | ||||
3408 | } | ||||
3409 | } | ||||
3410 | WasArrayIndex = false; | ||||
3411 | return I; | ||||
3412 | } | ||||
3413 | |||||
3414 | /// Determine whether the given subobject designators refer to elements of the | ||||
3415 | /// same array object. | ||||
3416 | static bool AreElementsOfSameArray(QualType ObjType, | ||||
3417 | const SubobjectDesignator &A, | ||||
3418 | const SubobjectDesignator &B) { | ||||
3419 | if (A.Entries.size() != B.Entries.size()) | ||||
3420 | return false; | ||||
3421 | |||||
3422 | bool IsArray = A.MostDerivedIsArrayElement; | ||||
3423 | if (IsArray && A.MostDerivedPathLength != A.Entries.size()) | ||||
3424 | // A is a subobject of the array element. | ||||
3425 | return false; | ||||
3426 | |||||
3427 | // If A (and B) designates an array element, the last entry will be the array | ||||
3428 | // index. That doesn't have to match. Otherwise, we're in the 'implicit array | ||||
3429 | // of length 1' case, and the entire path must match. | ||||
3430 | bool WasArrayIndex; | ||||
3431 | unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); | ||||
3432 | return CommonLength >= A.Entries.size() - IsArray; | ||||
3433 | } | ||||
3434 | |||||
3435 | /// Find the complete object to which an LValue refers. | ||||
3436 | static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, | ||||
3437 | AccessKinds AK, const LValue &LVal, | ||||
3438 | QualType LValType) { | ||||
3439 | if (LVal.InvalidBase) { | ||||
3440 | Info.FFDiag(E); | ||||
3441 | return CompleteObject(); | ||||
3442 | } | ||||
3443 | |||||
3444 | if (!LVal.Base) { | ||||
3445 | Info.FFDiag(E, diag::note_constexpr_access_null) << AK; | ||||
3446 | return CompleteObject(); | ||||
3447 | } | ||||
3448 | |||||
3449 | CallStackFrame *Frame = nullptr; | ||||
3450 | unsigned Depth = 0; | ||||
3451 | if (LVal.getLValueCallIndex()) { | ||||
3452 | std::tie(Frame, Depth) = | ||||
3453 | Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); | ||||
3454 | if (!Frame) { | ||||
3455 | Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) | ||||
3456 | << AK << LVal.Base.is<const ValueDecl*>(); | ||||
3457 | NoteLValueLocation(Info, LVal.Base); | ||||
3458 | return CompleteObject(); | ||||
3459 | } | ||||
3460 | } | ||||
3461 | |||||
3462 | bool IsAccess = isAnyAccess(AK); | ||||
3463 | |||||
3464 | // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type | ||||
3465 | // is not a constant expression (even if the object is non-volatile). We also | ||||
3466 | // apply this rule to C++98, in order to conform to the expected 'volatile' | ||||
3467 | // semantics. | ||||
3468 | if (isFormalAccess(AK) && LValType.isVolatileQualified()) { | ||||
3469 | if (Info.getLangOpts().CPlusPlus) | ||||
3470 | Info.FFDiag(E, diag::note_constexpr_access_volatile_type) | ||||
3471 | << AK << LValType; | ||||
3472 | else | ||||
3473 | Info.FFDiag(E); | ||||
3474 | return CompleteObject(); | ||||
3475 | } | ||||
3476 | |||||
3477 | // Compute value storage location and type of base object. | ||||
3478 | APValue *BaseVal = nullptr; | ||||
3479 | QualType BaseType = getType(LVal.Base); | ||||
3480 | |||||
3481 | if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { | ||||
3482 | // In C++98, const, non-volatile integers initialized with ICEs are ICEs. | ||||
3483 | // In C++11, constexpr, non-volatile variables initialized with constant | ||||
3484 | // expressions are constant expressions too. Inside constexpr functions, | ||||
3485 | // parameters are constant expressions even if they're non-const. | ||||
3486 | // In C++1y, objects local to a constant expression (those with a Frame) are | ||||
3487 | // both readable and writable inside constant expressions. | ||||
3488 | // In C, such things can also be folded, although they are not ICEs. | ||||
3489 | const VarDecl *VD = dyn_cast<VarDecl>(D); | ||||
3490 | if (VD) { | ||||
3491 | if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) | ||||
3492 | VD = VDef; | ||||
3493 | } | ||||
3494 | if (!VD || VD->isInvalidDecl()) { | ||||
3495 | Info.FFDiag(E); | ||||
3496 | return CompleteObject(); | ||||
3497 | } | ||||
3498 | |||||
3499 | // Unless we're looking at a local variable or argument in a constexpr call, | ||||
3500 | // the variable we're reading must be const. | ||||
3501 | if (!Frame) { | ||||
3502 | if (Info.getLangOpts().CPlusPlus14 && | ||||
3503 | lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||
3504 | // OK, we can read and modify an object if we're in the process of | ||||
3505 | // evaluating its initializer, because its lifetime began in this | ||||
3506 | // evaluation. | ||||
3507 | } else if (isModification(AK)) { | ||||
3508 | // All the remaining cases do not permit modification of the object. | ||||
3509 | Info.FFDiag(E, diag::note_constexpr_modify_global); | ||||
3510 | return CompleteObject(); | ||||
3511 | } else if (VD->isConstexpr()) { | ||||
3512 | // OK, we can read this variable. | ||||
3513 | } else if (BaseType->isIntegralOrEnumerationType()) { | ||||
3514 | // In OpenCL if a variable is in constant address space it is a const | ||||
3515 | // value. | ||||
3516 | if (!(BaseType.isConstQualified() || | ||||
3517 | (Info.getLangOpts().OpenCL && | ||||
3518 | BaseType.getAddressSpace() == LangAS::opencl_constant))) { | ||||
3519 | if (!IsAccess) | ||||
3520 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
3521 | if (Info.getLangOpts().CPlusPlus) { | ||||
3522 | Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; | ||||
3523 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
3524 | } else { | ||||
3525 | Info.FFDiag(E); | ||||
3526 | } | ||||
3527 | return CompleteObject(); | ||||
3528 | } | ||||
3529 | } else if (!IsAccess) { | ||||
3530 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
3531 | } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { | ||||
3532 | // We support folding of const floating-point types, in order to make | ||||
3533 | // static const data members of such types (supported as an extension) | ||||
3534 | // more useful. | ||||
3535 | if (Info.getLangOpts().CPlusPlus11) { | ||||
3536 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; | ||||
3537 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
3538 | } else { | ||||
3539 | Info.CCEDiag(E); | ||||
3540 | } | ||||
3541 | } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { | ||||
3542 | Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; | ||||
3543 | // Keep evaluating to see what we can do. | ||||
3544 | } else { | ||||
3545 | // FIXME: Allow folding of values of any literal type in all languages. | ||||
3546 | if (Info.checkingPotentialConstantExpression() && | ||||
3547 | VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { | ||||
3548 | // The definition of this variable could be constexpr. We can't | ||||
3549 | // access it right now, but may be able to in future. | ||||
3550 | } else if (Info.getLangOpts().CPlusPlus11) { | ||||
3551 | Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; | ||||
3552 | Info.Note(VD->getLocation(), diag::note_declared_at); | ||||
3553 | } else { | ||||
3554 | Info.FFDiag(E); | ||||
3555 | } | ||||
3556 | return CompleteObject(); | ||||
3557 | } | ||||
3558 | } | ||||
3559 | |||||
3560 | if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) | ||||
3561 | return CompleteObject(); | ||||
3562 | } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { | ||||
3563 | Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | ||||
3564 | if (!Alloc) { | ||||
3565 | Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; | ||||
3566 | return CompleteObject(); | ||||
3567 | } | ||||
3568 | return CompleteObject(LVal.Base, &(*Alloc)->Value, | ||||
3569 | LVal.Base.getDynamicAllocType()); | ||||
3570 | } else { | ||||
3571 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||
3572 | |||||
3573 | if (!Frame) { | ||||
3574 | if (const MaterializeTemporaryExpr *MTE = | ||||
3575 | dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { | ||||
3576 | assert(MTE->getStorageDuration() == SD_Static &&((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3577, __PRETTY_FUNCTION__)) | ||||
3577 | "should have a frame for a non-global materialized temporary")((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary" ) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3577, __PRETTY_FUNCTION__)); | ||||
3578 | |||||
3579 | // Per C++1y [expr.const]p2: | ||||
3580 | // an lvalue-to-rvalue conversion [is not allowed unless it applies to] | ||||
3581 | // - a [...] glvalue of integral or enumeration type that refers to | ||||
3582 | // a non-volatile const object [...] | ||||
3583 | // [...] | ||||
3584 | // - a [...] glvalue of literal type that refers to a non-volatile | ||||
3585 | // object whose lifetime began within the evaluation of e. | ||||
3586 | // | ||||
3587 | // C++11 misses the 'began within the evaluation of e' check and | ||||
3588 | // instead allows all temporaries, including things like: | ||||
3589 | // int &&r = 1; | ||||
3590 | // int x = ++r; | ||||
3591 | // constexpr int k = r; | ||||
3592 | // Therefore we use the C++14 rules in C++11 too. | ||||
3593 | // | ||||
3594 | // Note that temporaries whose lifetimes began while evaluating a | ||||
3595 | // variable's constructor are not usable while evaluating the | ||||
3596 | // corresponding destructor, not even if they're of const-qualified | ||||
3597 | // types. | ||||
3598 | if (!(BaseType.isConstQualified() && | ||||
3599 | BaseType->isIntegralOrEnumerationType()) && | ||||
3600 | !lifetimeStartedInEvaluation(Info, LVal.Base)) { | ||||
3601 | if (!IsAccess) | ||||
3602 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
3603 | Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; | ||||
3604 | Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); | ||||
3605 | return CompleteObject(); | ||||
3606 | } | ||||
3607 | |||||
3608 | BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); | ||||
3609 | assert(BaseVal && "got reference to unevaluated temporary")((BaseVal && "got reference to unevaluated temporary" ) ? static_cast<void> (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3609, __PRETTY_FUNCTION__)); | ||||
3610 | } else { | ||||
3611 | if (!IsAccess) | ||||
3612 | return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); | ||||
3613 | APValue Val; | ||||
3614 | LVal.moveInto(Val); | ||||
3615 | Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) | ||||
3616 | << AK | ||||
3617 | << Val.getAsString(Info.Ctx, | ||||
3618 | Info.Ctx.getLValueReferenceType(LValType)); | ||||
3619 | NoteLValueLocation(Info, LVal.Base); | ||||
3620 | return CompleteObject(); | ||||
3621 | } | ||||
3622 | } else { | ||||
3623 | BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); | ||||
3624 | assert(BaseVal && "missing value for temporary")((BaseVal && "missing value for temporary") ? static_cast <void> (0) : __assert_fail ("BaseVal && \"missing value for temporary\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3624, __PRETTY_FUNCTION__)); | ||||
3625 | } | ||||
3626 | } | ||||
3627 | |||||
3628 | // In C++14, we can't safely access any mutable state when we might be | ||||
3629 | // evaluating after an unmodeled side effect. | ||||
3630 | // | ||||
3631 | // FIXME: Not all local state is mutable. Allow local constant subobjects | ||||
3632 | // to be read here (but take care with 'mutable' fields). | ||||
3633 | if ((Frame && Info.getLangOpts().CPlusPlus14 && | ||||
3634 | Info.EvalStatus.HasSideEffects) || | ||||
3635 | (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) | ||||
3636 | return CompleteObject(); | ||||
3637 | |||||
3638 | return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); | ||||
3639 | } | ||||
3640 | |||||
3641 | /// Perform an lvalue-to-rvalue conversion on the given glvalue. This | ||||
3642 | /// can also be used for 'lvalue-to-lvalue' conversions for looking up the | ||||
3643 | /// glvalue referred to by an entity of reference type. | ||||
3644 | /// | ||||
3645 | /// \param Info - Information about the ongoing evaluation. | ||||
3646 | /// \param Conv - The expression for which we are performing the conversion. | ||||
3647 | /// Used for diagnostics. | ||||
3648 | /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the | ||||
3649 | /// case of a non-class type). | ||||
3650 | /// \param LVal - The glvalue on which we are attempting to perform this action. | ||||
3651 | /// \param RVal - The produced value will be placed here. | ||||
3652 | /// \param WantObjectRepresentation - If true, we're looking for the object | ||||
3653 | /// representation rather than the value, and in particular, | ||||
3654 | /// there is no requirement that the result be fully initialized. | ||||
3655 | static bool | ||||
3656 | handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, | ||||
3657 | const LValue &LVal, APValue &RVal, | ||||
3658 | bool WantObjectRepresentation = false) { | ||||
3659 | if (LVal.Designator.Invalid) | ||||
3660 | return false; | ||||
3661 | |||||
3662 | // Check for special cases where there is no existing APValue to look at. | ||||
3663 | const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); | ||||
3664 | |||||
3665 | AccessKinds AK = | ||||
3666 | WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; | ||||
3667 | |||||
3668 | if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { | ||||
3669 | if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { | ||||
3670 | // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the | ||||
3671 | // initializer until now for such expressions. Such an expression can't be | ||||
3672 | // an ICE in C, so this only matters for fold. | ||||
3673 | if (Type.isVolatileQualified()) { | ||||
3674 | Info.FFDiag(Conv); | ||||
3675 | return false; | ||||
3676 | } | ||||
3677 | APValue Lit; | ||||
3678 | if (!Evaluate(Lit, Info, CLE->getInitializer())) | ||||
3679 | return false; | ||||
3680 | CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); | ||||
3681 | return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); | ||||
3682 | } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { | ||||
3683 | // Special-case character extraction so we don't have to construct an | ||||
3684 | // APValue for the whole string. | ||||
3685 | assert(LVal.Designator.Entries.size() <= 1 &&((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3686, __PRETTY_FUNCTION__)) | ||||
3686 | "Can only read characters from string literals")((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals" ) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 3686, __PRETTY_FUNCTION__)); | ||||
3687 | if (LVal.Designator.Entries.empty()) { | ||||
3688 | // Fail for now for LValue to RValue conversion of an array. | ||||
3689 | // (This shouldn't show up in C/C++, but it could be triggered by a | ||||
3690 | // weird EvaluateAsRValue call from a tool.) | ||||
3691 | Info.FFDiag(Conv); | ||||
3692 | return false; | ||||
3693 | } | ||||
3694 | if (LVal.Designator.isOnePastTheEnd()) { | ||||
3695 | if (Info.getLangOpts().CPlusPlus11) | ||||
3696 | Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; | ||||
3697 | else | ||||
3698 | Info.FFDiag(Conv); | ||||
3699 | return false; | ||||
3700 | } | ||||
3701 | uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); | ||||
3702 | RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); | ||||
3703 | return true; | ||||
3704 | } | ||||
3705 | } | ||||
3706 | |||||
3707 | CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); | ||||
3708 | return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); | ||||
3709 | } | ||||
3710 | |||||
3711 | /// Perform an assignment of Val to LVal. Takes ownership of Val. | ||||
3712 | static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||
3713 | QualType LValType, APValue &Val) { | ||||
3714 | if (LVal.Designator.Invalid) | ||||
3715 | return false; | ||||
3716 | |||||
3717 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
3718 | Info.FFDiag(E); | ||||
3719 | return false; | ||||
3720 | } | ||||
3721 | |||||
3722 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||
3723 | return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); | ||||
3724 | } | ||||
3725 | |||||
3726 | namespace { | ||||
3727 | struct CompoundAssignSubobjectHandler { | ||||
3728 | EvalInfo &Info; | ||||
3729 | const Expr *E; | ||||
3730 | QualType PromotedLHSType; | ||||
3731 | BinaryOperatorKind Opcode; | ||||
3732 | const APValue &RHS; | ||||
3733 | |||||
3734 | static const AccessKinds AccessKind = AK_Assign; | ||||
3735 | |||||
3736 | typedef bool result_type; | ||||
3737 | |||||
3738 | bool checkConst(QualType QT) { | ||||
3739 | // Assigning to a const object has undefined behavior. | ||||
3740 | if (QT.isConstQualified()) { | ||||
3741 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
3742 | return false; | ||||
3743 | } | ||||
3744 | return true; | ||||
3745 | } | ||||
3746 | |||||
3747 | bool failed() { return false; } | ||||
3748 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3749 | switch (Subobj.getKind()) { | ||||
3750 | case APValue::Int: | ||||
3751 | return found(Subobj.getInt(), SubobjType); | ||||
3752 | case APValue::Float: | ||||
3753 | return found(Subobj.getFloat(), SubobjType); | ||||
3754 | case APValue::ComplexInt: | ||||
3755 | case APValue::ComplexFloat: | ||||
3756 | // FIXME: Implement complex compound assignment. | ||||
3757 | Info.FFDiag(E); | ||||
3758 | return false; | ||||
3759 | case APValue::LValue: | ||||
3760 | return foundPointer(Subobj, SubobjType); | ||||
3761 | default: | ||||
3762 | // FIXME: can this happen? | ||||
3763 | Info.FFDiag(E); | ||||
3764 | return false; | ||||
3765 | } | ||||
3766 | } | ||||
3767 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3768 | if (!checkConst(SubobjType)) | ||||
3769 | return false; | ||||
3770 | |||||
3771 | if (!SubobjType->isIntegerType()) { | ||||
3772 | // We don't support compound assignment on integer-cast-to-pointer | ||||
3773 | // values. | ||||
3774 | Info.FFDiag(E); | ||||
3775 | return false; | ||||
3776 | } | ||||
3777 | |||||
3778 | if (RHS.isInt()) { | ||||
3779 | APSInt LHS = | ||||
3780 | HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||
3781 | if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) | ||||
3782 | return false; | ||||
3783 | Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); | ||||
3784 | return true; | ||||
3785 | } else if (RHS.isFloat()) { | ||||
3786 | APFloat FValue(0.0); | ||||
3787 | return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, | ||||
3788 | FValue) && | ||||
3789 | handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && | ||||
3790 | HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, | ||||
3791 | Value); | ||||
3792 | } | ||||
3793 | |||||
3794 | Info.FFDiag(E); | ||||
3795 | return false; | ||||
3796 | } | ||||
3797 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3798 | return checkConst(SubobjType) && | ||||
3799 | HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, | ||||
3800 | Value) && | ||||
3801 | handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && | ||||
3802 | HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); | ||||
3803 | } | ||||
3804 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||
3805 | if (!checkConst(SubobjType)) | ||||
3806 | return false; | ||||
3807 | |||||
3808 | QualType PointeeType; | ||||
3809 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||
3810 | PointeeType = PT->getPointeeType(); | ||||
3811 | |||||
3812 | if (PointeeType.isNull() || !RHS.isInt() || | ||||
3813 | (Opcode != BO_Add && Opcode != BO_Sub)) { | ||||
3814 | Info.FFDiag(E); | ||||
3815 | return false; | ||||
3816 | } | ||||
3817 | |||||
3818 | APSInt Offset = RHS.getInt(); | ||||
3819 | if (Opcode == BO_Sub) | ||||
3820 | negateAsSigned(Offset); | ||||
3821 | |||||
3822 | LValue LVal; | ||||
3823 | LVal.setFrom(Info.Ctx, Subobj); | ||||
3824 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) | ||||
3825 | return false; | ||||
3826 | LVal.moveInto(Subobj); | ||||
3827 | return true; | ||||
3828 | } | ||||
3829 | }; | ||||
3830 | } // end anonymous namespace | ||||
3831 | |||||
3832 | const AccessKinds CompoundAssignSubobjectHandler::AccessKind; | ||||
3833 | |||||
3834 | /// Perform a compound assignment of LVal <op>= RVal. | ||||
3835 | static bool handleCompoundAssignment( | ||||
3836 | EvalInfo &Info, const Expr *E, | ||||
3837 | const LValue &LVal, QualType LValType, QualType PromotedLValType, | ||||
3838 | BinaryOperatorKind Opcode, const APValue &RVal) { | ||||
3839 | if (LVal.Designator.Invalid) | ||||
3840 | return false; | ||||
3841 | |||||
3842 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
3843 | Info.FFDiag(E); | ||||
3844 | return false; | ||||
3845 | } | ||||
3846 | |||||
3847 | CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); | ||||
3848 | CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, | ||||
3849 | RVal }; | ||||
3850 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||
3851 | } | ||||
3852 | |||||
3853 | namespace { | ||||
3854 | struct IncDecSubobjectHandler { | ||||
3855 | EvalInfo &Info; | ||||
3856 | const UnaryOperator *E; | ||||
3857 | AccessKinds AccessKind; | ||||
3858 | APValue *Old; | ||||
3859 | |||||
3860 | typedef bool result_type; | ||||
3861 | |||||
3862 | bool checkConst(QualType QT) { | ||||
3863 | // Assigning to a const object has undefined behavior. | ||||
3864 | if (QT.isConstQualified()) { | ||||
3865 | Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; | ||||
3866 | return false; | ||||
3867 | } | ||||
3868 | return true; | ||||
3869 | } | ||||
3870 | |||||
3871 | bool failed() { return false; } | ||||
3872 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
3873 | // Stash the old value. Also clear Old, so we don't clobber it later | ||||
3874 | // if we're post-incrementing a complex. | ||||
3875 | if (Old) { | ||||
3876 | *Old = Subobj; | ||||
3877 | Old = nullptr; | ||||
3878 | } | ||||
3879 | |||||
3880 | switch (Subobj.getKind()) { | ||||
3881 | case APValue::Int: | ||||
3882 | return found(Subobj.getInt(), SubobjType); | ||||
3883 | case APValue::Float: | ||||
3884 | return found(Subobj.getFloat(), SubobjType); | ||||
3885 | case APValue::ComplexInt: | ||||
3886 | return found(Subobj.getComplexIntReal(), | ||||
3887 | SubobjType->castAs<ComplexType>()->getElementType() | ||||
3888 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||
3889 | case APValue::ComplexFloat: | ||||
3890 | return found(Subobj.getComplexFloatReal(), | ||||
3891 | SubobjType->castAs<ComplexType>()->getElementType() | ||||
3892 | .withCVRQualifiers(SubobjType.getCVRQualifiers())); | ||||
3893 | case APValue::LValue: | ||||
3894 | return foundPointer(Subobj, SubobjType); | ||||
3895 | default: | ||||
3896 | // FIXME: can this happen? | ||||
3897 | Info.FFDiag(E); | ||||
3898 | return false; | ||||
3899 | } | ||||
3900 | } | ||||
3901 | bool found(APSInt &Value, QualType SubobjType) { | ||||
3902 | if (!checkConst(SubobjType)) | ||||
3903 | return false; | ||||
3904 | |||||
3905 | if (!SubobjType->isIntegerType()) { | ||||
3906 | // We don't support increment / decrement on integer-cast-to-pointer | ||||
3907 | // values. | ||||
3908 | Info.FFDiag(E); | ||||
3909 | return false; | ||||
3910 | } | ||||
3911 | |||||
3912 | if (Old) *Old = APValue(Value); | ||||
3913 | |||||
3914 | // bool arithmetic promotes to int, and the conversion back to bool | ||||
3915 | // doesn't reduce mod 2^n, so special-case it. | ||||
3916 | if (SubobjType->isBooleanType()) { | ||||
3917 | if (AccessKind == AK_Increment) | ||||
3918 | Value = 1; | ||||
3919 | else | ||||
3920 | Value = !Value; | ||||
3921 | return true; | ||||
3922 | } | ||||
3923 | |||||
3924 | bool WasNegative = Value.isNegative(); | ||||
3925 | if (AccessKind == AK_Increment) { | ||||
3926 | ++Value; | ||||
3927 | |||||
3928 | if (!WasNegative && Value.isNegative() && E->canOverflow()) { | ||||
3929 | APSInt ActualValue(Value, /*IsUnsigned*/true); | ||||
3930 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||
3931 | } | ||||
3932 | } else { | ||||
3933 | --Value; | ||||
3934 | |||||
3935 | if (WasNegative && !Value.isNegative() && E->canOverflow()) { | ||||
3936 | unsigned BitWidth = Value.getBitWidth(); | ||||
3937 | APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); | ||||
3938 | ActualValue.setBit(BitWidth); | ||||
3939 | return HandleOverflow(Info, E, ActualValue, SubobjType); | ||||
3940 | } | ||||
3941 | } | ||||
3942 | return true; | ||||
3943 | } | ||||
3944 | bool found(APFloat &Value, QualType SubobjType) { | ||||
3945 | if (!checkConst(SubobjType)) | ||||
3946 | return false; | ||||
3947 | |||||
3948 | if (Old) *Old = APValue(Value); | ||||
3949 | |||||
3950 | APFloat One(Value.getSemantics(), 1); | ||||
3951 | if (AccessKind == AK_Increment) | ||||
3952 | Value.add(One, APFloat::rmNearestTiesToEven); | ||||
3953 | else | ||||
3954 | Value.subtract(One, APFloat::rmNearestTiesToEven); | ||||
3955 | return true; | ||||
3956 | } | ||||
3957 | bool foundPointer(APValue &Subobj, QualType SubobjType) { | ||||
3958 | if (!checkConst(SubobjType)) | ||||
3959 | return false; | ||||
3960 | |||||
3961 | QualType PointeeType; | ||||
3962 | if (const PointerType *PT = SubobjType->getAs<PointerType>()) | ||||
3963 | PointeeType = PT->getPointeeType(); | ||||
3964 | else { | ||||
3965 | Info.FFDiag(E); | ||||
3966 | return false; | ||||
3967 | } | ||||
3968 | |||||
3969 | LValue LVal; | ||||
3970 | LVal.setFrom(Info.Ctx, Subobj); | ||||
3971 | if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, | ||||
3972 | AccessKind == AK_Increment ? 1 : -1)) | ||||
3973 | return false; | ||||
3974 | LVal.moveInto(Subobj); | ||||
3975 | return true; | ||||
3976 | } | ||||
3977 | }; | ||||
3978 | } // end anonymous namespace | ||||
3979 | |||||
3980 | /// Perform an increment or decrement on LVal. | ||||
3981 | static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, | ||||
3982 | QualType LValType, bool IsIncrement, APValue *Old) { | ||||
3983 | if (LVal.Designator.Invalid) | ||||
3984 | return false; | ||||
3985 | |||||
3986 | if (!Info.getLangOpts().CPlusPlus14) { | ||||
3987 | Info.FFDiag(E); | ||||
3988 | return false; | ||||
3989 | } | ||||
3990 | |||||
3991 | AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; | ||||
3992 | CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); | ||||
3993 | IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; | ||||
3994 | return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); | ||||
3995 | } | ||||
3996 | |||||
3997 | /// Build an lvalue for the object argument of a member function call. | ||||
3998 | static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, | ||||
3999 | LValue &This) { | ||||
4000 | if (Object->getType()->isPointerType() && Object->isRValue()) | ||||
4001 | return EvaluatePointer(Object, This, Info); | ||||
4002 | |||||
4003 | if (Object->isGLValue()) | ||||
4004 | return EvaluateLValue(Object, This, Info); | ||||
4005 | |||||
4006 | if (Object->getType()->isLiteralType(Info.Ctx)) | ||||
4007 | return EvaluateTemporary(Object, This, Info); | ||||
4008 | |||||
4009 | Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); | ||||
4010 | return false; | ||||
4011 | } | ||||
4012 | |||||
4013 | /// HandleMemberPointerAccess - Evaluate a member access operation and build an | ||||
4014 | /// lvalue referring to the result. | ||||
4015 | /// | ||||
4016 | /// \param Info - Information about the ongoing evaluation. | ||||
4017 | /// \param LV - An lvalue referring to the base of the member pointer. | ||||
4018 | /// \param RHS - The member pointer expression. | ||||
4019 | /// \param IncludeMember - Specifies whether the member itself is included in | ||||
4020 | /// the resulting LValue subobject designator. This is not possible when | ||||
4021 | /// creating a bound member function. | ||||
4022 | /// \return The field or method declaration to which the member pointer refers, | ||||
4023 | /// or 0 if evaluation fails. | ||||
4024 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||
4025 | QualType LVType, | ||||
4026 | LValue &LV, | ||||
4027 | const Expr *RHS, | ||||
4028 | bool IncludeMember = true) { | ||||
4029 | MemberPtr MemPtr; | ||||
4030 | if (!EvaluateMemberPointer(RHS, MemPtr, Info)) | ||||
4031 | return nullptr; | ||||
4032 | |||||
4033 | // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to | ||||
4034 | // member value, the behavior is undefined. | ||||
4035 | if (!MemPtr.getDecl()) { | ||||
4036 | // FIXME: Specific diagnostic. | ||||
4037 | Info.FFDiag(RHS); | ||||
4038 | return nullptr; | ||||
4039 | } | ||||
4040 | |||||
4041 | if (MemPtr.isDerivedMember()) { | ||||
4042 | // This is a member of some derived class. Truncate LV appropriately. | ||||
4043 | // The end of the derived-to-base path for the base object must match the | ||||
4044 | // derived-to-base path for the member pointer. | ||||
4045 | if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > | ||||
4046 | LV.Designator.Entries.size()) { | ||||
4047 | Info.FFDiag(RHS); | ||||
4048 | return nullptr; | ||||
4049 | } | ||||
4050 | unsigned PathLengthToMember = | ||||
4051 | LV.Designator.Entries.size() - MemPtr.Path.size(); | ||||
4052 | for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { | ||||
4053 | const CXXRecordDecl *LVDecl = getAsBaseClass( | ||||
4054 | LV.Designator.Entries[PathLengthToMember + I]); | ||||
4055 | const CXXRecordDecl *MPDecl = MemPtr.Path[I]; | ||||
4056 | if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { | ||||
4057 | Info.FFDiag(RHS); | ||||
4058 | return nullptr; | ||||
4059 | } | ||||
4060 | } | ||||
4061 | |||||
4062 | // Truncate the lvalue to the appropriate derived class. | ||||
4063 | if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), | ||||
4064 | PathLengthToMember)) | ||||
4065 | return nullptr; | ||||
4066 | } else if (!MemPtr.Path.empty()) { | ||||
4067 | // Extend the LValue path with the member pointer's path. | ||||
4068 | LV.Designator.Entries.reserve(LV.Designator.Entries.size() + | ||||
4069 | MemPtr.Path.size() + IncludeMember); | ||||
4070 | |||||
4071 | // Walk down to the appropriate base class. | ||||
4072 | if (const PointerType *PT = LVType->getAs<PointerType>()) | ||||
4073 | LVType = PT->getPointeeType(); | ||||
4074 | const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); | ||||
4075 | assert(RD && "member pointer access on non-class-type expression")((RD && "member pointer access on non-class-type expression" ) ? static_cast<void> (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4075, __PRETTY_FUNCTION__)); | ||||
4076 | // The first class in the path is that of the lvalue. | ||||
4077 | for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { | ||||
4078 | const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; | ||||
4079 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) | ||||
4080 | return nullptr; | ||||
4081 | RD = Base; | ||||
4082 | } | ||||
4083 | // Finally cast to the class containing the member. | ||||
4084 | if (!HandleLValueDirectBase(Info, RHS, LV, RD, | ||||
4085 | MemPtr.getContainingRecord())) | ||||
4086 | return nullptr; | ||||
4087 | } | ||||
4088 | |||||
4089 | // Add the member. Note that we cannot build bound member functions here. | ||||
4090 | if (IncludeMember) { | ||||
4091 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { | ||||
4092 | if (!HandleLValueMember(Info, RHS, LV, FD)) | ||||
4093 | return nullptr; | ||||
4094 | } else if (const IndirectFieldDecl *IFD = | ||||
4095 | dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { | ||||
4096 | if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) | ||||
4097 | return nullptr; | ||||
4098 | } else { | ||||
4099 | llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4099); | ||||
4100 | } | ||||
4101 | } | ||||
4102 | |||||
4103 | return MemPtr.getDecl(); | ||||
4104 | } | ||||
4105 | |||||
4106 | static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, | ||||
4107 | const BinaryOperator *BO, | ||||
4108 | LValue &LV, | ||||
4109 | bool IncludeMember = true) { | ||||
4110 | assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)((BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI ) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4110, __PRETTY_FUNCTION__)); | ||||
4111 | |||||
4112 | if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { | ||||
4113 | if (Info.noteFailure()) { | ||||
4114 | MemberPtr MemPtr; | ||||
4115 | EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); | ||||
4116 | } | ||||
4117 | return nullptr; | ||||
4118 | } | ||||
4119 | |||||
4120 | return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, | ||||
4121 | BO->getRHS(), IncludeMember); | ||||
4122 | } | ||||
4123 | |||||
4124 | /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on | ||||
4125 | /// the provided lvalue, which currently refers to the base object. | ||||
4126 | static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, | ||||
4127 | LValue &Result) { | ||||
4128 | SubobjectDesignator &D = Result.Designator; | ||||
4129 | if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) | ||||
4130 | return false; | ||||
4131 | |||||
4132 | QualType TargetQT = E->getType(); | ||||
4133 | if (const PointerType *PT = TargetQT->getAs<PointerType>()) | ||||
4134 | TargetQT = PT->getPointeeType(); | ||||
4135 | |||||
4136 | // Check this cast lands within the final derived-to-base subobject path. | ||||
4137 | if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { | ||||
4138 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||
4139 | << D.MostDerivedType << TargetQT; | ||||
4140 | return false; | ||||
4141 | } | ||||
4142 | |||||
4143 | // Check the type of the final cast. We don't need to check the path, | ||||
4144 | // since a cast can only be formed if the path is unique. | ||||
4145 | unsigned NewEntriesSize = D.Entries.size() - E->path_size(); | ||||
4146 | const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); | ||||
4147 | const CXXRecordDecl *FinalType; | ||||
4148 | if (NewEntriesSize == D.MostDerivedPathLength) | ||||
4149 | FinalType = D.MostDerivedType->getAsCXXRecordDecl(); | ||||
4150 | else | ||||
4151 | FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); | ||||
4152 | if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { | ||||
4153 | Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) | ||||
4154 | << D.MostDerivedType << TargetQT; | ||||
4155 | return false; | ||||
4156 | } | ||||
4157 | |||||
4158 | // Truncate the lvalue to the appropriate derived class. | ||||
4159 | return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); | ||||
4160 | } | ||||
4161 | |||||
4162 | /// Get the value to use for a default-initialized object of type T. | ||||
4163 | static APValue getDefaultInitValue(QualType T) { | ||||
4164 | if (auto *RD = T->getAsCXXRecordDecl()) { | ||||
4165 | if (RD->isUnion()) | ||||
4166 | return APValue((const FieldDecl*)nullptr); | ||||
4167 | |||||
4168 | APValue Struct(APValue::UninitStruct(), RD->getNumBases(), | ||||
4169 | std::distance(RD->field_begin(), RD->field_end())); | ||||
4170 | |||||
4171 | unsigned Index = 0; | ||||
4172 | for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), | ||||
4173 | End = RD->bases_end(); I != End; ++I, ++Index) | ||||
4174 | Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); | ||||
4175 | |||||
4176 | for (const auto *I : RD->fields()) { | ||||
4177 | if (I->isUnnamedBitfield()) | ||||
4178 | continue; | ||||
4179 | Struct.getStructField(I->getFieldIndex()) = | ||||
4180 | getDefaultInitValue(I->getType()); | ||||
4181 | } | ||||
4182 | return Struct; | ||||
4183 | } | ||||
4184 | |||||
4185 | if (auto *AT = | ||||
4186 | dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { | ||||
4187 | APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); | ||||
4188 | if (Array.hasArrayFiller()) | ||||
4189 | Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); | ||||
4190 | return Array; | ||||
4191 | } | ||||
4192 | |||||
4193 | return APValue::IndeterminateValue(); | ||||
4194 | } | ||||
4195 | |||||
4196 | namespace { | ||||
4197 | enum EvalStmtResult { | ||||
4198 | /// Evaluation failed. | ||||
4199 | ESR_Failed, | ||||
4200 | /// Hit a 'return' statement. | ||||
4201 | ESR_Returned, | ||||
4202 | /// Evaluation succeeded. | ||||
4203 | ESR_Succeeded, | ||||
4204 | /// Hit a 'continue' statement. | ||||
4205 | ESR_Continue, | ||||
4206 | /// Hit a 'break' statement. | ||||
4207 | ESR_Break, | ||||
4208 | /// Still scanning for 'case' or 'default' statement. | ||||
4209 | ESR_CaseNotFound | ||||
4210 | }; | ||||
4211 | } | ||||
4212 | |||||
4213 | static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { | ||||
4214 | // We don't need to evaluate the initializer for a static local. | ||||
4215 | if (!VD->hasLocalStorage()) | ||||
4216 | return true; | ||||
4217 | |||||
4218 | LValue Result; | ||||
4219 | APValue &Val = | ||||
4220 | Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); | ||||
4221 | |||||
4222 | const Expr *InitE = VD->getInit(); | ||||
4223 | if (!InitE) { | ||||
4224 | Val = getDefaultInitValue(VD->getType()); | ||||
4225 | return true; | ||||
4226 | } | ||||
4227 | |||||
4228 | if (InitE->isValueDependent()) | ||||
4229 | return false; | ||||
4230 | |||||
4231 | if (!EvaluateInPlace(Val, Info, Result, InitE)) { | ||||
4232 | // Wipe out any partially-computed value, to allow tracking that this | ||||
4233 | // evaluation failed. | ||||
4234 | Val = APValue(); | ||||
4235 | return false; | ||||
4236 | } | ||||
4237 | |||||
4238 | return true; | ||||
4239 | } | ||||
4240 | |||||
4241 | static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { | ||||
4242 | bool OK = true; | ||||
4243 | |||||
4244 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
4245 | OK &= EvaluateVarDecl(Info, VD); | ||||
4246 | |||||
4247 | if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) | ||||
4248 | for (auto *BD : DD->bindings()) | ||||
4249 | if (auto *VD = BD->getHoldingVar()) | ||||
4250 | OK &= EvaluateDecl(Info, VD); | ||||
4251 | |||||
4252 | return OK; | ||||
4253 | } | ||||
4254 | |||||
4255 | |||||
4256 | /// Evaluate a condition (either a variable declaration or an expression). | ||||
4257 | static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, | ||||
4258 | const Expr *Cond, bool &Result) { | ||||
4259 | FullExpressionRAII Scope(Info); | ||||
4260 | if (CondDecl && !EvaluateDecl(Info, CondDecl)) | ||||
4261 | return false; | ||||
4262 | if (!EvaluateAsBooleanCondition(Cond, Result, Info)) | ||||
4263 | return false; | ||||
4264 | return Scope.destroy(); | ||||
4265 | } | ||||
4266 | |||||
4267 | namespace { | ||||
4268 | /// A location where the result (returned value) of evaluating a | ||||
4269 | /// statement should be stored. | ||||
4270 | struct StmtResult { | ||||
4271 | /// The APValue that should be filled in with the returned value. | ||||
4272 | APValue &Value; | ||||
4273 | /// The location containing the result, if any (used to support RVO). | ||||
4274 | const LValue *Slot; | ||||
4275 | }; | ||||
4276 | |||||
4277 | struct TempVersionRAII { | ||||
4278 | CallStackFrame &Frame; | ||||
4279 | |||||
4280 | TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { | ||||
4281 | Frame.pushTempVersion(); | ||||
4282 | } | ||||
4283 | |||||
4284 | ~TempVersionRAII() { | ||||
4285 | Frame.popTempVersion(); | ||||
4286 | } | ||||
4287 | }; | ||||
4288 | |||||
4289 | } | ||||
4290 | |||||
4291 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||
4292 | const Stmt *S, | ||||
4293 | const SwitchCase *SC = nullptr); | ||||
4294 | |||||
4295 | /// Evaluate the body of a loop, and translate the result as appropriate. | ||||
4296 | static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, | ||||
4297 | const Stmt *Body, | ||||
4298 | const SwitchCase *Case = nullptr) { | ||||
4299 | BlockScopeRAII Scope(Info); | ||||
4300 | |||||
4301 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); | ||||
4302 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||
4303 | ESR = ESR_Failed; | ||||
4304 | |||||
4305 | switch (ESR) { | ||||
4306 | case ESR_Break: | ||||
4307 | return ESR_Succeeded; | ||||
4308 | case ESR_Succeeded: | ||||
4309 | case ESR_Continue: | ||||
4310 | return ESR_Continue; | ||||
4311 | case ESR_Failed: | ||||
4312 | case ESR_Returned: | ||||
4313 | case ESR_CaseNotFound: | ||||
4314 | return ESR; | ||||
4315 | } | ||||
4316 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4316); | ||||
4317 | } | ||||
4318 | |||||
4319 | /// Evaluate a switch statement. | ||||
4320 | static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, | ||||
4321 | const SwitchStmt *SS) { | ||||
4322 | BlockScopeRAII Scope(Info); | ||||
4323 | |||||
4324 | // Evaluate the switch condition. | ||||
4325 | APSInt Value; | ||||
4326 | { | ||||
4327 | if (const Stmt *Init = SS->getInit()) { | ||||
4328 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||
4329 | if (ESR != ESR_Succeeded) { | ||||
4330 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4331 | ESR = ESR_Failed; | ||||
4332 | return ESR; | ||||
4333 | } | ||||
4334 | } | ||||
4335 | |||||
4336 | FullExpressionRAII CondScope(Info); | ||||
4337 | if (SS->getConditionVariable() && | ||||
4338 | !EvaluateDecl(Info, SS->getConditionVariable())) | ||||
4339 | return ESR_Failed; | ||||
4340 | if (!EvaluateInteger(SS->getCond(), Value, Info)) | ||||
4341 | return ESR_Failed; | ||||
4342 | if (!CondScope.destroy()) | ||||
4343 | return ESR_Failed; | ||||
4344 | } | ||||
4345 | |||||
4346 | // Find the switch case corresponding to the value of the condition. | ||||
4347 | // FIXME: Cache this lookup. | ||||
4348 | const SwitchCase *Found = nullptr; | ||||
4349 | for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; | ||||
4350 | SC = SC->getNextSwitchCase()) { | ||||
4351 | if (isa<DefaultStmt>(SC)) { | ||||
4352 | Found = SC; | ||||
4353 | continue; | ||||
4354 | } | ||||
4355 | |||||
4356 | const CaseStmt *CS = cast<CaseStmt>(SC); | ||||
4357 | APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); | ||||
4358 | APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) | ||||
4359 | : LHS; | ||||
4360 | if (LHS <= Value && Value <= RHS) { | ||||
4361 | Found = SC; | ||||
4362 | break; | ||||
4363 | } | ||||
4364 | } | ||||
4365 | |||||
4366 | if (!Found) | ||||
4367 | return Scope.destroy() ? ESR_Failed : ESR_Succeeded; | ||||
4368 | |||||
4369 | // Search the switch body for the switch case and evaluate it from there. | ||||
4370 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); | ||||
4371 | if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) | ||||
4372 | return ESR_Failed; | ||||
4373 | |||||
4374 | switch (ESR) { | ||||
4375 | case ESR_Break: | ||||
4376 | return ESR_Succeeded; | ||||
4377 | case ESR_Succeeded: | ||||
4378 | case ESR_Continue: | ||||
4379 | case ESR_Failed: | ||||
4380 | case ESR_Returned: | ||||
4381 | return ESR; | ||||
4382 | case ESR_CaseNotFound: | ||||
4383 | // This can only happen if the switch case is nested within a statement | ||||
4384 | // expression. We have no intention of supporting that. | ||||
4385 | Info.FFDiag(Found->getBeginLoc(), | ||||
4386 | diag::note_constexpr_stmt_expr_unsupported); | ||||
4387 | return ESR_Failed; | ||||
4388 | } | ||||
4389 | llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4389); | ||||
4390 | } | ||||
4391 | |||||
4392 | // Evaluate a statement. | ||||
4393 | static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, | ||||
4394 | const Stmt *S, const SwitchCase *Case) { | ||||
4395 | if (!Info.nextStep(S)) | ||||
4396 | return ESR_Failed; | ||||
4397 | |||||
4398 | // If we're hunting down a 'case' or 'default' label, recurse through | ||||
4399 | // substatements until we hit the label. | ||||
4400 | if (Case) { | ||||
4401 | switch (S->getStmtClass()) { | ||||
4402 | case Stmt::CompoundStmtClass: | ||||
4403 | // FIXME: Precompute which substatement of a compound statement we | ||||
4404 | // would jump to, and go straight there rather than performing a | ||||
4405 | // linear scan each time. | ||||
4406 | case Stmt::LabelStmtClass: | ||||
4407 | case Stmt::AttributedStmtClass: | ||||
4408 | case Stmt::DoStmtClass: | ||||
4409 | break; | ||||
4410 | |||||
4411 | case Stmt::CaseStmtClass: | ||||
4412 | case Stmt::DefaultStmtClass: | ||||
4413 | if (Case == S) | ||||
4414 | Case = nullptr; | ||||
4415 | break; | ||||
4416 | |||||
4417 | case Stmt::IfStmtClass: { | ||||
4418 | // FIXME: Precompute which side of an 'if' we would jump to, and go | ||||
4419 | // straight there rather than scanning both sides. | ||||
4420 | const IfStmt *IS = cast<IfStmt>(S); | ||||
4421 | |||||
4422 | // Wrap the evaluation in a block scope, in case it's a DeclStmt | ||||
4423 | // preceded by our switch label. | ||||
4424 | BlockScopeRAII Scope(Info); | ||||
4425 | |||||
4426 | // Step into the init statement in case it brings an (uninitialized) | ||||
4427 | // variable into scope. | ||||
4428 | if (const Stmt *Init = IS->getInit()) { | ||||
4429 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||
4430 | if (ESR != ESR_CaseNotFound) { | ||||
4431 | assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4431, __PRETTY_FUNCTION__)); | ||||
4432 | return ESR; | ||||
4433 | } | ||||
4434 | } | ||||
4435 | |||||
4436 | // Condition variable must be initialized if it exists. | ||||
4437 | // FIXME: We can skip evaluating the body if there's a condition | ||||
4438 | // variable, as there can't be any case labels within it. | ||||
4439 | // (The same is true for 'for' statements.) | ||||
4440 | |||||
4441 | EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); | ||||
4442 | if (ESR == ESR_Failed) | ||||
4443 | return ESR; | ||||
4444 | if (ESR != ESR_CaseNotFound) | ||||
4445 | return Scope.destroy() ? ESR : ESR_Failed; | ||||
4446 | if (!IS->getElse()) | ||||
4447 | return ESR_CaseNotFound; | ||||
4448 | |||||
4449 | ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); | ||||
4450 | if (ESR == ESR_Failed) | ||||
4451 | return ESR; | ||||
4452 | if (ESR != ESR_CaseNotFound) | ||||
4453 | return Scope.destroy() ? ESR : ESR_Failed; | ||||
4454 | return ESR_CaseNotFound; | ||||
4455 | } | ||||
4456 | |||||
4457 | case Stmt::WhileStmtClass: { | ||||
4458 | EvalStmtResult ESR = | ||||
4459 | EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); | ||||
4460 | if (ESR != ESR_Continue) | ||||
4461 | return ESR; | ||||
4462 | break; | ||||
4463 | } | ||||
4464 | |||||
4465 | case Stmt::ForStmtClass: { | ||||
4466 | const ForStmt *FS = cast<ForStmt>(S); | ||||
4467 | BlockScopeRAII Scope(Info); | ||||
4468 | |||||
4469 | // Step into the init statement in case it brings an (uninitialized) | ||||
4470 | // variable into scope. | ||||
4471 | if (const Stmt *Init = FS->getInit()) { | ||||
4472 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); | ||||
4473 | if (ESR != ESR_CaseNotFound) { | ||||
4474 | assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail ("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4474, __PRETTY_FUNCTION__)); | ||||
4475 | return ESR; | ||||
4476 | } | ||||
4477 | } | ||||
4478 | |||||
4479 | EvalStmtResult ESR = | ||||
4480 | EvaluateLoopBody(Result, Info, FS->getBody(), Case); | ||||
4481 | if (ESR != ESR_Continue) | ||||
4482 | return ESR; | ||||
4483 | if (FS->getInc()) { | ||||
4484 | FullExpressionRAII IncScope(Info); | ||||
4485 | if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) | ||||
4486 | return ESR_Failed; | ||||
4487 | } | ||||
4488 | break; | ||||
4489 | } | ||||
4490 | |||||
4491 | case Stmt::DeclStmtClass: { | ||||
4492 | // Start the lifetime of any uninitialized variables we encounter. They | ||||
4493 | // might be used by the selected branch of the switch. | ||||
4494 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||
4495 | for (const auto *D : DS->decls()) { | ||||
4496 | if (const auto *VD = dyn_cast<VarDecl>(D)) { | ||||
4497 | if (VD->hasLocalStorage() && !VD->getInit()) | ||||
4498 | if (!EvaluateVarDecl(Info, VD)) | ||||
4499 | return ESR_Failed; | ||||
4500 | // FIXME: If the variable has initialization that can't be jumped | ||||
4501 | // over, bail out of any immediately-surrounding compound-statement | ||||
4502 | // too. There can't be any case labels here. | ||||
4503 | } | ||||
4504 | } | ||||
4505 | return ESR_CaseNotFound; | ||||
4506 | } | ||||
4507 | |||||
4508 | default: | ||||
4509 | return ESR_CaseNotFound; | ||||
4510 | } | ||||
4511 | } | ||||
4512 | |||||
4513 | switch (S->getStmtClass()) { | ||||
4514 | default: | ||||
4515 | if (const Expr *E = dyn_cast<Expr>(S)) { | ||||
4516 | // Don't bother evaluating beyond an expression-statement which couldn't | ||||
4517 | // be evaluated. | ||||
4518 | // FIXME: Do we need the FullExpressionRAII object here? | ||||
4519 | // VisitExprWithCleanups should create one when necessary. | ||||
4520 | FullExpressionRAII Scope(Info); | ||||
4521 | if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) | ||||
4522 | return ESR_Failed; | ||||
4523 | return ESR_Succeeded; | ||||
4524 | } | ||||
4525 | |||||
4526 | Info.FFDiag(S->getBeginLoc()); | ||||
4527 | return ESR_Failed; | ||||
4528 | |||||
4529 | case Stmt::NullStmtClass: | ||||
4530 | return ESR_Succeeded; | ||||
4531 | |||||
4532 | case Stmt::DeclStmtClass: { | ||||
4533 | const DeclStmt *DS = cast<DeclStmt>(S); | ||||
4534 | for (const auto *D : DS->decls()) { | ||||
4535 | // Each declaration initialization is its own full-expression. | ||||
4536 | FullExpressionRAII Scope(Info); | ||||
4537 | if (!EvaluateDecl(Info, D) && !Info.noteFailure()) | ||||
4538 | return ESR_Failed; | ||||
4539 | if (!Scope.destroy()) | ||||
4540 | return ESR_Failed; | ||||
4541 | } | ||||
4542 | return ESR_Succeeded; | ||||
4543 | } | ||||
4544 | |||||
4545 | case Stmt::ReturnStmtClass: { | ||||
4546 | const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); | ||||
4547 | FullExpressionRAII Scope(Info); | ||||
4548 | if (RetExpr && | ||||
4549 | !(Result.Slot | ||||
4550 | ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) | ||||
4551 | : Evaluate(Result.Value, Info, RetExpr))) | ||||
4552 | return ESR_Failed; | ||||
4553 | return Scope.destroy() ? ESR_Returned : ESR_Failed; | ||||
4554 | } | ||||
4555 | |||||
4556 | case Stmt::CompoundStmtClass: { | ||||
4557 | BlockScopeRAII Scope(Info); | ||||
4558 | |||||
4559 | const CompoundStmt *CS = cast<CompoundStmt>(S); | ||||
4560 | for (const auto *BI : CS->body()) { | ||||
4561 | EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); | ||||
4562 | if (ESR == ESR_Succeeded) | ||||
4563 | Case = nullptr; | ||||
4564 | else if (ESR != ESR_CaseNotFound) { | ||||
4565 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4566 | return ESR_Failed; | ||||
4567 | return ESR; | ||||
4568 | } | ||||
4569 | } | ||||
4570 | if (Case) | ||||
4571 | return ESR_CaseNotFound; | ||||
4572 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
4573 | } | ||||
4574 | |||||
4575 | case Stmt::IfStmtClass: { | ||||
4576 | const IfStmt *IS = cast<IfStmt>(S); | ||||
4577 | |||||
4578 | // Evaluate the condition, as either a var decl or as an expression. | ||||
4579 | BlockScopeRAII Scope(Info); | ||||
4580 | if (const Stmt *Init = IS->getInit()) { | ||||
4581 | EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); | ||||
4582 | if (ESR != ESR_Succeeded) { | ||||
4583 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4584 | return ESR_Failed; | ||||
4585 | return ESR; | ||||
4586 | } | ||||
4587 | } | ||||
4588 | bool Cond; | ||||
4589 | if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) | ||||
4590 | return ESR_Failed; | ||||
4591 | |||||
4592 | if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { | ||||
4593 | EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); | ||||
4594 | if (ESR != ESR_Succeeded) { | ||||
4595 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4596 | return ESR_Failed; | ||||
4597 | return ESR; | ||||
4598 | } | ||||
4599 | } | ||||
4600 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
4601 | } | ||||
4602 | |||||
4603 | case Stmt::WhileStmtClass: { | ||||
4604 | const WhileStmt *WS = cast<WhileStmt>(S); | ||||
4605 | while (true) { | ||||
4606 | BlockScopeRAII Scope(Info); | ||||
4607 | bool Continue; | ||||
4608 | if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), | ||||
4609 | Continue)) | ||||
4610 | return ESR_Failed; | ||||
4611 | if (!Continue) | ||||
4612 | break; | ||||
4613 | |||||
4614 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); | ||||
4615 | if (ESR != ESR_Continue) { | ||||
4616 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4617 | return ESR_Failed; | ||||
4618 | return ESR; | ||||
4619 | } | ||||
4620 | if (!Scope.destroy()) | ||||
4621 | return ESR_Failed; | ||||
4622 | } | ||||
4623 | return ESR_Succeeded; | ||||
4624 | } | ||||
4625 | |||||
4626 | case Stmt::DoStmtClass: { | ||||
4627 | const DoStmt *DS = cast<DoStmt>(S); | ||||
4628 | bool Continue; | ||||
4629 | do { | ||||
4630 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); | ||||
4631 | if (ESR != ESR_Continue) | ||||
4632 | return ESR; | ||||
4633 | Case = nullptr; | ||||
4634 | |||||
4635 | FullExpressionRAII CondScope(Info); | ||||
4636 | if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || | ||||
4637 | !CondScope.destroy()) | ||||
4638 | return ESR_Failed; | ||||
4639 | } while (Continue); | ||||
4640 | return ESR_Succeeded; | ||||
4641 | } | ||||
4642 | |||||
4643 | case Stmt::ForStmtClass: { | ||||
4644 | const ForStmt *FS = cast<ForStmt>(S); | ||||
4645 | BlockScopeRAII ForScope(Info); | ||||
4646 | if (FS->getInit()) { | ||||
4647 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||
4648 | if (ESR != ESR_Succeeded) { | ||||
4649 | if (ESR != ESR_Failed && !ForScope.destroy()) | ||||
4650 | return ESR_Failed; | ||||
4651 | return ESR; | ||||
4652 | } | ||||
4653 | } | ||||
4654 | while (true) { | ||||
4655 | BlockScopeRAII IterScope(Info); | ||||
4656 | bool Continue = true; | ||||
4657 | if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), | ||||
4658 | FS->getCond(), Continue)) | ||||
4659 | return ESR_Failed; | ||||
4660 | if (!Continue) | ||||
4661 | break; | ||||
4662 | |||||
4663 | EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||
4664 | if (ESR != ESR_Continue) { | ||||
4665 | if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) | ||||
4666 | return ESR_Failed; | ||||
4667 | return ESR; | ||||
4668 | } | ||||
4669 | |||||
4670 | if (FS->getInc()) { | ||||
4671 | FullExpressionRAII IncScope(Info); | ||||
4672 | if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) | ||||
4673 | return ESR_Failed; | ||||
4674 | } | ||||
4675 | |||||
4676 | if (!IterScope.destroy()) | ||||
4677 | return ESR_Failed; | ||||
4678 | } | ||||
4679 | return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
4680 | } | ||||
4681 | |||||
4682 | case Stmt::CXXForRangeStmtClass: { | ||||
4683 | const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); | ||||
4684 | BlockScopeRAII Scope(Info); | ||||
4685 | |||||
4686 | // Evaluate the init-statement if present. | ||||
4687 | if (FS->getInit()) { | ||||
4688 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); | ||||
4689 | if (ESR != ESR_Succeeded) { | ||||
4690 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4691 | return ESR_Failed; | ||||
4692 | return ESR; | ||||
4693 | } | ||||
4694 | } | ||||
4695 | |||||
4696 | // Initialize the __range variable. | ||||
4697 | EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); | ||||
4698 | if (ESR != ESR_Succeeded) { | ||||
4699 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4700 | return ESR_Failed; | ||||
4701 | return ESR; | ||||
4702 | } | ||||
4703 | |||||
4704 | // Create the __begin and __end iterators. | ||||
4705 | ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); | ||||
4706 | if (ESR != ESR_Succeeded) { | ||||
4707 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4708 | return ESR_Failed; | ||||
4709 | return ESR; | ||||
4710 | } | ||||
4711 | ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); | ||||
4712 | if (ESR != ESR_Succeeded) { | ||||
4713 | if (ESR != ESR_Failed && !Scope.destroy()) | ||||
4714 | return ESR_Failed; | ||||
4715 | return ESR; | ||||
4716 | } | ||||
4717 | |||||
4718 | while (true) { | ||||
4719 | // Condition: __begin != __end. | ||||
4720 | { | ||||
4721 | bool Continue = true; | ||||
4722 | FullExpressionRAII CondExpr(Info); | ||||
4723 | if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) | ||||
4724 | return ESR_Failed; | ||||
4725 | if (!Continue) | ||||
4726 | break; | ||||
4727 | } | ||||
4728 | |||||
4729 | // User's variable declaration, initialized by *__begin. | ||||
4730 | BlockScopeRAII InnerScope(Info); | ||||
4731 | ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); | ||||
4732 | if (ESR != ESR_Succeeded) { | ||||
4733 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||
4734 | return ESR_Failed; | ||||
4735 | return ESR; | ||||
4736 | } | ||||
4737 | |||||
4738 | // Loop body. | ||||
4739 | ESR = EvaluateLoopBody(Result, Info, FS->getBody()); | ||||
4740 | if (ESR != ESR_Continue) { | ||||
4741 | if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) | ||||
4742 | return ESR_Failed; | ||||
4743 | return ESR; | ||||
4744 | } | ||||
4745 | |||||
4746 | // Increment: ++__begin | ||||
4747 | if (!EvaluateIgnoredValue(Info, FS->getInc())) | ||||
4748 | return ESR_Failed; | ||||
4749 | |||||
4750 | if (!InnerScope.destroy()) | ||||
4751 | return ESR_Failed; | ||||
4752 | } | ||||
4753 | |||||
4754 | return Scope.destroy() ? ESR_Succeeded : ESR_Failed; | ||||
4755 | } | ||||
4756 | |||||
4757 | case Stmt::SwitchStmtClass: | ||||
4758 | return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); | ||||
4759 | |||||
4760 | case Stmt::ContinueStmtClass: | ||||
4761 | return ESR_Continue; | ||||
4762 | |||||
4763 | case Stmt::BreakStmtClass: | ||||
4764 | return ESR_Break; | ||||
4765 | |||||
4766 | case Stmt::LabelStmtClass: | ||||
4767 | return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); | ||||
4768 | |||||
4769 | case Stmt::AttributedStmtClass: | ||||
4770 | // As a general principle, C++11 attributes can be ignored without | ||||
4771 | // any semantic impact. | ||||
4772 | return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), | ||||
4773 | Case); | ||||
4774 | |||||
4775 | case Stmt::CaseStmtClass: | ||||
4776 | case Stmt::DefaultStmtClass: | ||||
4777 | return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); | ||||
4778 | case Stmt::CXXTryStmtClass: | ||||
4779 | // Evaluate try blocks by evaluating all sub statements. | ||||
4780 | return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); | ||||
4781 | } | ||||
4782 | } | ||||
4783 | |||||
4784 | /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial | ||||
4785 | /// default constructor. If so, we'll fold it whether or not it's marked as | ||||
4786 | /// constexpr. If it is marked as constexpr, we will never implicitly define it, | ||||
4787 | /// so we need special handling. | ||||
4788 | static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, | ||||
4789 | const CXXConstructorDecl *CD, | ||||
4790 | bool IsValueInitialization) { | ||||
4791 | if (!CD->isTrivial() || !CD->isDefaultConstructor()) | ||||
4792 | return false; | ||||
4793 | |||||
4794 | // Value-initialization does not call a trivial default constructor, so such a | ||||
4795 | // call is a core constant expression whether or not the constructor is | ||||
4796 | // constexpr. | ||||
4797 | if (!CD->isConstexpr() && !IsValueInitialization) { | ||||
4798 | if (Info.getLangOpts().CPlusPlus11) { | ||||
4799 | // FIXME: If DiagDecl is an implicitly-declared special member function, | ||||
4800 | // we should be much more explicit about why it's not constexpr. | ||||
4801 | Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) | ||||
4802 | << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; | ||||
4803 | Info.Note(CD->getLocation(), diag::note_declared_at); | ||||
4804 | } else { | ||||
4805 | Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); | ||||
4806 | } | ||||
4807 | } | ||||
4808 | return true; | ||||
4809 | } | ||||
4810 | |||||
4811 | /// CheckConstexprFunction - Check that a function can be called in a constant | ||||
4812 | /// expression. | ||||
4813 | static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, | ||||
4814 | const FunctionDecl *Declaration, | ||||
4815 | const FunctionDecl *Definition, | ||||
4816 | const Stmt *Body) { | ||||
4817 | // Potential constant expressions can contain calls to declared, but not yet | ||||
4818 | // defined, constexpr functions. | ||||
4819 | if (Info.checkingPotentialConstantExpression() && !Definition && | ||||
4820 | Declaration->isConstexpr()) | ||||
4821 | return false; | ||||
4822 | |||||
4823 | // Bail out if the function declaration itself is invalid. We will | ||||
4824 | // have produced a relevant diagnostic while parsing it, so just | ||||
4825 | // note the problematic sub-expression. | ||||
4826 | if (Declaration->isInvalidDecl()) { | ||||
4827 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
4828 | return false; | ||||
4829 | } | ||||
4830 | |||||
4831 | // DR1872: An instantiated virtual constexpr function can't be called in a | ||||
4832 | // constant expression (prior to C++20). We can still constant-fold such a | ||||
4833 | // call. | ||||
4834 | if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && | ||||
4835 | cast<CXXMethodDecl>(Declaration)->isVirtual()) | ||||
4836 | Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); | ||||
4837 | |||||
4838 | if (Definition && Definition->isInvalidDecl()) { | ||||
4839 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
4840 | return false; | ||||
4841 | } | ||||
4842 | |||||
4843 | // Can we evaluate this function call? | ||||
4844 | if (Definition && Definition->isConstexpr() && Body) | ||||
4845 | return true; | ||||
4846 | |||||
4847 | if (Info.getLangOpts().CPlusPlus11) { | ||||
4848 | const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; | ||||
4849 | |||||
4850 | // If this function is not constexpr because it is an inherited | ||||
4851 | // non-constexpr constructor, diagnose that directly. | ||||
4852 | auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); | ||||
4853 | if (CD && CD->isInheritingConstructor()) { | ||||
4854 | auto *Inherited = CD->getInheritedConstructor().getConstructor(); | ||||
4855 | if (!Inherited->isConstexpr()) | ||||
4856 | DiagDecl = CD = Inherited; | ||||
4857 | } | ||||
4858 | |||||
4859 | // FIXME: If DiagDecl is an implicitly-declared special member function | ||||
4860 | // or an inheriting constructor, we should be much more explicit about why | ||||
4861 | // it's not constexpr. | ||||
4862 | if (CD && CD->isInheritingConstructor()) | ||||
4863 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) | ||||
4864 | << CD->getInheritedConstructor().getConstructor()->getParent(); | ||||
4865 | else | ||||
4866 | Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) | ||||
4867 | << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; | ||||
4868 | Info.Note(DiagDecl->getLocation(), diag::note_declared_at); | ||||
4869 | } else { | ||||
4870 | Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); | ||||
4871 | } | ||||
4872 | return false; | ||||
4873 | } | ||||
4874 | |||||
4875 | namespace { | ||||
4876 | struct CheckDynamicTypeHandler { | ||||
4877 | AccessKinds AccessKind; | ||||
4878 | typedef bool result_type; | ||||
4879 | bool failed() { return false; } | ||||
4880 | bool found(APValue &Subobj, QualType SubobjType) { return true; } | ||||
4881 | bool found(APSInt &Value, QualType SubobjType) { return true; } | ||||
4882 | bool found(APFloat &Value, QualType SubobjType) { return true; } | ||||
4883 | }; | ||||
4884 | } // end anonymous namespace | ||||
4885 | |||||
4886 | /// Check that we can access the notional vptr of an object / determine its | ||||
4887 | /// dynamic type. | ||||
4888 | static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, | ||||
4889 | AccessKinds AK, bool Polymorphic) { | ||||
4890 | if (This.Designator.Invalid) | ||||
4891 | return false; | ||||
4892 | |||||
4893 | CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); | ||||
4894 | |||||
4895 | if (!Obj) | ||||
4896 | return false; | ||||
4897 | |||||
4898 | if (!Obj.Value) { | ||||
4899 | // The object is not usable in constant expressions, so we can't inspect | ||||
4900 | // its value to see if it's in-lifetime or what the active union members | ||||
4901 | // are. We can still check for a one-past-the-end lvalue. | ||||
4902 | if (This.Designator.isOnePastTheEnd() || | ||||
4903 | This.Designator.isMostDerivedAnUnsizedArray()) { | ||||
4904 | Info.FFDiag(E, This.Designator.isOnePastTheEnd() | ||||
4905 | ? diag::note_constexpr_access_past_end | ||||
4906 | : diag::note_constexpr_access_unsized_array) | ||||
4907 | << AK; | ||||
4908 | return false; | ||||
4909 | } else if (Polymorphic) { | ||||
4910 | // Conservatively refuse to perform a polymorphic operation if we would | ||||
4911 | // not be able to read a notional 'vptr' value. | ||||
4912 | APValue Val; | ||||
4913 | This.moveInto(Val); | ||||
4914 | QualType StarThisType = | ||||
4915 | Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); | ||||
4916 | Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) | ||||
4917 | << AK << Val.getAsString(Info.Ctx, StarThisType); | ||||
4918 | return false; | ||||
4919 | } | ||||
4920 | return true; | ||||
4921 | } | ||||
4922 | |||||
4923 | CheckDynamicTypeHandler Handler{AK}; | ||||
4924 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||
4925 | } | ||||
4926 | |||||
4927 | /// Check that the pointee of the 'this' pointer in a member function call is | ||||
4928 | /// either within its lifetime or in its period of construction or destruction. | ||||
4929 | static bool | ||||
4930 | checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, | ||||
4931 | const LValue &This, | ||||
4932 | const CXXMethodDecl *NamedMember) { | ||||
4933 | return checkDynamicType( | ||||
4934 | Info, E, This, | ||||
4935 | isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); | ||||
4936 | } | ||||
4937 | |||||
4938 | struct DynamicType { | ||||
4939 | /// The dynamic class type of the object. | ||||
4940 | const CXXRecordDecl *Type; | ||||
4941 | /// The corresponding path length in the lvalue. | ||||
4942 | unsigned PathLength; | ||||
4943 | }; | ||||
4944 | |||||
4945 | static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, | ||||
4946 | unsigned PathLength) { | ||||
4947 | assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=((PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length" ) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4948, __PRETTY_FUNCTION__)) | ||||
4948 | Designator.Entries.size() && "invalid path length")((PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && "invalid path length" ) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 4948, __PRETTY_FUNCTION__)); | ||||
4949 | return (PathLength == Designator.MostDerivedPathLength) | ||||
4950 | ? Designator.MostDerivedType->getAsCXXRecordDecl() | ||||
4951 | : getAsBaseClass(Designator.Entries[PathLength - 1]); | ||||
4952 | } | ||||
4953 | |||||
4954 | /// Determine the dynamic type of an object. | ||||
4955 | static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, | ||||
4956 | LValue &This, AccessKinds AK) { | ||||
4957 | // If we don't have an lvalue denoting an object of class type, there is no | ||||
4958 | // meaningful dynamic type. (We consider objects of non-class type to have no | ||||
4959 | // dynamic type.) | ||||
4960 | if (!checkDynamicType(Info, E, This, AK, true)) | ||||
4961 | return None; | ||||
4962 | |||||
4963 | // Refuse to compute a dynamic type in the presence of virtual bases. This | ||||
4964 | // shouldn't happen other than in constant-folding situations, since literal | ||||
4965 | // types can't have virtual bases. | ||||
4966 | // | ||||
4967 | // Note that consumers of DynamicType assume that the type has no virtual | ||||
4968 | // bases, and will need modifications if this restriction is relaxed. | ||||
4969 | const CXXRecordDecl *Class = | ||||
4970 | This.Designator.MostDerivedType->getAsCXXRecordDecl(); | ||||
4971 | if (!Class || Class->getNumVBases()) { | ||||
4972 | Info.FFDiag(E); | ||||
4973 | return None; | ||||
4974 | } | ||||
4975 | |||||
4976 | // FIXME: For very deep class hierarchies, it might be beneficial to use a | ||||
4977 | // binary search here instead. But the overwhelmingly common case is that | ||||
4978 | // we're not in the middle of a constructor, so it probably doesn't matter | ||||
4979 | // in practice. | ||||
4980 | ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; | ||||
4981 | for (unsigned PathLength = This.Designator.MostDerivedPathLength; | ||||
4982 | PathLength <= Path.size(); ++PathLength) { | ||||
4983 | switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), | ||||
4984 | Path.slice(0, PathLength))) { | ||||
4985 | case ConstructionPhase::Bases: | ||||
4986 | case ConstructionPhase::DestroyingBases: | ||||
4987 | // We're constructing or destroying a base class. This is not the dynamic | ||||
4988 | // type. | ||||
4989 | break; | ||||
4990 | |||||
4991 | case ConstructionPhase::None: | ||||
4992 | case ConstructionPhase::AfterBases: | ||||
4993 | case ConstructionPhase::Destroying: | ||||
4994 | // We've finished constructing the base classes and not yet started | ||||
4995 | // destroying them again, so this is the dynamic type. | ||||
4996 | return DynamicType{getBaseClassType(This.Designator, PathLength), | ||||
4997 | PathLength}; | ||||
4998 | } | ||||
4999 | } | ||||
5000 | |||||
5001 | // CWG issue 1517: we're constructing a base class of the object described by | ||||
5002 | // 'This', so that object has not yet begun its period of construction and | ||||
5003 | // any polymorphic operation on it results in undefined behavior. | ||||
5004 | Info.FFDiag(E); | ||||
5005 | return None; | ||||
5006 | } | ||||
5007 | |||||
5008 | /// Perform virtual dispatch. | ||||
5009 | static const CXXMethodDecl *HandleVirtualDispatch( | ||||
5010 | EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, | ||||
5011 | llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { | ||||
5012 | Optional<DynamicType> DynType = ComputeDynamicType( | ||||
5013 | Info, E, This, | ||||
5014 | isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); | ||||
5015 | if (!DynType) | ||||
5016 | return nullptr; | ||||
5017 | |||||
5018 | // Find the final overrider. It must be declared in one of the classes on the | ||||
5019 | // path from the dynamic type to the static type. | ||||
5020 | // FIXME: If we ever allow literal types to have virtual base classes, that | ||||
5021 | // won't be true. | ||||
5022 | const CXXMethodDecl *Callee = Found; | ||||
5023 | unsigned PathLength = DynType->PathLength; | ||||
5024 | for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { | ||||
5025 | const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); | ||||
5026 | const CXXMethodDecl *Overrider = | ||||
5027 | Found->getCorrespondingMethodDeclaredInClass(Class, false); | ||||
5028 | if (Overrider) { | ||||
5029 | Callee = Overrider; | ||||
5030 | break; | ||||
5031 | } | ||||
5032 | } | ||||
5033 | |||||
5034 | // C++2a [class.abstract]p6: | ||||
5035 | // the effect of making a virtual call to a pure virtual function [...] is | ||||
5036 | // undefined | ||||
5037 | if (Callee->isPure()) { | ||||
5038 | Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; | ||||
5039 | Info.Note(Callee->getLocation(), diag::note_declared_at); | ||||
5040 | return nullptr; | ||||
5041 | } | ||||
5042 | |||||
5043 | // If necessary, walk the rest of the path to determine the sequence of | ||||
5044 | // covariant adjustment steps to apply. | ||||
5045 | if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), | ||||
5046 | Found->getReturnType())) { | ||||
5047 | CovariantAdjustmentPath.push_back(Callee->getReturnType()); | ||||
5048 | for (unsigned CovariantPathLength = PathLength + 1; | ||||
5049 | CovariantPathLength != This.Designator.Entries.size(); | ||||
5050 | ++CovariantPathLength) { | ||||
5051 | const CXXRecordDecl *NextClass = | ||||
5052 | getBaseClassType(This.Designator, CovariantPathLength); | ||||
5053 | const CXXMethodDecl *Next = | ||||
5054 | Found->getCorrespondingMethodDeclaredInClass(NextClass, false); | ||||
5055 | if (Next && !Info.Ctx.hasSameUnqualifiedType( | ||||
5056 | Next->getReturnType(), CovariantAdjustmentPath.back())) | ||||
5057 | CovariantAdjustmentPath.push_back(Next->getReturnType()); | ||||
5058 | } | ||||
5059 | if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), | ||||
5060 | CovariantAdjustmentPath.back())) | ||||
5061 | CovariantAdjustmentPath.push_back(Found->getReturnType()); | ||||
5062 | } | ||||
5063 | |||||
5064 | // Perform 'this' adjustment. | ||||
5065 | if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) | ||||
5066 | return nullptr; | ||||
5067 | |||||
5068 | return Callee; | ||||
5069 | } | ||||
5070 | |||||
5071 | /// Perform the adjustment from a value returned by a virtual function to | ||||
5072 | /// a value of the statically expected type, which may be a pointer or | ||||
5073 | /// reference to a base class of the returned type. | ||||
5074 | static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, | ||||
5075 | APValue &Result, | ||||
5076 | ArrayRef<QualType> Path) { | ||||
5077 | assert(Result.isLValue() &&((Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5078, __PRETTY_FUNCTION__)) | ||||
5078 | "unexpected kind of APValue for covariant return")((Result.isLValue() && "unexpected kind of APValue for covariant return" ) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5078, __PRETTY_FUNCTION__)); | ||||
5079 | if (Result.isNullPointer()) | ||||
5080 | return true; | ||||
5081 | |||||
5082 | LValue LVal; | ||||
5083 | LVal.setFrom(Info.Ctx, Result); | ||||
5084 | |||||
5085 | const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); | ||||
5086 | for (unsigned I = 1; I != Path.size(); ++I) { | ||||
5087 | const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); | ||||
5088 | assert(OldClass && NewClass && "unexpected kind of covariant return")((OldClass && NewClass && "unexpected kind of covariant return" ) ? static_cast<void> (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5088, __PRETTY_FUNCTION__)); | ||||
5089 | if (OldClass != NewClass && | ||||
5090 | !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) | ||||
5091 | return false; | ||||
5092 | OldClass = NewClass; | ||||
5093 | } | ||||
5094 | |||||
5095 | LVal.moveInto(Result); | ||||
5096 | return true; | ||||
5097 | } | ||||
5098 | |||||
5099 | /// Determine whether \p Base, which is known to be a direct base class of | ||||
5100 | /// \p Derived, is a public base class. | ||||
5101 | static bool isBaseClassPublic(const CXXRecordDecl *Derived, | ||||
5102 | const CXXRecordDecl *Base) { | ||||
5103 | for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { | ||||
5104 | auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); | ||||
5105 | if (BaseClass && declaresSameEntity(BaseClass, Base)) | ||||
5106 | return BaseSpec.getAccessSpecifier() == AS_public; | ||||
5107 | } | ||||
5108 | llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5108); | ||||
5109 | } | ||||
5110 | |||||
5111 | /// Apply the given dynamic cast operation on the provided lvalue. | ||||
5112 | /// | ||||
5113 | /// This implements the hard case of dynamic_cast, requiring a "runtime check" | ||||
5114 | /// to find a suitable target subobject. | ||||
5115 | static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, | ||||
5116 | LValue &Ptr) { | ||||
5117 | // We can't do anything with a non-symbolic pointer value. | ||||
5118 | SubobjectDesignator &D = Ptr.Designator; | ||||
5119 | if (D.Invalid) | ||||
5120 | return false; | ||||
5121 | |||||
5122 | // C++ [expr.dynamic.cast]p6: | ||||
5123 | // If v is a null pointer value, the result is a null pointer value. | ||||
5124 | if (Ptr.isNullPointer() && !E->isGLValue()) | ||||
5125 | return true; | ||||
5126 | |||||
5127 | // For all the other cases, we need the pointer to point to an object within | ||||
5128 | // its lifetime / period of construction / destruction, and we need to know | ||||
5129 | // its dynamic type. | ||||
5130 | Optional<DynamicType> DynType = | ||||
5131 | ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); | ||||
5132 | if (!DynType) | ||||
5133 | return false; | ||||
5134 | |||||
5135 | // C++ [expr.dynamic.cast]p7: | ||||
5136 | // If T is "pointer to cv void", then the result is a pointer to the most | ||||
5137 | // derived object | ||||
5138 | if (E->getType()->isVoidPointerType()) | ||||
5139 | return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); | ||||
5140 | |||||
5141 | const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); | ||||
5142 | assert(C && "dynamic_cast target is not void pointer nor class")((C && "dynamic_cast target is not void pointer nor class" ) ? static_cast<void> (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5142, __PRETTY_FUNCTION__)); | ||||
5143 | CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); | ||||
5144 | |||||
5145 | auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { | ||||
5146 | // C++ [expr.dynamic.cast]p9: | ||||
5147 | if (!E->isGLValue()) { | ||||
5148 | // The value of a failed cast to pointer type is the null pointer value | ||||
5149 | // of the required result type. | ||||
5150 | auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); | ||||
5151 | Ptr.setNull(E->getType(), TargetVal); | ||||
5152 | return true; | ||||
5153 | } | ||||
5154 | |||||
5155 | // A failed cast to reference type throws [...] std::bad_cast. | ||||
5156 | unsigned DiagKind; | ||||
5157 | if (!Paths && (declaresSameEntity(DynType->Type, C) || | ||||
5158 | DynType->Type->isDerivedFrom(C))) | ||||
5159 | DiagKind = 0; | ||||
5160 | else if (!Paths || Paths->begin() == Paths->end()) | ||||
5161 | DiagKind = 1; | ||||
5162 | else if (Paths->isAmbiguous(CQT)) | ||||
5163 | DiagKind = 2; | ||||
5164 | else { | ||||
5165 | assert(Paths->front().Access != AS_public && "why did the cast fail?")((Paths->front().Access != AS_public && "why did the cast fail?" ) ? static_cast<void> (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5165, __PRETTY_FUNCTION__)); | ||||
5166 | DiagKind = 3; | ||||
5167 | } | ||||
5168 | Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) | ||||
5169 | << DiagKind << Ptr.Designator.getType(Info.Ctx) | ||||
5170 | << Info.Ctx.getRecordType(DynType->Type) | ||||
5171 | << E->getType().getUnqualifiedType(); | ||||
5172 | return false; | ||||
5173 | }; | ||||
5174 | |||||
5175 | // Runtime check, phase 1: | ||||
5176 | // Walk from the base subobject towards the derived object looking for the | ||||
5177 | // target type. | ||||
5178 | for (int PathLength = Ptr.Designator.Entries.size(); | ||||
5179 | PathLength >= (int)DynType->PathLength; --PathLength) { | ||||
5180 | const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); | ||||
5181 | if (declaresSameEntity(Class, C)) | ||||
5182 | return CastToDerivedClass(Info, E, Ptr, Class, PathLength); | ||||
5183 | // We can only walk across public inheritance edges. | ||||
5184 | if (PathLength > (int)DynType->PathLength && | ||||
5185 | !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), | ||||
5186 | Class)) | ||||
5187 | return RuntimeCheckFailed(nullptr); | ||||
5188 | } | ||||
5189 | |||||
5190 | // Runtime check, phase 2: | ||||
5191 | // Search the dynamic type for an unambiguous public base of type C. | ||||
5192 | CXXBasePaths Paths(/*FindAmbiguities=*/true, | ||||
5193 | /*RecordPaths=*/true, /*DetectVirtual=*/false); | ||||
5194 | if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && | ||||
5195 | Paths.front().Access == AS_public) { | ||||
5196 | // Downcast to the dynamic type... | ||||
5197 | if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) | ||||
5198 | return false; | ||||
5199 | // ... then upcast to the chosen base class subobject. | ||||
5200 | for (CXXBasePathElement &Elem : Paths.front()) | ||||
5201 | if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) | ||||
5202 | return false; | ||||
5203 | return true; | ||||
5204 | } | ||||
5205 | |||||
5206 | // Otherwise, the runtime check fails. | ||||
5207 | return RuntimeCheckFailed(&Paths); | ||||
5208 | } | ||||
5209 | |||||
5210 | namespace { | ||||
5211 | struct StartLifetimeOfUnionMemberHandler { | ||||
5212 | const FieldDecl *Field; | ||||
5213 | |||||
5214 | static const AccessKinds AccessKind = AK_Assign; | ||||
5215 | |||||
5216 | typedef bool result_type; | ||||
5217 | bool failed() { return false; } | ||||
5218 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
5219 | // We are supposed to perform no initialization but begin the lifetime of | ||||
5220 | // the object. We interpret that as meaning to do what default | ||||
5221 | // initialization of the object would do if all constructors involved were | ||||
5222 | // trivial: | ||||
5223 | // * All base, non-variant member, and array element subobjects' lifetimes | ||||
5224 | // begin | ||||
5225 | // * No variant members' lifetimes begin | ||||
5226 | // * All scalar subobjects whose lifetimes begin have indeterminate values | ||||
5227 | assert(SubobjType->isUnionType())((SubobjType->isUnionType()) ? static_cast<void> (0) : __assert_fail ("SubobjType->isUnionType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5227, __PRETTY_FUNCTION__)); | ||||
5228 | if (!declaresSameEntity(Subobj.getUnionField(), Field) || | ||||
5229 | !Subobj.getUnionValue().hasValue()) | ||||
5230 | Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); | ||||
5231 | return true; | ||||
5232 | } | ||||
5233 | bool found(APSInt &Value, QualType SubobjType) { | ||||
5234 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5234); | ||||
5235 | } | ||||
5236 | bool found(APFloat &Value, QualType SubobjType) { | ||||
5237 | llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5237); | ||||
5238 | } | ||||
5239 | }; | ||||
5240 | } // end anonymous namespace | ||||
5241 | |||||
5242 | const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; | ||||
5243 | |||||
5244 | /// Handle a builtin simple-assignment or a call to a trivial assignment | ||||
5245 | /// operator whose left-hand side might involve a union member access. If it | ||||
5246 | /// does, implicitly start the lifetime of any accessed union elements per | ||||
5247 | /// C++20 [class.union]5. | ||||
5248 | static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, | ||||
5249 | const LValue &LHS) { | ||||
5250 | if (LHS.InvalidBase || LHS.Designator.Invalid) | ||||
5251 | return false; | ||||
5252 | |||||
5253 | llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; | ||||
5254 | // C++ [class.union]p5: | ||||
5255 | // define the set S(E) of subexpressions of E as follows: | ||||
5256 | unsigned PathLength = LHS.Designator.Entries.size(); | ||||
5257 | for (const Expr *E = LHSExpr; E != nullptr;) { | ||||
5258 | // -- If E is of the form A.B, S(E) contains the elements of S(A)... | ||||
5259 | if (auto *ME = dyn_cast<MemberExpr>(E)) { | ||||
5260 | auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||
5261 | // Note that we can't implicitly start the lifetime of a reference, | ||||
5262 | // so we don't need to proceed any further if we reach one. | ||||
5263 | if (!FD || FD->getType()->isReferenceType()) | ||||
5264 | break; | ||||
5265 | |||||
5266 | // ... and also contains A.B if B names a union member | ||||
5267 | if (FD->getParent()->isUnion()) | ||||
5268 | UnionPathLengths.push_back({PathLength - 1, FD}); | ||||
5269 | |||||
5270 | E = ME->getBase(); | ||||
5271 | --PathLength; | ||||
5272 | assert(declaresSameEntity(FD,((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)) | ||||
5273 | LHS.Designator.Entries[PathLength]((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)) | ||||
5274 | .getAsBaseOrMember().getPointer()))((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] . getAsBaseOrMember().getPointer())) ? static_cast<void> ( 0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5274, __PRETTY_FUNCTION__)); | ||||
5275 | |||||
5276 | // -- If E is of the form A[B] and is interpreted as a built-in array | ||||
5277 | // subscripting operator, S(E) is [S(the array operand, if any)]. | ||||
5278 | } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { | ||||
5279 | // Step over an ArrayToPointerDecay implicit cast. | ||||
5280 | auto *Base = ASE->getBase()->IgnoreImplicit(); | ||||
5281 | if (!Base->getType()->isArrayType()) | ||||
5282 | break; | ||||
5283 | |||||
5284 | E = Base; | ||||
5285 | --PathLength; | ||||
5286 | |||||
5287 | } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { | ||||
5288 | // Step over a derived-to-base conversion. | ||||
5289 | E = ICE->getSubExpr(); | ||||
5290 | if (ICE->getCastKind() == CK_NoOp) | ||||
5291 | continue; | ||||
5292 | if (ICE->getCastKind() != CK_DerivedToBase && | ||||
5293 | ICE->getCastKind() != CK_UncheckedDerivedToBase) | ||||
5294 | break; | ||||
5295 | // Walk path backwards as we walk up from the base to the derived class. | ||||
5296 | for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { | ||||
5297 | --PathLength; | ||||
5298 | (void)Elt; | ||||
5299 | assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)) | ||||
5300 | LHS.Designator.Entries[PathLength]((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)) | ||||
5301 | .getAsBaseOrMember().getPointer()))((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl (), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer ())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5301, __PRETTY_FUNCTION__)); | ||||
5302 | } | ||||
5303 | |||||
5304 | // -- Otherwise, S(E) is empty. | ||||
5305 | } else { | ||||
5306 | break; | ||||
5307 | } | ||||
5308 | } | ||||
5309 | |||||
5310 | // Common case: no unions' lifetimes are started. | ||||
5311 | if (UnionPathLengths.empty()) | ||||
5312 | return true; | ||||
5313 | |||||
5314 | // if modification of X [would access an inactive union member], an object | ||||
5315 | // of the type of X is implicitly created | ||||
5316 | CompleteObject Obj = | ||||
5317 | findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); | ||||
5318 | if (!Obj) | ||||
5319 | return false; | ||||
5320 | for (std::pair<unsigned, const FieldDecl *> LengthAndField : | ||||
5321 | llvm::reverse(UnionPathLengths)) { | ||||
5322 | // Form a designator for the union object. | ||||
5323 | SubobjectDesignator D = LHS.Designator; | ||||
5324 | D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); | ||||
5325 | |||||
5326 | StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; | ||||
5327 | if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) | ||||
5328 | return false; | ||||
5329 | } | ||||
5330 | |||||
5331 | return true; | ||||
5332 | } | ||||
5333 | |||||
5334 | /// Determine if a class has any fields that might need to be copied by a | ||||
5335 | /// trivial copy or move operation. | ||||
5336 | static bool hasFields(const CXXRecordDecl *RD) { | ||||
5337 | if (!RD || RD->isEmpty()) | ||||
5338 | return false; | ||||
5339 | for (auto *FD : RD->fields()) { | ||||
5340 | if (FD->isUnnamedBitfield()) | ||||
5341 | continue; | ||||
5342 | return true; | ||||
5343 | } | ||||
5344 | for (auto &Base : RD->bases()) | ||||
5345 | if (hasFields(Base.getType()->getAsCXXRecordDecl())) | ||||
5346 | return true; | ||||
5347 | return false; | ||||
5348 | } | ||||
5349 | |||||
5350 | namespace { | ||||
5351 | typedef SmallVector<APValue, 8> ArgVector; | ||||
5352 | } | ||||
5353 | |||||
5354 | /// EvaluateArgs - Evaluate the arguments to a function call. | ||||
5355 | static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, | ||||
5356 | EvalInfo &Info, const FunctionDecl *Callee) { | ||||
5357 | bool Success = true; | ||||
5358 | llvm::SmallBitVector ForbiddenNullArgs; | ||||
5359 | if (Callee->hasAttr<NonNullAttr>()) { | ||||
5360 | ForbiddenNullArgs.resize(Args.size()); | ||||
5361 | for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { | ||||
5362 | if (!Attr->args_size()) { | ||||
5363 | ForbiddenNullArgs.set(); | ||||
5364 | break; | ||||
5365 | } else | ||||
5366 | for (auto Idx : Attr->args()) { | ||||
5367 | unsigned ASTIdx = Idx.getASTIndex(); | ||||
5368 | if (ASTIdx >= Args.size()) | ||||
5369 | continue; | ||||
5370 | ForbiddenNullArgs[ASTIdx] = 1; | ||||
5371 | } | ||||
5372 | } | ||||
5373 | } | ||||
5374 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | ||||
5375 | I != E; ++I) { | ||||
5376 | if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { | ||||
5377 | // If we're checking for a potential constant expression, evaluate all | ||||
5378 | // initializers even if some of them fail. | ||||
5379 | if (!Info.noteFailure()) | ||||
5380 | return false; | ||||
5381 | Success = false; | ||||
5382 | } else if (!ForbiddenNullArgs.empty() && | ||||
5383 | ForbiddenNullArgs[I - Args.begin()] && | ||||
5384 | ArgValues[I - Args.begin()].isNullPointer()) { | ||||
5385 | Info.CCEDiag(*I, diag::note_non_null_attribute_failed); | ||||
5386 | if (!Info.noteFailure()) | ||||
5387 | return false; | ||||
5388 | Success = false; | ||||
5389 | } | ||||
5390 | } | ||||
5391 | return Success; | ||||
5392 | } | ||||
5393 | |||||
5394 | /// Evaluate a function call. | ||||
5395 | static bool HandleFunctionCall(SourceLocation CallLoc, | ||||
5396 | const FunctionDecl *Callee, const LValue *This, | ||||
5397 | ArrayRef<const Expr*> Args, const Stmt *Body, | ||||
5398 | EvalInfo &Info, APValue &Result, | ||||
5399 | const LValue *ResultSlot) { | ||||
5400 | ArgVector ArgValues(Args.size()); | ||||
5401 | if (!EvaluateArgs(Args, ArgValues, Info, Callee)) | ||||
5402 | return false; | ||||
5403 | |||||
5404 | if (!Info.CheckCallLimit(CallLoc)) | ||||
5405 | return false; | ||||
5406 | |||||
5407 | CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); | ||||
5408 | |||||
5409 | // For a trivial copy or move assignment, perform an APValue copy. This is | ||||
5410 | // essential for unions, where the operations performed by the assignment | ||||
5411 | // operator cannot be represented as statements. | ||||
5412 | // | ||||
5413 | // Skip this for non-union classes with no fields; in that case, the defaulted | ||||
5414 | // copy/move does not actually read the object. | ||||
5415 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||
5416 | if (MD && MD->isDefaulted() && | ||||
5417 | (MD->getParent()->isUnion() || | ||||
5418 | (MD->isTrivial() && hasFields(MD->getParent())))) { | ||||
5419 | assert(This &&((This && (MD->isCopyAssignmentOperator() || MD-> isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5420, __PRETTY_FUNCTION__)) | ||||
5420 | (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))((This && (MD->isCopyAssignmentOperator() || MD-> isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail ("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5420, __PRETTY_FUNCTION__)); | ||||
5421 | LValue RHS; | ||||
5422 | RHS.setFrom(Info.Ctx, ArgValues[0]); | ||||
5423 | APValue RHSValue; | ||||
5424 | if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, | ||||
5425 | RHSValue, MD->getParent()->isUnion())) | ||||
5426 | return false; | ||||
5427 | if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && | ||||
5428 | !HandleUnionActiveMemberChange(Info, Args[0], *This)) | ||||
5429 | return false; | ||||
5430 | if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), | ||||
5431 | RHSValue)) | ||||
5432 | return false; | ||||
5433 | This->moveInto(Result); | ||||
5434 | return true; | ||||
5435 | } else if (MD && isLambdaCallOperator(MD)) { | ||||
5436 | // We're in a lambda; determine the lambda capture field maps unless we're | ||||
5437 | // just constexpr checking a lambda's call operator. constexpr checking is | ||||
5438 | // done before the captures have been added to the closure object (unless | ||||
5439 | // we're inferring constexpr-ness), so we don't have access to them in this | ||||
5440 | // case. But since we don't need the captures to constexpr check, we can | ||||
5441 | // just ignore them. | ||||
5442 | if (!Info.checkingPotentialConstantExpression()) | ||||
5443 | MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, | ||||
5444 | Frame.LambdaThisCaptureField); | ||||
5445 | } | ||||
5446 | |||||
5447 | StmtResult Ret = {Result, ResultSlot}; | ||||
5448 | EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); | ||||
5449 | if (ESR == ESR_Succeeded) { | ||||
5450 | if (Callee->getReturnType()->isVoidType()) | ||||
5451 | return true; | ||||
5452 | Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); | ||||
5453 | } | ||||
5454 | return ESR == ESR_Returned; | ||||
5455 | } | ||||
5456 | |||||
5457 | /// Evaluate a constructor call. | ||||
5458 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||
5459 | APValue *ArgValues, | ||||
5460 | const CXXConstructorDecl *Definition, | ||||
5461 | EvalInfo &Info, APValue &Result) { | ||||
5462 | SourceLocation CallLoc = E->getExprLoc(); | ||||
5463 | if (!Info.CheckCallLimit(CallLoc)) | ||||
5464 | return false; | ||||
5465 | |||||
5466 | const CXXRecordDecl *RD = Definition->getParent(); | ||||
5467 | if (RD->getNumVBases()) { | ||||
5468 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||
5469 | return false; | ||||
5470 | } | ||||
5471 | |||||
5472 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||
5473 | Info, | ||||
5474 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||
5475 | RD->getNumBases()); | ||||
5476 | CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); | ||||
5477 | |||||
5478 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||
5479 | // wasteful. | ||||
5480 | APValue RetVal; | ||||
5481 | StmtResult Ret = {RetVal, nullptr}; | ||||
5482 | |||||
5483 | // If it's a delegating constructor, delegate. | ||||
5484 | if (Definition->isDelegatingConstructor()) { | ||||
5485 | CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); | ||||
5486 | { | ||||
5487 | FullExpressionRAII InitScope(Info); | ||||
5488 | if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || | ||||
5489 | !InitScope.destroy()) | ||||
5490 | return false; | ||||
5491 | } | ||||
5492 | return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; | ||||
5493 | } | ||||
5494 | |||||
5495 | // For a trivial copy or move constructor, perform an APValue copy. This is | ||||
5496 | // essential for unions (or classes with anonymous union members), where the | ||||
5497 | // operations performed by the constructor cannot be represented by | ||||
5498 | // ctor-initializers. | ||||
5499 | // | ||||
5500 | // Skip this for empty non-union classes; we should not perform an | ||||
5501 | // lvalue-to-rvalue conversion on them because their copy constructor does not | ||||
5502 | // actually read them. | ||||
5503 | if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && | ||||
5504 | (Definition->getParent()->isUnion() || | ||||
5505 | (Definition->isTrivial() && hasFields(Definition->getParent())))) { | ||||
5506 | LValue RHS; | ||||
5507 | RHS.setFrom(Info.Ctx, ArgValues[0]); | ||||
5508 | return handleLValueToRValueConversion( | ||||
5509 | Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), | ||||
5510 | RHS, Result, Definition->getParent()->isUnion()); | ||||
5511 | } | ||||
5512 | |||||
5513 | // Reserve space for the struct members. | ||||
5514 | if (!RD->isUnion() && !Result.hasValue()) | ||||
5515 | Result = APValue(APValue::UninitStruct(), RD->getNumBases(), | ||||
5516 | std::distance(RD->field_begin(), RD->field_end())); | ||||
5517 | |||||
5518 | if (RD->isInvalidDecl()) return false; | ||||
5519 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
5520 | |||||
5521 | // A scope for temporaries lifetime-extended by reference members. | ||||
5522 | BlockScopeRAII LifetimeExtendedScope(Info); | ||||
5523 | |||||
5524 | bool Success = true; | ||||
5525 | unsigned BasesSeen = 0; | ||||
5526 | #ifndef NDEBUG | ||||
5527 | CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); | ||||
5528 | #endif | ||||
5529 | CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); | ||||
5530 | auto SkipToField = [&](FieldDecl *FD, bool Indirect) { | ||||
5531 | // We might be initializing the same field again if this is an indirect | ||||
5532 | // field initialization. | ||||
5533 | if (FieldIt == RD->field_end() || | ||||
5534 | FieldIt->getFieldIndex() > FD->getFieldIndex()) { | ||||
5535 | assert(Indirect && "fields out of order?")((Indirect && "fields out of order?") ? static_cast< void> (0) : __assert_fail ("Indirect && \"fields out of order?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5535, __PRETTY_FUNCTION__)); | ||||
5536 | return; | ||||
5537 | } | ||||
5538 | |||||
5539 | // Default-initialize any fields with no explicit initializer. | ||||
5540 | for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { | ||||
5541 | assert(FieldIt != RD->field_end() && "missing field?")((FieldIt != RD->field_end() && "missing field?") ? static_cast<void> (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5541, __PRETTY_FUNCTION__)); | ||||
5542 | if (!FieldIt->isUnnamedBitfield()) | ||||
5543 | Result.getStructField(FieldIt->getFieldIndex()) = | ||||
5544 | getDefaultInitValue(FieldIt->getType()); | ||||
5545 | } | ||||
5546 | ++FieldIt; | ||||
5547 | }; | ||||
5548 | for (const auto *I : Definition->inits()) { | ||||
5549 | LValue Subobject = This; | ||||
5550 | LValue SubobjectParent = This; | ||||
5551 | APValue *Value = &Result; | ||||
5552 | |||||
5553 | // Determine the subobject to initialize. | ||||
5554 | FieldDecl *FD = nullptr; | ||||
5555 | if (I->isBaseInitializer()) { | ||||
5556 | QualType BaseType(I->getBaseClass(), 0); | ||||
5557 | #ifndef NDEBUG | ||||
5558 | // Non-virtual base classes are initialized in the order in the class | ||||
5559 | // definition. We have already checked for virtual base classes. | ||||
5560 | assert(!BaseIt->isVirtual() && "virtual base for literal type")((!BaseIt->isVirtual() && "virtual base for literal type" ) ? static_cast<void> (0) : __assert_fail ("!BaseIt->isVirtual() && \"virtual base for literal type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5560, __PRETTY_FUNCTION__)); | ||||
5561 | assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && "base class initializers not in expected order") ? static_cast <void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5562, __PRETTY_FUNCTION__)) | ||||
5562 | "base class initializers not in expected order")((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && "base class initializers not in expected order") ? static_cast <void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5562, __PRETTY_FUNCTION__)); | ||||
5563 | ++BaseIt; | ||||
5564 | #endif | ||||
5565 | if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, | ||||
5566 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||
5567 | return false; | ||||
5568 | Value = &Result.getStructBase(BasesSeen++); | ||||
5569 | } else if ((FD = I->getMember())) { | ||||
5570 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) | ||||
5571 | return false; | ||||
5572 | if (RD->isUnion()) { | ||||
5573 | Result = APValue(FD); | ||||
5574 | Value = &Result.getUnionValue(); | ||||
5575 | } else { | ||||
5576 | SkipToField(FD, false); | ||||
5577 | Value = &Result.getStructField(FD->getFieldIndex()); | ||||
5578 | } | ||||
5579 | } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { | ||||
5580 | // Walk the indirect field decl's chain to find the object to initialize, | ||||
5581 | // and make sure we've initialized every step along it. | ||||
5582 | auto IndirectFieldChain = IFD->chain(); | ||||
5583 | for (auto *C : IndirectFieldChain) { | ||||
5584 | FD = cast<FieldDecl>(C); | ||||
5585 | CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); | ||||
5586 | // Switch the union field if it differs. This happens if we had | ||||
5587 | // preceding zero-initialization, and we're now initializing a union | ||||
5588 | // subobject other than the first. | ||||
5589 | // FIXME: In this case, the values of the other subobjects are | ||||
5590 | // specified, since zero-initialization sets all padding bits to zero. | ||||
5591 | if (!Value->hasValue() || | ||||
5592 | (Value->isUnion() && Value->getUnionField() != FD)) { | ||||
5593 | if (CD->isUnion()) | ||||
5594 | *Value = APValue(FD); | ||||
5595 | else | ||||
5596 | // FIXME: This immediately starts the lifetime of all members of an | ||||
5597 | // anonymous struct. It would be preferable to strictly start member | ||||
5598 | // lifetime in initialization order. | ||||
5599 | *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD)); | ||||
5600 | } | ||||
5601 | // Store Subobject as its parent before updating it for the last element | ||||
5602 | // in the chain. | ||||
5603 | if (C == IndirectFieldChain.back()) | ||||
5604 | SubobjectParent = Subobject; | ||||
5605 | if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) | ||||
5606 | return false; | ||||
5607 | if (CD->isUnion()) | ||||
5608 | Value = &Value->getUnionValue(); | ||||
5609 | else { | ||||
5610 | if (C == IndirectFieldChain.front() && !RD->isUnion()) | ||||
5611 | SkipToField(FD, true); | ||||
5612 | Value = &Value->getStructField(FD->getFieldIndex()); | ||||
5613 | } | ||||
5614 | } | ||||
5615 | } else { | ||||
5616 | llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5616); | ||||
5617 | } | ||||
5618 | |||||
5619 | // Need to override This for implicit field initializers as in this case | ||||
5620 | // This refers to innermost anonymous struct/union containing initializer, | ||||
5621 | // not to currently constructed class. | ||||
5622 | const Expr *Init = I->getInit(); | ||||
5623 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, | ||||
5624 | isa<CXXDefaultInitExpr>(Init)); | ||||
5625 | FullExpressionRAII InitScope(Info); | ||||
5626 | if (!EvaluateInPlace(*Value, Info, Subobject, Init) || | ||||
5627 | (FD && FD->isBitField() && | ||||
5628 | !truncateBitfieldValue(Info, Init, *Value, FD))) { | ||||
5629 | // If we're checking for a potential constant expression, evaluate all | ||||
5630 | // initializers even if some of them fail. | ||||
5631 | if (!Info.noteFailure()) | ||||
5632 | return false; | ||||
5633 | Success = false; | ||||
5634 | } | ||||
5635 | |||||
5636 | // This is the point at which the dynamic type of the object becomes this | ||||
5637 | // class type. | ||||
5638 | if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) | ||||
5639 | EvalObj.finishedConstructingBases(); | ||||
5640 | } | ||||
5641 | |||||
5642 | // Default-initialize any remaining fields. | ||||
5643 | if (!RD->isUnion()) { | ||||
5644 | for (; FieldIt != RD->field_end(); ++FieldIt) { | ||||
5645 | if (!FieldIt->isUnnamedBitfield()) | ||||
5646 | Result.getStructField(FieldIt->getFieldIndex()) = | ||||
5647 | getDefaultInitValue(FieldIt->getType()); | ||||
5648 | } | ||||
5649 | } | ||||
5650 | |||||
5651 | return Success && | ||||
5652 | EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && | ||||
5653 | LifetimeExtendedScope.destroy(); | ||||
5654 | } | ||||
5655 | |||||
5656 | static bool HandleConstructorCall(const Expr *E, const LValue &This, | ||||
5657 | ArrayRef<const Expr*> Args, | ||||
5658 | const CXXConstructorDecl *Definition, | ||||
5659 | EvalInfo &Info, APValue &Result) { | ||||
5660 | ArgVector ArgValues(Args.size()); | ||||
5661 | if (!EvaluateArgs(Args, ArgValues, Info, Definition)) | ||||
5662 | return false; | ||||
5663 | |||||
5664 | return HandleConstructorCall(E, This, ArgValues.data(), Definition, | ||||
5665 | Info, Result); | ||||
5666 | } | ||||
5667 | |||||
5668 | static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, | ||||
5669 | const LValue &This, APValue &Value, | ||||
5670 | QualType T) { | ||||
5671 | // Objects can only be destroyed while they're within their lifetimes. | ||||
5672 | // FIXME: We have no representation for whether an object of type nullptr_t | ||||
5673 | // is in its lifetime; it usually doesn't matter. Perhaps we should model it | ||||
5674 | // as indeterminate instead? | ||||
5675 | if (Value.isAbsent() && !T->isNullPtrType()) { | ||||
5676 | APValue Printable; | ||||
5677 | This.moveInto(Printable); | ||||
5678 | Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) | ||||
5679 | << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); | ||||
5680 | return false; | ||||
5681 | } | ||||
5682 | |||||
5683 | // Invent an expression for location purposes. | ||||
5684 | // FIXME: We shouldn't need to do this. | ||||
5685 | OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); | ||||
5686 | |||||
5687 | // For arrays, destroy elements right-to-left. | ||||
5688 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { | ||||
5689 | uint64_t Size = CAT->getSize().getZExtValue(); | ||||
5690 | QualType ElemT = CAT->getElementType(); | ||||
5691 | |||||
5692 | LValue ElemLV = This; | ||||
5693 | ElemLV.addArray(Info, &LocE, CAT); | ||||
5694 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) | ||||
5695 | return false; | ||||
5696 | |||||
5697 | // Ensure that we have actual array elements available to destroy; the | ||||
5698 | // destructors might mutate the value, so we can't run them on the array | ||||
5699 | // filler. | ||||
5700 | if (Size && Size > Value.getArrayInitializedElts()) | ||||
5701 | expandArray(Value, Value.getArraySize() - 1); | ||||
5702 | |||||
5703 | for (; Size != 0; --Size) { | ||||
5704 | APValue &Elem = Value.getArrayInitializedElt(Size - 1); | ||||
5705 | if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || | ||||
5706 | !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) | ||||
5707 | return false; | ||||
5708 | } | ||||
5709 | |||||
5710 | // End the lifetime of this array now. | ||||
5711 | Value = APValue(); | ||||
5712 | return true; | ||||
5713 | } | ||||
5714 | |||||
5715 | const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | ||||
5716 | if (!RD) { | ||||
5717 | if (T.isDestructedType()) { | ||||
5718 | Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; | ||||
5719 | return false; | ||||
5720 | } | ||||
5721 | |||||
5722 | Value = APValue(); | ||||
5723 | return true; | ||||
5724 | } | ||||
5725 | |||||
5726 | if (RD->getNumVBases()) { | ||||
5727 | Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; | ||||
5728 | return false; | ||||
5729 | } | ||||
5730 | |||||
5731 | const CXXDestructorDecl *DD = RD->getDestructor(); | ||||
5732 | if (!DD && !RD->hasTrivialDestructor()) { | ||||
5733 | Info.FFDiag(CallLoc); | ||||
5734 | return false; | ||||
5735 | } | ||||
5736 | |||||
5737 | if (!DD || DD->isTrivial() || | ||||
5738 | (RD->isAnonymousStructOrUnion() && RD->isUnion())) { | ||||
5739 | // A trivial destructor just ends the lifetime of the object. Check for | ||||
5740 | // this case before checking for a body, because we might not bother | ||||
5741 | // building a body for a trivial destructor. Note that it doesn't matter | ||||
5742 | // whether the destructor is constexpr in this case; all trivial | ||||
5743 | // destructors are constexpr. | ||||
5744 | // | ||||
5745 | // If an anonymous union would be destroyed, some enclosing destructor must | ||||
5746 | // have been explicitly defined, and the anonymous union destruction should | ||||
5747 | // have no effect. | ||||
5748 | Value = APValue(); | ||||
5749 | return true; | ||||
5750 | } | ||||
5751 | |||||
5752 | if (!Info.CheckCallLimit(CallLoc)) | ||||
5753 | return false; | ||||
5754 | |||||
5755 | const FunctionDecl *Definition = nullptr; | ||||
5756 | const Stmt *Body = DD->getBody(Definition); | ||||
5757 | |||||
5758 | if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) | ||||
5759 | return false; | ||||
5760 | |||||
5761 | CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); | ||||
5762 | |||||
5763 | // We're now in the period of destruction of this object. | ||||
5764 | unsigned BasesLeft = RD->getNumBases(); | ||||
5765 | EvalInfo::EvaluatingDestructorRAII EvalObj( | ||||
5766 | Info, | ||||
5767 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); | ||||
5768 | if (!EvalObj.DidInsert) { | ||||
5769 | // C++2a [class.dtor]p19: | ||||
5770 | // the behavior is undefined if the destructor is invoked for an object | ||||
5771 | // whose lifetime has ended | ||||
5772 | // (Note that formally the lifetime ends when the period of destruction | ||||
5773 | // begins, even though certain uses of the object remain valid until the | ||||
5774 | // period of destruction ends.) | ||||
5775 | Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); | ||||
5776 | return false; | ||||
5777 | } | ||||
5778 | |||||
5779 | // FIXME: Creating an APValue just to hold a nonexistent return value is | ||||
5780 | // wasteful. | ||||
5781 | APValue RetVal; | ||||
5782 | StmtResult Ret = {RetVal, nullptr}; | ||||
5783 | if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) | ||||
5784 | return false; | ||||
5785 | |||||
5786 | // A union destructor does not implicitly destroy its members. | ||||
5787 | if (RD->isUnion()) | ||||
5788 | return true; | ||||
5789 | |||||
5790 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
5791 | |||||
5792 | // We don't have a good way to iterate fields in reverse, so collect all the | ||||
5793 | // fields first and then walk them backwards. | ||||
5794 | SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); | ||||
5795 | for (const FieldDecl *FD : llvm::reverse(Fields)) { | ||||
5796 | if (FD->isUnnamedBitfield()) | ||||
5797 | continue; | ||||
5798 | |||||
5799 | LValue Subobject = This; | ||||
5800 | if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) | ||||
5801 | return false; | ||||
5802 | |||||
5803 | APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); | ||||
5804 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||
5805 | FD->getType())) | ||||
5806 | return false; | ||||
5807 | } | ||||
5808 | |||||
5809 | if (BasesLeft != 0) | ||||
5810 | EvalObj.startedDestroyingBases(); | ||||
5811 | |||||
5812 | // Destroy base classes in reverse order. | ||||
5813 | for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { | ||||
5814 | --BasesLeft; | ||||
5815 | |||||
5816 | QualType BaseType = Base.getType(); | ||||
5817 | LValue Subobject = This; | ||||
5818 | if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, | ||||
5819 | BaseType->getAsCXXRecordDecl(), &Layout)) | ||||
5820 | return false; | ||||
5821 | |||||
5822 | APValue *SubobjectValue = &Value.getStructBase(BasesLeft); | ||||
5823 | if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, | ||||
5824 | BaseType)) | ||||
5825 | return false; | ||||
5826 | } | ||||
5827 | assert(BasesLeft == 0 && "NumBases was wrong?")((BasesLeft == 0 && "NumBases was wrong?") ? static_cast <void> (0) : __assert_fail ("BasesLeft == 0 && \"NumBases was wrong?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5827, __PRETTY_FUNCTION__)); | ||||
5828 | |||||
5829 | // The period of destruction ends now. The object is gone. | ||||
5830 | Value = APValue(); | ||||
5831 | return true; | ||||
5832 | } | ||||
5833 | |||||
5834 | namespace { | ||||
5835 | struct DestroyObjectHandler { | ||||
5836 | EvalInfo &Info; | ||||
5837 | const Expr *E; | ||||
5838 | const LValue &This; | ||||
5839 | const AccessKinds AccessKind; | ||||
5840 | |||||
5841 | typedef bool result_type; | ||||
5842 | bool failed() { return false; } | ||||
5843 | bool found(APValue &Subobj, QualType SubobjType) { | ||||
5844 | return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, | ||||
5845 | SubobjType); | ||||
5846 | } | ||||
5847 | bool found(APSInt &Value, QualType SubobjType) { | ||||
5848 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||
5849 | return false; | ||||
5850 | } | ||||
5851 | bool found(APFloat &Value, QualType SubobjType) { | ||||
5852 | Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); | ||||
5853 | return false; | ||||
5854 | } | ||||
5855 | }; | ||||
5856 | } | ||||
5857 | |||||
5858 | /// Perform a destructor or pseudo-destructor call on the given object, which | ||||
5859 | /// might in general not be a complete object. | ||||
5860 | static bool HandleDestruction(EvalInfo &Info, const Expr *E, | ||||
5861 | const LValue &This, QualType ThisType) { | ||||
5862 | CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); | ||||
5863 | DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; | ||||
5864 | return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); | ||||
5865 | } | ||||
5866 | |||||
5867 | /// Destroy and end the lifetime of the given complete object. | ||||
5868 | static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, | ||||
5869 | APValue::LValueBase LVBase, APValue &Value, | ||||
5870 | QualType T) { | ||||
5871 | // If we've had an unmodeled side-effect, we can't rely on mutable state | ||||
5872 | // (such as the object we're about to destroy) being correct. | ||||
5873 | if (Info.EvalStatus.HasSideEffects) | ||||
5874 | return false; | ||||
5875 | |||||
5876 | LValue LV; | ||||
5877 | LV.set({LVBase}); | ||||
5878 | return HandleDestructionImpl(Info, Loc, LV, Value, T); | ||||
5879 | } | ||||
5880 | |||||
5881 | //===----------------------------------------------------------------------===// | ||||
5882 | // Generic Evaluation | ||||
5883 | //===----------------------------------------------------------------------===// | ||||
5884 | namespace { | ||||
5885 | |||||
5886 | class BitCastBuffer { | ||||
5887 | // FIXME: We're going to need bit-level granularity when we support | ||||
5888 | // bit-fields. | ||||
5889 | // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but | ||||
5890 | // we don't support a host or target where that is the case. Still, we should | ||||
5891 | // use a more generic type in case we ever do. | ||||
5892 | SmallVector<Optional<unsigned char>, 32> Bytes; | ||||
5893 | |||||
5894 | static_assert(std::numeric_limits<unsigned char>::digits >= 8, | ||||
5895 | "Need at least 8 bit unsigned char"); | ||||
5896 | |||||
5897 | bool TargetIsLittleEndian; | ||||
5898 | |||||
5899 | public: | ||||
5900 | BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) | ||||
5901 | : Bytes(Width.getQuantity()), | ||||
5902 | TargetIsLittleEndian(TargetIsLittleEndian) {} | ||||
5903 | |||||
5904 | LLVM_NODISCARD[[clang::warn_unused_result]] | ||||
5905 | bool readObject(CharUnits Offset, CharUnits Width, | ||||
5906 | SmallVectorImpl<unsigned char> &Output) const { | ||||
5907 | for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { | ||||
5908 | // If a byte of an integer is uninitialized, then the whole integer is | ||||
5909 | // uninitalized. | ||||
5910 | if (!Bytes[I.getQuantity()]) | ||||
5911 | return false; | ||||
5912 | Output.push_back(*Bytes[I.getQuantity()]); | ||||
5913 | } | ||||
5914 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||
5915 | std::reverse(Output.begin(), Output.end()); | ||||
5916 | return true; | ||||
5917 | } | ||||
5918 | |||||
5919 | void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { | ||||
5920 | if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) | ||||
5921 | std::reverse(Input.begin(), Input.end()); | ||||
5922 | |||||
5923 | size_t Index = 0; | ||||
5924 | for (unsigned char Byte : Input) { | ||||
5925 | assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?")((!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?" ) ? static_cast<void> (0) : __assert_fail ("!Bytes[Offset.getQuantity() + Index] && \"overwriting a byte?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5925, __PRETTY_FUNCTION__)); | ||||
5926 | Bytes[Offset.getQuantity() + Index] = Byte; | ||||
5927 | ++Index; | ||||
5928 | } | ||||
5929 | } | ||||
5930 | |||||
5931 | size_t size() { return Bytes.size(); } | ||||
5932 | }; | ||||
5933 | |||||
5934 | /// Traverse an APValue to produce an BitCastBuffer, emulating how the current | ||||
5935 | /// target would represent the value at runtime. | ||||
5936 | class APValueToBufferConverter { | ||||
5937 | EvalInfo &Info; | ||||
5938 | BitCastBuffer Buffer; | ||||
5939 | const CastExpr *BCE; | ||||
5940 | |||||
5941 | APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, | ||||
5942 | const CastExpr *BCE) | ||||
5943 | : Info(Info), | ||||
5944 | Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), | ||||
5945 | BCE(BCE) {} | ||||
5946 | |||||
5947 | bool visit(const APValue &Val, QualType Ty) { | ||||
5948 | return visit(Val, Ty, CharUnits::fromQuantity(0)); | ||||
5949 | } | ||||
5950 | |||||
5951 | // Write out Val with type Ty into Buffer starting at Offset. | ||||
5952 | bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
5953 | assert((size_t)Offset.getQuantity() <= Buffer.size())(((size_t)Offset.getQuantity() <= Buffer.size()) ? static_cast <void> (0) : __assert_fail ("(size_t)Offset.getQuantity() <= Buffer.size()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5953, __PRETTY_FUNCTION__)); | ||||
5954 | |||||
5955 | // As a special case, nullptr_t has an indeterminate value. | ||||
5956 | if (Ty->isNullPtrType()) | ||||
5957 | return true; | ||||
5958 | |||||
5959 | // Dig through Src to find the byte at SrcOffset. | ||||
5960 | switch (Val.getKind()) { | ||||
5961 | case APValue::Indeterminate: | ||||
5962 | case APValue::None: | ||||
5963 | return true; | ||||
5964 | |||||
5965 | case APValue::Int: | ||||
5966 | return visitInt(Val.getInt(), Ty, Offset); | ||||
5967 | case APValue::Float: | ||||
5968 | return visitFloat(Val.getFloat(), Ty, Offset); | ||||
5969 | case APValue::Array: | ||||
5970 | return visitArray(Val, Ty, Offset); | ||||
5971 | case APValue::Struct: | ||||
5972 | return visitRecord(Val, Ty, Offset); | ||||
5973 | |||||
5974 | case APValue::ComplexInt: | ||||
5975 | case APValue::ComplexFloat: | ||||
5976 | case APValue::Vector: | ||||
5977 | case APValue::FixedPoint: | ||||
5978 | // FIXME: We should support these. | ||||
5979 | |||||
5980 | case APValue::Union: | ||||
5981 | case APValue::MemberPointer: | ||||
5982 | case APValue::AddrLabelDiff: { | ||||
5983 | Info.FFDiag(BCE->getBeginLoc(), | ||||
5984 | diag::note_constexpr_bit_cast_unsupported_type) | ||||
5985 | << Ty; | ||||
5986 | return false; | ||||
5987 | } | ||||
5988 | |||||
5989 | case APValue::LValue: | ||||
5990 | llvm_unreachable("LValue subobject in bit_cast?")::llvm::llvm_unreachable_internal("LValue subobject in bit_cast?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5990); | ||||
5991 | } | ||||
5992 | llvm_unreachable("Unhandled APValue::ValueKind")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 5992); | ||||
5993 | } | ||||
5994 | |||||
5995 | bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
5996 | const RecordDecl *RD = Ty->getAsRecordDecl(); | ||||
5997 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
5998 | |||||
5999 | // Visit the base classes. | ||||
6000 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
6001 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||
6002 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||
6003 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||
6004 | |||||
6005 | if (!visitRecord(Val.getStructBase(I), BS.getType(), | ||||
6006 | Layout.getBaseClassOffset(BaseDecl) + Offset)) | ||||
6007 | return false; | ||||
6008 | } | ||||
6009 | } | ||||
6010 | |||||
6011 | // Visit the fields. | ||||
6012 | unsigned FieldIdx = 0; | ||||
6013 | for (FieldDecl *FD : RD->fields()) { | ||||
6014 | if (FD->isBitField()) { | ||||
6015 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6016 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||
6017 | return false; | ||||
6018 | } | ||||
6019 | |||||
6020 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||
6021 | |||||
6022 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment" ) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6023, __PRETTY_FUNCTION__)) | ||||
6023 | "only bit-fields can have sub-char alignment")((FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && "only bit-fields can have sub-char alignment" ) ? static_cast<void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && \"only bit-fields can have sub-char alignment\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6023, __PRETTY_FUNCTION__)); | ||||
6024 | CharUnits FieldOffset = | ||||
6025 | Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; | ||||
6026 | QualType FieldTy = FD->getType(); | ||||
6027 | if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) | ||||
6028 | return false; | ||||
6029 | ++FieldIdx; | ||||
6030 | } | ||||
6031 | |||||
6032 | return true; | ||||
6033 | } | ||||
6034 | |||||
6035 | bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { | ||||
6036 | const auto *CAT = | ||||
6037 | dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); | ||||
6038 | if (!CAT) | ||||
6039 | return false; | ||||
6040 | |||||
6041 | CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); | ||||
6042 | unsigned NumInitializedElts = Val.getArrayInitializedElts(); | ||||
6043 | unsigned ArraySize = Val.getArraySize(); | ||||
6044 | // First, initialize the initialized elements. | ||||
6045 | for (unsigned I = 0; I != NumInitializedElts; ++I) { | ||||
6046 | const APValue &SubObj = Val.getArrayInitializedElt(I); | ||||
6047 | if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) | ||||
6048 | return false; | ||||
6049 | } | ||||
6050 | |||||
6051 | // Next, initialize the rest of the array using the filler. | ||||
6052 | if (Val.hasArrayFiller()) { | ||||
6053 | const APValue &Filler = Val.getArrayFiller(); | ||||
6054 | for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { | ||||
6055 | if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) | ||||
6056 | return false; | ||||
6057 | } | ||||
6058 | } | ||||
6059 | |||||
6060 | return true; | ||||
6061 | } | ||||
6062 | |||||
6063 | bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { | ||||
6064 | CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); | ||||
6065 | SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); | ||||
6066 | llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); | ||||
6067 | Buffer.writeObject(Offset, Bytes); | ||||
6068 | return true; | ||||
6069 | } | ||||
6070 | |||||
6071 | bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { | ||||
6072 | APSInt AsInt(Val.bitcastToAPInt()); | ||||
6073 | return visitInt(AsInt, Ty, Offset); | ||||
6074 | } | ||||
6075 | |||||
6076 | public: | ||||
6077 | static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, | ||||
6078 | const CastExpr *BCE) { | ||||
6079 | CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); | ||||
6080 | APValueToBufferConverter Converter(Info, DstSize, BCE); | ||||
6081 | if (!Converter.visit(Src, BCE->getSubExpr()->getType())) | ||||
6082 | return None; | ||||
6083 | return Converter.Buffer; | ||||
6084 | } | ||||
6085 | }; | ||||
6086 | |||||
6087 | /// Write an BitCastBuffer into an APValue. | ||||
6088 | class BufferToAPValueConverter { | ||||
6089 | EvalInfo &Info; | ||||
6090 | const BitCastBuffer &Buffer; | ||||
6091 | const CastExpr *BCE; | ||||
6092 | |||||
6093 | BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, | ||||
6094 | const CastExpr *BCE) | ||||
6095 | : Info(Info), Buffer(Buffer), BCE(BCE) {} | ||||
6096 | |||||
6097 | // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast | ||||
6098 | // with an invalid type, so anything left is a deficiency on our part (FIXME). | ||||
6099 | // Ideally this will be unreachable. | ||||
6100 | llvm::NoneType unsupportedType(QualType Ty) { | ||||
6101 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6102 | diag::note_constexpr_bit_cast_unsupported_type) | ||||
6103 | << Ty; | ||||
6104 | return None; | ||||
6105 | } | ||||
6106 | |||||
6107 | Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, | ||||
6108 | const EnumType *EnumSugar = nullptr) { | ||||
6109 | if (T->isNullPtrType()) { | ||||
6110 | uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); | ||||
6111 | return APValue((Expr *)nullptr, | ||||
6112 | /*Offset=*/CharUnits::fromQuantity(NullValue), | ||||
6113 | APValue::NoLValuePath{}, /*IsNullPtr=*/true); | ||||
6114 | } | ||||
6115 | |||||
6116 | CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); | ||||
6117 | SmallVector<uint8_t, 8> Bytes; | ||||
6118 | if (!Buffer.readObject(Offset, SizeOf, Bytes)) { | ||||
6119 | // If this is std::byte or unsigned char, then its okay to store an | ||||
6120 | // indeterminate value. | ||||
6121 | bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); | ||||
6122 | bool IsUChar = | ||||
6123 | !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || | ||||
6124 | T->isSpecificBuiltinType(BuiltinType::Char_U)); | ||||
6125 | if (!IsStdByte && !IsUChar) { | ||||
6126 | QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); | ||||
6127 | Info.FFDiag(BCE->getExprLoc(), | ||||
6128 | diag::note_constexpr_bit_cast_indet_dest) | ||||
6129 | << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; | ||||
6130 | return None; | ||||
6131 | } | ||||
6132 | |||||
6133 | return APValue::IndeterminateValue(); | ||||
6134 | } | ||||
6135 | |||||
6136 | APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); | ||||
6137 | llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); | ||||
6138 | |||||
6139 | if (T->isIntegralOrEnumerationType()) { | ||||
6140 | Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); | ||||
6141 | return APValue(Val); | ||||
6142 | } | ||||
6143 | |||||
6144 | if (T->isRealFloatingType()) { | ||||
6145 | const llvm::fltSemantics &Semantics = | ||||
6146 | Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); | ||||
6147 | return APValue(APFloat(Semantics, Val)); | ||||
6148 | } | ||||
6149 | |||||
6150 | return unsupportedType(QualType(T, 0)); | ||||
6151 | } | ||||
6152 | |||||
6153 | Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { | ||||
6154 | const RecordDecl *RD = RTy->getAsRecordDecl(); | ||||
6155 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
6156 | |||||
6157 | unsigned NumBases = 0; | ||||
6158 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | ||||
6159 | NumBases = CXXRD->getNumBases(); | ||||
6160 | |||||
6161 | APValue ResultVal(APValue::UninitStruct(), NumBases, | ||||
6162 | std::distance(RD->field_begin(), RD->field_end())); | ||||
6163 | |||||
6164 | // Visit the base classes. | ||||
6165 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { | ||||
6166 | for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { | ||||
6167 | const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; | ||||
6168 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | ||||
6169 | if (BaseDecl->isEmpty() || | ||||
6170 | Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) | ||||
6171 | continue; | ||||
6172 | |||||
6173 | Optional<APValue> SubObj = visitType( | ||||
6174 | BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); | ||||
6175 | if (!SubObj) | ||||
6176 | return None; | ||||
6177 | ResultVal.getStructBase(I) = *SubObj; | ||||
6178 | } | ||||
6179 | } | ||||
6180 | |||||
6181 | // Visit the fields. | ||||
6182 | unsigned FieldIdx = 0; | ||||
6183 | for (FieldDecl *FD : RD->fields()) { | ||||
6184 | // FIXME: We don't currently support bit-fields. A lot of the logic for | ||||
6185 | // this is in CodeGen, so we need to factor it around. | ||||
6186 | if (FD->isBitField()) { | ||||
6187 | Info.FFDiag(BCE->getBeginLoc(), | ||||
6188 | diag::note_constexpr_bit_cast_unsupported_bitfield); | ||||
6189 | return None; | ||||
6190 | } | ||||
6191 | |||||
6192 | uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); | ||||
6193 | assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0)((FieldOffsetBits % Info.Ctx.getCharWidth() == 0) ? static_cast <void> (0) : __assert_fail ("FieldOffsetBits % Info.Ctx.getCharWidth() == 0" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6193, __PRETTY_FUNCTION__)); | ||||
6194 | |||||
6195 | CharUnits FieldOffset = | ||||
6196 | CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + | ||||
6197 | Offset; | ||||
6198 | QualType FieldTy = FD->getType(); | ||||
6199 | Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); | ||||
6200 | if (!SubObj) | ||||
6201 | return None; | ||||
6202 | ResultVal.getStructField(FieldIdx) = *SubObj; | ||||
6203 | ++FieldIdx; | ||||
6204 | } | ||||
6205 | |||||
6206 | return ResultVal; | ||||
6207 | } | ||||
6208 | |||||
6209 | Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { | ||||
6210 | QualType RepresentationType = Ty->getDecl()->getIntegerType(); | ||||
6211 | assert(!RepresentationType.isNull() &&((!RepresentationType.isNull() && "enum forward decl should be caught by Sema" ) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6212, __PRETTY_FUNCTION__)) | ||||
6212 | "enum forward decl should be caught by Sema")((!RepresentationType.isNull() && "enum forward decl should be caught by Sema" ) ? static_cast<void> (0) : __assert_fail ("!RepresentationType.isNull() && \"enum forward decl should be caught by Sema\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6212, __PRETTY_FUNCTION__)); | ||||
6213 | const BuiltinType *AsBuiltin = | ||||
6214 | RepresentationType.getCanonicalType()->getAs<BuiltinType>(); | ||||
6215 | assert(AsBuiltin && "non-integral enum underlying type?")((AsBuiltin && "non-integral enum underlying type?") ? static_cast<void> (0) : __assert_fail ("AsBuiltin && \"non-integral enum underlying type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6215, __PRETTY_FUNCTION__)); | ||||
6216 | // Recurse into the underlying type. Treat std::byte transparently as | ||||
6217 | // unsigned char. | ||||
6218 | return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); | ||||
6219 | } | ||||
6220 | |||||
6221 | Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { | ||||
6222 | size_t Size = Ty->getSize().getLimitedValue(); | ||||
6223 | CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); | ||||
6224 | |||||
6225 | APValue ArrayValue(APValue::UninitArray(), Size, Size); | ||||
6226 | for (size_t I = 0; I != Size; ++I) { | ||||
6227 | Optional<APValue> ElementValue = | ||||
6228 | visitType(Ty->getElementType(), Offset + I * ElementWidth); | ||||
6229 | if (!ElementValue) | ||||
6230 | return None; | ||||
6231 | ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); | ||||
6232 | } | ||||
6233 | |||||
6234 | return ArrayValue; | ||||
6235 | } | ||||
6236 | |||||
6237 | Optional<APValue> visit(const Type *Ty, CharUnits Offset) { | ||||
6238 | return unsupportedType(QualType(Ty, 0)); | ||||
6239 | } | ||||
6240 | |||||
6241 | Optional<APValue> visitType(QualType Ty, CharUnits Offset) { | ||||
6242 | QualType Can = Ty.getCanonicalType(); | ||||
6243 | |||||
6244 | switch (Can->getTypeClass()) { | ||||
6245 | #define TYPE(Class, Base) \ | ||||
6246 | case Type::Class: \ | ||||
6247 | return visit(cast<Class##Type>(Can.getTypePtr()), Offset); | ||||
6248 | #define ABSTRACT_TYPE(Class, Base) | ||||
6249 | #define NON_CANONICAL_TYPE(Class, Base) \ | ||||
6250 | case Type::Class: \ | ||||
6251 | llvm_unreachable("non-canonical type should be impossible!")::llvm::llvm_unreachable_internal("non-canonical type should be impossible!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6251); | ||||
6252 | #define DEPENDENT_TYPE(Class, Base) \ | ||||
6253 | case Type::Class: \ | ||||
6254 | llvm_unreachable( \::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6255) | ||||
6255 | "dependent types aren't supported in the constant evaluator!")::llvm::llvm_unreachable_internal("dependent types aren't supported in the constant evaluator!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6255); | ||||
6256 | #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)case Type::Class: ::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6256); \ | ||||
6257 | case Type::Class: \ | ||||
6258 | llvm_unreachable("either dependent or not canonical!")::llvm::llvm_unreachable_internal("either dependent or not canonical!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6258); | ||||
6259 | #include "clang/AST/TypeNodes.inc" | ||||
6260 | } | ||||
6261 | llvm_unreachable("Unhandled Type::TypeClass")::llvm::llvm_unreachable_internal("Unhandled Type::TypeClass" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6261); | ||||
6262 | } | ||||
6263 | |||||
6264 | public: | ||||
6265 | // Pull out a full value of type DstType. | ||||
6266 | static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, | ||||
6267 | const CastExpr *BCE) { | ||||
6268 | BufferToAPValueConverter Converter(Info, Buffer, BCE); | ||||
6269 | return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); | ||||
6270 | } | ||||
6271 | }; | ||||
6272 | |||||
6273 | static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, | ||||
6274 | QualType Ty, EvalInfo *Info, | ||||
6275 | const ASTContext &Ctx, | ||||
6276 | bool CheckingDest) { | ||||
6277 | Ty = Ty.getCanonicalType(); | ||||
6278 | |||||
6279 | auto diag = [&](int Reason) { | ||||
6280 | if (Info) | ||||
6281 | Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) | ||||
6282 | << CheckingDest << (Reason == 4) << Reason; | ||||
6283 | return false; | ||||
6284 | }; | ||||
6285 | auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { | ||||
6286 | if (Info) | ||||
6287 | Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) | ||||
6288 | << NoteTy << Construct << Ty; | ||||
6289 | return false; | ||||
6290 | }; | ||||
6291 | |||||
6292 | if (Ty->isUnionType()) | ||||
6293 | return diag(0); | ||||
6294 | if (Ty->isPointerType()) | ||||
6295 | return diag(1); | ||||
6296 | if (Ty->isMemberPointerType()) | ||||
6297 | return diag(2); | ||||
6298 | if (Ty.isVolatileQualified()) | ||||
6299 | return diag(3); | ||||
6300 | |||||
6301 | if (RecordDecl *Record = Ty->getAsRecordDecl()) { | ||||
6302 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { | ||||
6303 | for (CXXBaseSpecifier &BS : CXXRD->bases()) | ||||
6304 | if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, | ||||
6305 | CheckingDest)) | ||||
6306 | return note(1, BS.getType(), BS.getBeginLoc()); | ||||
6307 | } | ||||
6308 | for (FieldDecl *FD : Record->fields()) { | ||||
6309 | if (FD->getType()->isReferenceType()) | ||||
6310 | return diag(4); | ||||
6311 | if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, | ||||
6312 | CheckingDest)) | ||||
6313 | return note(0, FD->getType(), FD->getBeginLoc()); | ||||
6314 | } | ||||
6315 | } | ||||
6316 | |||||
6317 | if (Ty->isArrayType() && | ||||
6318 | !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), | ||||
6319 | Info, Ctx, CheckingDest)) | ||||
6320 | return false; | ||||
6321 | |||||
6322 | return true; | ||||
6323 | } | ||||
6324 | |||||
6325 | static bool checkBitCastConstexprEligibility(EvalInfo *Info, | ||||
6326 | const ASTContext &Ctx, | ||||
6327 | const CastExpr *BCE) { | ||||
6328 | bool DestOK = checkBitCastConstexprEligibilityType( | ||||
6329 | BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); | ||||
6330 | bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( | ||||
6331 | BCE->getBeginLoc(), | ||||
6332 | BCE->getSubExpr()->getType(), Info, Ctx, false); | ||||
6333 | return SourceOK; | ||||
6334 | } | ||||
6335 | |||||
6336 | static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, | ||||
6337 | APValue &SourceValue, | ||||
6338 | const CastExpr *BCE) { | ||||
6339 | assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && "no host or target supports non 8-bit chars") ? static_cast<void> (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6340, __PRETTY_FUNCTION__)) | ||||
6340 | "no host or target supports non 8-bit chars")((8 == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && "no host or target supports non 8-bit chars") ? static_cast<void> (0) : __assert_fail ("CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && \"no host or target supports non 8-bit chars\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6340, __PRETTY_FUNCTION__)); | ||||
6341 | assert(SourceValue.isLValue() &&((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6342, __PRETTY_FUNCTION__)) | ||||
6342 | "LValueToRValueBitcast requires an lvalue operand!")((SourceValue.isLValue() && "LValueToRValueBitcast requires an lvalue operand!" ) ? static_cast<void> (0) : __assert_fail ("SourceValue.isLValue() && \"LValueToRValueBitcast requires an lvalue operand!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6342, __PRETTY_FUNCTION__)); | ||||
6343 | |||||
6344 | if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) | ||||
6345 | return false; | ||||
6346 | |||||
6347 | LValue SourceLValue; | ||||
6348 | APValue SourceRValue; | ||||
6349 | SourceLValue.setFrom(Info.Ctx, SourceValue); | ||||
6350 | if (!handleLValueToRValueConversion( | ||||
6351 | Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, | ||||
6352 | SourceRValue, /*WantObjectRepresentation=*/true)) | ||||
6353 | return false; | ||||
6354 | |||||
6355 | // Read out SourceValue into a char buffer. | ||||
6356 | Optional<BitCastBuffer> Buffer = | ||||
6357 | APValueToBufferConverter::convert(Info, SourceRValue, BCE); | ||||
6358 | if (!Buffer) | ||||
6359 | return false; | ||||
6360 | |||||
6361 | // Write out the buffer into a new APValue. | ||||
6362 | Optional<APValue> MaybeDestValue = | ||||
6363 | BufferToAPValueConverter::convert(Info, *Buffer, BCE); | ||||
6364 | if (!MaybeDestValue) | ||||
6365 | return false; | ||||
6366 | |||||
6367 | DestValue = std::move(*MaybeDestValue); | ||||
6368 | return true; | ||||
6369 | } | ||||
6370 | |||||
6371 | template <class Derived> | ||||
6372 | class ExprEvaluatorBase | ||||
6373 | : public ConstStmtVisitor<Derived, bool> { | ||||
6374 | private: | ||||
6375 | Derived &getDerived() { return static_cast<Derived&>(*this); } | ||||
6376 | bool DerivedSuccess(const APValue &V, const Expr *E) { | ||||
6377 | return getDerived().Success(V, E); | ||||
6378 | } | ||||
6379 | bool DerivedZeroInitialization(const Expr *E) { | ||||
6380 | return getDerived().ZeroInitialization(E); | ||||
6381 | } | ||||
6382 | |||||
6383 | // Check whether a conditional operator with a non-constant condition is a | ||||
6384 | // potential constant expression. If neither arm is a potential constant | ||||
6385 | // expression, then the conditional operator is not either. | ||||
6386 | template<typename ConditionalOperator> | ||||
6387 | void CheckPotentialConstantConditional(const ConditionalOperator *E) { | ||||
6388 | assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast< void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6388, __PRETTY_FUNCTION__)); | ||||
6389 | |||||
6390 | // Speculatively evaluate both arms. | ||||
6391 | SmallVector<PartialDiagnosticAt, 8> Diag; | ||||
6392 | { | ||||
6393 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||
6394 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||
6395 | if (Diag.empty()) | ||||
6396 | return; | ||||
6397 | } | ||||
6398 | |||||
6399 | { | ||||
6400 | SpeculativeEvaluationRAII Speculate(Info, &Diag); | ||||
6401 | Diag.clear(); | ||||
6402 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||
6403 | if (Diag.empty()) | ||||
6404 | return; | ||||
6405 | } | ||||
6406 | |||||
6407 | Error(E, diag::note_constexpr_conditional_never_const); | ||||
6408 | } | ||||
6409 | |||||
6410 | |||||
6411 | template<typename ConditionalOperator> | ||||
6412 | bool HandleConditionalOperator(const ConditionalOperator *E) { | ||||
6413 | bool BoolResult; | ||||
6414 | if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { | ||||
6415 | if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { | ||||
6416 | CheckPotentialConstantConditional(E); | ||||
6417 | return false; | ||||
6418 | } | ||||
6419 | if (Info.noteFailure()) { | ||||
6420 | StmtVisitorTy::Visit(E->getTrueExpr()); | ||||
6421 | StmtVisitorTy::Visit(E->getFalseExpr()); | ||||
6422 | } | ||||
6423 | return false; | ||||
6424 | } | ||||
6425 | |||||
6426 | Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); | ||||
6427 | return StmtVisitorTy::Visit(EvalExpr); | ||||
6428 | } | ||||
6429 | |||||
6430 | protected: | ||||
6431 | EvalInfo &Info; | ||||
6432 | typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; | ||||
6433 | typedef ExprEvaluatorBase ExprEvaluatorBaseTy; | ||||
6434 | |||||
6435 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||
6436 | return Info.CCEDiag(E, D); | ||||
6437 | } | ||||
6438 | |||||
6439 | bool ZeroInitialization(const Expr *E) { return Error(E); } | ||||
6440 | |||||
6441 | public: | ||||
6442 | ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} | ||||
6443 | |||||
6444 | EvalInfo &getEvalInfo() { return Info; } | ||||
6445 | |||||
6446 | /// Report an evaluation error. This should only be called when an error is | ||||
6447 | /// first discovered. When propagating an error, just return false. | ||||
6448 | bool Error(const Expr *E, diag::kind D) { | ||||
6449 | Info.FFDiag(E, D); | ||||
6450 | return false; | ||||
6451 | } | ||||
6452 | bool Error(const Expr *E) { | ||||
6453 | return Error(E, diag::note_invalid_subexpr_in_const_expr); | ||||
6454 | } | ||||
6455 | |||||
6456 | bool VisitStmt(const Stmt *) { | ||||
6457 | llvm_unreachable("Expression evaluator should not be called on stmts")::llvm::llvm_unreachable_internal("Expression evaluator should not be called on stmts" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6457); | ||||
6458 | } | ||||
6459 | bool VisitExpr(const Expr *E) { | ||||
6460 | return Error(E); | ||||
6461 | } | ||||
6462 | |||||
6463 | bool VisitConstantExpr(const ConstantExpr *E) | ||||
6464 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
6465 | bool VisitParenExpr(const ParenExpr *E) | ||||
6466 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
6467 | bool VisitUnaryExtension(const UnaryOperator *E) | ||||
6468 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
6469 | bool VisitUnaryPlus(const UnaryOperator *E) | ||||
6470 | { return StmtVisitorTy::Visit(E->getSubExpr()); } | ||||
6471 | bool VisitChooseExpr(const ChooseExpr *E) | ||||
6472 | { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } | ||||
6473 | bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) | ||||
6474 | { return StmtVisitorTy::Visit(E->getResultExpr()); } | ||||
6475 | bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) | ||||
6476 | { return StmtVisitorTy::Visit(E->getReplacement()); } | ||||
6477 | bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { | ||||
6478 | TempVersionRAII RAII(*Info.CurrentCall); | ||||
6479 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||
6480 | return StmtVisitorTy::Visit(E->getExpr()); | ||||
6481 | } | ||||
6482 | bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { | ||||
6483 | TempVersionRAII RAII(*Info.CurrentCall); | ||||
6484 | // The initializer may not have been parsed yet, or might be erroneous. | ||||
6485 | if (!E->getExpr()) | ||||
6486 | return Error(E); | ||||
6487 | SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); | ||||
6488 | return StmtVisitorTy::Visit(E->getExpr()); | ||||
6489 | } | ||||
6490 | |||||
6491 | bool VisitExprWithCleanups(const ExprWithCleanups *E) { | ||||
6492 | FullExpressionRAII Scope(Info); | ||||
6493 | return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); | ||||
6494 | } | ||||
6495 | |||||
6496 | // Temporaries are registered when created, so we don't care about | ||||
6497 | // CXXBindTemporaryExpr. | ||||
6498 | bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { | ||||
6499 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||
6500 | } | ||||
6501 | |||||
6502 | bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { | ||||
6503 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; | ||||
6504 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
6505 | } | ||||
6506 | bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { | ||||
6507 | if (!Info.Ctx.getLangOpts().CPlusPlus2a) | ||||
6508 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; | ||||
6509 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
6510 | } | ||||
6511 | bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { | ||||
6512 | return static_cast<Derived*>(this)->VisitCastExpr(E); | ||||
6513 | } | ||||
6514 | |||||
6515 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||
6516 | switch (E->getOpcode()) { | ||||
6517 | default: | ||||
6518 | return Error(E); | ||||
6519 | |||||
6520 | case BO_Comma: | ||||
6521 | VisitIgnoredValue(E->getLHS()); | ||||
6522 | return StmtVisitorTy::Visit(E->getRHS()); | ||||
6523 | |||||
6524 | case BO_PtrMemD: | ||||
6525 | case BO_PtrMemI: { | ||||
6526 | LValue Obj; | ||||
6527 | if (!HandleMemberPointerAccess(Info, E, Obj)) | ||||
6528 | return false; | ||||
6529 | APValue Result; | ||||
6530 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) | ||||
6531 | return false; | ||||
6532 | return DerivedSuccess(Result, E); | ||||
6533 | } | ||||
6534 | } | ||||
6535 | } | ||||
6536 | |||||
6537 | bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { | ||||
6538 | // Evaluate and cache the common expression. We treat it as a temporary, | ||||
6539 | // even though it's not quite the same thing. | ||||
6540 | LValue CommonLV; | ||||
6541 | if (!Evaluate(Info.CurrentCall->createTemporary( | ||||
6542 | E->getOpaqueValue(), | ||||
6543 | getStorageType(Info.Ctx, E->getOpaqueValue()), false, | ||||
6544 | CommonLV), | ||||
6545 | Info, E->getCommon())) | ||||
6546 | return false; | ||||
6547 | |||||
6548 | return HandleConditionalOperator(E); | ||||
6549 | } | ||||
6550 | |||||
6551 | bool VisitConditionalOperator(const ConditionalOperator *E) { | ||||
6552 | bool IsBcpCall = false; | ||||
6553 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||
6554 | // the result is a constant expression if it can be folded without | ||||
6555 | // side-effects. This is an important GNU extension. See GCC PR38377 | ||||
6556 | // for discussion. | ||||
6557 | if (const CallExpr *CallCE = | ||||
6558 | dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) | ||||
6559 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||
6560 | IsBcpCall = true; | ||||
6561 | |||||
6562 | // Always assume __builtin_constant_p(...) ? ... : ... is a potential | ||||
6563 | // constant expression; we can't check whether it's potentially foldable. | ||||
6564 | // FIXME: We should instead treat __builtin_constant_p as non-constant if | ||||
6565 | // it would return 'false' in this mode. | ||||
6566 | if (Info.checkingPotentialConstantExpression() && IsBcpCall) | ||||
6567 | return false; | ||||
6568 | |||||
6569 | FoldConstant Fold(Info, IsBcpCall); | ||||
6570 | if (!HandleConditionalOperator(E)) { | ||||
6571 | Fold.keepDiagnostics(); | ||||
6572 | return false; | ||||
6573 | } | ||||
6574 | |||||
6575 | return true; | ||||
6576 | } | ||||
6577 | |||||
6578 | bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { | ||||
6579 | if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) | ||||
6580 | return DerivedSuccess(*Value, E); | ||||
6581 | |||||
6582 | const Expr *Source = E->getSourceExpr(); | ||||
6583 | if (!Source) | ||||
6584 | return Error(E); | ||||
6585 | if (Source == E) { // sanity checking. | ||||
6586 | assert(0 && "OpaqueValueExpr recursively refers to itself")((0 && "OpaqueValueExpr recursively refers to itself" ) ? static_cast<void> (0) : __assert_fail ("0 && \"OpaqueValueExpr recursively refers to itself\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6586, __PRETTY_FUNCTION__)); | ||||
6587 | return Error(E); | ||||
6588 | } | ||||
6589 | return StmtVisitorTy::Visit(Source); | ||||
6590 | } | ||||
6591 | |||||
6592 | bool VisitCallExpr(const CallExpr *E) { | ||||
6593 | APValue Result; | ||||
6594 | if (!handleCallExpr(E, Result, nullptr)) | ||||
6595 | return false; | ||||
6596 | return DerivedSuccess(Result, E); | ||||
6597 | } | ||||
6598 | |||||
6599 | bool handleCallExpr(const CallExpr *E, APValue &Result, | ||||
6600 | const LValue *ResultSlot) { | ||||
6601 | const Expr *Callee = E->getCallee()->IgnoreParens(); | ||||
6602 | QualType CalleeType = Callee->getType(); | ||||
6603 | |||||
6604 | const FunctionDecl *FD = nullptr; | ||||
6605 | LValue *This = nullptr, ThisVal; | ||||
6606 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||
6607 | bool HasQualifier = false; | ||||
6608 | |||||
6609 | // Extract function decl and 'this' pointer from the callee. | ||||
6610 | if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { | ||||
6611 | const CXXMethodDecl *Member = nullptr; | ||||
6612 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { | ||||
6613 | // Explicit bound member calls, such as x.f() or p->g(); | ||||
6614 | if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) | ||||
6615 | return false; | ||||
6616 | Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); | ||||
6617 | if (!Member) | ||||
6618 | return Error(Callee); | ||||
6619 | This = &ThisVal; | ||||
6620 | HasQualifier = ME->hasQualifier(); | ||||
6621 | } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { | ||||
6622 | // Indirect bound member calls ('.*' or '->*'). | ||||
6623 | Member = dyn_cast_or_null<CXXMethodDecl>( | ||||
6624 | HandleMemberPointerAccess(Info, BE, ThisVal, false)); | ||||
6625 | if (!Member) | ||||
6626 | return Error(Callee); | ||||
6627 | This = &ThisVal; | ||||
6628 | } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { | ||||
6629 | if (!Info.getLangOpts().CPlusPlus2a) | ||||
6630 | Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); | ||||
6631 | // FIXME: If pseudo-destructor calls ever start ending the lifetime of | ||||
6632 | // their callee, we should start calling HandleDestruction here. | ||||
6633 | // For now, we just evaluate the object argument and discard it. | ||||
6634 | return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal); | ||||
6635 | } else | ||||
6636 | return Error(Callee); | ||||
6637 | FD = Member; | ||||
6638 | } else if (CalleeType->isFunctionPointerType()) { | ||||
6639 | LValue Call; | ||||
6640 | if (!EvaluatePointer(Callee, Call, Info)) | ||||
6641 | return false; | ||||
6642 | |||||
6643 | if (!Call.getLValueOffset().isZero()) | ||||
6644 | return Error(Callee); | ||||
6645 | FD = dyn_cast_or_null<FunctionDecl>( | ||||
6646 | Call.getLValueBase().dyn_cast<const ValueDecl*>()); | ||||
6647 | if (!FD) | ||||
6648 | return Error(Callee); | ||||
6649 | // Don't call function pointers which have been cast to some other type. | ||||
6650 | // Per DR (no number yet), the caller and callee can differ in noexcept. | ||||
6651 | if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( | ||||
6652 | CalleeType->getPointeeType(), FD->getType())) { | ||||
6653 | return Error(E); | ||||
6654 | } | ||||
6655 | |||||
6656 | // Overloaded operator calls to member functions are represented as normal | ||||
6657 | // calls with '*this' as the first argument. | ||||
6658 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
6659 | if (MD && !MD->isStatic()) { | ||||
6660 | // FIXME: When selecting an implicit conversion for an overloaded | ||||
6661 | // operator delete, we sometimes try to evaluate calls to conversion | ||||
6662 | // operators without a 'this' parameter! | ||||
6663 | if (Args.empty()) | ||||
6664 | return Error(E); | ||||
6665 | |||||
6666 | if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) | ||||
6667 | return false; | ||||
6668 | This = &ThisVal; | ||||
6669 | Args = Args.slice(1); | ||||
6670 | } else if (MD && MD->isLambdaStaticInvoker()) { | ||||
6671 | // Map the static invoker for the lambda back to the call operator. | ||||
6672 | // Conveniently, we don't have to slice out the 'this' argument (as is | ||||
6673 | // being done for the non-static case), since a static member function | ||||
6674 | // doesn't have an implicit argument passed in. | ||||
6675 | const CXXRecordDecl *ClosureClass = MD->getParent(); | ||||
6676 | assert(((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)) | ||||
6677 | ClosureClass->captures_begin() == ClosureClass->captures_end() &&((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)) | ||||
6678 | "Number of captures must be zero for conversion to function-ptr")((ClosureClass->captures_begin() == ClosureClass->captures_end () && "Number of captures must be zero for conversion to function-ptr" ) ? static_cast<void> (0) : __assert_fail ("ClosureClass->captures_begin() == ClosureClass->captures_end() && \"Number of captures must be zero for conversion to function-ptr\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6678, __PRETTY_FUNCTION__)); | ||||
6679 | |||||
6680 | const CXXMethodDecl *LambdaCallOp = | ||||
6681 | ClosureClass->getLambdaCallOperator(); | ||||
6682 | |||||
6683 | // Set 'FD', the function that will be called below, to the call | ||||
6684 | // operator. If the closure object represents a generic lambda, find | ||||
6685 | // the corresponding specialization of the call operator. | ||||
6686 | |||||
6687 | if (ClosureClass->isGenericLambda()) { | ||||
6688 | assert(MD->isFunctionTemplateSpecialization() &&((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)) | ||||
6689 | "A generic lambda's static-invoker function must be a "((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)) | ||||
6690 | "template specialization")((MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization") ? static_cast<void> (0) : __assert_fail ("MD->isFunctionTemplateSpecialization() && \"A generic lambda's static-invoker function must be a \" \"template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6690, __PRETTY_FUNCTION__)); | ||||
6691 | const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); | ||||
6692 | FunctionTemplateDecl *CallOpTemplate = | ||||
6693 | LambdaCallOp->getDescribedFunctionTemplate(); | ||||
6694 | void *InsertPos = nullptr; | ||||
6695 | FunctionDecl *CorrespondingCallOpSpecialization = | ||||
6696 | CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); | ||||
6697 | assert(CorrespondingCallOpSpecialization &&((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)) | ||||
6698 | "We must always have a function call operator specialization "((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)) | ||||
6699 | "that corresponds to our static invoker specialization")((CorrespondingCallOpSpecialization && "We must always have a function call operator specialization " "that corresponds to our static invoker specialization") ? static_cast <void> (0) : __assert_fail ("CorrespondingCallOpSpecialization && \"We must always have a function call operator specialization \" \"that corresponds to our static invoker specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6699, __PRETTY_FUNCTION__)); | ||||
6700 | FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); | ||||
6701 | } else | ||||
6702 | FD = LambdaCallOp; | ||||
6703 | } | ||||
6704 | } else | ||||
6705 | return Error(E); | ||||
6706 | |||||
6707 | SmallVector<QualType, 4> CovariantAdjustmentPath; | ||||
6708 | if (This) { | ||||
6709 | auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); | ||||
6710 | if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { | ||||
6711 | // Perform virtual dispatch, if necessary. | ||||
6712 | FD = HandleVirtualDispatch(Info, E, *This, NamedMember, | ||||
6713 | CovariantAdjustmentPath); | ||||
6714 | if (!FD) | ||||
6715 | return false; | ||||
6716 | } else { | ||||
6717 | // Check that the 'this' pointer points to an object of the right type. | ||||
6718 | // FIXME: If this is an assignment operator call, we may need to change | ||||
6719 | // the active union member before we check this. | ||||
6720 | if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) | ||||
6721 | return false; | ||||
6722 | } | ||||
6723 | } | ||||
6724 | |||||
6725 | // Destructor calls are different enough that they have their own codepath. | ||||
6726 | if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { | ||||
6727 | assert(This && "no 'this' pointer for destructor call")((This && "no 'this' pointer for destructor call") ? static_cast <void> (0) : __assert_fail ("This && \"no 'this' pointer for destructor call\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6727, __PRETTY_FUNCTION__)); | ||||
6728 | return HandleDestruction(Info, E, *This, | ||||
6729 | Info.Ctx.getRecordType(DD->getParent())); | ||||
6730 | } | ||||
6731 | |||||
6732 | const FunctionDecl *Definition = nullptr; | ||||
6733 | Stmt *Body = FD->getBody(Definition); | ||||
6734 | |||||
6735 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || | ||||
6736 | !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, | ||||
6737 | Result, ResultSlot)) | ||||
6738 | return false; | ||||
6739 | |||||
6740 | if (!CovariantAdjustmentPath.empty() && | ||||
6741 | !HandleCovariantReturnAdjustment(Info, E, Result, | ||||
6742 | CovariantAdjustmentPath)) | ||||
6743 | return false; | ||||
6744 | |||||
6745 | return true; | ||||
6746 | } | ||||
6747 | |||||
6748 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||
6749 | return StmtVisitorTy::Visit(E->getInitializer()); | ||||
6750 | } | ||||
6751 | bool VisitInitListExpr(const InitListExpr *E) { | ||||
6752 | if (E->getNumInits() == 0) | ||||
6753 | return DerivedZeroInitialization(E); | ||||
6754 | if (E->getNumInits() == 1) | ||||
6755 | return StmtVisitorTy::Visit(E->getInit(0)); | ||||
6756 | return Error(E); | ||||
6757 | } | ||||
6758 | bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { | ||||
6759 | return DerivedZeroInitialization(E); | ||||
6760 | } | ||||
6761 | bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { | ||||
6762 | return DerivedZeroInitialization(E); | ||||
6763 | } | ||||
6764 | bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { | ||||
6765 | return DerivedZeroInitialization(E); | ||||
6766 | } | ||||
6767 | |||||
6768 | /// A member expression where the object is a prvalue is itself a prvalue. | ||||
6769 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
6770 | assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion" ) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6771, __PRETTY_FUNCTION__)) | ||||
6771 | "missing temporary materialization conversion")((!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion" ) ? static_cast<void> (0) : __assert_fail ("!Info.Ctx.getLangOpts().CPlusPlus11 && \"missing temporary materialization conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6771, __PRETTY_FUNCTION__)); | ||||
6772 | assert(!E->isArrow() && "missing call to bound member function?")((!E->isArrow() && "missing call to bound member function?" ) ? static_cast<void> (0) : __assert_fail ("!E->isArrow() && \"missing call to bound member function?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6772, __PRETTY_FUNCTION__)); | ||||
6773 | |||||
6774 | APValue Val; | ||||
6775 | if (!Evaluate(Val, Info, E->getBase())) | ||||
6776 | return false; | ||||
6777 | |||||
6778 | QualType BaseTy = E->getBase()->getType(); | ||||
6779 | |||||
6780 | const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); | ||||
6781 | if (!FD) return Error(E); | ||||
6782 | assert(!FD->getType()->isReferenceType() && "prvalue reference?")((!FD->getType()->isReferenceType() && "prvalue reference?" ) ? static_cast<void> (0) : __assert_fail ("!FD->getType()->isReferenceType() && \"prvalue reference?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6782, __PRETTY_FUNCTION__)); | ||||
6783 | assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6784, __PRETTY_FUNCTION__)) | ||||
6784 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6784, __PRETTY_FUNCTION__)); | ||||
6785 | |||||
6786 | // Note: there is no lvalue base here. But this case should only ever | ||||
6787 | // happen in C or in C++98, where we cannot be evaluating a constexpr | ||||
6788 | // constructor, which is the only case the base matters. | ||||
6789 | CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); | ||||
6790 | SubobjectDesignator Designator(BaseTy); | ||||
6791 | Designator.addDeclUnchecked(FD); | ||||
6792 | |||||
6793 | APValue Result; | ||||
6794 | return extractSubobject(Info, E, Obj, Designator, Result) && | ||||
6795 | DerivedSuccess(Result, E); | ||||
6796 | } | ||||
6797 | |||||
6798 | bool VisitCastExpr(const CastExpr *E) { | ||||
6799 | switch (E->getCastKind()) { | ||||
6800 | default: | ||||
6801 | break; | ||||
6802 | |||||
6803 | case CK_AtomicToNonAtomic: { | ||||
6804 | APValue AtomicVal; | ||||
6805 | // This does not need to be done in place even for class/array types: | ||||
6806 | // atomic-to-non-atomic conversion implies copying the object | ||||
6807 | // representation. | ||||
6808 | if (!Evaluate(AtomicVal, Info, E->getSubExpr())) | ||||
6809 | return false; | ||||
6810 | return DerivedSuccess(AtomicVal, E); | ||||
6811 | } | ||||
6812 | |||||
6813 | case CK_NoOp: | ||||
6814 | case CK_UserDefinedConversion: | ||||
6815 | return StmtVisitorTy::Visit(E->getSubExpr()); | ||||
6816 | |||||
6817 | case CK_LValueToRValue: { | ||||
6818 | LValue LVal; | ||||
6819 | if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) | ||||
6820 | return false; | ||||
6821 | APValue RVal; | ||||
6822 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||
6823 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||
6824 | LVal, RVal)) | ||||
6825 | return false; | ||||
6826 | return DerivedSuccess(RVal, E); | ||||
6827 | } | ||||
6828 | case CK_LValueToRValueBitCast: { | ||||
6829 | APValue DestValue, SourceValue; | ||||
6830 | if (!Evaluate(SourceValue, Info, E->getSubExpr())) | ||||
6831 | return false; | ||||
6832 | if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) | ||||
6833 | return false; | ||||
6834 | return DerivedSuccess(DestValue, E); | ||||
6835 | } | ||||
6836 | } | ||||
6837 | |||||
6838 | return Error(E); | ||||
6839 | } | ||||
6840 | |||||
6841 | bool VisitUnaryPostInc(const UnaryOperator *UO) { | ||||
6842 | return VisitUnaryPostIncDec(UO); | ||||
6843 | } | ||||
6844 | bool VisitUnaryPostDec(const UnaryOperator *UO) { | ||||
6845 | return VisitUnaryPostIncDec(UO); | ||||
6846 | } | ||||
6847 | bool VisitUnaryPostIncDec(const UnaryOperator *UO) { | ||||
6848 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
6849 | return Error(UO); | ||||
6850 | |||||
6851 | LValue LVal; | ||||
6852 | if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) | ||||
6853 | return false; | ||||
6854 | APValue RVal; | ||||
6855 | if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), | ||||
6856 | UO->isIncrementOp(), &RVal)) | ||||
6857 | return false; | ||||
6858 | return DerivedSuccess(RVal, UO); | ||||
6859 | } | ||||
6860 | |||||
6861 | bool VisitStmtExpr(const StmtExpr *E) { | ||||
6862 | // We will have checked the full-expressions inside the statement expression | ||||
6863 | // when they were completed, and don't need to check them again now. | ||||
6864 | if (Info.checkingForUndefinedBehavior()) | ||||
6865 | return Error(E); | ||||
6866 | |||||
6867 | const CompoundStmt *CS = E->getSubStmt(); | ||||
6868 | if (CS->body_empty()) | ||||
6869 | return true; | ||||
6870 | |||||
6871 | BlockScopeRAII Scope(Info); | ||||
6872 | for (CompoundStmt::const_body_iterator BI = CS->body_begin(), | ||||
6873 | BE = CS->body_end(); | ||||
6874 | /**/; ++BI) { | ||||
6875 | if (BI + 1 == BE) { | ||||
6876 | const Expr *FinalExpr = dyn_cast<Expr>(*BI); | ||||
6877 | if (!FinalExpr) { | ||||
6878 | Info.FFDiag((*BI)->getBeginLoc(), | ||||
6879 | diag::note_constexpr_stmt_expr_unsupported); | ||||
6880 | return false; | ||||
6881 | } | ||||
6882 | return this->Visit(FinalExpr) && Scope.destroy(); | ||||
6883 | } | ||||
6884 | |||||
6885 | APValue ReturnValue; | ||||
6886 | StmtResult Result = { ReturnValue, nullptr }; | ||||
6887 | EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); | ||||
6888 | if (ESR != ESR_Succeeded) { | ||||
6889 | // FIXME: If the statement-expression terminated due to 'return', | ||||
6890 | // 'break', or 'continue', it would be nice to propagate that to | ||||
6891 | // the outer statement evaluation rather than bailing out. | ||||
6892 | if (ESR != ESR_Failed) | ||||
6893 | Info.FFDiag((*BI)->getBeginLoc(), | ||||
6894 | diag::note_constexpr_stmt_expr_unsupported); | ||||
6895 | return false; | ||||
6896 | } | ||||
6897 | } | ||||
6898 | |||||
6899 | llvm_unreachable("Return from function from the loop above.")::llvm::llvm_unreachable_internal("Return from function from the loop above." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6899); | ||||
6900 | } | ||||
6901 | |||||
6902 | /// Visit a value which is evaluated, but whose value is ignored. | ||||
6903 | void VisitIgnoredValue(const Expr *E) { | ||||
6904 | EvaluateIgnoredValue(Info, E); | ||||
6905 | } | ||||
6906 | |||||
6907 | /// Potentially visit a MemberExpr's base expression. | ||||
6908 | void VisitIgnoredBaseExpression(const Expr *E) { | ||||
6909 | // While MSVC doesn't evaluate the base expression, it does diagnose the | ||||
6910 | // presence of side-effecting behavior. | ||||
6911 | if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) | ||||
6912 | return; | ||||
6913 | VisitIgnoredValue(E); | ||||
6914 | } | ||||
6915 | }; | ||||
6916 | |||||
6917 | } // namespace | ||||
6918 | |||||
6919 | //===----------------------------------------------------------------------===// | ||||
6920 | // Common base class for lvalue and temporary evaluation. | ||||
6921 | //===----------------------------------------------------------------------===// | ||||
6922 | namespace { | ||||
6923 | template<class Derived> | ||||
6924 | class LValueExprEvaluatorBase | ||||
6925 | : public ExprEvaluatorBase<Derived> { | ||||
6926 | protected: | ||||
6927 | LValue &Result; | ||||
6928 | bool InvalidBaseOK; | ||||
6929 | typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; | ||||
6930 | typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; | ||||
6931 | |||||
6932 | bool Success(APValue::LValueBase B) { | ||||
6933 | Result.set(B); | ||||
6934 | return true; | ||||
6935 | } | ||||
6936 | |||||
6937 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||
6938 | return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); | ||||
6939 | } | ||||
6940 | |||||
6941 | public: | ||||
6942 | LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) | ||||
6943 | : ExprEvaluatorBaseTy(Info), Result(Result), | ||||
6944 | InvalidBaseOK(InvalidBaseOK) {} | ||||
6945 | |||||
6946 | bool Success(const APValue &V, const Expr *E) { | ||||
6947 | Result.setFrom(this->Info.Ctx, V); | ||||
6948 | return true; | ||||
6949 | } | ||||
6950 | |||||
6951 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
6952 | // Handle non-static data members. | ||||
6953 | QualType BaseTy; | ||||
6954 | bool EvalOK; | ||||
6955 | if (E->isArrow()) { | ||||
| |||||
6956 | EvalOK = evaluatePointer(E->getBase(), Result); | ||||
6957 | BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); | ||||
6958 | } else if (E->getBase()->isRValue()) { | ||||
6959 | assert(E->getBase()->getType()->isRecordType())((E->getBase()->getType()->isRecordType()) ? static_cast <void> (0) : __assert_fail ("E->getBase()->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6959, __PRETTY_FUNCTION__)); | ||||
6960 | EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); | ||||
6961 | BaseTy = E->getBase()->getType(); | ||||
6962 | } else { | ||||
6963 | EvalOK = this->Visit(E->getBase()); | ||||
6964 | BaseTy = E->getBase()->getType(); | ||||
6965 | } | ||||
6966 | if (!EvalOK) { | ||||
6967 | if (!InvalidBaseOK) | ||||
6968 | return false; | ||||
6969 | Result.setInvalid(E); | ||||
6970 | return true; | ||||
6971 | } | ||||
6972 | |||||
6973 | const ValueDecl *MD = E->getMemberDecl(); | ||||
6974 | if (const FieldDecl *FD
| ||||
6975 | assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6976, __PRETTY_FUNCTION__)) | ||||
| |||||
6976 | FD->getParent()->getCanonicalDecl() && "record / field mismatch")((BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl () == FD->getParent()->getCanonicalDecl() && "record / field mismatch" ) ? static_cast<void> (0) : __assert_fail ("BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == FD->getParent()->getCanonicalDecl() && \"record / field mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 6976, __PRETTY_FUNCTION__)); | ||||
6977 | (void)BaseTy; | ||||
6978 | if (!HandleLValueMember(this->Info, E, Result, FD)) | ||||
6979 | return false; | ||||
6980 | } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { | ||||
6981 | if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) | ||||
6982 | return false; | ||||
6983 | } else | ||||
6984 | return this->Error(E); | ||||
6985 | |||||
6986 | if (MD->getType()->isReferenceType()) { | ||||
6987 | APValue RefValue; | ||||
6988 | if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, | ||||
6989 | RefValue)) | ||||
6990 | return false; | ||||
6991 | return Success(RefValue, E); | ||||
6992 | } | ||||
6993 | return true; | ||||
6994 | } | ||||
6995 | |||||
6996 | bool VisitBinaryOperator(const BinaryOperator *E) { | ||||
6997 | switch (E->getOpcode()) { | ||||
6998 | default: | ||||
6999 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
7000 | |||||
7001 | case BO_PtrMemD: | ||||
7002 | case BO_PtrMemI: | ||||
7003 | return HandleMemberPointerAccess(this->Info, E, Result); | ||||
7004 | } | ||||
7005 | } | ||||
7006 | |||||
7007 | bool VisitCastExpr(const CastExpr *E) { | ||||
7008 | switch (E->getCastKind()) { | ||||
7009 | default: | ||||
7010 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
7011 | |||||
7012 | case CK_DerivedToBase: | ||||
7013 | case CK_UncheckedDerivedToBase: | ||||
7014 | if (!this->Visit(E->getSubExpr())) | ||||
7015 | return false; | ||||
7016 | |||||
7017 | // Now figure out the necessary offset to add to the base LV to get from | ||||
7018 | // the derived class to the base class. | ||||
7019 | return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), | ||||
7020 | Result); | ||||
7021 | } | ||||
7022 | } | ||||
7023 | }; | ||||
7024 | } | ||||
7025 | |||||
7026 | //===----------------------------------------------------------------------===// | ||||
7027 | // LValue Evaluation | ||||
7028 | // | ||||
7029 | // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), | ||||
7030 | // function designators (in C), decl references to void objects (in C), and | ||||
7031 | // temporaries (if building with -Wno-address-of-temporary). | ||||
7032 | // | ||||
7033 | // LValue evaluation produces values comprising a base expression of one of the | ||||
7034 | // following types: | ||||
7035 | // - Declarations | ||||
7036 | // * VarDecl | ||||
7037 | // * FunctionDecl | ||||
7038 | // - Literals | ||||
7039 | // * CompoundLiteralExpr in C (and in global scope in C++) | ||||
7040 | // * StringLiteral | ||||
7041 | // * PredefinedExpr | ||||
7042 | // * ObjCStringLiteralExpr | ||||
7043 | // * ObjCEncodeExpr | ||||
7044 | // * AddrLabelExpr | ||||
7045 | // * BlockExpr | ||||
7046 | // * CallExpr for a MakeStringConstant builtin | ||||
7047 | // - typeid(T) expressions, as TypeInfoLValues | ||||
7048 | // - Locals and temporaries | ||||
7049 | // * MaterializeTemporaryExpr | ||||
7050 | // * Any Expr, with a CallIndex indicating the function in which the temporary | ||||
7051 | // was evaluated, for cases where the MaterializeTemporaryExpr is missing | ||||
7052 | // from the AST (FIXME). | ||||
7053 | // * A MaterializeTemporaryExpr that has static storage duration, with no | ||||
7054 | // CallIndex, for a lifetime-extended temporary. | ||||
7055 | // plus an offset in bytes. | ||||
7056 | //===----------------------------------------------------------------------===// | ||||
7057 | namespace { | ||||
7058 | class LValueExprEvaluator | ||||
7059 | : public LValueExprEvaluatorBase<LValueExprEvaluator> { | ||||
7060 | public: | ||||
7061 | LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : | ||||
7062 | LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} | ||||
7063 | |||||
7064 | bool VisitVarDecl(const Expr *E, const VarDecl *VD); | ||||
7065 | bool VisitUnaryPreIncDec(const UnaryOperator *UO); | ||||
7066 | |||||
7067 | bool VisitDeclRefExpr(const DeclRefExpr *E); | ||||
7068 | bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } | ||||
7069 | bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); | ||||
7070 | bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); | ||||
7071 | bool VisitMemberExpr(const MemberExpr *E); | ||||
7072 | bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } | ||||
7073 | bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } | ||||
7074 | bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); | ||||
7075 | bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); | ||||
7076 | bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); | ||||
7077 | bool VisitUnaryDeref(const UnaryOperator *E); | ||||
7078 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
7079 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
7080 | bool VisitUnaryPreInc(const UnaryOperator *UO) { | ||||
7081 | return VisitUnaryPreIncDec(UO); | ||||
7082 | } | ||||
7083 | bool VisitUnaryPreDec(const UnaryOperator *UO) { | ||||
7084 | return VisitUnaryPreIncDec(UO); | ||||
7085 | } | ||||
7086 | bool VisitBinAssign(const BinaryOperator *BO); | ||||
7087 | bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); | ||||
7088 | |||||
7089 | bool VisitCastExpr(const CastExpr *E) { | ||||
7090 | switch (E->getCastKind()) { | ||||
7091 | default: | ||||
7092 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
7093 | |||||
7094 | case CK_LValueBitCast: | ||||
7095 | this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
7096 | if (!Visit(E->getSubExpr())) | ||||
7097 | return false; | ||||
7098 | Result.Designator.setInvalid(); | ||||
7099 | return true; | ||||
7100 | |||||
7101 | case CK_BaseToDerived: | ||||
7102 | if (!Visit(E->getSubExpr())) | ||||
7103 | return false; | ||||
7104 | return HandleBaseToDerivedCast(Info, E, Result); | ||||
7105 | |||||
7106 | case CK_Dynamic: | ||||
7107 | if (!Visit(E->getSubExpr())) | ||||
7108 | return false; | ||||
7109 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||
7110 | } | ||||
7111 | } | ||||
7112 | }; | ||||
7113 | } // end anonymous namespace | ||||
7114 | |||||
7115 | /// Evaluate an expression as an lvalue. This can be legitimately called on | ||||
7116 | /// expressions which are not glvalues, in three cases: | ||||
7117 | /// * function designators in C, and | ||||
7118 | /// * "extern void" objects | ||||
7119 | /// * @selector() expressions in Objective-C | ||||
7120 | static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, | ||||
7121 | bool InvalidBaseOK) { | ||||
7122 | assert(E->isGLValue() || E->getType()->isFunctionType() ||((E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr> (E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7123, __PRETTY_FUNCTION__)) | ||||
7123 | E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E))((E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr> (E)) ? static_cast<void> (0) : __assert_fail ("E->isGLValue() || E->getType()->isFunctionType() || E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7123, __PRETTY_FUNCTION__)); | ||||
7124 | return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||
7125 | } | ||||
7126 | |||||
7127 | bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { | ||||
7128 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) | ||||
7129 | return Success(FD); | ||||
7130 | if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) | ||||
7131 | return VisitVarDecl(E, VD); | ||||
7132 | if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) | ||||
7133 | return Visit(BD->getBinding()); | ||||
7134 | return Error(E); | ||||
7135 | } | ||||
7136 | |||||
7137 | |||||
7138 | bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { | ||||
7139 | |||||
7140 | // If we are within a lambda's call operator, check whether the 'VD' referred | ||||
7141 | // to within 'E' actually represents a lambda-capture that maps to a | ||||
7142 | // data-member/field within the closure object, and if so, evaluate to the | ||||
7143 | // field or what the field refers to. | ||||
7144 | if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && | ||||
7145 | isa<DeclRefExpr>(E) && | ||||
7146 | cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { | ||||
7147 | // We don't always have a complete capture-map when checking or inferring if | ||||
7148 | // the function call operator meets the requirements of a constexpr function | ||||
7149 | // - but we don't need to evaluate the captures to determine constexprness | ||||
7150 | // (dcl.constexpr C++17). | ||||
7151 | if (Info.checkingPotentialConstantExpression()) | ||||
7152 | return false; | ||||
7153 | |||||
7154 | if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { | ||||
7155 | // Start with 'Result' referring to the complete closure object... | ||||
7156 | Result = *Info.CurrentCall->This; | ||||
7157 | // ... then update it to refer to the field of the closure object | ||||
7158 | // that represents the capture. | ||||
7159 | if (!HandleLValueMember(Info, E, Result, FD)) | ||||
7160 | return false; | ||||
7161 | // And if the field is of reference type, update 'Result' to refer to what | ||||
7162 | // the field refers to. | ||||
7163 | if (FD->getType()->isReferenceType()) { | ||||
7164 | APValue RVal; | ||||
7165 | if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, | ||||
7166 | RVal)) | ||||
7167 | return false; | ||||
7168 | Result.setFrom(Info.Ctx, RVal); | ||||
7169 | } | ||||
7170 | return true; | ||||
7171 | } | ||||
7172 | } | ||||
7173 | CallStackFrame *Frame = nullptr; | ||||
7174 | if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { | ||||
7175 | // Only if a local variable was declared in the function currently being | ||||
7176 | // evaluated, do we expect to be able to find its value in the current | ||||
7177 | // frame. (Otherwise it was likely declared in an enclosing context and | ||||
7178 | // could either have a valid evaluatable value (for e.g. a constexpr | ||||
7179 | // variable) or be ill-formed (and trigger an appropriate evaluation | ||||
7180 | // diagnostic)). | ||||
7181 | if (Info.CurrentCall->Callee && | ||||
7182 | Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { | ||||
7183 | Frame = Info.CurrentCall; | ||||
7184 | } | ||||
7185 | } | ||||
7186 | |||||
7187 | if (!VD->getType()->isReferenceType()) { | ||||
7188 | if (Frame) { | ||||
7189 | Result.set({VD, Frame->Index, | ||||
7190 | Info.CurrentCall->getCurrentTemporaryVersion(VD)}); | ||||
7191 | return true; | ||||
7192 | } | ||||
7193 | return Success(VD); | ||||
7194 | } | ||||
7195 | |||||
7196 | APValue *V; | ||||
7197 | if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) | ||||
7198 | return false; | ||||
7199 | if (!V->hasValue()) { | ||||
7200 | // FIXME: Is it possible for V to be indeterminate here? If so, we should | ||||
7201 | // adjust the diagnostic to say that. | ||||
7202 | if (!Info.checkingPotentialConstantExpression()) | ||||
7203 | Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); | ||||
7204 | return false; | ||||
7205 | } | ||||
7206 | return Success(*V, E); | ||||
7207 | } | ||||
7208 | |||||
7209 | bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( | ||||
7210 | const MaterializeTemporaryExpr *E) { | ||||
7211 | // Walk through the expression to find the materialized temporary itself. | ||||
7212 | SmallVector<const Expr *, 2> CommaLHSs; | ||||
7213 | SmallVector<SubobjectAdjustment, 2> Adjustments; | ||||
7214 | const Expr *Inner = E->GetTemporaryExpr()-> | ||||
7215 | skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); | ||||
7216 | |||||
7217 | // If we passed any comma operators, evaluate their LHSs. | ||||
7218 | for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) | ||||
7219 | if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) | ||||
7220 | return false; | ||||
7221 | |||||
7222 | // A materialized temporary with static storage duration can appear within the | ||||
7223 | // result of a constant expression evaluation, so we need to preserve its | ||||
7224 | // value for use outside this evaluation. | ||||
7225 | APValue *Value; | ||||
7226 | if (E->getStorageDuration() == SD_Static) { | ||||
7227 | Value = Info.Ctx.getMaterializedTemporaryValue(E, true); | ||||
7228 | *Value = APValue(); | ||||
7229 | Result.set(E); | ||||
7230 | } else { | ||||
7231 | Value = &Info.CurrentCall->createTemporary( | ||||
7232 | E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); | ||||
7233 | } | ||||
7234 | |||||
7235 | QualType Type = Inner->getType(); | ||||
7236 | |||||
7237 | // Materialize the temporary itself. | ||||
7238 | if (!EvaluateInPlace(*Value, Info, Result, Inner)) { | ||||
7239 | *Value = APValue(); | ||||
7240 | return false; | ||||
7241 | } | ||||
7242 | |||||
7243 | // Adjust our lvalue to refer to the desired subobject. | ||||
7244 | for (unsigned I = Adjustments.size(); I != 0; /**/) { | ||||
7245 | --I; | ||||
7246 | switch (Adjustments[I].Kind) { | ||||
7247 | case SubobjectAdjustment::DerivedToBaseAdjustment: | ||||
7248 | if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, | ||||
7249 | Type, Result)) | ||||
7250 | return false; | ||||
7251 | Type = Adjustments[I].DerivedToBase.BasePath->getType(); | ||||
7252 | break; | ||||
7253 | |||||
7254 | case SubobjectAdjustment::FieldAdjustment: | ||||
7255 | if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) | ||||
7256 | return false; | ||||
7257 | Type = Adjustments[I].Field->getType(); | ||||
7258 | break; | ||||
7259 | |||||
7260 | case SubobjectAdjustment::MemberPointerAdjustment: | ||||
7261 | if (!HandleMemberPointerAccess(this->Info, Type, Result, | ||||
7262 | Adjustments[I].Ptr.RHS)) | ||||
7263 | return false; | ||||
7264 | Type = Adjustments[I].Ptr.MPT->getPointeeType(); | ||||
7265 | break; | ||||
7266 | } | ||||
7267 | } | ||||
7268 | |||||
7269 | return true; | ||||
7270 | } | ||||
7271 | |||||
7272 | bool | ||||
7273 | LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { | ||||
7274 | assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && "lvalue compound literal in c++?") ? static_cast<void> (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7275, __PRETTY_FUNCTION__)) | ||||
7275 | "lvalue compound literal in c++?")(((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && "lvalue compound literal in c++?") ? static_cast<void> (0) : __assert_fail ("(!Info.getLangOpts().CPlusPlus || E->isFileScope()) && \"lvalue compound literal in c++?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7275, __PRETTY_FUNCTION__)); | ||||
7276 | // Defer visiting the literal until the lvalue-to-rvalue conversion. We can | ||||
7277 | // only see this when folding in C, so there's no standard to follow here. | ||||
7278 | return Success(E); | ||||
7279 | } | ||||
7280 | |||||
7281 | bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { | ||||
7282 | TypeInfoLValue TypeInfo; | ||||
7283 | |||||
7284 | if (!E->isPotentiallyEvaluated()) { | ||||
7285 | if (E->isTypeOperand()) | ||||
7286 | TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); | ||||
7287 | else | ||||
7288 | TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); | ||||
7289 | } else { | ||||
7290 | if (!Info.Ctx.getLangOpts().CPlusPlus2a) { | ||||
7291 | Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) | ||||
7292 | << E->getExprOperand()->getType() | ||||
7293 | << E->getExprOperand()->getSourceRange(); | ||||
7294 | } | ||||
7295 | |||||
7296 | if (!Visit(E->getExprOperand())) | ||||
7297 | return false; | ||||
7298 | |||||
7299 | Optional<DynamicType> DynType = | ||||
7300 | ComputeDynamicType(Info, E, Result, AK_TypeId); | ||||
7301 | if (!DynType) | ||||
7302 | return false; | ||||
7303 | |||||
7304 | TypeInfo = | ||||
7305 | TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); | ||||
7306 | } | ||||
7307 | |||||
7308 | return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); | ||||
7309 | } | ||||
7310 | |||||
7311 | bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { | ||||
7312 | return Success(E); | ||||
7313 | } | ||||
7314 | |||||
7315 | bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { | ||||
7316 | // Handle static data members. | ||||
7317 | if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { | ||||
7318 | VisitIgnoredBaseExpression(E->getBase()); | ||||
7319 | return VisitVarDecl(E, VD); | ||||
7320 | } | ||||
7321 | |||||
7322 | // Handle static member functions. | ||||
7323 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { | ||||
7324 | if (MD->isStatic()) { | ||||
7325 | VisitIgnoredBaseExpression(E->getBase()); | ||||
7326 | return Success(MD); | ||||
7327 | } | ||||
7328 | } | ||||
7329 | |||||
7330 | // Handle non-static data members. | ||||
7331 | return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||
7332 | } | ||||
7333 | |||||
7334 | bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { | ||||
7335 | // FIXME: Deal with vectors as array subscript bases. | ||||
7336 | if (E->getBase()->getType()->isVectorType()) | ||||
7337 | return Error(E); | ||||
7338 | |||||
7339 | bool Success = true; | ||||
7340 | if (!evaluatePointer(E->getBase(), Result)) { | ||||
7341 | if (!Info.noteFailure()) | ||||
7342 | return false; | ||||
7343 | Success = false; | ||||
7344 | } | ||||
7345 | |||||
7346 | APSInt Index; | ||||
7347 | if (!EvaluateInteger(E->getIdx(), Index, Info)) | ||||
7348 | return false; | ||||
7349 | |||||
7350 | return Success && | ||||
7351 | HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); | ||||
7352 | } | ||||
7353 | |||||
7354 | bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { | ||||
7355 | return evaluatePointer(E->getSubExpr(), Result); | ||||
7356 | } | ||||
7357 | |||||
7358 | bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
7359 | if (!Visit(E->getSubExpr())) | ||||
7360 | return false; | ||||
7361 | // __real is a no-op on scalar lvalues. | ||||
7362 | if (E->getSubExpr()->getType()->isAnyComplexType()) | ||||
7363 | HandleLValueComplexElement(Info, E, Result, E->getType(), false); | ||||
7364 | return true; | ||||
7365 | } | ||||
7366 | |||||
7367 | bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
7368 | assert(E->getSubExpr()->getType()->isAnyComplexType() &&((E->getSubExpr()->getType()->isAnyComplexType() && "lvalue __imag__ on scalar?") ? static_cast<void> (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7369, __PRETTY_FUNCTION__)) | ||||
7369 | "lvalue __imag__ on scalar?")((E->getSubExpr()->getType()->isAnyComplexType() && "lvalue __imag__ on scalar?") ? static_cast<void> (0) : __assert_fail ("E->getSubExpr()->getType()->isAnyComplexType() && \"lvalue __imag__ on scalar?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7369, __PRETTY_FUNCTION__)); | ||||
7370 | if (!Visit(E->getSubExpr())) | ||||
7371 | return false; | ||||
7372 | HandleLValueComplexElement(Info, E, Result, E->getType(), true); | ||||
7373 | return true; | ||||
7374 | } | ||||
7375 | |||||
7376 | bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { | ||||
7377 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
7378 | return Error(UO); | ||||
7379 | |||||
7380 | if (!this->Visit(UO->getSubExpr())) | ||||
7381 | return false; | ||||
7382 | |||||
7383 | return handleIncDec( | ||||
7384 | this->Info, UO, Result, UO->getSubExpr()->getType(), | ||||
7385 | UO->isIncrementOp(), nullptr); | ||||
7386 | } | ||||
7387 | |||||
7388 | bool LValueExprEvaluator::VisitCompoundAssignOperator( | ||||
7389 | const CompoundAssignOperator *CAO) { | ||||
7390 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
7391 | return Error(CAO); | ||||
7392 | |||||
7393 | APValue RHS; | ||||
7394 | |||||
7395 | // The overall lvalue result is the result of evaluating the LHS. | ||||
7396 | if (!this->Visit(CAO->getLHS())) { | ||||
7397 | if (Info.noteFailure()) | ||||
7398 | Evaluate(RHS, this->Info, CAO->getRHS()); | ||||
7399 | return false; | ||||
7400 | } | ||||
7401 | |||||
7402 | if (!Evaluate(RHS, this->Info, CAO->getRHS())) | ||||
7403 | return false; | ||||
7404 | |||||
7405 | return handleCompoundAssignment( | ||||
7406 | this->Info, CAO, | ||||
7407 | Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), | ||||
7408 | CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); | ||||
7409 | } | ||||
7410 | |||||
7411 | bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { | ||||
7412 | if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) | ||||
7413 | return Error(E); | ||||
7414 | |||||
7415 | APValue NewVal; | ||||
7416 | |||||
7417 | if (!this->Visit(E->getLHS())) { | ||||
7418 | if (Info.noteFailure()) | ||||
7419 | Evaluate(NewVal, this->Info, E->getRHS()); | ||||
7420 | return false; | ||||
7421 | } | ||||
7422 | |||||
7423 | if (!Evaluate(NewVal, this->Info, E->getRHS())) | ||||
7424 | return false; | ||||
7425 | |||||
7426 | if (Info.getLangOpts().CPlusPlus2a && | ||||
7427 | !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) | ||||
7428 | return false; | ||||
7429 | |||||
7430 | return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), | ||||
7431 | NewVal); | ||||
7432 | } | ||||
7433 | |||||
7434 | //===----------------------------------------------------------------------===// | ||||
7435 | // Pointer Evaluation | ||||
7436 | //===----------------------------------------------------------------------===// | ||||
7437 | |||||
7438 | /// Attempts to compute the number of bytes available at the pointer | ||||
7439 | /// returned by a function with the alloc_size attribute. Returns true if we | ||||
7440 | /// were successful. Places an unsigned number into `Result`. | ||||
7441 | /// | ||||
7442 | /// This expects the given CallExpr to be a call to a function with an | ||||
7443 | /// alloc_size attribute. | ||||
7444 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||
7445 | const CallExpr *Call, | ||||
7446 | llvm::APInt &Result) { | ||||
7447 | const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); | ||||
7448 | |||||
7449 | assert(AllocSize && AllocSize->getElemSizeParam().isValid())((AllocSize && AllocSize->getElemSizeParam().isValid ()) ? static_cast<void> (0) : __assert_fail ("AllocSize && AllocSize->getElemSizeParam().isValid()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7449, __PRETTY_FUNCTION__)); | ||||
7450 | unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); | ||||
7451 | unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); | ||||
7452 | if (Call->getNumArgs() <= SizeArgNo) | ||||
7453 | return false; | ||||
7454 | |||||
7455 | auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { | ||||
7456 | Expr::EvalResult ExprResult; | ||||
7457 | if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) | ||||
7458 | return false; | ||||
7459 | Into = ExprResult.Val.getInt(); | ||||
7460 | if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) | ||||
7461 | return false; | ||||
7462 | Into = Into.zextOrSelf(BitsInSizeT); | ||||
7463 | return true; | ||||
7464 | }; | ||||
7465 | |||||
7466 | APSInt SizeOfElem; | ||||
7467 | if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) | ||||
7468 | return false; | ||||
7469 | |||||
7470 | if (!AllocSize->getNumElemsParam().isValid()) { | ||||
7471 | Result = std::move(SizeOfElem); | ||||
7472 | return true; | ||||
7473 | } | ||||
7474 | |||||
7475 | APSInt NumberOfElems; | ||||
7476 | unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); | ||||
7477 | if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) | ||||
7478 | return false; | ||||
7479 | |||||
7480 | bool Overflow; | ||||
7481 | llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); | ||||
7482 | if (Overflow) | ||||
7483 | return false; | ||||
7484 | |||||
7485 | Result = std::move(BytesAvailable); | ||||
7486 | return true; | ||||
7487 | } | ||||
7488 | |||||
7489 | /// Convenience function. LVal's base must be a call to an alloc_size | ||||
7490 | /// function. | ||||
7491 | static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, | ||||
7492 | const LValue &LVal, | ||||
7493 | llvm::APInt &Result) { | ||||
7494 | assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function" ) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7495, __PRETTY_FUNCTION__)) | ||||
7495 | "Can't get the size of a non alloc_size function")((isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function" ) ? static_cast<void> (0) : __assert_fail ("isBaseAnAllocSizeCall(LVal.getLValueBase()) && \"Can't get the size of a non alloc_size function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7495, __PRETTY_FUNCTION__)); | ||||
7496 | const auto *Base = LVal.getLValueBase().get<const Expr *>(); | ||||
7497 | const CallExpr *CE = tryUnwrapAllocSizeCall(Base); | ||||
7498 | return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); | ||||
7499 | } | ||||
7500 | |||||
7501 | /// Attempts to evaluate the given LValueBase as the result of a call to | ||||
7502 | /// a function with the alloc_size attribute. If it was possible to do so, this | ||||
7503 | /// function will return true, make Result's Base point to said function call, | ||||
7504 | /// and mark Result's Base as invalid. | ||||
7505 | static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, | ||||
7506 | LValue &Result) { | ||||
7507 | if (Base.isNull()) | ||||
7508 | return false; | ||||
7509 | |||||
7510 | // Because we do no form of static analysis, we only support const variables. | ||||
7511 | // | ||||
7512 | // Additionally, we can't support parameters, nor can we support static | ||||
7513 | // variables (in the latter case, use-before-assign isn't UB; in the former, | ||||
7514 | // we have no clue what they'll be assigned to). | ||||
7515 | const auto *VD = | ||||
7516 | dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); | ||||
7517 | if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) | ||||
7518 | return false; | ||||
7519 | |||||
7520 | const Expr *Init = VD->getAnyInitializer(); | ||||
7521 | if (!Init) | ||||
7522 | return false; | ||||
7523 | |||||
7524 | const Expr *E = Init->IgnoreParens(); | ||||
7525 | if (!tryUnwrapAllocSizeCall(E)) | ||||
7526 | return false; | ||||
7527 | |||||
7528 | // Store E instead of E unwrapped so that the type of the LValue's base is | ||||
7529 | // what the user wanted. | ||||
7530 | Result.setInvalid(E); | ||||
7531 | |||||
7532 | QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||
7533 | Result.addUnsizedArray(Info, E, Pointee); | ||||
7534 | return true; | ||||
7535 | } | ||||
7536 | |||||
7537 | namespace { | ||||
7538 | class PointerExprEvaluator | ||||
7539 | : public ExprEvaluatorBase<PointerExprEvaluator> { | ||||
7540 | LValue &Result; | ||||
7541 | bool InvalidBaseOK; | ||||
7542 | |||||
7543 | bool Success(const Expr *E) { | ||||
7544 | Result.set(E); | ||||
7545 | return true; | ||||
7546 | } | ||||
7547 | |||||
7548 | bool evaluateLValue(const Expr *E, LValue &Result) { | ||||
7549 | return EvaluateLValue(E, Result, Info, InvalidBaseOK); | ||||
7550 | } | ||||
7551 | |||||
7552 | bool evaluatePointer(const Expr *E, LValue &Result) { | ||||
7553 | return EvaluatePointer(E, Result, Info, InvalidBaseOK); | ||||
7554 | } | ||||
7555 | |||||
7556 | bool visitNonBuiltinCallExpr(const CallExpr *E); | ||||
7557 | public: | ||||
7558 | |||||
7559 | PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) | ||||
7560 | : ExprEvaluatorBaseTy(info), Result(Result), | ||||
7561 | InvalidBaseOK(InvalidBaseOK) {} | ||||
7562 | |||||
7563 | bool Success(const APValue &V, const Expr *E) { | ||||
7564 | Result.setFrom(Info.Ctx, V); | ||||
7565 | return true; | ||||
7566 | } | ||||
7567 | bool ZeroInitialization(const Expr *E) { | ||||
7568 | auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); | ||||
7569 | Result.setNull(E->getType(), TargetVal); | ||||
7570 | return true; | ||||
7571 | } | ||||
7572 | |||||
7573 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
7574 | bool VisitCastExpr(const CastExpr* E); | ||||
7575 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||
7576 | bool VisitObjCStringLiteral(const ObjCStringLiteral *E) | ||||
7577 | { return Success(E); } | ||||
7578 | bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { | ||||
7579 | if (E->isExpressibleAsConstantInitializer()) | ||||
7580 | return Success(E); | ||||
7581 | if (Info.noteFailure()) | ||||
7582 | EvaluateIgnoredValue(Info, E->getSubExpr()); | ||||
7583 | return Error(E); | ||||
7584 | } | ||||
7585 | bool VisitAddrLabelExpr(const AddrLabelExpr *E) | ||||
7586 | { return Success(E); } | ||||
7587 | bool VisitCallExpr(const CallExpr *E); | ||||
7588 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||
7589 | bool VisitBlockExpr(const BlockExpr *E) { | ||||
7590 | if (!E->getBlockDecl()->hasCaptures()) | ||||
7591 | return Success(E); | ||||
7592 | return Error(E); | ||||
7593 | } | ||||
7594 | bool VisitCXXThisExpr(const CXXThisExpr *E) { | ||||
7595 | // Can't look at 'this' when checking a potential constant expression. | ||||
7596 | if (Info.checkingPotentialConstantExpression()) | ||||
7597 | return false; | ||||
7598 | if (!Info.CurrentCall->This) { | ||||
7599 | if (Info.getLangOpts().CPlusPlus11) | ||||
7600 | Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); | ||||
7601 | else | ||||
7602 | Info.FFDiag(E); | ||||
7603 | return false; | ||||
7604 | } | ||||
7605 | Result = *Info.CurrentCall->This; | ||||
7606 | // If we are inside a lambda's call operator, the 'this' expression refers | ||||
7607 | // to the enclosing '*this' object (either by value or reference) which is | ||||
7608 | // either copied into the closure object's field that represents the '*this' | ||||
7609 | // or refers to '*this'. | ||||
7610 | if (isLambdaCallOperator(Info.CurrentCall->Callee)) { | ||||
7611 | // Update 'Result' to refer to the data member/field of the closure object | ||||
7612 | // that represents the '*this' capture. | ||||
7613 | if (!HandleLValueMember(Info, E, Result, | ||||
7614 | Info.CurrentCall->LambdaThisCaptureField)) | ||||
7615 | return false; | ||||
7616 | // If we captured '*this' by reference, replace the field with its referent. | ||||
7617 | if (Info.CurrentCall->LambdaThisCaptureField->getType() | ||||
7618 | ->isPointerType()) { | ||||
7619 | APValue RVal; | ||||
7620 | if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, | ||||
7621 | RVal)) | ||||
7622 | return false; | ||||
7623 | |||||
7624 | Result.setFrom(Info.Ctx, RVal); | ||||
7625 | } | ||||
7626 | } | ||||
7627 | return true; | ||||
7628 | } | ||||
7629 | |||||
7630 | bool VisitCXXNewExpr(const CXXNewExpr *E); | ||||
7631 | |||||
7632 | bool VisitSourceLocExpr(const SourceLocExpr *E) { | ||||
7633 | assert(E->isStringType() && "SourceLocExpr isn't a pointer type?")((E->isStringType() && "SourceLocExpr isn't a pointer type?" ) ? static_cast<void> (0) : __assert_fail ("E->isStringType() && \"SourceLocExpr isn't a pointer type?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7633, __PRETTY_FUNCTION__)); | ||||
7634 | APValue LValResult = E->EvaluateInContext( | ||||
7635 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||
7636 | Result.setFrom(Info.Ctx, LValResult); | ||||
7637 | return true; | ||||
7638 | } | ||||
7639 | |||||
7640 | // FIXME: Missing: @protocol, @selector | ||||
7641 | }; | ||||
7642 | } // end anonymous namespace | ||||
7643 | |||||
7644 | static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, | ||||
7645 | bool InvalidBaseOK) { | ||||
7646 | assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7646, __PRETTY_FUNCTION__)); | ||||
7647 | return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); | ||||
7648 | } | ||||
7649 | |||||
7650 | bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
7651 | if (E->getOpcode() != BO_Add && | ||||
7652 | E->getOpcode() != BO_Sub) | ||||
7653 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
7654 | |||||
7655 | const Expr *PExp = E->getLHS(); | ||||
7656 | const Expr *IExp = E->getRHS(); | ||||
7657 | if (IExp->getType()->isPointerType()) | ||||
7658 | std::swap(PExp, IExp); | ||||
7659 | |||||
7660 | bool EvalPtrOK = evaluatePointer(PExp, Result); | ||||
7661 | if (!EvalPtrOK && !Info.noteFailure()) | ||||
7662 | return false; | ||||
7663 | |||||
7664 | llvm::APSInt Offset; | ||||
7665 | if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) | ||||
7666 | return false; | ||||
7667 | |||||
7668 | if (E->getOpcode() == BO_Sub) | ||||
7669 | negateAsSigned(Offset); | ||||
7670 | |||||
7671 | QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); | ||||
7672 | return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); | ||||
7673 | } | ||||
7674 | |||||
7675 | bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||
7676 | return evaluateLValue(E->getSubExpr(), Result); | ||||
7677 | } | ||||
7678 | |||||
7679 | bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
7680 | const Expr *SubExpr = E->getSubExpr(); | ||||
7681 | |||||
7682 | switch (E->getCastKind()) { | ||||
7683 | default: | ||||
7684 | break; | ||||
7685 | case CK_BitCast: | ||||
7686 | case CK_CPointerToObjCPointerCast: | ||||
7687 | case CK_BlockPointerToObjCPointerCast: | ||||
7688 | case CK_AnyPointerToBlockPointerCast: | ||||
7689 | case CK_AddressSpaceConversion: | ||||
7690 | if (!Visit(SubExpr)) | ||||
7691 | return false; | ||||
7692 | // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are | ||||
7693 | // permitted in constant expressions in C++11. Bitcasts from cv void* are | ||||
7694 | // also static_casts, but we disallow them as a resolution to DR1312. | ||||
7695 | if (!E->getType()->isVoidPointerType()) { | ||||
7696 | Result.Designator.setInvalid(); | ||||
7697 | if (SubExpr->getType()->isVoidPointerType()) | ||||
7698 | CCEDiag(E, diag::note_constexpr_invalid_cast) | ||||
7699 | << 3 << SubExpr->getType(); | ||||
7700 | else | ||||
7701 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
7702 | } | ||||
7703 | if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) | ||||
7704 | ZeroInitialization(E); | ||||
7705 | return true; | ||||
7706 | |||||
7707 | case CK_DerivedToBase: | ||||
7708 | case CK_UncheckedDerivedToBase: | ||||
7709 | if (!evaluatePointer(E->getSubExpr(), Result)) | ||||
7710 | return false; | ||||
7711 | if (!Result.Base && Result.Offset.isZero()) | ||||
7712 | return true; | ||||
7713 | |||||
7714 | // Now figure out the necessary offset to add to the base LV to get from | ||||
7715 | // the derived class to the base class. | ||||
7716 | return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> | ||||
7717 | castAs<PointerType>()->getPointeeType(), | ||||
7718 | Result); | ||||
7719 | |||||
7720 | case CK_BaseToDerived: | ||||
7721 | if (!Visit(E->getSubExpr())) | ||||
7722 | return false; | ||||
7723 | if (!Result.Base && Result.Offset.isZero()) | ||||
7724 | return true; | ||||
7725 | return HandleBaseToDerivedCast(Info, E, Result); | ||||
7726 | |||||
7727 | case CK_Dynamic: | ||||
7728 | if (!Visit(E->getSubExpr())) | ||||
7729 | return false; | ||||
7730 | return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); | ||||
7731 | |||||
7732 | case CK_NullToPointer: | ||||
7733 | VisitIgnoredValue(E->getSubExpr()); | ||||
7734 | return ZeroInitialization(E); | ||||
7735 | |||||
7736 | case CK_IntegralToPointer: { | ||||
7737 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
7738 | |||||
7739 | APValue Value; | ||||
7740 | if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) | ||||
7741 | break; | ||||
7742 | |||||
7743 | if (Value.isInt()) { | ||||
7744 | unsigned Size = Info.Ctx.getTypeSize(E->getType()); | ||||
7745 | uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); | ||||
7746 | Result.Base = (Expr*)nullptr; | ||||
7747 | Result.InvalidBase = false; | ||||
7748 | Result.Offset = CharUnits::fromQuantity(N); | ||||
7749 | Result.Designator.setInvalid(); | ||||
7750 | Result.IsNullPtr = false; | ||||
7751 | return true; | ||||
7752 | } else { | ||||
7753 | // Cast is of an lvalue, no need to change value. | ||||
7754 | Result.setFrom(Info.Ctx, Value); | ||||
7755 | return true; | ||||
7756 | } | ||||
7757 | } | ||||
7758 | |||||
7759 | case CK_ArrayToPointerDecay: { | ||||
7760 | if (SubExpr->isGLValue()) { | ||||
7761 | if (!evaluateLValue(SubExpr, Result)) | ||||
7762 | return false; | ||||
7763 | } else { | ||||
7764 | APValue &Value = Info.CurrentCall->createTemporary( | ||||
7765 | SubExpr, SubExpr->getType(), false, Result); | ||||
7766 | if (!EvaluateInPlace(Value, Info, Result, SubExpr)) | ||||
7767 | return false; | ||||
7768 | } | ||||
7769 | // The result is a pointer to the first element of the array. | ||||
7770 | auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); | ||||
7771 | if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) | ||||
7772 | Result.addArray(Info, E, CAT); | ||||
7773 | else | ||||
7774 | Result.addUnsizedArray(Info, E, AT->getElementType()); | ||||
7775 | return true; | ||||
7776 | } | ||||
7777 | |||||
7778 | case CK_FunctionToPointerDecay: | ||||
7779 | return evaluateLValue(SubExpr, Result); | ||||
7780 | |||||
7781 | case CK_LValueToRValue: { | ||||
7782 | LValue LVal; | ||||
7783 | if (!evaluateLValue(E->getSubExpr(), LVal)) | ||||
7784 | return false; | ||||
7785 | |||||
7786 | APValue RVal; | ||||
7787 | // Note, we use the subexpression's type in order to retain cv-qualifiers. | ||||
7788 | if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), | ||||
7789 | LVal, RVal)) | ||||
7790 | return InvalidBaseOK && | ||||
7791 | evaluateLValueAsAllocSize(Info, LVal.Base, Result); | ||||
7792 | return Success(RVal, E); | ||||
7793 | } | ||||
7794 | } | ||||
7795 | |||||
7796 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
7797 | } | ||||
7798 | |||||
7799 | static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, | ||||
7800 | UnaryExprOrTypeTrait ExprKind) { | ||||
7801 | // C++ [expr.alignof]p3: | ||||
7802 | // When alignof is applied to a reference type, the result is the | ||||
7803 | // alignment of the referenced type. | ||||
7804 | if (const ReferenceType *Ref = T->getAs<ReferenceType>()) | ||||
7805 | T = Ref->getPointeeType(); | ||||
7806 | |||||
7807 | if (T.getQualifiers().hasUnaligned()) | ||||
7808 | return CharUnits::One(); | ||||
7809 | |||||
7810 | const bool AlignOfReturnsPreferred = | ||||
7811 | Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; | ||||
7812 | |||||
7813 | // __alignof is defined to return the preferred alignment. | ||||
7814 | // Before 8, clang returned the preferred alignment for alignof and _Alignof | ||||
7815 | // as well. | ||||
7816 | if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) | ||||
7817 | return Info.Ctx.toCharUnitsFromBits( | ||||
7818 | Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); | ||||
7819 | // alignof and _Alignof are defined to return the ABI alignment. | ||||
7820 | else if (ExprKind == UETT_AlignOf) | ||||
7821 | return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); | ||||
7822 | else | ||||
7823 | llvm_unreachable("GetAlignOfType on a non-alignment ExprKind")::llvm::llvm_unreachable_internal("GetAlignOfType on a non-alignment ExprKind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7823); | ||||
7824 | } | ||||
7825 | |||||
7826 | static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, | ||||
7827 | UnaryExprOrTypeTrait ExprKind) { | ||||
7828 | E = E->IgnoreParens(); | ||||
7829 | |||||
7830 | // The kinds of expressions that we have special-case logic here for | ||||
7831 | // should be kept up to date with the special checks for those | ||||
7832 | // expressions in Sema. | ||||
7833 | |||||
7834 | // alignof decl is always accepted, even if it doesn't make sense: we default | ||||
7835 | // to 1 in those cases. | ||||
7836 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) | ||||
7837 | return Info.Ctx.getDeclAlign(DRE->getDecl(), | ||||
7838 | /*RefAsPointee*/true); | ||||
7839 | |||||
7840 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) | ||||
7841 | return Info.Ctx.getDeclAlign(ME->getMemberDecl(), | ||||
7842 | /*RefAsPointee*/true); | ||||
7843 | |||||
7844 | return GetAlignOfType(Info, E->getType(), ExprKind); | ||||
7845 | } | ||||
7846 | |||||
7847 | // To be clear: this happily visits unsupported builtins. Better name welcomed. | ||||
7848 | bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { | ||||
7849 | if (ExprEvaluatorBaseTy::VisitCallExpr(E)) | ||||
7850 | return true; | ||||
7851 | |||||
7852 | if (!(InvalidBaseOK && getAllocSizeAttr(E))) | ||||
7853 | return false; | ||||
7854 | |||||
7855 | Result.setInvalid(E); | ||||
7856 | QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); | ||||
7857 | Result.addUnsizedArray(Info, E, PointeeTy); | ||||
7858 | return true; | ||||
7859 | } | ||||
7860 | |||||
7861 | bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
7862 | if (IsStringLiteralCall(E)) | ||||
7863 | return Success(E); | ||||
7864 | |||||
7865 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||
7866 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||
7867 | |||||
7868 | return visitNonBuiltinCallExpr(E); | ||||
7869 | } | ||||
7870 | |||||
7871 | bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||
7872 | unsigned BuiltinOp) { | ||||
7873 | switch (BuiltinOp) { | ||||
7874 | case Builtin::BI__builtin_addressof: | ||||
7875 | return evaluateLValue(E->getArg(0), Result); | ||||
7876 | case Builtin::BI__builtin_assume_aligned: { | ||||
7877 | // We need to be very careful here because: if the pointer does not have the | ||||
7878 | // asserted alignment, then the behavior is undefined, and undefined | ||||
7879 | // behavior is non-constant. | ||||
7880 | if (!evaluatePointer(E->getArg(0), Result)) | ||||
7881 | return false; | ||||
7882 | |||||
7883 | LValue OffsetResult(Result); | ||||
7884 | APSInt Alignment; | ||||
7885 | if (!EvaluateInteger(E->getArg(1), Alignment, Info)) | ||||
7886 | return false; | ||||
7887 | CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); | ||||
7888 | |||||
7889 | if (E->getNumArgs() > 2) { | ||||
7890 | APSInt Offset; | ||||
7891 | if (!EvaluateInteger(E->getArg(2), Offset, Info)) | ||||
7892 | return false; | ||||
7893 | |||||
7894 | int64_t AdditionalOffset = -Offset.getZExtValue(); | ||||
7895 | OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); | ||||
7896 | } | ||||
7897 | |||||
7898 | // If there is a base object, then it must have the correct alignment. | ||||
7899 | if (OffsetResult.Base) { | ||||
7900 | CharUnits BaseAlignment; | ||||
7901 | if (const ValueDecl *VD = | ||||
7902 | OffsetResult.Base.dyn_cast<const ValueDecl*>()) { | ||||
7903 | BaseAlignment = Info.Ctx.getDeclAlign(VD); | ||||
7904 | } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { | ||||
7905 | BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); | ||||
7906 | } else { | ||||
7907 | BaseAlignment = GetAlignOfType( | ||||
7908 | Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); | ||||
7909 | } | ||||
7910 | |||||
7911 | if (BaseAlignment < Align) { | ||||
7912 | Result.Designator.setInvalid(); | ||||
7913 | // FIXME: Add support to Diagnostic for long / long long. | ||||
7914 | CCEDiag(E->getArg(0), | ||||
7915 | diag::note_constexpr_baa_insufficient_alignment) << 0 | ||||
7916 | << (unsigned)BaseAlignment.getQuantity() | ||||
7917 | << (unsigned)Align.getQuantity(); | ||||
7918 | return false; | ||||
7919 | } | ||||
7920 | } | ||||
7921 | |||||
7922 | // The offset must also have the correct alignment. | ||||
7923 | if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { | ||||
7924 | Result.Designator.setInvalid(); | ||||
7925 | |||||
7926 | (OffsetResult.Base | ||||
7927 | ? CCEDiag(E->getArg(0), | ||||
7928 | diag::note_constexpr_baa_insufficient_alignment) << 1 | ||||
7929 | : CCEDiag(E->getArg(0), | ||||
7930 | diag::note_constexpr_baa_value_insufficient_alignment)) | ||||
7931 | << (int)OffsetResult.Offset.getQuantity() | ||||
7932 | << (unsigned)Align.getQuantity(); | ||||
7933 | return false; | ||||
7934 | } | ||||
7935 | |||||
7936 | return true; | ||||
7937 | } | ||||
7938 | case Builtin::BI__builtin_launder: | ||||
7939 | return evaluatePointer(E->getArg(0), Result); | ||||
7940 | case Builtin::BIstrchr: | ||||
7941 | case Builtin::BIwcschr: | ||||
7942 | case Builtin::BImemchr: | ||||
7943 | case Builtin::BIwmemchr: | ||||
7944 | if (Info.getLangOpts().CPlusPlus11) | ||||
7945 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
7946 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
7947 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
7948 | else | ||||
7949 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
7950 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
7951 | case Builtin::BI__builtin_strchr: | ||||
7952 | case Builtin::BI__builtin_wcschr: | ||||
7953 | case Builtin::BI__builtin_memchr: | ||||
7954 | case Builtin::BI__builtin_char_memchr: | ||||
7955 | case Builtin::BI__builtin_wmemchr: { | ||||
7956 | if (!Visit(E->getArg(0))) | ||||
7957 | return false; | ||||
7958 | APSInt Desired; | ||||
7959 | if (!EvaluateInteger(E->getArg(1), Desired, Info)) | ||||
7960 | return false; | ||||
7961 | uint64_t MaxLength = uint64_t(-1); | ||||
7962 | if (BuiltinOp != Builtin::BIstrchr && | ||||
7963 | BuiltinOp != Builtin::BIwcschr && | ||||
7964 | BuiltinOp != Builtin::BI__builtin_strchr && | ||||
7965 | BuiltinOp != Builtin::BI__builtin_wcschr) { | ||||
7966 | APSInt N; | ||||
7967 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
7968 | return false; | ||||
7969 | MaxLength = N.getExtValue(); | ||||
7970 | } | ||||
7971 | // We cannot find the value if there are no candidates to match against. | ||||
7972 | if (MaxLength == 0u) | ||||
7973 | return ZeroInitialization(E); | ||||
7974 | if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
7975 | Result.Designator.Invalid) | ||||
7976 | return false; | ||||
7977 | QualType CharTy = Result.Designator.getType(Info.Ctx); | ||||
7978 | bool IsRawByte = BuiltinOp == Builtin::BImemchr || | ||||
7979 | BuiltinOp == Builtin::BI__builtin_memchr; | ||||
7980 | assert(IsRawByte ||((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)) | ||||
7981 | Info.Ctx.hasSameUnqualifiedType(((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)) | ||||
7982 | CharTy, E->getArg(0)->getType()->getPointeeType()))((IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E-> getArg(0)->getType()->getPointeeType())) ? static_cast< void> (0) : __assert_fail ("IsRawByte || Info.Ctx.hasSameUnqualifiedType( CharTy, E->getArg(0)->getType()->getPointeeType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 7982, __PRETTY_FUNCTION__)); | ||||
7983 | // Pointers to const void may point to objects of incomplete type. | ||||
7984 | if (IsRawByte && CharTy->isIncompleteType()) { | ||||
7985 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; | ||||
7986 | return false; | ||||
7987 | } | ||||
7988 | // Give up on byte-oriented matching against multibyte elements. | ||||
7989 | // FIXME: We can compare the bytes in the correct order. | ||||
7990 | if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) | ||||
7991 | return false; | ||||
7992 | // Figure out what value we're actually looking for (after converting to | ||||
7993 | // the corresponding unsigned type if necessary). | ||||
7994 | uint64_t DesiredVal; | ||||
7995 | bool StopAtNull = false; | ||||
7996 | switch (BuiltinOp) { | ||||
7997 | case Builtin::BIstrchr: | ||||
7998 | case Builtin::BI__builtin_strchr: | ||||
7999 | // strchr compares directly to the passed integer, and therefore | ||||
8000 | // always fails if given an int that is not a char. | ||||
8001 | if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, | ||||
8002 | E->getArg(1)->getType(), | ||||
8003 | Desired), | ||||
8004 | Desired)) | ||||
8005 | return ZeroInitialization(E); | ||||
8006 | StopAtNull = true; | ||||
8007 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
8008 | case Builtin::BImemchr: | ||||
8009 | case Builtin::BI__builtin_memchr: | ||||
8010 | case Builtin::BI__builtin_char_memchr: | ||||
8011 | // memchr compares by converting both sides to unsigned char. That's also | ||||
8012 | // correct for strchr if we get this far (to cope with plain char being | ||||
8013 | // unsigned in the strchr case). | ||||
8014 | DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); | ||||
8015 | break; | ||||
8016 | |||||
8017 | case Builtin::BIwcschr: | ||||
8018 | case Builtin::BI__builtin_wcschr: | ||||
8019 | StopAtNull = true; | ||||
8020 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
8021 | case Builtin::BIwmemchr: | ||||
8022 | case Builtin::BI__builtin_wmemchr: | ||||
8023 | // wcschr and wmemchr are given a wchar_t to look for. Just use it. | ||||
8024 | DesiredVal = Desired.getZExtValue(); | ||||
8025 | break; | ||||
8026 | } | ||||
8027 | |||||
8028 | for (; MaxLength; --MaxLength) { | ||||
8029 | APValue Char; | ||||
8030 | if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || | ||||
8031 | !Char.isInt()) | ||||
8032 | return false; | ||||
8033 | if (Char.getInt().getZExtValue() == DesiredVal) | ||||
8034 | return true; | ||||
8035 | if (StopAtNull && !Char.getInt()) | ||||
8036 | break; | ||||
8037 | if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) | ||||
8038 | return false; | ||||
8039 | } | ||||
8040 | // Not found: return nullptr. | ||||
8041 | return ZeroInitialization(E); | ||||
8042 | } | ||||
8043 | |||||
8044 | case Builtin::BImemcpy: | ||||
8045 | case Builtin::BImemmove: | ||||
8046 | case Builtin::BIwmemcpy: | ||||
8047 | case Builtin::BIwmemmove: | ||||
8048 | if (Info.getLangOpts().CPlusPlus11) | ||||
8049 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
8050 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
8051 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
8052 | else | ||||
8053 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
8054 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
8055 | case Builtin::BI__builtin_memcpy: | ||||
8056 | case Builtin::BI__builtin_memmove: | ||||
8057 | case Builtin::BI__builtin_wmemcpy: | ||||
8058 | case Builtin::BI__builtin_wmemmove: { | ||||
8059 | bool WChar = BuiltinOp == Builtin::BIwmemcpy || | ||||
8060 | BuiltinOp == Builtin::BIwmemmove || | ||||
8061 | BuiltinOp == Builtin::BI__builtin_wmemcpy || | ||||
8062 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||
8063 | bool Move = BuiltinOp == Builtin::BImemmove || | ||||
8064 | BuiltinOp == Builtin::BIwmemmove || | ||||
8065 | BuiltinOp == Builtin::BI__builtin_memmove || | ||||
8066 | BuiltinOp == Builtin::BI__builtin_wmemmove; | ||||
8067 | |||||
8068 | // The result of mem* is the first argument. | ||||
8069 | if (!Visit(E->getArg(0))) | ||||
8070 | return false; | ||||
8071 | LValue Dest = Result; | ||||
8072 | |||||
8073 | LValue Src; | ||||
8074 | if (!EvaluatePointer(E->getArg(1), Src, Info)) | ||||
8075 | return false; | ||||
8076 | |||||
8077 | APSInt N; | ||||
8078 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
8079 | return false; | ||||
8080 | assert(!N.isSigned() && "memcpy and friends take an unsigned size")((!N.isSigned() && "memcpy and friends take an unsigned size" ) ? static_cast<void> (0) : __assert_fail ("!N.isSigned() && \"memcpy and friends take an unsigned size\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8080, __PRETTY_FUNCTION__)); | ||||
8081 | |||||
8082 | // If the size is zero, we treat this as always being a valid no-op. | ||||
8083 | // (Even if one of the src and dest pointers is null.) | ||||
8084 | if (!N) | ||||
8085 | return true; | ||||
8086 | |||||
8087 | // Otherwise, if either of the operands is null, we can't proceed. Don't | ||||
8088 | // try to determine the type of the copied objects, because there aren't | ||||
8089 | // any. | ||||
8090 | if (!Src.Base || !Dest.Base) { | ||||
8091 | APValue Val; | ||||
8092 | (!Src.Base ? Src : Dest).moveInto(Val); | ||||
8093 | Info.FFDiag(E, diag::note_constexpr_memcpy_null) | ||||
8094 | << Move << WChar << !!Src.Base | ||||
8095 | << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); | ||||
8096 | return false; | ||||
8097 | } | ||||
8098 | if (Src.Designator.Invalid || Dest.Designator.Invalid) | ||||
8099 | return false; | ||||
8100 | |||||
8101 | // We require that Src and Dest are both pointers to arrays of | ||||
8102 | // trivially-copyable type. (For the wide version, the designator will be | ||||
8103 | // invalid if the designated object is not a wchar_t.) | ||||
8104 | QualType T = Dest.Designator.getType(Info.Ctx); | ||||
8105 | QualType SrcT = Src.Designator.getType(Info.Ctx); | ||||
8106 | if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { | ||||
8107 | Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; | ||||
8108 | return false; | ||||
8109 | } | ||||
8110 | if (T->isIncompleteType()) { | ||||
8111 | Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; | ||||
8112 | return false; | ||||
8113 | } | ||||
8114 | if (!T.isTriviallyCopyableType(Info.Ctx)) { | ||||
8115 | Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; | ||||
8116 | return false; | ||||
8117 | } | ||||
8118 | |||||
8119 | // Figure out how many T's we're copying. | ||||
8120 | uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); | ||||
8121 | if (!WChar) { | ||||
8122 | uint64_t Remainder; | ||||
8123 | llvm::APInt OrigN = N; | ||||
8124 | llvm::APInt::udivrem(OrigN, TSize, N, Remainder); | ||||
8125 | if (Remainder) { | ||||
8126 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||
8127 | << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) | ||||
8128 | << (unsigned)TSize; | ||||
8129 | return false; | ||||
8130 | } | ||||
8131 | } | ||||
8132 | |||||
8133 | // Check that the copying will remain within the arrays, just so that we | ||||
8134 | // can give a more meaningful diagnostic. This implicitly also checks that | ||||
8135 | // N fits into 64 bits. | ||||
8136 | uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; | ||||
8137 | uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; | ||||
8138 | if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { | ||||
8139 | Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) | ||||
8140 | << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T | ||||
8141 | << N.toString(10, /*Signed*/false); | ||||
8142 | return false; | ||||
8143 | } | ||||
8144 | uint64_t NElems = N.getZExtValue(); | ||||
8145 | uint64_t NBytes = NElems * TSize; | ||||
8146 | |||||
8147 | // Check for overlap. | ||||
8148 | int Direction = 1; | ||||
8149 | if (HasSameBase(Src, Dest)) { | ||||
8150 | uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); | ||||
8151 | uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); | ||||
8152 | if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { | ||||
8153 | // Dest is inside the source region. | ||||
8154 | if (!Move) { | ||||
8155 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||
8156 | return false; | ||||
8157 | } | ||||
8158 | // For memmove and friends, copy backwards. | ||||
8159 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || | ||||
8160 | !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) | ||||
8161 | return false; | ||||
8162 | Direction = -1; | ||||
8163 | } else if (!Move && SrcOffset >= DestOffset && | ||||
8164 | SrcOffset - DestOffset < NBytes) { | ||||
8165 | // Src is inside the destination region for memcpy: invalid. | ||||
8166 | Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; | ||||
8167 | return false; | ||||
8168 | } | ||||
8169 | } | ||||
8170 | |||||
8171 | while (true) { | ||||
8172 | APValue Val; | ||||
8173 | // FIXME: Set WantObjectRepresentation to true if we're copying a | ||||
8174 | // char-like type? | ||||
8175 | if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || | ||||
8176 | !handleAssignment(Info, E, Dest, T, Val)) | ||||
8177 | return false; | ||||
8178 | // Do not iterate past the last element; if we're copying backwards, that | ||||
8179 | // might take us off the start of the array. | ||||
8180 | if (--NElems == 0) | ||||
8181 | return true; | ||||
8182 | if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || | ||||
8183 | !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) | ||||
8184 | return false; | ||||
8185 | } | ||||
8186 | } | ||||
8187 | |||||
8188 | default: | ||||
8189 | return visitNonBuiltinCallExpr(E); | ||||
8190 | } | ||||
8191 | } | ||||
8192 | |||||
8193 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||
8194 | APValue &Result, const InitListExpr *ILE, | ||||
8195 | QualType AllocType); | ||||
8196 | |||||
8197 | bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { | ||||
8198 | if (!Info.getLangOpts().CPlusPlus2a) | ||||
8199 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||
8200 | |||||
8201 | // We cannot speculatively evaluate a delete expression. | ||||
8202 | if (Info.SpeculativeEvaluationDepth) | ||||
8203 | return false; | ||||
8204 | |||||
8205 | FunctionDecl *OperatorNew = E->getOperatorNew(); | ||||
8206 | if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { | ||||
8207 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||
8208 | << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; | ||||
8209 | return false; | ||||
8210 | } | ||||
8211 | |||||
8212 | bool IsNothrow = false; | ||||
8213 | if (E->getNumPlacementArgs()) { | ||||
8214 | // The only new-placement list we support is of the form (std::nothrow). | ||||
8215 | // | ||||
8216 | // FIXME: There is no restriction on this, but it's not clear that any | ||||
8217 | // other form makes any sense. We get here for cases such as: | ||||
8218 | // | ||||
8219 | // new (std::align_val_t{N}) X(int) | ||||
8220 | // | ||||
8221 | // (which should presumably be valid only if N is a multiple of | ||||
8222 | // alignof(int), and in any case can't be deallocated unless N is | ||||
8223 | // alignof(X) and X has new-extended alignment). | ||||
8224 | if (E->getNumPlacementArgs() != 1 || | ||||
8225 | !E->getPlacementArg(0)->getType()->isNothrowT()) | ||||
8226 | return Error(E, diag::note_constexpr_new_placement); | ||||
8227 | |||||
8228 | LValue Nothrow; | ||||
8229 | if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) | ||||
8230 | return false; | ||||
8231 | IsNothrow = true; | ||||
8232 | } | ||||
8233 | |||||
8234 | const Expr *Init = E->getInitializer(); | ||||
8235 | const InitListExpr *ResizedArrayILE = nullptr; | ||||
8236 | |||||
8237 | QualType AllocType = E->getAllocatedType(); | ||||
8238 | if (Optional<const Expr*> ArraySize = E->getArraySize()) { | ||||
8239 | const Expr *Stripped = *ArraySize; | ||||
8240 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); | ||||
8241 | Stripped = ICE->getSubExpr()) | ||||
8242 | if (ICE->getCastKind() != CK_NoOp && | ||||
8243 | ICE->getCastKind() != CK_IntegralCast) | ||||
8244 | break; | ||||
8245 | |||||
8246 | llvm::APSInt ArrayBound; | ||||
8247 | if (!EvaluateInteger(Stripped, ArrayBound, Info)) | ||||
8248 | return false; | ||||
8249 | |||||
8250 | // C++ [expr.new]p9: | ||||
8251 | // The expression is erroneous if: | ||||
8252 | // -- [...] its value before converting to size_t [or] applying the | ||||
8253 | // second standard conversion sequence is less than zero | ||||
8254 | if (ArrayBound.isSigned() && ArrayBound.isNegative()) { | ||||
8255 | if (IsNothrow) | ||||
8256 | return ZeroInitialization(E); | ||||
8257 | |||||
8258 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) | ||||
8259 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||
8260 | return false; | ||||
8261 | } | ||||
8262 | |||||
8263 | // -- its value is such that the size of the allocated object would | ||||
8264 | // exceed the implementation-defined limit | ||||
8265 | if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, | ||||
8266 | ArrayBound) > | ||||
8267 | ConstantArrayType::getMaxSizeBits(Info.Ctx)) { | ||||
8268 | if (IsNothrow) | ||||
8269 | return ZeroInitialization(E); | ||||
8270 | |||||
8271 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) | ||||
8272 | << ArrayBound << (*ArraySize)->getSourceRange(); | ||||
8273 | return false; | ||||
8274 | } | ||||
8275 | |||||
8276 | // -- the new-initializer is a braced-init-list and the number of | ||||
8277 | // array elements for which initializers are provided [...] | ||||
8278 | // exceeds the number of elements to initialize | ||||
8279 | if (Init) { | ||||
8280 | auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); | ||||
8281 | assert(CAT && "unexpected type for array initializer")((CAT && "unexpected type for array initializer") ? static_cast <void> (0) : __assert_fail ("CAT && \"unexpected type for array initializer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8281, __PRETTY_FUNCTION__)); | ||||
8282 | |||||
8283 | unsigned Bits = | ||||
8284 | std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); | ||||
8285 | llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); | ||||
8286 | llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); | ||||
8287 | if (InitBound.ugt(AllocBound)) { | ||||
8288 | if (IsNothrow) | ||||
8289 | return ZeroInitialization(E); | ||||
8290 | |||||
8291 | Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) | ||||
8292 | << AllocBound.toString(10, /*Signed=*/false) | ||||
8293 | << InitBound.toString(10, /*Signed=*/false) | ||||
8294 | << (*ArraySize)->getSourceRange(); | ||||
8295 | return false; | ||||
8296 | } | ||||
8297 | |||||
8298 | // If the sizes differ, we must have an initializer list, and we need | ||||
8299 | // special handling for this case when we initialize. | ||||
8300 | if (InitBound != AllocBound) | ||||
8301 | ResizedArrayILE = cast<InitListExpr>(Init); | ||||
8302 | } | ||||
8303 | |||||
8304 | AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, | ||||
8305 | ArrayType::Normal, 0); | ||||
8306 | } else { | ||||
8307 | assert(!AllocType->isArrayType() &&((!AllocType->isArrayType() && "array allocation with non-array new" ) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8308, __PRETTY_FUNCTION__)) | ||||
8308 | "array allocation with non-array new")((!AllocType->isArrayType() && "array allocation with non-array new" ) ? static_cast<void> (0) : __assert_fail ("!AllocType->isArrayType() && \"array allocation with non-array new\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8308, __PRETTY_FUNCTION__)); | ||||
8309 | } | ||||
8310 | |||||
8311 | // Perform the allocation and obtain a pointer to the resulting object. | ||||
8312 | APValue *Val = Info.createHeapAlloc(E, AllocType, Result); | ||||
8313 | if (!Val) | ||||
8314 | return false; | ||||
8315 | |||||
8316 | if (ResizedArrayILE) { | ||||
8317 | if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, | ||||
8318 | AllocType)) | ||||
8319 | return false; | ||||
8320 | } else if (Init) { | ||||
8321 | if (!EvaluateInPlace(*Val, Info, Result, Init)) | ||||
8322 | return false; | ||||
8323 | } else { | ||||
8324 | *Val = getDefaultInitValue(AllocType); | ||||
8325 | } | ||||
8326 | |||||
8327 | // Array new returns a pointer to the first element, not a pointer to the | ||||
8328 | // array. | ||||
8329 | if (auto *AT = AllocType->getAsArrayTypeUnsafe()) | ||||
8330 | Result.addArray(Info, E, cast<ConstantArrayType>(AT)); | ||||
8331 | |||||
8332 | return true; | ||||
8333 | } | ||||
8334 | //===----------------------------------------------------------------------===// | ||||
8335 | // Member Pointer Evaluation | ||||
8336 | //===----------------------------------------------------------------------===// | ||||
8337 | |||||
8338 | namespace { | ||||
8339 | class MemberPointerExprEvaluator | ||||
8340 | : public ExprEvaluatorBase<MemberPointerExprEvaluator> { | ||||
8341 | MemberPtr &Result; | ||||
8342 | |||||
8343 | bool Success(const ValueDecl *D) { | ||||
8344 | Result = MemberPtr(D); | ||||
8345 | return true; | ||||
8346 | } | ||||
8347 | public: | ||||
8348 | |||||
8349 | MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) | ||||
8350 | : ExprEvaluatorBaseTy(Info), Result(Result) {} | ||||
8351 | |||||
8352 | bool Success(const APValue &V, const Expr *E) { | ||||
8353 | Result.setFrom(V); | ||||
8354 | return true; | ||||
8355 | } | ||||
8356 | bool ZeroInitialization(const Expr *E) { | ||||
8357 | return Success((const ValueDecl*)nullptr); | ||||
8358 | } | ||||
8359 | |||||
8360 | bool VisitCastExpr(const CastExpr *E); | ||||
8361 | bool VisitUnaryAddrOf(const UnaryOperator *E); | ||||
8362 | }; | ||||
8363 | } // end anonymous namespace | ||||
8364 | |||||
8365 | static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, | ||||
8366 | EvalInfo &Info) { | ||||
8367 | assert(E->isRValue() && E->getType()->isMemberPointerType())((E->isRValue() && E->getType()->isMemberPointerType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isMemberPointerType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8367, __PRETTY_FUNCTION__)); | ||||
8368 | return MemberPointerExprEvaluator(Info, Result).Visit(E); | ||||
8369 | } | ||||
8370 | |||||
8371 | bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
8372 | switch (E->getCastKind()) { | ||||
8373 | default: | ||||
8374 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8375 | |||||
8376 | case CK_NullToMemberPointer: | ||||
8377 | VisitIgnoredValue(E->getSubExpr()); | ||||
8378 | return ZeroInitialization(E); | ||||
8379 | |||||
8380 | case CK_BaseToDerivedMemberPointer: { | ||||
8381 | if (!Visit(E->getSubExpr())) | ||||
8382 | return false; | ||||
8383 | if (E->path_empty()) | ||||
8384 | return true; | ||||
8385 | // Base-to-derived member pointer casts store the path in derived-to-base | ||||
8386 | // order, so iterate backwards. The CXXBaseSpecifier also provides us with | ||||
8387 | // the wrong end of the derived->base arc, so stagger the path by one class. | ||||
8388 | typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; | ||||
8389 | for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); | ||||
8390 | PathI != PathE; ++PathI) { | ||||
8391 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8391, __PRETTY_FUNCTION__)); | ||||
8392 | const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
8393 | if (!Result.castToDerived(Derived)) | ||||
8394 | return Error(E); | ||||
8395 | } | ||||
8396 | const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); | ||||
8397 | if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) | ||||
8398 | return Error(E); | ||||
8399 | return true; | ||||
8400 | } | ||||
8401 | |||||
8402 | case CK_DerivedToBaseMemberPointer: | ||||
8403 | if (!Visit(E->getSubExpr())) | ||||
8404 | return false; | ||||
8405 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
8406 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||
8407 | assert(!(*PathI)->isVirtual() && "memptr cast through vbase")((!(*PathI)->isVirtual() && "memptr cast through vbase" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"memptr cast through vbase\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8407, __PRETTY_FUNCTION__)); | ||||
8408 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
8409 | if (!Result.castToBase(Base)) | ||||
8410 | return Error(E); | ||||
8411 | } | ||||
8412 | return true; | ||||
8413 | } | ||||
8414 | } | ||||
8415 | |||||
8416 | bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { | ||||
8417 | // C++11 [expr.unary.op]p3 has very strict rules on how the address of a | ||||
8418 | // member can be formed. | ||||
8419 | return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); | ||||
8420 | } | ||||
8421 | |||||
8422 | //===----------------------------------------------------------------------===// | ||||
8423 | // Record Evaluation | ||||
8424 | //===----------------------------------------------------------------------===// | ||||
8425 | |||||
8426 | namespace { | ||||
8427 | class RecordExprEvaluator | ||||
8428 | : public ExprEvaluatorBase<RecordExprEvaluator> { | ||||
8429 | const LValue &This; | ||||
8430 | APValue &Result; | ||||
8431 | public: | ||||
8432 | |||||
8433 | RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) | ||||
8434 | : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} | ||||
8435 | |||||
8436 | bool Success(const APValue &V, const Expr *E) { | ||||
8437 | Result = V; | ||||
8438 | return true; | ||||
8439 | } | ||||
8440 | bool ZeroInitialization(const Expr *E) { | ||||
8441 | return ZeroInitialization(E, E->getType()); | ||||
8442 | } | ||||
8443 | bool ZeroInitialization(const Expr *E, QualType T); | ||||
8444 | |||||
8445 | bool VisitCallExpr(const CallExpr *E) { | ||||
8446 | return handleCallExpr(E, Result, &This); | ||||
8447 | } | ||||
8448 | bool VisitCastExpr(const CastExpr *E); | ||||
8449 | bool VisitInitListExpr(const InitListExpr *E); | ||||
8450 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
8451 | return VisitCXXConstructExpr(E, E->getType()); | ||||
8452 | } | ||||
8453 | bool VisitLambdaExpr(const LambdaExpr *E); | ||||
8454 | bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); | ||||
8455 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); | ||||
8456 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); | ||||
8457 | bool VisitBinCmp(const BinaryOperator *E); | ||||
8458 | }; | ||||
8459 | } | ||||
8460 | |||||
8461 | /// Perform zero-initialization on an object of non-union class type. | ||||
8462 | /// C++11 [dcl.init]p5: | ||||
8463 | /// To zero-initialize an object or reference of type T means: | ||||
8464 | /// [...] | ||||
8465 | /// -- if T is a (possibly cv-qualified) non-union class type, | ||||
8466 | /// each non-static data member and each base-class subobject is | ||||
8467 | /// zero-initialized | ||||
8468 | static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, | ||||
8469 | const RecordDecl *RD, | ||||
8470 | const LValue &This, APValue &Result) { | ||||
8471 | assert(!RD->isUnion() && "Expected non-union class type")((!RD->isUnion() && "Expected non-union class type" ) ? static_cast<void> (0) : __assert_fail ("!RD->isUnion() && \"Expected non-union class type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8471, __PRETTY_FUNCTION__)); | ||||
8472 | const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); | ||||
8473 | Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, | ||||
8474 | std::distance(RD->field_begin(), RD->field_end())); | ||||
8475 | |||||
8476 | if (RD->isInvalidDecl()) return false; | ||||
8477 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
8478 | |||||
8479 | if (CD) { | ||||
8480 | unsigned Index = 0; | ||||
8481 | for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), | ||||
8482 | End = CD->bases_end(); I != End; ++I, ++Index) { | ||||
8483 | const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); | ||||
8484 | LValue Subobject = This; | ||||
8485 | if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) | ||||
8486 | return false; | ||||
8487 | if (!HandleClassZeroInitialization(Info, E, Base, Subobject, | ||||
8488 | Result.getStructBase(Index))) | ||||
8489 | return false; | ||||
8490 | } | ||||
8491 | } | ||||
8492 | |||||
8493 | for (const auto *I : RD->fields()) { | ||||
8494 | // -- if T is a reference type, no initialization is performed. | ||||
8495 | if (I->getType()->isReferenceType()) | ||||
8496 | continue; | ||||
8497 | |||||
8498 | LValue Subobject = This; | ||||
8499 | if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) | ||||
8500 | return false; | ||||
8501 | |||||
8502 | ImplicitValueInitExpr VIE(I->getType()); | ||||
8503 | if (!EvaluateInPlace( | ||||
8504 | Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) | ||||
8505 | return false; | ||||
8506 | } | ||||
8507 | |||||
8508 | return true; | ||||
8509 | } | ||||
8510 | |||||
8511 | bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { | ||||
8512 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); | ||||
8513 | if (RD->isInvalidDecl()) return false; | ||||
8514 | if (RD->isUnion()) { | ||||
8515 | // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the | ||||
8516 | // object's first non-static named data member is zero-initialized | ||||
8517 | RecordDecl::field_iterator I = RD->field_begin(); | ||||
8518 | if (I == RD->field_end()) { | ||||
8519 | Result = APValue((const FieldDecl*)nullptr); | ||||
8520 | return true; | ||||
8521 | } | ||||
8522 | |||||
8523 | LValue Subobject = This; | ||||
8524 | if (!HandleLValueMember(Info, E, Subobject, *I)) | ||||
8525 | return false; | ||||
8526 | Result = APValue(*I); | ||||
8527 | ImplicitValueInitExpr VIE(I->getType()); | ||||
8528 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); | ||||
8529 | } | ||||
8530 | |||||
8531 | if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { | ||||
8532 | Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; | ||||
8533 | return false; | ||||
8534 | } | ||||
8535 | |||||
8536 | return HandleClassZeroInitialization(Info, E, RD, This, Result); | ||||
8537 | } | ||||
8538 | |||||
8539 | bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
8540 | switch (E->getCastKind()) { | ||||
8541 | default: | ||||
8542 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8543 | |||||
8544 | case CK_ConstructorConversion: | ||||
8545 | return Visit(E->getSubExpr()); | ||||
8546 | |||||
8547 | case CK_DerivedToBase: | ||||
8548 | case CK_UncheckedDerivedToBase: { | ||||
8549 | APValue DerivedObject; | ||||
8550 | if (!Evaluate(DerivedObject, Info, E->getSubExpr())) | ||||
8551 | return false; | ||||
8552 | if (!DerivedObject.isStruct()) | ||||
8553 | return Error(E->getSubExpr()); | ||||
8554 | |||||
8555 | // Derived-to-base rvalue conversion: just slice off the derived part. | ||||
8556 | APValue *Value = &DerivedObject; | ||||
8557 | const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); | ||||
8558 | for (CastExpr::path_const_iterator PathI = E->path_begin(), | ||||
8559 | PathE = E->path_end(); PathI != PathE; ++PathI) { | ||||
8560 | assert(!(*PathI)->isVirtual() && "record rvalue with virtual base")((!(*PathI)->isVirtual() && "record rvalue with virtual base" ) ? static_cast<void> (0) : __assert_fail ("!(*PathI)->isVirtual() && \"record rvalue with virtual base\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8560, __PRETTY_FUNCTION__)); | ||||
8561 | const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); | ||||
8562 | Value = &Value->getStructBase(getBaseIndex(RD, Base)); | ||||
8563 | RD = Base; | ||||
8564 | } | ||||
8565 | Result = *Value; | ||||
8566 | return true; | ||||
8567 | } | ||||
8568 | } | ||||
8569 | } | ||||
8570 | |||||
8571 | bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
8572 | if (E->isTransparent()) | ||||
8573 | return Visit(E->getInit(0)); | ||||
8574 | |||||
8575 | const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); | ||||
8576 | if (RD->isInvalidDecl()) return false; | ||||
8577 | const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); | ||||
8578 | auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); | ||||
8579 | |||||
8580 | EvalInfo::EvaluatingConstructorRAII EvalObj( | ||||
8581 | Info, | ||||
8582 | ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, | ||||
8583 | CXXRD && CXXRD->getNumBases()); | ||||
8584 | |||||
8585 | if (RD->isUnion()) { | ||||
8586 | const FieldDecl *Field = E->getInitializedFieldInUnion(); | ||||
8587 | Result = APValue(Field); | ||||
8588 | if (!Field) | ||||
8589 | return true; | ||||
8590 | |||||
8591 | // If the initializer list for a union does not contain any elements, the | ||||
8592 | // first element of the union is value-initialized. | ||||
8593 | // FIXME: The element should be initialized from an initializer list. | ||||
8594 | // Is this difference ever observable for initializer lists which | ||||
8595 | // we don't build? | ||||
8596 | ImplicitValueInitExpr VIE(Field->getType()); | ||||
8597 | const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; | ||||
8598 | |||||
8599 | LValue Subobject = This; | ||||
8600 | if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) | ||||
8601 | return false; | ||||
8602 | |||||
8603 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||
8604 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||
8605 | isa<CXXDefaultInitExpr>(InitExpr)); | ||||
8606 | |||||
8607 | return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); | ||||
8608 | } | ||||
8609 | |||||
8610 | if (!Result.hasValue()) | ||||
8611 | Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, | ||||
8612 | std::distance(RD->field_begin(), RD->field_end())); | ||||
8613 | unsigned ElementNo = 0; | ||||
8614 | bool Success = true; | ||||
8615 | |||||
8616 | // Initialize base classes. | ||||
8617 | if (CXXRD && CXXRD->getNumBases()) { | ||||
8618 | for (const auto &Base : CXXRD->bases()) { | ||||
8619 | assert(ElementNo < E->getNumInits() && "missing init for base class")((ElementNo < E->getNumInits() && "missing init for base class" ) ? static_cast<void> (0) : __assert_fail ("ElementNo < E->getNumInits() && \"missing init for base class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8619, __PRETTY_FUNCTION__)); | ||||
8620 | const Expr *Init = E->getInit(ElementNo); | ||||
8621 | |||||
8622 | LValue Subobject = This; | ||||
8623 | if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) | ||||
8624 | return false; | ||||
8625 | |||||
8626 | APValue &FieldVal = Result.getStructBase(ElementNo); | ||||
8627 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { | ||||
8628 | if (!Info.noteFailure()) | ||||
8629 | return false; | ||||
8630 | Success = false; | ||||
8631 | } | ||||
8632 | ++ElementNo; | ||||
8633 | } | ||||
8634 | |||||
8635 | EvalObj.finishedConstructingBases(); | ||||
8636 | } | ||||
8637 | |||||
8638 | // Initialize members. | ||||
8639 | for (const auto *Field : RD->fields()) { | ||||
8640 | // Anonymous bit-fields are not considered members of the class for | ||||
8641 | // purposes of aggregate initialization. | ||||
8642 | if (Field->isUnnamedBitfield()) | ||||
8643 | continue; | ||||
8644 | |||||
8645 | LValue Subobject = This; | ||||
8646 | |||||
8647 | bool HaveInit = ElementNo < E->getNumInits(); | ||||
8648 | |||||
8649 | // FIXME: Diagnostics here should point to the end of the initializer | ||||
8650 | // list, not the start. | ||||
8651 | if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, | ||||
8652 | Subobject, Field, &Layout)) | ||||
8653 | return false; | ||||
8654 | |||||
8655 | // Perform an implicit value-initialization for members beyond the end of | ||||
8656 | // the initializer list. | ||||
8657 | ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); | ||||
8658 | const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; | ||||
8659 | |||||
8660 | // Temporarily override This, in case there's a CXXDefaultInitExpr in here. | ||||
8661 | ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, | ||||
8662 | isa<CXXDefaultInitExpr>(Init)); | ||||
8663 | |||||
8664 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||
8665 | if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || | ||||
8666 | (Field->isBitField() && !truncateBitfieldValue(Info, Init, | ||||
8667 | FieldVal, Field))) { | ||||
8668 | if (!Info.noteFailure()) | ||||
8669 | return false; | ||||
8670 | Success = false; | ||||
8671 | } | ||||
8672 | } | ||||
8673 | |||||
8674 | return Success; | ||||
8675 | } | ||||
8676 | |||||
8677 | bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
8678 | QualType T) { | ||||
8679 | // Note that E's type is not necessarily the type of our class here; we might | ||||
8680 | // be initializing an array element instead. | ||||
8681 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||
8682 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; | ||||
8683 | |||||
8684 | bool ZeroInit = E->requiresZeroInitialization(); | ||||
8685 | if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { | ||||
8686 | // If we've already performed zero-initialization, we're already done. | ||||
8687 | if (Result.hasValue()) | ||||
8688 | return true; | ||||
8689 | |||||
8690 | if (ZeroInit) | ||||
8691 | return ZeroInitialization(E, T); | ||||
8692 | |||||
8693 | Result = getDefaultInitValue(T); | ||||
8694 | return true; | ||||
8695 | } | ||||
8696 | |||||
8697 | const FunctionDecl *Definition = nullptr; | ||||
8698 | auto Body = FD->getBody(Definition); | ||||
8699 | |||||
8700 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||
8701 | return false; | ||||
8702 | |||||
8703 | // Avoid materializing a temporary for an elidable copy/move constructor. | ||||
8704 | if (E->isElidable() && !ZeroInit) | ||||
8705 | if (const MaterializeTemporaryExpr *ME | ||||
8706 | = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) | ||||
8707 | return Visit(ME->GetTemporaryExpr()); | ||||
8708 | |||||
8709 | if (ZeroInit && !ZeroInitialization(E, T)) | ||||
8710 | return false; | ||||
8711 | |||||
8712 | auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); | ||||
8713 | return HandleConstructorCall(E, This, Args, | ||||
8714 | cast<CXXConstructorDecl>(Definition), Info, | ||||
8715 | Result); | ||||
8716 | } | ||||
8717 | |||||
8718 | bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( | ||||
8719 | const CXXInheritedCtorInitExpr *E) { | ||||
8720 | if (!Info.CurrentCall) { | ||||
8721 | assert(Info.checkingPotentialConstantExpression())((Info.checkingPotentialConstantExpression()) ? static_cast< void> (0) : __assert_fail ("Info.checkingPotentialConstantExpression()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8721, __PRETTY_FUNCTION__)); | ||||
8722 | return false; | ||||
8723 | } | ||||
8724 | |||||
8725 | const CXXConstructorDecl *FD = E->getConstructor(); | ||||
8726 | if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) | ||||
8727 | return false; | ||||
8728 | |||||
8729 | const FunctionDecl *Definition = nullptr; | ||||
8730 | auto Body = FD->getBody(Definition); | ||||
8731 | |||||
8732 | if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) | ||||
8733 | return false; | ||||
8734 | |||||
8735 | return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, | ||||
8736 | cast<CXXConstructorDecl>(Definition), Info, | ||||
8737 | Result); | ||||
8738 | } | ||||
8739 | |||||
8740 | bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( | ||||
8741 | const CXXStdInitializerListExpr *E) { | ||||
8742 | const ConstantArrayType *ArrayType = | ||||
8743 | Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); | ||||
8744 | |||||
8745 | LValue Array; | ||||
8746 | if (!EvaluateLValue(E->getSubExpr(), Array, Info)) | ||||
8747 | return false; | ||||
8748 | |||||
8749 | // Get a pointer to the first element of the array. | ||||
8750 | Array.addArray(Info, E, ArrayType); | ||||
8751 | |||||
8752 | // FIXME: Perform the checks on the field types in SemaInit. | ||||
8753 | RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); | ||||
8754 | RecordDecl::field_iterator Field = Record->field_begin(); | ||||
8755 | if (Field == Record->field_end()) | ||||
8756 | return Error(E); | ||||
8757 | |||||
8758 | // Start pointer. | ||||
8759 | if (!Field->getType()->isPointerType() || | ||||
8760 | !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||
8761 | ArrayType->getElementType())) | ||||
8762 | return Error(E); | ||||
8763 | |||||
8764 | // FIXME: What if the initializer_list type has base classes, etc? | ||||
8765 | Result = APValue(APValue::UninitStruct(), 0, 2); | ||||
8766 | Array.moveInto(Result.getStructField(0)); | ||||
8767 | |||||
8768 | if (++Field == Record->field_end()) | ||||
8769 | return Error(E); | ||||
8770 | |||||
8771 | if (Field->getType()->isPointerType() && | ||||
8772 | Info.Ctx.hasSameType(Field->getType()->getPointeeType(), | ||||
8773 | ArrayType->getElementType())) { | ||||
8774 | // End pointer. | ||||
8775 | if (!HandleLValueArrayAdjustment(Info, E, Array, | ||||
8776 | ArrayType->getElementType(), | ||||
8777 | ArrayType->getSize().getZExtValue())) | ||||
8778 | return false; | ||||
8779 | Array.moveInto(Result.getStructField(1)); | ||||
8780 | } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) | ||||
8781 | // Length. | ||||
8782 | Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); | ||||
8783 | else | ||||
8784 | return Error(E); | ||||
8785 | |||||
8786 | if (++Field != Record->field_end()) | ||||
8787 | return Error(E); | ||||
8788 | |||||
8789 | return true; | ||||
8790 | } | ||||
8791 | |||||
8792 | bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { | ||||
8793 | const CXXRecordDecl *ClosureClass = E->getLambdaClass(); | ||||
8794 | if (ClosureClass->isInvalidDecl()) | ||||
8795 | return false; | ||||
8796 | |||||
8797 | const size_t NumFields = | ||||
8798 | std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); | ||||
8799 | |||||
8800 | assert(NumFields == (size_t)std::distance(E->capture_init_begin(),((NumFields == (size_t)std::distance(E->capture_init_begin (), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? static_cast<void> ( 0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||
8801 | E->capture_init_end()) &&((NumFields == (size_t)std::distance(E->capture_init_begin (), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? static_cast<void> ( 0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||
8802 | "The number of lambda capture initializers should equal the number of "((NumFields == (size_t)std::distance(E->capture_init_begin (), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? static_cast<void> ( 0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)) | ||||
8803 | "fields within the closure type")((NumFields == (size_t)std::distance(E->capture_init_begin (), E->capture_init_end()) && "The number of lambda capture initializers should equal the number of " "fields within the closure type") ? static_cast<void> ( 0) : __assert_fail ("NumFields == (size_t)std::distance(E->capture_init_begin(), E->capture_init_end()) && \"The number of lambda capture initializers should equal the number of \" \"fields within the closure type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8803, __PRETTY_FUNCTION__)); | ||||
8804 | |||||
8805 | Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); | ||||
8806 | // Iterate through all the lambda's closure object's fields and initialize | ||||
8807 | // them. | ||||
8808 | auto *CaptureInitIt = E->capture_init_begin(); | ||||
8809 | const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); | ||||
8810 | bool Success = true; | ||||
8811 | for (const auto *Field : ClosureClass->fields()) { | ||||
8812 | assert(CaptureInitIt != E->capture_init_end())((CaptureInitIt != E->capture_init_end()) ? static_cast< void> (0) : __assert_fail ("CaptureInitIt != E->capture_init_end()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8812, __PRETTY_FUNCTION__)); | ||||
8813 | // Get the initializer for this field | ||||
8814 | Expr *const CurFieldInit = *CaptureInitIt++; | ||||
8815 | |||||
8816 | // If there is no initializer, either this is a VLA or an error has | ||||
8817 | // occurred. | ||||
8818 | if (!CurFieldInit) | ||||
8819 | return Error(E); | ||||
8820 | |||||
8821 | APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); | ||||
8822 | if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { | ||||
8823 | if (!Info.keepEvaluatingAfterFailure()) | ||||
8824 | return false; | ||||
8825 | Success = false; | ||||
8826 | } | ||||
8827 | ++CaptureIt; | ||||
8828 | } | ||||
8829 | return Success; | ||||
8830 | } | ||||
8831 | |||||
8832 | static bool EvaluateRecord(const Expr *E, const LValue &This, | ||||
8833 | APValue &Result, EvalInfo &Info) { | ||||
8834 | assert(E->isRValue() && E->getType()->isRecordType() &&((E->isRValue() && E->getType()->isRecordType () && "can't evaluate expression as a record rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8835, __PRETTY_FUNCTION__)) | ||||
8835 | "can't evaluate expression as a record rvalue")((E->isRValue() && E->getType()->isRecordType () && "can't evaluate expression as a record rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType() && \"can't evaluate expression as a record rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8835, __PRETTY_FUNCTION__)); | ||||
8836 | return RecordExprEvaluator(Info, This, Result).Visit(E); | ||||
8837 | } | ||||
8838 | |||||
8839 | //===----------------------------------------------------------------------===// | ||||
8840 | // Temporary Evaluation | ||||
8841 | // | ||||
8842 | // Temporaries are represented in the AST as rvalues, but generally behave like | ||||
8843 | // lvalues. The full-object of which the temporary is a subobject is implicitly | ||||
8844 | // materialized so that a reference can bind to it. | ||||
8845 | //===----------------------------------------------------------------------===// | ||||
8846 | namespace { | ||||
8847 | class TemporaryExprEvaluator | ||||
8848 | : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { | ||||
8849 | public: | ||||
8850 | TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : | ||||
8851 | LValueExprEvaluatorBaseTy(Info, Result, false) {} | ||||
8852 | |||||
8853 | /// Visit an expression which constructs the value of this temporary. | ||||
8854 | bool VisitConstructExpr(const Expr *E) { | ||||
8855 | APValue &Value = | ||||
8856 | Info.CurrentCall->createTemporary(E, E->getType(), false, Result); | ||||
8857 | return EvaluateInPlace(Value, Info, Result, E); | ||||
8858 | } | ||||
8859 | |||||
8860 | bool VisitCastExpr(const CastExpr *E) { | ||||
8861 | switch (E->getCastKind()) { | ||||
8862 | default: | ||||
8863 | return LValueExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
8864 | |||||
8865 | case CK_ConstructorConversion: | ||||
8866 | return VisitConstructExpr(E->getSubExpr()); | ||||
8867 | } | ||||
8868 | } | ||||
8869 | bool VisitInitListExpr(const InitListExpr *E) { | ||||
8870 | return VisitConstructExpr(E); | ||||
8871 | } | ||||
8872 | bool VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
8873 | return VisitConstructExpr(E); | ||||
8874 | } | ||||
8875 | bool VisitCallExpr(const CallExpr *E) { | ||||
8876 | return VisitConstructExpr(E); | ||||
8877 | } | ||||
8878 | bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { | ||||
8879 | return VisitConstructExpr(E); | ||||
8880 | } | ||||
8881 | bool VisitLambdaExpr(const LambdaExpr *E) { | ||||
8882 | return VisitConstructExpr(E); | ||||
8883 | } | ||||
8884 | }; | ||||
8885 | } // end anonymous namespace | ||||
8886 | |||||
8887 | /// Evaluate an expression of record type as a temporary. | ||||
8888 | static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { | ||||
8889 | assert(E->isRValue() && E->getType()->isRecordType())((E->isRValue() && E->getType()->isRecordType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRecordType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8889, __PRETTY_FUNCTION__)); | ||||
8890 | return TemporaryExprEvaluator(Info, Result).Visit(E); | ||||
8891 | } | ||||
8892 | |||||
8893 | //===----------------------------------------------------------------------===// | ||||
8894 | // Vector Evaluation | ||||
8895 | //===----------------------------------------------------------------------===// | ||||
8896 | |||||
8897 | namespace { | ||||
8898 | class VectorExprEvaluator | ||||
8899 | : public ExprEvaluatorBase<VectorExprEvaluator> { | ||||
8900 | APValue &Result; | ||||
8901 | public: | ||||
8902 | |||||
8903 | VectorExprEvaluator(EvalInfo &info, APValue &Result) | ||||
8904 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||
8905 | |||||
8906 | bool Success(ArrayRef<APValue> V, const Expr *E) { | ||||
8907 | assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements())((V.size() == E->getType()->castAs<VectorType>()-> getNumElements()) ? static_cast<void> (0) : __assert_fail ("V.size() == E->getType()->castAs<VectorType>()->getNumElements()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8907, __PRETTY_FUNCTION__)); | ||||
8908 | // FIXME: remove this APValue copy. | ||||
8909 | Result = APValue(V.data(), V.size()); | ||||
8910 | return true; | ||||
8911 | } | ||||
8912 | bool Success(const APValue &V, const Expr *E) { | ||||
8913 | assert(V.isVector())((V.isVector()) ? static_cast<void> (0) : __assert_fail ("V.isVector()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8913, __PRETTY_FUNCTION__)); | ||||
8914 | Result = V; | ||||
8915 | return true; | ||||
8916 | } | ||||
8917 | bool ZeroInitialization(const Expr *E); | ||||
8918 | |||||
8919 | bool VisitUnaryReal(const UnaryOperator *E) | ||||
8920 | { return Visit(E->getSubExpr()); } | ||||
8921 | bool VisitCastExpr(const CastExpr* E); | ||||
8922 | bool VisitInitListExpr(const InitListExpr *E); | ||||
8923 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
8924 | // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, | ||||
8925 | // binary comparisons, binary and/or/xor, | ||||
8926 | // shufflevector, ExtVectorElementExpr | ||||
8927 | }; | ||||
8928 | } // end anonymous namespace | ||||
8929 | |||||
8930 | static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { | ||||
8931 | assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue")((E->isRValue() && E->getType()->isVectorType () &&"not a vector rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isVectorType() &&\"not a vector rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 8931, __PRETTY_FUNCTION__)); | ||||
8932 | return VectorExprEvaluator(Info, Result).Visit(E); | ||||
8933 | } | ||||
8934 | |||||
8935 | bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
8936 | const VectorType *VTy = E->getType()->castAs<VectorType>(); | ||||
8937 | unsigned NElts = VTy->getNumElements(); | ||||
8938 | |||||
8939 | const Expr *SE = E->getSubExpr(); | ||||
8940 | QualType SETy = SE->getType(); | ||||
8941 | |||||
8942 | switch (E->getCastKind()) { | ||||
8943 | case CK_VectorSplat: { | ||||
8944 | APValue Val = APValue(); | ||||
8945 | if (SETy->isIntegerType()) { | ||||
8946 | APSInt IntResult; | ||||
8947 | if (!EvaluateInteger(SE, IntResult, Info)) | ||||
8948 | return false; | ||||
8949 | Val = APValue(std::move(IntResult)); | ||||
8950 | } else if (SETy->isRealFloatingType()) { | ||||
8951 | APFloat FloatResult(0.0); | ||||
8952 | if (!EvaluateFloat(SE, FloatResult, Info)) | ||||
8953 | return false; | ||||
8954 | Val = APValue(std::move(FloatResult)); | ||||
8955 | } else { | ||||
8956 | return Error(E); | ||||
8957 | } | ||||
8958 | |||||
8959 | // Splat and create vector APValue. | ||||
8960 | SmallVector<APValue, 4> Elts(NElts, Val); | ||||
8961 | return Success(Elts, E); | ||||
8962 | } | ||||
8963 | case CK_BitCast: { | ||||
8964 | // Evaluate the operand into an APInt we can extract from. | ||||
8965 | llvm::APInt SValInt; | ||||
8966 | if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) | ||||
8967 | return false; | ||||
8968 | // Extract the elements | ||||
8969 | QualType EltTy = VTy->getElementType(); | ||||
8970 | unsigned EltSize = Info.Ctx.getTypeSize(EltTy); | ||||
8971 | bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); | ||||
8972 | SmallVector<APValue, 4> Elts; | ||||
8973 | if (EltTy->isRealFloatingType()) { | ||||
8974 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); | ||||
8975 | unsigned FloatEltSize = EltSize; | ||||
8976 | if (&Sem == &APFloat::x87DoubleExtended()) | ||||
8977 | FloatEltSize = 80; | ||||
8978 | for (unsigned i = 0; i < NElts; i++) { | ||||
8979 | llvm::APInt Elt; | ||||
8980 | if (BigEndian) | ||||
8981 | Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); | ||||
8982 | else | ||||
8983 | Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); | ||||
8984 | Elts.push_back(APValue(APFloat(Sem, Elt))); | ||||
8985 | } | ||||
8986 | } else if (EltTy->isIntegerType()) { | ||||
8987 | for (unsigned i = 0; i < NElts; i++) { | ||||
8988 | llvm::APInt Elt; | ||||
8989 | if (BigEndian) | ||||
8990 | Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); | ||||
8991 | else | ||||
8992 | Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); | ||||
8993 | Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); | ||||
8994 | } | ||||
8995 | } else { | ||||
8996 | return Error(E); | ||||
8997 | } | ||||
8998 | return Success(Elts, E); | ||||
8999 | } | ||||
9000 | default: | ||||
9001 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
9002 | } | ||||
9003 | } | ||||
9004 | |||||
9005 | bool | ||||
9006 | VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
9007 | const VectorType *VT = E->getType()->castAs<VectorType>(); | ||||
9008 | unsigned NumInits = E->getNumInits(); | ||||
9009 | unsigned NumElements = VT->getNumElements(); | ||||
9010 | |||||
9011 | QualType EltTy = VT->getElementType(); | ||||
9012 | SmallVector<APValue, 4> Elements; | ||||
9013 | |||||
9014 | // The number of initializers can be less than the number of | ||||
9015 | // vector elements. For OpenCL, this can be due to nested vector | ||||
9016 | // initialization. For GCC compatibility, missing trailing elements | ||||
9017 | // should be initialized with zeroes. | ||||
9018 | unsigned CountInits = 0, CountElts = 0; | ||||
9019 | while (CountElts < NumElements) { | ||||
9020 | // Handle nested vector initialization. | ||||
9021 | if (CountInits < NumInits | ||||
9022 | && E->getInit(CountInits)->getType()->isVectorType()) { | ||||
9023 | APValue v; | ||||
9024 | if (!EvaluateVector(E->getInit(CountInits), v, Info)) | ||||
9025 | return Error(E); | ||||
9026 | unsigned vlen = v.getVectorLength(); | ||||
9027 | for (unsigned j = 0; j < vlen; j++) | ||||
9028 | Elements.push_back(v.getVectorElt(j)); | ||||
9029 | CountElts += vlen; | ||||
9030 | } else if (EltTy->isIntegerType()) { | ||||
9031 | llvm::APSInt sInt(32); | ||||
9032 | if (CountInits < NumInits) { | ||||
9033 | if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) | ||||
9034 | return false; | ||||
9035 | } else // trailing integer zero. | ||||
9036 | sInt = Info.Ctx.MakeIntValue(0, EltTy); | ||||
9037 | Elements.push_back(APValue(sInt)); | ||||
9038 | CountElts++; | ||||
9039 | } else { | ||||
9040 | llvm::APFloat f(0.0); | ||||
9041 | if (CountInits < NumInits) { | ||||
9042 | if (!EvaluateFloat(E->getInit(CountInits), f, Info)) | ||||
9043 | return false; | ||||
9044 | } else // trailing float zero. | ||||
9045 | f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); | ||||
9046 | Elements.push_back(APValue(f)); | ||||
9047 | CountElts++; | ||||
9048 | } | ||||
9049 | CountInits++; | ||||
9050 | } | ||||
9051 | return Success(Elements, E); | ||||
9052 | } | ||||
9053 | |||||
9054 | bool | ||||
9055 | VectorExprEvaluator::ZeroInitialization(const Expr *E) { | ||||
9056 | const VectorType *VT = E->getType()->getAs<VectorType>(); | ||||
9057 | QualType EltTy = VT->getElementType(); | ||||
9058 | APValue ZeroElement; | ||||
9059 | if (EltTy->isIntegerType()) | ||||
9060 | ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); | ||||
9061 | else | ||||
9062 | ZeroElement = | ||||
9063 | APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); | ||||
9064 | |||||
9065 | SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); | ||||
9066 | return Success(Elements, E); | ||||
9067 | } | ||||
9068 | |||||
9069 | bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
9070 | VisitIgnoredValue(E->getSubExpr()); | ||||
9071 | return ZeroInitialization(E); | ||||
9072 | } | ||||
9073 | |||||
9074 | //===----------------------------------------------------------------------===// | ||||
9075 | // Array Evaluation | ||||
9076 | //===----------------------------------------------------------------------===// | ||||
9077 | |||||
9078 | namespace { | ||||
9079 | class ArrayExprEvaluator | ||||
9080 | : public ExprEvaluatorBase<ArrayExprEvaluator> { | ||||
9081 | const LValue &This; | ||||
9082 | APValue &Result; | ||||
9083 | public: | ||||
9084 | |||||
9085 | ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) | ||||
9086 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||
9087 | |||||
9088 | bool Success(const APValue &V, const Expr *E) { | ||||
9089 | assert(V.isArray() && "expected array")((V.isArray() && "expected array") ? static_cast<void > (0) : __assert_fail ("V.isArray() && \"expected array\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9089, __PRETTY_FUNCTION__)); | ||||
9090 | Result = V; | ||||
9091 | return true; | ||||
9092 | } | ||||
9093 | |||||
9094 | bool ZeroInitialization(const Expr *E) { | ||||
9095 | const ConstantArrayType *CAT = | ||||
9096 | Info.Ctx.getAsConstantArrayType(E->getType()); | ||||
9097 | if (!CAT) | ||||
9098 | return Error(E); | ||||
9099 | |||||
9100 | Result = APValue(APValue::UninitArray(), 0, | ||||
9101 | CAT->getSize().getZExtValue()); | ||||
9102 | if (!Result.hasArrayFiller()) return true; | ||||
9103 | |||||
9104 | // Zero-initialize all elements. | ||||
9105 | LValue Subobject = This; | ||||
9106 | Subobject.addArray(Info, E, CAT); | ||||
9107 | ImplicitValueInitExpr VIE(CAT->getElementType()); | ||||
9108 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); | ||||
9109 | } | ||||
9110 | |||||
9111 | bool VisitCallExpr(const CallExpr *E) { | ||||
9112 | return handleCallExpr(E, Result, &This); | ||||
9113 | } | ||||
9114 | bool VisitInitListExpr(const InitListExpr *E, | ||||
9115 | QualType AllocType = QualType()); | ||||
9116 | bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); | ||||
9117 | bool VisitCXXConstructExpr(const CXXConstructExpr *E); | ||||
9118 | bool VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
9119 | const LValue &Subobject, | ||||
9120 | APValue *Value, QualType Type); | ||||
9121 | bool VisitStringLiteral(const StringLiteral *E, | ||||
9122 | QualType AllocType = QualType()) { | ||||
9123 | expandStringLiteral(Info, E, Result, AllocType); | ||||
9124 | return true; | ||||
9125 | } | ||||
9126 | }; | ||||
9127 | } // end anonymous namespace | ||||
9128 | |||||
9129 | static bool EvaluateArray(const Expr *E, const LValue &This, | ||||
9130 | APValue &Result, EvalInfo &Info) { | ||||
9131 | assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue")((E->isRValue() && E->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9131, __PRETTY_FUNCTION__)); | ||||
9132 | return ArrayExprEvaluator(Info, This, Result).Visit(E); | ||||
9133 | } | ||||
9134 | |||||
9135 | static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, | ||||
9136 | APValue &Result, const InitListExpr *ILE, | ||||
9137 | QualType AllocType) { | ||||
9138 | assert(ILE->isRValue() && ILE->getType()->isArrayType() &&((ILE->isRValue() && ILE->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9139, __PRETTY_FUNCTION__)) | ||||
9139 | "not an array rvalue")((ILE->isRValue() && ILE->getType()->isArrayType () && "not an array rvalue") ? static_cast<void> (0) : __assert_fail ("ILE->isRValue() && ILE->getType()->isArrayType() && \"not an array rvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9139, __PRETTY_FUNCTION__)); | ||||
9140 | return ArrayExprEvaluator(Info, This, Result) | ||||
9141 | .VisitInitListExpr(ILE, AllocType); | ||||
9142 | } | ||||
9143 | |||||
9144 | // Return true iff the given array filler may depend on the element index. | ||||
9145 | static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { | ||||
9146 | // For now, just whitelist non-class value-initialization and initialization | ||||
9147 | // lists comprised of them. | ||||
9148 | if (isa<ImplicitValueInitExpr>(FillerExpr)) | ||||
9149 | return false; | ||||
9150 | if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { | ||||
9151 | for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { | ||||
9152 | if (MaybeElementDependentArrayFiller(ILE->getInit(I))) | ||||
9153 | return true; | ||||
9154 | } | ||||
9155 | return false; | ||||
9156 | } | ||||
9157 | return true; | ||||
9158 | } | ||||
9159 | |||||
9160 | bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, | ||||
9161 | QualType AllocType) { | ||||
9162 | const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( | ||||
9163 | AllocType.isNull() ? E->getType() : AllocType); | ||||
9164 | if (!CAT) | ||||
9165 | return Error(E); | ||||
9166 | |||||
9167 | // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] | ||||
9168 | // an appropriately-typed string literal enclosed in braces. | ||||
9169 | if (E->isStringLiteralInit()) { | ||||
9170 | auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); | ||||
9171 | // FIXME: Support ObjCEncodeExpr here once we support it in | ||||
9172 | // ArrayExprEvaluator generally. | ||||
9173 | if (!SL) | ||||
9174 | return Error(E); | ||||
9175 | return VisitStringLiteral(SL, AllocType); | ||||
9176 | } | ||||
9177 | |||||
9178 | bool Success = true; | ||||
9179 | |||||
9180 | assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&(((!Result.isArray() || Result.getArrayInitializedElts() == 0 ) && "zero-initialized array shouldn't have any initialized elts" ) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9181, __PRETTY_FUNCTION__)) | ||||
9181 | "zero-initialized array shouldn't have any initialized elts")(((!Result.isArray() || Result.getArrayInitializedElts() == 0 ) && "zero-initialized array shouldn't have any initialized elts" ) ? static_cast<void> (0) : __assert_fail ("(!Result.isArray() || Result.getArrayInitializedElts() == 0) && \"zero-initialized array shouldn't have any initialized elts\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9181, __PRETTY_FUNCTION__)); | ||||
9182 | APValue Filler; | ||||
9183 | if (Result.isArray() && Result.hasArrayFiller()) | ||||
9184 | Filler = Result.getArrayFiller(); | ||||
9185 | |||||
9186 | unsigned NumEltsToInit = E->getNumInits(); | ||||
9187 | unsigned NumElts = CAT->getSize().getZExtValue(); | ||||
9188 | const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; | ||||
9189 | |||||
9190 | // If the initializer might depend on the array index, run it for each | ||||
9191 | // array element. | ||||
9192 | if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) | ||||
9193 | NumEltsToInit = NumElts; | ||||
9194 | |||||
9195 | LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false) | ||||
9196 | << NumEltsToInit << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("exprconstant")) { llvm::dbgs() << "The number of elements to initialize: " << NumEltsToInit << ".\n"; } } while (false); | ||||
9197 | |||||
9198 | Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); | ||||
9199 | |||||
9200 | // If the array was previously zero-initialized, preserve the | ||||
9201 | // zero-initialized values. | ||||
9202 | if (Filler.hasValue()) { | ||||
9203 | for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) | ||||
9204 | Result.getArrayInitializedElt(I) = Filler; | ||||
9205 | if (Result.hasArrayFiller()) | ||||
9206 | Result.getArrayFiller() = Filler; | ||||
9207 | } | ||||
9208 | |||||
9209 | LValue Subobject = This; | ||||
9210 | Subobject.addArray(Info, E, CAT); | ||||
9211 | for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { | ||||
9212 | const Expr *Init = | ||||
9213 | Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; | ||||
9214 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||
9215 | Info, Subobject, Init) || | ||||
9216 | !HandleLValueArrayAdjustment(Info, Init, Subobject, | ||||
9217 | CAT->getElementType(), 1)) { | ||||
9218 | if (!Info.noteFailure()) | ||||
9219 | return false; | ||||
9220 | Success = false; | ||||
9221 | } | ||||
9222 | } | ||||
9223 | |||||
9224 | if (!Result.hasArrayFiller()) | ||||
9225 | return Success; | ||||
9226 | |||||
9227 | // If we get here, we have a trivial filler, which we can just evaluate | ||||
9228 | // once and splat over the rest of the array elements. | ||||
9229 | assert(FillerExpr && "no array filler for incomplete init list")((FillerExpr && "no array filler for incomplete init list" ) ? static_cast<void> (0) : __assert_fail ("FillerExpr && \"no array filler for incomplete init list\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9229, __PRETTY_FUNCTION__)); | ||||
9230 | return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, | ||||
9231 | FillerExpr) && Success; | ||||
9232 | } | ||||
9233 | |||||
9234 | bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { | ||||
9235 | LValue CommonLV; | ||||
9236 | if (E->getCommonExpr() && | ||||
9237 | !Evaluate(Info.CurrentCall->createTemporary( | ||||
9238 | E->getCommonExpr(), | ||||
9239 | getStorageType(Info.Ctx, E->getCommonExpr()), false, | ||||
9240 | CommonLV), | ||||
9241 | Info, E->getCommonExpr()->getSourceExpr())) | ||||
9242 | return false; | ||||
9243 | |||||
9244 | auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); | ||||
9245 | |||||
9246 | uint64_t Elements = CAT->getSize().getZExtValue(); | ||||
9247 | Result = APValue(APValue::UninitArray(), Elements, Elements); | ||||
9248 | |||||
9249 | LValue Subobject = This; | ||||
9250 | Subobject.addArray(Info, E, CAT); | ||||
9251 | |||||
9252 | bool Success = true; | ||||
9253 | for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { | ||||
9254 | if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), | ||||
9255 | Info, Subobject, E->getSubExpr()) || | ||||
9256 | !HandleLValueArrayAdjustment(Info, E, Subobject, | ||||
9257 | CAT->getElementType(), 1)) { | ||||
9258 | if (!Info.noteFailure()) | ||||
9259 | return false; | ||||
9260 | Success = false; | ||||
9261 | } | ||||
9262 | } | ||||
9263 | |||||
9264 | return Success; | ||||
9265 | } | ||||
9266 | |||||
9267 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { | ||||
9268 | return VisitCXXConstructExpr(E, This, &Result, E->getType()); | ||||
9269 | } | ||||
9270 | |||||
9271 | bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, | ||||
9272 | const LValue &Subobject, | ||||
9273 | APValue *Value, | ||||
9274 | QualType Type) { | ||||
9275 | bool HadZeroInit = Value->hasValue(); | ||||
9276 | |||||
9277 | if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { | ||||
9278 | unsigned N = CAT->getSize().getZExtValue(); | ||||
9279 | |||||
9280 | // Preserve the array filler if we had prior zero-initialization. | ||||
9281 | APValue Filler = | ||||
9282 | HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() | ||||
9283 | : APValue(); | ||||
9284 | |||||
9285 | *Value = APValue(APValue::UninitArray(), N, N); | ||||
9286 | |||||
9287 | if (HadZeroInit) | ||||
9288 | for (unsigned I = 0; I != N; ++I) | ||||
9289 | Value->getArrayInitializedElt(I) = Filler; | ||||
9290 | |||||
9291 | // Initialize the elements. | ||||
9292 | LValue ArrayElt = Subobject; | ||||
9293 | ArrayElt.addArray(Info, E, CAT); | ||||
9294 | for (unsigned I = 0; I != N; ++I) | ||||
9295 | if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), | ||||
9296 | CAT->getElementType()) || | ||||
9297 | !HandleLValueArrayAdjustment(Info, E, ArrayElt, | ||||
9298 | CAT->getElementType(), 1)) | ||||
9299 | return false; | ||||
9300 | |||||
9301 | return true; | ||||
9302 | } | ||||
9303 | |||||
9304 | if (!Type->isRecordType()) | ||||
9305 | return Error(E); | ||||
9306 | |||||
9307 | return RecordExprEvaluator(Info, Subobject, *Value) | ||||
9308 | .VisitCXXConstructExpr(E, Type); | ||||
9309 | } | ||||
9310 | |||||
9311 | //===----------------------------------------------------------------------===// | ||||
9312 | // Integer Evaluation | ||||
9313 | // | ||||
9314 | // As a GNU extension, we support casting pointers to sufficiently-wide integer | ||||
9315 | // types and back in constant folding. Integer values are thus represented | ||||
9316 | // either as an integer-valued APValue, or as an lvalue-valued APValue. | ||||
9317 | //===----------------------------------------------------------------------===// | ||||
9318 | |||||
9319 | namespace { | ||||
9320 | class IntExprEvaluator | ||||
9321 | : public ExprEvaluatorBase<IntExprEvaluator> { | ||||
9322 | APValue &Result; | ||||
9323 | public: | ||||
9324 | IntExprEvaluator(EvalInfo &info, APValue &result) | ||||
9325 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
9326 | |||||
9327 | bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { | ||||
9328 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9329, __PRETTY_FUNCTION__)) | ||||
9329 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9329, __PRETTY_FUNCTION__)); | ||||
9330 | assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType () && "Invalid evaluation result.") ? static_cast< void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9331, __PRETTY_FUNCTION__)) | ||||
9331 | "Invalid evaluation result.")((SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType () && "Invalid evaluation result.") ? static_cast< void> (0) : __assert_fail ("SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9331, __PRETTY_FUNCTION__)); | ||||
9332 | assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9333, __PRETTY_FUNCTION__)) | ||||
9333 | "Invalid evaluation result.")((SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9333, __PRETTY_FUNCTION__)); | ||||
9334 | Result = APValue(SI); | ||||
9335 | return true; | ||||
9336 | } | ||||
9337 | bool Success(const llvm::APSInt &SI, const Expr *E) { | ||||
9338 | return Success(SI, E, Result); | ||||
9339 | } | ||||
9340 | |||||
9341 | bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { | ||||
9342 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9343, __PRETTY_FUNCTION__)) | ||||
9343 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9343, __PRETTY_FUNCTION__)); | ||||
9344 | assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9345, __PRETTY_FUNCTION__)) | ||||
9345 | "Invalid evaluation result.")((I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9345, __PRETTY_FUNCTION__)); | ||||
9346 | Result = APValue(APSInt(I)); | ||||
9347 | Result.getInt().setIsUnsigned( | ||||
9348 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||
9349 | return true; | ||||
9350 | } | ||||
9351 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||
9352 | return Success(I, E, Result); | ||||
9353 | } | ||||
9354 | |||||
9355 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||
9356 | assert(E->getType()->isIntegralOrEnumerationType() &&((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9357, __PRETTY_FUNCTION__)) | ||||
9357 | "Invalid evaluation result.")((E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("E->getType()->isIntegralOrEnumerationType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9357, __PRETTY_FUNCTION__)); | ||||
9358 | Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); | ||||
9359 | return true; | ||||
9360 | } | ||||
9361 | bool Success(uint64_t Value, const Expr *E) { | ||||
9362 | return Success(Value, E, Result); | ||||
9363 | } | ||||
9364 | |||||
9365 | bool Success(CharUnits Size, const Expr *E) { | ||||
9366 | return Success(Size.getQuantity(), E); | ||||
9367 | } | ||||
9368 | |||||
9369 | bool Success(const APValue &V, const Expr *E) { | ||||
9370 | if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { | ||||
9371 | Result = V; | ||||
9372 | return true; | ||||
9373 | } | ||||
9374 | return Success(V.getInt(), E); | ||||
9375 | } | ||||
9376 | |||||
9377 | bool ZeroInitialization(const Expr *E) { return Success(0, E); } | ||||
9378 | |||||
9379 | //===--------------------------------------------------------------------===// | ||||
9380 | // Visitor Methods | ||||
9381 | //===--------------------------------------------------------------------===// | ||||
9382 | |||||
9383 | bool VisitConstantExpr(const ConstantExpr *E); | ||||
9384 | |||||
9385 | bool VisitIntegerLiteral(const IntegerLiteral *E) { | ||||
9386 | return Success(E->getValue(), E); | ||||
9387 | } | ||||
9388 | bool VisitCharacterLiteral(const CharacterLiteral *E) { | ||||
9389 | return Success(E->getValue(), E); | ||||
9390 | } | ||||
9391 | |||||
9392 | bool CheckReferencedDecl(const Expr *E, const Decl *D); | ||||
9393 | bool VisitDeclRefExpr(const DeclRefExpr *E) { | ||||
9394 | if (CheckReferencedDecl(E, E->getDecl())) | ||||
9395 | return true; | ||||
9396 | |||||
9397 | return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); | ||||
9398 | } | ||||
9399 | bool VisitMemberExpr(const MemberExpr *E) { | ||||
9400 | if (CheckReferencedDecl(E, E->getMemberDecl())) { | ||||
9401 | VisitIgnoredBaseExpression(E->getBase()); | ||||
9402 | return true; | ||||
9403 | } | ||||
9404 | |||||
9405 | return ExprEvaluatorBaseTy::VisitMemberExpr(E); | ||||
9406 | } | ||||
9407 | |||||
9408 | bool VisitCallExpr(const CallExpr *E); | ||||
9409 | bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); | ||||
9410 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
9411 | bool VisitOffsetOfExpr(const OffsetOfExpr *E); | ||||
9412 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
9413 | |||||
9414 | bool VisitCastExpr(const CastExpr* E); | ||||
9415 | bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); | ||||
9416 | |||||
9417 | bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { | ||||
9418 | return Success(E->getValue(), E); | ||||
9419 | } | ||||
9420 | |||||
9421 | bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { | ||||
9422 | return Success(E->getValue(), E); | ||||
9423 | } | ||||
9424 | |||||
9425 | bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { | ||||
9426 | if (Info.ArrayInitIndex == uint64_t(-1)) { | ||||
9427 | // We were asked to evaluate this subexpression independent of the | ||||
9428 | // enclosing ArrayInitLoopExpr. We can't do that. | ||||
9429 | Info.FFDiag(E); | ||||
9430 | return false; | ||||
9431 | } | ||||
9432 | return Success(Info.ArrayInitIndex, E); | ||||
9433 | } | ||||
9434 | |||||
9435 | // Note, GNU defines __null as an integer, not a pointer. | ||||
9436 | bool VisitGNUNullExpr(const GNUNullExpr *E) { | ||||
9437 | return ZeroInitialization(E); | ||||
9438 | } | ||||
9439 | |||||
9440 | bool VisitTypeTraitExpr(const TypeTraitExpr *E) { | ||||
9441 | return Success(E->getValue(), E); | ||||
9442 | } | ||||
9443 | |||||
9444 | bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { | ||||
9445 | return Success(E->getValue(), E); | ||||
9446 | } | ||||
9447 | |||||
9448 | bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { | ||||
9449 | return Success(E->getValue(), E); | ||||
9450 | } | ||||
9451 | |||||
9452 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
9453 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
9454 | |||||
9455 | bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); | ||||
9456 | bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); | ||||
9457 | bool VisitSourceLocExpr(const SourceLocExpr *E); | ||||
9458 | // FIXME: Missing: array subscript of vector, member of vector | ||||
9459 | }; | ||||
9460 | |||||
9461 | class FixedPointExprEvaluator | ||||
9462 | : public ExprEvaluatorBase<FixedPointExprEvaluator> { | ||||
9463 | APValue &Result; | ||||
9464 | |||||
9465 | public: | ||||
9466 | FixedPointExprEvaluator(EvalInfo &info, APValue &result) | ||||
9467 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
9468 | |||||
9469 | bool Success(const llvm::APInt &I, const Expr *E) { | ||||
9470 | return Success( | ||||
9471 | APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||
9472 | } | ||||
9473 | |||||
9474 | bool Success(uint64_t Value, const Expr *E) { | ||||
9475 | return Success( | ||||
9476 | APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); | ||||
9477 | } | ||||
9478 | |||||
9479 | bool Success(const APValue &V, const Expr *E) { | ||||
9480 | return Success(V.getFixedPoint(), E); | ||||
9481 | } | ||||
9482 | |||||
9483 | bool Success(const APFixedPoint &V, const Expr *E) { | ||||
9484 | assert(E->getType()->isFixedPointType() && "Invalid evaluation result.")((E->getType()->isFixedPointType() && "Invalid evaluation result." ) ? static_cast<void> (0) : __assert_fail ("E->getType()->isFixedPointType() && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9484, __PRETTY_FUNCTION__)); | ||||
9485 | assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9486, __PRETTY_FUNCTION__)) | ||||
9486 | "Invalid evaluation result.")((V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result.") ? static_cast<void> (0) : __assert_fail ("V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && \"Invalid evaluation result.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9486, __PRETTY_FUNCTION__)); | ||||
9487 | Result = APValue(V); | ||||
9488 | return true; | ||||
9489 | } | ||||
9490 | |||||
9491 | //===--------------------------------------------------------------------===// | ||||
9492 | // Visitor Methods | ||||
9493 | //===--------------------------------------------------------------------===// | ||||
9494 | |||||
9495 | bool VisitFixedPointLiteral(const FixedPointLiteral *E) { | ||||
9496 | return Success(E->getValue(), E); | ||||
9497 | } | ||||
9498 | |||||
9499 | bool VisitCastExpr(const CastExpr *E); | ||||
9500 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
9501 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
9502 | }; | ||||
9503 | } // end anonymous namespace | ||||
9504 | |||||
9505 | /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and | ||||
9506 | /// produce either the integer value or a pointer. | ||||
9507 | /// | ||||
9508 | /// GCC has a heinous extension which folds casts between pointer types and | ||||
9509 | /// pointer-sized integral types. We support this by allowing the evaluation of | ||||
9510 | /// an integer rvalue to produce a pointer (represented as an lvalue) instead. | ||||
9511 | /// Some simple arithmetic on such values is supported (they are treated much | ||||
9512 | /// like char*). | ||||
9513 | static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, | ||||
9514 | EvalInfo &Info) { | ||||
9515 | assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType())((E->isRValue() && E->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9515, __PRETTY_FUNCTION__)); | ||||
9516 | return IntExprEvaluator(Info, Result).Visit(E); | ||||
9517 | } | ||||
9518 | |||||
9519 | static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { | ||||
9520 | APValue Val; | ||||
9521 | if (!EvaluateIntegerOrLValue(E, Val, Info)) | ||||
9522 | return false; | ||||
9523 | if (!Val.isInt()) { | ||||
9524 | // FIXME: It would be better to produce the diagnostic for casting | ||||
9525 | // a pointer to an integer. | ||||
9526 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
9527 | return false; | ||||
9528 | } | ||||
9529 | Result = Val.getInt(); | ||||
9530 | return true; | ||||
9531 | } | ||||
9532 | |||||
9533 | bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { | ||||
9534 | APValue Evaluated = E->EvaluateInContext( | ||||
9535 | Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); | ||||
9536 | return Success(Evaluated, E); | ||||
9537 | } | ||||
9538 | |||||
9539 | static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, | ||||
9540 | EvalInfo &Info) { | ||||
9541 | if (E->getType()->isFixedPointType()) { | ||||
9542 | APValue Val; | ||||
9543 | if (!FixedPointExprEvaluator(Info, Val).Visit(E)) | ||||
9544 | return false; | ||||
9545 | if (!Val.isFixedPoint()) | ||||
9546 | return false; | ||||
9547 | |||||
9548 | Result = Val.getFixedPoint(); | ||||
9549 | return true; | ||||
9550 | } | ||||
9551 | return false; | ||||
9552 | } | ||||
9553 | |||||
9554 | static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, | ||||
9555 | EvalInfo &Info) { | ||||
9556 | if (E->getType()->isIntegerType()) { | ||||
9557 | auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); | ||||
9558 | APSInt Val; | ||||
9559 | if (!EvaluateInteger(E, Val, Info)) | ||||
9560 | return false; | ||||
9561 | Result = APFixedPoint(Val, FXSema); | ||||
9562 | return true; | ||||
9563 | } else if (E->getType()->isFixedPointType()) { | ||||
9564 | return EvaluateFixedPoint(E, Result, Info); | ||||
9565 | } | ||||
9566 | return false; | ||||
9567 | } | ||||
9568 | |||||
9569 | /// Check whether the given declaration can be directly converted to an integral | ||||
9570 | /// rvalue. If not, no diagnostic is produced; there are other things we can | ||||
9571 | /// try. | ||||
9572 | bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { | ||||
9573 | // Enums are integer constant exprs. | ||||
9574 | if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { | ||||
9575 | // Check for signedness/width mismatches between E type and ECD value. | ||||
9576 | bool SameSign = (ECD->getInitVal().isSigned() | ||||
9577 | == E->getType()->isSignedIntegerOrEnumerationType()); | ||||
9578 | bool SameWidth = (ECD->getInitVal().getBitWidth() | ||||
9579 | == Info.Ctx.getIntWidth(E->getType())); | ||||
9580 | if (SameSign && SameWidth) | ||||
9581 | return Success(ECD->getInitVal(), E); | ||||
9582 | else { | ||||
9583 | // Get rid of mismatch (otherwise Success assertions will fail) | ||||
9584 | // by computing a new value matching the type of E. | ||||
9585 | llvm::APSInt Val = ECD->getInitVal(); | ||||
9586 | if (!SameSign) | ||||
9587 | Val.setIsSigned(!ECD->getInitVal().isSigned()); | ||||
9588 | if (!SameWidth) | ||||
9589 | Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); | ||||
9590 | return Success(Val, E); | ||||
9591 | } | ||||
9592 | } | ||||
9593 | return false; | ||||
9594 | } | ||||
9595 | |||||
9596 | /// Values returned by __builtin_classify_type, chosen to match the values | ||||
9597 | /// produced by GCC's builtin. | ||||
9598 | enum class GCCTypeClass { | ||||
9599 | None = -1, | ||||
9600 | Void = 0, | ||||
9601 | Integer = 1, | ||||
9602 | // GCC reserves 2 for character types, but instead classifies them as | ||||
9603 | // integers. | ||||
9604 | Enum = 3, | ||||
9605 | Bool = 4, | ||||
9606 | Pointer = 5, | ||||
9607 | // GCC reserves 6 for references, but appears to never use it (because | ||||
9608 | // expressions never have reference type, presumably). | ||||
9609 | PointerToDataMember = 7, | ||||
9610 | RealFloat = 8, | ||||
9611 | Complex = 9, | ||||
9612 | // GCC reserves 10 for functions, but does not use it since GCC version 6 due | ||||
9613 | // to decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||
9614 | // GCC claims to reserve 11 for pointers to member functions, but *actually* | ||||
9615 | // uses 12 for that purpose, same as for a class or struct. Maybe it | ||||
9616 | // internally implements a pointer to member as a struct? Who knows. | ||||
9617 | PointerToMemberFunction = 12, // Not a bug, see above. | ||||
9618 | ClassOrStruct = 12, | ||||
9619 | Union = 13, | ||||
9620 | // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to | ||||
9621 | // decay to pointer. (Prior to version 6 it was only used in C++ mode). | ||||
9622 | // GCC reserves 15 for strings, but actually uses 5 (pointer) for string | ||||
9623 | // literals. | ||||
9624 | }; | ||||
9625 | |||||
9626 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||
9627 | /// as GCC. | ||||
9628 | static GCCTypeClass | ||||
9629 | EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { | ||||
9630 | assert(!T->isDependentType() && "unexpected dependent type")((!T->isDependentType() && "unexpected dependent type" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"unexpected dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9630, __PRETTY_FUNCTION__)); | ||||
9631 | |||||
9632 | QualType CanTy = T.getCanonicalType(); | ||||
9633 | const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); | ||||
9634 | |||||
9635 | switch (CanTy->getTypeClass()) { | ||||
9636 | #define TYPE(ID, BASE) | ||||
9637 | #define DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||
9638 | #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: | ||||
9639 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: | ||||
9640 | #include "clang/AST/TypeNodes.inc" | ||||
9641 | case Type::Auto: | ||||
9642 | case Type::DeducedTemplateSpecialization: | ||||
9643 | llvm_unreachable("unexpected non-canonical or dependent type")::llvm::llvm_unreachable_internal("unexpected non-canonical or dependent type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9643); | ||||
9644 | |||||
9645 | case Type::Builtin: | ||||
9646 | switch (BT->getKind()) { | ||||
9647 | #define BUILTIN_TYPE(ID, SINGLETON_ID) | ||||
9648 | #define SIGNED_TYPE(ID, SINGLETON_ID) \ | ||||
9649 | case BuiltinType::ID: return GCCTypeClass::Integer; | ||||
9650 | #define FLOATING_TYPE(ID, SINGLETON_ID) \ | ||||
9651 | case BuiltinType::ID: return GCCTypeClass::RealFloat; | ||||
9652 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ | ||||
9653 | case BuiltinType::ID: break; | ||||
9654 | #include "clang/AST/BuiltinTypes.def" | ||||
9655 | case BuiltinType::Void: | ||||
9656 | return GCCTypeClass::Void; | ||||
9657 | |||||
9658 | case BuiltinType::Bool: | ||||
9659 | return GCCTypeClass::Bool; | ||||
9660 | |||||
9661 | case BuiltinType::Char_U: | ||||
9662 | case BuiltinType::UChar: | ||||
9663 | case BuiltinType::WChar_U: | ||||
9664 | case BuiltinType::Char8: | ||||
9665 | case BuiltinType::Char16: | ||||
9666 | case BuiltinType::Char32: | ||||
9667 | case BuiltinType::UShort: | ||||
9668 | case BuiltinType::UInt: | ||||
9669 | case BuiltinType::ULong: | ||||
9670 | case BuiltinType::ULongLong: | ||||
9671 | case BuiltinType::UInt128: | ||||
9672 | return GCCTypeClass::Integer; | ||||
9673 | |||||
9674 | case BuiltinType::UShortAccum: | ||||
9675 | case BuiltinType::UAccum: | ||||
9676 | case BuiltinType::ULongAccum: | ||||
9677 | case BuiltinType::UShortFract: | ||||
9678 | case BuiltinType::UFract: | ||||
9679 | case BuiltinType::ULongFract: | ||||
9680 | case BuiltinType::SatUShortAccum: | ||||
9681 | case BuiltinType::SatUAccum: | ||||
9682 | case BuiltinType::SatULongAccum: | ||||
9683 | case BuiltinType::SatUShortFract: | ||||
9684 | case BuiltinType::SatUFract: | ||||
9685 | case BuiltinType::SatULongFract: | ||||
9686 | return GCCTypeClass::None; | ||||
9687 | |||||
9688 | case BuiltinType::NullPtr: | ||||
9689 | |||||
9690 | case BuiltinType::ObjCId: | ||||
9691 | case BuiltinType::ObjCClass: | ||||
9692 | case BuiltinType::ObjCSel: | ||||
9693 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | ||||
9694 | case BuiltinType::Id: | ||||
9695 | #include "clang/Basic/OpenCLImageTypes.def" | ||||
9696 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | ||||
9697 | case BuiltinType::Id: | ||||
9698 | #include "clang/Basic/OpenCLExtensionTypes.def" | ||||
9699 | case BuiltinType::OCLSampler: | ||||
9700 | case BuiltinType::OCLEvent: | ||||
9701 | case BuiltinType::OCLClkEvent: | ||||
9702 | case BuiltinType::OCLQueue: | ||||
9703 | case BuiltinType::OCLReserveID: | ||||
9704 | #define SVE_TYPE(Name, Id, SingletonId) \ | ||||
9705 | case BuiltinType::Id: | ||||
9706 | #include "clang/Basic/AArch64SVEACLETypes.def" | ||||
9707 | return GCCTypeClass::None; | ||||
9708 | |||||
9709 | case BuiltinType::Dependent: | ||||
9710 | llvm_unreachable("unexpected dependent type")::llvm::llvm_unreachable_internal("unexpected dependent type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9710); | ||||
9711 | }; | ||||
9712 | llvm_unreachable("unexpected placeholder type")::llvm::llvm_unreachable_internal("unexpected placeholder type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9712); | ||||
9713 | |||||
9714 | case Type::Enum: | ||||
9715 | return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; | ||||
9716 | |||||
9717 | case Type::Pointer: | ||||
9718 | case Type::ConstantArray: | ||||
9719 | case Type::VariableArray: | ||||
9720 | case Type::IncompleteArray: | ||||
9721 | case Type::FunctionNoProto: | ||||
9722 | case Type::FunctionProto: | ||||
9723 | return GCCTypeClass::Pointer; | ||||
9724 | |||||
9725 | case Type::MemberPointer: | ||||
9726 | return CanTy->isMemberDataPointerType() | ||||
9727 | ? GCCTypeClass::PointerToDataMember | ||||
9728 | : GCCTypeClass::PointerToMemberFunction; | ||||
9729 | |||||
9730 | case Type::Complex: | ||||
9731 | return GCCTypeClass::Complex; | ||||
9732 | |||||
9733 | case Type::Record: | ||||
9734 | return CanTy->isUnionType() ? GCCTypeClass::Union | ||||
9735 | : GCCTypeClass::ClassOrStruct; | ||||
9736 | |||||
9737 | case Type::Atomic: | ||||
9738 | // GCC classifies _Atomic T the same as T. | ||||
9739 | return EvaluateBuiltinClassifyType( | ||||
9740 | CanTy->castAs<AtomicType>()->getValueType(), LangOpts); | ||||
9741 | |||||
9742 | case Type::BlockPointer: | ||||
9743 | case Type::Vector: | ||||
9744 | case Type::ExtVector: | ||||
9745 | case Type::ObjCObject: | ||||
9746 | case Type::ObjCInterface: | ||||
9747 | case Type::ObjCObjectPointer: | ||||
9748 | case Type::Pipe: | ||||
9749 | // GCC classifies vectors as None. We follow its lead and classify all | ||||
9750 | // other types that don't fit into the regular classification the same way. | ||||
9751 | return GCCTypeClass::None; | ||||
9752 | |||||
9753 | case Type::LValueReference: | ||||
9754 | case Type::RValueReference: | ||||
9755 | llvm_unreachable("invalid type for expression")::llvm::llvm_unreachable_internal("invalid type for expression" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9755); | ||||
9756 | } | ||||
9757 | |||||
9758 | llvm_unreachable("unexpected type class")::llvm::llvm_unreachable_internal("unexpected type class", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9758); | ||||
9759 | } | ||||
9760 | |||||
9761 | /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way | ||||
9762 | /// as GCC. | ||||
9763 | static GCCTypeClass | ||||
9764 | EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { | ||||
9765 | // If no argument was supplied, default to None. This isn't | ||||
9766 | // ideal, however it is what gcc does. | ||||
9767 | if (E->getNumArgs() == 0) | ||||
9768 | return GCCTypeClass::None; | ||||
9769 | |||||
9770 | // FIXME: Bizarrely, GCC treats a call with more than one argument as not | ||||
9771 | // being an ICE, but still folds it to a constant using the type of the first | ||||
9772 | // argument. | ||||
9773 | return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); | ||||
9774 | } | ||||
9775 | |||||
9776 | /// EvaluateBuiltinConstantPForLValue - Determine the result of | ||||
9777 | /// __builtin_constant_p when applied to the given pointer. | ||||
9778 | /// | ||||
9779 | /// A pointer is only "constant" if it is null (or a pointer cast to integer) | ||||
9780 | /// or it points to the first character of a string literal. | ||||
9781 | static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { | ||||
9782 | APValue::LValueBase Base = LV.getLValueBase(); | ||||
9783 | if (Base.isNull()) { | ||||
9784 | // A null base is acceptable. | ||||
9785 | return true; | ||||
9786 | } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { | ||||
9787 | if (!isa<StringLiteral>(E)) | ||||
9788 | return false; | ||||
9789 | return LV.getLValueOffset().isZero(); | ||||
9790 | } else if (Base.is<TypeInfoLValue>()) { | ||||
9791 | // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to | ||||
9792 | // evaluate to true. | ||||
9793 | return true; | ||||
9794 | } else { | ||||
9795 | // Any other base is not constant enough for GCC. | ||||
9796 | return false; | ||||
9797 | } | ||||
9798 | } | ||||
9799 | |||||
9800 | /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to | ||||
9801 | /// GCC as we can manage. | ||||
9802 | static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { | ||||
9803 | // This evaluation is not permitted to have side-effects, so evaluate it in | ||||
9804 | // a speculative evaluation context. | ||||
9805 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||
9806 | |||||
9807 | // Constant-folding is always enabled for the operand of __builtin_constant_p | ||||
9808 | // (even when the enclosing evaluation context otherwise requires a strict | ||||
9809 | // language-specific constant expression). | ||||
9810 | FoldConstant Fold(Info, true); | ||||
9811 | |||||
9812 | QualType ArgType = Arg->getType(); | ||||
9813 | |||||
9814 | // __builtin_constant_p always has one operand. The rules which gcc follows | ||||
9815 | // are not precisely documented, but are as follows: | ||||
9816 | // | ||||
9817 | // - If the operand is of integral, floating, complex or enumeration type, | ||||
9818 | // and can be folded to a known value of that type, it returns 1. | ||||
9819 | // - If the operand can be folded to a pointer to the first character | ||||
9820 | // of a string literal (or such a pointer cast to an integral type) | ||||
9821 | // or to a null pointer or an integer cast to a pointer, it returns 1. | ||||
9822 | // | ||||
9823 | // Otherwise, it returns 0. | ||||
9824 | // | ||||
9825 | // FIXME: GCC also intends to return 1 for literals of aggregate types, but | ||||
9826 | // its support for this did not work prior to GCC 9 and is not yet well | ||||
9827 | // understood. | ||||
9828 | if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || | ||||
9829 | ArgType->isAnyComplexType() || ArgType->isPointerType() || | ||||
9830 | ArgType->isNullPtrType()) { | ||||
9831 | APValue V; | ||||
9832 | if (!::EvaluateAsRValue(Info, Arg, V)) { | ||||
9833 | Fold.keepDiagnostics(); | ||||
9834 | return false; | ||||
9835 | } | ||||
9836 | |||||
9837 | // For a pointer (possibly cast to integer), there are special rules. | ||||
9838 | if (V.getKind() == APValue::LValue) | ||||
9839 | return EvaluateBuiltinConstantPForLValue(V); | ||||
9840 | |||||
9841 | // Otherwise, any constant value is good enough. | ||||
9842 | return V.hasValue(); | ||||
9843 | } | ||||
9844 | |||||
9845 | // Anything else isn't considered to be sufficiently constant. | ||||
9846 | return false; | ||||
9847 | } | ||||
9848 | |||||
9849 | /// Retrieves the "underlying object type" of the given expression, | ||||
9850 | /// as used by __builtin_object_size. | ||||
9851 | static QualType getObjectType(APValue::LValueBase B) { | ||||
9852 | if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { | ||||
9853 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
9854 | return VD->getType(); | ||||
9855 | } else if (const Expr *E = B.get<const Expr*>()) { | ||||
9856 | if (isa<CompoundLiteralExpr>(E)) | ||||
9857 | return E->getType(); | ||||
9858 | } else if (B.is<TypeInfoLValue>()) { | ||||
9859 | return B.getTypeInfoType(); | ||||
9860 | } else if (B.is<DynamicAllocLValue>()) { | ||||
9861 | return B.getDynamicAllocType(); | ||||
9862 | } | ||||
9863 | |||||
9864 | return QualType(); | ||||
9865 | } | ||||
9866 | |||||
9867 | /// A more selective version of E->IgnoreParenCasts for | ||||
9868 | /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only | ||||
9869 | /// to change the type of E. | ||||
9870 | /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` | ||||
9871 | /// | ||||
9872 | /// Always returns an RValue with a pointer representation. | ||||
9873 | static const Expr *ignorePointerCastsAndParens(const Expr *E) { | ||||
9874 | assert(E->isRValue() && E->getType()->hasPointerRepresentation())((E->isRValue() && E->getType()->hasPointerRepresentation ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->hasPointerRepresentation()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9874, __PRETTY_FUNCTION__)); | ||||
9875 | |||||
9876 | auto *NoParens = E->IgnoreParens(); | ||||
9877 | auto *Cast = dyn_cast<CastExpr>(NoParens); | ||||
9878 | if (Cast == nullptr) | ||||
9879 | return NoParens; | ||||
9880 | |||||
9881 | // We only conservatively allow a few kinds of casts, because this code is | ||||
9882 | // inherently a simple solution that seeks to support the common case. | ||||
9883 | auto CastKind = Cast->getCastKind(); | ||||
9884 | if (CastKind != CK_NoOp && CastKind != CK_BitCast && | ||||
9885 | CastKind != CK_AddressSpaceConversion) | ||||
9886 | return NoParens; | ||||
9887 | |||||
9888 | auto *SubExpr = Cast->getSubExpr(); | ||||
9889 | if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) | ||||
9890 | return NoParens; | ||||
9891 | return ignorePointerCastsAndParens(SubExpr); | ||||
9892 | } | ||||
9893 | |||||
9894 | /// Checks to see if the given LValue's Designator is at the end of the LValue's | ||||
9895 | /// record layout. e.g. | ||||
9896 | /// struct { struct { int a, b; } fst, snd; } obj; | ||||
9897 | /// obj.fst // no | ||||
9898 | /// obj.snd // yes | ||||
9899 | /// obj.fst.a // no | ||||
9900 | /// obj.fst.b // no | ||||
9901 | /// obj.snd.a // no | ||||
9902 | /// obj.snd.b // yes | ||||
9903 | /// | ||||
9904 | /// Please note: this function is specialized for how __builtin_object_size | ||||
9905 | /// views "objects". | ||||
9906 | /// | ||||
9907 | /// If this encounters an invalid RecordDecl or otherwise cannot determine the | ||||
9908 | /// correct result, it will always return true. | ||||
9909 | static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||
9910 | assert(!LVal.Designator.Invalid)((!LVal.Designator.Invalid) ? static_cast<void> (0) : __assert_fail ("!LVal.Designator.Invalid", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9910, __PRETTY_FUNCTION__)); | ||||
9911 | |||||
9912 | auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { | ||||
9913 | const RecordDecl *Parent = FD->getParent(); | ||||
9914 | Invalid = Parent->isInvalidDecl(); | ||||
9915 | if (Invalid || Parent->isUnion()) | ||||
9916 | return true; | ||||
9917 | const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); | ||||
9918 | return FD->getFieldIndex() + 1 == Layout.getFieldCount(); | ||||
9919 | }; | ||||
9920 | |||||
9921 | auto &Base = LVal.getLValueBase(); | ||||
9922 | if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { | ||||
9923 | if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { | ||||
9924 | bool Invalid; | ||||
9925 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||
9926 | return Invalid; | ||||
9927 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { | ||||
9928 | for (auto *FD : IFD->chain()) { | ||||
9929 | bool Invalid; | ||||
9930 | if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) | ||||
9931 | return Invalid; | ||||
9932 | } | ||||
9933 | } | ||||
9934 | } | ||||
9935 | |||||
9936 | unsigned I = 0; | ||||
9937 | QualType BaseType = getType(Base); | ||||
9938 | if (LVal.Designator.FirstEntryIsAnUnsizedArray) { | ||||
9939 | // If we don't know the array bound, conservatively assume we're looking at | ||||
9940 | // the final array element. | ||||
9941 | ++I; | ||||
9942 | if (BaseType->isIncompleteArrayType()) | ||||
9943 | BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); | ||||
9944 | else | ||||
9945 | BaseType = BaseType->castAs<PointerType>()->getPointeeType(); | ||||
9946 | } | ||||
9947 | |||||
9948 | for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { | ||||
9949 | const auto &Entry = LVal.Designator.Entries[I]; | ||||
9950 | if (BaseType->isArrayType()) { | ||||
9951 | // Because __builtin_object_size treats arrays as objects, we can ignore | ||||
9952 | // the index iff this is the last array in the Designator. | ||||
9953 | if (I + 1 == E) | ||||
9954 | return true; | ||||
9955 | const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); | ||||
9956 | uint64_t Index = Entry.getAsArrayIndex(); | ||||
9957 | if (Index + 1 != CAT->getSize()) | ||||
9958 | return false; | ||||
9959 | BaseType = CAT->getElementType(); | ||||
9960 | } else if (BaseType->isAnyComplexType()) { | ||||
9961 | const auto *CT = BaseType->castAs<ComplexType>(); | ||||
9962 | uint64_t Index = Entry.getAsArrayIndex(); | ||||
9963 | if (Index != 1) | ||||
9964 | return false; | ||||
9965 | BaseType = CT->getElementType(); | ||||
9966 | } else if (auto *FD = getAsField(Entry)) { | ||||
9967 | bool Invalid; | ||||
9968 | if (!IsLastOrInvalidFieldDecl(FD, Invalid)) | ||||
9969 | return Invalid; | ||||
9970 | BaseType = FD->getType(); | ||||
9971 | } else { | ||||
9972 | assert(getAsBaseClass(Entry) && "Expecting cast to a base class")((getAsBaseClass(Entry) && "Expecting cast to a base class" ) ? static_cast<void> (0) : __assert_fail ("getAsBaseClass(Entry) && \"Expecting cast to a base class\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 9972, __PRETTY_FUNCTION__)); | ||||
9973 | return false; | ||||
9974 | } | ||||
9975 | } | ||||
9976 | return true; | ||||
9977 | } | ||||
9978 | |||||
9979 | /// Tests to see if the LValue has a user-specified designator (that isn't | ||||
9980 | /// necessarily valid). Note that this always returns 'true' if the LValue has | ||||
9981 | /// an unsized array as its first designator entry, because there's currently no | ||||
9982 | /// way to tell if the user typed *foo or foo[0]. | ||||
9983 | static bool refersToCompleteObject(const LValue &LVal) { | ||||
9984 | if (LVal.Designator.Invalid) | ||||
9985 | return false; | ||||
9986 | |||||
9987 | if (!LVal.Designator.Entries.empty()) | ||||
9988 | return LVal.Designator.isMostDerivedAnUnsizedArray(); | ||||
9989 | |||||
9990 | if (!LVal.InvalidBase) | ||||
9991 | return true; | ||||
9992 | |||||
9993 | // If `E` is a MemberExpr, then the first part of the designator is hiding in | ||||
9994 | // the LValueBase. | ||||
9995 | const auto *E = LVal.Base.dyn_cast<const Expr *>(); | ||||
9996 | return !E || !isa<MemberExpr>(E); | ||||
9997 | } | ||||
9998 | |||||
9999 | /// Attempts to detect a user writing into a piece of memory that's impossible | ||||
10000 | /// to figure out the size of by just using types. | ||||
10001 | static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { | ||||
10002 | const SubobjectDesignator &Designator = LVal.Designator; | ||||
10003 | // Notes: | ||||
10004 | // - Users can only write off of the end when we have an invalid base. Invalid | ||||
10005 | // bases imply we don't know where the memory came from. | ||||
10006 | // - We used to be a bit more aggressive here; we'd only be conservative if | ||||
10007 | // the array at the end was flexible, or if it had 0 or 1 elements. This | ||||
10008 | // broke some common standard library extensions (PR30346), but was | ||||
10009 | // otherwise seemingly fine. It may be useful to reintroduce this behavior | ||||
10010 | // with some sort of whitelist. OTOH, it seems that GCC is always | ||||
10011 | // conservative with the last element in structs (if it's an array), so our | ||||
10012 | // current behavior is more compatible than a whitelisting approach would | ||||
10013 | // be. | ||||
10014 | return LVal.InvalidBase && | ||||
10015 | Designator.Entries.size() == Designator.MostDerivedPathLength && | ||||
10016 | Designator.MostDerivedIsArrayElement && | ||||
10017 | isDesignatorAtObjectEnd(Ctx, LVal); | ||||
10018 | } | ||||
10019 | |||||
10020 | /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. | ||||
10021 | /// Fails if the conversion would cause loss of precision. | ||||
10022 | static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, | ||||
10023 | CharUnits &Result) { | ||||
10024 | auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); | ||||
10025 | if (Int.ugt(CharUnitsMax)) | ||||
10026 | return false; | ||||
10027 | Result = CharUnits::fromQuantity(Int.getZExtValue()); | ||||
10028 | return true; | ||||
10029 | } | ||||
10030 | |||||
10031 | /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will | ||||
10032 | /// determine how many bytes exist from the beginning of the object to either | ||||
10033 | /// the end of the current subobject, or the end of the object itself, depending | ||||
10034 | /// on what the LValue looks like + the value of Type. | ||||
10035 | /// | ||||
10036 | /// If this returns false, the value of Result is undefined. | ||||
10037 | static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, | ||||
10038 | unsigned Type, const LValue &LVal, | ||||
10039 | CharUnits &EndOffset) { | ||||
10040 | bool DetermineForCompleteObject = refersToCompleteObject(LVal); | ||||
10041 | |||||
10042 | auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { | ||||
10043 | if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) | ||||
10044 | return false; | ||||
10045 | return HandleSizeof(Info, ExprLoc, Ty, Result); | ||||
10046 | }; | ||||
10047 | |||||
10048 | // We want to evaluate the size of the entire object. This is a valid fallback | ||||
10049 | // for when Type=1 and the designator is invalid, because we're asked for an | ||||
10050 | // upper-bound. | ||||
10051 | if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { | ||||
10052 | // Type=3 wants a lower bound, so we can't fall back to this. | ||||
10053 | if (Type == 3 && !DetermineForCompleteObject) | ||||
10054 | return false; | ||||
10055 | |||||
10056 | llvm::APInt APEndOffset; | ||||
10057 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||
10058 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||
10059 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||
10060 | |||||
10061 | if (LVal.InvalidBase) | ||||
10062 | return false; | ||||
10063 | |||||
10064 | QualType BaseTy = getObjectType(LVal.getLValueBase()); | ||||
10065 | return CheckedHandleSizeof(BaseTy, EndOffset); | ||||
10066 | } | ||||
10067 | |||||
10068 | // We want to evaluate the size of a subobject. | ||||
10069 | const SubobjectDesignator &Designator = LVal.Designator; | ||||
10070 | |||||
10071 | // The following is a moderately common idiom in C: | ||||
10072 | // | ||||
10073 | // struct Foo { int a; char c[1]; }; | ||||
10074 | // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); | ||||
10075 | // strcpy(&F->c[0], Bar); | ||||
10076 | // | ||||
10077 | // In order to not break too much legacy code, we need to support it. | ||||
10078 | if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { | ||||
10079 | // If we can resolve this to an alloc_size call, we can hand that back, | ||||
10080 | // because we know for certain how many bytes there are to write to. | ||||
10081 | llvm::APInt APEndOffset; | ||||
10082 | if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && | ||||
10083 | getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) | ||||
10084 | return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); | ||||
10085 | |||||
10086 | // If we cannot determine the size of the initial allocation, then we can't | ||||
10087 | // given an accurate upper-bound. However, we are still able to give | ||||
10088 | // conservative lower-bounds for Type=3. | ||||
10089 | if (Type == 1) | ||||
10090 | return false; | ||||
10091 | } | ||||
10092 | |||||
10093 | CharUnits BytesPerElem; | ||||
10094 | if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) | ||||
10095 | return false; | ||||
10096 | |||||
10097 | // According to the GCC documentation, we want the size of the subobject | ||||
10098 | // denoted by the pointer. But that's not quite right -- what we actually | ||||
10099 | // want is the size of the immediately-enclosing array, if there is one. | ||||
10100 | int64_t ElemsRemaining; | ||||
10101 | if (Designator.MostDerivedIsArrayElement && | ||||
10102 | Designator.Entries.size() == Designator.MostDerivedPathLength) { | ||||
10103 | uint64_t ArraySize = Designator.getMostDerivedArraySize(); | ||||
10104 | uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); | ||||
10105 | ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; | ||||
10106 | } else { | ||||
10107 | ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; | ||||
10108 | } | ||||
10109 | |||||
10110 | EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; | ||||
10111 | return true; | ||||
10112 | } | ||||
10113 | |||||
10114 | /// Tries to evaluate the __builtin_object_size for @p E. If successful, | ||||
10115 | /// returns true and stores the result in @p Size. | ||||
10116 | /// | ||||
10117 | /// If @p WasError is non-null, this will report whether the failure to evaluate | ||||
10118 | /// is to be treated as an Error in IntExprEvaluator. | ||||
10119 | static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, | ||||
10120 | EvalInfo &Info, uint64_t &Size) { | ||||
10121 | // Determine the denoted object. | ||||
10122 | LValue LVal; | ||||
10123 | { | ||||
10124 | // The operand of __builtin_object_size is never evaluated for side-effects. | ||||
10125 | // If there are any, but we can determine the pointed-to object anyway, then | ||||
10126 | // ignore the side-effects. | ||||
10127 | SpeculativeEvaluationRAII SpeculativeEval(Info); | ||||
10128 | IgnoreSideEffectsRAII Fold(Info); | ||||
10129 | |||||
10130 | if (E->isGLValue()) { | ||||
10131 | // It's possible for us to be given GLValues if we're called via | ||||
10132 | // Expr::tryEvaluateObjectSize. | ||||
10133 | APValue RVal; | ||||
10134 | if (!EvaluateAsRValue(Info, E, RVal)) | ||||
10135 | return false; | ||||
10136 | LVal.setFrom(Info.Ctx, RVal); | ||||
10137 | } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, | ||||
10138 | /*InvalidBaseOK=*/true)) | ||||
10139 | return false; | ||||
10140 | } | ||||
10141 | |||||
10142 | // If we point to before the start of the object, there are no accessible | ||||
10143 | // bytes. | ||||
10144 | if (LVal.getLValueOffset().isNegative()) { | ||||
10145 | Size = 0; | ||||
10146 | return true; | ||||
10147 | } | ||||
10148 | |||||
10149 | CharUnits EndOffset; | ||||
10150 | if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) | ||||
10151 | return false; | ||||
10152 | |||||
10153 | // If we've fallen outside of the end offset, just pretend there's nothing to | ||||
10154 | // write to/read from. | ||||
10155 | if (EndOffset <= LVal.getLValueOffset()) | ||||
10156 | Size = 0; | ||||
10157 | else | ||||
10158 | Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); | ||||
10159 | return true; | ||||
10160 | } | ||||
10161 | |||||
10162 | bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { | ||||
10163 | llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); | ||||
10164 | if (E->getResultAPValueKind() != APValue::None) | ||||
10165 | return Success(E->getAPValueResult(), E); | ||||
10166 | return ExprEvaluatorBaseTy::VisitConstantExpr(E); | ||||
10167 | } | ||||
10168 | |||||
10169 | bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
10170 | if (unsigned BuiltinOp = E->getBuiltinCallee()) | ||||
10171 | return VisitBuiltinCallExpr(E, BuiltinOp); | ||||
10172 | |||||
10173 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
10174 | } | ||||
10175 | |||||
10176 | bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, | ||||
10177 | unsigned BuiltinOp) { | ||||
10178 | switch (unsigned BuiltinOp = E->getBuiltinCallee()) { | ||||
10179 | default: | ||||
10180 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
10181 | |||||
10182 | case Builtin::BI__builtin_dynamic_object_size: | ||||
10183 | case Builtin::BI__builtin_object_size: { | ||||
10184 | // The type was checked when we built the expression. | ||||
10185 | unsigned Type = | ||||
10186 | E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||
10187 | assert(Type <= 3 && "unexpected type")((Type <= 3 && "unexpected type") ? static_cast< void> (0) : __assert_fail ("Type <= 3 && \"unexpected type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10187, __PRETTY_FUNCTION__)); | ||||
10188 | |||||
10189 | uint64_t Size; | ||||
10190 | if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) | ||||
10191 | return Success(Size, E); | ||||
10192 | |||||
10193 | if (E->getArg(0)->HasSideEffects(Info.Ctx)) | ||||
10194 | return Success((Type & 2) ? 0 : -1, E); | ||||
10195 | |||||
10196 | // Expression had no side effects, but we couldn't statically determine the | ||||
10197 | // size of the referenced object. | ||||
10198 | switch (Info.EvalMode) { | ||||
10199 | case EvalInfo::EM_ConstantExpression: | ||||
10200 | case EvalInfo::EM_ConstantFold: | ||||
10201 | case EvalInfo::EM_IgnoreSideEffects: | ||||
10202 | // Leave it to IR generation. | ||||
10203 | return Error(E); | ||||
10204 | case EvalInfo::EM_ConstantExpressionUnevaluated: | ||||
10205 | // Reduce it to a constant now. | ||||
10206 | return Success((Type & 2) ? 0 : -1, E); | ||||
10207 | } | ||||
10208 | |||||
10209 | llvm_unreachable("unexpected EvalMode")::llvm::llvm_unreachable_internal("unexpected EvalMode", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10209); | ||||
10210 | } | ||||
10211 | |||||
10212 | case Builtin::BI__builtin_os_log_format_buffer_size: { | ||||
10213 | analyze_os_log::OSLogBufferLayout Layout; | ||||
10214 | analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); | ||||
10215 | return Success(Layout.size().getQuantity(), E); | ||||
10216 | } | ||||
10217 | |||||
10218 | case Builtin::BI__builtin_bswap16: | ||||
10219 | case Builtin::BI__builtin_bswap32: | ||||
10220 | case Builtin::BI__builtin_bswap64: { | ||||
10221 | APSInt Val; | ||||
10222 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10223 | return false; | ||||
10224 | |||||
10225 | return Success(Val.byteSwap(), E); | ||||
10226 | } | ||||
10227 | |||||
10228 | case Builtin::BI__builtin_classify_type: | ||||
10229 | return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); | ||||
10230 | |||||
10231 | case Builtin::BI__builtin_clrsb: | ||||
10232 | case Builtin::BI__builtin_clrsbl: | ||||
10233 | case Builtin::BI__builtin_clrsbll: { | ||||
10234 | APSInt Val; | ||||
10235 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10236 | return false; | ||||
10237 | |||||
10238 | return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); | ||||
10239 | } | ||||
10240 | |||||
10241 | case Builtin::BI__builtin_clz: | ||||
10242 | case Builtin::BI__builtin_clzl: | ||||
10243 | case Builtin::BI__builtin_clzll: | ||||
10244 | case Builtin::BI__builtin_clzs: { | ||||
10245 | APSInt Val; | ||||
10246 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10247 | return false; | ||||
10248 | if (!Val) | ||||
10249 | return Error(E); | ||||
10250 | |||||
10251 | return Success(Val.countLeadingZeros(), E); | ||||
10252 | } | ||||
10253 | |||||
10254 | case Builtin::BI__builtin_constant_p: { | ||||
10255 | const Expr *Arg = E->getArg(0); | ||||
10256 | if (EvaluateBuiltinConstantP(Info, Arg)) | ||||
10257 | return Success(true, E); | ||||
10258 | if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { | ||||
10259 | // Outside a constant context, eagerly evaluate to false in the presence | ||||
10260 | // of side-effects in order to avoid -Wunsequenced false-positives in | ||||
10261 | // a branch on __builtin_constant_p(expr). | ||||
10262 | return Success(false, E); | ||||
10263 | } | ||||
10264 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
10265 | return false; | ||||
10266 | } | ||||
10267 | |||||
10268 | case Builtin::BI__builtin_is_constant_evaluated: | ||||
10269 | return Success(Info.InConstantContext, E); | ||||
10270 | |||||
10271 | case Builtin::BI__builtin_ctz: | ||||
10272 | case Builtin::BI__builtin_ctzl: | ||||
10273 | case Builtin::BI__builtin_ctzll: | ||||
10274 | case Builtin::BI__builtin_ctzs: { | ||||
10275 | APSInt Val; | ||||
10276 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10277 | return false; | ||||
10278 | if (!Val) | ||||
10279 | return Error(E); | ||||
10280 | |||||
10281 | return Success(Val.countTrailingZeros(), E); | ||||
10282 | } | ||||
10283 | |||||
10284 | case Builtin::BI__builtin_eh_return_data_regno: { | ||||
10285 | int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); | ||||
10286 | Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); | ||||
10287 | return Success(Operand, E); | ||||
10288 | } | ||||
10289 | |||||
10290 | case Builtin::BI__builtin_expect: | ||||
10291 | return Visit(E->getArg(0)); | ||||
10292 | |||||
10293 | case Builtin::BI__builtin_ffs: | ||||
10294 | case Builtin::BI__builtin_ffsl: | ||||
10295 | case Builtin::BI__builtin_ffsll: { | ||||
10296 | APSInt Val; | ||||
10297 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10298 | return false; | ||||
10299 | |||||
10300 | unsigned N = Val.countTrailingZeros(); | ||||
10301 | return Success(N == Val.getBitWidth() ? 0 : N + 1, E); | ||||
10302 | } | ||||
10303 | |||||
10304 | case Builtin::BI__builtin_fpclassify: { | ||||
10305 | APFloat Val(0.0); | ||||
10306 | if (!EvaluateFloat(E->getArg(5), Val, Info)) | ||||
10307 | return false; | ||||
10308 | unsigned Arg; | ||||
10309 | switch (Val.getCategory()) { | ||||
10310 | case APFloat::fcNaN: Arg = 0; break; | ||||
10311 | case APFloat::fcInfinity: Arg = 1; break; | ||||
10312 | case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; | ||||
10313 | case APFloat::fcZero: Arg = 4; break; | ||||
10314 | } | ||||
10315 | return Visit(E->getArg(Arg)); | ||||
10316 | } | ||||
10317 | |||||
10318 | case Builtin::BI__builtin_isinf_sign: { | ||||
10319 | APFloat Val(0.0); | ||||
10320 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
10321 | Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); | ||||
10322 | } | ||||
10323 | |||||
10324 | case Builtin::BI__builtin_isinf: { | ||||
10325 | APFloat Val(0.0); | ||||
10326 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
10327 | Success(Val.isInfinity() ? 1 : 0, E); | ||||
10328 | } | ||||
10329 | |||||
10330 | case Builtin::BI__builtin_isfinite: { | ||||
10331 | APFloat Val(0.0); | ||||
10332 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
10333 | Success(Val.isFinite() ? 1 : 0, E); | ||||
10334 | } | ||||
10335 | |||||
10336 | case Builtin::BI__builtin_isnan: { | ||||
10337 | APFloat Val(0.0); | ||||
10338 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
10339 | Success(Val.isNaN() ? 1 : 0, E); | ||||
10340 | } | ||||
10341 | |||||
10342 | case Builtin::BI__builtin_isnormal: { | ||||
10343 | APFloat Val(0.0); | ||||
10344 | return EvaluateFloat(E->getArg(0), Val, Info) && | ||||
10345 | Success(Val.isNormal() ? 1 : 0, E); | ||||
10346 | } | ||||
10347 | |||||
10348 | case Builtin::BI__builtin_parity: | ||||
10349 | case Builtin::BI__builtin_parityl: | ||||
10350 | case Builtin::BI__builtin_parityll: { | ||||
10351 | APSInt Val; | ||||
10352 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10353 | return false; | ||||
10354 | |||||
10355 | return Success(Val.countPopulation() % 2, E); | ||||
10356 | } | ||||
10357 | |||||
10358 | case Builtin::BI__builtin_popcount: | ||||
10359 | case Builtin::BI__builtin_popcountl: | ||||
10360 | case Builtin::BI__builtin_popcountll: { | ||||
10361 | APSInt Val; | ||||
10362 | if (!EvaluateInteger(E->getArg(0), Val, Info)) | ||||
10363 | return false; | ||||
10364 | |||||
10365 | return Success(Val.countPopulation(), E); | ||||
10366 | } | ||||
10367 | |||||
10368 | case Builtin::BIstrlen: | ||||
10369 | case Builtin::BIwcslen: | ||||
10370 | // A call to strlen is not a constant expression. | ||||
10371 | if (Info.getLangOpts().CPlusPlus11) | ||||
10372 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
10373 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
10374 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
10375 | else | ||||
10376 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
10377 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
10378 | case Builtin::BI__builtin_strlen: | ||||
10379 | case Builtin::BI__builtin_wcslen: { | ||||
10380 | // As an extension, we support __builtin_strlen() as a constant expression, | ||||
10381 | // and support folding strlen() to a constant. | ||||
10382 | LValue String; | ||||
10383 | if (!EvaluatePointer(E->getArg(0), String, Info)) | ||||
10384 | return false; | ||||
10385 | |||||
10386 | QualType CharTy = E->getArg(0)->getType()->getPointeeType(); | ||||
10387 | |||||
10388 | // Fast path: if it's a string literal, search the string value. | ||||
10389 | if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( | ||||
10390 | String.getLValueBase().dyn_cast<const Expr *>())) { | ||||
10391 | // The string literal may have embedded null characters. Find the first | ||||
10392 | // one and truncate there. | ||||
10393 | StringRef Str = S->getBytes(); | ||||
10394 | int64_t Off = String.Offset.getQuantity(); | ||||
10395 | if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && | ||||
10396 | S->getCharByteWidth() == 1 && | ||||
10397 | // FIXME: Add fast-path for wchar_t too. | ||||
10398 | Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { | ||||
10399 | Str = Str.substr(Off); | ||||
10400 | |||||
10401 | StringRef::size_type Pos = Str.find(0); | ||||
10402 | if (Pos != StringRef::npos) | ||||
10403 | Str = Str.substr(0, Pos); | ||||
10404 | |||||
10405 | return Success(Str.size(), E); | ||||
10406 | } | ||||
10407 | |||||
10408 | // Fall through to slow path to issue appropriate diagnostic. | ||||
10409 | } | ||||
10410 | |||||
10411 | // Slow path: scan the bytes of the string looking for the terminating 0. | ||||
10412 | for (uint64_t Strlen = 0; /**/; ++Strlen) { | ||||
10413 | APValue Char; | ||||
10414 | if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || | ||||
10415 | !Char.isInt()) | ||||
10416 | return false; | ||||
10417 | if (!Char.getInt()) | ||||
10418 | return Success(Strlen, E); | ||||
10419 | if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) | ||||
10420 | return false; | ||||
10421 | } | ||||
10422 | } | ||||
10423 | |||||
10424 | case Builtin::BIstrcmp: | ||||
10425 | case Builtin::BIwcscmp: | ||||
10426 | case Builtin::BIstrncmp: | ||||
10427 | case Builtin::BIwcsncmp: | ||||
10428 | case Builtin::BImemcmp: | ||||
10429 | case Builtin::BIbcmp: | ||||
10430 | case Builtin::BIwmemcmp: | ||||
10431 | // A call to strlen is not a constant expression. | ||||
10432 | if (Info.getLangOpts().CPlusPlus11) | ||||
10433 | Info.CCEDiag(E, diag::note_constexpr_invalid_function) | ||||
10434 | << /*isConstexpr*/0 << /*isConstructor*/0 | ||||
10435 | << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); | ||||
10436 | else | ||||
10437 | Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
10438 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
10439 | case Builtin::BI__builtin_strcmp: | ||||
10440 | case Builtin::BI__builtin_wcscmp: | ||||
10441 | case Builtin::BI__builtin_strncmp: | ||||
10442 | case Builtin::BI__builtin_wcsncmp: | ||||
10443 | case Builtin::BI__builtin_memcmp: | ||||
10444 | case Builtin::BI__builtin_bcmp: | ||||
10445 | case Builtin::BI__builtin_wmemcmp: { | ||||
10446 | LValue String1, String2; | ||||
10447 | if (!EvaluatePointer(E->getArg(0), String1, Info) || | ||||
10448 | !EvaluatePointer(E->getArg(1), String2, Info)) | ||||
10449 | return false; | ||||
10450 | |||||
10451 | uint64_t MaxLength = uint64_t(-1); | ||||
10452 | if (BuiltinOp != Builtin::BIstrcmp && | ||||
10453 | BuiltinOp != Builtin::BIwcscmp && | ||||
10454 | BuiltinOp != Builtin::BI__builtin_strcmp && | ||||
10455 | BuiltinOp != Builtin::BI__builtin_wcscmp) { | ||||
10456 | APSInt N; | ||||
10457 | if (!EvaluateInteger(E->getArg(2), N, Info)) | ||||
10458 | return false; | ||||
10459 | MaxLength = N.getExtValue(); | ||||
10460 | } | ||||
10461 | |||||
10462 | // Empty substrings compare equal by definition. | ||||
10463 | if (MaxLength == 0u) | ||||
10464 | return Success(0, E); | ||||
10465 | |||||
10466 | if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
10467 | !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || | ||||
10468 | String1.Designator.Invalid || String2.Designator.Invalid) | ||||
10469 | return false; | ||||
10470 | |||||
10471 | QualType CharTy1 = String1.Designator.getType(Info.Ctx); | ||||
10472 | QualType CharTy2 = String2.Designator.getType(Info.Ctx); | ||||
10473 | |||||
10474 | bool IsRawByte = BuiltinOp == Builtin::BImemcmp || | ||||
10475 | BuiltinOp == Builtin::BIbcmp || | ||||
10476 | BuiltinOp == Builtin::BI__builtin_memcmp || | ||||
10477 | BuiltinOp == Builtin::BI__builtin_bcmp; | ||||
10478 | |||||
10479 | assert(IsRawByte ||((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||
10480 | (Info.Ctx.hasSameUnqualifiedType(((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||
10481 | CharTy1, E->getArg(0)->getType()->getPointeeType()) &&((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)) | ||||
10482 | Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)))((IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E-> getArg(0)->getType()->getPointeeType()) && Info .Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))) ? static_cast <void> (0) : __assert_fail ("IsRawByte || (Info.Ctx.hasSameUnqualifiedType( CharTy1, E->getArg(0)->getType()->getPointeeType()) && Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10482, __PRETTY_FUNCTION__)); | ||||
10483 | |||||
10484 | const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { | ||||
10485 | return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && | ||||
10486 | handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && | ||||
10487 | Char1.isInt() && Char2.isInt(); | ||||
10488 | }; | ||||
10489 | const auto &AdvanceElems = [&] { | ||||
10490 | return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && | ||||
10491 | HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); | ||||
10492 | }; | ||||
10493 | |||||
10494 | if (IsRawByte) { | ||||
10495 | uint64_t BytesRemaining = MaxLength; | ||||
10496 | // Pointers to const void may point to objects of incomplete type. | ||||
10497 | if (CharTy1->isIncompleteType()) { | ||||
10498 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; | ||||
10499 | return false; | ||||
10500 | } | ||||
10501 | if (CharTy2->isIncompleteType()) { | ||||
10502 | Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; | ||||
10503 | return false; | ||||
10504 | } | ||||
10505 | uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; | ||||
10506 | CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); | ||||
10507 | // Give up on comparing between elements with disparate widths. | ||||
10508 | if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) | ||||
10509 | return false; | ||||
10510 | uint64_t BytesPerElement = CharTy1Size.getQuantity(); | ||||
10511 | assert(BytesRemaining && "BytesRemaining should not be zero: the "((BytesRemaining && "BytesRemaining should not be zero: the " "following loop considers at least one element") ? static_cast <void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10512, __PRETTY_FUNCTION__)) | ||||
10512 | "following loop considers at least one element")((BytesRemaining && "BytesRemaining should not be zero: the " "following loop considers at least one element") ? static_cast <void> (0) : __assert_fail ("BytesRemaining && \"BytesRemaining should not be zero: the \" \"following loop considers at least one element\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10512, __PRETTY_FUNCTION__)); | ||||
10513 | while (true) { | ||||
10514 | APValue Char1, Char2; | ||||
10515 | if (!ReadCurElems(Char1, Char2)) | ||||
10516 | return false; | ||||
10517 | // We have compatible in-memory widths, but a possible type and | ||||
10518 | // (for `bool`) internal representation mismatch. | ||||
10519 | // Assuming two's complement representation, including 0 for `false` and | ||||
10520 | // 1 for `true`, we can check an appropriate number of elements for | ||||
10521 | // equality even if they are not byte-sized. | ||||
10522 | APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); | ||||
10523 | APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); | ||||
10524 | if (Char1InMem.ne(Char2InMem)) { | ||||
10525 | // If the elements are byte-sized, then we can produce a three-way | ||||
10526 | // comparison result in a straightforward manner. | ||||
10527 | if (BytesPerElement == 1u) { | ||||
10528 | // memcmp always compares unsigned chars. | ||||
10529 | return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); | ||||
10530 | } | ||||
10531 | // The result is byte-order sensitive, and we have multibyte elements. | ||||
10532 | // FIXME: We can compare the remaining bytes in the correct order. | ||||
10533 | return false; | ||||
10534 | } | ||||
10535 | if (!AdvanceElems()) | ||||
10536 | return false; | ||||
10537 | if (BytesRemaining <= BytesPerElement) | ||||
10538 | break; | ||||
10539 | BytesRemaining -= BytesPerElement; | ||||
10540 | } | ||||
10541 | // Enough elements are equal to account for the memcmp limit. | ||||
10542 | return Success(0, E); | ||||
10543 | } | ||||
10544 | |||||
10545 | bool StopAtNull = | ||||
10546 | (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && | ||||
10547 | BuiltinOp != Builtin::BIwmemcmp && | ||||
10548 | BuiltinOp != Builtin::BI__builtin_memcmp && | ||||
10549 | BuiltinOp != Builtin::BI__builtin_bcmp && | ||||
10550 | BuiltinOp != Builtin::BI__builtin_wmemcmp); | ||||
10551 | bool IsWide = BuiltinOp == Builtin::BIwcscmp || | ||||
10552 | BuiltinOp == Builtin::BIwcsncmp || | ||||
10553 | BuiltinOp == Builtin::BIwmemcmp || | ||||
10554 | BuiltinOp == Builtin::BI__builtin_wcscmp || | ||||
10555 | BuiltinOp == Builtin::BI__builtin_wcsncmp || | ||||
10556 | BuiltinOp == Builtin::BI__builtin_wmemcmp; | ||||
10557 | |||||
10558 | for (; MaxLength; --MaxLength) { | ||||
10559 | APValue Char1, Char2; | ||||
10560 | if (!ReadCurElems(Char1, Char2)) | ||||
10561 | return false; | ||||
10562 | if (Char1.getInt() != Char2.getInt()) { | ||||
10563 | if (IsWide) // wmemcmp compares with wchar_t signedness. | ||||
10564 | return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); | ||||
10565 | // memcmp always compares unsigned chars. | ||||
10566 | return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); | ||||
10567 | } | ||||
10568 | if (StopAtNull && !Char1.getInt()) | ||||
10569 | return Success(0, E); | ||||
10570 | assert(!(StopAtNull && !Char2.getInt()))((!(StopAtNull && !Char2.getInt())) ? static_cast< void> (0) : __assert_fail ("!(StopAtNull && !Char2.getInt())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10570, __PRETTY_FUNCTION__)); | ||||
10571 | if (!AdvanceElems()) | ||||
10572 | return false; | ||||
10573 | } | ||||
10574 | // We hit the strncmp / memcmp limit. | ||||
10575 | return Success(0, E); | ||||
10576 | } | ||||
10577 | |||||
10578 | case Builtin::BI__atomic_always_lock_free: | ||||
10579 | case Builtin::BI__atomic_is_lock_free: | ||||
10580 | case Builtin::BI__c11_atomic_is_lock_free: { | ||||
10581 | APSInt SizeVal; | ||||
10582 | if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) | ||||
10583 | return false; | ||||
10584 | |||||
10585 | // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power | ||||
10586 | // of two less than the maximum inline atomic width, we know it is | ||||
10587 | // lock-free. If the size isn't a power of two, or greater than the | ||||
10588 | // maximum alignment where we promote atomics, we know it is not lock-free | ||||
10589 | // (at least not in the sense of atomic_is_lock_free). Otherwise, | ||||
10590 | // the answer can only be determined at runtime; for example, 16-byte | ||||
10591 | // atomics have lock-free implementations on some, but not all, | ||||
10592 | // x86-64 processors. | ||||
10593 | |||||
10594 | // Check power-of-two. | ||||
10595 | CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); | ||||
10596 | if (Size.isPowerOfTwo()) { | ||||
10597 | // Check against inlining width. | ||||
10598 | unsigned InlineWidthBits = | ||||
10599 | Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); | ||||
10600 | if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { | ||||
10601 | if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || | ||||
10602 | Size == CharUnits::One() || | ||||
10603 | E->getArg(1)->isNullPointerConstant(Info.Ctx, | ||||
10604 | Expr::NPC_NeverValueDependent)) | ||||
10605 | // OK, we will inline appropriately-aligned operations of this size, | ||||
10606 | // and _Atomic(T) is appropriately-aligned. | ||||
10607 | return Success(1, E); | ||||
10608 | |||||
10609 | QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> | ||||
10610 | castAs<PointerType>()->getPointeeType(); | ||||
10611 | if (!PointeeType->isIncompleteType() && | ||||
10612 | Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { | ||||
10613 | // OK, we will inline operations on this object. | ||||
10614 | return Success(1, E); | ||||
10615 | } | ||||
10616 | } | ||||
10617 | } | ||||
10618 | |||||
10619 | return BuiltinOp == Builtin::BI__atomic_always_lock_free ? | ||||
10620 | Success(0, E) : Error(E); | ||||
10621 | } | ||||
10622 | case Builtin::BIomp_is_initial_device: | ||||
10623 | // We can decide statically which value the runtime would return if called. | ||||
10624 | return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); | ||||
10625 | case Builtin::BI__builtin_add_overflow: | ||||
10626 | case Builtin::BI__builtin_sub_overflow: | ||||
10627 | case Builtin::BI__builtin_mul_overflow: | ||||
10628 | case Builtin::BI__builtin_sadd_overflow: | ||||
10629 | case Builtin::BI__builtin_uadd_overflow: | ||||
10630 | case Builtin::BI__builtin_uaddl_overflow: | ||||
10631 | case Builtin::BI__builtin_uaddll_overflow: | ||||
10632 | case Builtin::BI__builtin_usub_overflow: | ||||
10633 | case Builtin::BI__builtin_usubl_overflow: | ||||
10634 | case Builtin::BI__builtin_usubll_overflow: | ||||
10635 | case Builtin::BI__builtin_umul_overflow: | ||||
10636 | case Builtin::BI__builtin_umull_overflow: | ||||
10637 | case Builtin::BI__builtin_umulll_overflow: | ||||
10638 | case Builtin::BI__builtin_saddl_overflow: | ||||
10639 | case Builtin::BI__builtin_saddll_overflow: | ||||
10640 | case Builtin::BI__builtin_ssub_overflow: | ||||
10641 | case Builtin::BI__builtin_ssubl_overflow: | ||||
10642 | case Builtin::BI__builtin_ssubll_overflow: | ||||
10643 | case Builtin::BI__builtin_smul_overflow: | ||||
10644 | case Builtin::BI__builtin_smull_overflow: | ||||
10645 | case Builtin::BI__builtin_smulll_overflow: { | ||||
10646 | LValue ResultLValue; | ||||
10647 | APSInt LHS, RHS; | ||||
10648 | |||||
10649 | QualType ResultType = E->getArg(2)->getType()->getPointeeType(); | ||||
10650 | if (!EvaluateInteger(E->getArg(0), LHS, Info) || | ||||
10651 | !EvaluateInteger(E->getArg(1), RHS, Info) || | ||||
10652 | !EvaluatePointer(E->getArg(2), ResultLValue, Info)) | ||||
10653 | return false; | ||||
10654 | |||||
10655 | APSInt Result; | ||||
10656 | bool DidOverflow = false; | ||||
10657 | |||||
10658 | // If the types don't have to match, enlarge all 3 to the largest of them. | ||||
10659 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||
10660 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||
10661 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||
10662 | bool IsSigned = LHS.isSigned() || RHS.isSigned() || | ||||
10663 | ResultType->isSignedIntegerOrEnumerationType(); | ||||
10664 | bool AllSigned = LHS.isSigned() && RHS.isSigned() && | ||||
10665 | ResultType->isSignedIntegerOrEnumerationType(); | ||||
10666 | uint64_t LHSSize = LHS.getBitWidth(); | ||||
10667 | uint64_t RHSSize = RHS.getBitWidth(); | ||||
10668 | uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); | ||||
10669 | uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); | ||||
10670 | |||||
10671 | // Add an additional bit if the signedness isn't uniformly agreed to. We | ||||
10672 | // could do this ONLY if there is a signed and an unsigned that both have | ||||
10673 | // MaxBits, but the code to check that is pretty nasty. The issue will be | ||||
10674 | // caught in the shrink-to-result later anyway. | ||||
10675 | if (IsSigned && !AllSigned) | ||||
10676 | ++MaxBits; | ||||
10677 | |||||
10678 | LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); | ||||
10679 | RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); | ||||
10680 | Result = APSInt(MaxBits, !IsSigned); | ||||
10681 | } | ||||
10682 | |||||
10683 | // Find largest int. | ||||
10684 | switch (BuiltinOp) { | ||||
10685 | default: | ||||
10686 | llvm_unreachable("Invalid value for BuiltinOp")::llvm::llvm_unreachable_internal("Invalid value for BuiltinOp" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10686); | ||||
10687 | case Builtin::BI__builtin_add_overflow: | ||||
10688 | case Builtin::BI__builtin_sadd_overflow: | ||||
10689 | case Builtin::BI__builtin_saddl_overflow: | ||||
10690 | case Builtin::BI__builtin_saddll_overflow: | ||||
10691 | case Builtin::BI__builtin_uadd_overflow: | ||||
10692 | case Builtin::BI__builtin_uaddl_overflow: | ||||
10693 | case Builtin::BI__builtin_uaddll_overflow: | ||||
10694 | Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) | ||||
10695 | : LHS.uadd_ov(RHS, DidOverflow); | ||||
10696 | break; | ||||
10697 | case Builtin::BI__builtin_sub_overflow: | ||||
10698 | case Builtin::BI__builtin_ssub_overflow: | ||||
10699 | case Builtin::BI__builtin_ssubl_overflow: | ||||
10700 | case Builtin::BI__builtin_ssubll_overflow: | ||||
10701 | case Builtin::BI__builtin_usub_overflow: | ||||
10702 | case Builtin::BI__builtin_usubl_overflow: | ||||
10703 | case Builtin::BI__builtin_usubll_overflow: | ||||
10704 | Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) | ||||
10705 | : LHS.usub_ov(RHS, DidOverflow); | ||||
10706 | break; | ||||
10707 | case Builtin::BI__builtin_mul_overflow: | ||||
10708 | case Builtin::BI__builtin_smul_overflow: | ||||
10709 | case Builtin::BI__builtin_smull_overflow: | ||||
10710 | case Builtin::BI__builtin_smulll_overflow: | ||||
10711 | case Builtin::BI__builtin_umul_overflow: | ||||
10712 | case Builtin::BI__builtin_umull_overflow: | ||||
10713 | case Builtin::BI__builtin_umulll_overflow: | ||||
10714 | Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) | ||||
10715 | : LHS.umul_ov(RHS, DidOverflow); | ||||
10716 | break; | ||||
10717 | } | ||||
10718 | |||||
10719 | // In the case where multiple sizes are allowed, truncate and see if | ||||
10720 | // the values are the same. | ||||
10721 | if (BuiltinOp == Builtin::BI__builtin_add_overflow || | ||||
10722 | BuiltinOp == Builtin::BI__builtin_sub_overflow || | ||||
10723 | BuiltinOp == Builtin::BI__builtin_mul_overflow) { | ||||
10724 | // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, | ||||
10725 | // since it will give us the behavior of a TruncOrSelf in the case where | ||||
10726 | // its parameter <= its size. We previously set Result to be at least the | ||||
10727 | // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth | ||||
10728 | // will work exactly like TruncOrSelf. | ||||
10729 | APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); | ||||
10730 | Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); | ||||
10731 | |||||
10732 | if (!APSInt::isSameValue(Temp, Result)) | ||||
10733 | DidOverflow = true; | ||||
10734 | Result = Temp; | ||||
10735 | } | ||||
10736 | |||||
10737 | APValue APV{Result}; | ||||
10738 | if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) | ||||
10739 | return false; | ||||
10740 | return Success(DidOverflow, E); | ||||
10741 | } | ||||
10742 | } | ||||
10743 | } | ||||
10744 | |||||
10745 | /// Determine whether this is a pointer past the end of the complete | ||||
10746 | /// object referred to by the lvalue. | ||||
10747 | static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, | ||||
10748 | const LValue &LV) { | ||||
10749 | // A null pointer can be viewed as being "past the end" but we don't | ||||
10750 | // choose to look at it that way here. | ||||
10751 | if (!LV.getLValueBase()) | ||||
10752 | return false; | ||||
10753 | |||||
10754 | // If the designator is valid and refers to a subobject, we're not pointing | ||||
10755 | // past the end. | ||||
10756 | if (!LV.getLValueDesignator().Invalid && | ||||
10757 | !LV.getLValueDesignator().isOnePastTheEnd()) | ||||
10758 | return false; | ||||
10759 | |||||
10760 | // A pointer to an incomplete type might be past-the-end if the type's size is | ||||
10761 | // zero. We cannot tell because the type is incomplete. | ||||
10762 | QualType Ty = getType(LV.getLValueBase()); | ||||
10763 | if (Ty->isIncompleteType()) | ||||
10764 | return true; | ||||
10765 | |||||
10766 | // We're a past-the-end pointer if we point to the byte after the object, | ||||
10767 | // no matter what our type or path is. | ||||
10768 | auto Size = Ctx.getTypeSizeInChars(Ty); | ||||
10769 | return LV.getLValueOffset() == Size; | ||||
10770 | } | ||||
10771 | |||||
10772 | namespace { | ||||
10773 | |||||
10774 | /// Data recursive integer evaluator of certain binary operators. | ||||
10775 | /// | ||||
10776 | /// We use a data recursive algorithm for binary operators so that we are able | ||||
10777 | /// to handle extreme cases of chained binary operators without causing stack | ||||
10778 | /// overflow. | ||||
10779 | class DataRecursiveIntBinOpEvaluator { | ||||
10780 | struct EvalResult { | ||||
10781 | APValue Val; | ||||
10782 | bool Failed; | ||||
10783 | |||||
10784 | EvalResult() : Failed(false) { } | ||||
10785 | |||||
10786 | void swap(EvalResult &RHS) { | ||||
10787 | Val.swap(RHS.Val); | ||||
10788 | Failed = RHS.Failed; | ||||
10789 | RHS.Failed = false; | ||||
10790 | } | ||||
10791 | }; | ||||
10792 | |||||
10793 | struct Job { | ||||
10794 | const Expr *E; | ||||
10795 | EvalResult LHSResult; // meaningful only for binary operator expression. | ||||
10796 | enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; | ||||
10797 | |||||
10798 | Job() = default; | ||||
10799 | Job(Job &&) = default; | ||||
10800 | |||||
10801 | void startSpeculativeEval(EvalInfo &Info) { | ||||
10802 | SpecEvalRAII = SpeculativeEvaluationRAII(Info); | ||||
10803 | } | ||||
10804 | |||||
10805 | private: | ||||
10806 | SpeculativeEvaluationRAII SpecEvalRAII; | ||||
10807 | }; | ||||
10808 | |||||
10809 | SmallVector<Job, 16> Queue; | ||||
10810 | |||||
10811 | IntExprEvaluator &IntEval; | ||||
10812 | EvalInfo &Info; | ||||
10813 | APValue &FinalResult; | ||||
10814 | |||||
10815 | public: | ||||
10816 | DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) | ||||
10817 | : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } | ||||
10818 | |||||
10819 | /// True if \param E is a binary operator that we are going to handle | ||||
10820 | /// data recursively. | ||||
10821 | /// We handle binary operators that are comma, logical, or that have operands | ||||
10822 | /// with integral or enumeration type. | ||||
10823 | static bool shouldEnqueue(const BinaryOperator *E) { | ||||
10824 | return E->getOpcode() == BO_Comma || E->isLogicalOp() || | ||||
10825 | (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && | ||||
10826 | E->getLHS()->getType()->isIntegralOrEnumerationType() && | ||||
10827 | E->getRHS()->getType()->isIntegralOrEnumerationType()); | ||||
10828 | } | ||||
10829 | |||||
10830 | bool Traverse(const BinaryOperator *E) { | ||||
10831 | enqueue(E); | ||||
10832 | EvalResult PrevResult; | ||||
10833 | while (!Queue.empty()) | ||||
10834 | process(PrevResult); | ||||
10835 | |||||
10836 | if (PrevResult.Failed) return false; | ||||
10837 | |||||
10838 | FinalResult.swap(PrevResult.Val); | ||||
10839 | return true; | ||||
10840 | } | ||||
10841 | |||||
10842 | private: | ||||
10843 | bool Success(uint64_t Value, const Expr *E, APValue &Result) { | ||||
10844 | return IntEval.Success(Value, E, Result); | ||||
10845 | } | ||||
10846 | bool Success(const APSInt &Value, const Expr *E, APValue &Result) { | ||||
10847 | return IntEval.Success(Value, E, Result); | ||||
10848 | } | ||||
10849 | bool Error(const Expr *E) { | ||||
10850 | return IntEval.Error(E); | ||||
10851 | } | ||||
10852 | bool Error(const Expr *E, diag::kind D) { | ||||
10853 | return IntEval.Error(E, D); | ||||
10854 | } | ||||
10855 | |||||
10856 | OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { | ||||
10857 | return Info.CCEDiag(E, D); | ||||
10858 | } | ||||
10859 | |||||
10860 | // Returns true if visiting the RHS is necessary, false otherwise. | ||||
10861 | bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||
10862 | bool &SuppressRHSDiags); | ||||
10863 | |||||
10864 | bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||
10865 | const BinaryOperator *E, APValue &Result); | ||||
10866 | |||||
10867 | void EvaluateExpr(const Expr *E, EvalResult &Result) { | ||||
10868 | Result.Failed = !Evaluate(Result.Val, Info, E); | ||||
10869 | if (Result.Failed) | ||||
10870 | Result.Val = APValue(); | ||||
10871 | } | ||||
10872 | |||||
10873 | void process(EvalResult &Result); | ||||
10874 | |||||
10875 | void enqueue(const Expr *E) { | ||||
10876 | E = E->IgnoreParens(); | ||||
10877 | Queue.resize(Queue.size()+1); | ||||
10878 | Queue.back().E = E; | ||||
10879 | Queue.back().Kind = Job::AnyExprKind; | ||||
10880 | } | ||||
10881 | }; | ||||
10882 | |||||
10883 | } | ||||
10884 | |||||
10885 | bool DataRecursiveIntBinOpEvaluator:: | ||||
10886 | VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, | ||||
10887 | bool &SuppressRHSDiags) { | ||||
10888 | if (E->getOpcode() == BO_Comma) { | ||||
10889 | // Ignore LHS but note if we could not evaluate it. | ||||
10890 | if (LHSResult.Failed) | ||||
10891 | return Info.noteSideEffect(); | ||||
10892 | return true; | ||||
10893 | } | ||||
10894 | |||||
10895 | if (E->isLogicalOp()) { | ||||
10896 | bool LHSAsBool; | ||||
10897 | if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { | ||||
10898 | // We were able to evaluate the LHS, see if we can get away with not | ||||
10899 | // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 | ||||
10900 | if (LHSAsBool == (E->getOpcode() == BO_LOr)) { | ||||
10901 | Success(LHSAsBool, E, LHSResult.Val); | ||||
10902 | return false; // Ignore RHS | ||||
10903 | } | ||||
10904 | } else { | ||||
10905 | LHSResult.Failed = true; | ||||
10906 | |||||
10907 | // Since we weren't able to evaluate the left hand side, it | ||||
10908 | // might have had side effects. | ||||
10909 | if (!Info.noteSideEffect()) | ||||
10910 | return false; | ||||
10911 | |||||
10912 | // We can't evaluate the LHS; however, sometimes the result | ||||
10913 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||
10914 | // Don't ignore RHS and suppress diagnostics from this arm. | ||||
10915 | SuppressRHSDiags = true; | ||||
10916 | } | ||||
10917 | |||||
10918 | return true; | ||||
10919 | } | ||||
10920 | |||||
10921 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10922, __PRETTY_FUNCTION__)) | ||||
10922 | E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10922, __PRETTY_FUNCTION__)); | ||||
10923 | |||||
10924 | if (LHSResult.Failed && !Info.noteFailure()) | ||||
10925 | return false; // Ignore RHS; | ||||
10926 | |||||
10927 | return true; | ||||
10928 | } | ||||
10929 | |||||
10930 | static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, | ||||
10931 | bool IsSub) { | ||||
10932 | // Compute the new offset in the appropriate width, wrapping at 64 bits. | ||||
10933 | // FIXME: When compiling for a 32-bit target, we should use 32-bit | ||||
10934 | // offsets. | ||||
10935 | assert(!LVal.hasLValuePath() && "have designator for integer lvalue")((!LVal.hasLValuePath() && "have designator for integer lvalue" ) ? static_cast<void> (0) : __assert_fail ("!LVal.hasLValuePath() && \"have designator for integer lvalue\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10935, __PRETTY_FUNCTION__)); | ||||
10936 | CharUnits &Offset = LVal.getLValueOffset(); | ||||
10937 | uint64_t Offset64 = Offset.getQuantity(); | ||||
10938 | uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); | ||||
10939 | Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 | ||||
10940 | : Offset64 + Index64); | ||||
10941 | } | ||||
10942 | |||||
10943 | bool DataRecursiveIntBinOpEvaluator:: | ||||
10944 | VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, | ||||
10945 | const BinaryOperator *E, APValue &Result) { | ||||
10946 | if (E->getOpcode() == BO_Comma) { | ||||
10947 | if (RHSResult.Failed) | ||||
10948 | return false; | ||||
10949 | Result = RHSResult.Val; | ||||
10950 | return true; | ||||
10951 | } | ||||
10952 | |||||
10953 | if (E->isLogicalOp()) { | ||||
10954 | bool lhsResult, rhsResult; | ||||
10955 | bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); | ||||
10956 | bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); | ||||
10957 | |||||
10958 | if (LHSIsOK) { | ||||
10959 | if (RHSIsOK) { | ||||
10960 | if (E->getOpcode() == BO_LOr) | ||||
10961 | return Success(lhsResult || rhsResult, E, Result); | ||||
10962 | else | ||||
10963 | return Success(lhsResult && rhsResult, E, Result); | ||||
10964 | } | ||||
10965 | } else { | ||||
10966 | if (RHSIsOK) { | ||||
10967 | // We can't evaluate the LHS; however, sometimes the result | ||||
10968 | // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. | ||||
10969 | if (rhsResult == (E->getOpcode() == BO_LOr)) | ||||
10970 | return Success(rhsResult, E, Result); | ||||
10971 | } | ||||
10972 | } | ||||
10973 | |||||
10974 | return false; | ||||
10975 | } | ||||
10976 | |||||
10977 | assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10978, __PRETTY_FUNCTION__)) | ||||
10978 | E->getRHS()->getType()->isIntegralOrEnumerationType())((E->getLHS()->getType()->isIntegralOrEnumerationType () && E->getRHS()->getType()->isIntegralOrEnumerationType ()) ? static_cast<void> (0) : __assert_fail ("E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 10978, __PRETTY_FUNCTION__)); | ||||
10979 | |||||
10980 | if (LHSResult.Failed || RHSResult.Failed) | ||||
10981 | return false; | ||||
10982 | |||||
10983 | const APValue &LHSVal = LHSResult.Val; | ||||
10984 | const APValue &RHSVal = RHSResult.Val; | ||||
10985 | |||||
10986 | // Handle cases like (unsigned long)&a + 4. | ||||
10987 | if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { | ||||
10988 | Result = LHSVal; | ||||
10989 | addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); | ||||
10990 | return true; | ||||
10991 | } | ||||
10992 | |||||
10993 | // Handle cases like 4 + (unsigned long)&a | ||||
10994 | if (E->getOpcode() == BO_Add && | ||||
10995 | RHSVal.isLValue() && LHSVal.isInt()) { | ||||
10996 | Result = RHSVal; | ||||
10997 | addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); | ||||
10998 | return true; | ||||
10999 | } | ||||
11000 | |||||
11001 | if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { | ||||
11002 | // Handle (intptr_t)&&A - (intptr_t)&&B. | ||||
11003 | if (!LHSVal.getLValueOffset().isZero() || | ||||
11004 | !RHSVal.getLValueOffset().isZero()) | ||||
11005 | return false; | ||||
11006 | const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||
11007 | const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); | ||||
11008 | if (!LHSExpr || !RHSExpr) | ||||
11009 | return false; | ||||
11010 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||
11011 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||
11012 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||
11013 | return false; | ||||
11014 | // Make sure both labels come from the same function. | ||||
11015 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||
11016 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||
11017 | return false; | ||||
11018 | Result = APValue(LHSAddrExpr, RHSAddrExpr); | ||||
11019 | return true; | ||||
11020 | } | ||||
11021 | |||||
11022 | // All the remaining cases expect both operands to be an integer | ||||
11023 | if (!LHSVal.isInt() || !RHSVal.isInt()) | ||||
11024 | return Error(E); | ||||
11025 | |||||
11026 | // Set up the width and signedness manually, in case it can't be deduced | ||||
11027 | // from the operation we're performing. | ||||
11028 | // FIXME: Don't do this in the cases where we can deduce it. | ||||
11029 | APSInt Value(Info.Ctx.getIntWidth(E->getType()), | ||||
11030 | E->getType()->isUnsignedIntegerOrEnumerationType()); | ||||
11031 | if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), | ||||
11032 | RHSVal.getInt(), Value)) | ||||
11033 | return false; | ||||
11034 | return Success(Value, E, Result); | ||||
11035 | } | ||||
11036 | |||||
11037 | void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { | ||||
11038 | Job &job = Queue.back(); | ||||
11039 | |||||
11040 | switch (job.Kind) { | ||||
11041 | case Job::AnyExprKind: { | ||||
11042 | if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { | ||||
11043 | if (shouldEnqueue(Bop)) { | ||||
11044 | job.Kind = Job::BinOpKind; | ||||
11045 | enqueue(Bop->getLHS()); | ||||
11046 | return; | ||||
11047 | } | ||||
11048 | } | ||||
11049 | |||||
11050 | EvaluateExpr(job.E, Result); | ||||
11051 | Queue.pop_back(); | ||||
11052 | return; | ||||
11053 | } | ||||
11054 | |||||
11055 | case Job::BinOpKind: { | ||||
11056 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||
11057 | bool SuppressRHSDiags = false; | ||||
11058 | if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { | ||||
11059 | Queue.pop_back(); | ||||
11060 | return; | ||||
11061 | } | ||||
11062 | if (SuppressRHSDiags) | ||||
11063 | job.startSpeculativeEval(Info); | ||||
11064 | job.LHSResult.swap(Result); | ||||
11065 | job.Kind = Job::BinOpVisitedLHSKind; | ||||
11066 | enqueue(Bop->getRHS()); | ||||
11067 | return; | ||||
11068 | } | ||||
11069 | |||||
11070 | case Job::BinOpVisitedLHSKind: { | ||||
11071 | const BinaryOperator *Bop = cast<BinaryOperator>(job.E); | ||||
11072 | EvalResult RHS; | ||||
11073 | RHS.swap(Result); | ||||
11074 | Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); | ||||
11075 | Queue.pop_back(); | ||||
11076 | return; | ||||
11077 | } | ||||
11078 | } | ||||
11079 | |||||
11080 | llvm_unreachable("Invalid Job::Kind!")::llvm::llvm_unreachable_internal("Invalid Job::Kind!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11080); | ||||
11081 | } | ||||
11082 | |||||
11083 | namespace { | ||||
11084 | /// Used when we determine that we should fail, but can keep evaluating prior to | ||||
11085 | /// noting that we had a failure. | ||||
11086 | class DelayedNoteFailureRAII { | ||||
11087 | EvalInfo &Info; | ||||
11088 | bool NoteFailure; | ||||
11089 | |||||
11090 | public: | ||||
11091 | DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) | ||||
11092 | : Info(Info), NoteFailure(NoteFailure) {} | ||||
11093 | ~DelayedNoteFailureRAII() { | ||||
11094 | if (NoteFailure) { | ||||
11095 | bool ContinueAfterFailure = Info.noteFailure(); | ||||
11096 | (void)ContinueAfterFailure; | ||||
11097 | assert(ContinueAfterFailure &&((ContinueAfterFailure && "Shouldn't have kept evaluating on failure." ) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11098, __PRETTY_FUNCTION__)) | ||||
11098 | "Shouldn't have kept evaluating on failure.")((ContinueAfterFailure && "Shouldn't have kept evaluating on failure." ) ? static_cast<void> (0) : __assert_fail ("ContinueAfterFailure && \"Shouldn't have kept evaluating on failure.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11098, __PRETTY_FUNCTION__)); | ||||
11099 | } | ||||
11100 | } | ||||
11101 | }; | ||||
11102 | } | ||||
11103 | |||||
11104 | template <class SuccessCB, class AfterCB> | ||||
11105 | static bool | ||||
11106 | EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, | ||||
11107 | SuccessCB &&Success, AfterCB &&DoAfter) { | ||||
11108 | assert(E->isComparisonOp() && "expected comparison operator")((E->isComparisonOp() && "expected comparison operator" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"expected comparison operator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11108, __PRETTY_FUNCTION__)); | ||||
11109 | assert((E->getOpcode() == BO_Cmp ||(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)) | ||||
11110 | E->getType()->isIntegralOrEnumerationType()) &&(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)) | ||||
11111 | "unsupported binary expression evaluation")(((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType ()) && "unsupported binary expression evaluation") ? static_cast <void> (0) : __assert_fail ("(E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && \"unsupported binary expression evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11111, __PRETTY_FUNCTION__)); | ||||
11112 | auto Error = [&](const Expr *E) { | ||||
11113 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
11114 | return false; | ||||
11115 | }; | ||||
11116 | |||||
11117 | using CCR = ComparisonCategoryResult; | ||||
11118 | bool IsRelational = E->isRelationalOp(); | ||||
11119 | bool IsEquality = E->isEqualityOp(); | ||||
11120 | if (E->getOpcode() == BO_Cmp) { | ||||
11121 | const ComparisonCategoryInfo &CmpInfo = | ||||
11122 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | ||||
11123 | IsRelational = CmpInfo.isOrdered(); | ||||
11124 | IsEquality = CmpInfo.isEquality(); | ||||
11125 | } | ||||
11126 | |||||
11127 | QualType LHSTy = E->getLHS()->getType(); | ||||
11128 | QualType RHSTy = E->getRHS()->getType(); | ||||
11129 | |||||
11130 | if (LHSTy->isIntegralOrEnumerationType() && | ||||
11131 | RHSTy->isIntegralOrEnumerationType()) { | ||||
11132 | APSInt LHS, RHS; | ||||
11133 | bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); | ||||
11134 | if (!LHSOK && !Info.noteFailure()) | ||||
11135 | return false; | ||||
11136 | if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) | ||||
11137 | return false; | ||||
11138 | if (LHS < RHS) | ||||
11139 | return Success(CCR::Less, E); | ||||
11140 | if (LHS > RHS) | ||||
11141 | return Success(CCR::Greater, E); | ||||
11142 | return Success(CCR::Equal, E); | ||||
11143 | } | ||||
11144 | |||||
11145 | if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { | ||||
11146 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); | ||||
11147 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); | ||||
11148 | |||||
11149 | bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); | ||||
11150 | if (!LHSOK && !Info.noteFailure()) | ||||
11151 | return false; | ||||
11152 | if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) | ||||
11153 | return false; | ||||
11154 | if (LHSFX < RHSFX) | ||||
11155 | return Success(CCR::Less, E); | ||||
11156 | if (LHSFX > RHSFX) | ||||
11157 | return Success(CCR::Greater, E); | ||||
11158 | return Success(CCR::Equal, E); | ||||
11159 | } | ||||
11160 | |||||
11161 | if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { | ||||
11162 | ComplexValue LHS, RHS; | ||||
11163 | bool LHSOK; | ||||
11164 | if (E->isAssignmentOp()) { | ||||
11165 | LValue LV; | ||||
11166 | EvaluateLValue(E->getLHS(), LV, Info); | ||||
11167 | LHSOK = false; | ||||
11168 | } else if (LHSTy->isRealFloatingType()) { | ||||
11169 | LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); | ||||
11170 | if (LHSOK) { | ||||
11171 | LHS.makeComplexFloat(); | ||||
11172 | LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); | ||||
11173 | } | ||||
11174 | } else { | ||||
11175 | LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); | ||||
11176 | } | ||||
11177 | if (!LHSOK && !Info.noteFailure()) | ||||
11178 | return false; | ||||
11179 | |||||
11180 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||
11181 | if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) | ||||
11182 | return false; | ||||
11183 | RHS.makeComplexFloat(); | ||||
11184 | RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); | ||||
11185 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||
11186 | return false; | ||||
11187 | |||||
11188 | if (LHS.isComplexFloat()) { | ||||
11189 | APFloat::cmpResult CR_r = | ||||
11190 | LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); | ||||
11191 | APFloat::cmpResult CR_i = | ||||
11192 | LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); | ||||
11193 | bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; | ||||
11194 | return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); | ||||
11195 | } else { | ||||
11196 | assert(IsEquality && "invalid complex comparison")((IsEquality && "invalid complex comparison") ? static_cast <void> (0) : __assert_fail ("IsEquality && \"invalid complex comparison\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11196, __PRETTY_FUNCTION__)); | ||||
11197 | bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && | ||||
11198 | LHS.getComplexIntImag() == RHS.getComplexIntImag(); | ||||
11199 | return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); | ||||
11200 | } | ||||
11201 | } | ||||
11202 | |||||
11203 | if (LHSTy->isRealFloatingType() && | ||||
11204 | RHSTy->isRealFloatingType()) { | ||||
11205 | APFloat RHS(0.0), LHS(0.0); | ||||
11206 | |||||
11207 | bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); | ||||
11208 | if (!LHSOK && !Info.noteFailure()) | ||||
11209 | return false; | ||||
11210 | |||||
11211 | if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) | ||||
11212 | return false; | ||||
11213 | |||||
11214 | assert(E->isComparisonOp() && "Invalid binary operator!")((E->isComparisonOp() && "Invalid binary operator!" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"Invalid binary operator!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11214, __PRETTY_FUNCTION__)); | ||||
11215 | auto GetCmpRes = [&]() { | ||||
11216 | switch (LHS.compare(RHS)) { | ||||
11217 | case APFloat::cmpEqual: | ||||
11218 | return CCR::Equal; | ||||
11219 | case APFloat::cmpLessThan: | ||||
11220 | return CCR::Less; | ||||
11221 | case APFloat::cmpGreaterThan: | ||||
11222 | return CCR::Greater; | ||||
11223 | case APFloat::cmpUnordered: | ||||
11224 | return CCR::Unordered; | ||||
11225 | } | ||||
11226 | llvm_unreachable("Unrecognised APFloat::cmpResult enum")::llvm::llvm_unreachable_internal("Unrecognised APFloat::cmpResult enum" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11226); | ||||
11227 | }; | ||||
11228 | return Success(GetCmpRes(), E); | ||||
11229 | } | ||||
11230 | |||||
11231 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) { | ||||
11232 | LValue LHSValue, RHSValue; | ||||
11233 | |||||
11234 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||
11235 | if (!LHSOK && !Info.noteFailure()) | ||||
11236 | return false; | ||||
11237 | |||||
11238 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
11239 | return false; | ||||
11240 | |||||
11241 | // Reject differing bases from the normal codepath; we special-case | ||||
11242 | // comparisons to null. | ||||
11243 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||
11244 | // Inequalities and subtractions between unrelated pointers have | ||||
11245 | // unspecified or undefined behavior. | ||||
11246 | if (!IsEquality) | ||||
11247 | return Error(E); | ||||
11248 | // A constant address may compare equal to the address of a symbol. | ||||
11249 | // The one exception is that address of an object cannot compare equal | ||||
11250 | // to a null pointer constant. | ||||
11251 | if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || | ||||
11252 | (!RHSValue.Base && !RHSValue.Offset.isZero())) | ||||
11253 | return Error(E); | ||||
11254 | // It's implementation-defined whether distinct literals will have | ||||
11255 | // distinct addresses. In clang, the result of such a comparison is | ||||
11256 | // unspecified, so it is not a constant expression. However, we do know | ||||
11257 | // that the address of a literal will be non-null. | ||||
11258 | if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && | ||||
11259 | LHSValue.Base && RHSValue.Base) | ||||
11260 | return Error(E); | ||||
11261 | // We can't tell whether weak symbols will end up pointing to the same | ||||
11262 | // object. | ||||
11263 | if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) | ||||
11264 | return Error(E); | ||||
11265 | // We can't compare the address of the start of one object with the | ||||
11266 | // past-the-end address of another object, per C++ DR1652. | ||||
11267 | if ((LHSValue.Base && LHSValue.Offset.isZero() && | ||||
11268 | isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || | ||||
11269 | (RHSValue.Base && RHSValue.Offset.isZero() && | ||||
11270 | isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) | ||||
11271 | return Error(E); | ||||
11272 | // We can't tell whether an object is at the same address as another | ||||
11273 | // zero sized object. | ||||
11274 | if ((RHSValue.Base && isZeroSized(LHSValue)) || | ||||
11275 | (LHSValue.Base && isZeroSized(RHSValue))) | ||||
11276 | return Error(E); | ||||
11277 | return Success(CCR::Nonequal, E); | ||||
11278 | } | ||||
11279 | |||||
11280 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||
11281 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||
11282 | |||||
11283 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||
11284 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||
11285 | |||||
11286 | // C++11 [expr.rel]p3: | ||||
11287 | // Pointers to void (after pointer conversions) can be compared, with a | ||||
11288 | // result defined as follows: If both pointers represent the same | ||||
11289 | // address or are both the null pointer value, the result is true if the | ||||
11290 | // operator is <= or >= and false otherwise; otherwise the result is | ||||
11291 | // unspecified. | ||||
11292 | // We interpret this as applying to pointers to *cv* void. | ||||
11293 | if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) | ||||
11294 | Info.CCEDiag(E, diag::note_constexpr_void_comparison); | ||||
11295 | |||||
11296 | // C++11 [expr.rel]p2: | ||||
11297 | // - If two pointers point to non-static data members of the same object, | ||||
11298 | // or to subobjects or array elements fo such members, recursively, the | ||||
11299 | // pointer to the later declared member compares greater provided the | ||||
11300 | // two members have the same access control and provided their class is | ||||
11301 | // not a union. | ||||
11302 | // [...] | ||||
11303 | // - Otherwise pointer comparisons are unspecified. | ||||
11304 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { | ||||
11305 | bool WasArrayIndex; | ||||
11306 | unsigned Mismatch = FindDesignatorMismatch( | ||||
11307 | getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); | ||||
11308 | // At the point where the designators diverge, the comparison has a | ||||
11309 | // specified value if: | ||||
11310 | // - we are comparing array indices | ||||
11311 | // - we are comparing fields of a union, or fields with the same access | ||||
11312 | // Otherwise, the result is unspecified and thus the comparison is not a | ||||
11313 | // constant expression. | ||||
11314 | if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && | ||||
11315 | Mismatch < RHSDesignator.Entries.size()) { | ||||
11316 | const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); | ||||
11317 | const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); | ||||
11318 | if (!LF && !RF) | ||||
11319 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); | ||||
11320 | else if (!LF) | ||||
11321 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||
11322 | << getAsBaseClass(LHSDesignator.Entries[Mismatch]) | ||||
11323 | << RF->getParent() << RF; | ||||
11324 | else if (!RF) | ||||
11325 | Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) | ||||
11326 | << getAsBaseClass(RHSDesignator.Entries[Mismatch]) | ||||
11327 | << LF->getParent() << LF; | ||||
11328 | else if (!LF->getParent()->isUnion() && | ||||
11329 | LF->getAccess() != RF->getAccess()) | ||||
11330 | Info.CCEDiag(E, | ||||
11331 | diag::note_constexpr_pointer_comparison_differing_access) | ||||
11332 | << LF << LF->getAccess() << RF << RF->getAccess() | ||||
11333 | << LF->getParent(); | ||||
11334 | } | ||||
11335 | } | ||||
11336 | |||||
11337 | // The comparison here must be unsigned, and performed with the same | ||||
11338 | // width as the pointer. | ||||
11339 | unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); | ||||
11340 | uint64_t CompareLHS = LHSOffset.getQuantity(); | ||||
11341 | uint64_t CompareRHS = RHSOffset.getQuantity(); | ||||
11342 | assert(PtrSize <= 64 && "Unexpected pointer width")((PtrSize <= 64 && "Unexpected pointer width") ? static_cast <void> (0) : __assert_fail ("PtrSize <= 64 && \"Unexpected pointer width\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11342, __PRETTY_FUNCTION__)); | ||||
11343 | uint64_t Mask = ~0ULL >> (64 - PtrSize); | ||||
11344 | CompareLHS &= Mask; | ||||
11345 | CompareRHS &= Mask; | ||||
11346 | |||||
11347 | // If there is a base and this is a relational operator, we can only | ||||
11348 | // compare pointers within the object in question; otherwise, the result | ||||
11349 | // depends on where the object is located in memory. | ||||
11350 | if (!LHSValue.Base.isNull() && IsRelational) { | ||||
11351 | QualType BaseTy = getType(LHSValue.Base); | ||||
11352 | if (BaseTy->isIncompleteType()) | ||||
11353 | return Error(E); | ||||
11354 | CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); | ||||
11355 | uint64_t OffsetLimit = Size.getQuantity(); | ||||
11356 | if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) | ||||
11357 | return Error(E); | ||||
11358 | } | ||||
11359 | |||||
11360 | if (CompareLHS < CompareRHS) | ||||
11361 | return Success(CCR::Less, E); | ||||
11362 | if (CompareLHS > CompareRHS) | ||||
11363 | return Success(CCR::Greater, E); | ||||
11364 | return Success(CCR::Equal, E); | ||||
11365 | } | ||||
11366 | |||||
11367 | if (LHSTy->isMemberPointerType()) { | ||||
11368 | assert(IsEquality && "unexpected member pointer operation")((IsEquality && "unexpected member pointer operation" ) ? static_cast<void> (0) : __assert_fail ("IsEquality && \"unexpected member pointer operation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11368, __PRETTY_FUNCTION__)); | ||||
11369 | assert(RHSTy->isMemberPointerType() && "invalid comparison")((RHSTy->isMemberPointerType() && "invalid comparison" ) ? static_cast<void> (0) : __assert_fail ("RHSTy->isMemberPointerType() && \"invalid comparison\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11369, __PRETTY_FUNCTION__)); | ||||
11370 | |||||
11371 | MemberPtr LHSValue, RHSValue; | ||||
11372 | |||||
11373 | bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); | ||||
11374 | if (!LHSOK && !Info.noteFailure()) | ||||
11375 | return false; | ||||
11376 | |||||
11377 | if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
11378 | return false; | ||||
11379 | |||||
11380 | // C++11 [expr.eq]p2: | ||||
11381 | // If both operands are null, they compare equal. Otherwise if only one is | ||||
11382 | // null, they compare unequal. | ||||
11383 | if (!LHSValue.getDecl() || !RHSValue.getDecl()) { | ||||
11384 | bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); | ||||
11385 | return Success(Equal ? CCR::Equal : CCR::Nonequal, E); | ||||
11386 | } | ||||
11387 | |||||
11388 | // Otherwise if either is a pointer to a virtual member function, the | ||||
11389 | // result is unspecified. | ||||
11390 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) | ||||
11391 | if (MD->isVirtual()) | ||||
11392 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||
11393 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) | ||||
11394 | if (MD->isVirtual()) | ||||
11395 | Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; | ||||
11396 | |||||
11397 | // Otherwise they compare equal if and only if they would refer to the | ||||
11398 | // same member of the same most derived object or the same subobject if | ||||
11399 | // they were dereferenced with a hypothetical object of the associated | ||||
11400 | // class type. | ||||
11401 | bool Equal = LHSValue == RHSValue; | ||||
11402 | return Success(Equal ? CCR::Equal : CCR::Nonequal, E); | ||||
11403 | } | ||||
11404 | |||||
11405 | if (LHSTy->isNullPtrType()) { | ||||
11406 | assert(E->isComparisonOp() && "unexpected nullptr operation")((E->isComparisonOp() && "unexpected nullptr operation" ) ? static_cast<void> (0) : __assert_fail ("E->isComparisonOp() && \"unexpected nullptr operation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11406, __PRETTY_FUNCTION__)); | ||||
11407 | assert(RHSTy->isNullPtrType() && "missing pointer conversion")((RHSTy->isNullPtrType() && "missing pointer conversion" ) ? static_cast<void> (0) : __assert_fail ("RHSTy->isNullPtrType() && \"missing pointer conversion\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11407, __PRETTY_FUNCTION__)); | ||||
11408 | // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t | ||||
11409 | // are compared, the result is true of the operator is <=, >= or ==, and | ||||
11410 | // false otherwise. | ||||
11411 | return Success(CCR::Equal, E); | ||||
11412 | } | ||||
11413 | |||||
11414 | return DoAfter(); | ||||
11415 | } | ||||
11416 | |||||
11417 | bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { | ||||
11418 | if (!CheckLiteralType(Info, E)) | ||||
11419 | return false; | ||||
11420 | |||||
11421 | auto OnSuccess = [&](ComparisonCategoryResult ResKind, | ||||
11422 | const BinaryOperator *E) { | ||||
11423 | // Evaluation succeeded. Lookup the information for the comparison category | ||||
11424 | // type and fetch the VarDecl for the result. | ||||
11425 | const ComparisonCategoryInfo &CmpInfo = | ||||
11426 | Info.Ctx.CompCategories.getInfoForType(E->getType()); | ||||
11427 | const VarDecl *VD = | ||||
11428 | CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; | ||||
11429 | // Check and evaluate the result as a constant expression. | ||||
11430 | LValue LV; | ||||
11431 | LV.set(VD); | ||||
11432 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||
11433 | return false; | ||||
11434 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); | ||||
11435 | }; | ||||
11436 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||
11437 | return ExprEvaluatorBaseTy::VisitBinCmp(E); | ||||
11438 | }); | ||||
11439 | } | ||||
11440 | |||||
11441 | bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
11442 | // We don't call noteFailure immediately because the assignment happens after | ||||
11443 | // we evaluate LHS and RHS. | ||||
11444 | if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) | ||||
11445 | return Error(E); | ||||
11446 | |||||
11447 | DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); | ||||
11448 | if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) | ||||
11449 | return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); | ||||
11450 | |||||
11451 | assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)) | ||||
11452 | !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)) | ||||
11453 | "DataRecursiveIntBinOpEvaluator should have handled integral types")(((!E->getLHS()->getType()->isIntegralOrEnumerationType () || !E->getRHS()->getType()->isIntegralOrEnumerationType ()) && "DataRecursiveIntBinOpEvaluator should have handled integral types" ) ? static_cast<void> (0) : __assert_fail ("(!E->getLHS()->getType()->isIntegralOrEnumerationType() || !E->getRHS()->getType()->isIntegralOrEnumerationType()) && \"DataRecursiveIntBinOpEvaluator should have handled integral types\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11453, __PRETTY_FUNCTION__)); | ||||
11454 | |||||
11455 | if (E->isComparisonOp()) { | ||||
11456 | // Evaluate builtin binary comparisons by evaluating them as C++2a three-way | ||||
11457 | // comparisons and then translating the result. | ||||
11458 | auto OnSuccess = [&](ComparisonCategoryResult ResKind, | ||||
11459 | const BinaryOperator *E) { | ||||
11460 | using CCR = ComparisonCategoryResult; | ||||
11461 | bool IsEqual = ResKind == CCR::Equal, | ||||
11462 | IsLess = ResKind == CCR::Less, | ||||
11463 | IsGreater = ResKind == CCR::Greater; | ||||
11464 | auto Op = E->getOpcode(); | ||||
11465 | switch (Op) { | ||||
11466 | default: | ||||
11467 | llvm_unreachable("unsupported binary operator")::llvm::llvm_unreachable_internal("unsupported binary operator" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11467); | ||||
11468 | case BO_EQ: | ||||
11469 | case BO_NE: | ||||
11470 | return Success(IsEqual == (Op == BO_EQ), E); | ||||
11471 | case BO_LT: return Success(IsLess, E); | ||||
11472 | case BO_GT: return Success(IsGreater, E); | ||||
11473 | case BO_LE: return Success(IsEqual || IsLess, E); | ||||
11474 | case BO_GE: return Success(IsEqual || IsGreater, E); | ||||
11475 | } | ||||
11476 | }; | ||||
11477 | return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { | ||||
11478 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
11479 | }); | ||||
11480 | } | ||||
11481 | |||||
11482 | QualType LHSTy = E->getLHS()->getType(); | ||||
11483 | QualType RHSTy = E->getRHS()->getType(); | ||||
11484 | |||||
11485 | if (LHSTy->isPointerType() && RHSTy->isPointerType() && | ||||
11486 | E->getOpcode() == BO_Sub) { | ||||
11487 | LValue LHSValue, RHSValue; | ||||
11488 | |||||
11489 | bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); | ||||
11490 | if (!LHSOK && !Info.noteFailure()) | ||||
11491 | return false; | ||||
11492 | |||||
11493 | if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) | ||||
11494 | return false; | ||||
11495 | |||||
11496 | // Reject differing bases from the normal codepath; we special-case | ||||
11497 | // comparisons to null. | ||||
11498 | if (!HasSameBase(LHSValue, RHSValue)) { | ||||
11499 | // Handle &&A - &&B. | ||||
11500 | if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) | ||||
11501 | return Error(E); | ||||
11502 | const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); | ||||
11503 | const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); | ||||
11504 | if (!LHSExpr || !RHSExpr) | ||||
11505 | return Error(E); | ||||
11506 | const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); | ||||
11507 | const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); | ||||
11508 | if (!LHSAddrExpr || !RHSAddrExpr) | ||||
11509 | return Error(E); | ||||
11510 | // Make sure both labels come from the same function. | ||||
11511 | if (LHSAddrExpr->getLabel()->getDeclContext() != | ||||
11512 | RHSAddrExpr->getLabel()->getDeclContext()) | ||||
11513 | return Error(E); | ||||
11514 | return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); | ||||
11515 | } | ||||
11516 | const CharUnits &LHSOffset = LHSValue.getLValueOffset(); | ||||
11517 | const CharUnits &RHSOffset = RHSValue.getLValueOffset(); | ||||
11518 | |||||
11519 | SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); | ||||
11520 | SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); | ||||
11521 | |||||
11522 | // C++11 [expr.add]p6: | ||||
11523 | // Unless both pointers point to elements of the same array object, or | ||||
11524 | // one past the last element of the array object, the behavior is | ||||
11525 | // undefined. | ||||
11526 | if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && | ||||
11527 | !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, | ||||
11528 | RHSDesignator)) | ||||
11529 | Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); | ||||
11530 | |||||
11531 | QualType Type = E->getLHS()->getType(); | ||||
11532 | QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); | ||||
11533 | |||||
11534 | CharUnits ElementSize; | ||||
11535 | if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) | ||||
11536 | return false; | ||||
11537 | |||||
11538 | // As an extension, a type may have zero size (empty struct or union in | ||||
11539 | // C, array of zero length). Pointer subtraction in such cases has | ||||
11540 | // undefined behavior, so is not constant. | ||||
11541 | if (ElementSize.isZero()) { | ||||
11542 | Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) | ||||
11543 | << ElementType; | ||||
11544 | return false; | ||||
11545 | } | ||||
11546 | |||||
11547 | // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, | ||||
11548 | // and produce incorrect results when it overflows. Such behavior | ||||
11549 | // appears to be non-conforming, but is common, so perhaps we should | ||||
11550 | // assume the standard intended for such cases to be undefined behavior | ||||
11551 | // and check for them. | ||||
11552 | |||||
11553 | // Compute (LHSOffset - RHSOffset) / Size carefully, checking for | ||||
11554 | // overflow in the final conversion to ptrdiff_t. | ||||
11555 | APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); | ||||
11556 | APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); | ||||
11557 | APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), | ||||
11558 | false); | ||||
11559 | APSInt TrueResult = (LHS - RHS) / ElemSize; | ||||
11560 | APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); | ||||
11561 | |||||
11562 | if (Result.extend(65) != TrueResult && | ||||
11563 | !HandleOverflow(Info, E, TrueResult, E->getType())) | ||||
11564 | return false; | ||||
11565 | return Success(Result, E); | ||||
11566 | } | ||||
11567 | |||||
11568 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
11569 | } | ||||
11570 | |||||
11571 | /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with | ||||
11572 | /// a result as the expression's type. | ||||
11573 | bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( | ||||
11574 | const UnaryExprOrTypeTraitExpr *E) { | ||||
11575 | switch(E->getKind()) { | ||||
11576 | case UETT_PreferredAlignOf: | ||||
11577 | case UETT_AlignOf: { | ||||
11578 | if (E->isArgumentType()) | ||||
11579 | return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), | ||||
11580 | E); | ||||
11581 | else | ||||
11582 | return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), | ||||
11583 | E); | ||||
11584 | } | ||||
11585 | |||||
11586 | case UETT_VecStep: { | ||||
11587 | QualType Ty = E->getTypeOfArgument(); | ||||
11588 | |||||
11589 | if (Ty->isVectorType()) { | ||||
11590 | unsigned n = Ty->castAs<VectorType>()->getNumElements(); | ||||
11591 | |||||
11592 | // The vec_step built-in functions that take a 3-component | ||||
11593 | // vector return 4. (OpenCL 1.1 spec 6.11.12) | ||||
11594 | if (n == 3) | ||||
11595 | n = 4; | ||||
11596 | |||||
11597 | return Success(n, E); | ||||
11598 | } else | ||||
11599 | return Success(1, E); | ||||
11600 | } | ||||
11601 | |||||
11602 | case UETT_SizeOf: { | ||||
11603 | QualType SrcTy = E->getTypeOfArgument(); | ||||
11604 | // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, | ||||
11605 | // the result is the size of the referenced type." | ||||
11606 | if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) | ||||
11607 | SrcTy = Ref->getPointeeType(); | ||||
11608 | |||||
11609 | CharUnits Sizeof; | ||||
11610 | if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) | ||||
11611 | return false; | ||||
11612 | return Success(Sizeof, E); | ||||
11613 | } | ||||
11614 | case UETT_OpenMPRequiredSimdAlign: | ||||
11615 | assert(E->isArgumentType())((E->isArgumentType()) ? static_cast<void> (0) : __assert_fail ("E->isArgumentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11615, __PRETTY_FUNCTION__)); | ||||
11616 | return Success( | ||||
11617 | Info.Ctx.toCharUnitsFromBits( | ||||
11618 | Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) | ||||
11619 | .getQuantity(), | ||||
11620 | E); | ||||
11621 | } | ||||
11622 | |||||
11623 | llvm_unreachable("unknown expr/type trait")::llvm::llvm_unreachable_internal("unknown expr/type trait", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11623); | ||||
11624 | } | ||||
11625 | |||||
11626 | bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { | ||||
11627 | CharUnits Result; | ||||
11628 | unsigned n = OOE->getNumComponents(); | ||||
11629 | if (n == 0) | ||||
11630 | return Error(OOE); | ||||
11631 | QualType CurrentType = OOE->getTypeSourceInfo()->getType(); | ||||
11632 | for (unsigned i = 0; i != n; ++i) { | ||||
11633 | OffsetOfNode ON = OOE->getComponent(i); | ||||
11634 | switch (ON.getKind()) { | ||||
11635 | case OffsetOfNode::Array: { | ||||
11636 | const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); | ||||
11637 | APSInt IdxResult; | ||||
11638 | if (!EvaluateInteger(Idx, IdxResult, Info)) | ||||
11639 | return false; | ||||
11640 | const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); | ||||
11641 | if (!AT) | ||||
11642 | return Error(OOE); | ||||
11643 | CurrentType = AT->getElementType(); | ||||
11644 | CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); | ||||
11645 | Result += IdxResult.getSExtValue() * ElementSize; | ||||
11646 | break; | ||||
11647 | } | ||||
11648 | |||||
11649 | case OffsetOfNode::Field: { | ||||
11650 | FieldDecl *MemberDecl = ON.getField(); | ||||
11651 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||
11652 | if (!RT) | ||||
11653 | return Error(OOE); | ||||
11654 | RecordDecl *RD = RT->getDecl(); | ||||
11655 | if (RD->isInvalidDecl()) return false; | ||||
11656 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||
11657 | unsigned i = MemberDecl->getFieldIndex(); | ||||
11658 | assert(i < RL.getFieldCount() && "offsetof field in wrong type")((i < RL.getFieldCount() && "offsetof field in wrong type" ) ? static_cast<void> (0) : __assert_fail ("i < RL.getFieldCount() && \"offsetof field in wrong type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11658, __PRETTY_FUNCTION__)); | ||||
11659 | Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); | ||||
11660 | CurrentType = MemberDecl->getType().getNonReferenceType(); | ||||
11661 | break; | ||||
11662 | } | ||||
11663 | |||||
11664 | case OffsetOfNode::Identifier: | ||||
11665 | llvm_unreachable("dependent __builtin_offsetof")::llvm::llvm_unreachable_internal("dependent __builtin_offsetof" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11665); | ||||
11666 | |||||
11667 | case OffsetOfNode::Base: { | ||||
11668 | CXXBaseSpecifier *BaseSpec = ON.getBase(); | ||||
11669 | if (BaseSpec->isVirtual()) | ||||
11670 | return Error(OOE); | ||||
11671 | |||||
11672 | // Find the layout of the class whose base we are looking into. | ||||
11673 | const RecordType *RT = CurrentType->getAs<RecordType>(); | ||||
11674 | if (!RT) | ||||
11675 | return Error(OOE); | ||||
11676 | RecordDecl *RD = RT->getDecl(); | ||||
11677 | if (RD->isInvalidDecl()) return false; | ||||
11678 | const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); | ||||
11679 | |||||
11680 | // Find the base class itself. | ||||
11681 | CurrentType = BaseSpec->getType(); | ||||
11682 | const RecordType *BaseRT = CurrentType->getAs<RecordType>(); | ||||
11683 | if (!BaseRT) | ||||
11684 | return Error(OOE); | ||||
11685 | |||||
11686 | // Add the offset to the base. | ||||
11687 | Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); | ||||
11688 | break; | ||||
11689 | } | ||||
11690 | } | ||||
11691 | } | ||||
11692 | return Success(Result, OOE); | ||||
11693 | } | ||||
11694 | |||||
11695 | bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
11696 | switch (E->getOpcode()) { | ||||
11697 | default: | ||||
11698 | // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. | ||||
11699 | // See C99 6.6p3. | ||||
11700 | return Error(E); | ||||
11701 | case UO_Extension: | ||||
11702 | // FIXME: Should extension allow i-c-e extension expressions in its scope? | ||||
11703 | // If so, we could clear the diagnostic ID. | ||||
11704 | return Visit(E->getSubExpr()); | ||||
11705 | case UO_Plus: | ||||
11706 | // The result is just the value. | ||||
11707 | return Visit(E->getSubExpr()); | ||||
11708 | case UO_Minus: { | ||||
11709 | if (!Visit(E->getSubExpr())) | ||||
11710 | return false; | ||||
11711 | if (!Result.isInt()) return Error(E); | ||||
11712 | const APSInt &Value = Result.getInt(); | ||||
11713 | if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && | ||||
11714 | !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), | ||||
11715 | E->getType())) | ||||
11716 | return false; | ||||
11717 | return Success(-Value, E); | ||||
11718 | } | ||||
11719 | case UO_Not: { | ||||
11720 | if (!Visit(E->getSubExpr())) | ||||
11721 | return false; | ||||
11722 | if (!Result.isInt()) return Error(E); | ||||
11723 | return Success(~Result.getInt(), E); | ||||
11724 | } | ||||
11725 | case UO_LNot: { | ||||
11726 | bool bres; | ||||
11727 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||
11728 | return false; | ||||
11729 | return Success(!bres, E); | ||||
11730 | } | ||||
11731 | } | ||||
11732 | } | ||||
11733 | |||||
11734 | /// HandleCast - This is used to evaluate implicit or explicit casts where the | ||||
11735 | /// result type is integer. | ||||
11736 | bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
11737 | const Expr *SubExpr = E->getSubExpr(); | ||||
11738 | QualType DestType = E->getType(); | ||||
11739 | QualType SrcType = SubExpr->getType(); | ||||
11740 | |||||
11741 | switch (E->getCastKind()) { | ||||
11742 | case CK_BaseToDerived: | ||||
11743 | case CK_DerivedToBase: | ||||
11744 | case CK_UncheckedDerivedToBase: | ||||
11745 | case CK_Dynamic: | ||||
11746 | case CK_ToUnion: | ||||
11747 | case CK_ArrayToPointerDecay: | ||||
11748 | case CK_FunctionToPointerDecay: | ||||
11749 | case CK_NullToPointer: | ||||
11750 | case CK_NullToMemberPointer: | ||||
11751 | case CK_BaseToDerivedMemberPointer: | ||||
11752 | case CK_DerivedToBaseMemberPointer: | ||||
11753 | case CK_ReinterpretMemberPointer: | ||||
11754 | case CK_ConstructorConversion: | ||||
11755 | case CK_IntegralToPointer: | ||||
11756 | case CK_ToVoid: | ||||
11757 | case CK_VectorSplat: | ||||
11758 | case CK_IntegralToFloating: | ||||
11759 | case CK_FloatingCast: | ||||
11760 | case CK_CPointerToObjCPointerCast: | ||||
11761 | case CK_BlockPointerToObjCPointerCast: | ||||
11762 | case CK_AnyPointerToBlockPointerCast: | ||||
11763 | case CK_ObjCObjectLValueCast: | ||||
11764 | case CK_FloatingRealToComplex: | ||||
11765 | case CK_FloatingComplexToReal: | ||||
11766 | case CK_FloatingComplexCast: | ||||
11767 | case CK_FloatingComplexToIntegralComplex: | ||||
11768 | case CK_IntegralRealToComplex: | ||||
11769 | case CK_IntegralComplexCast: | ||||
11770 | case CK_IntegralComplexToFloatingComplex: | ||||
11771 | case CK_BuiltinFnToFnPtr: | ||||
11772 | case CK_ZeroToOCLOpaqueType: | ||||
11773 | case CK_NonAtomicToAtomic: | ||||
11774 | case CK_AddressSpaceConversion: | ||||
11775 | case CK_IntToOCLSampler: | ||||
11776 | case CK_FixedPointCast: | ||||
11777 | case CK_IntegralToFixedPoint: | ||||
11778 | llvm_unreachable("invalid cast kind for integral value")::llvm::llvm_unreachable_internal("invalid cast kind for integral value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11778); | ||||
11779 | |||||
11780 | case CK_BitCast: | ||||
11781 | case CK_Dependent: | ||||
11782 | case CK_LValueBitCast: | ||||
11783 | case CK_ARCProduceObject: | ||||
11784 | case CK_ARCConsumeObject: | ||||
11785 | case CK_ARCReclaimReturnedObject: | ||||
11786 | case CK_ARCExtendBlockObject: | ||||
11787 | case CK_CopyAndAutoreleaseBlockObject: | ||||
11788 | return Error(E); | ||||
11789 | |||||
11790 | case CK_UserDefinedConversion: | ||||
11791 | case CK_LValueToRValue: | ||||
11792 | case CK_AtomicToNonAtomic: | ||||
11793 | case CK_NoOp: | ||||
11794 | case CK_LValueToRValueBitCast: | ||||
11795 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
11796 | |||||
11797 | case CK_MemberPointerToBoolean: | ||||
11798 | case CK_PointerToBoolean: | ||||
11799 | case CK_IntegralToBoolean: | ||||
11800 | case CK_FloatingToBoolean: | ||||
11801 | case CK_BooleanToSignedIntegral: | ||||
11802 | case CK_FloatingComplexToBoolean: | ||||
11803 | case CK_IntegralComplexToBoolean: { | ||||
11804 | bool BoolResult; | ||||
11805 | if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) | ||||
11806 | return false; | ||||
11807 | uint64_t IntResult = BoolResult; | ||||
11808 | if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) | ||||
11809 | IntResult = (uint64_t)-1; | ||||
11810 | return Success(IntResult, E); | ||||
11811 | } | ||||
11812 | |||||
11813 | case CK_FixedPointToIntegral: { | ||||
11814 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); | ||||
11815 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||
11816 | return false; | ||||
11817 | bool Overflowed; | ||||
11818 | llvm::APSInt Result = Src.convertToInt( | ||||
11819 | Info.Ctx.getIntWidth(DestType), | ||||
11820 | DestType->isSignedIntegerOrEnumerationType(), &Overflowed); | ||||
11821 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | ||||
11822 | return false; | ||||
11823 | return Success(Result, E); | ||||
11824 | } | ||||
11825 | |||||
11826 | case CK_FixedPointToBoolean: { | ||||
11827 | // Unsigned padding does not affect this. | ||||
11828 | APValue Val; | ||||
11829 | if (!Evaluate(Val, Info, SubExpr)) | ||||
11830 | return false; | ||||
11831 | return Success(Val.getFixedPoint().getBoolValue(), E); | ||||
11832 | } | ||||
11833 | |||||
11834 | case CK_IntegralCast: { | ||||
11835 | if (!Visit(SubExpr)) | ||||
11836 | return false; | ||||
11837 | |||||
11838 | if (!Result.isInt()) { | ||||
11839 | // Allow casts of address-of-label differences if they are no-ops | ||||
11840 | // or narrowing. (The narrowing case isn't actually guaranteed to | ||||
11841 | // be constant-evaluatable except in some narrow cases which are hard | ||||
11842 | // to detect here. We let it through on the assumption the user knows | ||||
11843 | // what they are doing.) | ||||
11844 | if (Result.isAddrLabelDiff()) | ||||
11845 | return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); | ||||
11846 | // Only allow casts of lvalues if they are lossless. | ||||
11847 | return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); | ||||
11848 | } | ||||
11849 | |||||
11850 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, | ||||
11851 | Result.getInt()), E); | ||||
11852 | } | ||||
11853 | |||||
11854 | case CK_PointerToIntegral: { | ||||
11855 | CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; | ||||
11856 | |||||
11857 | LValue LV; | ||||
11858 | if (!EvaluatePointer(SubExpr, LV, Info)) | ||||
11859 | return false; | ||||
11860 | |||||
11861 | if (LV.getLValueBase()) { | ||||
11862 | // Only allow based lvalue casts if they are lossless. | ||||
11863 | // FIXME: Allow a larger integer size than the pointer size, and allow | ||||
11864 | // narrowing back down to pointer width in subsequent integral casts. | ||||
11865 | // FIXME: Check integer type's active bits, not its type size. | ||||
11866 | if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) | ||||
11867 | return Error(E); | ||||
11868 | |||||
11869 | LV.Designator.setInvalid(); | ||||
11870 | LV.moveInto(Result); | ||||
11871 | return true; | ||||
11872 | } | ||||
11873 | |||||
11874 | APSInt AsInt; | ||||
11875 | APValue V; | ||||
11876 | LV.moveInto(V); | ||||
11877 | if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) | ||||
11878 | llvm_unreachable("Can't cast this!")::llvm::llvm_unreachable_internal("Can't cast this!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11878); | ||||
11879 | |||||
11880 | return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); | ||||
11881 | } | ||||
11882 | |||||
11883 | case CK_IntegralComplexToReal: { | ||||
11884 | ComplexValue C; | ||||
11885 | if (!EvaluateComplex(SubExpr, C, Info)) | ||||
11886 | return false; | ||||
11887 | return Success(C.getComplexIntReal(), E); | ||||
11888 | } | ||||
11889 | |||||
11890 | case CK_FloatingToIntegral: { | ||||
11891 | APFloat F(0.0); | ||||
11892 | if (!EvaluateFloat(SubExpr, F, Info)) | ||||
11893 | return false; | ||||
11894 | |||||
11895 | APSInt Value; | ||||
11896 | if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) | ||||
11897 | return false; | ||||
11898 | return Success(Value, E); | ||||
11899 | } | ||||
11900 | } | ||||
11901 | |||||
11902 | llvm_unreachable("unknown cast resulting in integral value")::llvm::llvm_unreachable_internal("unknown cast resulting in integral value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11902); | ||||
11903 | } | ||||
11904 | |||||
11905 | bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
11906 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
11907 | ComplexValue LV; | ||||
11908 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||
11909 | return false; | ||||
11910 | if (!LV.isComplexInt()) | ||||
11911 | return Error(E); | ||||
11912 | return Success(LV.getComplexIntReal(), E); | ||||
11913 | } | ||||
11914 | |||||
11915 | return Visit(E->getSubExpr()); | ||||
11916 | } | ||||
11917 | |||||
11918 | bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
11919 | if (E->getSubExpr()->getType()->isComplexIntegerType()) { | ||||
11920 | ComplexValue LV; | ||||
11921 | if (!EvaluateComplex(E->getSubExpr(), LV, Info)) | ||||
11922 | return false; | ||||
11923 | if (!LV.isComplexInt()) | ||||
11924 | return Error(E); | ||||
11925 | return Success(LV.getComplexIntImag(), E); | ||||
11926 | } | ||||
11927 | |||||
11928 | VisitIgnoredValue(E->getSubExpr()); | ||||
11929 | return Success(0, E); | ||||
11930 | } | ||||
11931 | |||||
11932 | bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { | ||||
11933 | return Success(E->getPackLength(), E); | ||||
11934 | } | ||||
11935 | |||||
11936 | bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { | ||||
11937 | return Success(E->getValue(), E); | ||||
11938 | } | ||||
11939 | |||||
11940 | bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
11941 | switch (E->getOpcode()) { | ||||
11942 | default: | ||||
11943 | // Invalid unary operators | ||||
11944 | return Error(E); | ||||
11945 | case UO_Plus: | ||||
11946 | // The result is just the value. | ||||
11947 | return Visit(E->getSubExpr()); | ||||
11948 | case UO_Minus: { | ||||
11949 | if (!Visit(E->getSubExpr())) return false; | ||||
11950 | if (!Result.isFixedPoint()) | ||||
11951 | return Error(E); | ||||
11952 | bool Overflowed; | ||||
11953 | APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); | ||||
11954 | if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) | ||||
11955 | return false; | ||||
11956 | return Success(Negated, E); | ||||
11957 | } | ||||
11958 | case UO_LNot: { | ||||
11959 | bool bres; | ||||
11960 | if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) | ||||
11961 | return false; | ||||
11962 | return Success(!bres, E); | ||||
11963 | } | ||||
11964 | } | ||||
11965 | } | ||||
11966 | |||||
11967 | bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
11968 | const Expr *SubExpr = E->getSubExpr(); | ||||
11969 | QualType DestType = E->getType(); | ||||
11970 | assert(DestType->isFixedPointType() &&((DestType->isFixedPointType() && "Expected destination type to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11971, __PRETTY_FUNCTION__)) | ||||
11971 | "Expected destination type to be a fixed point type")((DestType->isFixedPointType() && "Expected destination type to be a fixed point type" ) ? static_cast<void> (0) : __assert_fail ("DestType->isFixedPointType() && \"Expected destination type to be a fixed point type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 11971, __PRETTY_FUNCTION__)); | ||||
11972 | auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); | ||||
11973 | |||||
11974 | switch (E->getCastKind()) { | ||||
11975 | case CK_FixedPointCast: { | ||||
11976 | APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); | ||||
11977 | if (!EvaluateFixedPoint(SubExpr, Src, Info)) | ||||
11978 | return false; | ||||
11979 | bool Overflowed; | ||||
11980 | APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); | ||||
11981 | if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) | ||||
11982 | return false; | ||||
11983 | return Success(Result, E); | ||||
11984 | } | ||||
11985 | case CK_IntegralToFixedPoint: { | ||||
11986 | APSInt Src; | ||||
11987 | if (!EvaluateInteger(SubExpr, Src, Info)) | ||||
11988 | return false; | ||||
11989 | |||||
11990 | bool Overflowed; | ||||
11991 | APFixedPoint IntResult = APFixedPoint::getFromIntValue( | ||||
11992 | Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); | ||||
11993 | |||||
11994 | if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) | ||||
11995 | return false; | ||||
11996 | |||||
11997 | return Success(IntResult, E); | ||||
11998 | } | ||||
11999 | case CK_NoOp: | ||||
12000 | case CK_LValueToRValue: | ||||
12001 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
12002 | default: | ||||
12003 | return Error(E); | ||||
12004 | } | ||||
12005 | } | ||||
12006 | |||||
12007 | bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
12008 | const Expr *LHS = E->getLHS(); | ||||
12009 | const Expr *RHS = E->getRHS(); | ||||
12010 | FixedPointSemantics ResultFXSema = | ||||
12011 | Info.Ctx.getFixedPointSemantics(E->getType()); | ||||
12012 | |||||
12013 | APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); | ||||
12014 | if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) | ||||
12015 | return false; | ||||
12016 | APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); | ||||
12017 | if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) | ||||
12018 | return false; | ||||
12019 | |||||
12020 | switch (E->getOpcode()) { | ||||
12021 | case BO_Add: { | ||||
12022 | bool AddOverflow, ConversionOverflow; | ||||
12023 | APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) | ||||
12024 | .convert(ResultFXSema, &ConversionOverflow); | ||||
12025 | if ((AddOverflow || ConversionOverflow) && | ||||
12026 | !HandleOverflow(Info, E, Result, E->getType())) | ||||
12027 | return false; | ||||
12028 | return Success(Result, E); | ||||
12029 | } | ||||
12030 | default: | ||||
12031 | return false; | ||||
12032 | } | ||||
12033 | llvm_unreachable("Should've exited before this")::llvm::llvm_unreachable_internal("Should've exited before this" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12033); | ||||
12034 | } | ||||
12035 | |||||
12036 | //===----------------------------------------------------------------------===// | ||||
12037 | // Float Evaluation | ||||
12038 | //===----------------------------------------------------------------------===// | ||||
12039 | |||||
12040 | namespace { | ||||
12041 | class FloatExprEvaluator | ||||
12042 | : public ExprEvaluatorBase<FloatExprEvaluator> { | ||||
12043 | APFloat &Result; | ||||
12044 | public: | ||||
12045 | FloatExprEvaluator(EvalInfo &info, APFloat &result) | ||||
12046 | : ExprEvaluatorBaseTy(info), Result(result) {} | ||||
12047 | |||||
12048 | bool Success(const APValue &V, const Expr *e) { | ||||
12049 | Result = V.getFloat(); | ||||
12050 | return true; | ||||
12051 | } | ||||
12052 | |||||
12053 | bool ZeroInitialization(const Expr *E) { | ||||
12054 | Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); | ||||
12055 | return true; | ||||
12056 | } | ||||
12057 | |||||
12058 | bool VisitCallExpr(const CallExpr *E); | ||||
12059 | |||||
12060 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
12061 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
12062 | bool VisitFloatingLiteral(const FloatingLiteral *E); | ||||
12063 | bool VisitCastExpr(const CastExpr *E); | ||||
12064 | |||||
12065 | bool VisitUnaryReal(const UnaryOperator *E); | ||||
12066 | bool VisitUnaryImag(const UnaryOperator *E); | ||||
12067 | |||||
12068 | // FIXME: Missing: array subscript of vector, member of vector | ||||
12069 | }; | ||||
12070 | } // end anonymous namespace | ||||
12071 | |||||
12072 | static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { | ||||
12073 | assert(E->isRValue() && E->getType()->isRealFloatingType())((E->isRValue() && E->getType()->isRealFloatingType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isRealFloatingType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12073, __PRETTY_FUNCTION__)); | ||||
12074 | return FloatExprEvaluator(Info, Result).Visit(E); | ||||
12075 | } | ||||
12076 | |||||
12077 | static bool TryEvaluateBuiltinNaN(const ASTContext &Context, | ||||
12078 | QualType ResultTy, | ||||
12079 | const Expr *Arg, | ||||
12080 | bool SNaN, | ||||
12081 | llvm::APFloat &Result) { | ||||
12082 | const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); | ||||
12083 | if (!S) return false; | ||||
12084 | |||||
12085 | const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); | ||||
12086 | |||||
12087 | llvm::APInt fill; | ||||
12088 | |||||
12089 | // Treat empty strings as if they were zero. | ||||
12090 | if (S->getString().empty()) | ||||
12091 | fill = llvm::APInt(32, 0); | ||||
12092 | else if (S->getString().getAsInteger(0, fill)) | ||||
12093 | return false; | ||||
12094 | |||||
12095 | if (Context.getTargetInfo().isNan2008()) { | ||||
12096 | if (SNaN) | ||||
12097 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||
12098 | else | ||||
12099 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||
12100 | } else { | ||||
12101 | // Prior to IEEE 754-2008, architectures were allowed to choose whether | ||||
12102 | // the first bit of their significand was set for qNaN or sNaN. MIPS chose | ||||
12103 | // a different encoding to what became a standard in 2008, and for pre- | ||||
12104 | // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as | ||||
12105 | // sNaN. This is now known as "legacy NaN" encoding. | ||||
12106 | if (SNaN) | ||||
12107 | Result = llvm::APFloat::getQNaN(Sem, false, &fill); | ||||
12108 | else | ||||
12109 | Result = llvm::APFloat::getSNaN(Sem, false, &fill); | ||||
12110 | } | ||||
12111 | |||||
12112 | return true; | ||||
12113 | } | ||||
12114 | |||||
12115 | bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { | ||||
12116 | switch (E->getBuiltinCallee()) { | ||||
12117 | default: | ||||
12118 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
12119 | |||||
12120 | case Builtin::BI__builtin_huge_val: | ||||
12121 | case Builtin::BI__builtin_huge_valf: | ||||
12122 | case Builtin::BI__builtin_huge_vall: | ||||
12123 | case Builtin::BI__builtin_huge_valf128: | ||||
12124 | case Builtin::BI__builtin_inf: | ||||
12125 | case Builtin::BI__builtin_inff: | ||||
12126 | case Builtin::BI__builtin_infl: | ||||
12127 | case Builtin::BI__builtin_inff128: { | ||||
12128 | const llvm::fltSemantics &Sem = | ||||
12129 | Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||
12130 | Result = llvm::APFloat::getInf(Sem); | ||||
12131 | return true; | ||||
12132 | } | ||||
12133 | |||||
12134 | case Builtin::BI__builtin_nans: | ||||
12135 | case Builtin::BI__builtin_nansf: | ||||
12136 | case Builtin::BI__builtin_nansl: | ||||
12137 | case Builtin::BI__builtin_nansf128: | ||||
12138 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||
12139 | true, Result)) | ||||
12140 | return Error(E); | ||||
12141 | return true; | ||||
12142 | |||||
12143 | case Builtin::BI__builtin_nan: | ||||
12144 | case Builtin::BI__builtin_nanf: | ||||
12145 | case Builtin::BI__builtin_nanl: | ||||
12146 | case Builtin::BI__builtin_nanf128: | ||||
12147 | // If this is __builtin_nan() turn this into a nan, otherwise we | ||||
12148 | // can't constant fold it. | ||||
12149 | if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), | ||||
12150 | false, Result)) | ||||
12151 | return Error(E); | ||||
12152 | return true; | ||||
12153 | |||||
12154 | case Builtin::BI__builtin_fabs: | ||||
12155 | case Builtin::BI__builtin_fabsf: | ||||
12156 | case Builtin::BI__builtin_fabsl: | ||||
12157 | case Builtin::BI__builtin_fabsf128: | ||||
12158 | if (!EvaluateFloat(E->getArg(0), Result, Info)) | ||||
12159 | return false; | ||||
12160 | |||||
12161 | if (Result.isNegative()) | ||||
12162 | Result.changeSign(); | ||||
12163 | return true; | ||||
12164 | |||||
12165 | // FIXME: Builtin::BI__builtin_powi | ||||
12166 | // FIXME: Builtin::BI__builtin_powif | ||||
12167 | // FIXME: Builtin::BI__builtin_powil | ||||
12168 | |||||
12169 | case Builtin::BI__builtin_copysign: | ||||
12170 | case Builtin::BI__builtin_copysignf: | ||||
12171 | case Builtin::BI__builtin_copysignl: | ||||
12172 | case Builtin::BI__builtin_copysignf128: { | ||||
12173 | APFloat RHS(0.); | ||||
12174 | if (!EvaluateFloat(E->getArg(0), Result, Info) || | ||||
12175 | !EvaluateFloat(E->getArg(1), RHS, Info)) | ||||
12176 | return false; | ||||
12177 | Result.copySign(RHS); | ||||
12178 | return true; | ||||
12179 | } | ||||
12180 | } | ||||
12181 | } | ||||
12182 | |||||
12183 | bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { | ||||
12184 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
12185 | ComplexValue CV; | ||||
12186 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||
12187 | return false; | ||||
12188 | Result = CV.FloatReal; | ||||
12189 | return true; | ||||
12190 | } | ||||
12191 | |||||
12192 | return Visit(E->getSubExpr()); | ||||
12193 | } | ||||
12194 | |||||
12195 | bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { | ||||
12196 | if (E->getSubExpr()->getType()->isAnyComplexType()) { | ||||
12197 | ComplexValue CV; | ||||
12198 | if (!EvaluateComplex(E->getSubExpr(), CV, Info)) | ||||
12199 | return false; | ||||
12200 | Result = CV.FloatImag; | ||||
12201 | return true; | ||||
12202 | } | ||||
12203 | |||||
12204 | VisitIgnoredValue(E->getSubExpr()); | ||||
12205 | const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); | ||||
12206 | Result = llvm::APFloat::getZero(Sem); | ||||
12207 | return true; | ||||
12208 | } | ||||
12209 | |||||
12210 | bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
12211 | switch (E->getOpcode()) { | ||||
12212 | default: return Error(E); | ||||
12213 | case UO_Plus: | ||||
12214 | return EvaluateFloat(E->getSubExpr(), Result, Info); | ||||
12215 | case UO_Minus: | ||||
12216 | if (!EvaluateFloat(E->getSubExpr(), Result, Info)) | ||||
12217 | return false; | ||||
12218 | Result.changeSign(); | ||||
12219 | return true; | ||||
12220 | } | ||||
12221 | } | ||||
12222 | |||||
12223 | bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
12224 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||
12225 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
12226 | |||||
12227 | APFloat RHS(0.0); | ||||
12228 | bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); | ||||
12229 | if (!LHSOK && !Info.noteFailure()) | ||||
12230 | return false; | ||||
12231 | return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && | ||||
12232 | handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); | ||||
12233 | } | ||||
12234 | |||||
12235 | bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { | ||||
12236 | Result = E->getValue(); | ||||
12237 | return true; | ||||
12238 | } | ||||
12239 | |||||
12240 | bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
12241 | const Expr* SubExpr = E->getSubExpr(); | ||||
12242 | |||||
12243 | switch (E->getCastKind()) { | ||||
12244 | default: | ||||
12245 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
12246 | |||||
12247 | case CK_IntegralToFloating: { | ||||
12248 | APSInt IntResult; | ||||
12249 | return EvaluateInteger(SubExpr, IntResult, Info) && | ||||
12250 | HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, | ||||
12251 | E->getType(), Result); | ||||
12252 | } | ||||
12253 | |||||
12254 | case CK_FloatingCast: { | ||||
12255 | if (!Visit(SubExpr)) | ||||
12256 | return false; | ||||
12257 | return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), | ||||
12258 | Result); | ||||
12259 | } | ||||
12260 | |||||
12261 | case CK_FloatingComplexToReal: { | ||||
12262 | ComplexValue V; | ||||
12263 | if (!EvaluateComplex(SubExpr, V, Info)) | ||||
12264 | return false; | ||||
12265 | Result = V.getComplexFloatReal(); | ||||
12266 | return true; | ||||
12267 | } | ||||
12268 | } | ||||
12269 | } | ||||
12270 | |||||
12271 | //===----------------------------------------------------------------------===// | ||||
12272 | // Complex Evaluation (for float and integer) | ||||
12273 | //===----------------------------------------------------------------------===// | ||||
12274 | |||||
12275 | namespace { | ||||
12276 | class ComplexExprEvaluator | ||||
12277 | : public ExprEvaluatorBase<ComplexExprEvaluator> { | ||||
12278 | ComplexValue &Result; | ||||
12279 | |||||
12280 | public: | ||||
12281 | ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) | ||||
12282 | : ExprEvaluatorBaseTy(info), Result(Result) {} | ||||
12283 | |||||
12284 | bool Success(const APValue &V, const Expr *e) { | ||||
12285 | Result.setFrom(V); | ||||
12286 | return true; | ||||
12287 | } | ||||
12288 | |||||
12289 | bool ZeroInitialization(const Expr *E); | ||||
12290 | |||||
12291 | //===--------------------------------------------------------------------===// | ||||
12292 | // Visitor Methods | ||||
12293 | //===--------------------------------------------------------------------===// | ||||
12294 | |||||
12295 | bool VisitImaginaryLiteral(const ImaginaryLiteral *E); | ||||
12296 | bool VisitCastExpr(const CastExpr *E); | ||||
12297 | bool VisitBinaryOperator(const BinaryOperator *E); | ||||
12298 | bool VisitUnaryOperator(const UnaryOperator *E); | ||||
12299 | bool VisitInitListExpr(const InitListExpr *E); | ||||
12300 | }; | ||||
12301 | } // end anonymous namespace | ||||
12302 | |||||
12303 | static bool EvaluateComplex(const Expr *E, ComplexValue &Result, | ||||
12304 | EvalInfo &Info) { | ||||
12305 | assert(E->isRValue() && E->getType()->isAnyComplexType())((E->isRValue() && E->getType()->isAnyComplexType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAnyComplexType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12305, __PRETTY_FUNCTION__)); | ||||
12306 | return ComplexExprEvaluator(Info, Result).Visit(E); | ||||
12307 | } | ||||
12308 | |||||
12309 | bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { | ||||
12310 | QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
12311 | if (ElemTy->isRealFloatingType()) { | ||||
12312 | Result.makeComplexFloat(); | ||||
12313 | APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); | ||||
12314 | Result.FloatReal = Zero; | ||||
12315 | Result.FloatImag = Zero; | ||||
12316 | } else { | ||||
12317 | Result.makeComplexInt(); | ||||
12318 | APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); | ||||
12319 | Result.IntReal = Zero; | ||||
12320 | Result.IntImag = Zero; | ||||
12321 | } | ||||
12322 | return true; | ||||
12323 | } | ||||
12324 | |||||
12325 | bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { | ||||
12326 | const Expr* SubExpr = E->getSubExpr(); | ||||
12327 | |||||
12328 | if (SubExpr->getType()->isRealFloatingType()) { | ||||
12329 | Result.makeComplexFloat(); | ||||
12330 | APFloat &Imag = Result.FloatImag; | ||||
12331 | if (!EvaluateFloat(SubExpr, Imag, Info)) | ||||
12332 | return false; | ||||
12333 | |||||
12334 | Result.FloatReal = APFloat(Imag.getSemantics()); | ||||
12335 | return true; | ||||
12336 | } else { | ||||
12337 | assert(SubExpr->getType()->isIntegerType() &&((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal." ) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12338, __PRETTY_FUNCTION__)) | ||||
12338 | "Unexpected imaginary literal.")((SubExpr->getType()->isIntegerType() && "Unexpected imaginary literal." ) ? static_cast<void> (0) : __assert_fail ("SubExpr->getType()->isIntegerType() && \"Unexpected imaginary literal.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12338, __PRETTY_FUNCTION__)); | ||||
12339 | |||||
12340 | Result.makeComplexInt(); | ||||
12341 | APSInt &Imag = Result.IntImag; | ||||
12342 | if (!EvaluateInteger(SubExpr, Imag, Info)) | ||||
12343 | return false; | ||||
12344 | |||||
12345 | Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); | ||||
12346 | return true; | ||||
12347 | } | ||||
12348 | } | ||||
12349 | |||||
12350 | bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { | ||||
12351 | |||||
12352 | switch (E->getCastKind()) { | ||||
12353 | case CK_BitCast: | ||||
12354 | case CK_BaseToDerived: | ||||
12355 | case CK_DerivedToBase: | ||||
12356 | case CK_UncheckedDerivedToBase: | ||||
12357 | case CK_Dynamic: | ||||
12358 | case CK_ToUnion: | ||||
12359 | case CK_ArrayToPointerDecay: | ||||
12360 | case CK_FunctionToPointerDecay: | ||||
12361 | case CK_NullToPointer: | ||||
12362 | case CK_NullToMemberPointer: | ||||
12363 | case CK_BaseToDerivedMemberPointer: | ||||
12364 | case CK_DerivedToBaseMemberPointer: | ||||
12365 | case CK_MemberPointerToBoolean: | ||||
12366 | case CK_ReinterpretMemberPointer: | ||||
12367 | case CK_ConstructorConversion: | ||||
12368 | case CK_IntegralToPointer: | ||||
12369 | case CK_PointerToIntegral: | ||||
12370 | case CK_PointerToBoolean: | ||||
12371 | case CK_ToVoid: | ||||
12372 | case CK_VectorSplat: | ||||
12373 | case CK_IntegralCast: | ||||
12374 | case CK_BooleanToSignedIntegral: | ||||
12375 | case CK_IntegralToBoolean: | ||||
12376 | case CK_IntegralToFloating: | ||||
12377 | case CK_FloatingToIntegral: | ||||
12378 | case CK_FloatingToBoolean: | ||||
12379 | case CK_FloatingCast: | ||||
12380 | case CK_CPointerToObjCPointerCast: | ||||
12381 | case CK_BlockPointerToObjCPointerCast: | ||||
12382 | case CK_AnyPointerToBlockPointerCast: | ||||
12383 | case CK_ObjCObjectLValueCast: | ||||
12384 | case CK_FloatingComplexToReal: | ||||
12385 | case CK_FloatingComplexToBoolean: | ||||
12386 | case CK_IntegralComplexToReal: | ||||
12387 | case CK_IntegralComplexToBoolean: | ||||
12388 | case CK_ARCProduceObject: | ||||
12389 | case CK_ARCConsumeObject: | ||||
12390 | case CK_ARCReclaimReturnedObject: | ||||
12391 | case CK_ARCExtendBlockObject: | ||||
12392 | case CK_CopyAndAutoreleaseBlockObject: | ||||
12393 | case CK_BuiltinFnToFnPtr: | ||||
12394 | case CK_ZeroToOCLOpaqueType: | ||||
12395 | case CK_NonAtomicToAtomic: | ||||
12396 | case CK_AddressSpaceConversion: | ||||
12397 | case CK_IntToOCLSampler: | ||||
12398 | case CK_FixedPointCast: | ||||
12399 | case CK_FixedPointToBoolean: | ||||
12400 | case CK_FixedPointToIntegral: | ||||
12401 | case CK_IntegralToFixedPoint: | ||||
12402 | llvm_unreachable("invalid cast kind for complex value")::llvm::llvm_unreachable_internal("invalid cast kind for complex value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12402); | ||||
12403 | |||||
12404 | case CK_LValueToRValue: | ||||
12405 | case CK_AtomicToNonAtomic: | ||||
12406 | case CK_NoOp: | ||||
12407 | case CK_LValueToRValueBitCast: | ||||
12408 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
12409 | |||||
12410 | case CK_Dependent: | ||||
12411 | case CK_LValueBitCast: | ||||
12412 | case CK_UserDefinedConversion: | ||||
12413 | return Error(E); | ||||
12414 | |||||
12415 | case CK_FloatingRealToComplex: { | ||||
12416 | APFloat &Real = Result.FloatReal; | ||||
12417 | if (!EvaluateFloat(E->getSubExpr(), Real, Info)) | ||||
12418 | return false; | ||||
12419 | |||||
12420 | Result.makeComplexFloat(); | ||||
12421 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||
12422 | return true; | ||||
12423 | } | ||||
12424 | |||||
12425 | case CK_FloatingComplexCast: { | ||||
12426 | if (!Visit(E->getSubExpr())) | ||||
12427 | return false; | ||||
12428 | |||||
12429 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||
12430 | QualType From | ||||
12431 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||
12432 | |||||
12433 | return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && | ||||
12434 | HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); | ||||
12435 | } | ||||
12436 | |||||
12437 | case CK_FloatingComplexToIntegralComplex: { | ||||
12438 | if (!Visit(E->getSubExpr())) | ||||
12439 | return false; | ||||
12440 | |||||
12441 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||
12442 | QualType From | ||||
12443 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||
12444 | Result.makeComplexInt(); | ||||
12445 | return HandleFloatToIntCast(Info, E, From, Result.FloatReal, | ||||
12446 | To, Result.IntReal) && | ||||
12447 | HandleFloatToIntCast(Info, E, From, Result.FloatImag, | ||||
12448 | To, Result.IntImag); | ||||
12449 | } | ||||
12450 | |||||
12451 | case CK_IntegralRealToComplex: { | ||||
12452 | APSInt &Real = Result.IntReal; | ||||
12453 | if (!EvaluateInteger(E->getSubExpr(), Real, Info)) | ||||
12454 | return false; | ||||
12455 | |||||
12456 | Result.makeComplexInt(); | ||||
12457 | Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); | ||||
12458 | return true; | ||||
12459 | } | ||||
12460 | |||||
12461 | case CK_IntegralComplexCast: { | ||||
12462 | if (!Visit(E->getSubExpr())) | ||||
12463 | return false; | ||||
12464 | |||||
12465 | QualType To = E->getType()->getAs<ComplexType>()->getElementType(); | ||||
12466 | QualType From | ||||
12467 | = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); | ||||
12468 | |||||
12469 | Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); | ||||
12470 | Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); | ||||
12471 | return true; | ||||
12472 | } | ||||
12473 | |||||
12474 | case CK_IntegralComplexToFloatingComplex: { | ||||
12475 | if (!Visit(E->getSubExpr())) | ||||
12476 | return false; | ||||
12477 | |||||
12478 | QualType To = E->getType()->castAs<ComplexType>()->getElementType(); | ||||
12479 | QualType From | ||||
12480 | = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); | ||||
12481 | Result.makeComplexFloat(); | ||||
12482 | return HandleIntToFloatCast(Info, E, From, Result.IntReal, | ||||
12483 | To, Result.FloatReal) && | ||||
12484 | HandleIntToFloatCast(Info, E, From, Result.IntImag, | ||||
12485 | To, Result.FloatImag); | ||||
12486 | } | ||||
12487 | } | ||||
12488 | |||||
12489 | llvm_unreachable("unknown cast resulting in complex value")::llvm::llvm_unreachable_internal("unknown cast resulting in complex value" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12489); | ||||
12490 | } | ||||
12491 | |||||
12492 | bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { | ||||
12493 | if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) | ||||
12494 | return ExprEvaluatorBaseTy::VisitBinaryOperator(E); | ||||
12495 | |||||
12496 | // Track whether the LHS or RHS is real at the type system level. When this is | ||||
12497 | // the case we can simplify our evaluation strategy. | ||||
12498 | bool LHSReal = false, RHSReal = false; | ||||
12499 | |||||
12500 | bool LHSOK; | ||||
12501 | if (E->getLHS()->getType()->isRealFloatingType()) { | ||||
12502 | LHSReal = true; | ||||
12503 | APFloat &Real = Result.FloatReal; | ||||
12504 | LHSOK = EvaluateFloat(E->getLHS(), Real, Info); | ||||
12505 | if (LHSOK) { | ||||
12506 | Result.makeComplexFloat(); | ||||
12507 | Result.FloatImag = APFloat(Real.getSemantics()); | ||||
12508 | } | ||||
12509 | } else { | ||||
12510 | LHSOK = Visit(E->getLHS()); | ||||
12511 | } | ||||
12512 | if (!LHSOK && !Info.noteFailure()) | ||||
12513 | return false; | ||||
12514 | |||||
12515 | ComplexValue RHS; | ||||
12516 | if (E->getRHS()->getType()->isRealFloatingType()) { | ||||
12517 | RHSReal = true; | ||||
12518 | APFloat &Real = RHS.FloatReal; | ||||
12519 | if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) | ||||
12520 | return false; | ||||
12521 | RHS.makeComplexFloat(); | ||||
12522 | RHS.FloatImag = APFloat(Real.getSemantics()); | ||||
12523 | } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) | ||||
12524 | return false; | ||||
12525 | |||||
12526 | assert(!(LHSReal && RHSReal) &&((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real." ) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12527, __PRETTY_FUNCTION__)) | ||||
12527 | "Cannot have both operands of a complex operation be real.")((!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real." ) ? static_cast<void> (0) : __assert_fail ("!(LHSReal && RHSReal) && \"Cannot have both operands of a complex operation be real.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12527, __PRETTY_FUNCTION__)); | ||||
12528 | switch (E->getOpcode()) { | ||||
12529 | default: return Error(E); | ||||
12530 | case BO_Add: | ||||
12531 | if (Result.isComplexFloat()) { | ||||
12532 | Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), | ||||
12533 | APFloat::rmNearestTiesToEven); | ||||
12534 | if (LHSReal) | ||||
12535 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||
12536 | else if (!RHSReal) | ||||
12537 | Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), | ||||
12538 | APFloat::rmNearestTiesToEven); | ||||
12539 | } else { | ||||
12540 | Result.getComplexIntReal() += RHS.getComplexIntReal(); | ||||
12541 | Result.getComplexIntImag() += RHS.getComplexIntImag(); | ||||
12542 | } | ||||
12543 | break; | ||||
12544 | case BO_Sub: | ||||
12545 | if (Result.isComplexFloat()) { | ||||
12546 | Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), | ||||
12547 | APFloat::rmNearestTiesToEven); | ||||
12548 | if (LHSReal) { | ||||
12549 | Result.getComplexFloatImag() = RHS.getComplexFloatImag(); | ||||
12550 | Result.getComplexFloatImag().changeSign(); | ||||
12551 | } else if (!RHSReal) { | ||||
12552 | Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), | ||||
12553 | APFloat::rmNearestTiesToEven); | ||||
12554 | } | ||||
12555 | } else { | ||||
12556 | Result.getComplexIntReal() -= RHS.getComplexIntReal(); | ||||
12557 | Result.getComplexIntImag() -= RHS.getComplexIntImag(); | ||||
12558 | } | ||||
12559 | break; | ||||
12560 | case BO_Mul: | ||||
12561 | if (Result.isComplexFloat()) { | ||||
12562 | // This is an implementation of complex multiplication according to the | ||||
12563 | // constraints laid out in C11 Annex G. The implementation uses the | ||||
12564 | // following naming scheme: | ||||
12565 | // (a + ib) * (c + id) | ||||
12566 | ComplexValue LHS = Result; | ||||
12567 | APFloat &A = LHS.getComplexFloatReal(); | ||||
12568 | APFloat &B = LHS.getComplexFloatImag(); | ||||
12569 | APFloat &C = RHS.getComplexFloatReal(); | ||||
12570 | APFloat &D = RHS.getComplexFloatImag(); | ||||
12571 | APFloat &ResR = Result.getComplexFloatReal(); | ||||
12572 | APFloat &ResI = Result.getComplexFloatImag(); | ||||
12573 | if (LHSReal) { | ||||
12574 | assert(!RHSReal && "Cannot have two real operands for a complex op!")((!RHSReal && "Cannot have two real operands for a complex op!" ) ? static_cast<void> (0) : __assert_fail ("!RHSReal && \"Cannot have two real operands for a complex op!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12574, __PRETTY_FUNCTION__)); | ||||
12575 | ResR = A * C; | ||||
12576 | ResI = A * D; | ||||
12577 | } else if (RHSReal) { | ||||
12578 | ResR = C * A; | ||||
12579 | ResI = C * B; | ||||
12580 | } else { | ||||
12581 | // In the fully general case, we need to handle NaNs and infinities | ||||
12582 | // robustly. | ||||
12583 | APFloat AC = A * C; | ||||
12584 | APFloat BD = B * D; | ||||
12585 | APFloat AD = A * D; | ||||
12586 | APFloat BC = B * C; | ||||
12587 | ResR = AC - BD; | ||||
12588 | ResI = AD + BC; | ||||
12589 | if (ResR.isNaN() && ResI.isNaN()) { | ||||
12590 | bool Recalc = false; | ||||
12591 | if (A.isInfinity() || B.isInfinity()) { | ||||
12592 | A = APFloat::copySign( | ||||
12593 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||
12594 | B = APFloat::copySign( | ||||
12595 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||
12596 | if (C.isNaN()) | ||||
12597 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||
12598 | if (D.isNaN()) | ||||
12599 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||
12600 | Recalc = true; | ||||
12601 | } | ||||
12602 | if (C.isInfinity() || D.isInfinity()) { | ||||
12603 | C = APFloat::copySign( | ||||
12604 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||
12605 | D = APFloat::copySign( | ||||
12606 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||
12607 | if (A.isNaN()) | ||||
12608 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||
12609 | if (B.isNaN()) | ||||
12610 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||
12611 | Recalc = true; | ||||
12612 | } | ||||
12613 | if (!Recalc && (AC.isInfinity() || BD.isInfinity() || | ||||
12614 | AD.isInfinity() || BC.isInfinity())) { | ||||
12615 | if (A.isNaN()) | ||||
12616 | A = APFloat::copySign(APFloat(A.getSemantics()), A); | ||||
12617 | if (B.isNaN()) | ||||
12618 | B = APFloat::copySign(APFloat(B.getSemantics()), B); | ||||
12619 | if (C.isNaN()) | ||||
12620 | C = APFloat::copySign(APFloat(C.getSemantics()), C); | ||||
12621 | if (D.isNaN()) | ||||
12622 | D = APFloat::copySign(APFloat(D.getSemantics()), D); | ||||
12623 | Recalc = true; | ||||
12624 | } | ||||
12625 | if (Recalc) { | ||||
12626 | ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); | ||||
12627 | ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); | ||||
12628 | } | ||||
12629 | } | ||||
12630 | } | ||||
12631 | } else { | ||||
12632 | ComplexValue LHS = Result; | ||||
12633 | Result.getComplexIntReal() = | ||||
12634 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() - | ||||
12635 | LHS.getComplexIntImag() * RHS.getComplexIntImag()); | ||||
12636 | Result.getComplexIntImag() = | ||||
12637 | (LHS.getComplexIntReal() * RHS.getComplexIntImag() + | ||||
12638 | LHS.getComplexIntImag() * RHS.getComplexIntReal()); | ||||
12639 | } | ||||
12640 | break; | ||||
12641 | case BO_Div: | ||||
12642 | if (Result.isComplexFloat()) { | ||||
12643 | // This is an implementation of complex division according to the | ||||
12644 | // constraints laid out in C11 Annex G. The implementation uses the | ||||
12645 | // following naming scheme: | ||||
12646 | // (a + ib) / (c + id) | ||||
12647 | ComplexValue LHS = Result; | ||||
12648 | APFloat &A = LHS.getComplexFloatReal(); | ||||
12649 | APFloat &B = LHS.getComplexFloatImag(); | ||||
12650 | APFloat &C = RHS.getComplexFloatReal(); | ||||
12651 | APFloat &D = RHS.getComplexFloatImag(); | ||||
12652 | APFloat &ResR = Result.getComplexFloatReal(); | ||||
12653 | APFloat &ResI = Result.getComplexFloatImag(); | ||||
12654 | if (RHSReal) { | ||||
12655 | ResR = A / C; | ||||
12656 | ResI = B / C; | ||||
12657 | } else { | ||||
12658 | if (LHSReal) { | ||||
12659 | // No real optimizations we can do here, stub out with zero. | ||||
12660 | B = APFloat::getZero(A.getSemantics()); | ||||
12661 | } | ||||
12662 | int DenomLogB = 0; | ||||
12663 | APFloat MaxCD = maxnum(abs(C), abs(D)); | ||||
12664 | if (MaxCD.isFinite()) { | ||||
12665 | DenomLogB = ilogb(MaxCD); | ||||
12666 | C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||
12667 | D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); | ||||
12668 | } | ||||
12669 | APFloat Denom = C * C + D * D; | ||||
12670 | ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, | ||||
12671 | APFloat::rmNearestTiesToEven); | ||||
12672 | ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, | ||||
12673 | APFloat::rmNearestTiesToEven); | ||||
12674 | if (ResR.isNaN() && ResI.isNaN()) { | ||||
12675 | if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { | ||||
12676 | ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; | ||||
12677 | ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; | ||||
12678 | } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && | ||||
12679 | D.isFinite()) { | ||||
12680 | A = APFloat::copySign( | ||||
12681 | APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); | ||||
12682 | B = APFloat::copySign( | ||||
12683 | APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); | ||||
12684 | ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); | ||||
12685 | ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); | ||||
12686 | } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { | ||||
12687 | C = APFloat::copySign( | ||||
12688 | APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); | ||||
12689 | D = APFloat::copySign( | ||||
12690 | APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); | ||||
12691 | ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); | ||||
12692 | ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); | ||||
12693 | } | ||||
12694 | } | ||||
12695 | } | ||||
12696 | } else { | ||||
12697 | if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) | ||||
12698 | return Error(E, diag::note_expr_divide_by_zero); | ||||
12699 | |||||
12700 | ComplexValue LHS = Result; | ||||
12701 | APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||
12702 | RHS.getComplexIntImag() * RHS.getComplexIntImag(); | ||||
12703 | Result.getComplexIntReal() = | ||||
12704 | (LHS.getComplexIntReal() * RHS.getComplexIntReal() + | ||||
12705 | LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; | ||||
12706 | Result.getComplexIntImag() = | ||||
12707 | (LHS.getComplexIntImag() * RHS.getComplexIntReal() - | ||||
12708 | LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; | ||||
12709 | } | ||||
12710 | break; | ||||
12711 | } | ||||
12712 | |||||
12713 | return true; | ||||
12714 | } | ||||
12715 | |||||
12716 | bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { | ||||
12717 | // Get the operand value into 'Result'. | ||||
12718 | if (!Visit(E->getSubExpr())) | ||||
12719 | return false; | ||||
12720 | |||||
12721 | switch (E->getOpcode()) { | ||||
12722 | default: | ||||
12723 | return Error(E); | ||||
12724 | case UO_Extension: | ||||
12725 | return true; | ||||
12726 | case UO_Plus: | ||||
12727 | // The result is always just the subexpr. | ||||
12728 | return true; | ||||
12729 | case UO_Minus: | ||||
12730 | if (Result.isComplexFloat()) { | ||||
12731 | Result.getComplexFloatReal().changeSign(); | ||||
12732 | Result.getComplexFloatImag().changeSign(); | ||||
12733 | } | ||||
12734 | else { | ||||
12735 | Result.getComplexIntReal() = -Result.getComplexIntReal(); | ||||
12736 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||
12737 | } | ||||
12738 | return true; | ||||
12739 | case UO_Not: | ||||
12740 | if (Result.isComplexFloat()) | ||||
12741 | Result.getComplexFloatImag().changeSign(); | ||||
12742 | else | ||||
12743 | Result.getComplexIntImag() = -Result.getComplexIntImag(); | ||||
12744 | return true; | ||||
12745 | } | ||||
12746 | } | ||||
12747 | |||||
12748 | bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { | ||||
12749 | if (E->getNumInits() == 2) { | ||||
12750 | if (E->getType()->isComplexType()) { | ||||
12751 | Result.makeComplexFloat(); | ||||
12752 | if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) | ||||
12753 | return false; | ||||
12754 | if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) | ||||
12755 | return false; | ||||
12756 | } else { | ||||
12757 | Result.makeComplexInt(); | ||||
12758 | if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) | ||||
12759 | return false; | ||||
12760 | if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) | ||||
12761 | return false; | ||||
12762 | } | ||||
12763 | return true; | ||||
12764 | } | ||||
12765 | return ExprEvaluatorBaseTy::VisitInitListExpr(E); | ||||
12766 | } | ||||
12767 | |||||
12768 | //===----------------------------------------------------------------------===// | ||||
12769 | // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic | ||||
12770 | // implicit conversion. | ||||
12771 | //===----------------------------------------------------------------------===// | ||||
12772 | |||||
12773 | namespace { | ||||
12774 | class AtomicExprEvaluator : | ||||
12775 | public ExprEvaluatorBase<AtomicExprEvaluator> { | ||||
12776 | const LValue *This; | ||||
12777 | APValue &Result; | ||||
12778 | public: | ||||
12779 | AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) | ||||
12780 | : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} | ||||
12781 | |||||
12782 | bool Success(const APValue &V, const Expr *E) { | ||||
12783 | Result = V; | ||||
12784 | return true; | ||||
12785 | } | ||||
12786 | |||||
12787 | bool ZeroInitialization(const Expr *E) { | ||||
12788 | ImplicitValueInitExpr VIE( | ||||
12789 | E->getType()->castAs<AtomicType>()->getValueType()); | ||||
12790 | // For atomic-qualified class (and array) types in C++, initialize the | ||||
12791 | // _Atomic-wrapped subobject directly, in-place. | ||||
12792 | return This ? EvaluateInPlace(Result, Info, *This, &VIE) | ||||
12793 | : Evaluate(Result, Info, &VIE); | ||||
12794 | } | ||||
12795 | |||||
12796 | bool VisitCastExpr(const CastExpr *E) { | ||||
12797 | switch (E->getCastKind()) { | ||||
12798 | default: | ||||
12799 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
12800 | case CK_NonAtomicToAtomic: | ||||
12801 | return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) | ||||
12802 | : Evaluate(Result, Info, E->getSubExpr()); | ||||
12803 | } | ||||
12804 | } | ||||
12805 | }; | ||||
12806 | } // end anonymous namespace | ||||
12807 | |||||
12808 | static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, | ||||
12809 | EvalInfo &Info) { | ||||
12810 | assert(E->isRValue() && E->getType()->isAtomicType())((E->isRValue() && E->getType()->isAtomicType ()) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isAtomicType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12810, __PRETTY_FUNCTION__)); | ||||
12811 | return AtomicExprEvaluator(Info, This, Result).Visit(E); | ||||
12812 | } | ||||
12813 | |||||
12814 | //===----------------------------------------------------------------------===// | ||||
12815 | // Void expression evaluation, primarily for a cast to void on the LHS of a | ||||
12816 | // comma operator | ||||
12817 | //===----------------------------------------------------------------------===// | ||||
12818 | |||||
12819 | namespace { | ||||
12820 | class VoidExprEvaluator | ||||
12821 | : public ExprEvaluatorBase<VoidExprEvaluator> { | ||||
12822 | public: | ||||
12823 | VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} | ||||
12824 | |||||
12825 | bool Success(const APValue &V, const Expr *e) { return true; } | ||||
12826 | |||||
12827 | bool ZeroInitialization(const Expr *E) { return true; } | ||||
12828 | |||||
12829 | bool VisitCastExpr(const CastExpr *E) { | ||||
12830 | switch (E->getCastKind()) { | ||||
12831 | default: | ||||
12832 | return ExprEvaluatorBaseTy::VisitCastExpr(E); | ||||
12833 | case CK_ToVoid: | ||||
12834 | VisitIgnoredValue(E->getSubExpr()); | ||||
12835 | return true; | ||||
12836 | } | ||||
12837 | } | ||||
12838 | |||||
12839 | bool VisitCallExpr(const CallExpr *E) { | ||||
12840 | switch (E->getBuiltinCallee()) { | ||||
12841 | default: | ||||
12842 | return ExprEvaluatorBaseTy::VisitCallExpr(E); | ||||
12843 | case Builtin::BI__assume: | ||||
12844 | case Builtin::BI__builtin_assume: | ||||
12845 | // The argument is not evaluated! | ||||
12846 | return true; | ||||
12847 | } | ||||
12848 | } | ||||
12849 | |||||
12850 | bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); | ||||
12851 | }; | ||||
12852 | } // end anonymous namespace | ||||
12853 | |||||
12854 | static bool hasVirtualDestructor(QualType T) { | ||||
12855 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | ||||
12856 | if (CXXDestructorDecl *DD = RD->getDestructor()) | ||||
12857 | return DD->isVirtual(); | ||||
12858 | return false; | ||||
12859 | } | ||||
12860 | |||||
12861 | bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { | ||||
12862 | // We cannot speculatively evaluate a delete expression. | ||||
12863 | if (Info.SpeculativeEvaluationDepth) | ||||
12864 | return false; | ||||
12865 | |||||
12866 | FunctionDecl *OperatorDelete = E->getOperatorDelete(); | ||||
12867 | if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { | ||||
12868 | Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) | ||||
12869 | << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; | ||||
12870 | return false; | ||||
12871 | } | ||||
12872 | |||||
12873 | const Expr *Arg = E->getArgument(); | ||||
12874 | |||||
12875 | LValue Pointer; | ||||
12876 | if (!EvaluatePointer(Arg, Pointer, Info)) | ||||
12877 | return false; | ||||
12878 | if (Pointer.Designator.Invalid) | ||||
12879 | return false; | ||||
12880 | |||||
12881 | // Deleting a null pointer has no effect. | ||||
12882 | if (Pointer.isNullPointer()) { | ||||
12883 | // This is the only case where we need to produce an extension warning: | ||||
12884 | // the only other way we can succeed is if we find a dynamic allocation, | ||||
12885 | // and we will have warned when we allocated it in that case. | ||||
12886 | if (!Info.getLangOpts().CPlusPlus2a) | ||||
12887 | Info.CCEDiag(E, diag::note_constexpr_new); | ||||
12888 | return true; | ||||
12889 | } | ||||
12890 | |||||
12891 | auto PointerAsString = [&] { | ||||
12892 | APValue Printable; | ||||
12893 | Pointer.moveInto(Printable); | ||||
12894 | return Printable.getAsString(Info.Ctx, Arg->getType()); | ||||
12895 | }; | ||||
12896 | |||||
12897 | DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); | ||||
12898 | if (!DA) { | ||||
12899 | Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) | ||||
12900 | << PointerAsString(); | ||||
12901 | if (Pointer.Base) | ||||
12902 | NoteLValueLocation(Info, Pointer.Base); | ||||
12903 | return false; | ||||
12904 | } | ||||
12905 | QualType AllocType = Pointer.Base.getDynamicAllocType(); | ||||
12906 | |||||
12907 | Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); | ||||
12908 | if (!Alloc) { | ||||
12909 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||
12910 | return false; | ||||
12911 | } | ||||
12912 | |||||
12913 | if (E->isArrayForm() != AllocType->isConstantArrayType()) { | ||||
12914 | Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) | ||||
12915 | << E->isArrayForm() << AllocType; | ||||
12916 | NoteLValueLocation(Info, Pointer.Base); | ||||
12917 | return false; | ||||
12918 | } | ||||
12919 | |||||
12920 | bool Subobject = false; | ||||
12921 | if (E->isArrayForm()) { | ||||
12922 | Subobject = Pointer.Designator.Entries.size() != 1 || | ||||
12923 | Pointer.Designator.Entries[0].getAsArrayIndex() != 0; | ||||
12924 | } else { | ||||
12925 | Subobject = Pointer.Designator.MostDerivedPathLength != 0 || | ||||
12926 | Pointer.Designator.isOnePastTheEnd(); | ||||
12927 | } | ||||
12928 | if (Subobject) { | ||||
12929 | Info.FFDiag(E, diag::note_constexpr_delete_subobject) | ||||
12930 | << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); | ||||
12931 | return false; | ||||
12932 | } | ||||
12933 | |||||
12934 | // For the non-array case, the designator must be empty if the static type | ||||
12935 | // does not have a virtual destructor. | ||||
12936 | if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && | ||||
12937 | !hasVirtualDestructor(Arg->getType()->getPointeeType())) { | ||||
12938 | Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) | ||||
12939 | << Arg->getType()->getPointeeType() << AllocType; | ||||
12940 | return false; | ||||
12941 | } | ||||
12942 | |||||
12943 | if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), | ||||
12944 | (*Alloc)->Value, AllocType)) | ||||
12945 | return false; | ||||
12946 | |||||
12947 | if (!Info.HeapAllocs.erase(DA)) { | ||||
12948 | // The element was already erased. This means the destructor call also | ||||
12949 | // deleted the object. | ||||
12950 | // FIXME: This probably results in undefined behavior before we get this | ||||
12951 | // far, and should be diagnosed elsewhere first. | ||||
12952 | Info.FFDiag(E, diag::note_constexpr_double_delete); | ||||
12953 | return false; | ||||
12954 | } | ||||
12955 | |||||
12956 | return true; | ||||
12957 | } | ||||
12958 | |||||
12959 | static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { | ||||
12960 | assert(E->isRValue() && E->getType()->isVoidType())((E->isRValue() && E->getType()->isVoidType( )) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && E->getType()->isVoidType()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 12960, __PRETTY_FUNCTION__)); | ||||
12961 | return VoidExprEvaluator(Info).Visit(E); | ||||
12962 | } | ||||
12963 | |||||
12964 | //===----------------------------------------------------------------------===// | ||||
12965 | // Top level Expr::EvaluateAsRValue method. | ||||
12966 | //===----------------------------------------------------------------------===// | ||||
12967 | |||||
12968 | static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { | ||||
12969 | // In C, function designators are not lvalues, but we evaluate them as if they | ||||
12970 | // are. | ||||
12971 | QualType T = E->getType(); | ||||
12972 | if (E->isGLValue() || T->isFunctionType()) { | ||||
12973 | LValue LV; | ||||
12974 | if (!EvaluateLValue(E, LV, Info)) | ||||
12975 | return false; | ||||
12976 | LV.moveInto(Result); | ||||
12977 | } else if (T->isVectorType()) { | ||||
12978 | if (!EvaluateVector(E, Result, Info)) | ||||
12979 | return false; | ||||
12980 | } else if (T->isIntegralOrEnumerationType()) { | ||||
12981 | if (!IntExprEvaluator(Info, Result).Visit(E)) | ||||
12982 | return false; | ||||
12983 | } else if (T->hasPointerRepresentation()) { | ||||
12984 | LValue LV; | ||||
12985 | if (!EvaluatePointer(E, LV, Info)) | ||||
12986 | return false; | ||||
12987 | LV.moveInto(Result); | ||||
12988 | } else if (T->isRealFloatingType()) { | ||||
12989 | llvm::APFloat F(0.0); | ||||
12990 | if (!EvaluateFloat(E, F, Info)) | ||||
12991 | return false; | ||||
12992 | Result = APValue(F); | ||||
12993 | } else if (T->isAnyComplexType()) { | ||||
12994 | ComplexValue C; | ||||
12995 | if (!EvaluateComplex(E, C, Info)) | ||||
12996 | return false; | ||||
12997 | C.moveInto(Result); | ||||
12998 | } else if (T->isFixedPointType()) { | ||||
12999 | if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; | ||||
13000 | } else if (T->isMemberPointerType()) { | ||||
13001 | MemberPtr P; | ||||
13002 | if (!EvaluateMemberPointer(E, P, Info)) | ||||
13003 | return false; | ||||
13004 | P.moveInto(Result); | ||||
13005 | return true; | ||||
13006 | } else if (T->isArrayType()) { | ||||
13007 | LValue LV; | ||||
13008 | APValue &Value = | ||||
13009 | Info.CurrentCall->createTemporary(E, T, false, LV); | ||||
13010 | if (!EvaluateArray(E, LV, Value, Info)) | ||||
13011 | return false; | ||||
13012 | Result = Value; | ||||
13013 | } else if (T->isRecordType()) { | ||||
13014 | LValue LV; | ||||
13015 | APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); | ||||
13016 | if (!EvaluateRecord(E, LV, Value, Info)) | ||||
13017 | return false; | ||||
13018 | Result = Value; | ||||
13019 | } else if (T->isVoidType()) { | ||||
13020 | if (!Info.getLangOpts().CPlusPlus11) | ||||
13021 | Info.CCEDiag(E, diag::note_constexpr_nonliteral) | ||||
13022 | << E->getType(); | ||||
13023 | if (!EvaluateVoid(E, Info)) | ||||
13024 | return false; | ||||
13025 | } else if (T->isAtomicType()) { | ||||
13026 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||
13027 | if (Unqual->isArrayType() || Unqual->isRecordType()) { | ||||
13028 | LValue LV; | ||||
13029 | APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); | ||||
13030 | if (!EvaluateAtomic(E, &LV, Value, Info)) | ||||
13031 | return false; | ||||
13032 | } else { | ||||
13033 | if (!EvaluateAtomic(E, nullptr, Result, Info)) | ||||
13034 | return false; | ||||
13035 | } | ||||
13036 | } else if (Info.getLangOpts().CPlusPlus11) { | ||||
13037 | Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); | ||||
13038 | return false; | ||||
13039 | } else { | ||||
13040 | Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); | ||||
13041 | return false; | ||||
13042 | } | ||||
13043 | |||||
13044 | return true; | ||||
13045 | } | ||||
13046 | |||||
13047 | /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some | ||||
13048 | /// cases, the in-place evaluation is essential, since later initializers for | ||||
13049 | /// an object can indirectly refer to subobjects which were initialized earlier. | ||||
13050 | static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, | ||||
13051 | const Expr *E, bool AllowNonLiteralTypes) { | ||||
13052 | assert(!E->isValueDependent())((!E->isValueDependent()) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13052, __PRETTY_FUNCTION__)); | ||||
13053 | |||||
13054 | if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) | ||||
13055 | return false; | ||||
13056 | |||||
13057 | if (E->isRValue()) { | ||||
13058 | // Evaluate arrays and record types in-place, so that later initializers can | ||||
13059 | // refer to earlier-initialized members of the object. | ||||
13060 | QualType T = E->getType(); | ||||
13061 | if (T->isArrayType()) | ||||
13062 | return EvaluateArray(E, This, Result, Info); | ||||
13063 | else if (T->isRecordType()) | ||||
13064 | return EvaluateRecord(E, This, Result, Info); | ||||
13065 | else if (T->isAtomicType()) { | ||||
13066 | QualType Unqual = T.getAtomicUnqualifiedType(); | ||||
13067 | if (Unqual->isArrayType() || Unqual->isRecordType()) | ||||
13068 | return EvaluateAtomic(E, &This, Result, Info); | ||||
13069 | } | ||||
13070 | } | ||||
13071 | |||||
13072 | // For any other type, in-place evaluation is unimportant. | ||||
13073 | return Evaluate(Result, Info, E); | ||||
13074 | } | ||||
13075 | |||||
13076 | /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit | ||||
13077 | /// lvalue-to-rvalue cast if it is an lvalue. | ||||
13078 | static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { | ||||
13079 | if (Info.EnableNewConstInterp) { | ||||
13080 | auto &InterpCtx = Info.Ctx.getInterpContext(); | ||||
13081 | switch (InterpCtx.evaluateAsRValue(Info, E, Result)) { | ||||
13082 | case interp::InterpResult::Success: | ||||
13083 | return true; | ||||
13084 | case interp::InterpResult::Fail: | ||||
13085 | return false; | ||||
13086 | case interp::InterpResult::Bail: | ||||
13087 | break; | ||||
13088 | } | ||||
13089 | } | ||||
13090 | |||||
13091 | if (E->getType().isNull()) | ||||
13092 | return false; | ||||
13093 | |||||
13094 | if (!CheckLiteralType(Info, E)) | ||||
13095 | return false; | ||||
13096 | |||||
13097 | if (!::Evaluate(Result, Info, E)) | ||||
13098 | return false; | ||||
13099 | |||||
13100 | if (E->isGLValue()) { | ||||
13101 | LValue LV; | ||||
13102 | LV.setFrom(Info.Ctx, Result); | ||||
13103 | if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) | ||||
13104 | return false; | ||||
13105 | } | ||||
13106 | |||||
13107 | // Check this core constant expression is a constant expression. | ||||
13108 | return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && | ||||
13109 | CheckMemoryLeaks(Info); | ||||
13110 | } | ||||
13111 | |||||
13112 | static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, | ||||
13113 | const ASTContext &Ctx, bool &IsConst) { | ||||
13114 | // Fast-path evaluations of integer literals, since we sometimes see files | ||||
13115 | // containing vast quantities of these. | ||||
13116 | if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { | ||||
13117 | Result.Val = APValue(APSInt(L->getValue(), | ||||
13118 | L->getType()->isUnsignedIntegerType())); | ||||
13119 | IsConst = true; | ||||
13120 | return true; | ||||
13121 | } | ||||
13122 | |||||
13123 | // This case should be rare, but we need to check it before we check on | ||||
13124 | // the type below. | ||||
13125 | if (Exp->getType().isNull()) { | ||||
13126 | IsConst = false; | ||||
13127 | return true; | ||||
13128 | } | ||||
13129 | |||||
13130 | // FIXME: Evaluating values of large array and record types can cause | ||||
13131 | // performance problems. Only do so in C++11 for now. | ||||
13132 | if (Exp->isRValue() && (Exp->getType()->isArrayType() || | ||||
13133 | Exp->getType()->isRecordType()) && | ||||
13134 | !Ctx.getLangOpts().CPlusPlus11) { | ||||
13135 | IsConst = false; | ||||
13136 | return true; | ||||
13137 | } | ||||
13138 | return false; | ||||
13139 | } | ||||
13140 | |||||
13141 | static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, | ||||
13142 | Expr::SideEffectsKind SEK) { | ||||
13143 | return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || | ||||
13144 | (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); | ||||
13145 | } | ||||
13146 | |||||
13147 | static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, | ||||
13148 | const ASTContext &Ctx, EvalInfo &Info) { | ||||
13149 | bool IsConst; | ||||
13150 | if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) | ||||
13151 | return IsConst; | ||||
13152 | |||||
13153 | return EvaluateAsRValue(Info, E, Result.Val); | ||||
13154 | } | ||||
13155 | |||||
13156 | static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, | ||||
13157 | const ASTContext &Ctx, | ||||
13158 | Expr::SideEffectsKind AllowSideEffects, | ||||
13159 | EvalInfo &Info) { | ||||
13160 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||
13161 | return false; | ||||
13162 | |||||
13163 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || | ||||
13164 | !ExprResult.Val.isInt() || | ||||
13165 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
13166 | return false; | ||||
13167 | |||||
13168 | return true; | ||||
13169 | } | ||||
13170 | |||||
13171 | static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, | ||||
13172 | const ASTContext &Ctx, | ||||
13173 | Expr::SideEffectsKind AllowSideEffects, | ||||
13174 | EvalInfo &Info) { | ||||
13175 | if (!E->getType()->isFixedPointType()) | ||||
13176 | return false; | ||||
13177 | |||||
13178 | if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) | ||||
13179 | return false; | ||||
13180 | |||||
13181 | if (!ExprResult.Val.isFixedPoint() || | ||||
13182 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
13183 | return false; | ||||
13184 | |||||
13185 | return true; | ||||
13186 | } | ||||
13187 | |||||
13188 | /// EvaluateAsRValue - Return true if this is a constant which we can fold using | ||||
13189 | /// any crazy technique (that has nothing to do with language standards) that | ||||
13190 | /// we want to. If this function returns true, it returns the folded constant | ||||
13191 | /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion | ||||
13192 | /// will be applied to the result. | ||||
13193 | bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, | ||||
13194 | bool InConstantContext) const { | ||||
13195 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13196, __PRETTY_FUNCTION__)) | ||||
13196 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13196, __PRETTY_FUNCTION__)); | ||||
13197 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
13198 | Info.InConstantContext = InConstantContext; | ||||
13199 | return ::EvaluateAsRValue(this, Result, Ctx, Info); | ||||
13200 | } | ||||
13201 | |||||
13202 | bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, | ||||
13203 | bool InConstantContext) const { | ||||
13204 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13205, __PRETTY_FUNCTION__)) | ||||
13205 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13205, __PRETTY_FUNCTION__)); | ||||
13206 | EvalResult Scratch; | ||||
13207 | return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && | ||||
13208 | HandleConversionToBool(Scratch.Val, Result); | ||||
13209 | } | ||||
13210 | |||||
13211 | bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, | ||||
13212 | SideEffectsKind AllowSideEffects, | ||||
13213 | bool InConstantContext) const { | ||||
13214 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13215, __PRETTY_FUNCTION__)) | ||||
13215 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13215, __PRETTY_FUNCTION__)); | ||||
13216 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
13217 | Info.InConstantContext = InConstantContext; | ||||
13218 | return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); | ||||
13219 | } | ||||
13220 | |||||
13221 | bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, | ||||
13222 | SideEffectsKind AllowSideEffects, | ||||
13223 | bool InConstantContext) const { | ||||
13224 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13225, __PRETTY_FUNCTION__)) | ||||
13225 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13225, __PRETTY_FUNCTION__)); | ||||
13226 | EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); | ||||
13227 | Info.InConstantContext = InConstantContext; | ||||
13228 | return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); | ||||
13229 | } | ||||
13230 | |||||
13231 | bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, | ||||
13232 | SideEffectsKind AllowSideEffects, | ||||
13233 | bool InConstantContext) const { | ||||
13234 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13235, __PRETTY_FUNCTION__)) | ||||
13235 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13235, __PRETTY_FUNCTION__)); | ||||
13236 | |||||
13237 | if (!getType()->isRealFloatingType()) | ||||
13238 | return false; | ||||
13239 | |||||
13240 | EvalResult ExprResult; | ||||
13241 | if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || | ||||
13242 | !ExprResult.Val.isFloat() || | ||||
13243 | hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) | ||||
13244 | return false; | ||||
13245 | |||||
13246 | Result = ExprResult.Val.getFloat(); | ||||
13247 | return true; | ||||
13248 | } | ||||
13249 | |||||
13250 | bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, | ||||
13251 | bool InConstantContext) const { | ||||
13252 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13253, __PRETTY_FUNCTION__)) | ||||
13253 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13253, __PRETTY_FUNCTION__)); | ||||
13254 | |||||
13255 | EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); | ||||
13256 | Info.InConstantContext = InConstantContext; | ||||
13257 | LValue LV; | ||||
13258 | CheckedTemporaries CheckedTemps; | ||||
13259 | if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || | ||||
13260 | Result.HasSideEffects || | ||||
13261 | !CheckLValueConstantExpression(Info, getExprLoc(), | ||||
13262 | Ctx.getLValueReferenceType(getType()), LV, | ||||
13263 | Expr::EvaluateForCodeGen, CheckedTemps)) | ||||
13264 | return false; | ||||
13265 | |||||
13266 | LV.moveInto(Result.Val); | ||||
13267 | return true; | ||||
13268 | } | ||||
13269 | |||||
13270 | bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, | ||||
13271 | const ASTContext &Ctx) const { | ||||
13272 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13273, __PRETTY_FUNCTION__)) | ||||
13273 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13273, __PRETTY_FUNCTION__)); | ||||
13274 | |||||
13275 | EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; | ||||
13276 | EvalInfo Info(Ctx, Result, EM); | ||||
13277 | Info.InConstantContext = true; | ||||
13278 | |||||
13279 | if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) | ||||
13280 | return false; | ||||
13281 | |||||
13282 | if (!Info.discardCleanups()) | ||||
13283 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13283); | ||||
13284 | |||||
13285 | return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, | ||||
13286 | Usage) && | ||||
13287 | CheckMemoryLeaks(Info); | ||||
13288 | } | ||||
13289 | |||||
13290 | bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, | ||||
13291 | const VarDecl *VD, | ||||
13292 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | ||||
13293 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13294, __PRETTY_FUNCTION__)) | ||||
13294 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13294, __PRETTY_FUNCTION__)); | ||||
13295 | |||||
13296 | // FIXME: Evaluating initializers for large array and record types can cause | ||||
13297 | // performance problems. Only do so in C++11 for now. | ||||
13298 | if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && | ||||
13299 | !Ctx.getLangOpts().CPlusPlus11) | ||||
13300 | return false; | ||||
13301 | |||||
13302 | Expr::EvalStatus EStatus; | ||||
13303 | EStatus.Diag = &Notes; | ||||
13304 | |||||
13305 | EvalInfo Info(Ctx, EStatus, VD->isConstexpr() | ||||
13306 | ? EvalInfo::EM_ConstantExpression | ||||
13307 | : EvalInfo::EM_ConstantFold); | ||||
13308 | Info.setEvaluatingDecl(VD, Value); | ||||
13309 | Info.InConstantContext = true; | ||||
13310 | |||||
13311 | SourceLocation DeclLoc = VD->getLocation(); | ||||
13312 | QualType DeclTy = VD->getType(); | ||||
13313 | |||||
13314 | if (Info.EnableNewConstInterp) { | ||||
13315 | auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); | ||||
13316 | switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) { | ||||
13317 | case interp::InterpResult::Fail: | ||||
13318 | // Bail out if an error was encountered. | ||||
13319 | return false; | ||||
13320 | case interp::InterpResult::Success: | ||||
13321 | // Evaluation succeeded and value was set. | ||||
13322 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); | ||||
13323 | case interp::InterpResult::Bail: | ||||
13324 | // Evaluate the value again for the tree evaluator to use. | ||||
13325 | break; | ||||
13326 | } | ||||
13327 | } | ||||
13328 | |||||
13329 | LValue LVal; | ||||
13330 | LVal.set(VD); | ||||
13331 | |||||
13332 | // C++11 [basic.start.init]p2: | ||||
13333 | // Variables with static storage duration or thread storage duration shall be | ||||
13334 | // zero-initialized before any other initialization takes place. | ||||
13335 | // This behavior is not present in C. | ||||
13336 | if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && | ||||
13337 | !DeclTy->isReferenceType()) { | ||||
13338 | ImplicitValueInitExpr VIE(DeclTy); | ||||
13339 | if (!EvaluateInPlace(Value, Info, LVal, &VIE, | ||||
13340 | /*AllowNonLiteralTypes=*/true)) | ||||
13341 | return false; | ||||
13342 | } | ||||
13343 | |||||
13344 | if (!EvaluateInPlace(Value, Info, LVal, this, | ||||
13345 | /*AllowNonLiteralTypes=*/true) || | ||||
13346 | EStatus.HasSideEffects) | ||||
13347 | return false; | ||||
13348 | |||||
13349 | // At this point, any lifetime-extended temporaries are completely | ||||
13350 | // initialized. | ||||
13351 | Info.performLifetimeExtension(); | ||||
13352 | |||||
13353 | if (!Info.discardCleanups()) | ||||
13354 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13354); | ||||
13355 | |||||
13356 | return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && | ||||
13357 | CheckMemoryLeaks(Info); | ||||
13358 | } | ||||
13359 | |||||
13360 | bool VarDecl::evaluateDestruction( | ||||
13361 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const { | ||||
13362 | assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&((getEvaluatedValue() && !getEvaluatedValue()->isAbsent () && "cannot evaluate destruction of non-constant-initialized variable" ) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13363, __PRETTY_FUNCTION__)) | ||||
13363 | "cannot evaluate destruction of non-constant-initialized variable")((getEvaluatedValue() && !getEvaluatedValue()->isAbsent () && "cannot evaluate destruction of non-constant-initialized variable" ) ? static_cast<void> (0) : __assert_fail ("getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && \"cannot evaluate destruction of non-constant-initialized variable\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13363, __PRETTY_FUNCTION__)); | ||||
13364 | |||||
13365 | Expr::EvalStatus EStatus; | ||||
13366 | EStatus.Diag = &Notes; | ||||
13367 | |||||
13368 | // Make a copy of the value for the destructor to mutate. | ||||
13369 | APValue DestroyedValue = *getEvaluatedValue(); | ||||
13370 | |||||
13371 | EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); | ||||
13372 | Info.setEvaluatingDecl(this, DestroyedValue, | ||||
13373 | EvalInfo::EvaluatingDeclKind::Dtor); | ||||
13374 | Info.InConstantContext = true; | ||||
13375 | |||||
13376 | SourceLocation DeclLoc = getLocation(); | ||||
13377 | QualType DeclTy = getType(); | ||||
13378 | |||||
13379 | LValue LVal; | ||||
13380 | LVal.set(this); | ||||
13381 | |||||
13382 | // FIXME: Consider storing whether this variable has constant destruction in | ||||
13383 | // the EvaluatedStmt so that CodeGen can query it. | ||||
13384 | if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || | ||||
13385 | EStatus.HasSideEffects) | ||||
13386 | return false; | ||||
13387 | |||||
13388 | if (!Info.discardCleanups()) | ||||
13389 | llvm_unreachable("Unhandled cleanup; missing full expression marker?")::llvm::llvm_unreachable_internal("Unhandled cleanup; missing full expression marker?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13389); | ||||
13390 | |||||
13391 | ensureEvaluatedStmt()->HasConstantDestruction = true; | ||||
13392 | return true; | ||||
13393 | } | ||||
13394 | |||||
13395 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be | ||||
13396 | /// constant folded, but discard the result. | ||||
13397 | bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { | ||||
13398 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13399, __PRETTY_FUNCTION__)) | ||||
13399 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13399, __PRETTY_FUNCTION__)); | ||||
13400 | |||||
13401 | EvalResult Result; | ||||
13402 | return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && | ||||
13403 | !hasUnacceptableSideEffect(Result, SEK); | ||||
13404 | } | ||||
13405 | |||||
13406 | APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, | ||||
13407 | SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||
13408 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13409, __PRETTY_FUNCTION__)) | ||||
13409 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13409, __PRETTY_FUNCTION__)); | ||||
13410 | |||||
13411 | EvalResult EVResult; | ||||
13412 | EVResult.Diag = Diag; | ||||
13413 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
13414 | Info.InConstantContext = true; | ||||
13415 | |||||
13416 | bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); | ||||
13417 | (void)Result; | ||||
13418 | assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast <void> (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13418, __PRETTY_FUNCTION__)); | ||||
13419 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13419, __PRETTY_FUNCTION__)); | ||||
13420 | |||||
13421 | return EVResult.Val.getInt(); | ||||
13422 | } | ||||
13423 | |||||
13424 | APSInt Expr::EvaluateKnownConstIntCheckOverflow( | ||||
13425 | const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { | ||||
13426 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13427, __PRETTY_FUNCTION__)) | ||||
13427 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13427, __PRETTY_FUNCTION__)); | ||||
13428 | |||||
13429 | EvalResult EVResult; | ||||
13430 | EVResult.Diag = Diag; | ||||
13431 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
13432 | Info.InConstantContext = true; | ||||
13433 | Info.CheckingForUndefinedBehavior = true; | ||||
13434 | |||||
13435 | bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); | ||||
13436 | (void)Result; | ||||
13437 | assert(Result && "Could not evaluate expression")((Result && "Could not evaluate expression") ? static_cast <void> (0) : __assert_fail ("Result && \"Could not evaluate expression\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13437, __PRETTY_FUNCTION__)); | ||||
13438 | assert(EVResult.Val.isInt() && "Expression did not evaluate to integer")((EVResult.Val.isInt() && "Expression did not evaluate to integer" ) ? static_cast<void> (0) : __assert_fail ("EVResult.Val.isInt() && \"Expression did not evaluate to integer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13438, __PRETTY_FUNCTION__)); | ||||
13439 | |||||
13440 | return EVResult.Val.getInt(); | ||||
13441 | } | ||||
13442 | |||||
13443 | void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { | ||||
13444 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13445, __PRETTY_FUNCTION__)) | ||||
13445 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13445, __PRETTY_FUNCTION__)); | ||||
13446 | |||||
13447 | bool IsConst; | ||||
13448 | EvalResult EVResult; | ||||
13449 | if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { | ||||
13450 | EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); | ||||
13451 | Info.CheckingForUndefinedBehavior = true; | ||||
13452 | (void)::EvaluateAsRValue(Info, this, EVResult.Val); | ||||
13453 | } | ||||
13454 | } | ||||
13455 | |||||
13456 | bool Expr::EvalResult::isGlobalLValue() const { | ||||
13457 | assert(Val.isLValue())((Val.isLValue()) ? static_cast<void> (0) : __assert_fail ("Val.isLValue()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13457, __PRETTY_FUNCTION__)); | ||||
13458 | return IsGlobalLValue(Val.getLValueBase()); | ||||
13459 | } | ||||
13460 | |||||
13461 | |||||
13462 | /// isIntegerConstantExpr - this recursive routine will test if an expression is | ||||
13463 | /// an integer constant expression. | ||||
13464 | |||||
13465 | /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, | ||||
13466 | /// comma, etc | ||||
13467 | |||||
13468 | // CheckICE - This function does the fundamental ICE checking: the returned | ||||
13469 | // ICEDiag contains an ICEKind indicating whether the expression is an ICE, | ||||
13470 | // and a (possibly null) SourceLocation indicating the location of the problem. | ||||
13471 | // | ||||
13472 | // Note that to reduce code duplication, this helper does no evaluation | ||||
13473 | // itself; the caller checks whether the expression is evaluatable, and | ||||
13474 | // in the rare cases where CheckICE actually cares about the evaluated | ||||
13475 | // value, it calls into Evaluate. | ||||
13476 | |||||
13477 | namespace { | ||||
13478 | |||||
13479 | enum ICEKind { | ||||
13480 | /// This expression is an ICE. | ||||
13481 | IK_ICE, | ||||
13482 | /// This expression is not an ICE, but if it isn't evaluated, it's | ||||
13483 | /// a legal subexpression for an ICE. This return value is used to handle | ||||
13484 | /// the comma operator in C99 mode, and non-constant subexpressions. | ||||
13485 | IK_ICEIfUnevaluated, | ||||
13486 | /// This expression is not an ICE, and is not a legal subexpression for one. | ||||
13487 | IK_NotICE | ||||
13488 | }; | ||||
13489 | |||||
13490 | struct ICEDiag { | ||||
13491 | ICEKind Kind; | ||||
13492 | SourceLocation Loc; | ||||
13493 | |||||
13494 | ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} | ||||
13495 | }; | ||||
13496 | |||||
13497 | } | ||||
13498 | |||||
13499 | static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } | ||||
13500 | |||||
13501 | static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } | ||||
13502 | |||||
13503 | static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { | ||||
13504 | Expr::EvalResult EVResult; | ||||
13505 | Expr::EvalStatus Status; | ||||
13506 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||
13507 | |||||
13508 | Info.InConstantContext = true; | ||||
13509 | if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || | ||||
13510 | !EVResult.Val.isInt()) | ||||
13511 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13512 | |||||
13513 | return NoDiag(); | ||||
13514 | } | ||||
13515 | |||||
13516 | static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { | ||||
13517 | assert(!E->isValueDependent() && "Should not see value dependent exprs!")((!E->isValueDependent() && "Should not see value dependent exprs!" ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Should not see value dependent exprs!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13517, __PRETTY_FUNCTION__)); | ||||
13518 | if (!E->getType()->isIntegralOrEnumerationType()) | ||||
13519 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13520 | |||||
13521 | switch (E->getStmtClass()) { | ||||
13522 | #define ABSTRACT_STMT(Node) | ||||
13523 | #define STMT(Node, Base) case Expr::Node##Class: | ||||
13524 | #define EXPR(Node, Base) | ||||
13525 | #include "clang/AST/StmtNodes.inc" | ||||
13526 | case Expr::PredefinedExprClass: | ||||
13527 | case Expr::FloatingLiteralClass: | ||||
13528 | case Expr::ImaginaryLiteralClass: | ||||
13529 | case Expr::StringLiteralClass: | ||||
13530 | case Expr::ArraySubscriptExprClass: | ||||
13531 | case Expr::OMPArraySectionExprClass: | ||||
13532 | case Expr::MemberExprClass: | ||||
13533 | case Expr::CompoundAssignOperatorClass: | ||||
13534 | case Expr::CompoundLiteralExprClass: | ||||
13535 | case Expr::ExtVectorElementExprClass: | ||||
13536 | case Expr::DesignatedInitExprClass: | ||||
13537 | case Expr::ArrayInitLoopExprClass: | ||||
13538 | case Expr::ArrayInitIndexExprClass: | ||||
13539 | case Expr::NoInitExprClass: | ||||
13540 | case Expr::DesignatedInitUpdateExprClass: | ||||
13541 | case Expr::ImplicitValueInitExprClass: | ||||
13542 | case Expr::ParenListExprClass: | ||||
13543 | case Expr::VAArgExprClass: | ||||
13544 | case Expr::AddrLabelExprClass: | ||||
13545 | case Expr::StmtExprClass: | ||||
13546 | case Expr::CXXMemberCallExprClass: | ||||
13547 | case Expr::CUDAKernelCallExprClass: | ||||
13548 | case Expr::CXXDynamicCastExprClass: | ||||
13549 | case Expr::CXXTypeidExprClass: | ||||
13550 | case Expr::CXXUuidofExprClass: | ||||
13551 | case Expr::MSPropertyRefExprClass: | ||||
13552 | case Expr::MSPropertySubscriptExprClass: | ||||
13553 | case Expr::CXXNullPtrLiteralExprClass: | ||||
13554 | case Expr::UserDefinedLiteralClass: | ||||
13555 | case Expr::CXXThisExprClass: | ||||
13556 | case Expr::CXXThrowExprClass: | ||||
13557 | case Expr::CXXNewExprClass: | ||||
13558 | case Expr::CXXDeleteExprClass: | ||||
13559 | case Expr::CXXPseudoDestructorExprClass: | ||||
13560 | case Expr::UnresolvedLookupExprClass: | ||||
13561 | case Expr::TypoExprClass: | ||||
13562 | case Expr::DependentScopeDeclRefExprClass: | ||||
13563 | case Expr::CXXConstructExprClass: | ||||
13564 | case Expr::CXXInheritedCtorInitExprClass: | ||||
13565 | case Expr::CXXStdInitializerListExprClass: | ||||
13566 | case Expr::CXXBindTemporaryExprClass: | ||||
13567 | case Expr::ExprWithCleanupsClass: | ||||
13568 | case Expr::CXXTemporaryObjectExprClass: | ||||
13569 | case Expr::CXXUnresolvedConstructExprClass: | ||||
13570 | case Expr::CXXDependentScopeMemberExprClass: | ||||
13571 | case Expr::UnresolvedMemberExprClass: | ||||
13572 | case Expr::ObjCStringLiteralClass: | ||||
13573 | case Expr::ObjCBoxedExprClass: | ||||
13574 | case Expr::ObjCArrayLiteralClass: | ||||
13575 | case Expr::ObjCDictionaryLiteralClass: | ||||
13576 | case Expr::ObjCEncodeExprClass: | ||||
13577 | case Expr::ObjCMessageExprClass: | ||||
13578 | case Expr::ObjCSelectorExprClass: | ||||
13579 | case Expr::ObjCProtocolExprClass: | ||||
13580 | case Expr::ObjCIvarRefExprClass: | ||||
13581 | case Expr::ObjCPropertyRefExprClass: | ||||
13582 | case Expr::ObjCSubscriptRefExprClass: | ||||
13583 | case Expr::ObjCIsaExprClass: | ||||
13584 | case Expr::ObjCAvailabilityCheckExprClass: | ||||
13585 | case Expr::ShuffleVectorExprClass: | ||||
13586 | case Expr::ConvertVectorExprClass: | ||||
13587 | case Expr::BlockExprClass: | ||||
13588 | case Expr::NoStmtClass: | ||||
13589 | case Expr::OpaqueValueExprClass: | ||||
13590 | case Expr::PackExpansionExprClass: | ||||
13591 | case Expr::SubstNonTypeTemplateParmPackExprClass: | ||||
13592 | case Expr::FunctionParmPackExprClass: | ||||
13593 | case Expr::AsTypeExprClass: | ||||
13594 | case Expr::ObjCIndirectCopyRestoreExprClass: | ||||
13595 | case Expr::MaterializeTemporaryExprClass: | ||||
13596 | case Expr::PseudoObjectExprClass: | ||||
13597 | case Expr::AtomicExprClass: | ||||
13598 | case Expr::LambdaExprClass: | ||||
13599 | case Expr::CXXFoldExprClass: | ||||
13600 | case Expr::CoawaitExprClass: | ||||
13601 | case Expr::DependentCoawaitExprClass: | ||||
13602 | case Expr::CoyieldExprClass: | ||||
13603 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13604 | |||||
13605 | case Expr::InitListExprClass: { | ||||
13606 | // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the | ||||
13607 | // form "T x = { a };" is equivalent to "T x = a;". | ||||
13608 | // Unless we're initializing a reference, T is a scalar as it is known to be | ||||
13609 | // of integral or enumeration type. | ||||
13610 | if (E->isRValue()) | ||||
13611 | if (cast<InitListExpr>(E)->getNumInits() == 1) | ||||
13612 | return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); | ||||
13613 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13614 | } | ||||
13615 | |||||
13616 | case Expr::SizeOfPackExprClass: | ||||
13617 | case Expr::GNUNullExprClass: | ||||
13618 | case Expr::SourceLocExprClass: | ||||
13619 | return NoDiag(); | ||||
13620 | |||||
13621 | case Expr::SubstNonTypeTemplateParmExprClass: | ||||
13622 | return | ||||
13623 | CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); | ||||
13624 | |||||
13625 | case Expr::ConstantExprClass: | ||||
13626 | return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); | ||||
13627 | |||||
13628 | case Expr::ParenExprClass: | ||||
13629 | return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); | ||||
13630 | case Expr::GenericSelectionExprClass: | ||||
13631 | return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); | ||||
13632 | case Expr::IntegerLiteralClass: | ||||
13633 | case Expr::FixedPointLiteralClass: | ||||
13634 | case Expr::CharacterLiteralClass: | ||||
13635 | case Expr::ObjCBoolLiteralExprClass: | ||||
13636 | case Expr::CXXBoolLiteralExprClass: | ||||
13637 | case Expr::CXXScalarValueInitExprClass: | ||||
13638 | case Expr::TypeTraitExprClass: | ||||
13639 | case Expr::ArrayTypeTraitExprClass: | ||||
13640 | case Expr::ExpressionTraitExprClass: | ||||
13641 | case Expr::CXXNoexceptExprClass: | ||||
13642 | return NoDiag(); | ||||
13643 | case Expr::CallExprClass: | ||||
13644 | case Expr::CXXOperatorCallExprClass: { | ||||
13645 | // C99 6.6/3 allows function calls within unevaluated subexpressions of | ||||
13646 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||
13647 | // contain an operand of (pointer to) function type. | ||||
13648 | const CallExpr *CE = cast<CallExpr>(E); | ||||
13649 | if (CE->getBuiltinCallee()) | ||||
13650 | return CheckEvalInICE(E, Ctx); | ||||
13651 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13652 | } | ||||
13653 | case Expr::DeclRefExprClass: { | ||||
13654 | if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) | ||||
13655 | return NoDiag(); | ||||
13656 | const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); | ||||
13657 | if (Ctx.getLangOpts().CPlusPlus && | ||||
13658 | D && IsConstNonVolatile(D->getType())) { | ||||
13659 | // Parameter variables are never constants. Without this check, | ||||
13660 | // getAnyInitializer() can find a default argument, which leads | ||||
13661 | // to chaos. | ||||
13662 | if (isa<ParmVarDecl>(D)) | ||||
13663 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||
13664 | |||||
13665 | // C++ 7.1.5.1p2 | ||||
13666 | // A variable of non-volatile const-qualified integral or enumeration | ||||
13667 | // type initialized by an ICE can be used in ICEs. | ||||
13668 | if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { | ||||
13669 | if (!Dcl->getType()->isIntegralOrEnumerationType()) | ||||
13670 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||
13671 | |||||
13672 | const VarDecl *VD; | ||||
13673 | // Look for a declaration of this variable that has an initializer, and | ||||
13674 | // check whether it is an ICE. | ||||
13675 | if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) | ||||
13676 | return NoDiag(); | ||||
13677 | else | ||||
13678 | return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); | ||||
13679 | } | ||||
13680 | } | ||||
13681 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13682 | } | ||||
13683 | case Expr::UnaryOperatorClass: { | ||||
13684 | const UnaryOperator *Exp = cast<UnaryOperator>(E); | ||||
13685 | switch (Exp->getOpcode()) { | ||||
13686 | case UO_PostInc: | ||||
13687 | case UO_PostDec: | ||||
13688 | case UO_PreInc: | ||||
13689 | case UO_PreDec: | ||||
13690 | case UO_AddrOf: | ||||
13691 | case UO_Deref: | ||||
13692 | case UO_Coawait: | ||||
13693 | // C99 6.6/3 allows increment and decrement within unevaluated | ||||
13694 | // subexpressions of constant expressions, but they can never be ICEs | ||||
13695 | // because an ICE cannot contain an lvalue operand. | ||||
13696 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13697 | case UO_Extension: | ||||
13698 | case UO_LNot: | ||||
13699 | case UO_Plus: | ||||
13700 | case UO_Minus: | ||||
13701 | case UO_Not: | ||||
13702 | case UO_Real: | ||||
13703 | case UO_Imag: | ||||
13704 | return CheckICE(Exp->getSubExpr(), Ctx); | ||||
13705 | } | ||||
13706 | llvm_unreachable("invalid unary operator class")::llvm::llvm_unreachable_internal("invalid unary operator class" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13706); | ||||
13707 | } | ||||
13708 | case Expr::OffsetOfExprClass: { | ||||
13709 | // Note that per C99, offsetof must be an ICE. And AFAIK, using | ||||
13710 | // EvaluateAsRValue matches the proposed gcc behavior for cases like | ||||
13711 | // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect | ||||
13712 | // compliance: we should warn earlier for offsetof expressions with | ||||
13713 | // array subscripts that aren't ICEs, and if the array subscripts | ||||
13714 | // are ICEs, the value of the offsetof must be an integer constant. | ||||
13715 | return CheckEvalInICE(E, Ctx); | ||||
13716 | } | ||||
13717 | case Expr::UnaryExprOrTypeTraitExprClass: { | ||||
13718 | const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); | ||||
13719 | if ((Exp->getKind() == UETT_SizeOf) && | ||||
13720 | Exp->getTypeOfArgument()->isVariableArrayType()) | ||||
13721 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13722 | return NoDiag(); | ||||
13723 | } | ||||
13724 | case Expr::BinaryOperatorClass: { | ||||
13725 | const BinaryOperator *Exp = cast<BinaryOperator>(E); | ||||
13726 | switch (Exp->getOpcode()) { | ||||
13727 | case BO_PtrMemD: | ||||
13728 | case BO_PtrMemI: | ||||
13729 | case BO_Assign: | ||||
13730 | case BO_MulAssign: | ||||
13731 | case BO_DivAssign: | ||||
13732 | case BO_RemAssign: | ||||
13733 | case BO_AddAssign: | ||||
13734 | case BO_SubAssign: | ||||
13735 | case BO_ShlAssign: | ||||
13736 | case BO_ShrAssign: | ||||
13737 | case BO_AndAssign: | ||||
13738 | case BO_XorAssign: | ||||
13739 | case BO_OrAssign: | ||||
13740 | // C99 6.6/3 allows assignments within unevaluated subexpressions of | ||||
13741 | // constant expressions, but they can never be ICEs because an ICE cannot | ||||
13742 | // contain an lvalue operand. | ||||
13743 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13744 | |||||
13745 | case BO_Mul: | ||||
13746 | case BO_Div: | ||||
13747 | case BO_Rem: | ||||
13748 | case BO_Add: | ||||
13749 | case BO_Sub: | ||||
13750 | case BO_Shl: | ||||
13751 | case BO_Shr: | ||||
13752 | case BO_LT: | ||||
13753 | case BO_GT: | ||||
13754 | case BO_LE: | ||||
13755 | case BO_GE: | ||||
13756 | case BO_EQ: | ||||
13757 | case BO_NE: | ||||
13758 | case BO_And: | ||||
13759 | case BO_Xor: | ||||
13760 | case BO_Or: | ||||
13761 | case BO_Comma: | ||||
13762 | case BO_Cmp: { | ||||
13763 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||
13764 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||
13765 | if (Exp->getOpcode() == BO_Div || | ||||
13766 | Exp->getOpcode() == BO_Rem) { | ||||
13767 | // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure | ||||
13768 | // we don't evaluate one. | ||||
13769 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { | ||||
13770 | llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); | ||||
13771 | if (REval == 0) | ||||
13772 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
13773 | if (REval.isSigned() && REval.isAllOnesValue()) { | ||||
13774 | llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); | ||||
13775 | if (LEval.isMinSignedValue()) | ||||
13776 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
13777 | } | ||||
13778 | } | ||||
13779 | } | ||||
13780 | if (Exp->getOpcode() == BO_Comma) { | ||||
13781 | if (Ctx.getLangOpts().C99) { | ||||
13782 | // C99 6.6p3 introduces a strange edge case: comma can be in an ICE | ||||
13783 | // if it isn't evaluated. | ||||
13784 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) | ||||
13785 | return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); | ||||
13786 | } else { | ||||
13787 | // In both C89 and C++, commas in ICEs are illegal. | ||||
13788 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13789 | } | ||||
13790 | } | ||||
13791 | return Worst(LHSResult, RHSResult); | ||||
13792 | } | ||||
13793 | case BO_LAnd: | ||||
13794 | case BO_LOr: { | ||||
13795 | ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); | ||||
13796 | ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); | ||||
13797 | if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { | ||||
13798 | // Rare case where the RHS has a comma "side-effect"; we need | ||||
13799 | // to actually check the condition to see whether the side | ||||
13800 | // with the comma is evaluated. | ||||
13801 | if ((Exp->getOpcode() == BO_LAnd) != | ||||
13802 | (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) | ||||
13803 | return RHSResult; | ||||
13804 | return NoDiag(); | ||||
13805 | } | ||||
13806 | |||||
13807 | return Worst(LHSResult, RHSResult); | ||||
13808 | } | ||||
13809 | } | ||||
13810 | llvm_unreachable("invalid binary operator kind")::llvm::llvm_unreachable_internal("invalid binary operator kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13810); | ||||
13811 | } | ||||
13812 | case Expr::ImplicitCastExprClass: | ||||
13813 | case Expr::CStyleCastExprClass: | ||||
13814 | case Expr::CXXFunctionalCastExprClass: | ||||
13815 | case Expr::CXXStaticCastExprClass: | ||||
13816 | case Expr::CXXReinterpretCastExprClass: | ||||
13817 | case Expr::CXXConstCastExprClass: | ||||
13818 | case Expr::ObjCBridgedCastExprClass: { | ||||
13819 | const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); | ||||
13820 | if (isa<ExplicitCastExpr>(E)) { | ||||
13821 | if (const FloatingLiteral *FL | ||||
13822 | = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { | ||||
13823 | unsigned DestWidth = Ctx.getIntWidth(E->getType()); | ||||
13824 | bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); | ||||
13825 | APSInt IgnoredVal(DestWidth, !DestSigned); | ||||
13826 | bool Ignored; | ||||
13827 | // If the value does not fit in the destination type, the behavior is | ||||
13828 | // undefined, so we are not required to treat it as a constant | ||||
13829 | // expression. | ||||
13830 | if (FL->getValue().convertToInteger(IgnoredVal, | ||||
13831 | llvm::APFloat::rmTowardZero, | ||||
13832 | &Ignored) & APFloat::opInvalidOp) | ||||
13833 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13834 | return NoDiag(); | ||||
13835 | } | ||||
13836 | } | ||||
13837 | switch (cast<CastExpr>(E)->getCastKind()) { | ||||
13838 | case CK_LValueToRValue: | ||||
13839 | case CK_AtomicToNonAtomic: | ||||
13840 | case CK_NonAtomicToAtomic: | ||||
13841 | case CK_NoOp: | ||||
13842 | case CK_IntegralToBoolean: | ||||
13843 | case CK_IntegralCast: | ||||
13844 | return CheckICE(SubExpr, Ctx); | ||||
13845 | default: | ||||
13846 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13847 | } | ||||
13848 | } | ||||
13849 | case Expr::BinaryConditionalOperatorClass: { | ||||
13850 | const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); | ||||
13851 | ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); | ||||
13852 | if (CommonResult.Kind == IK_NotICE) return CommonResult; | ||||
13853 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||
13854 | if (FalseResult.Kind == IK_NotICE) return FalseResult; | ||||
13855 | if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; | ||||
13856 | if (FalseResult.Kind == IK_ICEIfUnevaluated && | ||||
13857 | Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); | ||||
13858 | return FalseResult; | ||||
13859 | } | ||||
13860 | case Expr::ConditionalOperatorClass: { | ||||
13861 | const ConditionalOperator *Exp = cast<ConditionalOperator>(E); | ||||
13862 | // If the condition (ignoring parens) is a __builtin_constant_p call, | ||||
13863 | // then only the true side is actually considered in an integer constant | ||||
13864 | // expression, and it is fully evaluated. This is an important GNU | ||||
13865 | // extension. See GCC PR38377 for discussion. | ||||
13866 | if (const CallExpr *CallCE | ||||
13867 | = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) | ||||
13868 | if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) | ||||
13869 | return CheckEvalInICE(E, Ctx); | ||||
13870 | ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); | ||||
13871 | if (CondResult.Kind == IK_NotICE) | ||||
13872 | return CondResult; | ||||
13873 | |||||
13874 | ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); | ||||
13875 | ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); | ||||
13876 | |||||
13877 | if (TrueResult.Kind == IK_NotICE) | ||||
13878 | return TrueResult; | ||||
13879 | if (FalseResult.Kind == IK_NotICE) | ||||
13880 | return FalseResult; | ||||
13881 | if (CondResult.Kind == IK_ICEIfUnevaluated) | ||||
13882 | return CondResult; | ||||
13883 | if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) | ||||
13884 | return NoDiag(); | ||||
13885 | // Rare case where the diagnostics depend on which side is evaluated | ||||
13886 | // Note that if we get here, CondResult is 0, and at least one of | ||||
13887 | // TrueResult and FalseResult is non-zero. | ||||
13888 | if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) | ||||
13889 | return FalseResult; | ||||
13890 | return TrueResult; | ||||
13891 | } | ||||
13892 | case Expr::CXXDefaultArgExprClass: | ||||
13893 | return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); | ||||
13894 | case Expr::CXXDefaultInitExprClass: | ||||
13895 | return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); | ||||
13896 | case Expr::ChooseExprClass: { | ||||
13897 | return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); | ||||
13898 | } | ||||
13899 | case Expr::BuiltinBitCastExprClass: { | ||||
13900 | if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) | ||||
13901 | return ICEDiag(IK_NotICE, E->getBeginLoc()); | ||||
13902 | return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); | ||||
13903 | } | ||||
13904 | } | ||||
13905 | |||||
13906 | llvm_unreachable("Invalid StmtClass!")::llvm::llvm_unreachable_internal("Invalid StmtClass!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13906); | ||||
13907 | } | ||||
13908 | |||||
13909 | /// Evaluate an expression as a C++11 integral constant expression. | ||||
13910 | static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, | ||||
13911 | const Expr *E, | ||||
13912 | llvm::APSInt *Value, | ||||
13913 | SourceLocation *Loc) { | ||||
13914 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { | ||||
13915 | if (Loc) *Loc = E->getExprLoc(); | ||||
13916 | return false; | ||||
13917 | } | ||||
13918 | |||||
13919 | APValue Result; | ||||
13920 | if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) | ||||
13921 | return false; | ||||
13922 | |||||
13923 | if (!Result.isInt()) { | ||||
13924 | if (Loc) *Loc = E->getExprLoc(); | ||||
13925 | return false; | ||||
13926 | } | ||||
13927 | |||||
13928 | if (Value) *Value = Result.getInt(); | ||||
13929 | return true; | ||||
13930 | } | ||||
13931 | |||||
13932 | bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, | ||||
13933 | SourceLocation *Loc) const { | ||||
13934 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13935, __PRETTY_FUNCTION__)) | ||||
13935 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13935, __PRETTY_FUNCTION__)); | ||||
13936 | |||||
13937 | if (Ctx.getLangOpts().CPlusPlus11) | ||||
13938 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); | ||||
13939 | |||||
13940 | ICEDiag D = CheckICE(this, Ctx); | ||||
13941 | if (D.Kind != IK_ICE) { | ||||
13942 | if (Loc) *Loc = D.Loc; | ||||
13943 | return false; | ||||
13944 | } | ||||
13945 | return true; | ||||
13946 | } | ||||
13947 | |||||
13948 | bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, | ||||
13949 | SourceLocation *Loc, bool isEvaluated) const { | ||||
13950 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13951, __PRETTY_FUNCTION__)) | ||||
13951 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13951, __PRETTY_FUNCTION__)); | ||||
13952 | |||||
13953 | if (Ctx.getLangOpts().CPlusPlus11) | ||||
13954 | return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); | ||||
13955 | |||||
13956 | if (!isIntegerConstantExpr(Ctx, Loc)) | ||||
13957 | return false; | ||||
13958 | |||||
13959 | // The only possible side-effects here are due to UB discovered in the | ||||
13960 | // evaluation (for instance, INT_MAX + 1). In such a case, we are still | ||||
13961 | // required to treat the expression as an ICE, so we produce the folded | ||||
13962 | // value. | ||||
13963 | EvalResult ExprResult; | ||||
13964 | Expr::EvalStatus Status; | ||||
13965 | EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); | ||||
13966 | Info.InConstantContext = true; | ||||
13967 | |||||
13968 | if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) | ||||
13969 | llvm_unreachable("ICE cannot be evaluated!")::llvm::llvm_unreachable_internal("ICE cannot be evaluated!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13969); | ||||
13970 | |||||
13971 | Value = ExprResult.Val.getInt(); | ||||
13972 | return true; | ||||
13973 | } | ||||
13974 | |||||
13975 | bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { | ||||
13976 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13977, __PRETTY_FUNCTION__)) | ||||
13977 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13977, __PRETTY_FUNCTION__)); | ||||
13978 | |||||
13979 | return CheckICE(this, Ctx).Kind == IK_ICE; | ||||
13980 | } | ||||
13981 | |||||
13982 | bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, | ||||
13983 | SourceLocation *Loc) const { | ||||
13984 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13985, __PRETTY_FUNCTION__)) | ||||
13985 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13985, __PRETTY_FUNCTION__)); | ||||
13986 | |||||
13987 | // We support this checking in C++98 mode in order to diagnose compatibility | ||||
13988 | // issues. | ||||
13989 | assert(Ctx.getLangOpts().CPlusPlus)((Ctx.getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 13989, __PRETTY_FUNCTION__)); | ||||
13990 | |||||
13991 | // Build evaluation settings. | ||||
13992 | Expr::EvalStatus Status; | ||||
13993 | SmallVector<PartialDiagnosticAt, 8> Diags; | ||||
13994 | Status.Diag = &Diags; | ||||
13995 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); | ||||
13996 | |||||
13997 | APValue Scratch; | ||||
13998 | bool IsConstExpr = | ||||
13999 | ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && | ||||
14000 | // FIXME: We don't produce a diagnostic for this, but the callers that | ||||
14001 | // call us on arbitrary full-expressions should generally not care. | ||||
14002 | Info.discardCleanups() && !Status.HasSideEffects; | ||||
14003 | |||||
14004 | if (!Diags.empty()) { | ||||
14005 | IsConstExpr = false; | ||||
14006 | if (Loc) *Loc = Diags[0].first; | ||||
14007 | } else if (!IsConstExpr) { | ||||
14008 | // FIXME: This shouldn't happen. | ||||
14009 | if (Loc) *Loc = getExprLoc(); | ||||
14010 | } | ||||
14011 | |||||
14012 | return IsConstExpr; | ||||
14013 | } | ||||
14014 | |||||
14015 | bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, | ||||
14016 | const FunctionDecl *Callee, | ||||
14017 | ArrayRef<const Expr*> Args, | ||||
14018 | const Expr *This) const { | ||||
14019 | assert(!isValueDependent() &&((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14020, __PRETTY_FUNCTION__)) | ||||
14020 | "Expression evaluator can't be called on a dependent expression.")((!isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14020, __PRETTY_FUNCTION__)); | ||||
14021 | |||||
14022 | Expr::EvalStatus Status; | ||||
14023 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); | ||||
14024 | Info.InConstantContext = true; | ||||
14025 | |||||
14026 | LValue ThisVal; | ||||
14027 | const LValue *ThisPtr = nullptr; | ||||
14028 | if (This) { | ||||
14029 | #ifndef NDEBUG | ||||
14030 | auto *MD = dyn_cast<CXXMethodDecl>(Callee); | ||||
14031 | assert(MD && "Don't provide `this` for non-methods.")((MD && "Don't provide `this` for non-methods.") ? static_cast <void> (0) : __assert_fail ("MD && \"Don't provide `this` for non-methods.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14031, __PRETTY_FUNCTION__)); | ||||
14032 | assert(!MD->isStatic() && "Don't provide `this` for static methods.")((!MD->isStatic() && "Don't provide `this` for static methods." ) ? static_cast<void> (0) : __assert_fail ("!MD->isStatic() && \"Don't provide `this` for static methods.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14032, __PRETTY_FUNCTION__)); | ||||
14033 | #endif | ||||
14034 | if (EvaluateObjectArgument(Info, This, ThisVal)) | ||||
14035 | ThisPtr = &ThisVal; | ||||
14036 | if (Info.EvalStatus.HasSideEffects) | ||||
14037 | return false; | ||||
14038 | } | ||||
14039 | |||||
14040 | ArgVector ArgValues(Args.size()); | ||||
14041 | for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); | ||||
14042 | I != E; ++I) { | ||||
14043 | if ((*I)->isValueDependent() || | ||||
14044 | !Evaluate(ArgValues[I - Args.begin()], Info, *I)) | ||||
14045 | // If evaluation fails, throw away the argument entirely. | ||||
14046 | ArgValues[I - Args.begin()] = APValue(); | ||||
14047 | if (Info.EvalStatus.HasSideEffects) | ||||
14048 | return false; | ||||
14049 | } | ||||
14050 | |||||
14051 | // Build fake call to Callee. | ||||
14052 | CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, | ||||
14053 | ArgValues.data()); | ||||
14054 | return Evaluate(Value, Info, this) && Info.discardCleanups() && | ||||
14055 | !Info.EvalStatus.HasSideEffects; | ||||
14056 | } | ||||
14057 | |||||
14058 | bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, | ||||
14059 | SmallVectorImpl< | ||||
14060 | PartialDiagnosticAt> &Diags) { | ||||
14061 | // FIXME: It would be useful to check constexpr function templates, but at the | ||||
14062 | // moment the constant expression evaluator cannot cope with the non-rigorous | ||||
14063 | // ASTs which we build for dependent expressions. | ||||
14064 | if (FD->isDependentContext()) | ||||
14065 | return true; | ||||
14066 | |||||
14067 | Expr::EvalStatus Status; | ||||
14068 | Status.Diag = &Diags; | ||||
14069 | |||||
14070 | EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); | ||||
14071 | Info.InConstantContext = true; | ||||
14072 | Info.CheckingPotentialConstantExpression = true; | ||||
14073 | |||||
14074 | // The constexpr VM attempts to compile all methods to bytecode here. | ||||
14075 | if (Info.EnableNewConstInterp) { | ||||
14076 | auto &InterpCtx = Info.Ctx.getInterpContext(); | ||||
14077 | switch (InterpCtx.isPotentialConstantExpr(Info, FD)) { | ||||
14078 | case interp::InterpResult::Success: | ||||
14079 | case interp::InterpResult::Fail: | ||||
14080 | return Diags.empty(); | ||||
14081 | case interp::InterpResult::Bail: | ||||
14082 | break; | ||||
14083 | } | ||||
14084 | } | ||||
14085 | |||||
14086 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
14087 | const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; | ||||
14088 | |||||
14089 | // Fabricate an arbitrary expression on the stack and pretend that it | ||||
14090 | // is a temporary being used as the 'this' pointer. | ||||
14091 | LValue This; | ||||
14092 | ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); | ||||
14093 | This.set({&VIE, Info.CurrentCall->Index}); | ||||
14094 | |||||
14095 | ArrayRef<const Expr*> Args; | ||||
14096 | |||||
14097 | APValue Scratch; | ||||
14098 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { | ||||
14099 | // Evaluate the call as a constant initializer, to allow the construction | ||||
14100 | // of objects of non-literal types. | ||||
14101 | Info.setEvaluatingDecl(This.getLValueBase(), Scratch); | ||||
14102 | HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); | ||||
14103 | } else { | ||||
14104 | SourceLocation Loc = FD->getLocation(); | ||||
14105 | HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, | ||||
14106 | Args, FD->getBody(), Info, Scratch, nullptr); | ||||
14107 | } | ||||
14108 | |||||
14109 | return Diags.empty(); | ||||
14110 | } | ||||
14111 | |||||
14112 | bool Expr::isPotentialConstantExprUnevaluated(Expr *E, | ||||
14113 | const FunctionDecl *FD, | ||||
14114 | SmallVectorImpl< | ||||
14115 | PartialDiagnosticAt> &Diags) { | ||||
14116 | assert(!E->isValueDependent() &&((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14117, __PRETTY_FUNCTION__)) | ||||
14117 | "Expression evaluator can't be called on a dependent expression.")((!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression." ) ? static_cast<void> (0) : __assert_fail ("!E->isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14117, __PRETTY_FUNCTION__)); | ||||
14118 | |||||
14119 | Expr::EvalStatus Status; | ||||
14120 | Status.Diag = &Diags; | ||||
14121 | |||||
14122 | EvalInfo Info(FD->getASTContext(), Status, | ||||
14123 | EvalInfo::EM_ConstantExpressionUnevaluated); | ||||
14124 | Info.InConstantContext = true; | ||||
14125 | Info.CheckingPotentialConstantExpression = true; | ||||
14126 | |||||
14127 | // Fabricate a call stack frame to give the arguments a plausible cover story. | ||||
14128 | ArrayRef<const Expr*> Args; | ||||
14129 | ArgVector ArgValues(0); | ||||
14130 | bool Success = EvaluateArgs(Args, ArgValues, Info, FD); | ||||
14131 | (void)Success; | ||||
14132 | assert(Success &&((Success && "Failed to set up arguments for potential constant evaluation" ) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14133, __PRETTY_FUNCTION__)) | ||||
14133 | "Failed to set up arguments for potential constant evaluation")((Success && "Failed to set up arguments for potential constant evaluation" ) ? static_cast<void> (0) : __assert_fail ("Success && \"Failed to set up arguments for potential constant evaluation\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ExprConstant.cpp" , 14133, __PRETTY_FUNCTION__)); | ||||
14134 | CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); | ||||
14135 | |||||
14136 | APValue ResultScratch; | ||||
14137 | Evaluate(ResultScratch, Info, E); | ||||
14138 | return Diags.empty(); | ||||
14139 | } | ||||
14140 | |||||
14141 | bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, | ||||
14142 | unsigned Type) const { | ||||
14143 | if (!getType()->isPointerType()) | ||||
14144 | return false; | ||||
14145 | |||||
14146 | Expr::EvalStatus Status; | ||||
14147 | EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); | ||||
14148 | return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); | ||||
14149 | } |
1 | //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the Expr interface and subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_EXPR_H |
14 | #define LLVM_CLANG_AST_EXPR_H |
15 | |
16 | #include "clang/AST/APValue.h" |
17 | #include "clang/AST/ASTVector.h" |
18 | #include "clang/AST/Decl.h" |
19 | #include "clang/AST/DeclAccessPair.h" |
20 | #include "clang/AST/OperationKinds.h" |
21 | #include "clang/AST/Stmt.h" |
22 | #include "clang/AST/TemplateBase.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/Basic/CharInfo.h" |
25 | #include "clang/Basic/FixedPoint.h" |
26 | #include "clang/Basic/LangOptions.h" |
27 | #include "clang/Basic/SyncScope.h" |
28 | #include "clang/Basic/TypeTraits.h" |
29 | #include "llvm/ADT/APFloat.h" |
30 | #include "llvm/ADT/APSInt.h" |
31 | #include "llvm/ADT/iterator.h" |
32 | #include "llvm/ADT/iterator_range.h" |
33 | #include "llvm/ADT/SmallVector.h" |
34 | #include "llvm/ADT/StringRef.h" |
35 | #include "llvm/Support/AtomicOrdering.h" |
36 | #include "llvm/Support/Compiler.h" |
37 | #include "llvm/Support/TrailingObjects.h" |
38 | |
39 | namespace clang { |
40 | class APValue; |
41 | class ASTContext; |
42 | class BlockDecl; |
43 | class CXXBaseSpecifier; |
44 | class CXXMemberCallExpr; |
45 | class CXXOperatorCallExpr; |
46 | class CastExpr; |
47 | class Decl; |
48 | class IdentifierInfo; |
49 | class MaterializeTemporaryExpr; |
50 | class NamedDecl; |
51 | class ObjCPropertyRefExpr; |
52 | class OpaqueValueExpr; |
53 | class ParmVarDecl; |
54 | class StringLiteral; |
55 | class TargetInfo; |
56 | class ValueDecl; |
57 | |
58 | /// A simple array of base specifiers. |
59 | typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; |
60 | |
61 | /// An adjustment to be made to the temporary created when emitting a |
62 | /// reference binding, which accesses a particular subobject of that temporary. |
63 | struct SubobjectAdjustment { |
64 | enum { |
65 | DerivedToBaseAdjustment, |
66 | FieldAdjustment, |
67 | MemberPointerAdjustment |
68 | } Kind; |
69 | |
70 | struct DTB { |
71 | const CastExpr *BasePath; |
72 | const CXXRecordDecl *DerivedClass; |
73 | }; |
74 | |
75 | struct P { |
76 | const MemberPointerType *MPT; |
77 | Expr *RHS; |
78 | }; |
79 | |
80 | union { |
81 | struct DTB DerivedToBase; |
82 | FieldDecl *Field; |
83 | struct P Ptr; |
84 | }; |
85 | |
86 | SubobjectAdjustment(const CastExpr *BasePath, |
87 | const CXXRecordDecl *DerivedClass) |
88 | : Kind(DerivedToBaseAdjustment) { |
89 | DerivedToBase.BasePath = BasePath; |
90 | DerivedToBase.DerivedClass = DerivedClass; |
91 | } |
92 | |
93 | SubobjectAdjustment(FieldDecl *Field) |
94 | : Kind(FieldAdjustment) { |
95 | this->Field = Field; |
96 | } |
97 | |
98 | SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) |
99 | : Kind(MemberPointerAdjustment) { |
100 | this->Ptr.MPT = MPT; |
101 | this->Ptr.RHS = RHS; |
102 | } |
103 | }; |
104 | |
105 | /// This represents one expression. Note that Expr's are subclasses of Stmt. |
106 | /// This allows an expression to be transparently used any place a Stmt is |
107 | /// required. |
108 | class Expr : public ValueStmt { |
109 | QualType TR; |
110 | |
111 | public: |
112 | Expr() = delete; |
113 | Expr(const Expr&) = delete; |
114 | Expr(Expr &&) = delete; |
115 | Expr &operator=(const Expr&) = delete; |
116 | Expr &operator=(Expr&&) = delete; |
117 | |
118 | protected: |
119 | Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, |
120 | bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) |
121 | : ValueStmt(SC) |
122 | { |
123 | ExprBits.TypeDependent = TD; |
124 | ExprBits.ValueDependent = VD; |
125 | ExprBits.InstantiationDependent = ID; |
126 | ExprBits.ValueKind = VK; |
127 | ExprBits.ObjectKind = OK; |
128 | assert(ExprBits.ObjectKind == OK && "truncated kind")((ExprBits.ObjectKind == OK && "truncated kind") ? static_cast <void> (0) : __assert_fail ("ExprBits.ObjectKind == OK && \"truncated kind\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 128, __PRETTY_FUNCTION__)); |
129 | ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
130 | setType(T); |
131 | } |
132 | |
133 | /// Construct an empty expression. |
134 | explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { } |
135 | |
136 | public: |
137 | QualType getType() const { return TR; } |
138 | void setType(QualType t) { |
139 | // In C++, the type of an expression is always adjusted so that it |
140 | // will not have reference type (C++ [expr]p6). Use |
141 | // QualType::getNonReferenceType() to retrieve the non-reference |
142 | // type. Additionally, inspect Expr::isLvalue to determine whether |
143 | // an expression that is adjusted in this manner should be |
144 | // considered an lvalue. |
145 | assert((t.isNull() || !t->isReferenceType()) &&(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type" ) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 146, __PRETTY_FUNCTION__)) |
146 | "Expressions can't have reference type")(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type" ) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 146, __PRETTY_FUNCTION__)); |
147 | |
148 | TR = t; |
149 | } |
150 | |
151 | /// isValueDependent - Determines whether this expression is |
152 | /// value-dependent (C++ [temp.dep.constexpr]). For example, the |
153 | /// array bound of "Chars" in the following example is |
154 | /// value-dependent. |
155 | /// @code |
156 | /// template<int Size, char (&Chars)[Size]> struct meta_string; |
157 | /// @endcode |
158 | bool isValueDependent() const { return ExprBits.ValueDependent; } |
159 | |
160 | /// Set whether this expression is value-dependent or not. |
161 | void setValueDependent(bool VD) { |
162 | ExprBits.ValueDependent = VD; |
163 | } |
164 | |
165 | /// isTypeDependent - Determines whether this expression is |
166 | /// type-dependent (C++ [temp.dep.expr]), which means that its type |
167 | /// could change from one template instantiation to the next. For |
168 | /// example, the expressions "x" and "x + y" are type-dependent in |
169 | /// the following code, but "y" is not type-dependent: |
170 | /// @code |
171 | /// template<typename T> |
172 | /// void add(T x, int y) { |
173 | /// x + y; |
174 | /// } |
175 | /// @endcode |
176 | bool isTypeDependent() const { return ExprBits.TypeDependent; } |
177 | |
178 | /// Set whether this expression is type-dependent or not. |
179 | void setTypeDependent(bool TD) { |
180 | ExprBits.TypeDependent = TD; |
181 | } |
182 | |
183 | /// Whether this expression is instantiation-dependent, meaning that |
184 | /// it depends in some way on a template parameter, even if neither its type |
185 | /// nor (constant) value can change due to the template instantiation. |
186 | /// |
187 | /// In the following example, the expression \c sizeof(sizeof(T() + T())) is |
188 | /// instantiation-dependent (since it involves a template parameter \c T), but |
189 | /// is neither type- nor value-dependent, since the type of the inner |
190 | /// \c sizeof is known (\c std::size_t) and therefore the size of the outer |
191 | /// \c sizeof is known. |
192 | /// |
193 | /// \code |
194 | /// template<typename T> |
195 | /// void f(T x, T y) { |
196 | /// sizeof(sizeof(T() + T()); |
197 | /// } |
198 | /// \endcode |
199 | /// |
200 | bool isInstantiationDependent() const { |
201 | return ExprBits.InstantiationDependent; |
202 | } |
203 | |
204 | /// Set whether this expression is instantiation-dependent or not. |
205 | void setInstantiationDependent(bool ID) { |
206 | ExprBits.InstantiationDependent = ID; |
207 | } |
208 | |
209 | /// Whether this expression contains an unexpanded parameter |
210 | /// pack (for C++11 variadic templates). |
211 | /// |
212 | /// Given the following function template: |
213 | /// |
214 | /// \code |
215 | /// template<typename F, typename ...Types> |
216 | /// void forward(const F &f, Types &&...args) { |
217 | /// f(static_cast<Types&&>(args)...); |
218 | /// } |
219 | /// \endcode |
220 | /// |
221 | /// The expressions \c args and \c static_cast<Types&&>(args) both |
222 | /// contain parameter packs. |
223 | bool containsUnexpandedParameterPack() const { |
224 | return ExprBits.ContainsUnexpandedParameterPack; |
225 | } |
226 | |
227 | /// Set the bit that describes whether this expression |
228 | /// contains an unexpanded parameter pack. |
229 | void setContainsUnexpandedParameterPack(bool PP = true) { |
230 | ExprBits.ContainsUnexpandedParameterPack = PP; |
231 | } |
232 | |
233 | /// getExprLoc - Return the preferred location for the arrow when diagnosing |
234 | /// a problem with a generic expression. |
235 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)); |
236 | |
237 | /// isUnusedResultAWarning - Return true if this immediate expression should |
238 | /// be warned about if the result is unused. If so, fill in expr, location, |
239 | /// and ranges with expr to warn on and source locations/ranges appropriate |
240 | /// for a warning. |
241 | bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, |
242 | SourceRange &R1, SourceRange &R2, |
243 | ASTContext &Ctx) const; |
244 | |
245 | /// isLValue - True if this expression is an "l-value" according to |
246 | /// the rules of the current language. C and C++ give somewhat |
247 | /// different rules for this concept, but in general, the result of |
248 | /// an l-value expression identifies a specific object whereas the |
249 | /// result of an r-value expression is a value detached from any |
250 | /// specific storage. |
251 | /// |
252 | /// C++11 divides the concept of "r-value" into pure r-values |
253 | /// ("pr-values") and so-called expiring values ("x-values"), which |
254 | /// identify specific objects that can be safely cannibalized for |
255 | /// their resources. This is an unfortunate abuse of terminology on |
256 | /// the part of the C++ committee. In Clang, when we say "r-value", |
257 | /// we generally mean a pr-value. |
258 | bool isLValue() const { return getValueKind() == VK_LValue; } |
259 | bool isRValue() const { return getValueKind() == VK_RValue; } |
260 | bool isXValue() const { return getValueKind() == VK_XValue; } |
261 | bool isGLValue() const { return getValueKind() != VK_RValue; } |
262 | |
263 | enum LValueClassification { |
264 | LV_Valid, |
265 | LV_NotObjectType, |
266 | LV_IncompleteVoidType, |
267 | LV_DuplicateVectorComponents, |
268 | LV_InvalidExpression, |
269 | LV_InvalidMessageExpression, |
270 | LV_MemberFunction, |
271 | LV_SubObjCPropertySetting, |
272 | LV_ClassTemporary, |
273 | LV_ArrayTemporary |
274 | }; |
275 | /// Reasons why an expression might not be an l-value. |
276 | LValueClassification ClassifyLValue(ASTContext &Ctx) const; |
277 | |
278 | enum isModifiableLvalueResult { |
279 | MLV_Valid, |
280 | MLV_NotObjectType, |
281 | MLV_IncompleteVoidType, |
282 | MLV_DuplicateVectorComponents, |
283 | MLV_InvalidExpression, |
284 | MLV_LValueCast, // Specialized form of MLV_InvalidExpression. |
285 | MLV_IncompleteType, |
286 | MLV_ConstQualified, |
287 | MLV_ConstQualifiedField, |
288 | MLV_ConstAddrSpace, |
289 | MLV_ArrayType, |
290 | MLV_NoSetterProperty, |
291 | MLV_MemberFunction, |
292 | MLV_SubObjCPropertySetting, |
293 | MLV_InvalidMessageExpression, |
294 | MLV_ClassTemporary, |
295 | MLV_ArrayTemporary |
296 | }; |
297 | /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, |
298 | /// does not have an incomplete type, does not have a const-qualified type, |
299 | /// and if it is a structure or union, does not have any member (including, |
300 | /// recursively, any member or element of all contained aggregates or unions) |
301 | /// with a const-qualified type. |
302 | /// |
303 | /// \param Loc [in,out] - A source location which *may* be filled |
304 | /// in with the location of the expression making this a |
305 | /// non-modifiable lvalue, if specified. |
306 | isModifiableLvalueResult |
307 | isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; |
308 | |
309 | /// The return type of classify(). Represents the C++11 expression |
310 | /// taxonomy. |
311 | class Classification { |
312 | public: |
313 | /// The various classification results. Most of these mean prvalue. |
314 | enum Kinds { |
315 | CL_LValue, |
316 | CL_XValue, |
317 | CL_Function, // Functions cannot be lvalues in C. |
318 | CL_Void, // Void cannot be an lvalue in C. |
319 | CL_AddressableVoid, // Void expression whose address can be taken in C. |
320 | CL_DuplicateVectorComponents, // A vector shuffle with dupes. |
321 | CL_MemberFunction, // An expression referring to a member function |
322 | CL_SubObjCPropertySetting, |
323 | CL_ClassTemporary, // A temporary of class type, or subobject thereof. |
324 | CL_ArrayTemporary, // A temporary of array type. |
325 | CL_ObjCMessageRValue, // ObjC message is an rvalue |
326 | CL_PRValue // A prvalue for any other reason, of any other type |
327 | }; |
328 | /// The results of modification testing. |
329 | enum ModifiableType { |
330 | CM_Untested, // testModifiable was false. |
331 | CM_Modifiable, |
332 | CM_RValue, // Not modifiable because it's an rvalue |
333 | CM_Function, // Not modifiable because it's a function; C++ only |
334 | CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext |
335 | CM_NoSetterProperty,// Implicit assignment to ObjC property without setter |
336 | CM_ConstQualified, |
337 | CM_ConstQualifiedField, |
338 | CM_ConstAddrSpace, |
339 | CM_ArrayType, |
340 | CM_IncompleteType |
341 | }; |
342 | |
343 | private: |
344 | friend class Expr; |
345 | |
346 | unsigned short Kind; |
347 | unsigned short Modifiable; |
348 | |
349 | explicit Classification(Kinds k, ModifiableType m) |
350 | : Kind(k), Modifiable(m) |
351 | {} |
352 | |
353 | public: |
354 | Classification() {} |
355 | |
356 | Kinds getKind() const { return static_cast<Kinds>(Kind); } |
357 | ModifiableType getModifiable() const { |
358 | assert(Modifiable != CM_Untested && "Did not test for modifiability.")((Modifiable != CM_Untested && "Did not test for modifiability." ) ? static_cast<void> (0) : __assert_fail ("Modifiable != CM_Untested && \"Did not test for modifiability.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 358, __PRETTY_FUNCTION__)); |
359 | return static_cast<ModifiableType>(Modifiable); |
360 | } |
361 | bool isLValue() const { return Kind == CL_LValue; } |
362 | bool isXValue() const { return Kind == CL_XValue; } |
363 | bool isGLValue() const { return Kind <= CL_XValue; } |
364 | bool isPRValue() const { return Kind >= CL_Function; } |
365 | bool isRValue() const { return Kind >= CL_XValue; } |
366 | bool isModifiable() const { return getModifiable() == CM_Modifiable; } |
367 | |
368 | /// Create a simple, modifiably lvalue |
369 | static Classification makeSimpleLValue() { |
370 | return Classification(CL_LValue, CM_Modifiable); |
371 | } |
372 | |
373 | }; |
374 | /// Classify - Classify this expression according to the C++11 |
375 | /// expression taxonomy. |
376 | /// |
377 | /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the |
378 | /// old lvalue vs rvalue. This function determines the type of expression this |
379 | /// is. There are three expression types: |
380 | /// - lvalues are classical lvalues as in C++03. |
381 | /// - prvalues are equivalent to rvalues in C++03. |
382 | /// - xvalues are expressions yielding unnamed rvalue references, e.g. a |
383 | /// function returning an rvalue reference. |
384 | /// lvalues and xvalues are collectively referred to as glvalues, while |
385 | /// prvalues and xvalues together form rvalues. |
386 | Classification Classify(ASTContext &Ctx) const { |
387 | return ClassifyImpl(Ctx, nullptr); |
388 | } |
389 | |
390 | /// ClassifyModifiable - Classify this expression according to the |
391 | /// C++11 expression taxonomy, and see if it is valid on the left side |
392 | /// of an assignment. |
393 | /// |
394 | /// This function extends classify in that it also tests whether the |
395 | /// expression is modifiable (C99 6.3.2.1p1). |
396 | /// \param Loc A source location that might be filled with a relevant location |
397 | /// if the expression is not modifiable. |
398 | Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ |
399 | return ClassifyImpl(Ctx, &Loc); |
400 | } |
401 | |
402 | /// getValueKindForType - Given a formal return or parameter type, |
403 | /// give its value kind. |
404 | static ExprValueKind getValueKindForType(QualType T) { |
405 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) |
406 | return (isa<LValueReferenceType>(RT) |
407 | ? VK_LValue |
408 | : (RT->getPointeeType()->isFunctionType() |
409 | ? VK_LValue : VK_XValue)); |
410 | return VK_RValue; |
411 | } |
412 | |
413 | /// getValueKind - The value kind that this expression produces. |
414 | ExprValueKind getValueKind() const { |
415 | return static_cast<ExprValueKind>(ExprBits.ValueKind); |
416 | } |
417 | |
418 | /// getObjectKind - The object kind that this expression produces. |
419 | /// Object kinds are meaningful only for expressions that yield an |
420 | /// l-value or x-value. |
421 | ExprObjectKind getObjectKind() const { |
422 | return static_cast<ExprObjectKind>(ExprBits.ObjectKind); |
423 | } |
424 | |
425 | bool isOrdinaryOrBitFieldObject() const { |
426 | ExprObjectKind OK = getObjectKind(); |
427 | return (OK == OK_Ordinary || OK == OK_BitField); |
428 | } |
429 | |
430 | /// setValueKind - Set the value kind produced by this expression. |
431 | void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } |
432 | |
433 | /// setObjectKind - Set the object kind produced by this expression. |
434 | void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } |
435 | |
436 | private: |
437 | Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; |
438 | |
439 | public: |
440 | |
441 | /// Returns true if this expression is a gl-value that |
442 | /// potentially refers to a bit-field. |
443 | /// |
444 | /// In C++, whether a gl-value refers to a bitfield is essentially |
445 | /// an aspect of the value-kind type system. |
446 | bool refersToBitField() const { return getObjectKind() == OK_BitField; } |
447 | |
448 | /// If this expression refers to a bit-field, retrieve the |
449 | /// declaration of that bit-field. |
450 | /// |
451 | /// Note that this returns a non-null pointer in subtly different |
452 | /// places than refersToBitField returns true. In particular, this can |
453 | /// return a non-null pointer even for r-values loaded from |
454 | /// bit-fields, but it will return null for a conditional bit-field. |
455 | FieldDecl *getSourceBitField(); |
456 | |
457 | const FieldDecl *getSourceBitField() const { |
458 | return const_cast<Expr*>(this)->getSourceBitField(); |
459 | } |
460 | |
461 | Decl *getReferencedDeclOfCallee(); |
462 | const Decl *getReferencedDeclOfCallee() const { |
463 | return const_cast<Expr*>(this)->getReferencedDeclOfCallee(); |
464 | } |
465 | |
466 | /// If this expression is an l-value for an Objective C |
467 | /// property, find the underlying property reference expression. |
468 | const ObjCPropertyRefExpr *getObjCProperty() const; |
469 | |
470 | /// Check if this expression is the ObjC 'self' implicit parameter. |
471 | bool isObjCSelfExpr() const; |
472 | |
473 | /// Returns whether this expression refers to a vector element. |
474 | bool refersToVectorElement() const; |
475 | |
476 | /// Returns whether this expression refers to a global register |
477 | /// variable. |
478 | bool refersToGlobalRegisterVar() const; |
479 | |
480 | /// Returns whether this expression has a placeholder type. |
481 | bool hasPlaceholderType() const { |
482 | return getType()->isPlaceholderType(); |
483 | } |
484 | |
485 | /// Returns whether this expression has a specific placeholder type. |
486 | bool hasPlaceholderType(BuiltinType::Kind K) const { |
487 | assert(BuiltinType::isPlaceholderTypeKind(K))((BuiltinType::isPlaceholderTypeKind(K)) ? static_cast<void > (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind(K)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 487, __PRETTY_FUNCTION__)); |
488 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType())) |
489 | return BT->getKind() == K; |
490 | return false; |
491 | } |
492 | |
493 | /// isKnownToHaveBooleanValue - Return true if this is an integer expression |
494 | /// that is known to return 0 or 1. This happens for _Bool/bool expressions |
495 | /// but also int expressions which are produced by things like comparisons in |
496 | /// C. |
497 | bool isKnownToHaveBooleanValue() const; |
498 | |
499 | /// isIntegerConstantExpr - Return true if this expression is a valid integer |
500 | /// constant expression, and, if so, return its value in Result. If not a |
501 | /// valid i-c-e, return false and fill in Loc (if specified) with the location |
502 | /// of the invalid expression. |
503 | /// |
504 | /// Note: This does not perform the implicit conversions required by C++11 |
505 | /// [expr.const]p5. |
506 | bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, |
507 | SourceLocation *Loc = nullptr, |
508 | bool isEvaluated = true) const; |
509 | bool isIntegerConstantExpr(const ASTContext &Ctx, |
510 | SourceLocation *Loc = nullptr) const; |
511 | |
512 | /// isCXX98IntegralConstantExpr - Return true if this expression is an |
513 | /// integral constant expression in C++98. Can only be used in C++. |
514 | bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; |
515 | |
516 | /// isCXX11ConstantExpr - Return true if this expression is a constant |
517 | /// expression in C++11. Can only be used in C++. |
518 | /// |
519 | /// Note: This does not perform the implicit conversions required by C++11 |
520 | /// [expr.const]p5. |
521 | bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, |
522 | SourceLocation *Loc = nullptr) const; |
523 | |
524 | /// isPotentialConstantExpr - Return true if this function's definition |
525 | /// might be usable in a constant expression in C++11, if it were marked |
526 | /// constexpr. Return false if the function can never produce a constant |
527 | /// expression, along with diagnostics describing why not. |
528 | static bool isPotentialConstantExpr(const FunctionDecl *FD, |
529 | SmallVectorImpl< |
530 | PartialDiagnosticAt> &Diags); |
531 | |
532 | /// isPotentialConstantExprUnevaluted - Return true if this expression might |
533 | /// be usable in a constant expression in C++11 in an unevaluated context, if |
534 | /// it were in function FD marked constexpr. Return false if the function can |
535 | /// never produce a constant expression, along with diagnostics describing |
536 | /// why not. |
537 | static bool isPotentialConstantExprUnevaluated(Expr *E, |
538 | const FunctionDecl *FD, |
539 | SmallVectorImpl< |
540 | PartialDiagnosticAt> &Diags); |
541 | |
542 | /// isConstantInitializer - Returns true if this expression can be emitted to |
543 | /// IR as a constant, and thus can be used as a constant initializer in C. |
544 | /// If this expression is not constant and Culprit is non-null, |
545 | /// it is used to store the address of first non constant expr. |
546 | bool isConstantInitializer(ASTContext &Ctx, bool ForRef, |
547 | const Expr **Culprit = nullptr) const; |
548 | |
549 | /// EvalStatus is a struct with detailed info about an evaluation in progress. |
550 | struct EvalStatus { |
551 | /// Whether the evaluated expression has side effects. |
552 | /// For example, (f() && 0) can be folded, but it still has side effects. |
553 | bool HasSideEffects; |
554 | |
555 | /// Whether the evaluation hit undefined behavior. |
556 | /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. |
557 | /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. |
558 | bool HasUndefinedBehavior; |
559 | |
560 | /// Diag - If this is non-null, it will be filled in with a stack of notes |
561 | /// indicating why evaluation failed (or why it failed to produce a constant |
562 | /// expression). |
563 | /// If the expression is unfoldable, the notes will indicate why it's not |
564 | /// foldable. If the expression is foldable, but not a constant expression, |
565 | /// the notes will describes why it isn't a constant expression. If the |
566 | /// expression *is* a constant expression, no notes will be produced. |
567 | SmallVectorImpl<PartialDiagnosticAt> *Diag; |
568 | |
569 | EvalStatus() |
570 | : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {} |
571 | |
572 | // hasSideEffects - Return true if the evaluated expression has |
573 | // side effects. |
574 | bool hasSideEffects() const { |
575 | return HasSideEffects; |
576 | } |
577 | }; |
578 | |
579 | /// EvalResult is a struct with detailed info about an evaluated expression. |
580 | struct EvalResult : EvalStatus { |
581 | /// Val - This is the value the expression can be folded to. |
582 | APValue Val; |
583 | |
584 | // isGlobalLValue - Return true if the evaluated lvalue expression |
585 | // is global. |
586 | bool isGlobalLValue() const; |
587 | }; |
588 | |
589 | /// EvaluateAsRValue - Return true if this is a constant which we can fold to |
590 | /// an rvalue using any crazy technique (that has nothing to do with language |
591 | /// standards) that we want to, even if the expression has side-effects. If |
592 | /// this function returns true, it returns the folded constant in Result. If |
593 | /// the expression is a glvalue, an lvalue-to-rvalue conversion will be |
594 | /// applied. |
595 | bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, |
596 | bool InConstantContext = false) const; |
597 | |
598 | /// EvaluateAsBooleanCondition - Return true if this is a constant |
599 | /// which we can fold and convert to a boolean condition using |
600 | /// any crazy technique that we want to, even if the expression has |
601 | /// side-effects. |
602 | bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, |
603 | bool InConstantContext = false) const; |
604 | |
605 | enum SideEffectsKind { |
606 | SE_NoSideEffects, ///< Strictly evaluate the expression. |
607 | SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not |
608 | ///< arbitrary unmodeled side effects. |
609 | SE_AllowSideEffects ///< Allow any unmodeled side effect. |
610 | }; |
611 | |
612 | /// EvaluateAsInt - Return true if this is a constant which we can fold and |
613 | /// convert to an integer, using any crazy technique that we want to. |
614 | bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, |
615 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
616 | bool InConstantContext = false) const; |
617 | |
618 | /// EvaluateAsFloat - Return true if this is a constant which we can fold and |
619 | /// convert to a floating point value, using any crazy technique that we |
620 | /// want to. |
621 | bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, |
622 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
623 | bool InConstantContext = false) const; |
624 | |
625 | /// EvaluateAsFloat - Return true if this is a constant which we can fold and |
626 | /// convert to a fixed point value. |
627 | bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, |
628 | SideEffectsKind AllowSideEffects = SE_NoSideEffects, |
629 | bool InConstantContext = false) const; |
630 | |
631 | /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be |
632 | /// constant folded without side-effects, but discard the result. |
633 | bool isEvaluatable(const ASTContext &Ctx, |
634 | SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; |
635 | |
636 | /// HasSideEffects - This routine returns true for all those expressions |
637 | /// which have any effect other than producing a value. Example is a function |
638 | /// call, volatile variable read, or throwing an exception. If |
639 | /// IncludePossibleEffects is false, this call treats certain expressions with |
640 | /// potential side effects (such as function call-like expressions, |
641 | /// instantiation-dependent expressions, or invocations from a macro) as not |
642 | /// having side effects. |
643 | bool HasSideEffects(const ASTContext &Ctx, |
644 | bool IncludePossibleEffects = true) const; |
645 | |
646 | /// Determine whether this expression involves a call to any function |
647 | /// that is not trivial. |
648 | bool hasNonTrivialCall(const ASTContext &Ctx) const; |
649 | |
650 | /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded |
651 | /// integer. This must be called on an expression that constant folds to an |
652 | /// integer. |
653 | llvm::APSInt EvaluateKnownConstInt( |
654 | const ASTContext &Ctx, |
655 | SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; |
656 | |
657 | llvm::APSInt EvaluateKnownConstIntCheckOverflow( |
658 | const ASTContext &Ctx, |
659 | SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const; |
660 | |
661 | void EvaluateForOverflow(const ASTContext &Ctx) const; |
662 | |
663 | /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an |
664 | /// lvalue with link time known address, with no side-effects. |
665 | bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, |
666 | bool InConstantContext = false) const; |
667 | |
668 | /// EvaluateAsInitializer - Evaluate an expression as if it were the |
669 | /// initializer of the given declaration. Returns true if the initializer |
670 | /// can be folded to a constant, and produces any relevant notes. In C++11, |
671 | /// notes will be produced if the expression is not a constant expression. |
672 | bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, |
673 | const VarDecl *VD, |
674 | SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
675 | |
676 | /// EvaluateWithSubstitution - Evaluate an expression as if from the context |
677 | /// of a call to the given function with the given arguments, inside an |
678 | /// unevaluated context. Returns true if the expression could be folded to a |
679 | /// constant. |
680 | bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, |
681 | const FunctionDecl *Callee, |
682 | ArrayRef<const Expr*> Args, |
683 | const Expr *This = nullptr) const; |
684 | |
685 | /// Indicates how the constant expression will be used. |
686 | enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling }; |
687 | |
688 | /// Evaluate an expression that is required to be a constant expression. |
689 | bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, |
690 | const ASTContext &Ctx) const; |
691 | |
692 | /// If the current Expr is a pointer, this will try to statically |
693 | /// determine the number of bytes available where the pointer is pointing. |
694 | /// Returns true if all of the above holds and we were able to figure out the |
695 | /// size, false otherwise. |
696 | /// |
697 | /// \param Type - How to evaluate the size of the Expr, as defined by the |
698 | /// "type" parameter of __builtin_object_size |
699 | bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, |
700 | unsigned Type) const; |
701 | |
702 | /// Enumeration used to describe the kind of Null pointer constant |
703 | /// returned from \c isNullPointerConstant(). |
704 | enum NullPointerConstantKind { |
705 | /// Expression is not a Null pointer constant. |
706 | NPCK_NotNull = 0, |
707 | |
708 | /// Expression is a Null pointer constant built from a zero integer |
709 | /// expression that is not a simple, possibly parenthesized, zero literal. |
710 | /// C++ Core Issue 903 will classify these expressions as "not pointers" |
711 | /// once it is adopted. |
712 | /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
713 | NPCK_ZeroExpression, |
714 | |
715 | /// Expression is a Null pointer constant built from a literal zero. |
716 | NPCK_ZeroLiteral, |
717 | |
718 | /// Expression is a C++11 nullptr. |
719 | NPCK_CXX11_nullptr, |
720 | |
721 | /// Expression is a GNU-style __null constant. |
722 | NPCK_GNUNull |
723 | }; |
724 | |
725 | /// Enumeration used to describe how \c isNullPointerConstant() |
726 | /// should cope with value-dependent expressions. |
727 | enum NullPointerConstantValueDependence { |
728 | /// Specifies that the expression should never be value-dependent. |
729 | NPC_NeverValueDependent = 0, |
730 | |
731 | /// Specifies that a value-dependent expression of integral or |
732 | /// dependent type should be considered a null pointer constant. |
733 | NPC_ValueDependentIsNull, |
734 | |
735 | /// Specifies that a value-dependent expression should be considered |
736 | /// to never be a null pointer constant. |
737 | NPC_ValueDependentIsNotNull |
738 | }; |
739 | |
740 | /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to |
741 | /// a Null pointer constant. The return value can further distinguish the |
742 | /// kind of NULL pointer constant that was detected. |
743 | NullPointerConstantKind isNullPointerConstant( |
744 | ASTContext &Ctx, |
745 | NullPointerConstantValueDependence NPC) const; |
746 | |
747 | /// isOBJCGCCandidate - Return true if this expression may be used in a read/ |
748 | /// write barrier. |
749 | bool isOBJCGCCandidate(ASTContext &Ctx) const; |
750 | |
751 | /// Returns true if this expression is a bound member function. |
752 | bool isBoundMemberFunction(ASTContext &Ctx) const; |
753 | |
754 | /// Given an expression of bound-member type, find the type |
755 | /// of the member. Returns null if this is an *overloaded* bound |
756 | /// member expression. |
757 | static QualType findBoundMemberType(const Expr *expr); |
758 | |
759 | /// Skip past any implicit casts which might surround this expression until |
760 | /// reaching a fixed point. Skips: |
761 | /// * ImplicitCastExpr |
762 | /// * FullExpr |
763 | Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__)); |
764 | const Expr *IgnoreImpCasts() const { |
765 | return const_cast<Expr *>(this)->IgnoreImpCasts(); |
766 | } |
767 | |
768 | /// Skip past any casts which might surround this expression until reaching |
769 | /// a fixed point. Skips: |
770 | /// * CastExpr |
771 | /// * FullExpr |
772 | /// * MaterializeTemporaryExpr |
773 | /// * SubstNonTypeTemplateParmExpr |
774 | Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__)); |
775 | const Expr *IgnoreCasts() const { |
776 | return const_cast<Expr *>(this)->IgnoreCasts(); |
777 | } |
778 | |
779 | /// Skip past any implicit AST nodes which might surround this expression |
780 | /// until reaching a fixed point. Skips: |
781 | /// * What IgnoreImpCasts() skips |
782 | /// * MaterializeTemporaryExpr |
783 | /// * CXXBindTemporaryExpr |
784 | Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__)); |
785 | const Expr *IgnoreImplicit() const { |
786 | return const_cast<Expr *>(this)->IgnoreImplicit(); |
787 | } |
788 | |
789 | /// Skip past any parentheses which might surround this expression until |
790 | /// reaching a fixed point. Skips: |
791 | /// * ParenExpr |
792 | /// * UnaryOperator if `UO_Extension` |
793 | /// * GenericSelectionExpr if `!isResultDependent()` |
794 | /// * ChooseExpr if `!isConditionDependent()` |
795 | /// * ConstantExpr |
796 | Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__)); |
797 | const Expr *IgnoreParens() const { |
798 | return const_cast<Expr *>(this)->IgnoreParens(); |
799 | } |
800 | |
801 | /// Skip past any parentheses and implicit casts which might surround this |
802 | /// expression until reaching a fixed point. |
803 | /// FIXME: IgnoreParenImpCasts really ought to be equivalent to |
804 | /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However |
805 | /// this is currently not the case. Instead IgnoreParenImpCasts() skips: |
806 | /// * What IgnoreParens() skips |
807 | /// * What IgnoreImpCasts() skips |
808 | /// * MaterializeTemporaryExpr |
809 | /// * SubstNonTypeTemplateParmExpr |
810 | Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__)); |
811 | const Expr *IgnoreParenImpCasts() const { |
812 | return const_cast<Expr *>(this)->IgnoreParenImpCasts(); |
813 | } |
814 | |
815 | /// Skip past any parentheses and casts which might surround this expression |
816 | /// until reaching a fixed point. Skips: |
817 | /// * What IgnoreParens() skips |
818 | /// * What IgnoreCasts() skips |
819 | Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__)); |
820 | const Expr *IgnoreParenCasts() const { |
821 | return const_cast<Expr *>(this)->IgnoreParenCasts(); |
822 | } |
823 | |
824 | /// Skip conversion operators. If this Expr is a call to a conversion |
825 | /// operator, return the argument. |
826 | Expr *IgnoreConversionOperator() LLVM_READONLY__attribute__((__pure__)); |
827 | const Expr *IgnoreConversionOperator() const { |
828 | return const_cast<Expr *>(this)->IgnoreConversionOperator(); |
829 | } |
830 | |
831 | /// Skip past any parentheses and lvalue casts which might surround this |
832 | /// expression until reaching a fixed point. Skips: |
833 | /// * What IgnoreParens() skips |
834 | /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue |
835 | /// casts are skipped |
836 | /// FIXME: This is intended purely as a temporary workaround for code |
837 | /// that hasn't yet been rewritten to do the right thing about those |
838 | /// casts, and may disappear along with the last internal use. |
839 | Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__)); |
840 | const Expr *IgnoreParenLValueCasts() const { |
841 | return const_cast<Expr *>(this)->IgnoreParenLValueCasts(); |
842 | } |
843 | |
844 | /// Skip past any parenthese and casts which do not change the value |
845 | /// (including ptr->int casts of the same size) until reaching a fixed point. |
846 | /// Skips: |
847 | /// * What IgnoreParens() skips |
848 | /// * CastExpr which do not change the value |
849 | /// * SubstNonTypeTemplateParmExpr |
850 | Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__)); |
851 | const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const { |
852 | return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx); |
853 | } |
854 | |
855 | /// Skip past any parentheses and derived-to-base casts until reaching a |
856 | /// fixed point. Skips: |
857 | /// * What IgnoreParens() skips |
858 | /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase, |
859 | /// CK_UncheckedDerivedToBase and CK_NoOp) |
860 | Expr *ignoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__)); |
861 | const Expr *ignoreParenBaseCasts() const { |
862 | return const_cast<Expr *>(this)->ignoreParenBaseCasts(); |
863 | } |
864 | |
865 | /// Determine whether this expression is a default function argument. |
866 | /// |
867 | /// Default arguments are implicitly generated in the abstract syntax tree |
868 | /// by semantic analysis for function calls, object constructions, etc. in |
869 | /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; |
870 | /// this routine also looks through any implicit casts to determine whether |
871 | /// the expression is a default argument. |
872 | bool isDefaultArgument() const; |
873 | |
874 | /// Determine whether the result of this expression is a |
875 | /// temporary object of the given class type. |
876 | bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; |
877 | |
878 | /// Whether this expression is an implicit reference to 'this' in C++. |
879 | bool isImplicitCXXThis() const; |
880 | |
881 | static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs); |
882 | |
883 | /// For an expression of class type or pointer to class type, |
884 | /// return the most derived class decl the expression is known to refer to. |
885 | /// |
886 | /// If this expression is a cast, this method looks through it to find the |
887 | /// most derived decl that can be inferred from the expression. |
888 | /// This is valid because derived-to-base conversions have undefined |
889 | /// behavior if the object isn't dynamically of the derived type. |
890 | const CXXRecordDecl *getBestDynamicClassType() const; |
891 | |
892 | /// Get the inner expression that determines the best dynamic class. |
893 | /// If this is a prvalue, we guarantee that it is of the most-derived type |
894 | /// for the object itself. |
895 | const Expr *getBestDynamicClassTypeExpr() const; |
896 | |
897 | /// Walk outwards from an expression we want to bind a reference to and |
898 | /// find the expression whose lifetime needs to be extended. Record |
899 | /// the LHSs of comma expressions and adjustments needed along the path. |
900 | const Expr *skipRValueSubobjectAdjustments( |
901 | SmallVectorImpl<const Expr *> &CommaLHS, |
902 | SmallVectorImpl<SubobjectAdjustment> &Adjustments) const; |
903 | const Expr *skipRValueSubobjectAdjustments() const { |
904 | SmallVector<const Expr *, 8> CommaLHSs; |
905 | SmallVector<SubobjectAdjustment, 8> Adjustments; |
906 | return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); |
907 | } |
908 | |
909 | /// Checks that the two Expr's will refer to the same value as a comparison |
910 | /// operand. The caller must ensure that the values referenced by the Expr's |
911 | /// are not modified between E1 and E2 or the result my be invalid. |
912 | static bool isSameComparisonOperand(const Expr* E1, const Expr* E2); |
913 | |
914 | static bool classof(const Stmt *T) { |
915 | return T->getStmtClass() >= firstExprConstant && |
916 | T->getStmtClass() <= lastExprConstant; |
917 | } |
918 | }; |
919 | |
920 | //===----------------------------------------------------------------------===// |
921 | // Wrapper Expressions. |
922 | //===----------------------------------------------------------------------===// |
923 | |
924 | /// FullExpr - Represents a "full-expression" node. |
925 | class FullExpr : public Expr { |
926 | protected: |
927 | Stmt *SubExpr; |
928 | |
929 | FullExpr(StmtClass SC, Expr *subexpr) |
930 | : Expr(SC, subexpr->getType(), |
931 | subexpr->getValueKind(), subexpr->getObjectKind(), |
932 | subexpr->isTypeDependent(), subexpr->isValueDependent(), |
933 | subexpr->isInstantiationDependent(), |
934 | subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {} |
935 | FullExpr(StmtClass SC, EmptyShell Empty) |
936 | : Expr(SC, Empty) {} |
937 | public: |
938 | const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } |
939 | Expr *getSubExpr() { return cast<Expr>(SubExpr); } |
940 | |
941 | /// As with any mutator of the AST, be very careful when modifying an |
942 | /// existing AST to preserve its invariants. |
943 | void setSubExpr(Expr *E) { SubExpr = E; } |
944 | |
945 | static bool classof(const Stmt *T) { |
946 | return T->getStmtClass() >= firstFullExprConstant && |
947 | T->getStmtClass() <= lastFullExprConstant; |
948 | } |
949 | }; |
950 | |
951 | /// ConstantExpr - An expression that occurs in a constant context and |
952 | /// optionally the result of evaluating the expression. |
953 | class ConstantExpr final |
954 | : public FullExpr, |
955 | private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> { |
956 | static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value, |
957 | "this class assumes llvm::APInt::WordType is uint64_t for " |
958 | "trail-allocated storage"); |
959 | |
960 | public: |
961 | /// Describes the kind of result that can be trail-allocated. |
962 | enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue }; |
963 | |
964 | private: |
965 | size_t numTrailingObjects(OverloadToken<APValue>) const { |
966 | return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue; |
967 | } |
968 | size_t numTrailingObjects(OverloadToken<uint64_t>) const { |
969 | return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64; |
970 | } |
971 | |
972 | void DefaultInit(ResultStorageKind StorageKind); |
973 | uint64_t &Int64Result() { |
974 | assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 975, __PRETTY_FUNCTION__)) |
975 | "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 975, __PRETTY_FUNCTION__)); |
976 | return *getTrailingObjects<uint64_t>(); |
977 | } |
978 | const uint64_t &Int64Result() const { |
979 | return const_cast<ConstantExpr *>(this)->Int64Result(); |
980 | } |
981 | APValue &APValueResult() { |
982 | assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 983, __PRETTY_FUNCTION__)) |
983 | "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && "invalid accessor") ? static_cast<void> (0) : __assert_fail ("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 983, __PRETTY_FUNCTION__)); |
984 | return *getTrailingObjects<APValue>(); |
985 | } |
986 | const APValue &APValueResult() const { |
987 | return const_cast<ConstantExpr *>(this)->APValueResult(); |
988 | } |
989 | |
990 | ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind); |
991 | ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty); |
992 | |
993 | public: |
994 | friend TrailingObjects; |
995 | friend class ASTStmtReader; |
996 | friend class ASTStmtWriter; |
997 | static ConstantExpr *Create(const ASTContext &Context, Expr *E, |
998 | const APValue &Result); |
999 | static ConstantExpr *Create(const ASTContext &Context, Expr *E, |
1000 | ResultStorageKind Storage = RSK_None); |
1001 | static ConstantExpr *CreateEmpty(const ASTContext &Context, |
1002 | ResultStorageKind StorageKind, |
1003 | EmptyShell Empty); |
1004 | |
1005 | static ResultStorageKind getStorageKind(const APValue &Value); |
1006 | static ResultStorageKind getStorageKind(const Type *T, |
1007 | const ASTContext &Context); |
1008 | |
1009 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1010 | return SubExpr->getBeginLoc(); |
1011 | } |
1012 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1013 | return SubExpr->getEndLoc(); |
1014 | } |
1015 | |
1016 | static bool classof(const Stmt *T) { |
1017 | return T->getStmtClass() == ConstantExprClass; |
1018 | } |
1019 | |
1020 | void SetResult(APValue Value, const ASTContext &Context) { |
1021 | MoveIntoResult(Value, Context); |
1022 | } |
1023 | void MoveIntoResult(APValue &Value, const ASTContext &Context); |
1024 | |
1025 | APValue::ValueKind getResultAPValueKind() const { |
1026 | return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind); |
1027 | } |
1028 | ResultStorageKind getResultStorageKind() const { |
1029 | return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind); |
1030 | } |
1031 | APValue getAPValueResult() const; |
1032 | const APValue &getResultAsAPValue() const { return APValueResult(); } |
1033 | llvm::APSInt getResultAsAPSInt() const; |
1034 | // Iterators |
1035 | child_range children() { return child_range(&SubExpr, &SubExpr+1); } |
1036 | const_child_range children() const { |
1037 | return const_child_range(&SubExpr, &SubExpr + 1); |
1038 | } |
1039 | }; |
1040 | |
1041 | //===----------------------------------------------------------------------===// |
1042 | // Primary Expressions. |
1043 | //===----------------------------------------------------------------------===// |
1044 | |
1045 | /// OpaqueValueExpr - An expression referring to an opaque object of a |
1046 | /// fixed type and value class. These don't correspond to concrete |
1047 | /// syntax; instead they're used to express operations (usually copy |
1048 | /// operations) on values whose source is generally obvious from |
1049 | /// context. |
1050 | class OpaqueValueExpr : public Expr { |
1051 | friend class ASTStmtReader; |
1052 | Expr *SourceExpr; |
1053 | |
1054 | public: |
1055 | OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, |
1056 | ExprObjectKind OK = OK_Ordinary, |
1057 | Expr *SourceExpr = nullptr) |
1058 | : Expr(OpaqueValueExprClass, T, VK, OK, |
1059 | T->isDependentType() || |
1060 | (SourceExpr && SourceExpr->isTypeDependent()), |
1061 | T->isDependentType() || |
1062 | (SourceExpr && SourceExpr->isValueDependent()), |
1063 | T->isInstantiationDependentType() || |
1064 | (SourceExpr && SourceExpr->isInstantiationDependent()), |
1065 | false), |
1066 | SourceExpr(SourceExpr) { |
1067 | setIsUnique(false); |
1068 | OpaqueValueExprBits.Loc = Loc; |
1069 | } |
1070 | |
1071 | /// Given an expression which invokes a copy constructor --- i.e. a |
1072 | /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- |
1073 | /// find the OpaqueValueExpr that's the source of the construction. |
1074 | static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); |
1075 | |
1076 | explicit OpaqueValueExpr(EmptyShell Empty) |
1077 | : Expr(OpaqueValueExprClass, Empty) {} |
1078 | |
1079 | /// Retrieve the location of this expression. |
1080 | SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; } |
1081 | |
1082 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1083 | return SourceExpr ? SourceExpr->getBeginLoc() : getLocation(); |
1084 | } |
1085 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1086 | return SourceExpr ? SourceExpr->getEndLoc() : getLocation(); |
1087 | } |
1088 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1089 | return SourceExpr ? SourceExpr->getExprLoc() : getLocation(); |
1090 | } |
1091 | |
1092 | child_range children() { |
1093 | return child_range(child_iterator(), child_iterator()); |
1094 | } |
1095 | |
1096 | const_child_range children() const { |
1097 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1098 | } |
1099 | |
1100 | /// The source expression of an opaque value expression is the |
1101 | /// expression which originally generated the value. This is |
1102 | /// provided as a convenience for analyses that don't wish to |
1103 | /// precisely model the execution behavior of the program. |
1104 | /// |
1105 | /// The source expression is typically set when building the |
1106 | /// expression which binds the opaque value expression in the first |
1107 | /// place. |
1108 | Expr *getSourceExpr() const { return SourceExpr; } |
1109 | |
1110 | void setIsUnique(bool V) { |
1111 | assert((!V || SourceExpr) &&(((!V || SourceExpr) && "unique OVEs are expected to have source expressions" ) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1112, __PRETTY_FUNCTION__)) |
1112 | "unique OVEs are expected to have source expressions")(((!V || SourceExpr) && "unique OVEs are expected to have source expressions" ) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1112, __PRETTY_FUNCTION__)); |
1113 | OpaqueValueExprBits.IsUnique = V; |
1114 | } |
1115 | |
1116 | bool isUnique() const { return OpaqueValueExprBits.IsUnique; } |
1117 | |
1118 | static bool classof(const Stmt *T) { |
1119 | return T->getStmtClass() == OpaqueValueExprClass; |
1120 | } |
1121 | }; |
1122 | |
1123 | /// A reference to a declared variable, function, enum, etc. |
1124 | /// [C99 6.5.1p2] |
1125 | /// |
1126 | /// This encodes all the information about how a declaration is referenced |
1127 | /// within an expression. |
1128 | /// |
1129 | /// There are several optional constructs attached to DeclRefExprs only when |
1130 | /// they apply in order to conserve memory. These are laid out past the end of |
1131 | /// the object, and flags in the DeclRefExprBitfield track whether they exist: |
1132 | /// |
1133 | /// DeclRefExprBits.HasQualifier: |
1134 | /// Specifies when this declaration reference expression has a C++ |
1135 | /// nested-name-specifier. |
1136 | /// DeclRefExprBits.HasFoundDecl: |
1137 | /// Specifies when this declaration reference expression has a record of |
1138 | /// a NamedDecl (different from the referenced ValueDecl) which was found |
1139 | /// during name lookup and/or overload resolution. |
1140 | /// DeclRefExprBits.HasTemplateKWAndArgsInfo: |
1141 | /// Specifies when this declaration reference expression has an explicit |
1142 | /// C++ template keyword and/or template argument list. |
1143 | /// DeclRefExprBits.RefersToEnclosingVariableOrCapture |
1144 | /// Specifies when this declaration reference expression (validly) |
1145 | /// refers to an enclosed local or a captured variable. |
1146 | class DeclRefExpr final |
1147 | : public Expr, |
1148 | private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc, |
1149 | NamedDecl *, ASTTemplateKWAndArgsInfo, |
1150 | TemplateArgumentLoc> { |
1151 | friend class ASTStmtReader; |
1152 | friend class ASTStmtWriter; |
1153 | friend TrailingObjects; |
1154 | |
1155 | /// The declaration that we are referencing. |
1156 | ValueDecl *D; |
1157 | |
1158 | /// Provides source/type location info for the declaration name |
1159 | /// embedded in D. |
1160 | DeclarationNameLoc DNLoc; |
1161 | |
1162 | size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const { |
1163 | return hasQualifier(); |
1164 | } |
1165 | |
1166 | size_t numTrailingObjects(OverloadToken<NamedDecl *>) const { |
1167 | return hasFoundDecl(); |
1168 | } |
1169 | |
1170 | size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { |
1171 | return hasTemplateKWAndArgsInfo(); |
1172 | } |
1173 | |
1174 | /// Test whether there is a distinct FoundDecl attached to the end of |
1175 | /// this DRE. |
1176 | bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } |
1177 | |
1178 | DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, |
1179 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1180 | bool RefersToEnlosingVariableOrCapture, |
1181 | const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, |
1182 | const TemplateArgumentListInfo *TemplateArgs, QualType T, |
1183 | ExprValueKind VK, NonOdrUseReason NOUR); |
1184 | |
1185 | /// Construct an empty declaration reference expression. |
1186 | explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {} |
1187 | |
1188 | /// Computes the type- and value-dependence flags for this |
1189 | /// declaration reference expression. |
1190 | void computeDependence(const ASTContext &Ctx); |
1191 | |
1192 | public: |
1193 | DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, |
1194 | bool RefersToEnclosingVariableOrCapture, QualType T, |
1195 | ExprValueKind VK, SourceLocation L, |
1196 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc(), |
1197 | NonOdrUseReason NOUR = NOUR_None); |
1198 | |
1199 | static DeclRefExpr * |
1200 | Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, |
1201 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1202 | bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, |
1203 | QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, |
1204 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
1205 | NonOdrUseReason NOUR = NOUR_None); |
1206 | |
1207 | static DeclRefExpr * |
1208 | Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, |
1209 | SourceLocation TemplateKWLoc, ValueDecl *D, |
1210 | bool RefersToEnclosingVariableOrCapture, |
1211 | const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, |
1212 | NamedDecl *FoundD = nullptr, |
1213 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
1214 | NonOdrUseReason NOUR = NOUR_None); |
1215 | |
1216 | /// Construct an empty declaration reference expression. |
1217 | static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, |
1218 | bool HasFoundDecl, |
1219 | bool HasTemplateKWAndArgsInfo, |
1220 | unsigned NumTemplateArgs); |
1221 | |
1222 | ValueDecl *getDecl() { return D; } |
1223 | const ValueDecl *getDecl() const { return D; } |
1224 | void setDecl(ValueDecl *NewD) { D = NewD; } |
1225 | |
1226 | DeclarationNameInfo getNameInfo() const { |
1227 | return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc); |
1228 | } |
1229 | |
1230 | SourceLocation getLocation() const { return DeclRefExprBits.Loc; } |
1231 | void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; } |
1232 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
1233 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
1234 | |
1235 | /// Determine whether this declaration reference was preceded by a |
1236 | /// C++ nested-name-specifier, e.g., \c N::foo. |
1237 | bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } |
1238 | |
1239 | /// If the name was qualified, retrieves the nested-name-specifier |
1240 | /// that precedes the name, with source-location information. |
1241 | NestedNameSpecifierLoc getQualifierLoc() const { |
1242 | if (!hasQualifier()) |
1243 | return NestedNameSpecifierLoc(); |
1244 | return *getTrailingObjects<NestedNameSpecifierLoc>(); |
1245 | } |
1246 | |
1247 | /// If the name was qualified, retrieves the nested-name-specifier |
1248 | /// that precedes the name. Otherwise, returns NULL. |
1249 | NestedNameSpecifier *getQualifier() const { |
1250 | return getQualifierLoc().getNestedNameSpecifier(); |
1251 | } |
1252 | |
1253 | /// Get the NamedDecl through which this reference occurred. |
1254 | /// |
1255 | /// This Decl may be different from the ValueDecl actually referred to in the |
1256 | /// presence of using declarations, etc. It always returns non-NULL, and may |
1257 | /// simple return the ValueDecl when appropriate. |
1258 | |
1259 | NamedDecl *getFoundDecl() { |
1260 | return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; |
1261 | } |
1262 | |
1263 | /// Get the NamedDecl through which this reference occurred. |
1264 | /// See non-const variant. |
1265 | const NamedDecl *getFoundDecl() const { |
1266 | return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D; |
1267 | } |
1268 | |
1269 | bool hasTemplateKWAndArgsInfo() const { |
1270 | return DeclRefExprBits.HasTemplateKWAndArgsInfo; |
1271 | } |
1272 | |
1273 | /// Retrieve the location of the template keyword preceding |
1274 | /// this name, if any. |
1275 | SourceLocation getTemplateKeywordLoc() const { |
1276 | if (!hasTemplateKWAndArgsInfo()) |
1277 | return SourceLocation(); |
1278 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; |
1279 | } |
1280 | |
1281 | /// Retrieve the location of the left angle bracket starting the |
1282 | /// explicit template argument list following the name, if any. |
1283 | SourceLocation getLAngleLoc() const { |
1284 | if (!hasTemplateKWAndArgsInfo()) |
1285 | return SourceLocation(); |
1286 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; |
1287 | } |
1288 | |
1289 | /// Retrieve the location of the right angle bracket ending the |
1290 | /// explicit template argument list following the name, if any. |
1291 | SourceLocation getRAngleLoc() const { |
1292 | if (!hasTemplateKWAndArgsInfo()) |
1293 | return SourceLocation(); |
1294 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; |
1295 | } |
1296 | |
1297 | /// Determines whether the name in this declaration reference |
1298 | /// was preceded by the template keyword. |
1299 | bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } |
1300 | |
1301 | /// Determines whether this declaration reference was followed by an |
1302 | /// explicit template argument list. |
1303 | bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } |
1304 | |
1305 | /// Copies the template arguments (if present) into the given |
1306 | /// structure. |
1307 | void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { |
1308 | if (hasExplicitTemplateArgs()) |
1309 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( |
1310 | getTrailingObjects<TemplateArgumentLoc>(), List); |
1311 | } |
1312 | |
1313 | /// Retrieve the template arguments provided as part of this |
1314 | /// template-id. |
1315 | const TemplateArgumentLoc *getTemplateArgs() const { |
1316 | if (!hasExplicitTemplateArgs()) |
1317 | return nullptr; |
1318 | return getTrailingObjects<TemplateArgumentLoc>(); |
1319 | } |
1320 | |
1321 | /// Retrieve the number of template arguments provided as part of this |
1322 | /// template-id. |
1323 | unsigned getNumTemplateArgs() const { |
1324 | if (!hasExplicitTemplateArgs()) |
1325 | return 0; |
1326 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; |
1327 | } |
1328 | |
1329 | ArrayRef<TemplateArgumentLoc> template_arguments() const { |
1330 | return {getTemplateArgs(), getNumTemplateArgs()}; |
1331 | } |
1332 | |
1333 | /// Returns true if this expression refers to a function that |
1334 | /// was resolved from an overloaded set having size greater than 1. |
1335 | bool hadMultipleCandidates() const { |
1336 | return DeclRefExprBits.HadMultipleCandidates; |
1337 | } |
1338 | /// Sets the flag telling whether this expression refers to |
1339 | /// a function that was resolved from an overloaded set having size |
1340 | /// greater than 1. |
1341 | void setHadMultipleCandidates(bool V = true) { |
1342 | DeclRefExprBits.HadMultipleCandidates = V; |
1343 | } |
1344 | |
1345 | /// Is this expression a non-odr-use reference, and if so, why? |
1346 | NonOdrUseReason isNonOdrUse() const { |
1347 | return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason); |
1348 | } |
1349 | |
1350 | /// Does this DeclRefExpr refer to an enclosing local or a captured |
1351 | /// variable? |
1352 | bool refersToEnclosingVariableOrCapture() const { |
1353 | return DeclRefExprBits.RefersToEnclosingVariableOrCapture; |
1354 | } |
1355 | |
1356 | static bool classof(const Stmt *T) { |
1357 | return T->getStmtClass() == DeclRefExprClass; |
1358 | } |
1359 | |
1360 | // Iterators |
1361 | child_range children() { |
1362 | return child_range(child_iterator(), child_iterator()); |
1363 | } |
1364 | |
1365 | const_child_range children() const { |
1366 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1367 | } |
1368 | }; |
1369 | |
1370 | /// Used by IntegerLiteral/FloatingLiteral to store the numeric without |
1371 | /// leaking memory. |
1372 | /// |
1373 | /// For large floats/integers, APFloat/APInt will allocate memory from the heap |
1374 | /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator |
1375 | /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with |
1376 | /// the APFloat/APInt values will never get freed. APNumericStorage uses |
1377 | /// ASTContext's allocator for memory allocation. |
1378 | class APNumericStorage { |
1379 | union { |
1380 | uint64_t VAL; ///< Used to store the <= 64 bits integer value. |
1381 | uint64_t *pVal; ///< Used to store the >64 bits integer value. |
1382 | }; |
1383 | unsigned BitWidth; |
1384 | |
1385 | bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } |
1386 | |
1387 | APNumericStorage(const APNumericStorage &) = delete; |
1388 | void operator=(const APNumericStorage &) = delete; |
1389 | |
1390 | protected: |
1391 | APNumericStorage() : VAL(0), BitWidth(0) { } |
1392 | |
1393 | llvm::APInt getIntValue() const { |
1394 | unsigned NumWords = llvm::APInt::getNumWords(BitWidth); |
1395 | if (NumWords > 1) |
1396 | return llvm::APInt(BitWidth, NumWords, pVal); |
1397 | else |
1398 | return llvm::APInt(BitWidth, VAL); |
1399 | } |
1400 | void setIntValue(const ASTContext &C, const llvm::APInt &Val); |
1401 | }; |
1402 | |
1403 | class APIntStorage : private APNumericStorage { |
1404 | public: |
1405 | llvm::APInt getValue() const { return getIntValue(); } |
1406 | void setValue(const ASTContext &C, const llvm::APInt &Val) { |
1407 | setIntValue(C, Val); |
1408 | } |
1409 | }; |
1410 | |
1411 | class APFloatStorage : private APNumericStorage { |
1412 | public: |
1413 | llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { |
1414 | return llvm::APFloat(Semantics, getIntValue()); |
1415 | } |
1416 | void setValue(const ASTContext &C, const llvm::APFloat &Val) { |
1417 | setIntValue(C, Val.bitcastToAPInt()); |
1418 | } |
1419 | }; |
1420 | |
1421 | class IntegerLiteral : public Expr, public APIntStorage { |
1422 | SourceLocation Loc; |
1423 | |
1424 | /// Construct an empty integer literal. |
1425 | explicit IntegerLiteral(EmptyShell Empty) |
1426 | : Expr(IntegerLiteralClass, Empty) { } |
1427 | |
1428 | public: |
1429 | // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, |
1430 | // or UnsignedLongLongTy |
1431 | IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, |
1432 | SourceLocation l); |
1433 | |
1434 | /// Returns a new integer literal with value 'V' and type 'type'. |
1435 | /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, |
1436 | /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V |
1437 | /// \param V - the value that the returned integer literal contains. |
1438 | static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, |
1439 | QualType type, SourceLocation l); |
1440 | /// Returns a new empty integer literal. |
1441 | static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); |
1442 | |
1443 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1444 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1445 | |
1446 | /// Retrieve the location of the literal. |
1447 | SourceLocation getLocation() const { return Loc; } |
1448 | |
1449 | void setLocation(SourceLocation Location) { Loc = Location; } |
1450 | |
1451 | static bool classof(const Stmt *T) { |
1452 | return T->getStmtClass() == IntegerLiteralClass; |
1453 | } |
1454 | |
1455 | // Iterators |
1456 | child_range children() { |
1457 | return child_range(child_iterator(), child_iterator()); |
1458 | } |
1459 | const_child_range children() const { |
1460 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1461 | } |
1462 | }; |
1463 | |
1464 | class FixedPointLiteral : public Expr, public APIntStorage { |
1465 | SourceLocation Loc; |
1466 | unsigned Scale; |
1467 | |
1468 | /// \brief Construct an empty integer literal. |
1469 | explicit FixedPointLiteral(EmptyShell Empty) |
1470 | : Expr(FixedPointLiteralClass, Empty) {} |
1471 | |
1472 | public: |
1473 | FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, |
1474 | SourceLocation l, unsigned Scale); |
1475 | |
1476 | // Store the int as is without any bit shifting. |
1477 | static FixedPointLiteral *CreateFromRawInt(const ASTContext &C, |
1478 | const llvm::APInt &V, |
1479 | QualType type, SourceLocation l, |
1480 | unsigned Scale); |
1481 | |
1482 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1483 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1484 | |
1485 | /// \brief Retrieve the location of the literal. |
1486 | SourceLocation getLocation() const { return Loc; } |
1487 | |
1488 | void setLocation(SourceLocation Location) { Loc = Location; } |
1489 | |
1490 | static bool classof(const Stmt *T) { |
1491 | return T->getStmtClass() == FixedPointLiteralClass; |
1492 | } |
1493 | |
1494 | std::string getValueAsString(unsigned Radix) const; |
1495 | |
1496 | // Iterators |
1497 | child_range children() { |
1498 | return child_range(child_iterator(), child_iterator()); |
1499 | } |
1500 | const_child_range children() const { |
1501 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1502 | } |
1503 | }; |
1504 | |
1505 | class CharacterLiteral : public Expr { |
1506 | public: |
1507 | enum CharacterKind { |
1508 | Ascii, |
1509 | Wide, |
1510 | UTF8, |
1511 | UTF16, |
1512 | UTF32 |
1513 | }; |
1514 | |
1515 | private: |
1516 | unsigned Value; |
1517 | SourceLocation Loc; |
1518 | public: |
1519 | // type should be IntTy |
1520 | CharacterLiteral(unsigned value, CharacterKind kind, QualType type, |
1521 | SourceLocation l) |
1522 | : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, |
1523 | false, false), |
1524 | Value(value), Loc(l) { |
1525 | CharacterLiteralBits.Kind = kind; |
1526 | } |
1527 | |
1528 | /// Construct an empty character literal. |
1529 | CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } |
1530 | |
1531 | SourceLocation getLocation() const { return Loc; } |
1532 | CharacterKind getKind() const { |
1533 | return static_cast<CharacterKind>(CharacterLiteralBits.Kind); |
1534 | } |
1535 | |
1536 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1537 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1538 | |
1539 | unsigned getValue() const { return Value; } |
1540 | |
1541 | void setLocation(SourceLocation Location) { Loc = Location; } |
1542 | void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } |
1543 | void setValue(unsigned Val) { Value = Val; } |
1544 | |
1545 | static bool classof(const Stmt *T) { |
1546 | return T->getStmtClass() == CharacterLiteralClass; |
1547 | } |
1548 | |
1549 | // Iterators |
1550 | child_range children() { |
1551 | return child_range(child_iterator(), child_iterator()); |
1552 | } |
1553 | const_child_range children() const { |
1554 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1555 | } |
1556 | }; |
1557 | |
1558 | class FloatingLiteral : public Expr, private APFloatStorage { |
1559 | SourceLocation Loc; |
1560 | |
1561 | FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, |
1562 | QualType Type, SourceLocation L); |
1563 | |
1564 | /// Construct an empty floating-point literal. |
1565 | explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); |
1566 | |
1567 | public: |
1568 | static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, |
1569 | bool isexact, QualType Type, SourceLocation L); |
1570 | static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); |
1571 | |
1572 | llvm::APFloat getValue() const { |
1573 | return APFloatStorage::getValue(getSemantics()); |
1574 | } |
1575 | void setValue(const ASTContext &C, const llvm::APFloat &Val) { |
1576 | assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")((&getSemantics() == &Val.getSemantics() && "Inconsistent semantics" ) ? static_cast<void> (0) : __assert_fail ("&getSemantics() == &Val.getSemantics() && \"Inconsistent semantics\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1576, __PRETTY_FUNCTION__)); |
1577 | APFloatStorage::setValue(C, Val); |
1578 | } |
1579 | |
1580 | /// Get a raw enumeration value representing the floating-point semantics of |
1581 | /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. |
1582 | llvm::APFloatBase::Semantics getRawSemantics() const { |
1583 | return static_cast<llvm::APFloatBase::Semantics>( |
1584 | FloatingLiteralBits.Semantics); |
1585 | } |
1586 | |
1587 | /// Set the raw enumeration value representing the floating-point semantics of |
1588 | /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. |
1589 | void setRawSemantics(llvm::APFloatBase::Semantics Sem) { |
1590 | FloatingLiteralBits.Semantics = Sem; |
1591 | } |
1592 | |
1593 | /// Return the APFloat semantics this literal uses. |
1594 | const llvm::fltSemantics &getSemantics() const { |
1595 | return llvm::APFloatBase::EnumToSemantics( |
1596 | static_cast<llvm::APFloatBase::Semantics>( |
1597 | FloatingLiteralBits.Semantics)); |
1598 | } |
1599 | |
1600 | /// Set the APFloat semantics this literal uses. |
1601 | void setSemantics(const llvm::fltSemantics &Sem) { |
1602 | FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem); |
1603 | } |
1604 | |
1605 | bool isExact() const { return FloatingLiteralBits.IsExact; } |
1606 | void setExact(bool E) { FloatingLiteralBits.IsExact = E; } |
1607 | |
1608 | /// getValueAsApproximateDouble - This returns the value as an inaccurate |
1609 | /// double. Note that this may cause loss of precision, but is useful for |
1610 | /// debugging dumps, etc. |
1611 | double getValueAsApproximateDouble() const; |
1612 | |
1613 | SourceLocation getLocation() const { return Loc; } |
1614 | void setLocation(SourceLocation L) { Loc = L; } |
1615 | |
1616 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1617 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; } |
1618 | |
1619 | static bool classof(const Stmt *T) { |
1620 | return T->getStmtClass() == FloatingLiteralClass; |
1621 | } |
1622 | |
1623 | // Iterators |
1624 | child_range children() { |
1625 | return child_range(child_iterator(), child_iterator()); |
1626 | } |
1627 | const_child_range children() const { |
1628 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1629 | } |
1630 | }; |
1631 | |
1632 | /// ImaginaryLiteral - We support imaginary integer and floating point literals, |
1633 | /// like "1.0i". We represent these as a wrapper around FloatingLiteral and |
1634 | /// IntegerLiteral classes. Instances of this class always have a Complex type |
1635 | /// whose element type matches the subexpression. |
1636 | /// |
1637 | class ImaginaryLiteral : public Expr { |
1638 | Stmt *Val; |
1639 | public: |
1640 | ImaginaryLiteral(Expr *val, QualType Ty) |
1641 | : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, |
1642 | false, false), |
1643 | Val(val) {} |
1644 | |
1645 | /// Build an empty imaginary literal. |
1646 | explicit ImaginaryLiteral(EmptyShell Empty) |
1647 | : Expr(ImaginaryLiteralClass, Empty) { } |
1648 | |
1649 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
1650 | Expr *getSubExpr() { return cast<Expr>(Val); } |
1651 | void setSubExpr(Expr *E) { Val = E; } |
1652 | |
1653 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
1654 | return Val->getBeginLoc(); |
1655 | } |
1656 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Val->getEndLoc(); } |
1657 | |
1658 | static bool classof(const Stmt *T) { |
1659 | return T->getStmtClass() == ImaginaryLiteralClass; |
1660 | } |
1661 | |
1662 | // Iterators |
1663 | child_range children() { return child_range(&Val, &Val+1); } |
1664 | const_child_range children() const { |
1665 | return const_child_range(&Val, &Val + 1); |
1666 | } |
1667 | }; |
1668 | |
1669 | /// StringLiteral - This represents a string literal expression, e.g. "foo" |
1670 | /// or L"bar" (wide strings). The actual string data can be obtained with |
1671 | /// getBytes() and is NOT null-terminated. The length of the string data is |
1672 | /// determined by calling getByteLength(). |
1673 | /// |
1674 | /// The C type for a string is always a ConstantArrayType. In C++, the char |
1675 | /// type is const qualified, in C it is not. |
1676 | /// |
1677 | /// Note that strings in C can be formed by concatenation of multiple string |
1678 | /// literal pptokens in translation phase #6. This keeps track of the locations |
1679 | /// of each of these pieces. |
1680 | /// |
1681 | /// Strings in C can also be truncated and extended by assigning into arrays, |
1682 | /// e.g. with constructs like: |
1683 | /// char X[2] = "foobar"; |
1684 | /// In this case, getByteLength() will return 6, but the string literal will |
1685 | /// have type "char[2]". |
1686 | class StringLiteral final |
1687 | : public Expr, |
1688 | private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation, |
1689 | char> { |
1690 | friend class ASTStmtReader; |
1691 | friend TrailingObjects; |
1692 | |
1693 | /// StringLiteral is followed by several trailing objects. They are in order: |
1694 | /// |
1695 | /// * A single unsigned storing the length in characters of this string. The |
1696 | /// length in bytes is this length times the width of a single character. |
1697 | /// Always present and stored as a trailing objects because storing it in |
1698 | /// StringLiteral would increase the size of StringLiteral by sizeof(void *) |
1699 | /// due to alignment requirements. If you add some data to StringLiteral, |
1700 | /// consider moving it inside StringLiteral. |
1701 | /// |
1702 | /// * An array of getNumConcatenated() SourceLocation, one for each of the |
1703 | /// token this string is made of. |
1704 | /// |
1705 | /// * An array of getByteLength() char used to store the string data. |
1706 | |
1707 | public: |
1708 | enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 }; |
1709 | |
1710 | private: |
1711 | unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; } |
1712 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
1713 | return getNumConcatenated(); |
1714 | } |
1715 | |
1716 | unsigned numTrailingObjects(OverloadToken<char>) const { |
1717 | return getByteLength(); |
1718 | } |
1719 | |
1720 | char *getStrDataAsChar() { return getTrailingObjects<char>(); } |
1721 | const char *getStrDataAsChar() const { return getTrailingObjects<char>(); } |
1722 | |
1723 | const uint16_t *getStrDataAsUInt16() const { |
1724 | return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>()); |
1725 | } |
1726 | |
1727 | const uint32_t *getStrDataAsUInt32() const { |
1728 | return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>()); |
1729 | } |
1730 | |
1731 | /// Build a string literal. |
1732 | StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind, |
1733 | bool Pascal, QualType Ty, const SourceLocation *Loc, |
1734 | unsigned NumConcatenated); |
1735 | |
1736 | /// Build an empty string literal. |
1737 | StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length, |
1738 | unsigned CharByteWidth); |
1739 | |
1740 | /// Map a target and string kind to the appropriate character width. |
1741 | static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK); |
1742 | |
1743 | /// Set one of the string literal token. |
1744 | void setStrTokenLoc(unsigned TokNum, SourceLocation L) { |
1745 | assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number" ) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1745, __PRETTY_FUNCTION__)); |
1746 | getTrailingObjects<SourceLocation>()[TokNum] = L; |
1747 | } |
1748 | |
1749 | public: |
1750 | /// This is the "fully general" constructor that allows representation of |
1751 | /// strings formed from multiple concatenated tokens. |
1752 | static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, |
1753 | StringKind Kind, bool Pascal, QualType Ty, |
1754 | const SourceLocation *Loc, |
1755 | unsigned NumConcatenated); |
1756 | |
1757 | /// Simple constructor for string literals made from one token. |
1758 | static StringLiteral *Create(const ASTContext &Ctx, StringRef Str, |
1759 | StringKind Kind, bool Pascal, QualType Ty, |
1760 | SourceLocation Loc) { |
1761 | return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1); |
1762 | } |
1763 | |
1764 | /// Construct an empty string literal. |
1765 | static StringLiteral *CreateEmpty(const ASTContext &Ctx, |
1766 | unsigned NumConcatenated, unsigned Length, |
1767 | unsigned CharByteWidth); |
1768 | |
1769 | StringRef getString() const { |
1770 | assert(getCharByteWidth() == 1 &&((getCharByteWidth() == 1 && "This function is used in places that assume strings use char" ) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1771, __PRETTY_FUNCTION__)) |
1771 | "This function is used in places that assume strings use char")((getCharByteWidth() == 1 && "This function is used in places that assume strings use char" ) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1771, __PRETTY_FUNCTION__)); |
1772 | return StringRef(getStrDataAsChar(), getByteLength()); |
1773 | } |
1774 | |
1775 | /// Allow access to clients that need the byte representation, such as |
1776 | /// ASTWriterStmt::VisitStringLiteral(). |
1777 | StringRef getBytes() const { |
1778 | // FIXME: StringRef may not be the right type to use as a result for this. |
1779 | return StringRef(getStrDataAsChar(), getByteLength()); |
1780 | } |
1781 | |
1782 | void outputString(raw_ostream &OS) const; |
1783 | |
1784 | uint32_t getCodeUnit(size_t i) const { |
1785 | assert(i < getLength() && "out of bounds access")((i < getLength() && "out of bounds access") ? static_cast <void> (0) : __assert_fail ("i < getLength() && \"out of bounds access\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1785, __PRETTY_FUNCTION__)); |
1786 | switch (getCharByteWidth()) { |
1787 | case 1: |
1788 | return static_cast<unsigned char>(getStrDataAsChar()[i]); |
1789 | case 2: |
1790 | return getStrDataAsUInt16()[i]; |
1791 | case 4: |
1792 | return getStrDataAsUInt32()[i]; |
1793 | } |
1794 | llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1794); |
1795 | } |
1796 | |
1797 | unsigned getByteLength() const { return getCharByteWidth() * getLength(); } |
1798 | unsigned getLength() const { return *getTrailingObjects<unsigned>(); } |
1799 | unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; } |
1800 | |
1801 | StringKind getKind() const { |
1802 | return static_cast<StringKind>(StringLiteralBits.Kind); |
1803 | } |
1804 | |
1805 | bool isAscii() const { return getKind() == Ascii; } |
1806 | bool isWide() const { return getKind() == Wide; } |
1807 | bool isUTF8() const { return getKind() == UTF8; } |
1808 | bool isUTF16() const { return getKind() == UTF16; } |
1809 | bool isUTF32() const { return getKind() == UTF32; } |
1810 | bool isPascal() const { return StringLiteralBits.IsPascal; } |
1811 | |
1812 | bool containsNonAscii() const { |
1813 | for (auto c : getString()) |
1814 | if (!isASCII(c)) |
1815 | return true; |
1816 | return false; |
1817 | } |
1818 | |
1819 | bool containsNonAsciiOrNull() const { |
1820 | for (auto c : getString()) |
1821 | if (!isASCII(c) || !c) |
1822 | return true; |
1823 | return false; |
1824 | } |
1825 | |
1826 | /// getNumConcatenated - Get the number of string literal tokens that were |
1827 | /// concatenated in translation phase #6 to form this string literal. |
1828 | unsigned getNumConcatenated() const { |
1829 | return StringLiteralBits.NumConcatenated; |
1830 | } |
1831 | |
1832 | /// Get one of the string literal token. |
1833 | SourceLocation getStrTokenLoc(unsigned TokNum) const { |
1834 | assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number" ) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1834, __PRETTY_FUNCTION__)); |
1835 | return getTrailingObjects<SourceLocation>()[TokNum]; |
1836 | } |
1837 | |
1838 | /// getLocationOfByte - Return a source location that points to the specified |
1839 | /// byte of this string literal. |
1840 | /// |
1841 | /// Strings are amazingly complex. They can be formed from multiple tokens |
1842 | /// and can have escape sequences in them in addition to the usual trigraph |
1843 | /// and escaped newline business. This routine handles this complexity. |
1844 | /// |
1845 | SourceLocation |
1846 | getLocationOfByte(unsigned ByteNo, const SourceManager &SM, |
1847 | const LangOptions &Features, const TargetInfo &Target, |
1848 | unsigned *StartToken = nullptr, |
1849 | unsigned *StartTokenByteOffset = nullptr) const; |
1850 | |
1851 | typedef const SourceLocation *tokloc_iterator; |
1852 | |
1853 | tokloc_iterator tokloc_begin() const { |
1854 | return getTrailingObjects<SourceLocation>(); |
1855 | } |
1856 | |
1857 | tokloc_iterator tokloc_end() const { |
1858 | return getTrailingObjects<SourceLocation>() + getNumConcatenated(); |
1859 | } |
1860 | |
1861 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return *tokloc_begin(); } |
1862 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return *(tokloc_end() - 1); } |
1863 | |
1864 | static bool classof(const Stmt *T) { |
1865 | return T->getStmtClass() == StringLiteralClass; |
1866 | } |
1867 | |
1868 | // Iterators |
1869 | child_range children() { |
1870 | return child_range(child_iterator(), child_iterator()); |
1871 | } |
1872 | const_child_range children() const { |
1873 | return const_child_range(const_child_iterator(), const_child_iterator()); |
1874 | } |
1875 | }; |
1876 | |
1877 | /// [C99 6.4.2.2] - A predefined identifier such as __func__. |
1878 | class PredefinedExpr final |
1879 | : public Expr, |
1880 | private llvm::TrailingObjects<PredefinedExpr, Stmt *> { |
1881 | friend class ASTStmtReader; |
1882 | friend TrailingObjects; |
1883 | |
1884 | // PredefinedExpr is optionally followed by a single trailing |
1885 | // "Stmt *" for the predefined identifier. It is present if and only if |
1886 | // hasFunctionName() is true and is always a "StringLiteral *". |
1887 | |
1888 | public: |
1889 | enum IdentKind { |
1890 | Func, |
1891 | Function, |
1892 | LFunction, // Same as Function, but as wide string. |
1893 | FuncDName, |
1894 | FuncSig, |
1895 | LFuncSig, // Same as FuncSig, but as as wide string |
1896 | PrettyFunction, |
1897 | /// The same as PrettyFunction, except that the |
1898 | /// 'virtual' keyword is omitted for virtual member functions. |
1899 | PrettyFunctionNoVirtual |
1900 | }; |
1901 | |
1902 | private: |
1903 | PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK, |
1904 | StringLiteral *SL); |
1905 | |
1906 | explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName); |
1907 | |
1908 | /// True if this PredefinedExpr has storage for a function name. |
1909 | bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; } |
1910 | |
1911 | void setFunctionName(StringLiteral *SL) { |
1912 | assert(hasFunctionName() &&((hasFunctionName() && "This PredefinedExpr has no storage for a function name!" ) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1913, __PRETTY_FUNCTION__)) |
1913 | "This PredefinedExpr has no storage for a function name!")((hasFunctionName() && "This PredefinedExpr has no storage for a function name!" ) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 1913, __PRETTY_FUNCTION__)); |
1914 | *getTrailingObjects<Stmt *>() = SL; |
1915 | } |
1916 | |
1917 | public: |
1918 | /// Create a PredefinedExpr. |
1919 | static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L, |
1920 | QualType FNTy, IdentKind IK, StringLiteral *SL); |
1921 | |
1922 | /// Create an empty PredefinedExpr. |
1923 | static PredefinedExpr *CreateEmpty(const ASTContext &Ctx, |
1924 | bool HasFunctionName); |
1925 | |
1926 | IdentKind getIdentKind() const { |
1927 | return static_cast<IdentKind>(PredefinedExprBits.Kind); |
1928 | } |
1929 | |
1930 | SourceLocation getLocation() const { return PredefinedExprBits.Loc; } |
1931 | void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; } |
1932 | |
1933 | StringLiteral *getFunctionName() { |
1934 | return hasFunctionName() |
1935 | ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) |
1936 | : nullptr; |
1937 | } |
1938 | |
1939 | const StringLiteral *getFunctionName() const { |
1940 | return hasFunctionName() |
1941 | ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>()) |
1942 | : nullptr; |
1943 | } |
1944 | |
1945 | static StringRef getIdentKindName(IdentKind IK); |
1946 | static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl); |
1947 | |
1948 | SourceLocation getBeginLoc() const { return getLocation(); } |
1949 | SourceLocation getEndLoc() const { return getLocation(); } |
1950 | |
1951 | static bool classof(const Stmt *T) { |
1952 | return T->getStmtClass() == PredefinedExprClass; |
1953 | } |
1954 | |
1955 | // Iterators |
1956 | child_range children() { |
1957 | return child_range(getTrailingObjects<Stmt *>(), |
1958 | getTrailingObjects<Stmt *>() + hasFunctionName()); |
1959 | } |
1960 | |
1961 | const_child_range children() const { |
1962 | return const_child_range(getTrailingObjects<Stmt *>(), |
1963 | getTrailingObjects<Stmt *>() + hasFunctionName()); |
1964 | } |
1965 | }; |
1966 | |
1967 | /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This |
1968 | /// AST node is only formed if full location information is requested. |
1969 | class ParenExpr : public Expr { |
1970 | SourceLocation L, R; |
1971 | Stmt *Val; |
1972 | public: |
1973 | ParenExpr(SourceLocation l, SourceLocation r, Expr *val) |
1974 | : Expr(ParenExprClass, val->getType(), |
1975 | val->getValueKind(), val->getObjectKind(), |
1976 | val->isTypeDependent(), val->isValueDependent(), |
1977 | val->isInstantiationDependent(), |
1978 | val->containsUnexpandedParameterPack()), |
1979 | L(l), R(r), Val(val) {} |
1980 | |
1981 | /// Construct an empty parenthesized expression. |
1982 | explicit ParenExpr(EmptyShell Empty) |
1983 | : Expr(ParenExprClass, Empty) { } |
1984 | |
1985 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
1986 | Expr *getSubExpr() { return cast<Expr>(Val); } |
1987 | void setSubExpr(Expr *E) { Val = E; } |
1988 | |
1989 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return L; } |
1990 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return R; } |
1991 | |
1992 | /// Get the location of the left parentheses '('. |
1993 | SourceLocation getLParen() const { return L; } |
1994 | void setLParen(SourceLocation Loc) { L = Loc; } |
1995 | |
1996 | /// Get the location of the right parentheses ')'. |
1997 | SourceLocation getRParen() const { return R; } |
1998 | void setRParen(SourceLocation Loc) { R = Loc; } |
1999 | |
2000 | static bool classof(const Stmt *T) { |
2001 | return T->getStmtClass() == ParenExprClass; |
2002 | } |
2003 | |
2004 | // Iterators |
2005 | child_range children() { return child_range(&Val, &Val+1); } |
2006 | const_child_range children() const { |
2007 | return const_child_range(&Val, &Val + 1); |
2008 | } |
2009 | }; |
2010 | |
2011 | /// UnaryOperator - This represents the unary-expression's (except sizeof and |
2012 | /// alignof), the postinc/postdec operators from postfix-expression, and various |
2013 | /// extensions. |
2014 | /// |
2015 | /// Notes on various nodes: |
2016 | /// |
2017 | /// Real/Imag - These return the real/imag part of a complex operand. If |
2018 | /// applied to a non-complex value, the former returns its operand and the |
2019 | /// later returns zero in the type of the operand. |
2020 | /// |
2021 | class UnaryOperator : public Expr { |
2022 | Stmt *Val; |
2023 | |
2024 | public: |
2025 | typedef UnaryOperatorKind Opcode; |
2026 | |
2027 | UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK, |
2028 | ExprObjectKind OK, SourceLocation l, bool CanOverflow) |
2029 | : Expr(UnaryOperatorClass, type, VK, OK, |
2030 | input->isTypeDependent() || type->isDependentType(), |
2031 | input->isValueDependent(), |
2032 | (input->isInstantiationDependent() || |
2033 | type->isInstantiationDependentType()), |
2034 | input->containsUnexpandedParameterPack()), |
2035 | Val(input) { |
2036 | UnaryOperatorBits.Opc = opc; |
2037 | UnaryOperatorBits.CanOverflow = CanOverflow; |
2038 | UnaryOperatorBits.Loc = l; |
2039 | } |
2040 | |
2041 | /// Build an empty unary operator. |
2042 | explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) { |
2043 | UnaryOperatorBits.Opc = UO_AddrOf; |
2044 | } |
2045 | |
2046 | Opcode getOpcode() const { |
2047 | return static_cast<Opcode>(UnaryOperatorBits.Opc); |
2048 | } |
2049 | void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; } |
2050 | |
2051 | Expr *getSubExpr() const { return cast<Expr>(Val); } |
2052 | void setSubExpr(Expr *E) { Val = E; } |
2053 | |
2054 | /// getOperatorLoc - Return the location of the operator. |
2055 | SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; } |
2056 | void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; } |
2057 | |
2058 | /// Returns true if the unary operator can cause an overflow. For instance, |
2059 | /// signed int i = INT_MAX; i++; |
2060 | /// signed char c = CHAR_MAX; c++; |
2061 | /// Due to integer promotions, c++ is promoted to an int before the postfix |
2062 | /// increment, and the result is an int that cannot overflow. However, i++ |
2063 | /// can overflow. |
2064 | bool canOverflow() const { return UnaryOperatorBits.CanOverflow; } |
2065 | void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; } |
2066 | |
2067 | /// isPostfix - Return true if this is a postfix operation, like x++. |
2068 | static bool isPostfix(Opcode Op) { |
2069 | return Op == UO_PostInc || Op == UO_PostDec; |
2070 | } |
2071 | |
2072 | /// isPrefix - Return true if this is a prefix operation, like --x. |
2073 | static bool isPrefix(Opcode Op) { |
2074 | return Op == UO_PreInc || Op == UO_PreDec; |
2075 | } |
2076 | |
2077 | bool isPrefix() const { return isPrefix(getOpcode()); } |
2078 | bool isPostfix() const { return isPostfix(getOpcode()); } |
2079 | |
2080 | static bool isIncrementOp(Opcode Op) { |
2081 | return Op == UO_PreInc || Op == UO_PostInc; |
2082 | } |
2083 | bool isIncrementOp() const { |
2084 | return isIncrementOp(getOpcode()); |
2085 | } |
2086 | |
2087 | static bool isDecrementOp(Opcode Op) { |
2088 | return Op == UO_PreDec || Op == UO_PostDec; |
2089 | } |
2090 | bool isDecrementOp() const { |
2091 | return isDecrementOp(getOpcode()); |
2092 | } |
2093 | |
2094 | static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } |
2095 | bool isIncrementDecrementOp() const { |
2096 | return isIncrementDecrementOp(getOpcode()); |
2097 | } |
2098 | |
2099 | static bool isArithmeticOp(Opcode Op) { |
2100 | return Op >= UO_Plus && Op <= UO_LNot; |
2101 | } |
2102 | bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } |
2103 | |
2104 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
2105 | /// corresponds to, e.g. "sizeof" or "[pre]++" |
2106 | static StringRef getOpcodeStr(Opcode Op); |
2107 | |
2108 | /// Retrieve the unary opcode that corresponds to the given |
2109 | /// overloaded operator. |
2110 | static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); |
2111 | |
2112 | /// Retrieve the overloaded operator kind that corresponds to |
2113 | /// the given unary opcode. |
2114 | static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); |
2115 | |
2116 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2117 | return isPostfix() ? Val->getBeginLoc() : getOperatorLoc(); |
2118 | } |
2119 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2120 | return isPostfix() ? getOperatorLoc() : Val->getEndLoc(); |
2121 | } |
2122 | SourceLocation getExprLoc() const { return getOperatorLoc(); } |
2123 | |
2124 | static bool classof(const Stmt *T) { |
2125 | return T->getStmtClass() == UnaryOperatorClass; |
2126 | } |
2127 | |
2128 | // Iterators |
2129 | child_range children() { return child_range(&Val, &Val+1); } |
2130 | const_child_range children() const { |
2131 | return const_child_range(&Val, &Val + 1); |
2132 | } |
2133 | }; |
2134 | |
2135 | /// Helper class for OffsetOfExpr. |
2136 | |
2137 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) |
2138 | class OffsetOfNode { |
2139 | public: |
2140 | /// The kind of offsetof node we have. |
2141 | enum Kind { |
2142 | /// An index into an array. |
2143 | Array = 0x00, |
2144 | /// A field. |
2145 | Field = 0x01, |
2146 | /// A field in a dependent type, known only by its name. |
2147 | Identifier = 0x02, |
2148 | /// An implicit indirection through a C++ base class, when the |
2149 | /// field found is in a base class. |
2150 | Base = 0x03 |
2151 | }; |
2152 | |
2153 | private: |
2154 | enum { MaskBits = 2, Mask = 0x03 }; |
2155 | |
2156 | /// The source range that covers this part of the designator. |
2157 | SourceRange Range; |
2158 | |
2159 | /// The data describing the designator, which comes in three |
2160 | /// different forms, depending on the lower two bits. |
2161 | /// - An unsigned index into the array of Expr*'s stored after this node |
2162 | /// in memory, for [constant-expression] designators. |
2163 | /// - A FieldDecl*, for references to a known field. |
2164 | /// - An IdentifierInfo*, for references to a field with a given name |
2165 | /// when the class type is dependent. |
2166 | /// - A CXXBaseSpecifier*, for references that look at a field in a |
2167 | /// base class. |
2168 | uintptr_t Data; |
2169 | |
2170 | public: |
2171 | /// Create an offsetof node that refers to an array element. |
2172 | OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, |
2173 | SourceLocation RBracketLoc) |
2174 | : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} |
2175 | |
2176 | /// Create an offsetof node that refers to a field. |
2177 | OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) |
2178 | : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), |
2179 | Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {} |
2180 | |
2181 | /// Create an offsetof node that refers to an identifier. |
2182 | OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, |
2183 | SourceLocation NameLoc) |
2184 | : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), |
2185 | Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {} |
2186 | |
2187 | /// Create an offsetof node that refers into a C++ base class. |
2188 | explicit OffsetOfNode(const CXXBaseSpecifier *Base) |
2189 | : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {} |
2190 | |
2191 | /// Determine what kind of offsetof node this is. |
2192 | Kind getKind() const { return static_cast<Kind>(Data & Mask); } |
2193 | |
2194 | /// For an array element node, returns the index into the array |
2195 | /// of expressions. |
2196 | unsigned getArrayExprIndex() const { |
2197 | assert(getKind() == Array)((getKind() == Array) ? static_cast<void> (0) : __assert_fail ("getKind() == Array", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2197, __PRETTY_FUNCTION__)); |
2198 | return Data >> 2; |
2199 | } |
2200 | |
2201 | /// For a field offsetof node, returns the field. |
2202 | FieldDecl *getField() const { |
2203 | assert(getKind() == Field)((getKind() == Field) ? static_cast<void> (0) : __assert_fail ("getKind() == Field", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2203, __PRETTY_FUNCTION__)); |
2204 | return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask); |
2205 | } |
2206 | |
2207 | /// For a field or identifier offsetof node, returns the name of |
2208 | /// the field. |
2209 | IdentifierInfo *getFieldName() const; |
2210 | |
2211 | /// For a base class node, returns the base specifier. |
2212 | CXXBaseSpecifier *getBase() const { |
2213 | assert(getKind() == Base)((getKind() == Base) ? static_cast<void> (0) : __assert_fail ("getKind() == Base", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2213, __PRETTY_FUNCTION__)); |
2214 | return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask); |
2215 | } |
2216 | |
2217 | /// Retrieve the source range that covers this offsetof node. |
2218 | /// |
2219 | /// For an array element node, the source range contains the locations of |
2220 | /// the square brackets. For a field or identifier node, the source range |
2221 | /// contains the location of the period (if there is one) and the |
2222 | /// identifier. |
2223 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
2224 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
2225 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
2226 | }; |
2227 | |
2228 | /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form |
2229 | /// offsetof(record-type, member-designator). For example, given: |
2230 | /// @code |
2231 | /// struct S { |
2232 | /// float f; |
2233 | /// double d; |
2234 | /// }; |
2235 | /// struct T { |
2236 | /// int i; |
2237 | /// struct S s[10]; |
2238 | /// }; |
2239 | /// @endcode |
2240 | /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). |
2241 | |
2242 | class OffsetOfExpr final |
2243 | : public Expr, |
2244 | private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> { |
2245 | SourceLocation OperatorLoc, RParenLoc; |
2246 | // Base type; |
2247 | TypeSourceInfo *TSInfo; |
2248 | // Number of sub-components (i.e. instances of OffsetOfNode). |
2249 | unsigned NumComps; |
2250 | // Number of sub-expressions (i.e. array subscript expressions). |
2251 | unsigned NumExprs; |
2252 | |
2253 | size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const { |
2254 | return NumComps; |
2255 | } |
2256 | |
2257 | OffsetOfExpr(const ASTContext &C, QualType type, |
2258 | SourceLocation OperatorLoc, TypeSourceInfo *tsi, |
2259 | ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, |
2260 | SourceLocation RParenLoc); |
2261 | |
2262 | explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) |
2263 | : Expr(OffsetOfExprClass, EmptyShell()), |
2264 | TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} |
2265 | |
2266 | public: |
2267 | |
2268 | static OffsetOfExpr *Create(const ASTContext &C, QualType type, |
2269 | SourceLocation OperatorLoc, TypeSourceInfo *tsi, |
2270 | ArrayRef<OffsetOfNode> comps, |
2271 | ArrayRef<Expr*> exprs, SourceLocation RParenLoc); |
2272 | |
2273 | static OffsetOfExpr *CreateEmpty(const ASTContext &C, |
2274 | unsigned NumComps, unsigned NumExprs); |
2275 | |
2276 | /// getOperatorLoc - Return the location of the operator. |
2277 | SourceLocation getOperatorLoc() const { return OperatorLoc; } |
2278 | void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } |
2279 | |
2280 | /// Return the location of the right parentheses. |
2281 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2282 | void setRParenLoc(SourceLocation R) { RParenLoc = R; } |
2283 | |
2284 | TypeSourceInfo *getTypeSourceInfo() const { |
2285 | return TSInfo; |
2286 | } |
2287 | void setTypeSourceInfo(TypeSourceInfo *tsi) { |
2288 | TSInfo = tsi; |
2289 | } |
2290 | |
2291 | const OffsetOfNode &getComponent(unsigned Idx) const { |
2292 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2292, __PRETTY_FUNCTION__)); |
2293 | return getTrailingObjects<OffsetOfNode>()[Idx]; |
2294 | } |
2295 | |
2296 | void setComponent(unsigned Idx, OffsetOfNode ON) { |
2297 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2297, __PRETTY_FUNCTION__)); |
2298 | getTrailingObjects<OffsetOfNode>()[Idx] = ON; |
2299 | } |
2300 | |
2301 | unsigned getNumComponents() const { |
2302 | return NumComps; |
2303 | } |
2304 | |
2305 | Expr* getIndexExpr(unsigned Idx) { |
2306 | assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2306, __PRETTY_FUNCTION__)); |
2307 | return getTrailingObjects<Expr *>()[Idx]; |
2308 | } |
2309 | |
2310 | const Expr *getIndexExpr(unsigned Idx) const { |
2311 | assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2311, __PRETTY_FUNCTION__)); |
2312 | return getTrailingObjects<Expr *>()[Idx]; |
2313 | } |
2314 | |
2315 | void setIndexExpr(unsigned Idx, Expr* E) { |
2316 | assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast <void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2316, __PRETTY_FUNCTION__)); |
2317 | getTrailingObjects<Expr *>()[Idx] = E; |
2318 | } |
2319 | |
2320 | unsigned getNumExpressions() const { |
2321 | return NumExprs; |
2322 | } |
2323 | |
2324 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; } |
2325 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
2326 | |
2327 | static bool classof(const Stmt *T) { |
2328 | return T->getStmtClass() == OffsetOfExprClass; |
2329 | } |
2330 | |
2331 | // Iterators |
2332 | child_range children() { |
2333 | Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); |
2334 | return child_range(begin, begin + NumExprs); |
2335 | } |
2336 | const_child_range children() const { |
2337 | Stmt *const *begin = |
2338 | reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); |
2339 | return const_child_range(begin, begin + NumExprs); |
2340 | } |
2341 | friend TrailingObjects; |
2342 | }; |
2343 | |
2344 | /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) |
2345 | /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and |
2346 | /// vec_step (OpenCL 1.1 6.11.12). |
2347 | class UnaryExprOrTypeTraitExpr : public Expr { |
2348 | union { |
2349 | TypeSourceInfo *Ty; |
2350 | Stmt *Ex; |
2351 | } Argument; |
2352 | SourceLocation OpLoc, RParenLoc; |
2353 | |
2354 | public: |
2355 | UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, |
2356 | QualType resultType, SourceLocation op, |
2357 | SourceLocation rp) : |
2358 | Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, |
2359 | false, // Never type-dependent (C++ [temp.dep.expr]p3). |
2360 | // Value-dependent if the argument is type-dependent. |
2361 | TInfo->getType()->isDependentType(), |
2362 | TInfo->getType()->isInstantiationDependentType(), |
2363 | TInfo->getType()->containsUnexpandedParameterPack()), |
2364 | OpLoc(op), RParenLoc(rp) { |
2365 | UnaryExprOrTypeTraitExprBits.Kind = ExprKind; |
2366 | UnaryExprOrTypeTraitExprBits.IsType = true; |
2367 | Argument.Ty = TInfo; |
2368 | } |
2369 | |
2370 | UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, |
2371 | QualType resultType, SourceLocation op, |
2372 | SourceLocation rp); |
2373 | |
2374 | /// Construct an empty sizeof/alignof expression. |
2375 | explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) |
2376 | : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } |
2377 | |
2378 | UnaryExprOrTypeTrait getKind() const { |
2379 | return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind); |
2380 | } |
2381 | void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} |
2382 | |
2383 | bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } |
2384 | QualType getArgumentType() const { |
2385 | return getArgumentTypeInfo()->getType(); |
2386 | } |
2387 | TypeSourceInfo *getArgumentTypeInfo() const { |
2388 | assert(isArgumentType() && "calling getArgumentType() when arg is expr")((isArgumentType() && "calling getArgumentType() when arg is expr" ) ? static_cast<void> (0) : __assert_fail ("isArgumentType() && \"calling getArgumentType() when arg is expr\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2388, __PRETTY_FUNCTION__)); |
2389 | return Argument.Ty; |
2390 | } |
2391 | Expr *getArgumentExpr() { |
2392 | assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")((!isArgumentType() && "calling getArgumentExpr() when arg is type" ) ? static_cast<void> (0) : __assert_fail ("!isArgumentType() && \"calling getArgumentExpr() when arg is type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2392, __PRETTY_FUNCTION__)); |
2393 | return static_cast<Expr*>(Argument.Ex); |
2394 | } |
2395 | const Expr *getArgumentExpr() const { |
2396 | return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr(); |
2397 | } |
2398 | |
2399 | void setArgument(Expr *E) { |
2400 | Argument.Ex = E; |
2401 | UnaryExprOrTypeTraitExprBits.IsType = false; |
2402 | } |
2403 | void setArgument(TypeSourceInfo *TInfo) { |
2404 | Argument.Ty = TInfo; |
2405 | UnaryExprOrTypeTraitExprBits.IsType = true; |
2406 | } |
2407 | |
2408 | /// Gets the argument type, or the type of the argument expression, whichever |
2409 | /// is appropriate. |
2410 | QualType getTypeOfArgument() const { |
2411 | return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); |
2412 | } |
2413 | |
2414 | SourceLocation getOperatorLoc() const { return OpLoc; } |
2415 | void setOperatorLoc(SourceLocation L) { OpLoc = L; } |
2416 | |
2417 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2418 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
2419 | |
2420 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; } |
2421 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
2422 | |
2423 | static bool classof(const Stmt *T) { |
2424 | return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; |
2425 | } |
2426 | |
2427 | // Iterators |
2428 | child_range children(); |
2429 | const_child_range children() const; |
2430 | }; |
2431 | |
2432 | //===----------------------------------------------------------------------===// |
2433 | // Postfix Operators. |
2434 | //===----------------------------------------------------------------------===// |
2435 | |
2436 | /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. |
2437 | class ArraySubscriptExpr : public Expr { |
2438 | enum { LHS, RHS, END_EXPR }; |
2439 | Stmt *SubExprs[END_EXPR]; |
2440 | |
2441 | bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); } |
2442 | |
2443 | public: |
2444 | ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, |
2445 | ExprValueKind VK, ExprObjectKind OK, |
2446 | SourceLocation rbracketloc) |
2447 | : Expr(ArraySubscriptExprClass, t, VK, OK, |
2448 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
2449 | lhs->isValueDependent() || rhs->isValueDependent(), |
2450 | (lhs->isInstantiationDependent() || |
2451 | rhs->isInstantiationDependent()), |
2452 | (lhs->containsUnexpandedParameterPack() || |
2453 | rhs->containsUnexpandedParameterPack())) { |
2454 | SubExprs[LHS] = lhs; |
2455 | SubExprs[RHS] = rhs; |
2456 | ArraySubscriptExprBits.RBracketLoc = rbracketloc; |
2457 | } |
2458 | |
2459 | /// Create an empty array subscript expression. |
2460 | explicit ArraySubscriptExpr(EmptyShell Shell) |
2461 | : Expr(ArraySubscriptExprClass, Shell) { } |
2462 | |
2463 | /// An array access can be written A[4] or 4[A] (both are equivalent). |
2464 | /// - getBase() and getIdx() always present the normalized view: A[4]. |
2465 | /// In this case getBase() returns "A" and getIdx() returns "4". |
2466 | /// - getLHS() and getRHS() present the syntactic view. e.g. for |
2467 | /// 4[A] getLHS() returns "4". |
2468 | /// Note: Because vector element access is also written A[4] we must |
2469 | /// predicate the format conversion in getBase and getIdx only on the |
2470 | /// the type of the RHS, as it is possible for the LHS to be a vector of |
2471 | /// integer type |
2472 | Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); } |
2473 | const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
2474 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
2475 | |
2476 | Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); } |
2477 | const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
2478 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
2479 | |
2480 | Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); } |
2481 | const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); } |
2482 | |
2483 | Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); } |
2484 | const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); } |
2485 | |
2486 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2487 | return getLHS()->getBeginLoc(); |
2488 | } |
2489 | SourceLocation getEndLoc() const { return getRBracketLoc(); } |
2490 | |
2491 | SourceLocation getRBracketLoc() const { |
2492 | return ArraySubscriptExprBits.RBracketLoc; |
2493 | } |
2494 | void setRBracketLoc(SourceLocation L) { |
2495 | ArraySubscriptExprBits.RBracketLoc = L; |
2496 | } |
2497 | |
2498 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2499 | return getBase()->getExprLoc(); |
2500 | } |
2501 | |
2502 | static bool classof(const Stmt *T) { |
2503 | return T->getStmtClass() == ArraySubscriptExprClass; |
2504 | } |
2505 | |
2506 | // Iterators |
2507 | child_range children() { |
2508 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
2509 | } |
2510 | const_child_range children() const { |
2511 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
2512 | } |
2513 | }; |
2514 | |
2515 | /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). |
2516 | /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", |
2517 | /// while its subclasses may represent alternative syntax that (semantically) |
2518 | /// results in a function call. For example, CXXOperatorCallExpr is |
2519 | /// a subclass for overloaded operator calls that use operator syntax, e.g., |
2520 | /// "str1 + str2" to resolve to a function call. |
2521 | class CallExpr : public Expr { |
2522 | enum { FN = 0, PREARGS_START = 1 }; |
2523 | |
2524 | /// The number of arguments in the call expression. |
2525 | unsigned NumArgs; |
2526 | |
2527 | /// The location of the right parenthese. This has a different meaning for |
2528 | /// the derived classes of CallExpr. |
2529 | SourceLocation RParenLoc; |
2530 | |
2531 | void updateDependenciesFromArg(Expr *Arg); |
2532 | |
2533 | // CallExpr store some data in trailing objects. However since CallExpr |
2534 | // is used a base of other expression classes we cannot use |
2535 | // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic |
2536 | // and casts. |
2537 | // |
2538 | // The trailing objects are in order: |
2539 | // |
2540 | // * A single "Stmt *" for the callee expression. |
2541 | // |
2542 | // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions. |
2543 | // |
2544 | // * An array of getNumArgs() "Stmt *" for the argument expressions. |
2545 | // |
2546 | // Note that we store the offset in bytes from the this pointer to the start |
2547 | // of the trailing objects. It would be perfectly possible to compute it |
2548 | // based on the dynamic kind of the CallExpr. However 1.) we have plenty of |
2549 | // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to |
2550 | // compute this once and then load the offset from the bit-fields of Stmt, |
2551 | // instead of re-computing the offset each time the trailing objects are |
2552 | // accessed. |
2553 | |
2554 | /// Return a pointer to the start of the trailing array of "Stmt *". |
2555 | Stmt **getTrailingStmts() { |
2556 | return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) + |
2557 | CallExprBits.OffsetToTrailingObjects); |
2558 | } |
2559 | Stmt *const *getTrailingStmts() const { |
2560 | return const_cast<CallExpr *>(this)->getTrailingStmts(); |
2561 | } |
2562 | |
2563 | /// Map a statement class to the appropriate offset in bytes from the |
2564 | /// this pointer to the trailing objects. |
2565 | static unsigned offsetToTrailingObjects(StmtClass SC); |
2566 | |
2567 | public: |
2568 | enum class ADLCallKind : bool { NotADL, UsesADL }; |
2569 | static constexpr ADLCallKind NotADL = ADLCallKind::NotADL; |
2570 | static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL; |
2571 | |
2572 | protected: |
2573 | /// Build a call expression, assuming that appropriate storage has been |
2574 | /// allocated for the trailing objects. |
2575 | CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs, |
2576 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
2577 | SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL); |
2578 | |
2579 | /// Build an empty call expression, for deserialization. |
2580 | CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs, |
2581 | EmptyShell Empty); |
2582 | |
2583 | /// Return the size in bytes needed for the trailing objects. |
2584 | /// Used by the derived classes to allocate the right amount of storage. |
2585 | static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) { |
2586 | return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *); |
2587 | } |
2588 | |
2589 | Stmt *getPreArg(unsigned I) { |
2590 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2590, __PRETTY_FUNCTION__)); |
2591 | return getTrailingStmts()[PREARGS_START + I]; |
2592 | } |
2593 | const Stmt *getPreArg(unsigned I) const { |
2594 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2594, __PRETTY_FUNCTION__)); |
2595 | return getTrailingStmts()[PREARGS_START + I]; |
2596 | } |
2597 | void setPreArg(unsigned I, Stmt *PreArg) { |
2598 | assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2598, __PRETTY_FUNCTION__)); |
2599 | getTrailingStmts()[PREARGS_START + I] = PreArg; |
2600 | } |
2601 | |
2602 | unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } |
2603 | |
2604 | public: |
2605 | /// Create a call expression. Fn is the callee expression, Args is the |
2606 | /// argument array, Ty is the type of the call expression (which is *not* |
2607 | /// the return type in general), VK is the value kind of the call expression |
2608 | /// (lvalue, rvalue, ...), and RParenLoc is the location of the right |
2609 | /// parenthese in the call expression. MinNumArgs specifies the minimum |
2610 | /// number of arguments. The actual number of arguments will be the greater |
2611 | /// of Args.size() and MinNumArgs. This is used in a few places to allocate |
2612 | /// enough storage for the default arguments. UsesADL specifies whether the |
2613 | /// callee was found through argument-dependent lookup. |
2614 | /// |
2615 | /// Note that you can use CreateTemporary if you need a temporary call |
2616 | /// expression on the stack. |
2617 | static CallExpr *Create(const ASTContext &Ctx, Expr *Fn, |
2618 | ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK, |
2619 | SourceLocation RParenLoc, unsigned MinNumArgs = 0, |
2620 | ADLCallKind UsesADL = NotADL); |
2621 | |
2622 | /// Create a temporary call expression with no arguments in the memory |
2623 | /// pointed to by Mem. Mem must points to at least sizeof(CallExpr) |
2624 | /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr): |
2625 | /// |
2626 | /// \code{.cpp} |
2627 | /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
2628 | /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc); |
2629 | /// \endcode |
2630 | static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty, |
2631 | ExprValueKind VK, SourceLocation RParenLoc, |
2632 | ADLCallKind UsesADL = NotADL); |
2633 | |
2634 | /// Create an empty call expression, for deserialization. |
2635 | static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, |
2636 | EmptyShell Empty); |
2637 | |
2638 | Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); } |
2639 | const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); } |
2640 | void setCallee(Expr *F) { getTrailingStmts()[FN] = F; } |
2641 | |
2642 | ADLCallKind getADLCallKind() const { |
2643 | return static_cast<ADLCallKind>(CallExprBits.UsesADL); |
2644 | } |
2645 | void setADLCallKind(ADLCallKind V = UsesADL) { |
2646 | CallExprBits.UsesADL = static_cast<bool>(V); |
2647 | } |
2648 | bool usesADL() const { return getADLCallKind() == UsesADL; } |
2649 | |
2650 | Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } |
2651 | const Decl *getCalleeDecl() const { |
2652 | return getCallee()->getReferencedDeclOfCallee(); |
2653 | } |
2654 | |
2655 | /// If the callee is a FunctionDecl, return it. Otherwise return null. |
2656 | FunctionDecl *getDirectCallee() { |
2657 | return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); |
2658 | } |
2659 | const FunctionDecl *getDirectCallee() const { |
2660 | return dyn_cast_or_null<FunctionDecl>(getCalleeDecl()); |
2661 | } |
2662 | |
2663 | /// getNumArgs - Return the number of actual arguments to this call. |
2664 | unsigned getNumArgs() const { return NumArgs; } |
2665 | |
2666 | /// Retrieve the call arguments. |
2667 | Expr **getArgs() { |
2668 | return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START + |
2669 | getNumPreArgs()); |
2670 | } |
2671 | const Expr *const *getArgs() const { |
2672 | return reinterpret_cast<const Expr *const *>( |
2673 | getTrailingStmts() + PREARGS_START + getNumPreArgs()); |
2674 | } |
2675 | |
2676 | /// getArg - Return the specified argument. |
2677 | Expr *getArg(unsigned Arg) { |
2678 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2678, __PRETTY_FUNCTION__)); |
2679 | return getArgs()[Arg]; |
2680 | } |
2681 | const Expr *getArg(unsigned Arg) const { |
2682 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2682, __PRETTY_FUNCTION__)); |
2683 | return getArgs()[Arg]; |
2684 | } |
2685 | |
2686 | /// setArg - Set the specified argument. |
2687 | void setArg(unsigned Arg, Expr *ArgExpr) { |
2688 | assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2688, __PRETTY_FUNCTION__)); |
2689 | getArgs()[Arg] = ArgExpr; |
2690 | } |
2691 | |
2692 | /// Reduce the number of arguments in this call expression. This is used for |
2693 | /// example during error recovery to drop extra arguments. There is no way |
2694 | /// to perform the opposite because: 1.) We don't track how much storage |
2695 | /// we have for the argument array 2.) This would potentially require growing |
2696 | /// the argument array, something we cannot support since the arguments are |
2697 | /// stored in a trailing array. |
2698 | void shrinkNumArgs(unsigned NewNumArgs) { |
2699 | assert((NewNumArgs <= getNumArgs()) &&(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!" ) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2700, __PRETTY_FUNCTION__)) |
2700 | "shrinkNumArgs cannot increase the number of arguments!")(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!" ) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 2700, __PRETTY_FUNCTION__)); |
2701 | NumArgs = NewNumArgs; |
2702 | } |
2703 | |
2704 | /// Bluntly set a new number of arguments without doing any checks whatsoever. |
2705 | /// Only used during construction of a CallExpr in a few places in Sema. |
2706 | /// FIXME: Find a way to remove it. |
2707 | void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; } |
2708 | |
2709 | typedef ExprIterator arg_iterator; |
2710 | typedef ConstExprIterator const_arg_iterator; |
2711 | typedef llvm::iterator_range<arg_iterator> arg_range; |
2712 | typedef llvm::iterator_range<const_arg_iterator> const_arg_range; |
2713 | |
2714 | arg_range arguments() { return arg_range(arg_begin(), arg_end()); } |
2715 | const_arg_range arguments() const { |
2716 | return const_arg_range(arg_begin(), arg_end()); |
2717 | } |
2718 | |
2719 | arg_iterator arg_begin() { |
2720 | return getTrailingStmts() + PREARGS_START + getNumPreArgs(); |
2721 | } |
2722 | arg_iterator arg_end() { return arg_begin() + getNumArgs(); } |
2723 | |
2724 | const_arg_iterator arg_begin() const { |
2725 | return getTrailingStmts() + PREARGS_START + getNumPreArgs(); |
2726 | } |
2727 | const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); } |
2728 | |
2729 | /// This method provides fast access to all the subexpressions of |
2730 | /// a CallExpr without going through the slower virtual child_iterator |
2731 | /// interface. This provides efficient reverse iteration of the |
2732 | /// subexpressions. This is currently used for CFG construction. |
2733 | ArrayRef<Stmt *> getRawSubExprs() { |
2734 | return llvm::makeArrayRef(getTrailingStmts(), |
2735 | PREARGS_START + getNumPreArgs() + getNumArgs()); |
2736 | } |
2737 | |
2738 | /// getNumCommas - Return the number of commas that must have been present in |
2739 | /// this function call. |
2740 | unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; } |
2741 | |
2742 | /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID |
2743 | /// of the callee. If not, return 0. |
2744 | unsigned getBuiltinCallee() const; |
2745 | |
2746 | /// Returns \c true if this is a call to a builtin which does not |
2747 | /// evaluate side-effects within its arguments. |
2748 | bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; |
2749 | |
2750 | /// getCallReturnType - Get the return type of the call expr. This is not |
2751 | /// always the type of the expr itself, if the return type is a reference |
2752 | /// type. |
2753 | QualType getCallReturnType(const ASTContext &Ctx) const; |
2754 | |
2755 | /// Returns the WarnUnusedResultAttr that is either declared on the called |
2756 | /// function, or its return type declaration. |
2757 | const Attr *getUnusedResultAttr(const ASTContext &Ctx) const; |
2758 | |
2759 | /// Returns true if this call expression should warn on unused results. |
2760 | bool hasUnusedResultAttr(const ASTContext &Ctx) const { |
2761 | return getUnusedResultAttr(Ctx) != nullptr; |
2762 | } |
2763 | |
2764 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2765 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
2766 | |
2767 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
2768 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
2769 | |
2770 | /// Return true if this is a call to __assume() or __builtin_assume() with |
2771 | /// a non-value-dependent constant parameter evaluating as false. |
2772 | bool isBuiltinAssumeFalse(const ASTContext &Ctx) const; |
2773 | |
2774 | bool isCallToStdMove() const { |
2775 | const FunctionDecl *FD = getDirectCallee(); |
2776 | return getNumArgs() == 1 && FD && FD->isInStdNamespace() && |
2777 | FD->getIdentifier() && FD->getIdentifier()->isStr("move"); |
2778 | } |
2779 | |
2780 | static bool classof(const Stmt *T) { |
2781 | return T->getStmtClass() >= firstCallExprConstant && |
2782 | T->getStmtClass() <= lastCallExprConstant; |
2783 | } |
2784 | |
2785 | // Iterators |
2786 | child_range children() { |
2787 | return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START + |
2788 | getNumPreArgs() + getNumArgs()); |
2789 | } |
2790 | |
2791 | const_child_range children() const { |
2792 | return const_child_range(getTrailingStmts(), |
2793 | getTrailingStmts() + PREARGS_START + |
2794 | getNumPreArgs() + getNumArgs()); |
2795 | } |
2796 | }; |
2797 | |
2798 | /// Extra data stored in some MemberExpr objects. |
2799 | struct MemberExprNameQualifier { |
2800 | /// The nested-name-specifier that qualifies the name, including |
2801 | /// source-location information. |
2802 | NestedNameSpecifierLoc QualifierLoc; |
2803 | |
2804 | /// The DeclAccessPair through which the MemberDecl was found due to |
2805 | /// name qualifiers. |
2806 | DeclAccessPair FoundDecl; |
2807 | }; |
2808 | |
2809 | /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. |
2810 | /// |
2811 | class MemberExpr final |
2812 | : public Expr, |
2813 | private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier, |
2814 | ASTTemplateKWAndArgsInfo, |
2815 | TemplateArgumentLoc> { |
2816 | friend class ASTReader; |
2817 | friend class ASTStmtReader; |
2818 | friend class ASTStmtWriter; |
2819 | friend TrailingObjects; |
2820 | |
2821 | /// Base - the expression for the base pointer or structure references. In |
2822 | /// X.F, this is "X". |
2823 | Stmt *Base; |
2824 | |
2825 | /// MemberDecl - This is the decl being referenced by the field/member name. |
2826 | /// In X.F, this is the decl referenced by F. |
2827 | ValueDecl *MemberDecl; |
2828 | |
2829 | /// MemberDNLoc - Provides source/type location info for the |
2830 | /// declaration name embedded in MemberDecl. |
2831 | DeclarationNameLoc MemberDNLoc; |
2832 | |
2833 | /// MemberLoc - This is the location of the member name. |
2834 | SourceLocation MemberLoc; |
2835 | |
2836 | size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const { |
2837 | return hasQualifierOrFoundDecl(); |
2838 | } |
2839 | |
2840 | size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const { |
2841 | return hasTemplateKWAndArgsInfo(); |
2842 | } |
2843 | |
2844 | bool hasQualifierOrFoundDecl() const { |
2845 | return MemberExprBits.HasQualifierOrFoundDecl; |
2846 | } |
2847 | |
2848 | bool hasTemplateKWAndArgsInfo() const { |
2849 | return MemberExprBits.HasTemplateKWAndArgsInfo; |
2850 | } |
2851 | |
2852 | MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, |
2853 | ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo, |
2854 | QualType T, ExprValueKind VK, ExprObjectKind OK, |
2855 | NonOdrUseReason NOUR); |
2856 | MemberExpr(EmptyShell Empty) |
2857 | : Expr(MemberExprClass, Empty), Base(), MemberDecl() {} |
2858 | |
2859 | public: |
2860 | static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow, |
2861 | SourceLocation OperatorLoc, |
2862 | NestedNameSpecifierLoc QualifierLoc, |
2863 | SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, |
2864 | DeclAccessPair FoundDecl, |
2865 | DeclarationNameInfo MemberNameInfo, |
2866 | const TemplateArgumentListInfo *TemplateArgs, |
2867 | QualType T, ExprValueKind VK, ExprObjectKind OK, |
2868 | NonOdrUseReason NOUR); |
2869 | |
2870 | /// Create an implicit MemberExpr, with no location, qualifier, template |
2871 | /// arguments, and so on. Suitable only for non-static member access. |
2872 | static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base, |
2873 | bool IsArrow, ValueDecl *MemberDecl, |
2874 | QualType T, ExprValueKind VK, |
2875 | ExprObjectKind OK) { |
2876 | return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(), |
2877 | SourceLocation(), MemberDecl, |
2878 | DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()), |
2879 | DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None); |
2880 | } |
2881 | |
2882 | static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, |
2883 | bool HasFoundDecl, |
2884 | bool HasTemplateKWAndArgsInfo, |
2885 | unsigned NumTemplateArgs); |
2886 | |
2887 | void setBase(Expr *E) { Base = E; } |
2888 | Expr *getBase() const { return cast<Expr>(Base); } |
2889 | |
2890 | /// Retrieve the member declaration to which this expression refers. |
2891 | /// |
2892 | /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for |
2893 | /// static data members), a CXXMethodDecl, or an EnumConstantDecl. |
2894 | ValueDecl *getMemberDecl() const { return MemberDecl; } |
2895 | void setMemberDecl(ValueDecl *D) { MemberDecl = D; } |
2896 | |
2897 | /// Retrieves the declaration found by lookup. |
2898 | DeclAccessPair getFoundDecl() const { |
2899 | if (!hasQualifierOrFoundDecl()) |
2900 | return DeclAccessPair::make(getMemberDecl(), |
2901 | getMemberDecl()->getAccess()); |
2902 | return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl; |
2903 | } |
2904 | |
2905 | /// Determines whether this member expression actually had |
2906 | /// a C++ nested-name-specifier prior to the name of the member, e.g., |
2907 | /// x->Base::foo. |
2908 | bool hasQualifier() const { return getQualifier() != nullptr; } |
2909 | |
2910 | /// If the member name was qualified, retrieves the |
2911 | /// nested-name-specifier that precedes the member name, with source-location |
2912 | /// information. |
2913 | NestedNameSpecifierLoc getQualifierLoc() const { |
2914 | if (!hasQualifierOrFoundDecl()) |
2915 | return NestedNameSpecifierLoc(); |
2916 | return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc; |
2917 | } |
2918 | |
2919 | /// If the member name was qualified, retrieves the |
2920 | /// nested-name-specifier that precedes the member name. Otherwise, returns |
2921 | /// NULL. |
2922 | NestedNameSpecifier *getQualifier() const { |
2923 | return getQualifierLoc().getNestedNameSpecifier(); |
2924 | } |
2925 | |
2926 | /// Retrieve the location of the template keyword preceding |
2927 | /// the member name, if any. |
2928 | SourceLocation getTemplateKeywordLoc() const { |
2929 | if (!hasTemplateKWAndArgsInfo()) |
2930 | return SourceLocation(); |
2931 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc; |
2932 | } |
2933 | |
2934 | /// Retrieve the location of the left angle bracket starting the |
2935 | /// explicit template argument list following the member name, if any. |
2936 | SourceLocation getLAngleLoc() const { |
2937 | if (!hasTemplateKWAndArgsInfo()) |
2938 | return SourceLocation(); |
2939 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc; |
2940 | } |
2941 | |
2942 | /// Retrieve the location of the right angle bracket ending the |
2943 | /// explicit template argument list following the member name, if any. |
2944 | SourceLocation getRAngleLoc() const { |
2945 | if (!hasTemplateKWAndArgsInfo()) |
2946 | return SourceLocation(); |
2947 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc; |
2948 | } |
2949 | |
2950 | /// Determines whether the member name was preceded by the template keyword. |
2951 | bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } |
2952 | |
2953 | /// Determines whether the member name was followed by an |
2954 | /// explicit template argument list. |
2955 | bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } |
2956 | |
2957 | /// Copies the template arguments (if present) into the given |
2958 | /// structure. |
2959 | void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { |
2960 | if (hasExplicitTemplateArgs()) |
2961 | getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto( |
2962 | getTrailingObjects<TemplateArgumentLoc>(), List); |
2963 | } |
2964 | |
2965 | /// Retrieve the template arguments provided as part of this |
2966 | /// template-id. |
2967 | const TemplateArgumentLoc *getTemplateArgs() const { |
2968 | if (!hasExplicitTemplateArgs()) |
2969 | return nullptr; |
2970 | |
2971 | return getTrailingObjects<TemplateArgumentLoc>(); |
2972 | } |
2973 | |
2974 | /// Retrieve the number of template arguments provided as part of this |
2975 | /// template-id. |
2976 | unsigned getNumTemplateArgs() const { |
2977 | if (!hasExplicitTemplateArgs()) |
2978 | return 0; |
2979 | |
2980 | return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs; |
2981 | } |
2982 | |
2983 | ArrayRef<TemplateArgumentLoc> template_arguments() const { |
2984 | return {getTemplateArgs(), getNumTemplateArgs()}; |
2985 | } |
2986 | |
2987 | /// Retrieve the member declaration name info. |
2988 | DeclarationNameInfo getMemberNameInfo() const { |
2989 | return DeclarationNameInfo(MemberDecl->getDeclName(), |
2990 | MemberLoc, MemberDNLoc); |
2991 | } |
2992 | |
2993 | SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; } |
2994 | |
2995 | bool isArrow() const { return MemberExprBits.IsArrow; } |
2996 | void setArrow(bool A) { MemberExprBits.IsArrow = A; } |
2997 | |
2998 | /// getMemberLoc - Return the location of the "member", in X->F, it is the |
2999 | /// location of 'F'. |
3000 | SourceLocation getMemberLoc() const { return MemberLoc; } |
3001 | void setMemberLoc(SourceLocation L) { MemberLoc = L; } |
3002 | |
3003 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
3004 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
3005 | |
3006 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; } |
3007 | |
3008 | /// Determine whether the base of this explicit is implicit. |
3009 | bool isImplicitAccess() const { |
3010 | return getBase() && getBase()->isImplicitCXXThis(); |
3011 | } |
3012 | |
3013 | /// Returns true if this member expression refers to a method that |
3014 | /// was resolved from an overloaded set having size greater than 1. |
3015 | bool hadMultipleCandidates() const { |
3016 | return MemberExprBits.HadMultipleCandidates; |
3017 | } |
3018 | /// Sets the flag telling whether this expression refers to |
3019 | /// a method that was resolved from an overloaded set having size |
3020 | /// greater than 1. |
3021 | void setHadMultipleCandidates(bool V = true) { |
3022 | MemberExprBits.HadMultipleCandidates = V; |
3023 | } |
3024 | |
3025 | /// Returns true if virtual dispatch is performed. |
3026 | /// If the member access is fully qualified, (i.e. X::f()), virtual |
3027 | /// dispatching is not performed. In -fapple-kext mode qualified |
3028 | /// calls to virtual method will still go through the vtable. |
3029 | bool performsVirtualDispatch(const LangOptions &LO) const { |
3030 | return LO.AppleKext || !hasQualifier(); |
3031 | } |
3032 | |
3033 | /// Is this expression a non-odr-use reference, and if so, why? |
3034 | /// This is only meaningful if the named member is a static member. |
3035 | NonOdrUseReason isNonOdrUse() const { |
3036 | return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason); |
3037 | } |
3038 | |
3039 | static bool classof(const Stmt *T) { |
3040 | return T->getStmtClass() == MemberExprClass; |
3041 | } |
3042 | |
3043 | // Iterators |
3044 | child_range children() { return child_range(&Base, &Base+1); } |
3045 | const_child_range children() const { |
3046 | return const_child_range(&Base, &Base + 1); |
3047 | } |
3048 | }; |
3049 | |
3050 | /// CompoundLiteralExpr - [C99 6.5.2.5] |
3051 | /// |
3052 | class CompoundLiteralExpr : public Expr { |
3053 | /// LParenLoc - If non-null, this is the location of the left paren in a |
3054 | /// compound literal like "(int){4}". This can be null if this is a |
3055 | /// synthesized compound expression. |
3056 | SourceLocation LParenLoc; |
3057 | |
3058 | /// The type as written. This can be an incomplete array type, in |
3059 | /// which case the actual expression type will be different. |
3060 | /// The int part of the pair stores whether this expr is file scope. |
3061 | llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope; |
3062 | Stmt *Init; |
3063 | public: |
3064 | CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, |
3065 | QualType T, ExprValueKind VK, Expr *init, bool fileScope) |
3066 | : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, |
3067 | tinfo->getType()->isDependentType(), |
3068 | init->isValueDependent(), |
3069 | (init->isInstantiationDependent() || |
3070 | tinfo->getType()->isInstantiationDependentType()), |
3071 | init->containsUnexpandedParameterPack()), |
3072 | LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} |
3073 | |
3074 | /// Construct an empty compound literal. |
3075 | explicit CompoundLiteralExpr(EmptyShell Empty) |
3076 | : Expr(CompoundLiteralExprClass, Empty) { } |
3077 | |
3078 | const Expr *getInitializer() const { return cast<Expr>(Init); } |
3079 | Expr *getInitializer() { return cast<Expr>(Init); } |
3080 | void setInitializer(Expr *E) { Init = E; } |
3081 | |
3082 | bool isFileScope() const { return TInfoAndScope.getInt(); } |
3083 | void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } |
3084 | |
3085 | SourceLocation getLParenLoc() const { return LParenLoc; } |
3086 | void setLParenLoc(SourceLocation L) { LParenLoc = L; } |
3087 | |
3088 | TypeSourceInfo *getTypeSourceInfo() const { |
3089 | return TInfoAndScope.getPointer(); |
3090 | } |
3091 | void setTypeSourceInfo(TypeSourceInfo *tinfo) { |
3092 | TInfoAndScope.setPointer(tinfo); |
3093 | } |
3094 | |
3095 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3096 | // FIXME: Init should never be null. |
3097 | if (!Init) |
3098 | return SourceLocation(); |
3099 | if (LParenLoc.isInvalid()) |
3100 | return Init->getBeginLoc(); |
3101 | return LParenLoc; |
3102 | } |
3103 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3104 | // FIXME: Init should never be null. |
3105 | if (!Init) |
3106 | return SourceLocation(); |
3107 | return Init->getEndLoc(); |
3108 | } |
3109 | |
3110 | static bool classof(const Stmt *T) { |
3111 | return T->getStmtClass() == CompoundLiteralExprClass; |
3112 | } |
3113 | |
3114 | // Iterators |
3115 | child_range children() { return child_range(&Init, &Init+1); } |
3116 | const_child_range children() const { |
3117 | return const_child_range(&Init, &Init + 1); |
3118 | } |
3119 | }; |
3120 | |
3121 | /// CastExpr - Base class for type casts, including both implicit |
3122 | /// casts (ImplicitCastExpr) and explicit casts that have some |
3123 | /// representation in the source code (ExplicitCastExpr's derived |
3124 | /// classes). |
3125 | class CastExpr : public Expr { |
3126 | Stmt *Op; |
3127 | |
3128 | bool CastConsistency() const; |
3129 | |
3130 | const CXXBaseSpecifier * const *path_buffer() const { |
3131 | return const_cast<CastExpr*>(this)->path_buffer(); |
3132 | } |
3133 | CXXBaseSpecifier **path_buffer(); |
3134 | |
3135 | protected: |
3136 | CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, |
3137 | Expr *op, unsigned BasePathSize) |
3138 | : Expr(SC, ty, VK, OK_Ordinary, |
3139 | // Cast expressions are type-dependent if the type is |
3140 | // dependent (C++ [temp.dep.expr]p3). |
3141 | ty->isDependentType(), |
3142 | // Cast expressions are value-dependent if the type is |
3143 | // dependent or if the subexpression is value-dependent. |
3144 | ty->isDependentType() || (op && op->isValueDependent()), |
3145 | (ty->isInstantiationDependentType() || |
3146 | (op && op->isInstantiationDependent())), |
3147 | // An implicit cast expression doesn't (lexically) contain an |
3148 | // unexpanded pack, even if its target type does. |
3149 | ((SC != ImplicitCastExprClass && |
3150 | ty->containsUnexpandedParameterPack()) || |
3151 | (op && op->containsUnexpandedParameterPack()))), |
3152 | Op(op) { |
3153 | CastExprBits.Kind = kind; |
3154 | CastExprBits.PartOfExplicitCast = false; |
3155 | CastExprBits.BasePathSize = BasePathSize; |
3156 | assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3157, __PRETTY_FUNCTION__)) |
3157 | "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3157, __PRETTY_FUNCTION__)); |
3158 | assert(CastConsistency())((CastConsistency()) ? static_cast<void> (0) : __assert_fail ("CastConsistency()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3158, __PRETTY_FUNCTION__)); |
3159 | } |
3160 | |
3161 | /// Construct an empty cast. |
3162 | CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) |
3163 | : Expr(SC, Empty) { |
3164 | CastExprBits.PartOfExplicitCast = false; |
3165 | CastExprBits.BasePathSize = BasePathSize; |
3166 | assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3167, __PRETTY_FUNCTION__)) |
3167 | "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!" ) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3167, __PRETTY_FUNCTION__)); |
3168 | } |
3169 | |
3170 | public: |
3171 | CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } |
3172 | void setCastKind(CastKind K) { CastExprBits.Kind = K; } |
3173 | |
3174 | static const char *getCastKindName(CastKind CK); |
3175 | const char *getCastKindName() const { return getCastKindName(getCastKind()); } |
3176 | |
3177 | Expr *getSubExpr() { return cast<Expr>(Op); } |
3178 | const Expr *getSubExpr() const { return cast<Expr>(Op); } |
3179 | void setSubExpr(Expr *E) { Op = E; } |
3180 | |
3181 | /// Retrieve the cast subexpression as it was written in the source |
3182 | /// code, looking through any implicit casts or other intermediate nodes |
3183 | /// introduced by semantic analysis. |
3184 | Expr *getSubExprAsWritten(); |
3185 | const Expr *getSubExprAsWritten() const { |
3186 | return const_cast<CastExpr *>(this)->getSubExprAsWritten(); |
3187 | } |
3188 | |
3189 | /// If this cast applies a user-defined conversion, retrieve the conversion |
3190 | /// function that it invokes. |
3191 | NamedDecl *getConversionFunction() const; |
3192 | |
3193 | typedef CXXBaseSpecifier **path_iterator; |
3194 | typedef const CXXBaseSpecifier *const *path_const_iterator; |
3195 | bool path_empty() const { return path_size() == 0; } |
3196 | unsigned path_size() const { return CastExprBits.BasePathSize; } |
3197 | path_iterator path_begin() { return path_buffer(); } |
3198 | path_iterator path_end() { return path_buffer() + path_size(); } |
3199 | path_const_iterator path_begin() const { return path_buffer(); } |
3200 | path_const_iterator path_end() const { return path_buffer() + path_size(); } |
3201 | |
3202 | llvm::iterator_range<path_iterator> path() { |
3203 | return llvm::make_range(path_begin(), path_end()); |
3204 | } |
3205 | llvm::iterator_range<path_const_iterator> path() const { |
3206 | return llvm::make_range(path_begin(), path_end()); |
3207 | } |
3208 | |
3209 | const FieldDecl *getTargetUnionField() const { |
3210 | assert(getCastKind() == CK_ToUnion)((getCastKind() == CK_ToUnion) ? static_cast<void> (0) : __assert_fail ("getCastKind() == CK_ToUnion", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3210, __PRETTY_FUNCTION__)); |
3211 | return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType()); |
3212 | } |
3213 | |
3214 | static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType, |
3215 | QualType opType); |
3216 | static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD, |
3217 | QualType opType); |
3218 | |
3219 | static bool classof(const Stmt *T) { |
3220 | return T->getStmtClass() >= firstCastExprConstant && |
3221 | T->getStmtClass() <= lastCastExprConstant; |
3222 | } |
3223 | |
3224 | // Iterators |
3225 | child_range children() { return child_range(&Op, &Op+1); } |
3226 | const_child_range children() const { return const_child_range(&Op, &Op + 1); } |
3227 | }; |
3228 | |
3229 | /// ImplicitCastExpr - Allows us to explicitly represent implicit type |
3230 | /// conversions, which have no direct representation in the original |
3231 | /// source code. For example: converting T[]->T*, void f()->void |
3232 | /// (*f)(), float->double, short->int, etc. |
3233 | /// |
3234 | /// In C, implicit casts always produce rvalues. However, in C++, an |
3235 | /// implicit cast whose result is being bound to a reference will be |
3236 | /// an lvalue or xvalue. For example: |
3237 | /// |
3238 | /// @code |
3239 | /// class Base { }; |
3240 | /// class Derived : public Base { }; |
3241 | /// Derived &&ref(); |
3242 | /// void f(Derived d) { |
3243 | /// Base& b = d; // initializer is an ImplicitCastExpr |
3244 | /// // to an lvalue of type Base |
3245 | /// Base&& r = ref(); // initializer is an ImplicitCastExpr |
3246 | /// // to an xvalue of type Base |
3247 | /// } |
3248 | /// @endcode |
3249 | class ImplicitCastExpr final |
3250 | : public CastExpr, |
3251 | private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> { |
3252 | |
3253 | ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, |
3254 | unsigned BasePathLength, ExprValueKind VK) |
3255 | : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { } |
3256 | |
3257 | /// Construct an empty implicit cast. |
3258 | explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) |
3259 | : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } |
3260 | |
3261 | public: |
3262 | enum OnStack_t { OnStack }; |
3263 | ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, |
3264 | ExprValueKind VK) |
3265 | : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { |
3266 | } |
3267 | |
3268 | bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; } |
3269 | void setIsPartOfExplicitCast(bool PartOfExplicitCast) { |
3270 | CastExprBits.PartOfExplicitCast = PartOfExplicitCast; |
3271 | } |
3272 | |
3273 | static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, |
3274 | CastKind Kind, Expr *Operand, |
3275 | const CXXCastPath *BasePath, |
3276 | ExprValueKind Cat); |
3277 | |
3278 | static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, |
3279 | unsigned PathSize); |
3280 | |
3281 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3282 | return getSubExpr()->getBeginLoc(); |
3283 | } |
3284 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3285 | return getSubExpr()->getEndLoc(); |
3286 | } |
3287 | |
3288 | static bool classof(const Stmt *T) { |
3289 | return T->getStmtClass() == ImplicitCastExprClass; |
3290 | } |
3291 | |
3292 | friend TrailingObjects; |
3293 | friend class CastExpr; |
3294 | }; |
3295 | |
3296 | /// ExplicitCastExpr - An explicit cast written in the source |
3297 | /// code. |
3298 | /// |
3299 | /// This class is effectively an abstract class, because it provides |
3300 | /// the basic representation of an explicitly-written cast without |
3301 | /// specifying which kind of cast (C cast, functional cast, static |
3302 | /// cast, etc.) was written; specific derived classes represent the |
3303 | /// particular style of cast and its location information. |
3304 | /// |
3305 | /// Unlike implicit casts, explicit cast nodes have two different |
3306 | /// types: the type that was written into the source code, and the |
3307 | /// actual type of the expression as determined by semantic |
3308 | /// analysis. These types may differ slightly. For example, in C++ one |
3309 | /// can cast to a reference type, which indicates that the resulting |
3310 | /// expression will be an lvalue or xvalue. The reference type, however, |
3311 | /// will not be used as the type of the expression. |
3312 | class ExplicitCastExpr : public CastExpr { |
3313 | /// TInfo - Source type info for the (written) type |
3314 | /// this expression is casting to. |
3315 | TypeSourceInfo *TInfo; |
3316 | |
3317 | protected: |
3318 | ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, |
3319 | CastKind kind, Expr *op, unsigned PathSize, |
3320 | TypeSourceInfo *writtenTy) |
3321 | : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} |
3322 | |
3323 | /// Construct an empty explicit cast. |
3324 | ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) |
3325 | : CastExpr(SC, Shell, PathSize) { } |
3326 | |
3327 | public: |
3328 | /// getTypeInfoAsWritten - Returns the type source info for the type |
3329 | /// that this expression is casting to. |
3330 | TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } |
3331 | void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } |
3332 | |
3333 | /// getTypeAsWritten - Returns the type that this expression is |
3334 | /// casting to, as written in the source code. |
3335 | QualType getTypeAsWritten() const { return TInfo->getType(); } |
3336 | |
3337 | static bool classof(const Stmt *T) { |
3338 | return T->getStmtClass() >= firstExplicitCastExprConstant && |
3339 | T->getStmtClass() <= lastExplicitCastExprConstant; |
3340 | } |
3341 | }; |
3342 | |
3343 | /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style |
3344 | /// cast in C++ (C++ [expr.cast]), which uses the syntax |
3345 | /// (Type)expr. For example: @c (int)f. |
3346 | class CStyleCastExpr final |
3347 | : public ExplicitCastExpr, |
3348 | private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> { |
3349 | SourceLocation LPLoc; // the location of the left paren |
3350 | SourceLocation RPLoc; // the location of the right paren |
3351 | |
3352 | CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, |
3353 | unsigned PathSize, TypeSourceInfo *writtenTy, |
3354 | SourceLocation l, SourceLocation r) |
3355 | : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, |
3356 | writtenTy), LPLoc(l), RPLoc(r) {} |
3357 | |
3358 | /// Construct an empty C-style explicit cast. |
3359 | explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) |
3360 | : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } |
3361 | |
3362 | public: |
3363 | static CStyleCastExpr *Create(const ASTContext &Context, QualType T, |
3364 | ExprValueKind VK, CastKind K, |
3365 | Expr *Op, const CXXCastPath *BasePath, |
3366 | TypeSourceInfo *WrittenTy, SourceLocation L, |
3367 | SourceLocation R); |
3368 | |
3369 | static CStyleCastExpr *CreateEmpty(const ASTContext &Context, |
3370 | unsigned PathSize); |
3371 | |
3372 | SourceLocation getLParenLoc() const { return LPLoc; } |
3373 | void setLParenLoc(SourceLocation L) { LPLoc = L; } |
3374 | |
3375 | SourceLocation getRParenLoc() const { return RPLoc; } |
3376 | void setRParenLoc(SourceLocation L) { RPLoc = L; } |
3377 | |
3378 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; } |
3379 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3380 | return getSubExpr()->getEndLoc(); |
3381 | } |
3382 | |
3383 | static bool classof(const Stmt *T) { |
3384 | return T->getStmtClass() == CStyleCastExprClass; |
3385 | } |
3386 | |
3387 | friend TrailingObjects; |
3388 | friend class CastExpr; |
3389 | }; |
3390 | |
3391 | /// A builtin binary operation expression such as "x + y" or "x <= y". |
3392 | /// |
3393 | /// This expression node kind describes a builtin binary operation, |
3394 | /// such as "x + y" for integer values "x" and "y". The operands will |
3395 | /// already have been converted to appropriate types (e.g., by |
3396 | /// performing promotions or conversions). |
3397 | /// |
3398 | /// In C++, where operators may be overloaded, a different kind of |
3399 | /// expression node (CXXOperatorCallExpr) is used to express the |
3400 | /// invocation of an overloaded operator with operator syntax. Within |
3401 | /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is |
3402 | /// used to store an expression "x + y" depends on the subexpressions |
3403 | /// for x and y. If neither x or y is type-dependent, and the "+" |
3404 | /// operator resolves to a built-in operation, BinaryOperator will be |
3405 | /// used to express the computation (x and y may still be |
3406 | /// value-dependent). If either x or y is type-dependent, or if the |
3407 | /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will |
3408 | /// be used to express the computation. |
3409 | class BinaryOperator : public Expr { |
3410 | enum { LHS, RHS, END_EXPR }; |
3411 | Stmt *SubExprs[END_EXPR]; |
3412 | |
3413 | public: |
3414 | typedef BinaryOperatorKind Opcode; |
3415 | |
3416 | BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, |
3417 | ExprValueKind VK, ExprObjectKind OK, |
3418 | SourceLocation opLoc, FPOptions FPFeatures) |
3419 | : Expr(BinaryOperatorClass, ResTy, VK, OK, |
3420 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
3421 | lhs->isValueDependent() || rhs->isValueDependent(), |
3422 | (lhs->isInstantiationDependent() || |
3423 | rhs->isInstantiationDependent()), |
3424 | (lhs->containsUnexpandedParameterPack() || |
3425 | rhs->containsUnexpandedParameterPack())) { |
3426 | BinaryOperatorBits.Opc = opc; |
3427 | BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); |
3428 | BinaryOperatorBits.OpLoc = opLoc; |
3429 | SubExprs[LHS] = lhs; |
3430 | SubExprs[RHS] = rhs; |
3431 | assert(!isCompoundAssignmentOp() &&((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3432, __PRETTY_FUNCTION__)) |
3432 | "Use CompoundAssignOperator for compound assignments")((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3432, __PRETTY_FUNCTION__)); |
3433 | } |
3434 | |
3435 | /// Construct an empty binary operator. |
3436 | explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) { |
3437 | BinaryOperatorBits.Opc = BO_Comma; |
3438 | } |
3439 | |
3440 | SourceLocation getExprLoc() const { return getOperatorLoc(); } |
3441 | SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; } |
3442 | void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; } |
3443 | |
3444 | Opcode getOpcode() const { |
3445 | return static_cast<Opcode>(BinaryOperatorBits.Opc); |
3446 | } |
3447 | void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; } |
3448 | |
3449 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
3450 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
3451 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
3452 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
3453 | |
3454 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3455 | return getLHS()->getBeginLoc(); |
3456 | } |
3457 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3458 | return getRHS()->getEndLoc(); |
3459 | } |
3460 | |
3461 | /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it |
3462 | /// corresponds to, e.g. "<<=". |
3463 | static StringRef getOpcodeStr(Opcode Op); |
3464 | |
3465 | StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } |
3466 | |
3467 | /// Retrieve the binary opcode that corresponds to the given |
3468 | /// overloaded operator. |
3469 | static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); |
3470 | |
3471 | /// Retrieve the overloaded operator kind that corresponds to |
3472 | /// the given binary opcode. |
3473 | static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); |
3474 | |
3475 | /// predicates to categorize the respective opcodes. |
3476 | static bool isPtrMemOp(Opcode Opc) { |
3477 | return Opc == BO_PtrMemD || Opc == BO_PtrMemI; |
3478 | } |
3479 | bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); } |
3480 | |
3481 | static bool isMultiplicativeOp(Opcode Opc) { |
3482 | return Opc >= BO_Mul && Opc <= BO_Rem; |
3483 | } |
3484 | bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } |
3485 | static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } |
3486 | bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } |
3487 | static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } |
3488 | bool isShiftOp() const { return isShiftOp(getOpcode()); } |
3489 | |
3490 | static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } |
3491 | bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } |
3492 | |
3493 | static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } |
3494 | bool isRelationalOp() const { return isRelationalOp(getOpcode()); } |
3495 | |
3496 | static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } |
3497 | bool isEqualityOp() const { return isEqualityOp(getOpcode()); } |
3498 | |
3499 | static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; } |
3500 | bool isComparisonOp() const { return isComparisonOp(getOpcode()); } |
3501 | |
3502 | static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; } |
3503 | bool isCommaOp() const { return isCommaOp(getOpcode()); } |
3504 | |
3505 | static Opcode negateComparisonOp(Opcode Opc) { |
3506 | switch (Opc) { |
3507 | default: |
3508 | llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3508); |
3509 | case BO_LT: return BO_GE; |
3510 | case BO_GT: return BO_LE; |
3511 | case BO_LE: return BO_GT; |
3512 | case BO_GE: return BO_LT; |
3513 | case BO_EQ: return BO_NE; |
3514 | case BO_NE: return BO_EQ; |
3515 | } |
3516 | } |
3517 | |
3518 | static Opcode reverseComparisonOp(Opcode Opc) { |
3519 | switch (Opc) { |
3520 | default: |
3521 | llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3521); |
3522 | case BO_LT: return BO_GT; |
3523 | case BO_GT: return BO_LT; |
3524 | case BO_LE: return BO_GE; |
3525 | case BO_GE: return BO_LE; |
3526 | case BO_EQ: |
3527 | case BO_NE: |
3528 | return Opc; |
3529 | } |
3530 | } |
3531 | |
3532 | static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } |
3533 | bool isLogicalOp() const { return isLogicalOp(getOpcode()); } |
3534 | |
3535 | static bool isAssignmentOp(Opcode Opc) { |
3536 | return Opc >= BO_Assign && Opc <= BO_OrAssign; |
3537 | } |
3538 | bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } |
3539 | |
3540 | static bool isCompoundAssignmentOp(Opcode Opc) { |
3541 | return Opc > BO_Assign && Opc <= BO_OrAssign; |
3542 | } |
3543 | bool isCompoundAssignmentOp() const { |
3544 | return isCompoundAssignmentOp(getOpcode()); |
3545 | } |
3546 | static Opcode getOpForCompoundAssignment(Opcode Opc) { |
3547 | assert(isCompoundAssignmentOp(Opc))((isCompoundAssignmentOp(Opc)) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp(Opc)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3547, __PRETTY_FUNCTION__)); |
3548 | if (Opc >= BO_AndAssign) |
3549 | return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); |
3550 | else |
3551 | return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); |
3552 | } |
3553 | |
3554 | static bool isShiftAssignOp(Opcode Opc) { |
3555 | return Opc == BO_ShlAssign || Opc == BO_ShrAssign; |
3556 | } |
3557 | bool isShiftAssignOp() const { |
3558 | return isShiftAssignOp(getOpcode()); |
3559 | } |
3560 | |
3561 | // Return true if a binary operator using the specified opcode and operands |
3562 | // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized |
3563 | // integer to a pointer. |
3564 | static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, |
3565 | Expr *LHS, Expr *RHS); |
3566 | |
3567 | static bool classof(const Stmt *S) { |
3568 | return S->getStmtClass() >= firstBinaryOperatorConstant && |
3569 | S->getStmtClass() <= lastBinaryOperatorConstant; |
3570 | } |
3571 | |
3572 | // Iterators |
3573 | child_range children() { |
3574 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
3575 | } |
3576 | const_child_range children() const { |
3577 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
3578 | } |
3579 | |
3580 | // Set the FP contractability status of this operator. Only meaningful for |
3581 | // operations on floating point types. |
3582 | void setFPFeatures(FPOptions F) { |
3583 | BinaryOperatorBits.FPFeatures = F.getInt(); |
3584 | } |
3585 | |
3586 | FPOptions getFPFeatures() const { |
3587 | return FPOptions(BinaryOperatorBits.FPFeatures); |
3588 | } |
3589 | |
3590 | // Get the FP contractability status of this operator. Only meaningful for |
3591 | // operations on floating point types. |
3592 | bool isFPContractableWithinStatement() const { |
3593 | return getFPFeatures().allowFPContractWithinStatement(); |
3594 | } |
3595 | |
3596 | // Get the FENV_ACCESS status of this operator. Only meaningful for |
3597 | // operations on floating point types. |
3598 | bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); } |
3599 | |
3600 | protected: |
3601 | BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, |
3602 | ExprValueKind VK, ExprObjectKind OK, |
3603 | SourceLocation opLoc, FPOptions FPFeatures, bool dead2) |
3604 | : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, |
3605 | lhs->isTypeDependent() || rhs->isTypeDependent(), |
3606 | lhs->isValueDependent() || rhs->isValueDependent(), |
3607 | (lhs->isInstantiationDependent() || |
3608 | rhs->isInstantiationDependent()), |
3609 | (lhs->containsUnexpandedParameterPack() || |
3610 | rhs->containsUnexpandedParameterPack())) { |
3611 | BinaryOperatorBits.Opc = opc; |
3612 | BinaryOperatorBits.FPFeatures = FPFeatures.getInt(); |
3613 | BinaryOperatorBits.OpLoc = opLoc; |
3614 | SubExprs[LHS] = lhs; |
3615 | SubExprs[RHS] = rhs; |
3616 | } |
3617 | |
3618 | BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { |
3619 | BinaryOperatorBits.Opc = BO_MulAssign; |
3620 | } |
3621 | }; |
3622 | |
3623 | /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep |
3624 | /// track of the type the operation is performed in. Due to the semantics of |
3625 | /// these operators, the operands are promoted, the arithmetic performed, an |
3626 | /// implicit conversion back to the result type done, then the assignment takes |
3627 | /// place. This captures the intermediate type which the computation is done |
3628 | /// in. |
3629 | class CompoundAssignOperator : public BinaryOperator { |
3630 | QualType ComputationLHSType; |
3631 | QualType ComputationResultType; |
3632 | public: |
3633 | CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, |
3634 | ExprValueKind VK, ExprObjectKind OK, |
3635 | QualType CompLHSType, QualType CompResultType, |
3636 | SourceLocation OpLoc, FPOptions FPFeatures) |
3637 | : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, |
3638 | true), |
3639 | ComputationLHSType(CompLHSType), |
3640 | ComputationResultType(CompResultType) { |
3641 | assert(isCompoundAssignmentOp() &&((isCompoundAssignmentOp() && "Only should be used for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3642, __PRETTY_FUNCTION__)) |
3642 | "Only should be used for compound assignments")((isCompoundAssignmentOp() && "Only should be used for compound assignments" ) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3642, __PRETTY_FUNCTION__)); |
3643 | } |
3644 | |
3645 | /// Build an empty compound assignment operator expression. |
3646 | explicit CompoundAssignOperator(EmptyShell Empty) |
3647 | : BinaryOperator(CompoundAssignOperatorClass, Empty) { } |
3648 | |
3649 | // The two computation types are the type the LHS is converted |
3650 | // to for the computation and the type of the result; the two are |
3651 | // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). |
3652 | QualType getComputationLHSType() const { return ComputationLHSType; } |
3653 | void setComputationLHSType(QualType T) { ComputationLHSType = T; } |
3654 | |
3655 | QualType getComputationResultType() const { return ComputationResultType; } |
3656 | void setComputationResultType(QualType T) { ComputationResultType = T; } |
3657 | |
3658 | static bool classof(const Stmt *S) { |
3659 | return S->getStmtClass() == CompoundAssignOperatorClass; |
3660 | } |
3661 | }; |
3662 | |
3663 | /// AbstractConditionalOperator - An abstract base class for |
3664 | /// ConditionalOperator and BinaryConditionalOperator. |
3665 | class AbstractConditionalOperator : public Expr { |
3666 | SourceLocation QuestionLoc, ColonLoc; |
3667 | friend class ASTStmtReader; |
3668 | |
3669 | protected: |
3670 | AbstractConditionalOperator(StmtClass SC, QualType T, |
3671 | ExprValueKind VK, ExprObjectKind OK, |
3672 | bool TD, bool VD, bool ID, |
3673 | bool ContainsUnexpandedParameterPack, |
3674 | SourceLocation qloc, |
3675 | SourceLocation cloc) |
3676 | : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), |
3677 | QuestionLoc(qloc), ColonLoc(cloc) {} |
3678 | |
3679 | AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) |
3680 | : Expr(SC, Empty) { } |
3681 | |
3682 | public: |
3683 | // getCond - Return the expression representing the condition for |
3684 | // the ?: operator. |
3685 | Expr *getCond() const; |
3686 | |
3687 | // getTrueExpr - Return the subexpression representing the value of |
3688 | // the expression if the condition evaluates to true. |
3689 | Expr *getTrueExpr() const; |
3690 | |
3691 | // getFalseExpr - Return the subexpression representing the value of |
3692 | // the expression if the condition evaluates to false. This is |
3693 | // the same as getRHS. |
3694 | Expr *getFalseExpr() const; |
3695 | |
3696 | SourceLocation getQuestionLoc() const { return QuestionLoc; } |
3697 | SourceLocation getColonLoc() const { return ColonLoc; } |
3698 | |
3699 | static bool classof(const Stmt *T) { |
3700 | return T->getStmtClass() == ConditionalOperatorClass || |
3701 | T->getStmtClass() == BinaryConditionalOperatorClass; |
3702 | } |
3703 | }; |
3704 | |
3705 | /// ConditionalOperator - The ?: ternary operator. The GNU "missing |
3706 | /// middle" extension is a BinaryConditionalOperator. |
3707 | class ConditionalOperator : public AbstractConditionalOperator { |
3708 | enum { COND, LHS, RHS, END_EXPR }; |
3709 | Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. |
3710 | |
3711 | friend class ASTStmtReader; |
3712 | public: |
3713 | ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, |
3714 | SourceLocation CLoc, Expr *rhs, |
3715 | QualType t, ExprValueKind VK, ExprObjectKind OK) |
3716 | : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, |
3717 | // FIXME: the type of the conditional operator doesn't |
3718 | // depend on the type of the conditional, but the standard |
3719 | // seems to imply that it could. File a bug! |
3720 | (lhs->isTypeDependent() || rhs->isTypeDependent()), |
3721 | (cond->isValueDependent() || lhs->isValueDependent() || |
3722 | rhs->isValueDependent()), |
3723 | (cond->isInstantiationDependent() || |
3724 | lhs->isInstantiationDependent() || |
3725 | rhs->isInstantiationDependent()), |
3726 | (cond->containsUnexpandedParameterPack() || |
3727 | lhs->containsUnexpandedParameterPack() || |
3728 | rhs->containsUnexpandedParameterPack()), |
3729 | QLoc, CLoc) { |
3730 | SubExprs[COND] = cond; |
3731 | SubExprs[LHS] = lhs; |
3732 | SubExprs[RHS] = rhs; |
3733 | } |
3734 | |
3735 | /// Build an empty conditional operator. |
3736 | explicit ConditionalOperator(EmptyShell Empty) |
3737 | : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } |
3738 | |
3739 | // getCond - Return the expression representing the condition for |
3740 | // the ?: operator. |
3741 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
3742 | |
3743 | // getTrueExpr - Return the subexpression representing the value of |
3744 | // the expression if the condition evaluates to true. |
3745 | Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); } |
3746 | |
3747 | // getFalseExpr - Return the subexpression representing the value of |
3748 | // the expression if the condition evaluates to false. This is |
3749 | // the same as getRHS. |
3750 | Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); } |
3751 | |
3752 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
3753 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
3754 | |
3755 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3756 | return getCond()->getBeginLoc(); |
3757 | } |
3758 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3759 | return getRHS()->getEndLoc(); |
3760 | } |
3761 | |
3762 | static bool classof(const Stmt *T) { |
3763 | return T->getStmtClass() == ConditionalOperatorClass; |
3764 | } |
3765 | |
3766 | // Iterators |
3767 | child_range children() { |
3768 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
3769 | } |
3770 | const_child_range children() const { |
3771 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
3772 | } |
3773 | }; |
3774 | |
3775 | /// BinaryConditionalOperator - The GNU extension to the conditional |
3776 | /// operator which allows the middle operand to be omitted. |
3777 | /// |
3778 | /// This is a different expression kind on the assumption that almost |
3779 | /// every client ends up needing to know that these are different. |
3780 | class BinaryConditionalOperator : public AbstractConditionalOperator { |
3781 | enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; |
3782 | |
3783 | /// - the common condition/left-hand-side expression, which will be |
3784 | /// evaluated as the opaque value |
3785 | /// - the condition, expressed in terms of the opaque value |
3786 | /// - the left-hand-side, expressed in terms of the opaque value |
3787 | /// - the right-hand-side |
3788 | Stmt *SubExprs[NUM_SUBEXPRS]; |
3789 | OpaqueValueExpr *OpaqueValue; |
3790 | |
3791 | friend class ASTStmtReader; |
3792 | public: |
3793 | BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, |
3794 | Expr *cond, Expr *lhs, Expr *rhs, |
3795 | SourceLocation qloc, SourceLocation cloc, |
3796 | QualType t, ExprValueKind VK, ExprObjectKind OK) |
3797 | : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, |
3798 | (common->isTypeDependent() || rhs->isTypeDependent()), |
3799 | (common->isValueDependent() || rhs->isValueDependent()), |
3800 | (common->isInstantiationDependent() || |
3801 | rhs->isInstantiationDependent()), |
3802 | (common->containsUnexpandedParameterPack() || |
3803 | rhs->containsUnexpandedParameterPack()), |
3804 | qloc, cloc), |
3805 | OpaqueValue(opaqueValue) { |
3806 | SubExprs[COMMON] = common; |
3807 | SubExprs[COND] = cond; |
3808 | SubExprs[LHS] = lhs; |
3809 | SubExprs[RHS] = rhs; |
3810 | assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")((OpaqueValue->getSourceExpr() == common && "Wrong opaque value" ) ? static_cast<void> (0) : __assert_fail ("OpaqueValue->getSourceExpr() == common && \"Wrong opaque value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 3810, __PRETTY_FUNCTION__)); |
3811 | } |
3812 | |
3813 | /// Build an empty conditional operator. |
3814 | explicit BinaryConditionalOperator(EmptyShell Empty) |
3815 | : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } |
3816 | |
3817 | /// getCommon - Return the common expression, written to the |
3818 | /// left of the condition. The opaque value will be bound to the |
3819 | /// result of this expression. |
3820 | Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); } |
3821 | |
3822 | /// getOpaqueValue - Return the opaque value placeholder. |
3823 | OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } |
3824 | |
3825 | /// getCond - Return the condition expression; this is defined |
3826 | /// in terms of the opaque value. |
3827 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
3828 | |
3829 | /// getTrueExpr - Return the subexpression which will be |
3830 | /// evaluated if the condition evaluates to true; this is defined |
3831 | /// in terms of the opaque value. |
3832 | Expr *getTrueExpr() const { |
3833 | return cast<Expr>(SubExprs[LHS]); |
3834 | } |
3835 | |
3836 | /// getFalseExpr - Return the subexpression which will be |
3837 | /// evaluated if the condnition evaluates to false; this is |
3838 | /// defined in terms of the opaque value. |
3839 | Expr *getFalseExpr() const { |
3840 | return cast<Expr>(SubExprs[RHS]); |
3841 | } |
3842 | |
3843 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3844 | return getCommon()->getBeginLoc(); |
3845 | } |
3846 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
3847 | return getFalseExpr()->getEndLoc(); |
3848 | } |
3849 | |
3850 | static bool classof(const Stmt *T) { |
3851 | return T->getStmtClass() == BinaryConditionalOperatorClass; |
3852 | } |
3853 | |
3854 | // Iterators |
3855 | child_range children() { |
3856 | return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); |
3857 | } |
3858 | const_child_range children() const { |
3859 | return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); |
3860 | } |
3861 | }; |
3862 | |
3863 | inline Expr *AbstractConditionalOperator::getCond() const { |
3864 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3865 | return co->getCond(); |
3866 | return cast<BinaryConditionalOperator>(this)->getCond(); |
3867 | } |
3868 | |
3869 | inline Expr *AbstractConditionalOperator::getTrueExpr() const { |
3870 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3871 | return co->getTrueExpr(); |
3872 | return cast<BinaryConditionalOperator>(this)->getTrueExpr(); |
3873 | } |
3874 | |
3875 | inline Expr *AbstractConditionalOperator::getFalseExpr() const { |
3876 | if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this)) |
3877 | return co->getFalseExpr(); |
3878 | return cast<BinaryConditionalOperator>(this)->getFalseExpr(); |
3879 | } |
3880 | |
3881 | /// AddrLabelExpr - The GNU address of label extension, representing &&label. |
3882 | class AddrLabelExpr : public Expr { |
3883 | SourceLocation AmpAmpLoc, LabelLoc; |
3884 | LabelDecl *Label; |
3885 | public: |
3886 | AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, |
3887 | QualType t) |
3888 | : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, |
3889 | false), |
3890 | AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} |
3891 | |
3892 | /// Build an empty address of a label expression. |
3893 | explicit AddrLabelExpr(EmptyShell Empty) |
3894 | : Expr(AddrLabelExprClass, Empty) { } |
3895 | |
3896 | SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } |
3897 | void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } |
3898 | SourceLocation getLabelLoc() const { return LabelLoc; } |
3899 | void setLabelLoc(SourceLocation L) { LabelLoc = L; } |
3900 | |
3901 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AmpAmpLoc; } |
3902 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return LabelLoc; } |
3903 | |
3904 | LabelDecl *getLabel() const { return Label; } |
3905 | void setLabel(LabelDecl *L) { Label = L; } |
3906 | |
3907 | static bool classof(const Stmt *T) { |
3908 | return T->getStmtClass() == AddrLabelExprClass; |
3909 | } |
3910 | |
3911 | // Iterators |
3912 | child_range children() { |
3913 | return child_range(child_iterator(), child_iterator()); |
3914 | } |
3915 | const_child_range children() const { |
3916 | return const_child_range(const_child_iterator(), const_child_iterator()); |
3917 | } |
3918 | }; |
3919 | |
3920 | /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). |
3921 | /// The StmtExpr contains a single CompoundStmt node, which it evaluates and |
3922 | /// takes the value of the last subexpression. |
3923 | /// |
3924 | /// A StmtExpr is always an r-value; values "returned" out of a |
3925 | /// StmtExpr will be copied. |
3926 | class StmtExpr : public Expr { |
3927 | Stmt *SubStmt; |
3928 | SourceLocation LParenLoc, RParenLoc; |
3929 | public: |
3930 | // FIXME: Does type-dependence need to be computed differently? |
3931 | // FIXME: Do we need to compute instantiation instantiation-dependence for |
3932 | // statements? (ugh!) |
3933 | StmtExpr(CompoundStmt *substmt, QualType T, |
3934 | SourceLocation lp, SourceLocation rp) : |
3935 | Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, |
3936 | T->isDependentType(), false, false, false), |
3937 | SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } |
3938 | |
3939 | /// Build an empty statement expression. |
3940 | explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } |
3941 | |
3942 | CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); } |
3943 | const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); } |
3944 | void setSubStmt(CompoundStmt *S) { SubStmt = S; } |
3945 | |
3946 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; } |
3947 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
3948 | |
3949 | SourceLocation getLParenLoc() const { return LParenLoc; } |
3950 | void setLParenLoc(SourceLocation L) { LParenLoc = L; } |
3951 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3952 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3953 | |
3954 | static bool classof(const Stmt *T) { |
3955 | return T->getStmtClass() == StmtExprClass; |
3956 | } |
3957 | |
3958 | // Iterators |
3959 | child_range children() { return child_range(&SubStmt, &SubStmt+1); } |
3960 | const_child_range children() const { |
3961 | return const_child_range(&SubStmt, &SubStmt + 1); |
3962 | } |
3963 | }; |
3964 | |
3965 | /// ShuffleVectorExpr - clang-specific builtin-in function |
3966 | /// __builtin_shufflevector. |
3967 | /// This AST node represents a operator that does a constant |
3968 | /// shuffle, similar to LLVM's shufflevector instruction. It takes |
3969 | /// two vectors and a variable number of constant indices, |
3970 | /// and returns the appropriately shuffled vector. |
3971 | class ShuffleVectorExpr : public Expr { |
3972 | SourceLocation BuiltinLoc, RParenLoc; |
3973 | |
3974 | // SubExprs - the list of values passed to the __builtin_shufflevector |
3975 | // function. The first two are vectors, and the rest are constant |
3976 | // indices. The number of values in this list is always |
3977 | // 2+the number of indices in the vector type. |
3978 | Stmt **SubExprs; |
3979 | unsigned NumExprs; |
3980 | |
3981 | public: |
3982 | ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, |
3983 | SourceLocation BLoc, SourceLocation RP); |
3984 | |
3985 | /// Build an empty vector-shuffle expression. |
3986 | explicit ShuffleVectorExpr(EmptyShell Empty) |
3987 | : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } |
3988 | |
3989 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
3990 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
3991 | |
3992 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3993 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3994 | |
3995 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
3996 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
3997 | |
3998 | static bool classof(const Stmt *T) { |
3999 | return T->getStmtClass() == ShuffleVectorExprClass; |
4000 | } |
4001 | |
4002 | /// getNumSubExprs - Return the size of the SubExprs array. This includes the |
4003 | /// constant expression, the actual arguments passed in, and the function |
4004 | /// pointers. |
4005 | unsigned getNumSubExprs() const { return NumExprs; } |
4006 | |
4007 | /// Retrieve the array of expressions. |
4008 | Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } |
4009 | |
4010 | /// getExpr - Return the Expr at the specified index. |
4011 | Expr *getExpr(unsigned Index) { |
4012 | assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4012, __PRETTY_FUNCTION__)); |
4013 | return cast<Expr>(SubExprs[Index]); |
4014 | } |
4015 | const Expr *getExpr(unsigned Index) const { |
4016 | assert((Index < NumExprs) && "Arg access out of range!")(((Index < NumExprs) && "Arg access out of range!" ) ? static_cast<void> (0) : __assert_fail ("(Index < NumExprs) && \"Arg access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4016, __PRETTY_FUNCTION__)); |
4017 | return cast<Expr>(SubExprs[Index]); |
4018 | } |
4019 | |
4020 | void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs); |
4021 | |
4022 | llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { |
4023 | assert((N < NumExprs - 2) && "Shuffle idx out of range!")(((N < NumExprs - 2) && "Shuffle idx out of range!" ) ? static_cast<void> (0) : __assert_fail ("(N < NumExprs - 2) && \"Shuffle idx out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4023, __PRETTY_FUNCTION__)); |
4024 | return getExpr(N+2)->EvaluateKnownConstInt(Ctx); |
4025 | } |
4026 | |
4027 | // Iterators |
4028 | child_range children() { |
4029 | return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); |
4030 | } |
4031 | const_child_range children() const { |
4032 | return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); |
4033 | } |
4034 | }; |
4035 | |
4036 | /// ConvertVectorExpr - Clang builtin function __builtin_convertvector |
4037 | /// This AST node provides support for converting a vector type to another |
4038 | /// vector type of the same arity. |
4039 | class ConvertVectorExpr : public Expr { |
4040 | private: |
4041 | Stmt *SrcExpr; |
4042 | TypeSourceInfo *TInfo; |
4043 | SourceLocation BuiltinLoc, RParenLoc; |
4044 | |
4045 | friend class ASTReader; |
4046 | friend class ASTStmtReader; |
4047 | explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} |
4048 | |
4049 | public: |
4050 | ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType, |
4051 | ExprValueKind VK, ExprObjectKind OK, |
4052 | SourceLocation BuiltinLoc, SourceLocation RParenLoc) |
4053 | : Expr(ConvertVectorExprClass, DstType, VK, OK, |
4054 | DstType->isDependentType(), |
4055 | DstType->isDependentType() || SrcExpr->isValueDependent(), |
4056 | (DstType->isInstantiationDependentType() || |
4057 | SrcExpr->isInstantiationDependent()), |
4058 | (DstType->containsUnexpandedParameterPack() || |
4059 | SrcExpr->containsUnexpandedParameterPack())), |
4060 | SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} |
4061 | |
4062 | /// getSrcExpr - Return the Expr to be converted. |
4063 | Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } |
4064 | |
4065 | /// getTypeSourceInfo - Return the destination type. |
4066 | TypeSourceInfo *getTypeSourceInfo() const { |
4067 | return TInfo; |
4068 | } |
4069 | void setTypeSourceInfo(TypeSourceInfo *ti) { |
4070 | TInfo = ti; |
4071 | } |
4072 | |
4073 | /// getBuiltinLoc - Return the location of the __builtin_convertvector token. |
4074 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4075 | |
4076 | /// getRParenLoc - Return the location of final right parenthesis. |
4077 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4078 | |
4079 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4080 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4081 | |
4082 | static bool classof(const Stmt *T) { |
4083 | return T->getStmtClass() == ConvertVectorExprClass; |
4084 | } |
4085 | |
4086 | // Iterators |
4087 | child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } |
4088 | const_child_range children() const { |
4089 | return const_child_range(&SrcExpr, &SrcExpr + 1); |
4090 | } |
4091 | }; |
4092 | |
4093 | /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. |
4094 | /// This AST node is similar to the conditional operator (?:) in C, with |
4095 | /// the following exceptions: |
4096 | /// - the test expression must be a integer constant expression. |
4097 | /// - the expression returned acts like the chosen subexpression in every |
4098 | /// visible way: the type is the same as that of the chosen subexpression, |
4099 | /// and all predicates (whether it's an l-value, whether it's an integer |
4100 | /// constant expression, etc.) return the same result as for the chosen |
4101 | /// sub-expression. |
4102 | class ChooseExpr : public Expr { |
4103 | enum { COND, LHS, RHS, END_EXPR }; |
4104 | Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. |
4105 | SourceLocation BuiltinLoc, RParenLoc; |
4106 | bool CondIsTrue; |
4107 | public: |
4108 | ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, |
4109 | QualType t, ExprValueKind VK, ExprObjectKind OK, |
4110 | SourceLocation RP, bool condIsTrue, |
4111 | bool TypeDependent, bool ValueDependent) |
4112 | : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, |
4113 | (cond->isInstantiationDependent() || |
4114 | lhs->isInstantiationDependent() || |
4115 | rhs->isInstantiationDependent()), |
4116 | (cond->containsUnexpandedParameterPack() || |
4117 | lhs->containsUnexpandedParameterPack() || |
4118 | rhs->containsUnexpandedParameterPack())), |
4119 | BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) { |
4120 | SubExprs[COND] = cond; |
4121 | SubExprs[LHS] = lhs; |
4122 | SubExprs[RHS] = rhs; |
4123 | } |
4124 | |
4125 | /// Build an empty __builtin_choose_expr. |
4126 | explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } |
4127 | |
4128 | /// isConditionTrue - Return whether the condition is true (i.e. not |
4129 | /// equal to zero). |
4130 | bool isConditionTrue() const { |
4131 | assert(!isConditionDependent() &&((!isConditionDependent() && "Dependent condition isn't true or false" ) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4132, __PRETTY_FUNCTION__)) |
4132 | "Dependent condition isn't true or false")((!isConditionDependent() && "Dependent condition isn't true or false" ) ? static_cast<void> (0) : __assert_fail ("!isConditionDependent() && \"Dependent condition isn't true or false\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4132, __PRETTY_FUNCTION__)); |
4133 | return CondIsTrue; |
4134 | } |
4135 | void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } |
4136 | |
4137 | bool isConditionDependent() const { |
4138 | return getCond()->isTypeDependent() || getCond()->isValueDependent(); |
4139 | } |
4140 | |
4141 | /// getChosenSubExpr - Return the subexpression chosen according to the |
4142 | /// condition. |
4143 | Expr *getChosenSubExpr() const { |
4144 | return isConditionTrue() ? getLHS() : getRHS(); |
4145 | } |
4146 | |
4147 | Expr *getCond() const { return cast<Expr>(SubExprs[COND]); } |
4148 | void setCond(Expr *E) { SubExprs[COND] = E; } |
4149 | Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); } |
4150 | void setLHS(Expr *E) { SubExprs[LHS] = E; } |
4151 | Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); } |
4152 | void setRHS(Expr *E) { SubExprs[RHS] = E; } |
4153 | |
4154 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4155 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
4156 | |
4157 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4158 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4159 | |
4160 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4161 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4162 | |
4163 | static bool classof(const Stmt *T) { |
4164 | return T->getStmtClass() == ChooseExprClass; |
4165 | } |
4166 | |
4167 | // Iterators |
4168 | child_range children() { |
4169 | return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); |
4170 | } |
4171 | const_child_range children() const { |
4172 | return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); |
4173 | } |
4174 | }; |
4175 | |
4176 | /// GNUNullExpr - Implements the GNU __null extension, which is a name |
4177 | /// for a null pointer constant that has integral type (e.g., int or |
4178 | /// long) and is the same size and alignment as a pointer. The __null |
4179 | /// extension is typically only used by system headers, which define |
4180 | /// NULL as __null in C++ rather than using 0 (which is an integer |
4181 | /// that may not match the size of a pointer). |
4182 | class GNUNullExpr : public Expr { |
4183 | /// TokenLoc - The location of the __null keyword. |
4184 | SourceLocation TokenLoc; |
4185 | |
4186 | public: |
4187 | GNUNullExpr(QualType Ty, SourceLocation Loc) |
4188 | : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, |
4189 | false), |
4190 | TokenLoc(Loc) { } |
4191 | |
4192 | /// Build an empty GNU __null expression. |
4193 | explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } |
4194 | |
4195 | /// getTokenLocation - The location of the __null token. |
4196 | SourceLocation getTokenLocation() const { return TokenLoc; } |
4197 | void setTokenLocation(SourceLocation L) { TokenLoc = L; } |
4198 | |
4199 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; } |
4200 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return TokenLoc; } |
4201 | |
4202 | static bool classof(const Stmt *T) { |
4203 | return T->getStmtClass() == GNUNullExprClass; |
4204 | } |
4205 | |
4206 | // Iterators |
4207 | child_range children() { |
4208 | return child_range(child_iterator(), child_iterator()); |
4209 | } |
4210 | const_child_range children() const { |
4211 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4212 | } |
4213 | }; |
4214 | |
4215 | /// Represents a call to the builtin function \c __builtin_va_arg. |
4216 | class VAArgExpr : public Expr { |
4217 | Stmt *Val; |
4218 | llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo; |
4219 | SourceLocation BuiltinLoc, RParenLoc; |
4220 | public: |
4221 | VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, |
4222 | SourceLocation RPLoc, QualType t, bool IsMS) |
4223 | : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(), |
4224 | false, (TInfo->getType()->isInstantiationDependentType() || |
4225 | e->isInstantiationDependent()), |
4226 | (TInfo->getType()->containsUnexpandedParameterPack() || |
4227 | e->containsUnexpandedParameterPack())), |
4228 | Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {} |
4229 | |
4230 | /// Create an empty __builtin_va_arg expression. |
4231 | explicit VAArgExpr(EmptyShell Empty) |
4232 | : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} |
4233 | |
4234 | const Expr *getSubExpr() const { return cast<Expr>(Val); } |
4235 | Expr *getSubExpr() { return cast<Expr>(Val); } |
4236 | void setSubExpr(Expr *E) { Val = E; } |
4237 | |
4238 | /// Returns whether this is really a Win64 ABI va_arg expression. |
4239 | bool isMicrosoftABI() const { return TInfo.getInt(); } |
4240 | void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } |
4241 | |
4242 | TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } |
4243 | void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } |
4244 | |
4245 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
4246 | void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } |
4247 | |
4248 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4249 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4250 | |
4251 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
4252 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
4253 | |
4254 | static bool classof(const Stmt *T) { |
4255 | return T->getStmtClass() == VAArgExprClass; |
4256 | } |
4257 | |
4258 | // Iterators |
4259 | child_range children() { return child_range(&Val, &Val+1); } |
4260 | const_child_range children() const { |
4261 | return const_child_range(&Val, &Val + 1); |
4262 | } |
4263 | }; |
4264 | |
4265 | /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), |
4266 | /// __builtin_FUNCTION(), or __builtin_FILE(). |
4267 | class SourceLocExpr final : public Expr { |
4268 | SourceLocation BuiltinLoc, RParenLoc; |
4269 | DeclContext *ParentContext; |
4270 | |
4271 | public: |
4272 | enum IdentKind { Function, File, Line, Column }; |
4273 | |
4274 | SourceLocExpr(const ASTContext &Ctx, IdentKind Type, SourceLocation BLoc, |
4275 | SourceLocation RParenLoc, DeclContext *Context); |
4276 | |
4277 | /// Build an empty call expression. |
4278 | explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {} |
4279 | |
4280 | /// Return the result of evaluating this SourceLocExpr in the specified |
4281 | /// (and possibly null) default argument or initialization context. |
4282 | APValue EvaluateInContext(const ASTContext &Ctx, |
4283 | const Expr *DefaultExpr) const; |
4284 | |
4285 | /// Return a string representing the name of the specific builtin function. |
4286 | StringRef getBuiltinStr() const; |
4287 | |
4288 | IdentKind getIdentKind() const { |
4289 | return static_cast<IdentKind>(SourceLocExprBits.Kind); |
4290 | } |
4291 | |
4292 | bool isStringType() const { |
4293 | switch (getIdentKind()) { |
4294 | case File: |
4295 | case Function: |
4296 | return true; |
4297 | case Line: |
4298 | case Column: |
4299 | return false; |
4300 | } |
4301 | llvm_unreachable("unknown source location expression kind")::llvm::llvm_unreachable_internal("unknown source location expression kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4301); |
4302 | } |
4303 | bool isIntType() const LLVM_READONLY__attribute__((__pure__)) { return !isStringType(); } |
4304 | |
4305 | /// If the SourceLocExpr has been resolved return the subexpression |
4306 | /// representing the resolved value. Otherwise return null. |
4307 | const DeclContext *getParentContext() const { return ParentContext; } |
4308 | DeclContext *getParentContext() { return ParentContext; } |
4309 | |
4310 | SourceLocation getLocation() const { return BuiltinLoc; } |
4311 | SourceLocation getBeginLoc() const { return BuiltinLoc; } |
4312 | SourceLocation getEndLoc() const { return RParenLoc; } |
4313 | |
4314 | child_range children() { |
4315 | return child_range(child_iterator(), child_iterator()); |
4316 | } |
4317 | |
4318 | const_child_range children() const { |
4319 | return const_child_range(child_iterator(), child_iterator()); |
4320 | } |
4321 | |
4322 | static bool classof(const Stmt *T) { |
4323 | return T->getStmtClass() == SourceLocExprClass; |
4324 | } |
4325 | |
4326 | private: |
4327 | friend class ASTStmtReader; |
4328 | }; |
4329 | |
4330 | /// Describes an C or C++ initializer list. |
4331 | /// |
4332 | /// InitListExpr describes an initializer list, which can be used to |
4333 | /// initialize objects of different types, including |
4334 | /// struct/class/union types, arrays, and vectors. For example: |
4335 | /// |
4336 | /// @code |
4337 | /// struct foo x = { 1, { 2, 3 } }; |
4338 | /// @endcode |
4339 | /// |
4340 | /// Prior to semantic analysis, an initializer list will represent the |
4341 | /// initializer list as written by the user, but will have the |
4342 | /// placeholder type "void". This initializer list is called the |
4343 | /// syntactic form of the initializer, and may contain C99 designated |
4344 | /// initializers (represented as DesignatedInitExprs), initializations |
4345 | /// of subobject members without explicit braces, and so on. Clients |
4346 | /// interested in the original syntax of the initializer list should |
4347 | /// use the syntactic form of the initializer list. |
4348 | /// |
4349 | /// After semantic analysis, the initializer list will represent the |
4350 | /// semantic form of the initializer, where the initializations of all |
4351 | /// subobjects are made explicit with nested InitListExpr nodes and |
4352 | /// C99 designators have been eliminated by placing the designated |
4353 | /// initializations into the subobject they initialize. Additionally, |
4354 | /// any "holes" in the initialization, where no initializer has been |
4355 | /// specified for a particular subobject, will be replaced with |
4356 | /// implicitly-generated ImplicitValueInitExpr expressions that |
4357 | /// value-initialize the subobjects. Note, however, that the |
4358 | /// initializer lists may still have fewer initializers than there are |
4359 | /// elements to initialize within the object. |
4360 | /// |
4361 | /// After semantic analysis has completed, given an initializer list, |
4362 | /// method isSemanticForm() returns true if and only if this is the |
4363 | /// semantic form of the initializer list (note: the same AST node |
4364 | /// may at the same time be the syntactic form). |
4365 | /// Given the semantic form of the initializer list, one can retrieve |
4366 | /// the syntactic form of that initializer list (when different) |
4367 | /// using method getSyntacticForm(); the method returns null if applied |
4368 | /// to a initializer list which is already in syntactic form. |
4369 | /// Similarly, given the syntactic form (i.e., an initializer list such |
4370 | /// that isSemanticForm() returns false), one can retrieve the semantic |
4371 | /// form using method getSemanticForm(). |
4372 | /// Since many initializer lists have the same syntactic and semantic forms, |
4373 | /// getSyntacticForm() may return NULL, indicating that the current |
4374 | /// semantic initializer list also serves as its syntactic form. |
4375 | class InitListExpr : public Expr { |
4376 | // FIXME: Eliminate this vector in favor of ASTContext allocation |
4377 | typedef ASTVector<Stmt *> InitExprsTy; |
4378 | InitExprsTy InitExprs; |
4379 | SourceLocation LBraceLoc, RBraceLoc; |
4380 | |
4381 | /// The alternative form of the initializer list (if it exists). |
4382 | /// The int part of the pair stores whether this initializer list is |
4383 | /// in semantic form. If not null, the pointer points to: |
4384 | /// - the syntactic form, if this is in semantic form; |
4385 | /// - the semantic form, if this is in syntactic form. |
4386 | llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm; |
4387 | |
4388 | /// Either: |
4389 | /// If this initializer list initializes an array with more elements than |
4390 | /// there are initializers in the list, specifies an expression to be used |
4391 | /// for value initialization of the rest of the elements. |
4392 | /// Or |
4393 | /// If this initializer list initializes a union, specifies which |
4394 | /// field within the union will be initialized. |
4395 | llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit; |
4396 | |
4397 | public: |
4398 | InitListExpr(const ASTContext &C, SourceLocation lbraceloc, |
4399 | ArrayRef<Expr*> initExprs, SourceLocation rbraceloc); |
4400 | |
4401 | /// Build an empty initializer list. |
4402 | explicit InitListExpr(EmptyShell Empty) |
4403 | : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } |
4404 | |
4405 | unsigned getNumInits() const { return InitExprs.size(); } |
4406 | |
4407 | /// Retrieve the set of initializers. |
4408 | Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); } |
4409 | |
4410 | /// Retrieve the set of initializers. |
4411 | Expr * const *getInits() const { |
4412 | return reinterpret_cast<Expr * const *>(InitExprs.data()); |
4413 | } |
4414 | |
4415 | ArrayRef<Expr *> inits() { |
4416 | return llvm::makeArrayRef(getInits(), getNumInits()); |
4417 | } |
4418 | |
4419 | ArrayRef<Expr *> inits() const { |
4420 | return llvm::makeArrayRef(getInits(), getNumInits()); |
4421 | } |
4422 | |
4423 | const Expr *getInit(unsigned Init) const { |
4424 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4424, __PRETTY_FUNCTION__)); |
4425 | return cast_or_null<Expr>(InitExprs[Init]); |
4426 | } |
4427 | |
4428 | Expr *getInit(unsigned Init) { |
4429 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4429, __PRETTY_FUNCTION__)); |
4430 | return cast_or_null<Expr>(InitExprs[Init]); |
4431 | } |
4432 | |
4433 | void setInit(unsigned Init, Expr *expr) { |
4434 | assert(Init < getNumInits() && "Initializer access out of range!")((Init < getNumInits() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumInits() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4434, __PRETTY_FUNCTION__)); |
4435 | InitExprs[Init] = expr; |
4436 | |
4437 | if (expr) { |
4438 | ExprBits.TypeDependent |= expr->isTypeDependent(); |
4439 | ExprBits.ValueDependent |= expr->isValueDependent(); |
4440 | ExprBits.InstantiationDependent |= expr->isInstantiationDependent(); |
4441 | ExprBits.ContainsUnexpandedParameterPack |= |
4442 | expr->containsUnexpandedParameterPack(); |
4443 | } |
4444 | } |
4445 | |
4446 | /// Reserve space for some number of initializers. |
4447 | void reserveInits(const ASTContext &C, unsigned NumInits); |
4448 | |
4449 | /// Specify the number of initializers |
4450 | /// |
4451 | /// If there are more than @p NumInits initializers, the remaining |
4452 | /// initializers will be destroyed. If there are fewer than @p |
4453 | /// NumInits initializers, NULL expressions will be added for the |
4454 | /// unknown initializers. |
4455 | void resizeInits(const ASTContext &Context, unsigned NumInits); |
4456 | |
4457 | /// Updates the initializer at index @p Init with the new |
4458 | /// expression @p expr, and returns the old expression at that |
4459 | /// location. |
4460 | /// |
4461 | /// When @p Init is out of range for this initializer list, the |
4462 | /// initializer list will be extended with NULL expressions to |
4463 | /// accommodate the new entry. |
4464 | Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); |
4465 | |
4466 | /// If this initializer list initializes an array with more elements |
4467 | /// than there are initializers in the list, specifies an expression to be |
4468 | /// used for value initialization of the rest of the elements. |
4469 | Expr *getArrayFiller() { |
4470 | return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>(); |
4471 | } |
4472 | const Expr *getArrayFiller() const { |
4473 | return const_cast<InitListExpr *>(this)->getArrayFiller(); |
4474 | } |
4475 | void setArrayFiller(Expr *filler); |
4476 | |
4477 | /// Return true if this is an array initializer and its array "filler" |
4478 | /// has been set. |
4479 | bool hasArrayFiller() const { return getArrayFiller(); } |
4480 | |
4481 | /// If this initializes a union, specifies which field in the |
4482 | /// union to initialize. |
4483 | /// |
4484 | /// Typically, this field is the first named field within the |
4485 | /// union. However, a designated initializer can specify the |
4486 | /// initialization of a different field within the union. |
4487 | FieldDecl *getInitializedFieldInUnion() { |
4488 | return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>(); |
4489 | } |
4490 | const FieldDecl *getInitializedFieldInUnion() const { |
4491 | return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion(); |
4492 | } |
4493 | void setInitializedFieldInUnion(FieldDecl *FD) { |
4494 | assert((FD == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4495 | || getInitializedFieldInUnion() == nullptr(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4496 | || getInitializedFieldInUnion() == FD)(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)) |
4497 | && "Only one field of a union may be initialized at a time!")(((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!" ) ? static_cast<void> (0) : __assert_fail ("(FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && \"Only one field of a union may be initialized at a time!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4497, __PRETTY_FUNCTION__)); |
4498 | ArrayFillerOrUnionFieldInit = FD; |
4499 | } |
4500 | |
4501 | // Explicit InitListExpr's originate from source code (and have valid source |
4502 | // locations). Implicit InitListExpr's are created by the semantic analyzer. |
4503 | // FIXME: This is wrong; InitListExprs created by semantic analysis have |
4504 | // valid source locations too! |
4505 | bool isExplicit() const { |
4506 | return LBraceLoc.isValid() && RBraceLoc.isValid(); |
4507 | } |
4508 | |
4509 | // Is this an initializer for an array of characters, initialized by a string |
4510 | // literal or an @encode? |
4511 | bool isStringLiteralInit() const; |
4512 | |
4513 | /// Is this a transparent initializer list (that is, an InitListExpr that is |
4514 | /// purely syntactic, and whose semantics are that of the sole contained |
4515 | /// initializer)? |
4516 | bool isTransparent() const; |
4517 | |
4518 | /// Is this the zero initializer {0} in a language which considers it |
4519 | /// idiomatic? |
4520 | bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; |
4521 | |
4522 | SourceLocation getLBraceLoc() const { return LBraceLoc; } |
4523 | void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } |
4524 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4525 | void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } |
4526 | |
4527 | bool isSemanticForm() const { return AltForm.getInt(); } |
4528 | InitListExpr *getSemanticForm() const { |
4529 | return isSemanticForm() ? nullptr : AltForm.getPointer(); |
4530 | } |
4531 | bool isSyntacticForm() const { |
4532 | return !AltForm.getInt() || !AltForm.getPointer(); |
4533 | } |
4534 | InitListExpr *getSyntacticForm() const { |
4535 | return isSemanticForm() ? AltForm.getPointer() : nullptr; |
4536 | } |
4537 | |
4538 | void setSyntacticForm(InitListExpr *Init) { |
4539 | AltForm.setPointer(Init); |
4540 | AltForm.setInt(true); |
4541 | Init->AltForm.setPointer(this); |
4542 | Init->AltForm.setInt(false); |
4543 | } |
4544 | |
4545 | bool hadArrayRangeDesignator() const { |
4546 | return InitListExprBits.HadArrayRangeDesignator != 0; |
4547 | } |
4548 | void sawArrayRangeDesignator(bool ARD = true) { |
4549 | InitListExprBits.HadArrayRangeDesignator = ARD; |
4550 | } |
4551 | |
4552 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4553 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4554 | |
4555 | static bool classof(const Stmt *T) { |
4556 | return T->getStmtClass() == InitListExprClass; |
4557 | } |
4558 | |
4559 | // Iterators |
4560 | child_range children() { |
4561 | const_child_range CCR = const_cast<const InitListExpr *>(this)->children(); |
4562 | return child_range(cast_away_const(CCR.begin()), |
4563 | cast_away_const(CCR.end())); |
4564 | } |
4565 | |
4566 | const_child_range children() const { |
4567 | // FIXME: This does not include the array filler expression. |
4568 | if (InitExprs.empty()) |
4569 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4570 | return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); |
4571 | } |
4572 | |
4573 | typedef InitExprsTy::iterator iterator; |
4574 | typedef InitExprsTy::const_iterator const_iterator; |
4575 | typedef InitExprsTy::reverse_iterator reverse_iterator; |
4576 | typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; |
4577 | |
4578 | iterator begin() { return InitExprs.begin(); } |
4579 | const_iterator begin() const { return InitExprs.begin(); } |
4580 | iterator end() { return InitExprs.end(); } |
4581 | const_iterator end() const { return InitExprs.end(); } |
4582 | reverse_iterator rbegin() { return InitExprs.rbegin(); } |
4583 | const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } |
4584 | reverse_iterator rend() { return InitExprs.rend(); } |
4585 | const_reverse_iterator rend() const { return InitExprs.rend(); } |
4586 | |
4587 | friend class ASTStmtReader; |
4588 | friend class ASTStmtWriter; |
4589 | }; |
4590 | |
4591 | /// Represents a C99 designated initializer expression. |
4592 | /// |
4593 | /// A designated initializer expression (C99 6.7.8) contains one or |
4594 | /// more designators (which can be field designators, array |
4595 | /// designators, or GNU array-range designators) followed by an |
4596 | /// expression that initializes the field or element(s) that the |
4597 | /// designators refer to. For example, given: |
4598 | /// |
4599 | /// @code |
4600 | /// struct point { |
4601 | /// double x; |
4602 | /// double y; |
4603 | /// }; |
4604 | /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; |
4605 | /// @endcode |
4606 | /// |
4607 | /// The InitListExpr contains three DesignatedInitExprs, the first of |
4608 | /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two |
4609 | /// designators, one array designator for @c [2] followed by one field |
4610 | /// designator for @c .y. The initialization expression will be 1.0. |
4611 | class DesignatedInitExpr final |
4612 | : public Expr, |
4613 | private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> { |
4614 | public: |
4615 | /// Forward declaration of the Designator class. |
4616 | class Designator; |
4617 | |
4618 | private: |
4619 | /// The location of the '=' or ':' prior to the actual initializer |
4620 | /// expression. |
4621 | SourceLocation EqualOrColonLoc; |
4622 | |
4623 | /// Whether this designated initializer used the GNU deprecated |
4624 | /// syntax rather than the C99 '=' syntax. |
4625 | unsigned GNUSyntax : 1; |
4626 | |
4627 | /// The number of designators in this initializer expression. |
4628 | unsigned NumDesignators : 15; |
4629 | |
4630 | /// The number of subexpressions of this initializer expression, |
4631 | /// which contains both the initializer and any additional |
4632 | /// expressions used by array and array-range designators. |
4633 | unsigned NumSubExprs : 16; |
4634 | |
4635 | /// The designators in this designated initialization |
4636 | /// expression. |
4637 | Designator *Designators; |
4638 | |
4639 | DesignatedInitExpr(const ASTContext &C, QualType Ty, |
4640 | llvm::ArrayRef<Designator> Designators, |
4641 | SourceLocation EqualOrColonLoc, bool GNUSyntax, |
4642 | ArrayRef<Expr *> IndexExprs, Expr *Init); |
4643 | |
4644 | explicit DesignatedInitExpr(unsigned NumSubExprs) |
4645 | : Expr(DesignatedInitExprClass, EmptyShell()), |
4646 | NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } |
4647 | |
4648 | public: |
4649 | /// A field designator, e.g., ".x". |
4650 | struct FieldDesignator { |
4651 | /// Refers to the field that is being initialized. The low bit |
4652 | /// of this field determines whether this is actually a pointer |
4653 | /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When |
4654 | /// initially constructed, a field designator will store an |
4655 | /// IdentifierInfo*. After semantic analysis has resolved that |
4656 | /// name, the field designator will instead store a FieldDecl*. |
4657 | uintptr_t NameOrField; |
4658 | |
4659 | /// The location of the '.' in the designated initializer. |
4660 | unsigned DotLoc; |
4661 | |
4662 | /// The location of the field name in the designated initializer. |
4663 | unsigned FieldLoc; |
4664 | }; |
4665 | |
4666 | /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". |
4667 | struct ArrayOrRangeDesignator { |
4668 | /// Location of the first index expression within the designated |
4669 | /// initializer expression's list of subexpressions. |
4670 | unsigned Index; |
4671 | /// The location of the '[' starting the array range designator. |
4672 | unsigned LBracketLoc; |
4673 | /// The location of the ellipsis separating the start and end |
4674 | /// indices. Only valid for GNU array-range designators. |
4675 | unsigned EllipsisLoc; |
4676 | /// The location of the ']' terminating the array range designator. |
4677 | unsigned RBracketLoc; |
4678 | }; |
4679 | |
4680 | /// Represents a single C99 designator. |
4681 | /// |
4682 | /// @todo This class is infuriatingly similar to clang::Designator, |
4683 | /// but minor differences (storing indices vs. storing pointers) |
4684 | /// keep us from reusing it. Try harder, later, to rectify these |
4685 | /// differences. |
4686 | class Designator { |
4687 | /// The kind of designator this describes. |
4688 | enum { |
4689 | FieldDesignator, |
4690 | ArrayDesignator, |
4691 | ArrayRangeDesignator |
4692 | } Kind; |
4693 | |
4694 | union { |
4695 | /// A field designator, e.g., ".x". |
4696 | struct FieldDesignator Field; |
4697 | /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". |
4698 | struct ArrayOrRangeDesignator ArrayOrRange; |
4699 | }; |
4700 | friend class DesignatedInitExpr; |
4701 | |
4702 | public: |
4703 | Designator() {} |
4704 | |
4705 | /// Initializes a field designator. |
4706 | Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, |
4707 | SourceLocation FieldLoc) |
4708 | : Kind(FieldDesignator) { |
4709 | Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01; |
4710 | Field.DotLoc = DotLoc.getRawEncoding(); |
4711 | Field.FieldLoc = FieldLoc.getRawEncoding(); |
4712 | } |
4713 | |
4714 | /// Initializes an array designator. |
4715 | Designator(unsigned Index, SourceLocation LBracketLoc, |
4716 | SourceLocation RBracketLoc) |
4717 | : Kind(ArrayDesignator) { |
4718 | ArrayOrRange.Index = Index; |
4719 | ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); |
4720 | ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); |
4721 | ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); |
4722 | } |
4723 | |
4724 | /// Initializes a GNU array-range designator. |
4725 | Designator(unsigned Index, SourceLocation LBracketLoc, |
4726 | SourceLocation EllipsisLoc, SourceLocation RBracketLoc) |
4727 | : Kind(ArrayRangeDesignator) { |
4728 | ArrayOrRange.Index = Index; |
4729 | ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); |
4730 | ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); |
4731 | ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); |
4732 | } |
4733 | |
4734 | bool isFieldDesignator() const { return Kind == FieldDesignator; } |
4735 | bool isArrayDesignator() const { return Kind == ArrayDesignator; } |
4736 | bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } |
4737 | |
4738 | IdentifierInfo *getFieldName() const; |
4739 | |
4740 | FieldDecl *getField() const { |
4741 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4741, __PRETTY_FUNCTION__)); |
4742 | if (Field.NameOrField & 0x01) |
4743 | return nullptr; |
4744 | else |
4745 | return reinterpret_cast<FieldDecl *>(Field.NameOrField); |
4746 | } |
4747 | |
4748 | void setField(FieldDecl *FD) { |
4749 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4749, __PRETTY_FUNCTION__)); |
4750 | Field.NameOrField = reinterpret_cast<uintptr_t>(FD); |
4751 | } |
4752 | |
4753 | SourceLocation getDotLoc() const { |
4754 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4754, __PRETTY_FUNCTION__)); |
4755 | return SourceLocation::getFromRawEncoding(Field.DotLoc); |
4756 | } |
4757 | |
4758 | SourceLocation getFieldLoc() const { |
4759 | assert(Kind == FieldDesignator && "Only valid on a field designator")((Kind == FieldDesignator && "Only valid on a field designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == FieldDesignator && \"Only valid on a field designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4759, __PRETTY_FUNCTION__)); |
4760 | return SourceLocation::getFromRawEncoding(Field.FieldLoc); |
4761 | } |
4762 | |
4763 | SourceLocation getLBracketLoc() const { |
4764 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4765, __PRETTY_FUNCTION__)) |
4765 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4765, __PRETTY_FUNCTION__)); |
4766 | return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); |
4767 | } |
4768 | |
4769 | SourceLocation getRBracketLoc() const { |
4770 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4771, __PRETTY_FUNCTION__)) |
4771 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4771, __PRETTY_FUNCTION__)); |
4772 | return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); |
4773 | } |
4774 | |
4775 | SourceLocation getEllipsisLoc() const { |
4776 | assert(Kind == ArrayRangeDesignator &&((Kind == ArrayRangeDesignator && "Only valid on an array-range designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4777, __PRETTY_FUNCTION__)) |
4777 | "Only valid on an array-range designator")((Kind == ArrayRangeDesignator && "Only valid on an array-range designator" ) ? static_cast<void> (0) : __assert_fail ("Kind == ArrayRangeDesignator && \"Only valid on an array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4777, __PRETTY_FUNCTION__)); |
4778 | return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); |
4779 | } |
4780 | |
4781 | unsigned getFirstExprIndex() const { |
4782 | assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4783, __PRETTY_FUNCTION__)) |
4783 | "Only valid on an array or array-range designator")(((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator") ? static_cast <void> (0) : __assert_fail ("(Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && \"Only valid on an array or array-range designator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4783, __PRETTY_FUNCTION__)); |
4784 | return ArrayOrRange.Index; |
4785 | } |
4786 | |
4787 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4788 | if (Kind == FieldDesignator) |
4789 | return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); |
4790 | else |
4791 | return getLBracketLoc(); |
4792 | } |
4793 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4794 | return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); |
4795 | } |
4796 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
4797 | return SourceRange(getBeginLoc(), getEndLoc()); |
4798 | } |
4799 | }; |
4800 | |
4801 | static DesignatedInitExpr *Create(const ASTContext &C, |
4802 | llvm::ArrayRef<Designator> Designators, |
4803 | ArrayRef<Expr*> IndexExprs, |
4804 | SourceLocation EqualOrColonLoc, |
4805 | bool GNUSyntax, Expr *Init); |
4806 | |
4807 | static DesignatedInitExpr *CreateEmpty(const ASTContext &C, |
4808 | unsigned NumIndexExprs); |
4809 | |
4810 | /// Returns the number of designators in this initializer. |
4811 | unsigned size() const { return NumDesignators; } |
4812 | |
4813 | // Iterator access to the designators. |
4814 | llvm::MutableArrayRef<Designator> designators() { |
4815 | return {Designators, NumDesignators}; |
4816 | } |
4817 | |
4818 | llvm::ArrayRef<Designator> designators() const { |
4819 | return {Designators, NumDesignators}; |
4820 | } |
4821 | |
4822 | Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } |
4823 | const Designator *getDesignator(unsigned Idx) const { |
4824 | return &designators()[Idx]; |
4825 | } |
4826 | |
4827 | void setDesignators(const ASTContext &C, const Designator *Desigs, |
4828 | unsigned NumDesigs); |
4829 | |
4830 | Expr *getArrayIndex(const Designator &D) const; |
4831 | Expr *getArrayRangeStart(const Designator &D) const; |
4832 | Expr *getArrayRangeEnd(const Designator &D) const; |
4833 | |
4834 | /// Retrieve the location of the '=' that precedes the |
4835 | /// initializer value itself, if present. |
4836 | SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } |
4837 | void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } |
4838 | |
4839 | /// Whether this designated initializer should result in direct-initialization |
4840 | /// of the designated subobject (eg, '{.foo{1, 2, 3}}'). |
4841 | bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); } |
4842 | |
4843 | /// Determines whether this designated initializer used the |
4844 | /// deprecated GNU syntax for designated initializers. |
4845 | bool usesGNUSyntax() const { return GNUSyntax; } |
4846 | void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } |
4847 | |
4848 | /// Retrieve the initializer value. |
4849 | Expr *getInit() const { |
4850 | return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin()); |
4851 | } |
4852 | |
4853 | void setInit(Expr *init) { |
4854 | *child_begin() = init; |
4855 | } |
4856 | |
4857 | /// Retrieve the total number of subexpressions in this |
4858 | /// designated initializer expression, including the actual |
4859 | /// initialized value and any expressions that occur within array |
4860 | /// and array-range designators. |
4861 | unsigned getNumSubExprs() const { return NumSubExprs; } |
4862 | |
4863 | Expr *getSubExpr(unsigned Idx) const { |
4864 | assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ? static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4864, __PRETTY_FUNCTION__)); |
4865 | return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]); |
4866 | } |
4867 | |
4868 | void setSubExpr(unsigned Idx, Expr *E) { |
4869 | assert(Idx < NumSubExprs && "Subscript out of range")((Idx < NumSubExprs && "Subscript out of range") ? static_cast<void> (0) : __assert_fail ("Idx < NumSubExprs && \"Subscript out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 4869, __PRETTY_FUNCTION__)); |
4870 | getTrailingObjects<Stmt *>()[Idx] = E; |
4871 | } |
4872 | |
4873 | /// Replaces the designator at index @p Idx with the series |
4874 | /// of designators in [First, Last). |
4875 | void ExpandDesignator(const ASTContext &C, unsigned Idx, |
4876 | const Designator *First, const Designator *Last); |
4877 | |
4878 | SourceRange getDesignatorsSourceRange() const; |
4879 | |
4880 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4881 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4882 | |
4883 | static bool classof(const Stmt *T) { |
4884 | return T->getStmtClass() == DesignatedInitExprClass; |
4885 | } |
4886 | |
4887 | // Iterators |
4888 | child_range children() { |
4889 | Stmt **begin = getTrailingObjects<Stmt *>(); |
4890 | return child_range(begin, begin + NumSubExprs); |
4891 | } |
4892 | const_child_range children() const { |
4893 | Stmt * const *begin = getTrailingObjects<Stmt *>(); |
4894 | return const_child_range(begin, begin + NumSubExprs); |
4895 | } |
4896 | |
4897 | friend TrailingObjects; |
4898 | }; |
4899 | |
4900 | /// Represents a place-holder for an object not to be initialized by |
4901 | /// anything. |
4902 | /// |
4903 | /// This only makes sense when it appears as part of an updater of a |
4904 | /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE |
4905 | /// initializes a big object, and the NoInitExpr's mark the spots within the |
4906 | /// big object not to be overwritten by the updater. |
4907 | /// |
4908 | /// \see DesignatedInitUpdateExpr |
4909 | class NoInitExpr : public Expr { |
4910 | public: |
4911 | explicit NoInitExpr(QualType ty) |
4912 | : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary, |
4913 | false, false, ty->isInstantiationDependentType(), false) { } |
4914 | |
4915 | explicit NoInitExpr(EmptyShell Empty) |
4916 | : Expr(NoInitExprClass, Empty) { } |
4917 | |
4918 | static bool classof(const Stmt *T) { |
4919 | return T->getStmtClass() == NoInitExprClass; |
4920 | } |
4921 | |
4922 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
4923 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
4924 | |
4925 | // Iterators |
4926 | child_range children() { |
4927 | return child_range(child_iterator(), child_iterator()); |
4928 | } |
4929 | const_child_range children() const { |
4930 | return const_child_range(const_child_iterator(), const_child_iterator()); |
4931 | } |
4932 | }; |
4933 | |
4934 | // In cases like: |
4935 | // struct Q { int a, b, c; }; |
4936 | // Q *getQ(); |
4937 | // void foo() { |
4938 | // struct A { Q q; } a = { *getQ(), .q.b = 3 }; |
4939 | // } |
4940 | // |
4941 | // We will have an InitListExpr for a, with type A, and then a |
4942 | // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE |
4943 | // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" |
4944 | // |
4945 | class DesignatedInitUpdateExpr : public Expr { |
4946 | // BaseAndUpdaterExprs[0] is the base expression; |
4947 | // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. |
4948 | Stmt *BaseAndUpdaterExprs[2]; |
4949 | |
4950 | public: |
4951 | DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, |
4952 | Expr *baseExprs, SourceLocation rBraceLoc); |
4953 | |
4954 | explicit DesignatedInitUpdateExpr(EmptyShell Empty) |
4955 | : Expr(DesignatedInitUpdateExprClass, Empty) { } |
4956 | |
4957 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)); |
4958 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)); |
4959 | |
4960 | static bool classof(const Stmt *T) { |
4961 | return T->getStmtClass() == DesignatedInitUpdateExprClass; |
4962 | } |
4963 | |
4964 | Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); } |
4965 | void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } |
4966 | |
4967 | InitListExpr *getUpdater() const { |
4968 | return cast<InitListExpr>(BaseAndUpdaterExprs[1]); |
4969 | } |
4970 | void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } |
4971 | |
4972 | // Iterators |
4973 | // children = the base and the updater |
4974 | child_range children() { |
4975 | return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); |
4976 | } |
4977 | const_child_range children() const { |
4978 | return const_child_range(&BaseAndUpdaterExprs[0], |
4979 | &BaseAndUpdaterExprs[0] + 2); |
4980 | } |
4981 | }; |
4982 | |
4983 | /// Represents a loop initializing the elements of an array. |
4984 | /// |
4985 | /// The need to initialize the elements of an array occurs in a number of |
4986 | /// contexts: |
4987 | /// |
4988 | /// * in the implicit copy/move constructor for a class with an array member |
4989 | /// * when a lambda-expression captures an array by value |
4990 | /// * when a decomposition declaration decomposes an array |
4991 | /// |
4992 | /// There are two subexpressions: a common expression (the source array) |
4993 | /// that is evaluated once up-front, and a per-element initializer that |
4994 | /// runs once for each array element. |
4995 | /// |
4996 | /// Within the per-element initializer, the common expression may be referenced |
4997 | /// via an OpaqueValueExpr, and the current index may be obtained via an |
4998 | /// ArrayInitIndexExpr. |
4999 | class ArrayInitLoopExpr : public Expr { |
5000 | Stmt *SubExprs[2]; |
5001 | |
5002 | explicit ArrayInitLoopExpr(EmptyShell Empty) |
5003 | : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} |
5004 | |
5005 | public: |
5006 | explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) |
5007 | : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false, |
5008 | CommonInit->isValueDependent() || ElementInit->isValueDependent(), |
5009 | T->isInstantiationDependentType(), |
5010 | CommonInit->containsUnexpandedParameterPack() || |
5011 | ElementInit->containsUnexpandedParameterPack()), |
5012 | SubExprs{CommonInit, ElementInit} {} |
5013 | |
5014 | /// Get the common subexpression shared by all initializations (the source |
5015 | /// array). |
5016 | OpaqueValueExpr *getCommonExpr() const { |
5017 | return cast<OpaqueValueExpr>(SubExprs[0]); |
5018 | } |
5019 | |
5020 | /// Get the initializer to use for each array element. |
5021 | Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); } |
5022 | |
5023 | llvm::APInt getArraySize() const { |
5024 | return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe()) |
5025 | ->getSize(); |
5026 | } |
5027 | |
5028 | static bool classof(const Stmt *S) { |
5029 | return S->getStmtClass() == ArrayInitLoopExprClass; |
5030 | } |
5031 | |
5032 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5033 | return getCommonExpr()->getBeginLoc(); |
5034 | } |
5035 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5036 | return getCommonExpr()->getEndLoc(); |
5037 | } |
5038 | |
5039 | child_range children() { |
5040 | return child_range(SubExprs, SubExprs + 2); |
5041 | } |
5042 | const_child_range children() const { |
5043 | return const_child_range(SubExprs, SubExprs + 2); |
5044 | } |
5045 | |
5046 | friend class ASTReader; |
5047 | friend class ASTStmtReader; |
5048 | friend class ASTStmtWriter; |
5049 | }; |
5050 | |
5051 | /// Represents the index of the current element of an array being |
5052 | /// initialized by an ArrayInitLoopExpr. This can only appear within the |
5053 | /// subexpression of an ArrayInitLoopExpr. |
5054 | class ArrayInitIndexExpr : public Expr { |
5055 | explicit ArrayInitIndexExpr(EmptyShell Empty) |
5056 | : Expr(ArrayInitIndexExprClass, Empty) {} |
5057 | |
5058 | public: |
5059 | explicit ArrayInitIndexExpr(QualType T) |
5060 | : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary, |
5061 | false, false, false, false) {} |
5062 | |
5063 | static bool classof(const Stmt *S) { |
5064 | return S->getStmtClass() == ArrayInitIndexExprClass; |
5065 | } |
5066 | |
5067 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5068 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5069 | |
5070 | child_range children() { |
5071 | return child_range(child_iterator(), child_iterator()); |
5072 | } |
5073 | const_child_range children() const { |
5074 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5075 | } |
5076 | |
5077 | friend class ASTReader; |
5078 | friend class ASTStmtReader; |
5079 | }; |
5080 | |
5081 | /// Represents an implicitly-generated value initialization of |
5082 | /// an object of a given type. |
5083 | /// |
5084 | /// Implicit value initializations occur within semantic initializer |
5085 | /// list expressions (InitListExpr) as placeholders for subobject |
5086 | /// initializations not explicitly specified by the user. |
5087 | /// |
5088 | /// \see InitListExpr |
5089 | class ImplicitValueInitExpr : public Expr { |
5090 | public: |
5091 | explicit ImplicitValueInitExpr(QualType ty) |
5092 | : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, |
5093 | false, false, ty->isInstantiationDependentType(), false) { } |
5094 | |
5095 | /// Construct an empty implicit value initialization. |
5096 | explicit ImplicitValueInitExpr(EmptyShell Empty) |
5097 | : Expr(ImplicitValueInitExprClass, Empty) { } |
5098 | |
5099 | static bool classof(const Stmt *T) { |
5100 | return T->getStmtClass() == ImplicitValueInitExprClass; |
5101 | } |
5102 | |
5103 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5104 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5105 | |
5106 | // Iterators |
5107 | child_range children() { |
5108 | return child_range(child_iterator(), child_iterator()); |
5109 | } |
5110 | const_child_range children() const { |
5111 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5112 | } |
5113 | }; |
5114 | |
5115 | class ParenListExpr final |
5116 | : public Expr, |
5117 | private llvm::TrailingObjects<ParenListExpr, Stmt *> { |
5118 | friend class ASTStmtReader; |
5119 | friend TrailingObjects; |
5120 | |
5121 | /// The location of the left and right parentheses. |
5122 | SourceLocation LParenLoc, RParenLoc; |
5123 | |
5124 | /// Build a paren list. |
5125 | ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs, |
5126 | SourceLocation RParenLoc); |
5127 | |
5128 | /// Build an empty paren list. |
5129 | ParenListExpr(EmptyShell Empty, unsigned NumExprs); |
5130 | |
5131 | public: |
5132 | /// Create a paren list. |
5133 | static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc, |
5134 | ArrayRef<Expr *> Exprs, |
5135 | SourceLocation RParenLoc); |
5136 | |
5137 | /// Create an empty paren list. |
5138 | static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs); |
5139 | |
5140 | /// Return the number of expressions in this paren list. |
5141 | unsigned getNumExprs() const { return ParenListExprBits.NumExprs; } |
5142 | |
5143 | Expr *getExpr(unsigned Init) { |
5144 | assert(Init < getNumExprs() && "Initializer access out of range!")((Init < getNumExprs() && "Initializer access out of range!" ) ? static_cast<void> (0) : __assert_fail ("Init < getNumExprs() && \"Initializer access out of range!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5144, __PRETTY_FUNCTION__)); |
5145 | return getExprs()[Init]; |
5146 | } |
5147 | |
5148 | const Expr *getExpr(unsigned Init) const { |
5149 | return const_cast<ParenListExpr *>(this)->getExpr(Init); |
5150 | } |
5151 | |
5152 | Expr **getExprs() { |
5153 | return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>()); |
5154 | } |
5155 | |
5156 | ArrayRef<Expr *> exprs() { |
5157 | return llvm::makeArrayRef(getExprs(), getNumExprs()); |
5158 | } |
5159 | |
5160 | SourceLocation getLParenLoc() const { return LParenLoc; } |
5161 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5162 | SourceLocation getBeginLoc() const { return getLParenLoc(); } |
5163 | SourceLocation getEndLoc() const { return getRParenLoc(); } |
5164 | |
5165 | static bool classof(const Stmt *T) { |
5166 | return T->getStmtClass() == ParenListExprClass; |
5167 | } |
5168 | |
5169 | // Iterators |
5170 | child_range children() { |
5171 | return child_range(getTrailingObjects<Stmt *>(), |
5172 | getTrailingObjects<Stmt *>() + getNumExprs()); |
5173 | } |
5174 | const_child_range children() const { |
5175 | return const_child_range(getTrailingObjects<Stmt *>(), |
5176 | getTrailingObjects<Stmt *>() + getNumExprs()); |
5177 | } |
5178 | }; |
5179 | |
5180 | /// Represents a C11 generic selection. |
5181 | /// |
5182 | /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling |
5183 | /// expression, followed by one or more generic associations. Each generic |
5184 | /// association specifies a type name and an expression, or "default" and an |
5185 | /// expression (in which case it is known as a default generic association). |
5186 | /// The type and value of the generic selection are identical to those of its |
5187 | /// result expression, which is defined as the expression in the generic |
5188 | /// association with a type name that is compatible with the type of the |
5189 | /// controlling expression, or the expression in the default generic association |
5190 | /// if no types are compatible. For example: |
5191 | /// |
5192 | /// @code |
5193 | /// _Generic(X, double: 1, float: 2, default: 3) |
5194 | /// @endcode |
5195 | /// |
5196 | /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f |
5197 | /// or 3 if "hello". |
5198 | /// |
5199 | /// As an extension, generic selections are allowed in C++, where the following |
5200 | /// additional semantics apply: |
5201 | /// |
5202 | /// Any generic selection whose controlling expression is type-dependent or |
5203 | /// which names a dependent type in its association list is result-dependent, |
5204 | /// which means that the choice of result expression is dependent. |
5205 | /// Result-dependent generic associations are both type- and value-dependent. |
5206 | class GenericSelectionExpr final |
5207 | : public Expr, |
5208 | private llvm::TrailingObjects<GenericSelectionExpr, Stmt *, |
5209 | TypeSourceInfo *> { |
5210 | friend class ASTStmtReader; |
5211 | friend class ASTStmtWriter; |
5212 | friend TrailingObjects; |
5213 | |
5214 | /// The number of association expressions and the index of the result |
5215 | /// expression in the case where the generic selection expression is not |
5216 | /// result-dependent. The result index is equal to ResultDependentIndex |
5217 | /// if and only if the generic selection expression is result-dependent. |
5218 | unsigned NumAssocs, ResultIndex; |
5219 | enum : unsigned { |
5220 | ResultDependentIndex = std::numeric_limits<unsigned>::max(), |
5221 | ControllingIndex = 0, |
5222 | AssocExprStartIndex = 1 |
5223 | }; |
5224 | |
5225 | /// The location of the "default" and of the right parenthesis. |
5226 | SourceLocation DefaultLoc, RParenLoc; |
5227 | |
5228 | // GenericSelectionExpr is followed by several trailing objects. |
5229 | // They are (in order): |
5230 | // |
5231 | // * A single Stmt * for the controlling expression. |
5232 | // * An array of getNumAssocs() Stmt * for the association expressions. |
5233 | // * An array of getNumAssocs() TypeSourceInfo *, one for each of the |
5234 | // association expressions. |
5235 | unsigned numTrailingObjects(OverloadToken<Stmt *>) const { |
5236 | // Add one to account for the controlling expression; the remainder |
5237 | // are the associated expressions. |
5238 | return 1 + getNumAssocs(); |
5239 | } |
5240 | |
5241 | unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const { |
5242 | return getNumAssocs(); |
5243 | } |
5244 | |
5245 | template <bool Const> class AssociationIteratorTy; |
5246 | /// Bundle together an association expression and its TypeSourceInfo. |
5247 | /// The Const template parameter is for the const and non-const versions |
5248 | /// of AssociationTy. |
5249 | template <bool Const> class AssociationTy { |
5250 | friend class GenericSelectionExpr; |
5251 | template <bool OtherConst> friend class AssociationIteratorTy; |
5252 | using ExprPtrTy = |
5253 | typename std::conditional<Const, const Expr *, Expr *>::type; |
5254 | using TSIPtrTy = typename std::conditional<Const, const TypeSourceInfo *, |
5255 | TypeSourceInfo *>::type; |
5256 | ExprPtrTy E; |
5257 | TSIPtrTy TSI; |
5258 | bool Selected; |
5259 | AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected) |
5260 | : E(E), TSI(TSI), Selected(Selected) {} |
5261 | |
5262 | public: |
5263 | ExprPtrTy getAssociationExpr() const { return E; } |
5264 | TSIPtrTy getTypeSourceInfo() const { return TSI; } |
5265 | QualType getType() const { return TSI ? TSI->getType() : QualType(); } |
5266 | bool isSelected() const { return Selected; } |
5267 | AssociationTy *operator->() { return this; } |
5268 | const AssociationTy *operator->() const { return this; } |
5269 | }; // class AssociationTy |
5270 | |
5271 | /// Iterator over const and non-const Association objects. The Association |
5272 | /// objects are created on the fly when the iterator is dereferenced. |
5273 | /// This abstract over how exactly the association expressions and the |
5274 | /// corresponding TypeSourceInfo * are stored. |
5275 | template <bool Const> |
5276 | class AssociationIteratorTy |
5277 | : public llvm::iterator_facade_base< |
5278 | AssociationIteratorTy<Const>, std::input_iterator_tag, |
5279 | AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>, |
5280 | AssociationTy<Const>> { |
5281 | friend class GenericSelectionExpr; |
5282 | // FIXME: This iterator could conceptually be a random access iterator, and |
5283 | // it would be nice if we could strengthen the iterator category someday. |
5284 | // However this iterator does not satisfy two requirements of forward |
5285 | // iterators: |
5286 | // a) reference = T& or reference = const T& |
5287 | // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only |
5288 | // if *It1 and *It2 are bound to the same objects. |
5289 | // An alternative design approach was discussed during review; |
5290 | // store an Association object inside the iterator, and return a reference |
5291 | // to it when dereferenced. This idea was discarded beacuse of nasty |
5292 | // lifetime issues: |
5293 | // AssociationIterator It = ...; |
5294 | // const Association &Assoc = *It++; // Oops, Assoc is dangling. |
5295 | using BaseTy = typename AssociationIteratorTy::iterator_facade_base; |
5296 | using StmtPtrPtrTy = |
5297 | typename std::conditional<Const, const Stmt *const *, Stmt **>::type; |
5298 | using TSIPtrPtrTy = |
5299 | typename std::conditional<Const, const TypeSourceInfo *const *, |
5300 | TypeSourceInfo **>::type; |
5301 | StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped. |
5302 | TSIPtrPtrTy TSI; // Kept in sync with E. |
5303 | unsigned Offset = 0, SelectedOffset = 0; |
5304 | AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset, |
5305 | unsigned SelectedOffset) |
5306 | : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {} |
5307 | |
5308 | public: |
5309 | AssociationIteratorTy() : E(nullptr), TSI(nullptr) {} |
5310 | typename BaseTy::reference operator*() const { |
5311 | return AssociationTy<Const>(cast<Expr>(*E), *TSI, |
5312 | Offset == SelectedOffset); |
5313 | } |
5314 | typename BaseTy::pointer operator->() const { return **this; } |
5315 | using BaseTy::operator++; |
5316 | AssociationIteratorTy &operator++() { |
5317 | ++E; |
5318 | ++TSI; |
5319 | ++Offset; |
5320 | return *this; |
5321 | } |
5322 | bool operator==(AssociationIteratorTy Other) const { return E == Other.E; } |
5323 | }; // class AssociationIterator |
5324 | |
5325 | /// Build a non-result-dependent generic selection expression. |
5326 | GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, |
5327 | Expr *ControllingExpr, |
5328 | ArrayRef<TypeSourceInfo *> AssocTypes, |
5329 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5330 | SourceLocation RParenLoc, |
5331 | bool ContainsUnexpandedParameterPack, |
5332 | unsigned ResultIndex); |
5333 | |
5334 | /// Build a result-dependent generic selection expression. |
5335 | GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, |
5336 | Expr *ControllingExpr, |
5337 | ArrayRef<TypeSourceInfo *> AssocTypes, |
5338 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5339 | SourceLocation RParenLoc, |
5340 | bool ContainsUnexpandedParameterPack); |
5341 | |
5342 | /// Build an empty generic selection expression for deserialization. |
5343 | explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs); |
5344 | |
5345 | public: |
5346 | /// Create a non-result-dependent generic selection expression. |
5347 | static GenericSelectionExpr * |
5348 | Create(const ASTContext &Context, SourceLocation GenericLoc, |
5349 | Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, |
5350 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5351 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, |
5352 | unsigned ResultIndex); |
5353 | |
5354 | /// Create a result-dependent generic selection expression. |
5355 | static GenericSelectionExpr * |
5356 | Create(const ASTContext &Context, SourceLocation GenericLoc, |
5357 | Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes, |
5358 | ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc, |
5359 | SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); |
5360 | |
5361 | /// Create an empty generic selection expression for deserialization. |
5362 | static GenericSelectionExpr *CreateEmpty(const ASTContext &Context, |
5363 | unsigned NumAssocs); |
5364 | |
5365 | using Association = AssociationTy<false>; |
5366 | using ConstAssociation = AssociationTy<true>; |
5367 | using AssociationIterator = AssociationIteratorTy<false>; |
5368 | using ConstAssociationIterator = AssociationIteratorTy<true>; |
5369 | using association_range = llvm::iterator_range<AssociationIterator>; |
5370 | using const_association_range = |
5371 | llvm::iterator_range<ConstAssociationIterator>; |
5372 | |
5373 | /// The number of association expressions. |
5374 | unsigned getNumAssocs() const { return NumAssocs; } |
5375 | |
5376 | /// The zero-based index of the result expression's generic association in |
5377 | /// the generic selection's association list. Defined only if the |
5378 | /// generic selection is not result-dependent. |
5379 | unsigned getResultIndex() const { |
5380 | assert(!isResultDependent() &&((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!" ) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5381, __PRETTY_FUNCTION__)) |
5381 | "Generic selection is result-dependent but getResultIndex called!")((!isResultDependent() && "Generic selection is result-dependent but getResultIndex called!" ) ? static_cast<void> (0) : __assert_fail ("!isResultDependent() && \"Generic selection is result-dependent but getResultIndex called!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5381, __PRETTY_FUNCTION__)); |
5382 | return ResultIndex; |
5383 | } |
5384 | |
5385 | /// Whether this generic selection is result-dependent. |
5386 | bool isResultDependent() const { return ResultIndex == ResultDependentIndex; } |
5387 | |
5388 | /// Return the controlling expression of this generic selection expression. |
5389 | Expr *getControllingExpr() { |
5390 | return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); |
5391 | } |
5392 | const Expr *getControllingExpr() const { |
5393 | return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]); |
5394 | } |
5395 | |
5396 | /// Return the result expression of this controlling expression. Defined if |
5397 | /// and only if the generic selection expression is not result-dependent. |
5398 | Expr *getResultExpr() { |
5399 | return cast<Expr>( |
5400 | getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); |
5401 | } |
5402 | const Expr *getResultExpr() const { |
5403 | return cast<Expr>( |
5404 | getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]); |
5405 | } |
5406 | |
5407 | ArrayRef<Expr *> getAssocExprs() const { |
5408 | return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() + |
5409 | AssocExprStartIndex), |
5410 | NumAssocs}; |
5411 | } |
5412 | ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const { |
5413 | return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs}; |
5414 | } |
5415 | |
5416 | /// Return the Ith association expression with its TypeSourceInfo, |
5417 | /// bundled together in GenericSelectionExpr::(Const)Association. |
5418 | Association getAssociation(unsigned I) { |
5419 | assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5420, __PRETTY_FUNCTION__)) |
5420 | "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5420, __PRETTY_FUNCTION__)); |
5421 | return Association( |
5422 | cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), |
5423 | getTrailingObjects<TypeSourceInfo *>()[I], |
5424 | !isResultDependent() && (getResultIndex() == I)); |
5425 | } |
5426 | ConstAssociation getAssociation(unsigned I) const { |
5427 | assert(I < getNumAssocs() &&((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5428, __PRETTY_FUNCTION__)) |
5428 | "Out-of-range index in GenericSelectionExpr::getAssociation!")((I < getNumAssocs() && "Out-of-range index in GenericSelectionExpr::getAssociation!" ) ? static_cast<void> (0) : __assert_fail ("I < getNumAssocs() && \"Out-of-range index in GenericSelectionExpr::getAssociation!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5428, __PRETTY_FUNCTION__)); |
5429 | return ConstAssociation( |
5430 | cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]), |
5431 | getTrailingObjects<TypeSourceInfo *>()[I], |
5432 | !isResultDependent() && (getResultIndex() == I)); |
5433 | } |
5434 | |
5435 | association_range associations() { |
5436 | AssociationIterator Begin(getTrailingObjects<Stmt *>() + |
5437 | AssocExprStartIndex, |
5438 | getTrailingObjects<TypeSourceInfo *>(), |
5439 | /*Offset=*/0, ResultIndex); |
5440 | AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, |
5441 | /*Offset=*/NumAssocs, ResultIndex); |
5442 | return llvm::make_range(Begin, End); |
5443 | } |
5444 | |
5445 | const_association_range associations() const { |
5446 | ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() + |
5447 | AssocExprStartIndex, |
5448 | getTrailingObjects<TypeSourceInfo *>(), |
5449 | /*Offset=*/0, ResultIndex); |
5450 | ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs, |
5451 | /*Offset=*/NumAssocs, ResultIndex); |
5452 | return llvm::make_range(Begin, End); |
5453 | } |
5454 | |
5455 | SourceLocation getGenericLoc() const { |
5456 | return GenericSelectionExprBits.GenericLoc; |
5457 | } |
5458 | SourceLocation getDefaultLoc() const { return DefaultLoc; } |
5459 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5460 | SourceLocation getBeginLoc() const { return getGenericLoc(); } |
5461 | SourceLocation getEndLoc() const { return getRParenLoc(); } |
5462 | |
5463 | static bool classof(const Stmt *T) { |
5464 | return T->getStmtClass() == GenericSelectionExprClass; |
5465 | } |
5466 | |
5467 | child_range children() { |
5468 | return child_range(getTrailingObjects<Stmt *>(), |
5469 | getTrailingObjects<Stmt *>() + |
5470 | numTrailingObjects(OverloadToken<Stmt *>())); |
5471 | } |
5472 | const_child_range children() const { |
5473 | return const_child_range(getTrailingObjects<Stmt *>(), |
5474 | getTrailingObjects<Stmt *>() + |
5475 | numTrailingObjects(OverloadToken<Stmt *>())); |
5476 | } |
5477 | }; |
5478 | |
5479 | //===----------------------------------------------------------------------===// |
5480 | // Clang Extensions |
5481 | //===----------------------------------------------------------------------===// |
5482 | |
5483 | /// ExtVectorElementExpr - This represents access to specific elements of a |
5484 | /// vector, and may occur on the left hand side or right hand side. For example |
5485 | /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. |
5486 | /// |
5487 | /// Note that the base may have either vector or pointer to vector type, just |
5488 | /// like a struct field reference. |
5489 | /// |
5490 | class ExtVectorElementExpr : public Expr { |
5491 | Stmt *Base; |
5492 | IdentifierInfo *Accessor; |
5493 | SourceLocation AccessorLoc; |
5494 | public: |
5495 | ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, |
5496 | IdentifierInfo &accessor, SourceLocation loc) |
5497 | : Expr(ExtVectorElementExprClass, ty, VK, |
5498 | (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), |
5499 | base->isTypeDependent(), base->isValueDependent(), |
5500 | base->isInstantiationDependent(), |
5501 | base->containsUnexpandedParameterPack()), |
5502 | Base(base), Accessor(&accessor), AccessorLoc(loc) {} |
5503 | |
5504 | /// Build an empty vector element expression. |
5505 | explicit ExtVectorElementExpr(EmptyShell Empty) |
5506 | : Expr(ExtVectorElementExprClass, Empty) { } |
5507 | |
5508 | const Expr *getBase() const { return cast<Expr>(Base); } |
5509 | Expr *getBase() { return cast<Expr>(Base); } |
5510 | void setBase(Expr *E) { Base = E; } |
5511 | |
5512 | IdentifierInfo &getAccessor() const { return *Accessor; } |
5513 | void setAccessor(IdentifierInfo *II) { Accessor = II; } |
5514 | |
5515 | SourceLocation getAccessorLoc() const { return AccessorLoc; } |
5516 | void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } |
5517 | |
5518 | /// getNumElements - Get the number of components being selected. |
5519 | unsigned getNumElements() const; |
5520 | |
5521 | /// containsDuplicateElements - Return true if any element access is |
5522 | /// repeated. |
5523 | bool containsDuplicateElements() const; |
5524 | |
5525 | /// getEncodedElementAccess - Encode the elements accessed into an llvm |
5526 | /// aggregate Constant of ConstantInt(s). |
5527 | void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const; |
5528 | |
5529 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5530 | return getBase()->getBeginLoc(); |
5531 | } |
5532 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return AccessorLoc; } |
5533 | |
5534 | /// isArrow - Return true if the base expression is a pointer to vector, |
5535 | /// return false if the base expression is a vector. |
5536 | bool isArrow() const; |
5537 | |
5538 | static bool classof(const Stmt *T) { |
5539 | return T->getStmtClass() == ExtVectorElementExprClass; |
5540 | } |
5541 | |
5542 | // Iterators |
5543 | child_range children() { return child_range(&Base, &Base+1); } |
5544 | const_child_range children() const { |
5545 | return const_child_range(&Base, &Base + 1); |
5546 | } |
5547 | }; |
5548 | |
5549 | /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. |
5550 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
5551 | class BlockExpr : public Expr { |
5552 | protected: |
5553 | BlockDecl *TheBlock; |
5554 | public: |
5555 | BlockExpr(BlockDecl *BD, QualType ty) |
5556 | : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, |
5557 | ty->isDependentType(), ty->isDependentType(), |
5558 | ty->isInstantiationDependentType() || BD->isDependentContext(), |
5559 | false), |
5560 | TheBlock(BD) {} |
5561 | |
5562 | /// Build an empty block expression. |
5563 | explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } |
5564 | |
5565 | const BlockDecl *getBlockDecl() const { return TheBlock; } |
5566 | BlockDecl *getBlockDecl() { return TheBlock; } |
5567 | void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } |
5568 | |
5569 | // Convenience functions for probing the underlying BlockDecl. |
5570 | SourceLocation getCaretLocation() const; |
5571 | const Stmt *getBody() const; |
5572 | Stmt *getBody(); |
5573 | |
5574 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5575 | return getCaretLocation(); |
5576 | } |
5577 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5578 | return getBody()->getEndLoc(); |
5579 | } |
5580 | |
5581 | /// getFunctionType - Return the underlying function type for this block. |
5582 | const FunctionProtoType *getFunctionType() const; |
5583 | |
5584 | static bool classof(const Stmt *T) { |
5585 | return T->getStmtClass() == BlockExprClass; |
5586 | } |
5587 | |
5588 | // Iterators |
5589 | child_range children() { |
5590 | return child_range(child_iterator(), child_iterator()); |
5591 | } |
5592 | const_child_range children() const { |
5593 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5594 | } |
5595 | }; |
5596 | |
5597 | /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] |
5598 | /// This AST node provides support for reinterpreting a type to another |
5599 | /// type of the same size. |
5600 | class AsTypeExpr : public Expr { |
5601 | private: |
5602 | Stmt *SrcExpr; |
5603 | SourceLocation BuiltinLoc, RParenLoc; |
5604 | |
5605 | friend class ASTReader; |
5606 | friend class ASTStmtReader; |
5607 | explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} |
5608 | |
5609 | public: |
5610 | AsTypeExpr(Expr* SrcExpr, QualType DstType, |
5611 | ExprValueKind VK, ExprObjectKind OK, |
5612 | SourceLocation BuiltinLoc, SourceLocation RParenLoc) |
5613 | : Expr(AsTypeExprClass, DstType, VK, OK, |
5614 | DstType->isDependentType(), |
5615 | DstType->isDependentType() || SrcExpr->isValueDependent(), |
5616 | (DstType->isInstantiationDependentType() || |
5617 | SrcExpr->isInstantiationDependent()), |
5618 | (DstType->containsUnexpandedParameterPack() || |
5619 | SrcExpr->containsUnexpandedParameterPack())), |
5620 | SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} |
5621 | |
5622 | /// getSrcExpr - Return the Expr to be converted. |
5623 | Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); } |
5624 | |
5625 | /// getBuiltinLoc - Return the location of the __builtin_astype token. |
5626 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
5627 | |
5628 | /// getRParenLoc - Return the location of final right parenthesis. |
5629 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5630 | |
5631 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
5632 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
5633 | |
5634 | static bool classof(const Stmt *T) { |
5635 | return T->getStmtClass() == AsTypeExprClass; |
5636 | } |
5637 | |
5638 | // Iterators |
5639 | child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } |
5640 | const_child_range children() const { |
5641 | return const_child_range(&SrcExpr, &SrcExpr + 1); |
5642 | } |
5643 | }; |
5644 | |
5645 | /// PseudoObjectExpr - An expression which accesses a pseudo-object |
5646 | /// l-value. A pseudo-object is an abstract object, accesses to which |
5647 | /// are translated to calls. The pseudo-object expression has a |
5648 | /// syntactic form, which shows how the expression was actually |
5649 | /// written in the source code, and a semantic form, which is a series |
5650 | /// of expressions to be executed in order which detail how the |
5651 | /// operation is actually evaluated. Optionally, one of the semantic |
5652 | /// forms may also provide a result value for the expression. |
5653 | /// |
5654 | /// If any of the semantic-form expressions is an OpaqueValueExpr, |
5655 | /// that OVE is required to have a source expression, and it is bound |
5656 | /// to the result of that source expression. Such OVEs may appear |
5657 | /// only in subsequent semantic-form expressions and as |
5658 | /// sub-expressions of the syntactic form. |
5659 | /// |
5660 | /// PseudoObjectExpr should be used only when an operation can be |
5661 | /// usefully described in terms of fairly simple rewrite rules on |
5662 | /// objects and functions that are meant to be used by end-developers. |
5663 | /// For example, under the Itanium ABI, dynamic casts are implemented |
5664 | /// as a call to a runtime function called __dynamic_cast; using this |
5665 | /// class to describe that would be inappropriate because that call is |
5666 | /// not really part of the user-visible semantics, and instead the |
5667 | /// cast is properly reflected in the AST and IR-generation has been |
5668 | /// taught to generate the call as necessary. In contrast, an |
5669 | /// Objective-C property access is semantically defined to be |
5670 | /// equivalent to a particular message send, and this is very much |
5671 | /// part of the user model. The name of this class encourages this |
5672 | /// modelling design. |
5673 | class PseudoObjectExpr final |
5674 | : public Expr, |
5675 | private llvm::TrailingObjects<PseudoObjectExpr, Expr *> { |
5676 | // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. |
5677 | // Always at least two, because the first sub-expression is the |
5678 | // syntactic form. |
5679 | |
5680 | // PseudoObjectExprBits.ResultIndex - The index of the |
5681 | // sub-expression holding the result. 0 means the result is void, |
5682 | // which is unambiguous because it's the index of the syntactic |
5683 | // form. Note that this is therefore 1 higher than the value passed |
5684 | // in to Create, which is an index within the semantic forms. |
5685 | // Note also that ASTStmtWriter assumes this encoding. |
5686 | |
5687 | Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); } |
5688 | const Expr * const *getSubExprsBuffer() const { |
5689 | return getTrailingObjects<Expr *>(); |
5690 | } |
5691 | |
5692 | PseudoObjectExpr(QualType type, ExprValueKind VK, |
5693 | Expr *syntactic, ArrayRef<Expr*> semantic, |
5694 | unsigned resultIndex); |
5695 | |
5696 | PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); |
5697 | |
5698 | unsigned getNumSubExprs() const { |
5699 | return PseudoObjectExprBits.NumSubExprs; |
5700 | } |
5701 | |
5702 | public: |
5703 | /// NoResult - A value for the result index indicating that there is |
5704 | /// no semantic result. |
5705 | enum : unsigned { NoResult = ~0U }; |
5706 | |
5707 | static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, |
5708 | ArrayRef<Expr*> semantic, |
5709 | unsigned resultIndex); |
5710 | |
5711 | static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, |
5712 | unsigned numSemanticExprs); |
5713 | |
5714 | /// Return the syntactic form of this expression, i.e. the |
5715 | /// expression it actually looks like. Likely to be expressed in |
5716 | /// terms of OpaqueValueExprs bound in the semantic form. |
5717 | Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } |
5718 | const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } |
5719 | |
5720 | /// Return the index of the result-bearing expression into the semantics |
5721 | /// expressions, or PseudoObjectExpr::NoResult if there is none. |
5722 | unsigned getResultExprIndex() const { |
5723 | if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; |
5724 | return PseudoObjectExprBits.ResultIndex - 1; |
5725 | } |
5726 | |
5727 | /// Return the result-bearing expression, or null if there is none. |
5728 | Expr *getResultExpr() { |
5729 | if (PseudoObjectExprBits.ResultIndex == 0) |
5730 | return nullptr; |
5731 | return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; |
5732 | } |
5733 | const Expr *getResultExpr() const { |
5734 | return const_cast<PseudoObjectExpr*>(this)->getResultExpr(); |
5735 | } |
5736 | |
5737 | unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } |
5738 | |
5739 | typedef Expr * const *semantics_iterator; |
5740 | typedef const Expr * const *const_semantics_iterator; |
5741 | semantics_iterator semantics_begin() { |
5742 | return getSubExprsBuffer() + 1; |
5743 | } |
5744 | const_semantics_iterator semantics_begin() const { |
5745 | return getSubExprsBuffer() + 1; |
5746 | } |
5747 | semantics_iterator semantics_end() { |
5748 | return getSubExprsBuffer() + getNumSubExprs(); |
5749 | } |
5750 | const_semantics_iterator semantics_end() const { |
5751 | return getSubExprsBuffer() + getNumSubExprs(); |
5752 | } |
5753 | |
5754 | llvm::iterator_range<semantics_iterator> semantics() { |
5755 | return llvm::make_range(semantics_begin(), semantics_end()); |
5756 | } |
5757 | llvm::iterator_range<const_semantics_iterator> semantics() const { |
5758 | return llvm::make_range(semantics_begin(), semantics_end()); |
5759 | } |
5760 | |
5761 | Expr *getSemanticExpr(unsigned index) { |
5762 | assert(index + 1 < getNumSubExprs())((index + 1 < getNumSubExprs()) ? static_cast<void> ( 0) : __assert_fail ("index + 1 < getNumSubExprs()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5762, __PRETTY_FUNCTION__)); |
5763 | return getSubExprsBuffer()[index + 1]; |
5764 | } |
5765 | const Expr *getSemanticExpr(unsigned index) const { |
5766 | return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index); |
5767 | } |
5768 | |
5769 | SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5770 | return getSyntacticForm()->getExprLoc(); |
5771 | } |
5772 | |
5773 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5774 | return getSyntacticForm()->getBeginLoc(); |
5775 | } |
5776 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
5777 | return getSyntacticForm()->getEndLoc(); |
5778 | } |
5779 | |
5780 | child_range children() { |
5781 | const_child_range CCR = |
5782 | const_cast<const PseudoObjectExpr *>(this)->children(); |
5783 | return child_range(cast_away_const(CCR.begin()), |
5784 | cast_away_const(CCR.end())); |
5785 | } |
5786 | const_child_range children() const { |
5787 | Stmt *const *cs = const_cast<Stmt *const *>( |
5788 | reinterpret_cast<const Stmt *const *>(getSubExprsBuffer())); |
5789 | return const_child_range(cs, cs + getNumSubExprs()); |
5790 | } |
5791 | |
5792 | static bool classof(const Stmt *T) { |
5793 | return T->getStmtClass() == PseudoObjectExprClass; |
5794 | } |
5795 | |
5796 | friend TrailingObjects; |
5797 | friend class ASTStmtReader; |
5798 | }; |
5799 | |
5800 | /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, |
5801 | /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the |
5802 | /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, |
5803 | /// and corresponding __opencl_atomic_* for OpenCL 2.0. |
5804 | /// All of these instructions take one primary pointer, at least one memory |
5805 | /// order. The instructions for which getScopeModel returns non-null value |
5806 | /// take one synch scope. |
5807 | class AtomicExpr : public Expr { |
5808 | public: |
5809 | enum AtomicOp { |
5810 | #define BUILTIN(ID, TYPE, ATTRS) |
5811 | #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, |
5812 | #include "clang/Basic/Builtins.def" |
5813 | // Avoid trailing comma |
5814 | BI_First = 0 |
5815 | }; |
5816 | |
5817 | private: |
5818 | /// Location of sub-expressions. |
5819 | /// The location of Scope sub-expression is NumSubExprs - 1, which is |
5820 | /// not fixed, therefore is not defined in enum. |
5821 | enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; |
5822 | Stmt *SubExprs[END_EXPR + 1]; |
5823 | unsigned NumSubExprs; |
5824 | SourceLocation BuiltinLoc, RParenLoc; |
5825 | AtomicOp Op; |
5826 | |
5827 | friend class ASTStmtReader; |
5828 | public: |
5829 | AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t, |
5830 | AtomicOp op, SourceLocation RP); |
5831 | |
5832 | /// Determine the number of arguments the specified atomic builtin |
5833 | /// should have. |
5834 | static unsigned getNumSubExprs(AtomicOp Op); |
5835 | |
5836 | /// Build an empty AtomicExpr. |
5837 | explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } |
5838 | |
5839 | Expr *getPtr() const { |
5840 | return cast<Expr>(SubExprs[PTR]); |
5841 | } |
5842 | Expr *getOrder() const { |
5843 | return cast<Expr>(SubExprs[ORDER]); |
5844 | } |
5845 | Expr *getScope() const { |
5846 | assert(getScopeModel() && "No scope")((getScopeModel() && "No scope") ? static_cast<void > (0) : __assert_fail ("getScopeModel() && \"No scope\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5846, __PRETTY_FUNCTION__)); |
5847 | return cast<Expr>(SubExprs[NumSubExprs - 1]); |
5848 | } |
5849 | Expr *getVal1() const { |
5850 | if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init) |
5851 | return cast<Expr>(SubExprs[ORDER]); |
5852 | assert(NumSubExprs > VAL1)((NumSubExprs > VAL1) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > VAL1", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5852, __PRETTY_FUNCTION__)); |
5853 | return cast<Expr>(SubExprs[VAL1]); |
5854 | } |
5855 | Expr *getOrderFail() const { |
5856 | assert(NumSubExprs > ORDER_FAIL)((NumSubExprs > ORDER_FAIL) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > ORDER_FAIL", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5856, __PRETTY_FUNCTION__)); |
5857 | return cast<Expr>(SubExprs[ORDER_FAIL]); |
5858 | } |
5859 | Expr *getVal2() const { |
5860 | if (Op == AO__atomic_exchange) |
5861 | return cast<Expr>(SubExprs[ORDER_FAIL]); |
5862 | assert(NumSubExprs > VAL2)((NumSubExprs > VAL2) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > VAL2", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5862, __PRETTY_FUNCTION__)); |
5863 | return cast<Expr>(SubExprs[VAL2]); |
5864 | } |
5865 | Expr *getWeak() const { |
5866 | assert(NumSubExprs > WEAK)((NumSubExprs > WEAK) ? static_cast<void> (0) : __assert_fail ("NumSubExprs > WEAK", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5866, __PRETTY_FUNCTION__)); |
5867 | return cast<Expr>(SubExprs[WEAK]); |
5868 | } |
5869 | QualType getValueType() const; |
5870 | |
5871 | AtomicOp getOp() const { return Op; } |
5872 | unsigned getNumSubExprs() const { return NumSubExprs; } |
5873 | |
5874 | Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); } |
5875 | const Expr * const *getSubExprs() const { |
5876 | return reinterpret_cast<Expr * const *>(SubExprs); |
5877 | } |
5878 | |
5879 | bool isVolatile() const { |
5880 | return getPtr()->getType()->getPointeeType().isVolatileQualified(); |
5881 | } |
5882 | |
5883 | bool isCmpXChg() const { |
5884 | return getOp() == AO__c11_atomic_compare_exchange_strong || |
5885 | getOp() == AO__c11_atomic_compare_exchange_weak || |
5886 | getOp() == AO__opencl_atomic_compare_exchange_strong || |
5887 | getOp() == AO__opencl_atomic_compare_exchange_weak || |
5888 | getOp() == AO__atomic_compare_exchange || |
5889 | getOp() == AO__atomic_compare_exchange_n; |
5890 | } |
5891 | |
5892 | bool isOpenCL() const { |
5893 | return getOp() >= AO__opencl_atomic_init && |
5894 | getOp() <= AO__opencl_atomic_fetch_max; |
5895 | } |
5896 | |
5897 | SourceLocation getBuiltinLoc() const { return BuiltinLoc; } |
5898 | SourceLocation getRParenLoc() const { return RParenLoc; } |
5899 | |
5900 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return BuiltinLoc; } |
5901 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; } |
5902 | |
5903 | static bool classof(const Stmt *T) { |
5904 | return T->getStmtClass() == AtomicExprClass; |
5905 | } |
5906 | |
5907 | // Iterators |
5908 | child_range children() { |
5909 | return child_range(SubExprs, SubExprs+NumSubExprs); |
5910 | } |
5911 | const_child_range children() const { |
5912 | return const_child_range(SubExprs, SubExprs + NumSubExprs); |
5913 | } |
5914 | |
5915 | /// Get atomic scope model for the atomic op code. |
5916 | /// \return empty atomic scope model if the atomic op code does not have |
5917 | /// scope operand. |
5918 | static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) { |
5919 | auto Kind = |
5920 | (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max) |
5921 | ? AtomicScopeModelKind::OpenCL |
5922 | : AtomicScopeModelKind::None; |
5923 | return AtomicScopeModel::create(Kind); |
5924 | } |
5925 | |
5926 | /// Get atomic scope model. |
5927 | /// \return empty atomic scope model if this atomic expression does not have |
5928 | /// scope operand. |
5929 | std::unique_ptr<AtomicScopeModel> getScopeModel() const { |
5930 | return getScopeModel(getOp()); |
5931 | } |
5932 | }; |
5933 | |
5934 | /// TypoExpr - Internal placeholder for expressions where typo correction |
5935 | /// still needs to be performed and/or an error diagnostic emitted. |
5936 | class TypoExpr : public Expr { |
5937 | public: |
5938 | TypoExpr(QualType T) |
5939 | : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary, |
5940 | /*isTypeDependent*/ true, |
5941 | /*isValueDependent*/ true, |
5942 | /*isInstantiationDependent*/ true, |
5943 | /*containsUnexpandedParameterPack*/ false) { |
5944 | assert(T->isDependentType() && "TypoExpr given a non-dependent type")((T->isDependentType() && "TypoExpr given a non-dependent type" ) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"TypoExpr given a non-dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h" , 5944, __PRETTY_FUNCTION__)); |
5945 | } |
5946 | |
5947 | child_range children() { |
5948 | return child_range(child_iterator(), child_iterator()); |
5949 | } |
5950 | const_child_range children() const { |
5951 | return const_child_range(const_child_iterator(), const_child_iterator()); |
5952 | } |
5953 | |
5954 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5955 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return SourceLocation(); } |
5956 | |
5957 | static bool classof(const Stmt *T) { |
5958 | return T->getStmtClass() == TypoExprClass; |
5959 | } |
5960 | |
5961 | }; |
5962 | } // end namespace clang |
5963 | |
5964 | #endif // LLVM_CLANG_AST_EXPR_H |