cmake: Inline the add_llvm_symbol_exports.py script
[llvm-project.git] / clang / lib / AST / ExprConstant.cpp
blob34e75723b3f30c564585bbae565a868fd28fdc32
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.
11 // Constant expression evaluation produces four main results:
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.
18 // * An evaluated result, valid only if constant folding has not failed.
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.
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.
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).
33 //===----------------------------------------------------------------------===//
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/TimeProfiler.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <cstring>
62 #include <functional>
64 #define DEBUG_TYPE "exprconstant"
66 using namespace clang;
67 using llvm::APFixedPoint;
68 using llvm::APInt;
69 using llvm::APSInt;
70 using llvm::APFloat;
71 using llvm::FixedPointSemantics;
72 using llvm::Optional;
74 namespace {
75 struct LValue;
76 class CallStackFrame;
77 class EvalInfo;
79 using SourceLocExprScopeGuard =
80 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
82 static QualType getType(APValue::LValueBase B) {
83 return B.getType();
86 /// Get an LValue path entry, which is known to not be an array index, as a
87 /// field declaration.
88 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
89 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
91 /// Get an LValue path entry, which is known to not be an array index, as a
92 /// base class declaration.
93 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
94 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
96 /// Determine whether this LValue path entry for a base class names a virtual
97 /// base class.
98 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
99 return E.getAsBaseOrMember().getInt();
102 /// Given an expression, determine the type used to store the result of
103 /// evaluating that expression.
104 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
105 if (E->isPRValue())
106 return E->getType();
107 return Ctx.getLValueReferenceType(E->getType());
110 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
111 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
112 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
113 return DirectCallee->getAttr<AllocSizeAttr>();
114 if (const Decl *IndirectCallee = CE->getCalleeDecl())
115 return IndirectCallee->getAttr<AllocSizeAttr>();
116 return nullptr;
119 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
120 /// This will look through a single cast.
122 /// Returns null if we couldn't unwrap a function with alloc_size.
123 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
124 if (!E->getType()->isPointerType())
125 return nullptr;
127 E = E->IgnoreParens();
128 // If we're doing a variable assignment from e.g. malloc(N), there will
129 // probably be a cast of some kind. In exotic cases, we might also see a
130 // top-level ExprWithCleanups. Ignore them either way.
131 if (const auto *FE = dyn_cast<FullExpr>(E))
132 E = FE->getSubExpr()->IgnoreParens();
134 if (const auto *Cast = dyn_cast<CastExpr>(E))
135 E = Cast->getSubExpr()->IgnoreParens();
137 if (const auto *CE = dyn_cast<CallExpr>(E))
138 return getAllocSizeAttr(CE) ? CE : nullptr;
139 return nullptr;
142 /// Determines whether or not the given Base contains a call to a function
143 /// with the alloc_size attribute.
144 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
145 const auto *E = Base.dyn_cast<const Expr *>();
146 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
149 /// Determines whether the given kind of constant expression is only ever
150 /// used for name mangling. If so, it's permitted to reference things that we
151 /// can't generate code for (in particular, dllimported functions).
152 static bool isForManglingOnly(ConstantExprKind Kind) {
153 switch (Kind) {
154 case ConstantExprKind::Normal:
155 case ConstantExprKind::ClassTemplateArgument:
156 case ConstantExprKind::ImmediateInvocation:
157 // Note that non-type template arguments of class type are emitted as
158 // template parameter objects.
159 return false;
161 case ConstantExprKind::NonClassTemplateArgument:
162 return true;
164 llvm_unreachable("unknown ConstantExprKind");
167 static bool isTemplateArgument(ConstantExprKind Kind) {
168 switch (Kind) {
169 case ConstantExprKind::Normal:
170 case ConstantExprKind::ImmediateInvocation:
171 return false;
173 case ConstantExprKind::ClassTemplateArgument:
174 case ConstantExprKind::NonClassTemplateArgument:
175 return true;
177 llvm_unreachable("unknown ConstantExprKind");
180 /// The bound to claim that an array of unknown bound has.
181 /// The value in MostDerivedArraySize is undefined in this case. So, set it
182 /// to an arbitrary value that's likely to loudly break things if it's used.
183 static const uint64_t AssumedSizeForUnsizedArray =
184 std::numeric_limits<uint64_t>::max() / 2;
186 /// Determines if an LValue with the given LValueBase will have an unsized
187 /// array in its designator.
188 /// Find the path length and type of the most-derived subobject in the given
189 /// path, and find the size of the containing array, if any.
190 static unsigned
191 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
192 ArrayRef<APValue::LValuePathEntry> Path,
193 uint64_t &ArraySize, QualType &Type, bool &IsArray,
194 bool &FirstEntryIsUnsizedArray) {
195 // This only accepts LValueBases from APValues, and APValues don't support
196 // arrays that lack size info.
197 assert(!isBaseAnAllocSizeCall(Base) &&
198 "Unsized arrays shouldn't appear here");
199 unsigned MostDerivedLength = 0;
200 Type = getType(Base);
202 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
203 if (Type->isArrayType()) {
204 const ArrayType *AT = Ctx.getAsArrayType(Type);
205 Type = AT->getElementType();
206 MostDerivedLength = I + 1;
207 IsArray = true;
209 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
210 ArraySize = CAT->getSize().getZExtValue();
211 } else {
212 assert(I == 0 && "unexpected unsized array designator");
213 FirstEntryIsUnsizedArray = true;
214 ArraySize = AssumedSizeForUnsizedArray;
216 } else if (Type->isAnyComplexType()) {
217 const ComplexType *CT = Type->castAs<ComplexType>();
218 Type = CT->getElementType();
219 ArraySize = 2;
220 MostDerivedLength = I + 1;
221 IsArray = true;
222 } else if (const FieldDecl *FD = getAsField(Path[I])) {
223 Type = FD->getType();
224 ArraySize = 0;
225 MostDerivedLength = I + 1;
226 IsArray = false;
227 } else {
228 // Path[I] describes a base class.
229 ArraySize = 0;
230 IsArray = false;
233 return MostDerivedLength;
236 /// A path from a glvalue to a subobject of that glvalue.
237 struct SubobjectDesignator {
238 /// True if the subobject was named in a manner not supported by C++11. Such
239 /// lvalues can still be folded, but they are not core constant expressions
240 /// and we cannot perform lvalue-to-rvalue conversions on them.
241 unsigned Invalid : 1;
243 /// Is this a pointer one past the end of an object?
244 unsigned IsOnePastTheEnd : 1;
246 /// Indicator of whether the first entry is an unsized array.
247 unsigned FirstEntryIsAnUnsizedArray : 1;
249 /// Indicator of whether the most-derived object is an array element.
250 unsigned MostDerivedIsArrayElement : 1;
252 /// The length of the path to the most-derived object of which this is a
253 /// subobject.
254 unsigned MostDerivedPathLength : 28;
256 /// The size of the array of which the most-derived object is an element.
257 /// This will always be 0 if the most-derived object is not an array
258 /// element. 0 is not an indicator of whether or not the most-derived object
259 /// is an array, however, because 0-length arrays are allowed.
261 /// If the current array is an unsized array, the value of this is
262 /// undefined.
263 uint64_t MostDerivedArraySize;
265 /// The type of the most derived object referred to by this address.
266 QualType MostDerivedType;
268 typedef APValue::LValuePathEntry PathEntry;
270 /// The entries on the path from the glvalue to the designated subobject.
271 SmallVector<PathEntry, 8> Entries;
273 SubobjectDesignator() : Invalid(true) {}
275 explicit SubobjectDesignator(QualType T)
276 : Invalid(false), IsOnePastTheEnd(false),
277 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
278 MostDerivedPathLength(0), MostDerivedArraySize(0),
279 MostDerivedType(T) {}
281 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
282 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284 MostDerivedPathLength(0), MostDerivedArraySize(0) {
285 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
286 if (!Invalid) {
287 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
288 ArrayRef<PathEntry> VEntries = V.getLValuePath();
289 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
290 if (V.getLValueBase()) {
291 bool IsArray = false;
292 bool FirstIsUnsizedArray = false;
293 MostDerivedPathLength = findMostDerivedSubobject(
294 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
295 MostDerivedType, IsArray, FirstIsUnsizedArray);
296 MostDerivedIsArrayElement = IsArray;
297 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
302 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
303 unsigned NewLength) {
304 if (Invalid)
305 return;
307 assert(Base && "cannot truncate path for null pointer");
308 assert(NewLength <= Entries.size() && "not a truncation");
310 if (NewLength == Entries.size())
311 return;
312 Entries.resize(NewLength);
314 bool IsArray = false;
315 bool FirstIsUnsizedArray = false;
316 MostDerivedPathLength = findMostDerivedSubobject(
317 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
318 FirstIsUnsizedArray);
319 MostDerivedIsArrayElement = IsArray;
320 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323 void setInvalid() {
324 Invalid = true;
325 Entries.clear();
328 /// Determine whether the most derived subobject is an array without a
329 /// known bound.
330 bool isMostDerivedAnUnsizedArray() const {
331 assert(!Invalid && "Calling this makes no sense on invalid designators");
332 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
335 /// Determine what the most derived array's size is. Results in an assertion
336 /// failure if the most derived array lacks a size.
337 uint64_t getMostDerivedArraySize() const {
338 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
339 return MostDerivedArraySize;
342 /// Determine whether this is a one-past-the-end pointer.
343 bool isOnePastTheEnd() const {
344 assert(!Invalid);
345 if (IsOnePastTheEnd)
346 return true;
347 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
348 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
349 MostDerivedArraySize)
350 return true;
351 return false;
354 /// Get the range of valid index adjustments in the form
355 /// {maximum value that can be subtracted from this pointer,
356 /// maximum value that can be added to this pointer}
357 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
358 if (Invalid || isMostDerivedAnUnsizedArray())
359 return {0, 0};
361 // [expr.add]p4: For the purposes of these operators, a pointer to a
362 // nonarray object behaves the same as a pointer to the first element of
363 // an array of length one with the type of the object as its element type.
364 bool IsArray = MostDerivedPathLength == Entries.size() &&
365 MostDerivedIsArrayElement;
366 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
367 : (uint64_t)IsOnePastTheEnd;
368 uint64_t ArraySize =
369 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
370 return {ArrayIndex, ArraySize - ArrayIndex};
373 /// Check that this refers to a valid subobject.
374 bool isValidSubobject() const {
375 if (Invalid)
376 return false;
377 return !isOnePastTheEnd();
379 /// Check that this refers to a valid subobject, and if not, produce a
380 /// relevant diagnostic and set the designator as invalid.
381 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
383 /// Get the type of the designated object.
384 QualType getType(ASTContext &Ctx) const {
385 assert(!Invalid && "invalid designator has no subobject type");
386 return MostDerivedPathLength == Entries.size()
387 ? MostDerivedType
388 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391 /// Update this designator to refer to the first element within this array.
392 void addArrayUnchecked(const ConstantArrayType *CAT) {
393 Entries.push_back(PathEntry::ArrayIndex(0));
395 // This is a most-derived object.
396 MostDerivedType = CAT->getElementType();
397 MostDerivedIsArrayElement = true;
398 MostDerivedArraySize = CAT->getSize().getZExtValue();
399 MostDerivedPathLength = Entries.size();
401 /// Update this designator to refer to the first element within the array of
402 /// elements of type T. This is an array of unknown size.
403 void addUnsizedArrayUnchecked(QualType ElemTy) {
404 Entries.push_back(PathEntry::ArrayIndex(0));
406 MostDerivedType = ElemTy;
407 MostDerivedIsArrayElement = true;
408 // The value in MostDerivedArraySize is undefined in this case. So, set it
409 // to an arbitrary value that's likely to loudly break things if it's
410 // used.
411 MostDerivedArraySize = AssumedSizeForUnsizedArray;
412 MostDerivedPathLength = Entries.size();
414 /// Update this designator to refer to the given base or member of this
415 /// object.
416 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
417 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
419 // If this isn't a base class, it's a new most-derived object.
420 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
421 MostDerivedType = FD->getType();
422 MostDerivedIsArrayElement = false;
423 MostDerivedArraySize = 0;
424 MostDerivedPathLength = Entries.size();
427 /// Update this designator to refer to the given complex component.
428 void addComplexUnchecked(QualType EltTy, bool Imag) {
429 Entries.push_back(PathEntry::ArrayIndex(Imag));
431 // This is technically a most-derived object, though in practice this
432 // is unlikely to matter.
433 MostDerivedType = EltTy;
434 MostDerivedIsArrayElement = true;
435 MostDerivedArraySize = 2;
436 MostDerivedPathLength = Entries.size();
438 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
439 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
440 const APSInt &N);
441 /// Add N to the address of this subobject.
442 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
443 if (Invalid || !N) return;
444 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
445 if (isMostDerivedAnUnsizedArray()) {
446 diagnoseUnsizedArrayPointerArithmetic(Info, E);
447 // Can't verify -- trust that the user is doing the right thing (or if
448 // not, trust that the caller will catch the bad behavior).
449 // FIXME: Should we reject if this overflows, at least?
450 Entries.back() = PathEntry::ArrayIndex(
451 Entries.back().getAsArrayIndex() + TruncatedN);
452 return;
455 // [expr.add]p4: For the purposes of these operators, a pointer to a
456 // nonarray object behaves the same as a pointer to the first element of
457 // an array of length one with the type of the object as its element type.
458 bool IsArray = MostDerivedPathLength == Entries.size() &&
459 MostDerivedIsArrayElement;
460 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
461 : (uint64_t)IsOnePastTheEnd;
462 uint64_t ArraySize =
463 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
465 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
466 // Calculate the actual index in a wide enough type, so we can include
467 // it in the note.
468 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
469 (llvm::APInt&)N += ArrayIndex;
470 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
471 diagnosePointerArithmetic(Info, E, N);
472 setInvalid();
473 return;
476 ArrayIndex += TruncatedN;
477 assert(ArrayIndex <= ArraySize &&
478 "bounds check succeeded for out-of-bounds index");
480 if (IsArray)
481 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
482 else
483 IsOnePastTheEnd = (ArrayIndex != 0);
487 /// A scope at the end of which an object can need to be destroyed.
488 enum class ScopeKind {
489 Block,
490 FullExpression,
491 Call
494 /// A reference to a particular call and its arguments.
495 struct CallRef {
496 CallRef() : OrigCallee(), CallIndex(0), Version() {}
497 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
498 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
500 explicit operator bool() const { return OrigCallee; }
502 /// Get the parameter that the caller initialized, corresponding to the
503 /// given parameter in the callee.
504 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
505 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
506 : PVD;
509 /// The callee at the point where the arguments were evaluated. This might
510 /// be different from the actual callee (a different redeclaration, or a
511 /// virtual override), but this function's parameters are the ones that
512 /// appear in the parameter map.
513 const FunctionDecl *OrigCallee;
514 /// The call index of the frame that holds the argument values.
515 unsigned CallIndex;
516 /// The version of the parameters corresponding to this call.
517 unsigned Version;
520 /// A stack frame in the constexpr call stack.
521 class CallStackFrame : public interp::Frame {
522 public:
523 EvalInfo &Info;
525 /// Parent - The caller of this stack frame.
526 CallStackFrame *Caller;
528 /// Callee - The function which was called.
529 const FunctionDecl *Callee;
531 /// This - The binding for the this pointer in this call, if any.
532 const LValue *This;
534 /// Information on how to find the arguments to this call. Our arguments
535 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
536 /// key and this value as the version.
537 CallRef Arguments;
539 /// Source location information about the default argument or default
540 /// initializer expression we're evaluating, if any.
541 CurrentSourceLocExprScope CurSourceLocExprScope;
543 // Note that we intentionally use std::map here so that references to
544 // values are stable.
545 typedef std::pair<const void *, unsigned> MapKeyTy;
546 typedef std::map<MapKeyTy, APValue> MapTy;
547 /// Temporaries - Temporary lvalues materialized within this stack frame.
548 MapTy Temporaries;
550 /// CallLoc - The location of the call expression for this call.
551 SourceLocation CallLoc;
553 /// Index - The call index of this call.
554 unsigned Index;
556 /// The stack of integers for tracking version numbers for temporaries.
557 SmallVector<unsigned, 2> TempVersionStack = {1};
558 unsigned CurTempVersion = TempVersionStack.back();
560 unsigned getTempVersion() const { return TempVersionStack.back(); }
562 void pushTempVersion() {
563 TempVersionStack.push_back(++CurTempVersion);
566 void popTempVersion() {
567 TempVersionStack.pop_back();
570 CallRef createCall(const FunctionDecl *Callee) {
571 return {Callee, Index, ++CurTempVersion};
574 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
575 // on the overall stack usage of deeply-recursing constexpr evaluations.
576 // (We should cache this map rather than recomputing it repeatedly.)
577 // But let's try this and see how it goes; we can look into caching the map
578 // as a later change.
580 /// LambdaCaptureFields - Mapping from captured variables/this to
581 /// corresponding data members in the closure class.
582 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
583 FieldDecl *LambdaThisCaptureField;
585 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
586 const FunctionDecl *Callee, const LValue *This,
587 CallRef Arguments);
588 ~CallStackFrame();
590 // Return the temporary for Key whose version number is Version.
591 APValue *getTemporary(const void *Key, unsigned Version) {
592 MapKeyTy KV(Key, Version);
593 auto LB = Temporaries.lower_bound(KV);
594 if (LB != Temporaries.end() && LB->first == KV)
595 return &LB->second;
596 // Pair (Key,Version) wasn't found in the map. Check that no elements
597 // in the map have 'Key' as their key.
598 assert((LB == Temporaries.end() || LB->first.first != Key) &&
599 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
600 "Element with key 'Key' found in map");
601 return nullptr;
604 // Return the current temporary for Key in the map.
605 APValue *getCurrentTemporary(const void *Key) {
606 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
607 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
608 return &std::prev(UB)->second;
609 return nullptr;
612 // Return the version number of the current temporary for Key.
613 unsigned getCurrentTemporaryVersion(const void *Key) const {
614 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
615 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
616 return std::prev(UB)->first.second;
617 return 0;
620 /// Allocate storage for an object of type T in this stack frame.
621 /// Populates LV with a handle to the created object. Key identifies
622 /// the temporary within the stack frame, and must not be reused without
623 /// bumping the temporary version number.
624 template<typename KeyT>
625 APValue &createTemporary(const KeyT *Key, QualType T,
626 ScopeKind Scope, LValue &LV);
628 /// Allocate storage for a parameter of a function call made in this frame.
629 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
631 void describe(llvm::raw_ostream &OS) override;
633 Frame *getCaller() const override { return Caller; }
634 SourceLocation getCallLocation() const override { return CallLoc; }
635 const FunctionDecl *getCallee() const override { return Callee; }
637 bool isStdFunction() const {
638 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
639 if (DC->isStdNamespace())
640 return true;
641 return false;
644 private:
645 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
646 ScopeKind Scope);
649 /// Temporarily override 'this'.
650 class ThisOverrideRAII {
651 public:
652 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
653 : Frame(Frame), OldThis(Frame.This) {
654 if (Enable)
655 Frame.This = NewThis;
657 ~ThisOverrideRAII() {
658 Frame.This = OldThis;
660 private:
661 CallStackFrame &Frame;
662 const LValue *OldThis;
665 // A shorthand time trace scope struct, prints source range, for example
666 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
667 class ExprTimeTraceScope {
668 public:
669 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
670 : TimeScope(Name, [E, &Ctx] {
671 return E->getSourceRange().printToString(Ctx.getSourceManager());
672 }) {}
674 private:
675 llvm::TimeTraceScope TimeScope;
679 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
680 const LValue &This, QualType ThisType);
681 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
682 APValue::LValueBase LVBase, APValue &Value,
683 QualType T);
685 namespace {
686 /// A cleanup, and a flag indicating whether it is lifetime-extended.
687 class Cleanup {
688 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
689 APValue::LValueBase Base;
690 QualType T;
692 public:
693 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
694 ScopeKind Scope)
695 : Value(Val, Scope), Base(Base), T(T) {}
697 /// Determine whether this cleanup should be performed at the end of the
698 /// given kind of scope.
699 bool isDestroyedAtEndOf(ScopeKind K) const {
700 return (int)Value.getInt() >= (int)K;
702 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
703 if (RunDestructors) {
704 SourceLocation Loc;
705 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
706 Loc = VD->getLocation();
707 else if (const Expr *E = Base.dyn_cast<const Expr*>())
708 Loc = E->getExprLoc();
709 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
711 *Value.getPointer() = APValue();
712 return true;
715 bool hasSideEffect() {
716 return T.isDestructedType();
720 /// A reference to an object whose construction we are currently evaluating.
721 struct ObjectUnderConstruction {
722 APValue::LValueBase Base;
723 ArrayRef<APValue::LValuePathEntry> Path;
724 friend bool operator==(const ObjectUnderConstruction &LHS,
725 const ObjectUnderConstruction &RHS) {
726 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
728 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
729 return llvm::hash_combine(Obj.Base, Obj.Path);
732 enum class ConstructionPhase {
733 None,
734 Bases,
735 AfterBases,
736 AfterFields,
737 Destroying,
738 DestroyingBases
742 namespace llvm {
743 template<> struct DenseMapInfo<ObjectUnderConstruction> {
744 using Base = DenseMapInfo<APValue::LValueBase>;
745 static ObjectUnderConstruction getEmptyKey() {
746 return {Base::getEmptyKey(), {}}; }
747 static ObjectUnderConstruction getTombstoneKey() {
748 return {Base::getTombstoneKey(), {}};
750 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
751 return hash_value(Object);
753 static bool isEqual(const ObjectUnderConstruction &LHS,
754 const ObjectUnderConstruction &RHS) {
755 return LHS == RHS;
760 namespace {
761 /// A dynamically-allocated heap object.
762 struct DynAlloc {
763 /// The value of this heap-allocated object.
764 APValue Value;
765 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
766 /// or a CallExpr (the latter is for direct calls to operator new inside
767 /// std::allocator<T>::allocate).
768 const Expr *AllocExpr = nullptr;
770 enum Kind {
771 New,
772 ArrayNew,
773 StdAllocator
776 /// Get the kind of the allocation. This must match between allocation
777 /// and deallocation.
778 Kind getKind() const {
779 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
780 return NE->isArray() ? ArrayNew : New;
781 assert(isa<CallExpr>(AllocExpr));
782 return StdAllocator;
786 struct DynAllocOrder {
787 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
788 return L.getIndex() < R.getIndex();
792 /// EvalInfo - This is a private struct used by the evaluator to capture
793 /// information about a subexpression as it is folded. It retains information
794 /// about the AST context, but also maintains information about the folded
795 /// expression.
797 /// If an expression could be evaluated, it is still possible it is not a C
798 /// "integer constant expression" or constant expression. If not, this struct
799 /// captures information about how and why not.
801 /// One bit of information passed *into* the request for constant folding
802 /// indicates whether the subexpression is "evaluated" or not according to C
803 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
804 /// evaluate the expression regardless of what the RHS is, but C only allows
805 /// certain things in certain situations.
806 class EvalInfo : public interp::State {
807 public:
808 ASTContext &Ctx;
810 /// EvalStatus - Contains information about the evaluation.
811 Expr::EvalStatus &EvalStatus;
813 /// CurrentCall - The top of the constexpr call stack.
814 CallStackFrame *CurrentCall;
816 /// CallStackDepth - The number of calls in the call stack right now.
817 unsigned CallStackDepth;
819 /// NextCallIndex - The next call index to assign.
820 unsigned NextCallIndex;
822 /// StepsLeft - The remaining number of evaluation steps we're permitted
823 /// to perform. This is essentially a limit for the number of statements
824 /// we will evaluate.
825 unsigned StepsLeft;
827 /// Enable the experimental new constant interpreter. If an expression is
828 /// not supported by the interpreter, an error is triggered.
829 bool EnableNewConstInterp;
831 /// BottomFrame - The frame in which evaluation started. This must be
832 /// initialized after CurrentCall and CallStackDepth.
833 CallStackFrame BottomFrame;
835 /// A stack of values whose lifetimes end at the end of some surrounding
836 /// evaluation frame.
837 llvm::SmallVector<Cleanup, 16> CleanupStack;
839 /// EvaluatingDecl - This is the declaration whose initializer is being
840 /// evaluated, if any.
841 APValue::LValueBase EvaluatingDecl;
843 enum class EvaluatingDeclKind {
844 None,
845 /// We're evaluating the construction of EvaluatingDecl.
846 Ctor,
847 /// We're evaluating the destruction of EvaluatingDecl.
848 Dtor,
850 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
852 /// EvaluatingDeclValue - This is the value being constructed for the
853 /// declaration whose initializer is being evaluated, if any.
854 APValue *EvaluatingDeclValue;
856 /// Set of objects that are currently being constructed.
857 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
858 ObjectsUnderConstruction;
860 /// Current heap allocations, along with the location where each was
861 /// allocated. We use std::map here because we need stable addresses
862 /// for the stored APValues.
863 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
865 /// The number of heap allocations performed so far in this evaluation.
866 unsigned NumHeapAllocs = 0;
868 struct EvaluatingConstructorRAII {
869 EvalInfo &EI;
870 ObjectUnderConstruction Object;
871 bool DidInsert;
872 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
873 bool HasBases)
874 : EI(EI), Object(Object) {
875 DidInsert =
876 EI.ObjectsUnderConstruction
877 .insert({Object, HasBases ? ConstructionPhase::Bases
878 : ConstructionPhase::AfterBases})
879 .second;
881 void finishedConstructingBases() {
882 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
884 void finishedConstructingFields() {
885 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
887 ~EvaluatingConstructorRAII() {
888 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
892 struct EvaluatingDestructorRAII {
893 EvalInfo &EI;
894 ObjectUnderConstruction Object;
895 bool DidInsert;
896 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
897 : EI(EI), Object(Object) {
898 DidInsert = EI.ObjectsUnderConstruction
899 .insert({Object, ConstructionPhase::Destroying})
900 .second;
902 void startedDestroyingBases() {
903 EI.ObjectsUnderConstruction[Object] =
904 ConstructionPhase::DestroyingBases;
906 ~EvaluatingDestructorRAII() {
907 if (DidInsert)
908 EI.ObjectsUnderConstruction.erase(Object);
912 ConstructionPhase
913 isEvaluatingCtorDtor(APValue::LValueBase Base,
914 ArrayRef<APValue::LValuePathEntry> Path) {
915 return ObjectsUnderConstruction.lookup({Base, Path});
918 /// If we're currently speculatively evaluating, the outermost call stack
919 /// depth at which we can mutate state, otherwise 0.
920 unsigned SpeculativeEvaluationDepth = 0;
922 /// The current array initialization index, if we're performing array
923 /// initialization.
924 uint64_t ArrayInitIndex = -1;
926 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
927 /// notes attached to it will also be stored, otherwise they will not be.
928 bool HasActiveDiagnostic;
930 /// Have we emitted a diagnostic explaining why we couldn't constant
931 /// fold (not just why it's not strictly a constant expression)?
932 bool HasFoldFailureDiagnostic;
934 /// Whether or not we're in a context where the front end requires a
935 /// constant value.
936 bool InConstantContext;
938 /// Whether we're checking that an expression is a potential constant
939 /// expression. If so, do not fail on constructs that could become constant
940 /// later on (such as a use of an undefined global).
941 bool CheckingPotentialConstantExpression = false;
943 /// Whether we're checking for an expression that has undefined behavior.
944 /// If so, we will produce warnings if we encounter an operation that is
945 /// always undefined.
947 /// Note that we still need to evaluate the expression normally when this
948 /// is set; this is used when evaluating ICEs in C.
949 bool CheckingForUndefinedBehavior = false;
951 enum EvaluationMode {
952 /// Evaluate as a constant expression. Stop if we find that the expression
953 /// is not a constant expression.
954 EM_ConstantExpression,
956 /// Evaluate as a constant expression. Stop if we find that the expression
957 /// is not a constant expression. Some expressions can be retried in the
958 /// optimizer if we don't constant fold them here, but in an unevaluated
959 /// context we try to fold them immediately since the optimizer never
960 /// gets a chance to look at it.
961 EM_ConstantExpressionUnevaluated,
963 /// Fold the expression to a constant. Stop if we hit a side-effect that
964 /// we can't model.
965 EM_ConstantFold,
967 /// Evaluate in any way we know how. Don't worry about side-effects that
968 /// can't be modeled.
969 EM_IgnoreSideEffects,
970 } EvalMode;
972 /// Are we checking whether the expression is a potential constant
973 /// expression?
974 bool checkingPotentialConstantExpression() const override {
975 return CheckingPotentialConstantExpression;
978 /// Are we checking an expression for overflow?
979 // FIXME: We should check for any kind of undefined or suspicious behavior
980 // in such constructs, not just overflow.
981 bool checkingForUndefinedBehavior() const override {
982 return CheckingForUndefinedBehavior;
985 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
986 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
987 CallStackDepth(0), NextCallIndex(1),
988 StepsLeft(C.getLangOpts().ConstexprStepLimit),
989 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
990 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
991 EvaluatingDecl((const ValueDecl *)nullptr),
992 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
993 HasFoldFailureDiagnostic(false), InConstantContext(false),
994 EvalMode(Mode) {}
996 ~EvalInfo() {
997 discardCleanups();
1000 ASTContext &getCtx() const override { return Ctx; }
1002 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1003 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1004 EvaluatingDecl = Base;
1005 IsEvaluatingDecl = EDK;
1006 EvaluatingDeclValue = &Value;
1009 bool CheckCallLimit(SourceLocation Loc) {
1010 // Don't perform any constexpr calls (other than the call we're checking)
1011 // when checking a potential constant expression.
1012 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1013 return false;
1014 if (NextCallIndex == 0) {
1015 // NextCallIndex has wrapped around.
1016 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1017 return false;
1019 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1020 return true;
1021 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1022 << getLangOpts().ConstexprCallDepth;
1023 return false;
1026 std::pair<CallStackFrame *, unsigned>
1027 getCallFrameAndDepth(unsigned CallIndex) {
1028 assert(CallIndex && "no call index in getCallFrameAndDepth");
1029 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1030 // be null in this loop.
1031 unsigned Depth = CallStackDepth;
1032 CallStackFrame *Frame = CurrentCall;
1033 while (Frame->Index > CallIndex) {
1034 Frame = Frame->Caller;
1035 --Depth;
1037 if (Frame->Index == CallIndex)
1038 return {Frame, Depth};
1039 return {nullptr, 0};
1042 bool nextStep(const Stmt *S) {
1043 if (!StepsLeft) {
1044 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1045 return false;
1047 --StepsLeft;
1048 return true;
1051 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1053 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1054 Optional<DynAlloc*> Result;
1055 auto It = HeapAllocs.find(DA);
1056 if (It != HeapAllocs.end())
1057 Result = &It->second;
1058 return Result;
1061 /// Get the allocated storage for the given parameter of the given call.
1062 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1063 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1064 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1065 : nullptr;
1068 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1069 struct StdAllocatorCaller {
1070 unsigned FrameIndex;
1071 QualType ElemType;
1072 explicit operator bool() const { return FrameIndex != 0; };
1075 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1076 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1077 Call = Call->Caller) {
1078 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1079 if (!MD)
1080 continue;
1081 const IdentifierInfo *FnII = MD->getIdentifier();
1082 if (!FnII || !FnII->isStr(FnName))
1083 continue;
1085 const auto *CTSD =
1086 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1087 if (!CTSD)
1088 continue;
1090 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1091 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1092 if (CTSD->isInStdNamespace() && ClassII &&
1093 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1094 TAL[0].getKind() == TemplateArgument::Type)
1095 return {Call->Index, TAL[0].getAsType()};
1098 return {};
1101 void performLifetimeExtension() {
1102 // Disable the cleanups for lifetime-extended temporaries.
1103 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1104 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1108 /// Throw away any remaining cleanups at the end of evaluation. If any
1109 /// cleanups would have had a side-effect, note that as an unmodeled
1110 /// side-effect and return false. Otherwise, return true.
1111 bool discardCleanups() {
1112 for (Cleanup &C : CleanupStack) {
1113 if (C.hasSideEffect() && !noteSideEffect()) {
1114 CleanupStack.clear();
1115 return false;
1118 CleanupStack.clear();
1119 return true;
1122 private:
1123 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1124 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1126 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1127 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1129 void setFoldFailureDiagnostic(bool Flag) override {
1130 HasFoldFailureDiagnostic = Flag;
1133 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1135 // If we have a prior diagnostic, it will be noting that the expression
1136 // isn't a constant expression. This diagnostic is more important,
1137 // unless we require this evaluation to produce a constant expression.
1139 // FIXME: We might want to show both diagnostics to the user in
1140 // EM_ConstantFold mode.
1141 bool hasPriorDiagnostic() override {
1142 if (!EvalStatus.Diag->empty()) {
1143 switch (EvalMode) {
1144 case EM_ConstantFold:
1145 case EM_IgnoreSideEffects:
1146 if (!HasFoldFailureDiagnostic)
1147 break;
1148 // We've already failed to fold something. Keep that diagnostic.
1149 [[fallthrough]];
1150 case EM_ConstantExpression:
1151 case EM_ConstantExpressionUnevaluated:
1152 setActiveDiagnostic(false);
1153 return true;
1156 return false;
1159 unsigned getCallStackDepth() override { return CallStackDepth; }
1161 public:
1162 /// Should we continue evaluation after encountering a side-effect that we
1163 /// couldn't model?
1164 bool keepEvaluatingAfterSideEffect() {
1165 switch (EvalMode) {
1166 case EM_IgnoreSideEffects:
1167 return true;
1169 case EM_ConstantExpression:
1170 case EM_ConstantExpressionUnevaluated:
1171 case EM_ConstantFold:
1172 // By default, assume any side effect might be valid in some other
1173 // evaluation of this expression from a different context.
1174 return checkingPotentialConstantExpression() ||
1175 checkingForUndefinedBehavior();
1177 llvm_unreachable("Missed EvalMode case");
1180 /// Note that we have had a side-effect, and determine whether we should
1181 /// keep evaluating.
1182 bool noteSideEffect() {
1183 EvalStatus.HasSideEffects = true;
1184 return keepEvaluatingAfterSideEffect();
1187 /// Should we continue evaluation after encountering undefined behavior?
1188 bool keepEvaluatingAfterUndefinedBehavior() {
1189 switch (EvalMode) {
1190 case EM_IgnoreSideEffects:
1191 case EM_ConstantFold:
1192 return true;
1194 case EM_ConstantExpression:
1195 case EM_ConstantExpressionUnevaluated:
1196 return checkingForUndefinedBehavior();
1198 llvm_unreachable("Missed EvalMode case");
1201 /// Note that we hit something that was technically undefined behavior, but
1202 /// that we can evaluate past it (such as signed overflow or floating-point
1203 /// division by zero.)
1204 bool noteUndefinedBehavior() override {
1205 EvalStatus.HasUndefinedBehavior = true;
1206 return keepEvaluatingAfterUndefinedBehavior();
1209 /// Should we continue evaluation as much as possible after encountering a
1210 /// construct which can't be reduced to a value?
1211 bool keepEvaluatingAfterFailure() const override {
1212 if (!StepsLeft)
1213 return false;
1215 switch (EvalMode) {
1216 case EM_ConstantExpression:
1217 case EM_ConstantExpressionUnevaluated:
1218 case EM_ConstantFold:
1219 case EM_IgnoreSideEffects:
1220 return checkingPotentialConstantExpression() ||
1221 checkingForUndefinedBehavior();
1223 llvm_unreachable("Missed EvalMode case");
1226 /// Notes that we failed to evaluate an expression that other expressions
1227 /// directly depend on, and determine if we should keep evaluating. This
1228 /// should only be called if we actually intend to keep evaluating.
1230 /// Call noteSideEffect() instead if we may be able to ignore the value that
1231 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1233 /// (Foo(), 1) // use noteSideEffect
1234 /// (Foo() || true) // use noteSideEffect
1235 /// Foo() + 1 // use noteFailure
1236 [[nodiscard]] bool noteFailure() {
1237 // Failure when evaluating some expression often means there is some
1238 // subexpression whose evaluation was skipped. Therefore, (because we
1239 // don't track whether we skipped an expression when unwinding after an
1240 // evaluation failure) every evaluation failure that bubbles up from a
1241 // subexpression implies that a side-effect has potentially happened. We
1242 // skip setting the HasSideEffects flag to true until we decide to
1243 // continue evaluating after that point, which happens here.
1244 bool KeepGoing = keepEvaluatingAfterFailure();
1245 EvalStatus.HasSideEffects |= KeepGoing;
1246 return KeepGoing;
1249 class ArrayInitLoopIndex {
1250 EvalInfo &Info;
1251 uint64_t OuterIndex;
1253 public:
1254 ArrayInitLoopIndex(EvalInfo &Info)
1255 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1256 Info.ArrayInitIndex = 0;
1258 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1260 operator uint64_t&() { return Info.ArrayInitIndex; }
1264 /// Object used to treat all foldable expressions as constant expressions.
1265 struct FoldConstant {
1266 EvalInfo &Info;
1267 bool Enabled;
1268 bool HadNoPriorDiags;
1269 EvalInfo::EvaluationMode OldMode;
1271 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1272 : Info(Info),
1273 Enabled(Enabled),
1274 HadNoPriorDiags(Info.EvalStatus.Diag &&
1275 Info.EvalStatus.Diag->empty() &&
1276 !Info.EvalStatus.HasSideEffects),
1277 OldMode(Info.EvalMode) {
1278 if (Enabled)
1279 Info.EvalMode = EvalInfo::EM_ConstantFold;
1281 void keepDiagnostics() { Enabled = false; }
1282 ~FoldConstant() {
1283 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1284 !Info.EvalStatus.HasSideEffects)
1285 Info.EvalStatus.Diag->clear();
1286 Info.EvalMode = OldMode;
1290 /// RAII object used to set the current evaluation mode to ignore
1291 /// side-effects.
1292 struct IgnoreSideEffectsRAII {
1293 EvalInfo &Info;
1294 EvalInfo::EvaluationMode OldMode;
1295 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1296 : Info(Info), OldMode(Info.EvalMode) {
1297 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1300 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1303 /// RAII object used to optionally suppress diagnostics and side-effects from
1304 /// a speculative evaluation.
1305 class SpeculativeEvaluationRAII {
1306 EvalInfo *Info = nullptr;
1307 Expr::EvalStatus OldStatus;
1308 unsigned OldSpeculativeEvaluationDepth;
1310 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1311 Info = Other.Info;
1312 OldStatus = Other.OldStatus;
1313 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1314 Other.Info = nullptr;
1317 void maybeRestoreState() {
1318 if (!Info)
1319 return;
1321 Info->EvalStatus = OldStatus;
1322 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1325 public:
1326 SpeculativeEvaluationRAII() = default;
1328 SpeculativeEvaluationRAII(
1329 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1330 : Info(&Info), OldStatus(Info.EvalStatus),
1331 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1332 Info.EvalStatus.Diag = NewDiag;
1333 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1336 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1337 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1338 moveFromAndCancel(std::move(Other));
1341 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1342 maybeRestoreState();
1343 moveFromAndCancel(std::move(Other));
1344 return *this;
1347 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1350 /// RAII object wrapping a full-expression or block scope, and handling
1351 /// the ending of the lifetime of temporaries created within it.
1352 template<ScopeKind Kind>
1353 class ScopeRAII {
1354 EvalInfo &Info;
1355 unsigned OldStackSize;
1356 public:
1357 ScopeRAII(EvalInfo &Info)
1358 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1359 // Push a new temporary version. This is needed to distinguish between
1360 // temporaries created in different iterations of a loop.
1361 Info.CurrentCall->pushTempVersion();
1363 bool destroy(bool RunDestructors = true) {
1364 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1365 OldStackSize = -1U;
1366 return OK;
1368 ~ScopeRAII() {
1369 if (OldStackSize != -1U)
1370 destroy(false);
1371 // Body moved to a static method to encourage the compiler to inline away
1372 // instances of this class.
1373 Info.CurrentCall->popTempVersion();
1375 private:
1376 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1377 unsigned OldStackSize) {
1378 assert(OldStackSize <= Info.CleanupStack.size() &&
1379 "running cleanups out of order?");
1381 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1382 // for a full-expression scope.
1383 bool Success = true;
1384 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1385 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1386 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1387 Success = false;
1388 break;
1393 // Compact any retained cleanups.
1394 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1395 if (Kind != ScopeKind::Block)
1396 NewEnd =
1397 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1398 return C.isDestroyedAtEndOf(Kind);
1400 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1401 return Success;
1404 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1405 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1406 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1409 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1410 CheckSubobjectKind CSK) {
1411 if (Invalid)
1412 return false;
1413 if (isOnePastTheEnd()) {
1414 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1415 << CSK;
1416 setInvalid();
1417 return false;
1419 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1420 // must actually be at least one array element; even a VLA cannot have a
1421 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1422 return true;
1425 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1426 const Expr *E) {
1427 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1428 // Do not set the designator as invalid: we can represent this situation,
1429 // and correct handling of __builtin_object_size requires us to do so.
1432 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1433 const Expr *E,
1434 const APSInt &N) {
1435 // If we're complaining, we must be able to statically determine the size of
1436 // the most derived array.
1437 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1438 Info.CCEDiag(E, diag::note_constexpr_array_index)
1439 << N << /*array*/ 0
1440 << static_cast<unsigned>(getMostDerivedArraySize());
1441 else
1442 Info.CCEDiag(E, diag::note_constexpr_array_index)
1443 << N << /*non-array*/ 1;
1444 setInvalid();
1447 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1448 const FunctionDecl *Callee, const LValue *This,
1449 CallRef Call)
1450 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1451 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1452 Info.CurrentCall = this;
1453 ++Info.CallStackDepth;
1456 CallStackFrame::~CallStackFrame() {
1457 assert(Info.CurrentCall == this && "calls retired out of order");
1458 --Info.CallStackDepth;
1459 Info.CurrentCall = Caller;
1462 static bool isRead(AccessKinds AK) {
1463 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1466 static bool isModification(AccessKinds AK) {
1467 switch (AK) {
1468 case AK_Read:
1469 case AK_ReadObjectRepresentation:
1470 case AK_MemberCall:
1471 case AK_DynamicCast:
1472 case AK_TypeId:
1473 return false;
1474 case AK_Assign:
1475 case AK_Increment:
1476 case AK_Decrement:
1477 case AK_Construct:
1478 case AK_Destroy:
1479 return true;
1481 llvm_unreachable("unknown access kind");
1484 static bool isAnyAccess(AccessKinds AK) {
1485 return isRead(AK) || isModification(AK);
1488 /// Is this an access per the C++ definition?
1489 static bool isFormalAccess(AccessKinds AK) {
1490 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1493 /// Is this kind of axcess valid on an indeterminate object value?
1494 static bool isValidIndeterminateAccess(AccessKinds AK) {
1495 switch (AK) {
1496 case AK_Read:
1497 case AK_Increment:
1498 case AK_Decrement:
1499 // These need the object's value.
1500 return false;
1502 case AK_ReadObjectRepresentation:
1503 case AK_Assign:
1504 case AK_Construct:
1505 case AK_Destroy:
1506 // Construction and destruction don't need the value.
1507 return true;
1509 case AK_MemberCall:
1510 case AK_DynamicCast:
1511 case AK_TypeId:
1512 // These aren't really meaningful on scalars.
1513 return true;
1515 llvm_unreachable("unknown access kind");
1518 namespace {
1519 struct ComplexValue {
1520 private:
1521 bool IsInt;
1523 public:
1524 APSInt IntReal, IntImag;
1525 APFloat FloatReal, FloatImag;
1527 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1529 void makeComplexFloat() { IsInt = false; }
1530 bool isComplexFloat() const { return !IsInt; }
1531 APFloat &getComplexFloatReal() { return FloatReal; }
1532 APFloat &getComplexFloatImag() { return FloatImag; }
1534 void makeComplexInt() { IsInt = true; }
1535 bool isComplexInt() const { return IsInt; }
1536 APSInt &getComplexIntReal() { return IntReal; }
1537 APSInt &getComplexIntImag() { return IntImag; }
1539 void moveInto(APValue &v) const {
1540 if (isComplexFloat())
1541 v = APValue(FloatReal, FloatImag);
1542 else
1543 v = APValue(IntReal, IntImag);
1545 void setFrom(const APValue &v) {
1546 assert(v.isComplexFloat() || v.isComplexInt());
1547 if (v.isComplexFloat()) {
1548 makeComplexFloat();
1549 FloatReal = v.getComplexFloatReal();
1550 FloatImag = v.getComplexFloatImag();
1551 } else {
1552 makeComplexInt();
1553 IntReal = v.getComplexIntReal();
1554 IntImag = v.getComplexIntImag();
1559 struct LValue {
1560 APValue::LValueBase Base;
1561 CharUnits Offset;
1562 SubobjectDesignator Designator;
1563 bool IsNullPtr : 1;
1564 bool InvalidBase : 1;
1566 const APValue::LValueBase getLValueBase() const { return Base; }
1567 CharUnits &getLValueOffset() { return Offset; }
1568 const CharUnits &getLValueOffset() const { return Offset; }
1569 SubobjectDesignator &getLValueDesignator() { return Designator; }
1570 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1571 bool isNullPointer() const { return IsNullPtr;}
1573 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1574 unsigned getLValueVersion() const { return Base.getVersion(); }
1576 void moveInto(APValue &V) const {
1577 if (Designator.Invalid)
1578 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1579 else {
1580 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1581 V = APValue(Base, Offset, Designator.Entries,
1582 Designator.IsOnePastTheEnd, IsNullPtr);
1585 void setFrom(ASTContext &Ctx, const APValue &V) {
1586 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1587 Base = V.getLValueBase();
1588 Offset = V.getLValueOffset();
1589 InvalidBase = false;
1590 Designator = SubobjectDesignator(Ctx, V);
1591 IsNullPtr = V.isNullPointer();
1594 void set(APValue::LValueBase B, bool BInvalid = false) {
1595 #ifndef NDEBUG
1596 // We only allow a few types of invalid bases. Enforce that here.
1597 if (BInvalid) {
1598 const auto *E = B.get<const Expr *>();
1599 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1600 "Unexpected type of invalid base");
1602 #endif
1604 Base = B;
1605 Offset = CharUnits::fromQuantity(0);
1606 InvalidBase = BInvalid;
1607 Designator = SubobjectDesignator(getType(B));
1608 IsNullPtr = false;
1611 void setNull(ASTContext &Ctx, QualType PointerTy) {
1612 Base = (const ValueDecl *)nullptr;
1613 Offset =
1614 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1615 InvalidBase = false;
1616 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1617 IsNullPtr = true;
1620 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1621 set(B, true);
1624 std::string toString(ASTContext &Ctx, QualType T) const {
1625 APValue Printable;
1626 moveInto(Printable);
1627 return Printable.getAsString(Ctx, T);
1630 private:
1631 // Check that this LValue is not based on a null pointer. If it is, produce
1632 // a diagnostic and mark the designator as invalid.
1633 template <typename GenDiagType>
1634 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1635 if (Designator.Invalid)
1636 return false;
1637 if (IsNullPtr) {
1638 GenDiag();
1639 Designator.setInvalid();
1640 return false;
1642 return true;
1645 public:
1646 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1647 CheckSubobjectKind CSK) {
1648 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1649 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1653 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1654 AccessKinds AK) {
1655 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1656 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1660 // Check this LValue refers to an object. If not, set the designator to be
1661 // invalid and emit a diagnostic.
1662 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1663 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1664 Designator.checkSubobject(Info, E, CSK);
1667 void addDecl(EvalInfo &Info, const Expr *E,
1668 const Decl *D, bool Virtual = false) {
1669 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1670 Designator.addDeclUnchecked(D, Virtual);
1672 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1673 if (!Designator.Entries.empty()) {
1674 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1675 Designator.setInvalid();
1676 return;
1678 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1679 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1680 Designator.FirstEntryIsAnUnsizedArray = true;
1681 Designator.addUnsizedArrayUnchecked(ElemTy);
1684 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1685 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1686 Designator.addArrayUnchecked(CAT);
1688 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1689 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1690 Designator.addComplexUnchecked(EltTy, Imag);
1692 void clearIsNullPointer() {
1693 IsNullPtr = false;
1695 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1696 const APSInt &Index, CharUnits ElementSize) {
1697 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1698 // but we're not required to diagnose it and it's valid in C++.)
1699 if (!Index)
1700 return;
1702 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1703 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1704 // offsets.
1705 uint64_t Offset64 = Offset.getQuantity();
1706 uint64_t ElemSize64 = ElementSize.getQuantity();
1707 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1708 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1710 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1711 Designator.adjustIndex(Info, E, Index);
1712 clearIsNullPointer();
1714 void adjustOffset(CharUnits N) {
1715 Offset += N;
1716 if (N.getQuantity())
1717 clearIsNullPointer();
1721 struct MemberPtr {
1722 MemberPtr() {}
1723 explicit MemberPtr(const ValueDecl *Decl)
1724 : DeclAndIsDerivedMember(Decl, false) {}
1726 /// The member or (direct or indirect) field referred to by this member
1727 /// pointer, or 0 if this is a null member pointer.
1728 const ValueDecl *getDecl() const {
1729 return DeclAndIsDerivedMember.getPointer();
1731 /// Is this actually a member of some type derived from the relevant class?
1732 bool isDerivedMember() const {
1733 return DeclAndIsDerivedMember.getInt();
1735 /// Get the class which the declaration actually lives in.
1736 const CXXRecordDecl *getContainingRecord() const {
1737 return cast<CXXRecordDecl>(
1738 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1741 void moveInto(APValue &V) const {
1742 V = APValue(getDecl(), isDerivedMember(), Path);
1744 void setFrom(const APValue &V) {
1745 assert(V.isMemberPointer());
1746 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1747 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1748 Path.clear();
1749 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1750 Path.insert(Path.end(), P.begin(), P.end());
1753 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1754 /// whether the member is a member of some class derived from the class type
1755 /// of the member pointer.
1756 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1757 /// Path - The path of base/derived classes from the member declaration's
1758 /// class (exclusive) to the class type of the member pointer (inclusive).
1759 SmallVector<const CXXRecordDecl*, 4> Path;
1761 /// Perform a cast towards the class of the Decl (either up or down the
1762 /// hierarchy).
1763 bool castBack(const CXXRecordDecl *Class) {
1764 assert(!Path.empty());
1765 const CXXRecordDecl *Expected;
1766 if (Path.size() >= 2)
1767 Expected = Path[Path.size() - 2];
1768 else
1769 Expected = getContainingRecord();
1770 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1771 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1772 // if B does not contain the original member and is not a base or
1773 // derived class of the class containing the original member, the result
1774 // of the cast is undefined.
1775 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1776 // (D::*). We consider that to be a language defect.
1777 return false;
1779 Path.pop_back();
1780 return true;
1782 /// Perform a base-to-derived member pointer cast.
1783 bool castToDerived(const CXXRecordDecl *Derived) {
1784 if (!getDecl())
1785 return true;
1786 if (!isDerivedMember()) {
1787 Path.push_back(Derived);
1788 return true;
1790 if (!castBack(Derived))
1791 return false;
1792 if (Path.empty())
1793 DeclAndIsDerivedMember.setInt(false);
1794 return true;
1796 /// Perform a derived-to-base member pointer cast.
1797 bool castToBase(const CXXRecordDecl *Base) {
1798 if (!getDecl())
1799 return true;
1800 if (Path.empty())
1801 DeclAndIsDerivedMember.setInt(true);
1802 if (isDerivedMember()) {
1803 Path.push_back(Base);
1804 return true;
1806 return castBack(Base);
1810 /// Compare two member pointers, which are assumed to be of the same type.
1811 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1812 if (!LHS.getDecl() || !RHS.getDecl())
1813 return !LHS.getDecl() && !RHS.getDecl();
1814 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1815 return false;
1816 return LHS.Path == RHS.Path;
1820 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1821 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1822 const LValue &This, const Expr *E,
1823 bool AllowNonLiteralTypes = false);
1824 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1825 bool InvalidBaseOK = false);
1826 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1827 bool InvalidBaseOK = false);
1828 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1829 EvalInfo &Info);
1830 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1831 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1832 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1833 EvalInfo &Info);
1834 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1835 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1836 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1837 EvalInfo &Info);
1838 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1839 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1840 EvalInfo &Info);
1842 /// Evaluate an integer or fixed point expression into an APResult.
1843 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1844 EvalInfo &Info);
1846 /// Evaluate only a fixed point expression into an APResult.
1847 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1848 EvalInfo &Info);
1850 //===----------------------------------------------------------------------===//
1851 // Misc utilities
1852 //===----------------------------------------------------------------------===//
1854 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1855 /// preserving its value (by extending by up to one bit as needed).
1856 static void negateAsSigned(APSInt &Int) {
1857 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1858 Int = Int.extend(Int.getBitWidth() + 1);
1859 Int.setIsSigned(true);
1861 Int = -Int;
1864 template<typename KeyT>
1865 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1866 ScopeKind Scope, LValue &LV) {
1867 unsigned Version = getTempVersion();
1868 APValue::LValueBase Base(Key, Index, Version);
1869 LV.set(Base);
1870 return createLocal(Base, Key, T, Scope);
1873 /// Allocate storage for a parameter of a function call made in this frame.
1874 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1875 LValue &LV) {
1876 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1877 APValue::LValueBase Base(PVD, Index, Args.Version);
1878 LV.set(Base);
1879 // We always destroy parameters at the end of the call, even if we'd allow
1880 // them to live to the end of the full-expression at runtime, in order to
1881 // give portable results and match other compilers.
1882 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1885 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1886 QualType T, ScopeKind Scope) {
1887 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1888 unsigned Version = Base.getVersion();
1889 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1890 assert(Result.isAbsent() && "local created multiple times");
1892 // If we're creating a local immediately in the operand of a speculative
1893 // evaluation, don't register a cleanup to be run outside the speculative
1894 // evaluation context, since we won't actually be able to initialize this
1895 // object.
1896 if (Index <= Info.SpeculativeEvaluationDepth) {
1897 if (T.isDestructedType())
1898 Info.noteSideEffect();
1899 } else {
1900 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1902 return Result;
1905 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1906 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1907 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1908 return nullptr;
1911 DynamicAllocLValue DA(NumHeapAllocs++);
1912 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1913 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1914 std::forward_as_tuple(DA), std::tuple<>());
1915 assert(Result.second && "reused a heap alloc index?");
1916 Result.first->second.AllocExpr = E;
1917 return &Result.first->second.Value;
1920 /// Produce a string describing the given constexpr call.
1921 void CallStackFrame::describe(raw_ostream &Out) {
1922 unsigned ArgIndex = 0;
1923 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1924 !isa<CXXConstructorDecl>(Callee) &&
1925 cast<CXXMethodDecl>(Callee)->isInstance();
1927 if (!IsMemberCall)
1928 Out << *Callee << '(';
1930 if (This && IsMemberCall) {
1931 APValue Val;
1932 This->moveInto(Val);
1933 Val.printPretty(Out, Info.Ctx,
1934 This->Designator.MostDerivedType);
1935 // FIXME: Add parens around Val if needed.
1936 Out << "->" << *Callee << '(';
1937 IsMemberCall = false;
1940 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1941 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1942 if (ArgIndex > (unsigned)IsMemberCall)
1943 Out << ", ";
1945 const ParmVarDecl *Param = *I;
1946 APValue *V = Info.getParamSlot(Arguments, Param);
1947 if (V)
1948 V->printPretty(Out, Info.Ctx, Param->getType());
1949 else
1950 Out << "<...>";
1952 if (ArgIndex == 0 && IsMemberCall)
1953 Out << "->" << *Callee << '(';
1956 Out << ')';
1959 /// Evaluate an expression to see if it had side-effects, and discard its
1960 /// result.
1961 /// \return \c true if the caller should keep evaluating.
1962 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1963 assert(!E->isValueDependent());
1964 APValue Scratch;
1965 if (!Evaluate(Scratch, Info, E))
1966 // We don't need the value, but we might have skipped a side effect here.
1967 return Info.noteSideEffect();
1968 return true;
1971 /// Should this call expression be treated as a no-op?
1972 static bool IsNoOpCall(const CallExpr *E) {
1973 unsigned Builtin = E->getBuiltinCallee();
1974 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1975 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1976 Builtin == Builtin::BI__builtin_function_start);
1979 static bool IsGlobalLValue(APValue::LValueBase B) {
1980 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1981 // constant expression of pointer type that evaluates to...
1983 // ... a null pointer value, or a prvalue core constant expression of type
1984 // std::nullptr_t.
1985 if (!B) return true;
1987 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1988 // ... the address of an object with static storage duration,
1989 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1990 return VD->hasGlobalStorage();
1991 if (isa<TemplateParamObjectDecl>(D))
1992 return true;
1993 // ... the address of a function,
1994 // ... the address of a GUID [MS extension],
1995 // ... the address of an unnamed global constant
1996 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1999 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2000 return true;
2002 const Expr *E = B.get<const Expr*>();
2003 switch (E->getStmtClass()) {
2004 default:
2005 return false;
2006 case Expr::CompoundLiteralExprClass: {
2007 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2008 return CLE->isFileScope() && CLE->isLValue();
2010 case Expr::MaterializeTemporaryExprClass:
2011 // A materialized temporary might have been lifetime-extended to static
2012 // storage duration.
2013 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2014 // A string literal has static storage duration.
2015 case Expr::StringLiteralClass:
2016 case Expr::PredefinedExprClass:
2017 case Expr::ObjCStringLiteralClass:
2018 case Expr::ObjCEncodeExprClass:
2019 return true;
2020 case Expr::ObjCBoxedExprClass:
2021 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2022 case Expr::CallExprClass:
2023 return IsNoOpCall(cast<CallExpr>(E));
2024 // For GCC compatibility, &&label has static storage duration.
2025 case Expr::AddrLabelExprClass:
2026 return true;
2027 // A Block literal expression may be used as the initialization value for
2028 // Block variables at global or local static scope.
2029 case Expr::BlockExprClass:
2030 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2031 // The APValue generated from a __builtin_source_location will be emitted as a
2032 // literal.
2033 case Expr::SourceLocExprClass:
2034 return true;
2035 case Expr::ImplicitValueInitExprClass:
2036 // FIXME:
2037 // We can never form an lvalue with an implicit value initialization as its
2038 // base through expression evaluation, so these only appear in one case: the
2039 // implicit variable declaration we invent when checking whether a constexpr
2040 // constructor can produce a constant expression. We must assume that such
2041 // an expression might be a global lvalue.
2042 return true;
2046 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2047 return LVal.Base.dyn_cast<const ValueDecl*>();
2050 static bool IsLiteralLValue(const LValue &Value) {
2051 if (Value.getLValueCallIndex())
2052 return false;
2053 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2054 return E && !isa<MaterializeTemporaryExpr>(E);
2057 static bool IsWeakLValue(const LValue &Value) {
2058 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2059 return Decl && Decl->isWeak();
2062 static bool isZeroSized(const LValue &Value) {
2063 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2064 if (Decl && isa<VarDecl>(Decl)) {
2065 QualType Ty = Decl->getType();
2066 if (Ty->isArrayType())
2067 return Ty->isIncompleteType() ||
2068 Decl->getASTContext().getTypeSize(Ty) == 0;
2070 return false;
2073 static bool HasSameBase(const LValue &A, const LValue &B) {
2074 if (!A.getLValueBase())
2075 return !B.getLValueBase();
2076 if (!B.getLValueBase())
2077 return false;
2079 if (A.getLValueBase().getOpaqueValue() !=
2080 B.getLValueBase().getOpaqueValue())
2081 return false;
2083 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2084 A.getLValueVersion() == B.getLValueVersion();
2087 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2088 assert(Base && "no location for a null lvalue");
2089 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2091 // For a parameter, find the corresponding call stack frame (if it still
2092 // exists), and point at the parameter of the function definition we actually
2093 // invoked.
2094 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2095 unsigned Idx = PVD->getFunctionScopeIndex();
2096 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2097 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2098 F->Arguments.Version == Base.getVersion() && F->Callee &&
2099 Idx < F->Callee->getNumParams()) {
2100 VD = F->Callee->getParamDecl(Idx);
2101 break;
2106 if (VD)
2107 Info.Note(VD->getLocation(), diag::note_declared_at);
2108 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2109 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2110 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2111 // FIXME: Produce a note for dangling pointers too.
2112 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2113 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2114 diag::note_constexpr_dynamic_alloc_here);
2116 // We have no information to show for a typeid(T) object.
2119 enum class CheckEvaluationResultKind {
2120 ConstantExpression,
2121 FullyInitialized,
2124 /// Materialized temporaries that we've already checked to determine if they're
2125 /// initializsed by a constant expression.
2126 using CheckedTemporaries =
2127 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2129 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2130 EvalInfo &Info, SourceLocation DiagLoc,
2131 QualType Type, const APValue &Value,
2132 ConstantExprKind Kind,
2133 SourceLocation SubobjectLoc,
2134 CheckedTemporaries &CheckedTemps);
2136 /// Check that this reference or pointer core constant expression is a valid
2137 /// value for an address or reference constant expression. Return true if we
2138 /// can fold this expression, whether or not it's a constant expression.
2139 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2140 QualType Type, const LValue &LVal,
2141 ConstantExprKind Kind,
2142 CheckedTemporaries &CheckedTemps) {
2143 bool IsReferenceType = Type->isReferenceType();
2145 APValue::LValueBase Base = LVal.getLValueBase();
2146 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2148 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2149 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2151 // Additional restrictions apply in a template argument. We only enforce the
2152 // C++20 restrictions here; additional syntactic and semantic restrictions
2153 // are applied elsewhere.
2154 if (isTemplateArgument(Kind)) {
2155 int InvalidBaseKind = -1;
2156 StringRef Ident;
2157 if (Base.is<TypeInfoLValue>())
2158 InvalidBaseKind = 0;
2159 else if (isa_and_nonnull<StringLiteral>(BaseE))
2160 InvalidBaseKind = 1;
2161 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2162 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2163 InvalidBaseKind = 2;
2164 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2165 InvalidBaseKind = 3;
2166 Ident = PE->getIdentKindName();
2169 if (InvalidBaseKind != -1) {
2170 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2171 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2172 << Ident;
2173 return false;
2177 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2178 if (FD->isConsteval()) {
2179 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2180 << !Type->isAnyPointerType();
2181 Info.Note(FD->getLocation(), diag::note_declared_at);
2182 return false;
2186 // Check that the object is a global. Note that the fake 'this' object we
2187 // manufacture when checking potential constant expressions is conservatively
2188 // assumed to be global here.
2189 if (!IsGlobalLValue(Base)) {
2190 if (Info.getLangOpts().CPlusPlus11) {
2191 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2192 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2193 << BaseVD;
2194 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2195 if (VarD && VarD->isConstexpr()) {
2196 // Non-static local constexpr variables have unintuitive semantics:
2197 // constexpr int a = 1;
2198 // constexpr const int *p = &a;
2199 // ... is invalid because the address of 'a' is not constant. Suggest
2200 // adding a 'static' in this case.
2201 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2202 << VarD
2203 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2204 } else {
2205 NoteLValueLocation(Info, Base);
2207 } else {
2208 Info.FFDiag(Loc);
2210 // Don't allow references to temporaries to escape.
2211 return false;
2213 assert((Info.checkingPotentialConstantExpression() ||
2214 LVal.getLValueCallIndex() == 0) &&
2215 "have call index for global lvalue");
2217 if (Base.is<DynamicAllocLValue>()) {
2218 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2219 << IsReferenceType << !Designator.Entries.empty();
2220 NoteLValueLocation(Info, Base);
2221 return false;
2224 if (BaseVD) {
2225 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2226 // Check if this is a thread-local variable.
2227 if (Var->getTLSKind())
2228 // FIXME: Diagnostic!
2229 return false;
2231 // A dllimport variable never acts like a constant, unless we're
2232 // evaluating a value for use only in name mangling.
2233 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2234 // FIXME: Diagnostic!
2235 return false;
2237 // In CUDA/HIP device compilation, only device side variables have
2238 // constant addresses.
2239 if (Info.getCtx().getLangOpts().CUDA &&
2240 Info.getCtx().getLangOpts().CUDAIsDevice &&
2241 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2242 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2243 !Var->hasAttr<CUDAConstantAttr>() &&
2244 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2245 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2246 Var->hasAttr<HIPManagedAttr>())
2247 return false;
2250 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2251 // __declspec(dllimport) must be handled very carefully:
2252 // We must never initialize an expression with the thunk in C++.
2253 // Doing otherwise would allow the same id-expression to yield
2254 // different addresses for the same function in different translation
2255 // units. However, this means that we must dynamically initialize the
2256 // expression with the contents of the import address table at runtime.
2258 // The C language has no notion of ODR; furthermore, it has no notion of
2259 // dynamic initialization. This means that we are permitted to
2260 // perform initialization with the address of the thunk.
2261 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2262 FD->hasAttr<DLLImportAttr>())
2263 // FIXME: Diagnostic!
2264 return false;
2266 } else if (const auto *MTE =
2267 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2268 if (CheckedTemps.insert(MTE).second) {
2269 QualType TempType = getType(Base);
2270 if (TempType.isDestructedType()) {
2271 Info.FFDiag(MTE->getExprLoc(),
2272 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2273 << TempType;
2274 return false;
2277 APValue *V = MTE->getOrCreateValue(false);
2278 assert(V && "evasluation result refers to uninitialised temporary");
2279 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2280 Info, MTE->getExprLoc(), TempType, *V,
2281 Kind, SourceLocation(), CheckedTemps))
2282 return false;
2286 // Allow address constant expressions to be past-the-end pointers. This is
2287 // an extension: the standard requires them to point to an object.
2288 if (!IsReferenceType)
2289 return true;
2291 // A reference constant expression must refer to an object.
2292 if (!Base) {
2293 // FIXME: diagnostic
2294 Info.CCEDiag(Loc);
2295 return true;
2298 // Does this refer one past the end of some object?
2299 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2300 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2301 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2302 NoteLValueLocation(Info, Base);
2305 return true;
2308 /// Member pointers are constant expressions unless they point to a
2309 /// non-virtual dllimport member function.
2310 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2311 SourceLocation Loc,
2312 QualType Type,
2313 const APValue &Value,
2314 ConstantExprKind Kind) {
2315 const ValueDecl *Member = Value.getMemberPointerDecl();
2316 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2317 if (!FD)
2318 return true;
2319 if (FD->isConsteval()) {
2320 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2321 Info.Note(FD->getLocation(), diag::note_declared_at);
2322 return false;
2324 return isForManglingOnly(Kind) || FD->isVirtual() ||
2325 !FD->hasAttr<DLLImportAttr>();
2328 /// Check that this core constant expression is of literal type, and if not,
2329 /// produce an appropriate diagnostic.
2330 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2331 const LValue *This = nullptr) {
2332 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2333 return true;
2335 // C++1y: A constant initializer for an object o [...] may also invoke
2336 // constexpr constructors for o and its subobjects even if those objects
2337 // are of non-literal class types.
2339 // C++11 missed this detail for aggregates, so classes like this:
2340 // struct foo_t { union { int i; volatile int j; } u; };
2341 // are not (obviously) initializable like so:
2342 // __attribute__((__require_constant_initialization__))
2343 // static const foo_t x = {{0}};
2344 // because "i" is a subobject with non-literal initialization (due to the
2345 // volatile member of the union). See:
2346 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2347 // Therefore, we use the C++1y behavior.
2348 if (This && Info.EvaluatingDecl == This->getLValueBase())
2349 return true;
2351 // Prvalue constant expressions must be of literal types.
2352 if (Info.getLangOpts().CPlusPlus11)
2353 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2354 << E->getType();
2355 else
2356 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2357 return false;
2360 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2361 EvalInfo &Info, SourceLocation DiagLoc,
2362 QualType Type, const APValue &Value,
2363 ConstantExprKind Kind,
2364 SourceLocation SubobjectLoc,
2365 CheckedTemporaries &CheckedTemps) {
2366 if (!Value.hasValue()) {
2367 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2368 << true << Type;
2369 if (SubobjectLoc.isValid())
2370 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2371 return false;
2374 // We allow _Atomic(T) to be initialized from anything that T can be
2375 // initialized from.
2376 if (const AtomicType *AT = Type->getAs<AtomicType>())
2377 Type = AT->getValueType();
2379 // Core issue 1454: For a literal constant expression of array or class type,
2380 // each subobject of its value shall have been initialized by a constant
2381 // expression.
2382 if (Value.isArray()) {
2383 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2384 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2385 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2386 Value.getArrayInitializedElt(I), Kind,
2387 SubobjectLoc, CheckedTemps))
2388 return false;
2390 if (!Value.hasArrayFiller())
2391 return true;
2392 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2393 Value.getArrayFiller(), Kind, SubobjectLoc,
2394 CheckedTemps);
2396 if (Value.isUnion() && Value.getUnionField()) {
2397 return CheckEvaluationResult(
2398 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2399 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2400 CheckedTemps);
2402 if (Value.isStruct()) {
2403 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2404 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2405 unsigned BaseIndex = 0;
2406 for (const CXXBaseSpecifier &BS : CD->bases()) {
2407 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2408 Value.getStructBase(BaseIndex), Kind,
2409 BS.getBeginLoc(), CheckedTemps))
2410 return false;
2411 ++BaseIndex;
2414 for (const auto *I : RD->fields()) {
2415 if (I->isUnnamedBitfield())
2416 continue;
2418 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2419 Value.getStructField(I->getFieldIndex()),
2420 Kind, I->getLocation(), CheckedTemps))
2421 return false;
2425 if (Value.isLValue() &&
2426 CERK == CheckEvaluationResultKind::ConstantExpression) {
2427 LValue LVal;
2428 LVal.setFrom(Info.Ctx, Value);
2429 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2430 CheckedTemps);
2433 if (Value.isMemberPointer() &&
2434 CERK == CheckEvaluationResultKind::ConstantExpression)
2435 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2437 // Everything else is fine.
2438 return true;
2441 /// Check that this core constant expression value is a valid value for a
2442 /// constant expression. If not, report an appropriate diagnostic. Does not
2443 /// check that the expression is of literal type.
2444 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2445 QualType Type, const APValue &Value,
2446 ConstantExprKind Kind) {
2447 // Nothing to check for a constant expression of type 'cv void'.
2448 if (Type->isVoidType())
2449 return true;
2451 CheckedTemporaries CheckedTemps;
2452 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2453 Info, DiagLoc, Type, Value, Kind,
2454 SourceLocation(), CheckedTemps);
2457 /// Check that this evaluated value is fully-initialized and can be loaded by
2458 /// an lvalue-to-rvalue conversion.
2459 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2460 QualType Type, const APValue &Value) {
2461 CheckedTemporaries CheckedTemps;
2462 return CheckEvaluationResult(
2463 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2464 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2467 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2468 /// "the allocated storage is deallocated within the evaluation".
2469 static bool CheckMemoryLeaks(EvalInfo &Info) {
2470 if (!Info.HeapAllocs.empty()) {
2471 // We can still fold to a constant despite a compile-time memory leak,
2472 // so long as the heap allocation isn't referenced in the result (we check
2473 // that in CheckConstantExpression).
2474 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2475 diag::note_constexpr_memory_leak)
2476 << unsigned(Info.HeapAllocs.size() - 1);
2478 return true;
2481 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2482 // A null base expression indicates a null pointer. These are always
2483 // evaluatable, and they are false unless the offset is zero.
2484 if (!Value.getLValueBase()) {
2485 Result = !Value.getLValueOffset().isZero();
2486 return true;
2489 // We have a non-null base. These are generally known to be true, but if it's
2490 // a weak declaration it can be null at runtime.
2491 Result = true;
2492 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2493 return !Decl || !Decl->isWeak();
2496 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2497 switch (Val.getKind()) {
2498 case APValue::None:
2499 case APValue::Indeterminate:
2500 return false;
2501 case APValue::Int:
2502 Result = Val.getInt().getBoolValue();
2503 return true;
2504 case APValue::FixedPoint:
2505 Result = Val.getFixedPoint().getBoolValue();
2506 return true;
2507 case APValue::Float:
2508 Result = !Val.getFloat().isZero();
2509 return true;
2510 case APValue::ComplexInt:
2511 Result = Val.getComplexIntReal().getBoolValue() ||
2512 Val.getComplexIntImag().getBoolValue();
2513 return true;
2514 case APValue::ComplexFloat:
2515 Result = !Val.getComplexFloatReal().isZero() ||
2516 !Val.getComplexFloatImag().isZero();
2517 return true;
2518 case APValue::LValue:
2519 return EvalPointerValueAsBool(Val, Result);
2520 case APValue::MemberPointer:
2521 Result = Val.getMemberPointerDecl();
2522 return true;
2523 case APValue::Vector:
2524 case APValue::Array:
2525 case APValue::Struct:
2526 case APValue::Union:
2527 case APValue::AddrLabelDiff:
2528 return false;
2531 llvm_unreachable("unknown APValue kind");
2534 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2535 EvalInfo &Info) {
2536 assert(!E->isValueDependent());
2537 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2538 APValue Val;
2539 if (!Evaluate(Val, Info, E))
2540 return false;
2541 return HandleConversionToBool(Val, Result);
2544 template<typename T>
2545 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2546 const T &SrcValue, QualType DestType) {
2547 Info.CCEDiag(E, diag::note_constexpr_overflow)
2548 << SrcValue << DestType;
2549 return Info.noteUndefinedBehavior();
2552 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2553 QualType SrcType, const APFloat &Value,
2554 QualType DestType, APSInt &Result) {
2555 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2556 // Determine whether we are converting to unsigned or signed.
2557 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2559 Result = APSInt(DestWidth, !DestSigned);
2560 bool ignored;
2561 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2562 & APFloat::opInvalidOp)
2563 return HandleOverflow(Info, E, Value, DestType);
2564 return true;
2567 /// Get rounding mode to use in evaluation of the specified expression.
2569 /// If rounding mode is unknown at compile time, still try to evaluate the
2570 /// expression. If the result is exact, it does not depend on rounding mode.
2571 /// So return "tonearest" mode instead of "dynamic".
2572 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2573 llvm::RoundingMode RM =
2574 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2575 if (RM == llvm::RoundingMode::Dynamic)
2576 RM = llvm::RoundingMode::NearestTiesToEven;
2577 return RM;
2580 /// Check if the given evaluation result is allowed for constant evaluation.
2581 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2582 APFloat::opStatus St) {
2583 // In a constant context, assume that any dynamic rounding mode or FP
2584 // exception state matches the default floating-point environment.
2585 if (Info.InConstantContext)
2586 return true;
2588 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2589 if ((St & APFloat::opInexact) &&
2590 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2591 // Inexact result means that it depends on rounding mode. If the requested
2592 // mode is dynamic, the evaluation cannot be made in compile time.
2593 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2594 return false;
2597 if ((St != APFloat::opOK) &&
2598 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2599 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2600 FPO.getAllowFEnvAccess())) {
2601 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2602 return false;
2605 if ((St & APFloat::opStatus::opInvalidOp) &&
2606 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2607 // There is no usefully definable result.
2608 Info.FFDiag(E);
2609 return false;
2612 // FIXME: if:
2613 // - evaluation triggered other FP exception, and
2614 // - exception mode is not "ignore", and
2615 // - the expression being evaluated is not a part of global variable
2616 // initializer,
2617 // the evaluation probably need to be rejected.
2618 return true;
2621 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2622 QualType SrcType, QualType DestType,
2623 APFloat &Result) {
2624 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2625 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2626 APFloat::opStatus St;
2627 APFloat Value = Result;
2628 bool ignored;
2629 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2630 return checkFloatingPointResult(Info, E, St);
2633 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2634 QualType DestType, QualType SrcType,
2635 const APSInt &Value) {
2636 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2637 // Figure out if this is a truncate, extend or noop cast.
2638 // If the input is signed, do a sign extend, noop, or truncate.
2639 APSInt Result = Value.extOrTrunc(DestWidth);
2640 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2641 if (DestType->isBooleanType())
2642 Result = Value.getBoolValue();
2643 return Result;
2646 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2647 const FPOptions FPO,
2648 QualType SrcType, const APSInt &Value,
2649 QualType DestType, APFloat &Result) {
2650 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2651 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2652 APFloat::rmNearestTiesToEven);
2653 if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2654 FPO.isFPConstrained()) {
2655 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2656 return false;
2658 return true;
2661 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2662 APValue &Value, const FieldDecl *FD) {
2663 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2665 if (!Value.isInt()) {
2666 // Trying to store a pointer-cast-to-integer into a bitfield.
2667 // FIXME: In this case, we should provide the diagnostic for casting
2668 // a pointer to an integer.
2669 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2670 Info.FFDiag(E);
2671 return false;
2674 APSInt &Int = Value.getInt();
2675 unsigned OldBitWidth = Int.getBitWidth();
2676 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2677 if (NewBitWidth < OldBitWidth)
2678 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2679 return true;
2682 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2683 llvm::APInt &Res) {
2684 APValue SVal;
2685 if (!Evaluate(SVal, Info, E))
2686 return false;
2687 if (SVal.isInt()) {
2688 Res = SVal.getInt();
2689 return true;
2691 if (SVal.isFloat()) {
2692 Res = SVal.getFloat().bitcastToAPInt();
2693 return true;
2695 if (SVal.isVector()) {
2696 QualType VecTy = E->getType();
2697 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2698 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2699 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2700 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2701 Res = llvm::APInt::getZero(VecSize);
2702 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2703 APValue &Elt = SVal.getVectorElt(i);
2704 llvm::APInt EltAsInt;
2705 if (Elt.isInt()) {
2706 EltAsInt = Elt.getInt();
2707 } else if (Elt.isFloat()) {
2708 EltAsInt = Elt.getFloat().bitcastToAPInt();
2709 } else {
2710 // Don't try to handle vectors of anything other than int or float
2711 // (not sure if it's possible to hit this case).
2712 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2713 return false;
2715 unsigned BaseEltSize = EltAsInt.getBitWidth();
2716 if (BigEndian)
2717 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2718 else
2719 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2721 return true;
2723 // Give up if the input isn't an int, float, or vector. For example, we
2724 // reject "(v4i16)(intptr_t)&a".
2725 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2726 return false;
2729 /// Perform the given integer operation, which is known to need at most BitWidth
2730 /// bits, and check for overflow in the original type (if that type was not an
2731 /// unsigned type).
2732 template<typename Operation>
2733 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2734 const APSInt &LHS, const APSInt &RHS,
2735 unsigned BitWidth, Operation Op,
2736 APSInt &Result) {
2737 if (LHS.isUnsigned()) {
2738 Result = Op(LHS, RHS);
2739 return true;
2742 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2743 Result = Value.trunc(LHS.getBitWidth());
2744 if (Result.extend(BitWidth) != Value) {
2745 if (Info.checkingForUndefinedBehavior())
2746 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2747 diag::warn_integer_constant_overflow)
2748 << toString(Result, 10) << E->getType();
2749 return HandleOverflow(Info, E, Value, E->getType());
2751 return true;
2754 /// Perform the given binary integer operation.
2755 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2756 BinaryOperatorKind Opcode, APSInt RHS,
2757 APSInt &Result) {
2758 switch (Opcode) {
2759 default:
2760 Info.FFDiag(E);
2761 return false;
2762 case BO_Mul:
2763 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2764 std::multiplies<APSInt>(), Result);
2765 case BO_Add:
2766 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2767 std::plus<APSInt>(), Result);
2768 case BO_Sub:
2769 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2770 std::minus<APSInt>(), Result);
2771 case BO_And: Result = LHS & RHS; return true;
2772 case BO_Xor: Result = LHS ^ RHS; return true;
2773 case BO_Or: Result = LHS | RHS; return true;
2774 case BO_Div:
2775 case BO_Rem:
2776 if (RHS == 0) {
2777 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2778 return false;
2780 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2781 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2782 // this operation and gives the two's complement result.
2783 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2784 LHS.isMinSignedValue())
2785 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2786 E->getType());
2787 return true;
2788 case BO_Shl: {
2789 if (Info.getLangOpts().OpenCL)
2790 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2791 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2792 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2793 RHS.isUnsigned());
2794 else if (RHS.isSigned() && RHS.isNegative()) {
2795 // During constant-folding, a negative shift is an opposite shift. Such
2796 // a shift is not a constant expression.
2797 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2798 RHS = -RHS;
2799 goto shift_right;
2801 shift_left:
2802 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2803 // the shifted type.
2804 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2805 if (SA != RHS) {
2806 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2807 << RHS << E->getType() << LHS.getBitWidth();
2808 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2809 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2810 // operand, and must not overflow the corresponding unsigned type.
2811 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2812 // E1 x 2^E2 module 2^N.
2813 if (LHS.isNegative())
2814 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2815 else if (LHS.countLeadingZeros() < SA)
2816 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2818 Result = LHS << SA;
2819 return true;
2821 case BO_Shr: {
2822 if (Info.getLangOpts().OpenCL)
2823 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2824 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2825 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2826 RHS.isUnsigned());
2827 else if (RHS.isSigned() && RHS.isNegative()) {
2828 // During constant-folding, a negative shift is an opposite shift. Such a
2829 // shift is not a constant expression.
2830 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2831 RHS = -RHS;
2832 goto shift_left;
2834 shift_right:
2835 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2836 // shifted type.
2837 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2838 if (SA != RHS)
2839 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2840 << RHS << E->getType() << LHS.getBitWidth();
2841 Result = LHS >> SA;
2842 return true;
2845 case BO_LT: Result = LHS < RHS; return true;
2846 case BO_GT: Result = LHS > RHS; return true;
2847 case BO_LE: Result = LHS <= RHS; return true;
2848 case BO_GE: Result = LHS >= RHS; return true;
2849 case BO_EQ: Result = LHS == RHS; return true;
2850 case BO_NE: Result = LHS != RHS; return true;
2851 case BO_Cmp:
2852 llvm_unreachable("BO_Cmp should be handled elsewhere");
2856 /// Perform the given binary floating-point operation, in-place, on LHS.
2857 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2858 APFloat &LHS, BinaryOperatorKind Opcode,
2859 const APFloat &RHS) {
2860 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2861 APFloat::opStatus St;
2862 switch (Opcode) {
2863 default:
2864 Info.FFDiag(E);
2865 return false;
2866 case BO_Mul:
2867 St = LHS.multiply(RHS, RM);
2868 break;
2869 case BO_Add:
2870 St = LHS.add(RHS, RM);
2871 break;
2872 case BO_Sub:
2873 St = LHS.subtract(RHS, RM);
2874 break;
2875 case BO_Div:
2876 // [expr.mul]p4:
2877 // If the second operand of / or % is zero the behavior is undefined.
2878 if (RHS.isZero())
2879 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2880 St = LHS.divide(RHS, RM);
2881 break;
2884 // [expr.pre]p4:
2885 // If during the evaluation of an expression, the result is not
2886 // mathematically defined [...], the behavior is undefined.
2887 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2888 if (LHS.isNaN()) {
2889 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2890 return Info.noteUndefinedBehavior();
2893 return checkFloatingPointResult(Info, E, St);
2896 static bool handleLogicalOpForVector(const APInt &LHSValue,
2897 BinaryOperatorKind Opcode,
2898 const APInt &RHSValue, APInt &Result) {
2899 bool LHS = (LHSValue != 0);
2900 bool RHS = (RHSValue != 0);
2902 if (Opcode == BO_LAnd)
2903 Result = LHS && RHS;
2904 else
2905 Result = LHS || RHS;
2906 return true;
2908 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2909 BinaryOperatorKind Opcode,
2910 const APFloat &RHSValue, APInt &Result) {
2911 bool LHS = !LHSValue.isZero();
2912 bool RHS = !RHSValue.isZero();
2914 if (Opcode == BO_LAnd)
2915 Result = LHS && RHS;
2916 else
2917 Result = LHS || RHS;
2918 return true;
2921 static bool handleLogicalOpForVector(const APValue &LHSValue,
2922 BinaryOperatorKind Opcode,
2923 const APValue &RHSValue, APInt &Result) {
2924 // The result is always an int type, however operands match the first.
2925 if (LHSValue.getKind() == APValue::Int)
2926 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2927 RHSValue.getInt(), Result);
2928 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2929 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2930 RHSValue.getFloat(), Result);
2933 template <typename APTy>
2934 static bool
2935 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2936 const APTy &RHSValue, APInt &Result) {
2937 switch (Opcode) {
2938 default:
2939 llvm_unreachable("unsupported binary operator");
2940 case BO_EQ:
2941 Result = (LHSValue == RHSValue);
2942 break;
2943 case BO_NE:
2944 Result = (LHSValue != RHSValue);
2945 break;
2946 case BO_LT:
2947 Result = (LHSValue < RHSValue);
2948 break;
2949 case BO_GT:
2950 Result = (LHSValue > RHSValue);
2951 break;
2952 case BO_LE:
2953 Result = (LHSValue <= RHSValue);
2954 break;
2955 case BO_GE:
2956 Result = (LHSValue >= RHSValue);
2957 break;
2960 // The boolean operations on these vector types use an instruction that
2961 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2962 // to -1 to make sure that we produce the correct value.
2963 Result.negate();
2965 return true;
2968 static bool handleCompareOpForVector(const APValue &LHSValue,
2969 BinaryOperatorKind Opcode,
2970 const APValue &RHSValue, APInt &Result) {
2971 // The result is always an int type, however operands match the first.
2972 if (LHSValue.getKind() == APValue::Int)
2973 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2974 RHSValue.getInt(), Result);
2975 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2976 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2977 RHSValue.getFloat(), Result);
2980 // Perform binary operations for vector types, in place on the LHS.
2981 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2982 BinaryOperatorKind Opcode,
2983 APValue &LHSValue,
2984 const APValue &RHSValue) {
2985 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2986 "Operation not supported on vector types");
2988 const auto *VT = E->getType()->castAs<VectorType>();
2989 unsigned NumElements = VT->getNumElements();
2990 QualType EltTy = VT->getElementType();
2992 // In the cases (typically C as I've observed) where we aren't evaluating
2993 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2994 // just give up.
2995 if (!LHSValue.isVector()) {
2996 assert(LHSValue.isLValue() &&
2997 "A vector result that isn't a vector OR uncalculated LValue");
2998 Info.FFDiag(E);
2999 return false;
3002 assert(LHSValue.getVectorLength() == NumElements &&
3003 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3005 SmallVector<APValue, 4> ResultElements;
3007 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3008 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3009 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3011 if (EltTy->isIntegerType()) {
3012 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3013 EltTy->isUnsignedIntegerType()};
3014 bool Success = true;
3016 if (BinaryOperator::isLogicalOp(Opcode))
3017 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3018 else if (BinaryOperator::isComparisonOp(Opcode))
3019 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3020 else
3021 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3022 RHSElt.getInt(), EltResult);
3024 if (!Success) {
3025 Info.FFDiag(E);
3026 return false;
3028 ResultElements.emplace_back(EltResult);
3030 } else if (EltTy->isFloatingType()) {
3031 assert(LHSElt.getKind() == APValue::Float &&
3032 RHSElt.getKind() == APValue::Float &&
3033 "Mismatched LHS/RHS/Result Type");
3034 APFloat LHSFloat = LHSElt.getFloat();
3036 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3037 RHSElt.getFloat())) {
3038 Info.FFDiag(E);
3039 return false;
3042 ResultElements.emplace_back(LHSFloat);
3046 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3047 return true;
3050 /// Cast an lvalue referring to a base subobject to a derived class, by
3051 /// truncating the lvalue's path to the given length.
3052 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3053 const RecordDecl *TruncatedType,
3054 unsigned TruncatedElements) {
3055 SubobjectDesignator &D = Result.Designator;
3057 // Check we actually point to a derived class object.
3058 if (TruncatedElements == D.Entries.size())
3059 return true;
3060 assert(TruncatedElements >= D.MostDerivedPathLength &&
3061 "not casting to a derived class");
3062 if (!Result.checkSubobject(Info, E, CSK_Derived))
3063 return false;
3065 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3066 const RecordDecl *RD = TruncatedType;
3067 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3068 if (RD->isInvalidDecl()) return false;
3069 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3070 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3071 if (isVirtualBaseClass(D.Entries[I]))
3072 Result.Offset -= Layout.getVBaseClassOffset(Base);
3073 else
3074 Result.Offset -= Layout.getBaseClassOffset(Base);
3075 RD = Base;
3077 D.Entries.resize(TruncatedElements);
3078 return true;
3081 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3082 const CXXRecordDecl *Derived,
3083 const CXXRecordDecl *Base,
3084 const ASTRecordLayout *RL = nullptr) {
3085 if (!RL) {
3086 if (Derived->isInvalidDecl()) return false;
3087 RL = &Info.Ctx.getASTRecordLayout(Derived);
3090 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3091 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3092 return true;
3095 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3096 const CXXRecordDecl *DerivedDecl,
3097 const CXXBaseSpecifier *Base) {
3098 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3100 if (!Base->isVirtual())
3101 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3103 SubobjectDesignator &D = Obj.Designator;
3104 if (D.Invalid)
3105 return false;
3107 // Extract most-derived object and corresponding type.
3108 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3109 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3110 return false;
3112 // Find the virtual base class.
3113 if (DerivedDecl->isInvalidDecl()) return false;
3114 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3115 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3116 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3117 return true;
3120 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3121 QualType Type, LValue &Result) {
3122 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3123 PathE = E->path_end();
3124 PathI != PathE; ++PathI) {
3125 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3126 *PathI))
3127 return false;
3128 Type = (*PathI)->getType();
3130 return true;
3133 /// Cast an lvalue referring to a derived class to a known base subobject.
3134 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3135 const CXXRecordDecl *DerivedRD,
3136 const CXXRecordDecl *BaseRD) {
3137 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3138 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3139 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3140 llvm_unreachable("Class must be derived from the passed in base class!");
3142 for (CXXBasePathElement &Elem : Paths.front())
3143 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3144 return false;
3145 return true;
3148 /// Update LVal to refer to the given field, which must be a member of the type
3149 /// currently described by LVal.
3150 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3151 const FieldDecl *FD,
3152 const ASTRecordLayout *RL = nullptr) {
3153 if (!RL) {
3154 if (FD->getParent()->isInvalidDecl()) return false;
3155 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3158 unsigned I = FD->getFieldIndex();
3159 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3160 LVal.addDecl(Info, E, FD);
3161 return true;
3164 /// Update LVal to refer to the given indirect field.
3165 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3166 LValue &LVal,
3167 const IndirectFieldDecl *IFD) {
3168 for (const auto *C : IFD->chain())
3169 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3170 return false;
3171 return true;
3174 /// Get the size of the given type in char units.
3175 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3176 QualType Type, CharUnits &Size) {
3177 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3178 // extension.
3179 if (Type->isVoidType() || Type->isFunctionType()) {
3180 Size = CharUnits::One();
3181 return true;
3184 if (Type->isDependentType()) {
3185 Info.FFDiag(Loc);
3186 return false;
3189 if (!Type->isConstantSizeType()) {
3190 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3191 // FIXME: Better diagnostic.
3192 Info.FFDiag(Loc);
3193 return false;
3196 Size = Info.Ctx.getTypeSizeInChars(Type);
3197 return true;
3200 /// Update a pointer value to model pointer arithmetic.
3201 /// \param Info - Information about the ongoing evaluation.
3202 /// \param E - The expression being evaluated, for diagnostic purposes.
3203 /// \param LVal - The pointer value to be updated.
3204 /// \param EltTy - The pointee type represented by LVal.
3205 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3206 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3207 LValue &LVal, QualType EltTy,
3208 APSInt Adjustment) {
3209 CharUnits SizeOfPointee;
3210 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3211 return false;
3213 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3214 return true;
3217 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3218 LValue &LVal, QualType EltTy,
3219 int64_t Adjustment) {
3220 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3221 APSInt::get(Adjustment));
3224 /// Update an lvalue to refer to a component of a complex number.
3225 /// \param Info - Information about the ongoing evaluation.
3226 /// \param LVal - The lvalue to be updated.
3227 /// \param EltTy - The complex number's component type.
3228 /// \param Imag - False for the real component, true for the imaginary.
3229 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3230 LValue &LVal, QualType EltTy,
3231 bool Imag) {
3232 if (Imag) {
3233 CharUnits SizeOfComponent;
3234 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3235 return false;
3236 LVal.Offset += SizeOfComponent;
3238 LVal.addComplex(Info, E, EltTy, Imag);
3239 return true;
3242 /// Try to evaluate the initializer for a variable declaration.
3244 /// \param Info Information about the ongoing evaluation.
3245 /// \param E An expression to be used when printing diagnostics.
3246 /// \param VD The variable whose initializer should be obtained.
3247 /// \param Version The version of the variable within the frame.
3248 /// \param Frame The frame in which the variable was created. Must be null
3249 /// if this variable is not local to the evaluation.
3250 /// \param Result Filled in with a pointer to the value of the variable.
3251 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3252 const VarDecl *VD, CallStackFrame *Frame,
3253 unsigned Version, APValue *&Result) {
3254 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3256 // If this is a local variable, dig out its value.
3257 if (Frame) {
3258 Result = Frame->getTemporary(VD, Version);
3259 if (Result)
3260 return true;
3262 if (!isa<ParmVarDecl>(VD)) {
3263 // Assume variables referenced within a lambda's call operator that were
3264 // not declared within the call operator are captures and during checking
3265 // of a potential constant expression, assume they are unknown constant
3266 // expressions.
3267 assert(isLambdaCallOperator(Frame->Callee) &&
3268 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3269 "missing value for local variable");
3270 if (Info.checkingPotentialConstantExpression())
3271 return false;
3272 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3273 // still reachable at all?
3274 Info.FFDiag(E->getBeginLoc(),
3275 diag::note_unimplemented_constexpr_lambda_feature_ast)
3276 << "captures not currently allowed";
3277 return false;
3281 // If we're currently evaluating the initializer of this declaration, use that
3282 // in-flight value.
3283 if (Info.EvaluatingDecl == Base) {
3284 Result = Info.EvaluatingDeclValue;
3285 return true;
3288 if (isa<ParmVarDecl>(VD)) {
3289 // Assume parameters of a potential constant expression are usable in
3290 // constant expressions.
3291 if (!Info.checkingPotentialConstantExpression() ||
3292 !Info.CurrentCall->Callee ||
3293 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3294 if (Info.getLangOpts().CPlusPlus11) {
3295 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3296 << VD;
3297 NoteLValueLocation(Info, Base);
3298 } else {
3299 Info.FFDiag(E);
3302 return false;
3305 // Dig out the initializer, and use the declaration which it's attached to.
3306 // FIXME: We should eventually check whether the variable has a reachable
3307 // initializing declaration.
3308 const Expr *Init = VD->getAnyInitializer(VD);
3309 if (!Init) {
3310 // Don't diagnose during potential constant expression checking; an
3311 // initializer might be added later.
3312 if (!Info.checkingPotentialConstantExpression()) {
3313 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3314 << VD;
3315 NoteLValueLocation(Info, Base);
3317 return false;
3320 if (Init->isValueDependent()) {
3321 // The DeclRefExpr is not value-dependent, but the variable it refers to
3322 // has a value-dependent initializer. This should only happen in
3323 // constant-folding cases, where the variable is not actually of a suitable
3324 // type for use in a constant expression (otherwise the DeclRefExpr would
3325 // have been value-dependent too), so diagnose that.
3326 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3327 if (!Info.checkingPotentialConstantExpression()) {
3328 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3329 ? diag::note_constexpr_ltor_non_constexpr
3330 : diag::note_constexpr_ltor_non_integral, 1)
3331 << VD << VD->getType();
3332 NoteLValueLocation(Info, Base);
3334 return false;
3337 // Check that we can fold the initializer. In C++, we will have already done
3338 // this in the cases where it matters for conformance.
3339 if (!VD->evaluateValue()) {
3340 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3341 NoteLValueLocation(Info, Base);
3342 return false;
3345 // Check that the variable is actually usable in constant expressions. For a
3346 // const integral variable or a reference, we might have a non-constant
3347 // initializer that we can nonetheless evaluate the initializer for. Such
3348 // variables are not usable in constant expressions. In C++98, the
3349 // initializer also syntactically needs to be an ICE.
3351 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3352 // expressions here; doing so would regress diagnostics for things like
3353 // reading from a volatile constexpr variable.
3354 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3355 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3356 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3357 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3358 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3359 NoteLValueLocation(Info, Base);
3362 // Never use the initializer of a weak variable, not even for constant
3363 // folding. We can't be sure that this is the definition that will be used.
3364 if (VD->isWeak()) {
3365 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3366 NoteLValueLocation(Info, Base);
3367 return false;
3370 Result = VD->getEvaluatedValue();
3371 return true;
3374 /// Get the base index of the given base class within an APValue representing
3375 /// the given derived class.
3376 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3377 const CXXRecordDecl *Base) {
3378 Base = Base->getCanonicalDecl();
3379 unsigned Index = 0;
3380 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3381 E = Derived->bases_end(); I != E; ++I, ++Index) {
3382 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3383 return Index;
3386 llvm_unreachable("base class missing from derived class's bases list");
3389 /// Extract the value of a character from a string literal.
3390 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3391 uint64_t Index) {
3392 assert(!isa<SourceLocExpr>(Lit) &&
3393 "SourceLocExpr should have already been converted to a StringLiteral");
3395 // FIXME: Support MakeStringConstant
3396 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3397 std::string Str;
3398 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3399 assert(Index <= Str.size() && "Index too large");
3400 return APSInt::getUnsigned(Str.c_str()[Index]);
3403 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3404 Lit = PE->getFunctionName();
3405 const StringLiteral *S = cast<StringLiteral>(Lit);
3406 const ConstantArrayType *CAT =
3407 Info.Ctx.getAsConstantArrayType(S->getType());
3408 assert(CAT && "string literal isn't an array");
3409 QualType CharType = CAT->getElementType();
3410 assert(CharType->isIntegerType() && "unexpected character type");
3412 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3413 CharType->isUnsignedIntegerType());
3414 if (Index < S->getLength())
3415 Value = S->getCodeUnit(Index);
3416 return Value;
3419 // Expand a string literal into an array of characters.
3421 // FIXME: This is inefficient; we should probably introduce something similar
3422 // to the LLVM ConstantDataArray to make this cheaper.
3423 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3424 APValue &Result,
3425 QualType AllocType = QualType()) {
3426 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3427 AllocType.isNull() ? S->getType() : AllocType);
3428 assert(CAT && "string literal isn't an array");
3429 QualType CharType = CAT->getElementType();
3430 assert(CharType->isIntegerType() && "unexpected character type");
3432 unsigned Elts = CAT->getSize().getZExtValue();
3433 Result = APValue(APValue::UninitArray(),
3434 std::min(S->getLength(), Elts), Elts);
3435 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3436 CharType->isUnsignedIntegerType());
3437 if (Result.hasArrayFiller())
3438 Result.getArrayFiller() = APValue(Value);
3439 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3440 Value = S->getCodeUnit(I);
3441 Result.getArrayInitializedElt(I) = APValue(Value);
3445 // Expand an array so that it has more than Index filled elements.
3446 static void expandArray(APValue &Array, unsigned Index) {
3447 unsigned Size = Array.getArraySize();
3448 assert(Index < Size);
3450 // Always at least double the number of elements for which we store a value.
3451 unsigned OldElts = Array.getArrayInitializedElts();
3452 unsigned NewElts = std::max(Index+1, OldElts * 2);
3453 NewElts = std::min(Size, std::max(NewElts, 8u));
3455 // Copy the data across.
3456 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3457 for (unsigned I = 0; I != OldElts; ++I)
3458 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3459 for (unsigned I = OldElts; I != NewElts; ++I)
3460 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3461 if (NewValue.hasArrayFiller())
3462 NewValue.getArrayFiller() = Array.getArrayFiller();
3463 Array.swap(NewValue);
3466 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3467 /// conversion. If it's of class type, we may assume that the copy operation
3468 /// is trivial. Note that this is never true for a union type with fields
3469 /// (because the copy always "reads" the active member) and always true for
3470 /// a non-class type.
3471 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3472 static bool isReadByLvalueToRvalueConversion(QualType T) {
3473 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3474 return !RD || isReadByLvalueToRvalueConversion(RD);
3476 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3477 // FIXME: A trivial copy of a union copies the object representation, even if
3478 // the union is empty.
3479 if (RD->isUnion())
3480 return !RD->field_empty();
3481 if (RD->isEmpty())
3482 return false;
3484 for (auto *Field : RD->fields())
3485 if (!Field->isUnnamedBitfield() &&
3486 isReadByLvalueToRvalueConversion(Field->getType()))
3487 return true;
3489 for (auto &BaseSpec : RD->bases())
3490 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3491 return true;
3493 return false;
3496 /// Diagnose an attempt to read from any unreadable field within the specified
3497 /// type, which might be a class type.
3498 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3499 QualType T) {
3500 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3501 if (!RD)
3502 return false;
3504 if (!RD->hasMutableFields())
3505 return false;
3507 for (auto *Field : RD->fields()) {
3508 // If we're actually going to read this field in some way, then it can't
3509 // be mutable. If we're in a union, then assigning to a mutable field
3510 // (even an empty one) can change the active member, so that's not OK.
3511 // FIXME: Add core issue number for the union case.
3512 if (Field->isMutable() &&
3513 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3514 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3515 Info.Note(Field->getLocation(), diag::note_declared_at);
3516 return true;
3519 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3520 return true;
3523 for (auto &BaseSpec : RD->bases())
3524 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3525 return true;
3527 // All mutable fields were empty, and thus not actually read.
3528 return false;
3531 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3532 APValue::LValueBase Base,
3533 bool MutableSubobject = false) {
3534 // A temporary or transient heap allocation we created.
3535 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3536 return true;
3538 switch (Info.IsEvaluatingDecl) {
3539 case EvalInfo::EvaluatingDeclKind::None:
3540 return false;
3542 case EvalInfo::EvaluatingDeclKind::Ctor:
3543 // The variable whose initializer we're evaluating.
3544 if (Info.EvaluatingDecl == Base)
3545 return true;
3547 // A temporary lifetime-extended by the variable whose initializer we're
3548 // evaluating.
3549 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3550 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3551 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3552 return false;
3554 case EvalInfo::EvaluatingDeclKind::Dtor:
3555 // C++2a [expr.const]p6:
3556 // [during constant destruction] the lifetime of a and its non-mutable
3557 // subobjects (but not its mutable subobjects) [are] considered to start
3558 // within e.
3559 if (MutableSubobject || Base != Info.EvaluatingDecl)
3560 return false;
3561 // FIXME: We can meaningfully extend this to cover non-const objects, but
3562 // we will need special handling: we should be able to access only
3563 // subobjects of such objects that are themselves declared const.
3564 QualType T = getType(Base);
3565 return T.isConstQualified() || T->isReferenceType();
3568 llvm_unreachable("unknown evaluating decl kind");
3571 namespace {
3572 /// A handle to a complete object (an object that is not a subobject of
3573 /// another object).
3574 struct CompleteObject {
3575 /// The identity of the object.
3576 APValue::LValueBase Base;
3577 /// The value of the complete object.
3578 APValue *Value;
3579 /// The type of the complete object.
3580 QualType Type;
3582 CompleteObject() : Value(nullptr) {}
3583 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3584 : Base(Base), Value(Value), Type(Type) {}
3586 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3587 // If this isn't a "real" access (eg, if it's just accessing the type
3588 // info), allow it. We assume the type doesn't change dynamically for
3589 // subobjects of constexpr objects (even though we'd hit UB here if it
3590 // did). FIXME: Is this right?
3591 if (!isAnyAccess(AK))
3592 return true;
3594 // In C++14 onwards, it is permitted to read a mutable member whose
3595 // lifetime began within the evaluation.
3596 // FIXME: Should we also allow this in C++11?
3597 if (!Info.getLangOpts().CPlusPlus14)
3598 return false;
3599 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3602 explicit operator bool() const { return !Type.isNull(); }
3604 } // end anonymous namespace
3606 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3607 bool IsMutable = false) {
3608 // C++ [basic.type.qualifier]p1:
3609 // - A const object is an object of type const T or a non-mutable subobject
3610 // of a const object.
3611 if (ObjType.isConstQualified() && !IsMutable)
3612 SubobjType.addConst();
3613 // - A volatile object is an object of type const T or a subobject of a
3614 // volatile object.
3615 if (ObjType.isVolatileQualified())
3616 SubobjType.addVolatile();
3617 return SubobjType;
3620 /// Find the designated sub-object of an rvalue.
3621 template<typename SubobjectHandler>
3622 typename SubobjectHandler::result_type
3623 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3624 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3625 if (Sub.Invalid)
3626 // A diagnostic will have already been produced.
3627 return handler.failed();
3628 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3629 if (Info.getLangOpts().CPlusPlus11)
3630 Info.FFDiag(E, Sub.isOnePastTheEnd()
3631 ? diag::note_constexpr_access_past_end
3632 : diag::note_constexpr_access_unsized_array)
3633 << handler.AccessKind;
3634 else
3635 Info.FFDiag(E);
3636 return handler.failed();
3639 APValue *O = Obj.Value;
3640 QualType ObjType = Obj.Type;
3641 const FieldDecl *LastField = nullptr;
3642 const FieldDecl *VolatileField = nullptr;
3644 // Walk the designator's path to find the subobject.
3645 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3646 // Reading an indeterminate value is undefined, but assigning over one is OK.
3647 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3648 (O->isIndeterminate() &&
3649 !isValidIndeterminateAccess(handler.AccessKind))) {
3650 if (!Info.checkingPotentialConstantExpression())
3651 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3652 << handler.AccessKind << O->isIndeterminate();
3653 return handler.failed();
3656 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3657 // const and volatile semantics are not applied on an object under
3658 // {con,de}struction.
3659 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3660 ObjType->isRecordType() &&
3661 Info.isEvaluatingCtorDtor(
3662 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3663 Sub.Entries.begin() + I)) !=
3664 ConstructionPhase::None) {
3665 ObjType = Info.Ctx.getCanonicalType(ObjType);
3666 ObjType.removeLocalConst();
3667 ObjType.removeLocalVolatile();
3670 // If this is our last pass, check that the final object type is OK.
3671 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3672 // Accesses to volatile objects are prohibited.
3673 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3674 if (Info.getLangOpts().CPlusPlus) {
3675 int DiagKind;
3676 SourceLocation Loc;
3677 const NamedDecl *Decl = nullptr;
3678 if (VolatileField) {
3679 DiagKind = 2;
3680 Loc = VolatileField->getLocation();
3681 Decl = VolatileField;
3682 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3683 DiagKind = 1;
3684 Loc = VD->getLocation();
3685 Decl = VD;
3686 } else {
3687 DiagKind = 0;
3688 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3689 Loc = E->getExprLoc();
3691 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3692 << handler.AccessKind << DiagKind << Decl;
3693 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3694 } else {
3695 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3697 return handler.failed();
3700 // If we are reading an object of class type, there may still be more
3701 // things we need to check: if there are any mutable subobjects, we
3702 // cannot perform this read. (This only happens when performing a trivial
3703 // copy or assignment.)
3704 if (ObjType->isRecordType() &&
3705 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3706 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3707 return handler.failed();
3710 if (I == N) {
3711 if (!handler.found(*O, ObjType))
3712 return false;
3714 // If we modified a bit-field, truncate it to the right width.
3715 if (isModification(handler.AccessKind) &&
3716 LastField && LastField->isBitField() &&
3717 !truncateBitfieldValue(Info, E, *O, LastField))
3718 return false;
3720 return true;
3723 LastField = nullptr;
3724 if (ObjType->isArrayType()) {
3725 // Next subobject is an array element.
3726 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3727 assert(CAT && "vla in literal type?");
3728 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3729 if (CAT->getSize().ule(Index)) {
3730 // Note, it should not be possible to form a pointer with a valid
3731 // designator which points more than one past the end of the array.
3732 if (Info.getLangOpts().CPlusPlus11)
3733 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3734 << handler.AccessKind;
3735 else
3736 Info.FFDiag(E);
3737 return handler.failed();
3740 ObjType = CAT->getElementType();
3742 if (O->getArrayInitializedElts() > Index)
3743 O = &O->getArrayInitializedElt(Index);
3744 else if (!isRead(handler.AccessKind)) {
3745 expandArray(*O, Index);
3746 O = &O->getArrayInitializedElt(Index);
3747 } else
3748 O = &O->getArrayFiller();
3749 } else if (ObjType->isAnyComplexType()) {
3750 // Next subobject is a complex number.
3751 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3752 if (Index > 1) {
3753 if (Info.getLangOpts().CPlusPlus11)
3754 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3755 << handler.AccessKind;
3756 else
3757 Info.FFDiag(E);
3758 return handler.failed();
3761 ObjType = getSubobjectType(
3762 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3764 assert(I == N - 1 && "extracting subobject of scalar?");
3765 if (O->isComplexInt()) {
3766 return handler.found(Index ? O->getComplexIntImag()
3767 : O->getComplexIntReal(), ObjType);
3768 } else {
3769 assert(O->isComplexFloat());
3770 return handler.found(Index ? O->getComplexFloatImag()
3771 : O->getComplexFloatReal(), ObjType);
3773 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3774 if (Field->isMutable() &&
3775 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3776 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3777 << handler.AccessKind << Field;
3778 Info.Note(Field->getLocation(), diag::note_declared_at);
3779 return handler.failed();
3782 // Next subobject is a class, struct or union field.
3783 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3784 if (RD->isUnion()) {
3785 const FieldDecl *UnionField = O->getUnionField();
3786 if (!UnionField ||
3787 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3788 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3789 // Placement new onto an inactive union member makes it active.
3790 O->setUnion(Field, APValue());
3791 } else {
3792 // FIXME: If O->getUnionValue() is absent, report that there's no
3793 // active union member rather than reporting the prior active union
3794 // member. We'll need to fix nullptr_t to not use APValue() as its
3795 // representation first.
3796 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3797 << handler.AccessKind << Field << !UnionField << UnionField;
3798 return handler.failed();
3801 O = &O->getUnionValue();
3802 } else
3803 O = &O->getStructField(Field->getFieldIndex());
3805 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3806 LastField = Field;
3807 if (Field->getType().isVolatileQualified())
3808 VolatileField = Field;
3809 } else {
3810 // Next subobject is a base class.
3811 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3812 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3813 O = &O->getStructBase(getBaseIndex(Derived, Base));
3815 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3820 namespace {
3821 struct ExtractSubobjectHandler {
3822 EvalInfo &Info;
3823 const Expr *E;
3824 APValue &Result;
3825 const AccessKinds AccessKind;
3827 typedef bool result_type;
3828 bool failed() { return false; }
3829 bool found(APValue &Subobj, QualType SubobjType) {
3830 Result = Subobj;
3831 if (AccessKind == AK_ReadObjectRepresentation)
3832 return true;
3833 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3835 bool found(APSInt &Value, QualType SubobjType) {
3836 Result = APValue(Value);
3837 return true;
3839 bool found(APFloat &Value, QualType SubobjType) {
3840 Result = APValue(Value);
3841 return true;
3844 } // end anonymous namespace
3846 /// Extract the designated sub-object of an rvalue.
3847 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3848 const CompleteObject &Obj,
3849 const SubobjectDesignator &Sub, APValue &Result,
3850 AccessKinds AK = AK_Read) {
3851 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3852 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3853 return findSubobject(Info, E, Obj, Sub, Handler);
3856 namespace {
3857 struct ModifySubobjectHandler {
3858 EvalInfo &Info;
3859 APValue &NewVal;
3860 const Expr *E;
3862 typedef bool result_type;
3863 static const AccessKinds AccessKind = AK_Assign;
3865 bool checkConst(QualType QT) {
3866 // Assigning to a const object has undefined behavior.
3867 if (QT.isConstQualified()) {
3868 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3869 return false;
3871 return true;
3874 bool failed() { return false; }
3875 bool found(APValue &Subobj, QualType SubobjType) {
3876 if (!checkConst(SubobjType))
3877 return false;
3878 // We've been given ownership of NewVal, so just swap it in.
3879 Subobj.swap(NewVal);
3880 return true;
3882 bool found(APSInt &Value, QualType SubobjType) {
3883 if (!checkConst(SubobjType))
3884 return false;
3885 if (!NewVal.isInt()) {
3886 // Maybe trying to write a cast pointer value into a complex?
3887 Info.FFDiag(E);
3888 return false;
3890 Value = NewVal.getInt();
3891 return true;
3893 bool found(APFloat &Value, QualType SubobjType) {
3894 if (!checkConst(SubobjType))
3895 return false;
3896 Value = NewVal.getFloat();
3897 return true;
3900 } // end anonymous namespace
3902 const AccessKinds ModifySubobjectHandler::AccessKind;
3904 /// Update the designated sub-object of an rvalue to the given value.
3905 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3906 const CompleteObject &Obj,
3907 const SubobjectDesignator &Sub,
3908 APValue &NewVal) {
3909 ModifySubobjectHandler Handler = { Info, NewVal, E };
3910 return findSubobject(Info, E, Obj, Sub, Handler);
3913 /// Find the position where two subobject designators diverge, or equivalently
3914 /// the length of the common initial subsequence.
3915 static unsigned FindDesignatorMismatch(QualType ObjType,
3916 const SubobjectDesignator &A,
3917 const SubobjectDesignator &B,
3918 bool &WasArrayIndex) {
3919 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3920 for (/**/; I != N; ++I) {
3921 if (!ObjType.isNull() &&
3922 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3923 // Next subobject is an array element.
3924 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3925 WasArrayIndex = true;
3926 return I;
3928 if (ObjType->isAnyComplexType())
3929 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3930 else
3931 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3932 } else {
3933 if (A.Entries[I].getAsBaseOrMember() !=
3934 B.Entries[I].getAsBaseOrMember()) {
3935 WasArrayIndex = false;
3936 return I;
3938 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3939 // Next subobject is a field.
3940 ObjType = FD->getType();
3941 else
3942 // Next subobject is a base class.
3943 ObjType = QualType();
3946 WasArrayIndex = false;
3947 return I;
3950 /// Determine whether the given subobject designators refer to elements of the
3951 /// same array object.
3952 static bool AreElementsOfSameArray(QualType ObjType,
3953 const SubobjectDesignator &A,
3954 const SubobjectDesignator &B) {
3955 if (A.Entries.size() != B.Entries.size())
3956 return false;
3958 bool IsArray = A.MostDerivedIsArrayElement;
3959 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3960 // A is a subobject of the array element.
3961 return false;
3963 // If A (and B) designates an array element, the last entry will be the array
3964 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3965 // of length 1' case, and the entire path must match.
3966 bool WasArrayIndex;
3967 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3968 return CommonLength >= A.Entries.size() - IsArray;
3971 /// Find the complete object to which an LValue refers.
3972 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3973 AccessKinds AK, const LValue &LVal,
3974 QualType LValType) {
3975 if (LVal.InvalidBase) {
3976 Info.FFDiag(E);
3977 return CompleteObject();
3980 if (!LVal.Base) {
3981 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3982 return CompleteObject();
3985 CallStackFrame *Frame = nullptr;
3986 unsigned Depth = 0;
3987 if (LVal.getLValueCallIndex()) {
3988 std::tie(Frame, Depth) =
3989 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3990 if (!Frame) {
3991 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3992 << AK << LVal.Base.is<const ValueDecl*>();
3993 NoteLValueLocation(Info, LVal.Base);
3994 return CompleteObject();
3998 bool IsAccess = isAnyAccess(AK);
4000 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4001 // is not a constant expression (even if the object is non-volatile). We also
4002 // apply this rule to C++98, in order to conform to the expected 'volatile'
4003 // semantics.
4004 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4005 if (Info.getLangOpts().CPlusPlus)
4006 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4007 << AK << LValType;
4008 else
4009 Info.FFDiag(E);
4010 return CompleteObject();
4013 // Compute value storage location and type of base object.
4014 APValue *BaseVal = nullptr;
4015 QualType BaseType = getType(LVal.Base);
4017 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4018 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4019 // This is the object whose initializer we're evaluating, so its lifetime
4020 // started in the current evaluation.
4021 BaseVal = Info.EvaluatingDeclValue;
4022 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4023 // Allow reading from a GUID declaration.
4024 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4025 if (isModification(AK)) {
4026 // All the remaining cases do not permit modification of the object.
4027 Info.FFDiag(E, diag::note_constexpr_modify_global);
4028 return CompleteObject();
4030 APValue &V = GD->getAsAPValue();
4031 if (V.isAbsent()) {
4032 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4033 << GD->getType();
4034 return CompleteObject();
4036 return CompleteObject(LVal.Base, &V, GD->getType());
4039 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4040 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4041 if (isModification(AK)) {
4042 Info.FFDiag(E, diag::note_constexpr_modify_global);
4043 return CompleteObject();
4045 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4046 GCD->getType());
4049 // Allow reading from template parameter objects.
4050 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4051 if (isModification(AK)) {
4052 Info.FFDiag(E, diag::note_constexpr_modify_global);
4053 return CompleteObject();
4055 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4056 TPO->getType());
4059 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4060 // In C++11, constexpr, non-volatile variables initialized with constant
4061 // expressions are constant expressions too. Inside constexpr functions,
4062 // parameters are constant expressions even if they're non-const.
4063 // In C++1y, objects local to a constant expression (those with a Frame) are
4064 // both readable and writable inside constant expressions.
4065 // In C, such things can also be folded, although they are not ICEs.
4066 const VarDecl *VD = dyn_cast<VarDecl>(D);
4067 if (VD) {
4068 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4069 VD = VDef;
4071 if (!VD || VD->isInvalidDecl()) {
4072 Info.FFDiag(E);
4073 return CompleteObject();
4076 bool IsConstant = BaseType.isConstant(Info.Ctx);
4078 // Unless we're looking at a local variable or argument in a constexpr call,
4079 // the variable we're reading must be const.
4080 if (!Frame) {
4081 if (IsAccess && isa<ParmVarDecl>(VD)) {
4082 // Access of a parameter that's not associated with a frame isn't going
4083 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4084 // suitable diagnostic.
4085 } else if (Info.getLangOpts().CPlusPlus14 &&
4086 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4087 // OK, we can read and modify an object if we're in the process of
4088 // evaluating its initializer, because its lifetime began in this
4089 // evaluation.
4090 } else if (isModification(AK)) {
4091 // All the remaining cases do not permit modification of the object.
4092 Info.FFDiag(E, diag::note_constexpr_modify_global);
4093 return CompleteObject();
4094 } else if (VD->isConstexpr()) {
4095 // OK, we can read this variable.
4096 } else if (BaseType->isIntegralOrEnumerationType()) {
4097 if (!IsConstant) {
4098 if (!IsAccess)
4099 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4100 if (Info.getLangOpts().CPlusPlus) {
4101 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4102 Info.Note(VD->getLocation(), diag::note_declared_at);
4103 } else {
4104 Info.FFDiag(E);
4106 return CompleteObject();
4108 } else if (!IsAccess) {
4109 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4110 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4111 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4112 // This variable might end up being constexpr. Don't diagnose it yet.
4113 } else if (IsConstant) {
4114 // Keep evaluating to see what we can do. In particular, we support
4115 // folding of const floating-point types, in order to make static const
4116 // data members of such types (supported as an extension) more useful.
4117 if (Info.getLangOpts().CPlusPlus) {
4118 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4119 ? diag::note_constexpr_ltor_non_constexpr
4120 : diag::note_constexpr_ltor_non_integral, 1)
4121 << VD << BaseType;
4122 Info.Note(VD->getLocation(), diag::note_declared_at);
4123 } else {
4124 Info.CCEDiag(E);
4126 } else {
4127 // Never allow reading a non-const value.
4128 if (Info.getLangOpts().CPlusPlus) {
4129 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4130 ? diag::note_constexpr_ltor_non_constexpr
4131 : diag::note_constexpr_ltor_non_integral, 1)
4132 << VD << BaseType;
4133 Info.Note(VD->getLocation(), diag::note_declared_at);
4134 } else {
4135 Info.FFDiag(E);
4137 return CompleteObject();
4141 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4142 return CompleteObject();
4143 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4144 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4145 if (!Alloc) {
4146 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4147 return CompleteObject();
4149 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4150 LVal.Base.getDynamicAllocType());
4151 } else {
4152 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4154 if (!Frame) {
4155 if (const MaterializeTemporaryExpr *MTE =
4156 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4157 assert(MTE->getStorageDuration() == SD_Static &&
4158 "should have a frame for a non-global materialized temporary");
4160 // C++20 [expr.const]p4: [DR2126]
4161 // An object or reference is usable in constant expressions if it is
4162 // - a temporary object of non-volatile const-qualified literal type
4163 // whose lifetime is extended to that of a variable that is usable
4164 // in constant expressions
4166 // C++20 [expr.const]p5:
4167 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4168 // - a non-volatile glvalue that refers to an object that is usable
4169 // in constant expressions, or
4170 // - a non-volatile glvalue of literal type that refers to a
4171 // non-volatile object whose lifetime began within the evaluation
4172 // of E;
4174 // C++11 misses the 'began within the evaluation of e' check and
4175 // instead allows all temporaries, including things like:
4176 // int &&r = 1;
4177 // int x = ++r;
4178 // constexpr int k = r;
4179 // Therefore we use the C++14-onwards rules in C++11 too.
4181 // Note that temporaries whose lifetimes began while evaluating a
4182 // variable's constructor are not usable while evaluating the
4183 // corresponding destructor, not even if they're of const-qualified
4184 // types.
4185 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4186 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4187 if (!IsAccess)
4188 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4189 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4190 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4191 return CompleteObject();
4194 BaseVal = MTE->getOrCreateValue(false);
4195 assert(BaseVal && "got reference to unevaluated temporary");
4196 } else {
4197 if (!IsAccess)
4198 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4199 APValue Val;
4200 LVal.moveInto(Val);
4201 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4202 << AK
4203 << Val.getAsString(Info.Ctx,
4204 Info.Ctx.getLValueReferenceType(LValType));
4205 NoteLValueLocation(Info, LVal.Base);
4206 return CompleteObject();
4208 } else {
4209 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4210 assert(BaseVal && "missing value for temporary");
4214 // In C++14, we can't safely access any mutable state when we might be
4215 // evaluating after an unmodeled side effect. Parameters are modeled as state
4216 // in the caller, but aren't visible once the call returns, so they can be
4217 // modified in a speculatively-evaluated call.
4219 // FIXME: Not all local state is mutable. Allow local constant subobjects
4220 // to be read here (but take care with 'mutable' fields).
4221 unsigned VisibleDepth = Depth;
4222 if (llvm::isa_and_nonnull<ParmVarDecl>(
4223 LVal.Base.dyn_cast<const ValueDecl *>()))
4224 ++VisibleDepth;
4225 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4226 Info.EvalStatus.HasSideEffects) ||
4227 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4228 return CompleteObject();
4230 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4233 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4234 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4235 /// glvalue referred to by an entity of reference type.
4237 /// \param Info - Information about the ongoing evaluation.
4238 /// \param Conv - The expression for which we are performing the conversion.
4239 /// Used for diagnostics.
4240 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4241 /// case of a non-class type).
4242 /// \param LVal - The glvalue on which we are attempting to perform this action.
4243 /// \param RVal - The produced value will be placed here.
4244 /// \param WantObjectRepresentation - If true, we're looking for the object
4245 /// representation rather than the value, and in particular,
4246 /// there is no requirement that the result be fully initialized.
4247 static bool
4248 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4249 const LValue &LVal, APValue &RVal,
4250 bool WantObjectRepresentation = false) {
4251 if (LVal.Designator.Invalid)
4252 return false;
4254 // Check for special cases where there is no existing APValue to look at.
4255 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4257 AccessKinds AK =
4258 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4260 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4261 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4262 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4263 // initializer until now for such expressions. Such an expression can't be
4264 // an ICE in C, so this only matters for fold.
4265 if (Type.isVolatileQualified()) {
4266 Info.FFDiag(Conv);
4267 return false;
4270 APValue Lit;
4271 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4272 return false;
4274 // According to GCC info page:
4276 // 6.28 Compound Literals
4278 // As an optimization, G++ sometimes gives array compound literals longer
4279 // lifetimes: when the array either appears outside a function or has a
4280 // const-qualified type. If foo and its initializer had elements of type
4281 // char *const rather than char *, or if foo were a global variable, the
4282 // array would have static storage duration. But it is probably safest
4283 // just to avoid the use of array compound literals in C++ code.
4285 // Obey that rule by checking constness for converted array types.
4287 QualType CLETy = CLE->getType();
4288 if (CLETy->isArrayType() && !Type->isArrayType()) {
4289 if (!CLETy.isConstant(Info.Ctx)) {
4290 Info.FFDiag(Conv);
4291 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4292 return false;
4296 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4297 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4298 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4299 // Special-case character extraction so we don't have to construct an
4300 // APValue for the whole string.
4301 assert(LVal.Designator.Entries.size() <= 1 &&
4302 "Can only read characters from string literals");
4303 if (LVal.Designator.Entries.empty()) {
4304 // Fail for now for LValue to RValue conversion of an array.
4305 // (This shouldn't show up in C/C++, but it could be triggered by a
4306 // weird EvaluateAsRValue call from a tool.)
4307 Info.FFDiag(Conv);
4308 return false;
4310 if (LVal.Designator.isOnePastTheEnd()) {
4311 if (Info.getLangOpts().CPlusPlus11)
4312 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4313 else
4314 Info.FFDiag(Conv);
4315 return false;
4317 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4318 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4319 return true;
4323 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4324 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4327 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4328 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4329 QualType LValType, APValue &Val) {
4330 if (LVal.Designator.Invalid)
4331 return false;
4333 if (!Info.getLangOpts().CPlusPlus14) {
4334 Info.FFDiag(E);
4335 return false;
4338 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4339 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4342 namespace {
4343 struct CompoundAssignSubobjectHandler {
4344 EvalInfo &Info;
4345 const CompoundAssignOperator *E;
4346 QualType PromotedLHSType;
4347 BinaryOperatorKind Opcode;
4348 const APValue &RHS;
4350 static const AccessKinds AccessKind = AK_Assign;
4352 typedef bool result_type;
4354 bool checkConst(QualType QT) {
4355 // Assigning to a const object has undefined behavior.
4356 if (QT.isConstQualified()) {
4357 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4358 return false;
4360 return true;
4363 bool failed() { return false; }
4364 bool found(APValue &Subobj, QualType SubobjType) {
4365 switch (Subobj.getKind()) {
4366 case APValue::Int:
4367 return found(Subobj.getInt(), SubobjType);
4368 case APValue::Float:
4369 return found(Subobj.getFloat(), SubobjType);
4370 case APValue::ComplexInt:
4371 case APValue::ComplexFloat:
4372 // FIXME: Implement complex compound assignment.
4373 Info.FFDiag(E);
4374 return false;
4375 case APValue::LValue:
4376 return foundPointer(Subobj, SubobjType);
4377 case APValue::Vector:
4378 return foundVector(Subobj, SubobjType);
4379 default:
4380 // FIXME: can this happen?
4381 Info.FFDiag(E);
4382 return false;
4386 bool foundVector(APValue &Value, QualType SubobjType) {
4387 if (!checkConst(SubobjType))
4388 return false;
4390 if (!SubobjType->isVectorType()) {
4391 Info.FFDiag(E);
4392 return false;
4394 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4397 bool found(APSInt &Value, QualType SubobjType) {
4398 if (!checkConst(SubobjType))
4399 return false;
4401 if (!SubobjType->isIntegerType()) {
4402 // We don't support compound assignment on integer-cast-to-pointer
4403 // values.
4404 Info.FFDiag(E);
4405 return false;
4408 if (RHS.isInt()) {
4409 APSInt LHS =
4410 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4411 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4412 return false;
4413 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4414 return true;
4415 } else if (RHS.isFloat()) {
4416 const FPOptions FPO = E->getFPFeaturesInEffect(
4417 Info.Ctx.getLangOpts());
4418 APFloat FValue(0.0);
4419 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4420 PromotedLHSType, FValue) &&
4421 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4422 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4423 Value);
4426 Info.FFDiag(E);
4427 return false;
4429 bool found(APFloat &Value, QualType SubobjType) {
4430 return checkConst(SubobjType) &&
4431 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4432 Value) &&
4433 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4434 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4436 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4437 if (!checkConst(SubobjType))
4438 return false;
4440 QualType PointeeType;
4441 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4442 PointeeType = PT->getPointeeType();
4444 if (PointeeType.isNull() || !RHS.isInt() ||
4445 (Opcode != BO_Add && Opcode != BO_Sub)) {
4446 Info.FFDiag(E);
4447 return false;
4450 APSInt Offset = RHS.getInt();
4451 if (Opcode == BO_Sub)
4452 negateAsSigned(Offset);
4454 LValue LVal;
4455 LVal.setFrom(Info.Ctx, Subobj);
4456 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4457 return false;
4458 LVal.moveInto(Subobj);
4459 return true;
4462 } // end anonymous namespace
4464 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4466 /// Perform a compound assignment of LVal <op>= RVal.
4467 static bool handleCompoundAssignment(EvalInfo &Info,
4468 const CompoundAssignOperator *E,
4469 const LValue &LVal, QualType LValType,
4470 QualType PromotedLValType,
4471 BinaryOperatorKind Opcode,
4472 const APValue &RVal) {
4473 if (LVal.Designator.Invalid)
4474 return false;
4476 if (!Info.getLangOpts().CPlusPlus14) {
4477 Info.FFDiag(E);
4478 return false;
4481 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4482 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4483 RVal };
4484 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4487 namespace {
4488 struct IncDecSubobjectHandler {
4489 EvalInfo &Info;
4490 const UnaryOperator *E;
4491 AccessKinds AccessKind;
4492 APValue *Old;
4494 typedef bool result_type;
4496 bool checkConst(QualType QT) {
4497 // Assigning to a const object has undefined behavior.
4498 if (QT.isConstQualified()) {
4499 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4500 return false;
4502 return true;
4505 bool failed() { return false; }
4506 bool found(APValue &Subobj, QualType SubobjType) {
4507 // Stash the old value. Also clear Old, so we don't clobber it later
4508 // if we're post-incrementing a complex.
4509 if (Old) {
4510 *Old = Subobj;
4511 Old = nullptr;
4514 switch (Subobj.getKind()) {
4515 case APValue::Int:
4516 return found(Subobj.getInt(), SubobjType);
4517 case APValue::Float:
4518 return found(Subobj.getFloat(), SubobjType);
4519 case APValue::ComplexInt:
4520 return found(Subobj.getComplexIntReal(),
4521 SubobjType->castAs<ComplexType>()->getElementType()
4522 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4523 case APValue::ComplexFloat:
4524 return found(Subobj.getComplexFloatReal(),
4525 SubobjType->castAs<ComplexType>()->getElementType()
4526 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4527 case APValue::LValue:
4528 return foundPointer(Subobj, SubobjType);
4529 default:
4530 // FIXME: can this happen?
4531 Info.FFDiag(E);
4532 return false;
4535 bool found(APSInt &Value, QualType SubobjType) {
4536 if (!checkConst(SubobjType))
4537 return false;
4539 if (!SubobjType->isIntegerType()) {
4540 // We don't support increment / decrement on integer-cast-to-pointer
4541 // values.
4542 Info.FFDiag(E);
4543 return false;
4546 if (Old) *Old = APValue(Value);
4548 // bool arithmetic promotes to int, and the conversion back to bool
4549 // doesn't reduce mod 2^n, so special-case it.
4550 if (SubobjType->isBooleanType()) {
4551 if (AccessKind == AK_Increment)
4552 Value = 1;
4553 else
4554 Value = !Value;
4555 return true;
4558 bool WasNegative = Value.isNegative();
4559 if (AccessKind == AK_Increment) {
4560 ++Value;
4562 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4563 APSInt ActualValue(Value, /*IsUnsigned*/true);
4564 return HandleOverflow(Info, E, ActualValue, SubobjType);
4566 } else {
4567 --Value;
4569 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4570 unsigned BitWidth = Value.getBitWidth();
4571 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4572 ActualValue.setBit(BitWidth);
4573 return HandleOverflow(Info, E, ActualValue, SubobjType);
4576 return true;
4578 bool found(APFloat &Value, QualType SubobjType) {
4579 if (!checkConst(SubobjType))
4580 return false;
4582 if (Old) *Old = APValue(Value);
4584 APFloat One(Value.getSemantics(), 1);
4585 if (AccessKind == AK_Increment)
4586 Value.add(One, APFloat::rmNearestTiesToEven);
4587 else
4588 Value.subtract(One, APFloat::rmNearestTiesToEven);
4589 return true;
4591 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4592 if (!checkConst(SubobjType))
4593 return false;
4595 QualType PointeeType;
4596 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4597 PointeeType = PT->getPointeeType();
4598 else {
4599 Info.FFDiag(E);
4600 return false;
4603 LValue LVal;
4604 LVal.setFrom(Info.Ctx, Subobj);
4605 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4606 AccessKind == AK_Increment ? 1 : -1))
4607 return false;
4608 LVal.moveInto(Subobj);
4609 return true;
4612 } // end anonymous namespace
4614 /// Perform an increment or decrement on LVal.
4615 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4616 QualType LValType, bool IsIncrement, APValue *Old) {
4617 if (LVal.Designator.Invalid)
4618 return false;
4620 if (!Info.getLangOpts().CPlusPlus14) {
4621 Info.FFDiag(E);
4622 return false;
4625 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4626 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4627 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4628 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4631 /// Build an lvalue for the object argument of a member function call.
4632 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4633 LValue &This) {
4634 if (Object->getType()->isPointerType() && Object->isPRValue())
4635 return EvaluatePointer(Object, This, Info);
4637 if (Object->isGLValue())
4638 return EvaluateLValue(Object, This, Info);
4640 if (Object->getType()->isLiteralType(Info.Ctx))
4641 return EvaluateTemporary(Object, This, Info);
4643 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4644 return false;
4647 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4648 /// lvalue referring to the result.
4650 /// \param Info - Information about the ongoing evaluation.
4651 /// \param LV - An lvalue referring to the base of the member pointer.
4652 /// \param RHS - The member pointer expression.
4653 /// \param IncludeMember - Specifies whether the member itself is included in
4654 /// the resulting LValue subobject designator. This is not possible when
4655 /// creating a bound member function.
4656 /// \return The field or method declaration to which the member pointer refers,
4657 /// or 0 if evaluation fails.
4658 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4659 QualType LVType,
4660 LValue &LV,
4661 const Expr *RHS,
4662 bool IncludeMember = true) {
4663 MemberPtr MemPtr;
4664 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4665 return nullptr;
4667 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4668 // member value, the behavior is undefined.
4669 if (!MemPtr.getDecl()) {
4670 // FIXME: Specific diagnostic.
4671 Info.FFDiag(RHS);
4672 return nullptr;
4675 if (MemPtr.isDerivedMember()) {
4676 // This is a member of some derived class. Truncate LV appropriately.
4677 // The end of the derived-to-base path for the base object must match the
4678 // derived-to-base path for the member pointer.
4679 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4680 LV.Designator.Entries.size()) {
4681 Info.FFDiag(RHS);
4682 return nullptr;
4684 unsigned PathLengthToMember =
4685 LV.Designator.Entries.size() - MemPtr.Path.size();
4686 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4687 const CXXRecordDecl *LVDecl = getAsBaseClass(
4688 LV.Designator.Entries[PathLengthToMember + I]);
4689 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4690 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4691 Info.FFDiag(RHS);
4692 return nullptr;
4696 // Truncate the lvalue to the appropriate derived class.
4697 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4698 PathLengthToMember))
4699 return nullptr;
4700 } else if (!MemPtr.Path.empty()) {
4701 // Extend the LValue path with the member pointer's path.
4702 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4703 MemPtr.Path.size() + IncludeMember);
4705 // Walk down to the appropriate base class.
4706 if (const PointerType *PT = LVType->getAs<PointerType>())
4707 LVType = PT->getPointeeType();
4708 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4709 assert(RD && "member pointer access on non-class-type expression");
4710 // The first class in the path is that of the lvalue.
4711 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4712 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4713 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4714 return nullptr;
4715 RD = Base;
4717 // Finally cast to the class containing the member.
4718 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4719 MemPtr.getContainingRecord()))
4720 return nullptr;
4723 // Add the member. Note that we cannot build bound member functions here.
4724 if (IncludeMember) {
4725 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4726 if (!HandleLValueMember(Info, RHS, LV, FD))
4727 return nullptr;
4728 } else if (const IndirectFieldDecl *IFD =
4729 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4730 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4731 return nullptr;
4732 } else {
4733 llvm_unreachable("can't construct reference to bound member function");
4737 return MemPtr.getDecl();
4740 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4741 const BinaryOperator *BO,
4742 LValue &LV,
4743 bool IncludeMember = true) {
4744 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4746 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4747 if (Info.noteFailure()) {
4748 MemberPtr MemPtr;
4749 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4751 return nullptr;
4754 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4755 BO->getRHS(), IncludeMember);
4758 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4759 /// the provided lvalue, which currently refers to the base object.
4760 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4761 LValue &Result) {
4762 SubobjectDesignator &D = Result.Designator;
4763 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4764 return false;
4766 QualType TargetQT = E->getType();
4767 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4768 TargetQT = PT->getPointeeType();
4770 // Check this cast lands within the final derived-to-base subobject path.
4771 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4772 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4773 << D.MostDerivedType << TargetQT;
4774 return false;
4777 // Check the type of the final cast. We don't need to check the path,
4778 // since a cast can only be formed if the path is unique.
4779 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4780 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4781 const CXXRecordDecl *FinalType;
4782 if (NewEntriesSize == D.MostDerivedPathLength)
4783 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4784 else
4785 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4786 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4787 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4788 << D.MostDerivedType << TargetQT;
4789 return false;
4792 // Truncate the lvalue to the appropriate derived class.
4793 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4796 /// Get the value to use for a default-initialized object of type T.
4797 /// Return false if it encounters something invalid.
4798 static bool getDefaultInitValue(QualType T, APValue &Result) {
4799 bool Success = true;
4800 if (auto *RD = T->getAsCXXRecordDecl()) {
4801 if (RD->isInvalidDecl()) {
4802 Result = APValue();
4803 return false;
4805 if (RD->isUnion()) {
4806 Result = APValue((const FieldDecl *)nullptr);
4807 return true;
4809 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4810 std::distance(RD->field_begin(), RD->field_end()));
4812 unsigned Index = 0;
4813 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4814 End = RD->bases_end();
4815 I != End; ++I, ++Index)
4816 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4818 for (const auto *I : RD->fields()) {
4819 if (I->isUnnamedBitfield())
4820 continue;
4821 Success &= getDefaultInitValue(I->getType(),
4822 Result.getStructField(I->getFieldIndex()));
4824 return Success;
4827 if (auto *AT =
4828 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4829 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4830 if (Result.hasArrayFiller())
4831 Success &=
4832 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4834 return Success;
4837 Result = APValue::IndeterminateValue();
4838 return true;
4841 namespace {
4842 enum EvalStmtResult {
4843 /// Evaluation failed.
4844 ESR_Failed,
4845 /// Hit a 'return' statement.
4846 ESR_Returned,
4847 /// Evaluation succeeded.
4848 ESR_Succeeded,
4849 /// Hit a 'continue' statement.
4850 ESR_Continue,
4851 /// Hit a 'break' statement.
4852 ESR_Break,
4853 /// Still scanning for 'case' or 'default' statement.
4854 ESR_CaseNotFound
4858 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4859 if (VD->isInvalidDecl())
4860 return false;
4861 // We don't need to evaluate the initializer for a static local.
4862 if (!VD->hasLocalStorage())
4863 return true;
4865 LValue Result;
4866 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4867 ScopeKind::Block, Result);
4869 const Expr *InitE = VD->getInit();
4870 if (!InitE) {
4871 if (VD->getType()->isDependentType())
4872 return Info.noteSideEffect();
4873 return getDefaultInitValue(VD->getType(), Val);
4875 if (InitE->isValueDependent())
4876 return false;
4878 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4879 // Wipe out any partially-computed value, to allow tracking that this
4880 // evaluation failed.
4881 Val = APValue();
4882 return false;
4885 return true;
4888 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4889 bool OK = true;
4891 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4892 OK &= EvaluateVarDecl(Info, VD);
4894 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4895 for (auto *BD : DD->bindings())
4896 if (auto *VD = BD->getHoldingVar())
4897 OK &= EvaluateDecl(Info, VD);
4899 return OK;
4902 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4903 assert(E->isValueDependent());
4904 if (Info.noteSideEffect())
4905 return true;
4906 assert(E->containsErrors() && "valid value-dependent expression should never "
4907 "reach invalid code path.");
4908 return false;
4911 /// Evaluate a condition (either a variable declaration or an expression).
4912 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4913 const Expr *Cond, bool &Result) {
4914 if (Cond->isValueDependent())
4915 return false;
4916 FullExpressionRAII Scope(Info);
4917 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4918 return false;
4919 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4920 return false;
4921 return Scope.destroy();
4924 namespace {
4925 /// A location where the result (returned value) of evaluating a
4926 /// statement should be stored.
4927 struct StmtResult {
4928 /// The APValue that should be filled in with the returned value.
4929 APValue &Value;
4930 /// The location containing the result, if any (used to support RVO).
4931 const LValue *Slot;
4934 struct TempVersionRAII {
4935 CallStackFrame &Frame;
4937 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4938 Frame.pushTempVersion();
4941 ~TempVersionRAII() {
4942 Frame.popTempVersion();
4948 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4949 const Stmt *S,
4950 const SwitchCase *SC = nullptr);
4952 /// Evaluate the body of a loop, and translate the result as appropriate.
4953 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4954 const Stmt *Body,
4955 const SwitchCase *Case = nullptr) {
4956 BlockScopeRAII Scope(Info);
4958 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4959 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4960 ESR = ESR_Failed;
4962 switch (ESR) {
4963 case ESR_Break:
4964 return ESR_Succeeded;
4965 case ESR_Succeeded:
4966 case ESR_Continue:
4967 return ESR_Continue;
4968 case ESR_Failed:
4969 case ESR_Returned:
4970 case ESR_CaseNotFound:
4971 return ESR;
4973 llvm_unreachable("Invalid EvalStmtResult!");
4976 /// Evaluate a switch statement.
4977 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4978 const SwitchStmt *SS) {
4979 BlockScopeRAII Scope(Info);
4981 // Evaluate the switch condition.
4982 APSInt Value;
4984 if (const Stmt *Init = SS->getInit()) {
4985 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4986 if (ESR != ESR_Succeeded) {
4987 if (ESR != ESR_Failed && !Scope.destroy())
4988 ESR = ESR_Failed;
4989 return ESR;
4993 FullExpressionRAII CondScope(Info);
4994 if (SS->getConditionVariable() &&
4995 !EvaluateDecl(Info, SS->getConditionVariable()))
4996 return ESR_Failed;
4997 if (SS->getCond()->isValueDependent()) {
4998 if (!EvaluateDependentExpr(SS->getCond(), Info))
4999 return ESR_Failed;
5000 } else {
5001 if (!EvaluateInteger(SS->getCond(), Value, Info))
5002 return ESR_Failed;
5004 if (!CondScope.destroy())
5005 return ESR_Failed;
5008 // Find the switch case corresponding to the value of the condition.
5009 // FIXME: Cache this lookup.
5010 const SwitchCase *Found = nullptr;
5011 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5012 SC = SC->getNextSwitchCase()) {
5013 if (isa<DefaultStmt>(SC)) {
5014 Found = SC;
5015 continue;
5018 const CaseStmt *CS = cast<CaseStmt>(SC);
5019 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5020 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5021 : LHS;
5022 if (LHS <= Value && Value <= RHS) {
5023 Found = SC;
5024 break;
5028 if (!Found)
5029 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5031 // Search the switch body for the switch case and evaluate it from there.
5032 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5033 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5034 return ESR_Failed;
5036 switch (ESR) {
5037 case ESR_Break:
5038 return ESR_Succeeded;
5039 case ESR_Succeeded:
5040 case ESR_Continue:
5041 case ESR_Failed:
5042 case ESR_Returned:
5043 return ESR;
5044 case ESR_CaseNotFound:
5045 // This can only happen if the switch case is nested within a statement
5046 // expression. We have no intention of supporting that.
5047 Info.FFDiag(Found->getBeginLoc(),
5048 diag::note_constexpr_stmt_expr_unsupported);
5049 return ESR_Failed;
5051 llvm_unreachable("Invalid EvalStmtResult!");
5054 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5055 // An expression E is a core constant expression unless the evaluation of E
5056 // would evaluate one of the following: [C++2b] - a control flow that passes
5057 // through a declaration of a variable with static or thread storage duration.
5058 if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5059 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5060 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5061 return false;
5063 return true;
5066 // Evaluate a statement.
5067 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5068 const Stmt *S, const SwitchCase *Case) {
5069 if (!Info.nextStep(S))
5070 return ESR_Failed;
5072 // If we're hunting down a 'case' or 'default' label, recurse through
5073 // substatements until we hit the label.
5074 if (Case) {
5075 switch (S->getStmtClass()) {
5076 case Stmt::CompoundStmtClass:
5077 // FIXME: Precompute which substatement of a compound statement we
5078 // would jump to, and go straight there rather than performing a
5079 // linear scan each time.
5080 case Stmt::LabelStmtClass:
5081 case Stmt::AttributedStmtClass:
5082 case Stmt::DoStmtClass:
5083 break;
5085 case Stmt::CaseStmtClass:
5086 case Stmt::DefaultStmtClass:
5087 if (Case == S)
5088 Case = nullptr;
5089 break;
5091 case Stmt::IfStmtClass: {
5092 // FIXME: Precompute which side of an 'if' we would jump to, and go
5093 // straight there rather than scanning both sides.
5094 const IfStmt *IS = cast<IfStmt>(S);
5096 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5097 // preceded by our switch label.
5098 BlockScopeRAII Scope(Info);
5100 // Step into the init statement in case it brings an (uninitialized)
5101 // variable into scope.
5102 if (const Stmt *Init = IS->getInit()) {
5103 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5104 if (ESR != ESR_CaseNotFound) {
5105 assert(ESR != ESR_Succeeded);
5106 return ESR;
5110 // Condition variable must be initialized if it exists.
5111 // FIXME: We can skip evaluating the body if there's a condition
5112 // variable, as there can't be any case labels within it.
5113 // (The same is true for 'for' statements.)
5115 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5116 if (ESR == ESR_Failed)
5117 return ESR;
5118 if (ESR != ESR_CaseNotFound)
5119 return Scope.destroy() ? ESR : ESR_Failed;
5120 if (!IS->getElse())
5121 return ESR_CaseNotFound;
5123 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5124 if (ESR == ESR_Failed)
5125 return ESR;
5126 if (ESR != ESR_CaseNotFound)
5127 return Scope.destroy() ? ESR : ESR_Failed;
5128 return ESR_CaseNotFound;
5131 case Stmt::WhileStmtClass: {
5132 EvalStmtResult ESR =
5133 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5134 if (ESR != ESR_Continue)
5135 return ESR;
5136 break;
5139 case Stmt::ForStmtClass: {
5140 const ForStmt *FS = cast<ForStmt>(S);
5141 BlockScopeRAII Scope(Info);
5143 // Step into the init statement in case it brings an (uninitialized)
5144 // variable into scope.
5145 if (const Stmt *Init = FS->getInit()) {
5146 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5147 if (ESR != ESR_CaseNotFound) {
5148 assert(ESR != ESR_Succeeded);
5149 return ESR;
5153 EvalStmtResult ESR =
5154 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5155 if (ESR != ESR_Continue)
5156 return ESR;
5157 if (const auto *Inc = FS->getInc()) {
5158 if (Inc->isValueDependent()) {
5159 if (!EvaluateDependentExpr(Inc, Info))
5160 return ESR_Failed;
5161 } else {
5162 FullExpressionRAII IncScope(Info);
5163 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5164 return ESR_Failed;
5167 break;
5170 case Stmt::DeclStmtClass: {
5171 // Start the lifetime of any uninitialized variables we encounter. They
5172 // might be used by the selected branch of the switch.
5173 const DeclStmt *DS = cast<DeclStmt>(S);
5174 for (const auto *D : DS->decls()) {
5175 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5176 if (!CheckLocalVariableDeclaration(Info, VD))
5177 return ESR_Failed;
5178 if (VD->hasLocalStorage() && !VD->getInit())
5179 if (!EvaluateVarDecl(Info, VD))
5180 return ESR_Failed;
5181 // FIXME: If the variable has initialization that can't be jumped
5182 // over, bail out of any immediately-surrounding compound-statement
5183 // too. There can't be any case labels here.
5186 return ESR_CaseNotFound;
5189 default:
5190 return ESR_CaseNotFound;
5194 switch (S->getStmtClass()) {
5195 default:
5196 if (const Expr *E = dyn_cast<Expr>(S)) {
5197 if (E->isValueDependent()) {
5198 if (!EvaluateDependentExpr(E, Info))
5199 return ESR_Failed;
5200 } else {
5201 // Don't bother evaluating beyond an expression-statement which couldn't
5202 // be evaluated.
5203 // FIXME: Do we need the FullExpressionRAII object here?
5204 // VisitExprWithCleanups should create one when necessary.
5205 FullExpressionRAII Scope(Info);
5206 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5207 return ESR_Failed;
5209 return ESR_Succeeded;
5212 Info.FFDiag(S->getBeginLoc());
5213 return ESR_Failed;
5215 case Stmt::NullStmtClass:
5216 return ESR_Succeeded;
5218 case Stmt::DeclStmtClass: {
5219 const DeclStmt *DS = cast<DeclStmt>(S);
5220 for (const auto *D : DS->decls()) {
5221 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5222 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5223 return ESR_Failed;
5224 // Each declaration initialization is its own full-expression.
5225 FullExpressionRAII Scope(Info);
5226 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5227 return ESR_Failed;
5228 if (!Scope.destroy())
5229 return ESR_Failed;
5231 return ESR_Succeeded;
5234 case Stmt::ReturnStmtClass: {
5235 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5236 FullExpressionRAII Scope(Info);
5237 if (RetExpr && RetExpr->isValueDependent()) {
5238 EvaluateDependentExpr(RetExpr, Info);
5239 // We know we returned, but we don't know what the value is.
5240 return ESR_Failed;
5242 if (RetExpr &&
5243 !(Result.Slot
5244 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5245 : Evaluate(Result.Value, Info, RetExpr)))
5246 return ESR_Failed;
5247 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5250 case Stmt::CompoundStmtClass: {
5251 BlockScopeRAII Scope(Info);
5253 const CompoundStmt *CS = cast<CompoundStmt>(S);
5254 for (const auto *BI : CS->body()) {
5255 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5256 if (ESR == ESR_Succeeded)
5257 Case = nullptr;
5258 else if (ESR != ESR_CaseNotFound) {
5259 if (ESR != ESR_Failed && !Scope.destroy())
5260 return ESR_Failed;
5261 return ESR;
5264 if (Case)
5265 return ESR_CaseNotFound;
5266 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5269 case Stmt::IfStmtClass: {
5270 const IfStmt *IS = cast<IfStmt>(S);
5272 // Evaluate the condition, as either a var decl or as an expression.
5273 BlockScopeRAII Scope(Info);
5274 if (const Stmt *Init = IS->getInit()) {
5275 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5276 if (ESR != ESR_Succeeded) {
5277 if (ESR != ESR_Failed && !Scope.destroy())
5278 return ESR_Failed;
5279 return ESR;
5282 bool Cond;
5283 if (IS->isConsteval()) {
5284 Cond = IS->isNonNegatedConsteval();
5285 // If we are not in a constant context, if consteval should not evaluate
5286 // to true.
5287 if (!Info.InConstantContext)
5288 Cond = !Cond;
5289 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5290 Cond))
5291 return ESR_Failed;
5293 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5294 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5295 if (ESR != ESR_Succeeded) {
5296 if (ESR != ESR_Failed && !Scope.destroy())
5297 return ESR_Failed;
5298 return ESR;
5301 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5304 case Stmt::WhileStmtClass: {
5305 const WhileStmt *WS = cast<WhileStmt>(S);
5306 while (true) {
5307 BlockScopeRAII Scope(Info);
5308 bool Continue;
5309 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5310 Continue))
5311 return ESR_Failed;
5312 if (!Continue)
5313 break;
5315 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5316 if (ESR != ESR_Continue) {
5317 if (ESR != ESR_Failed && !Scope.destroy())
5318 return ESR_Failed;
5319 return ESR;
5321 if (!Scope.destroy())
5322 return ESR_Failed;
5324 return ESR_Succeeded;
5327 case Stmt::DoStmtClass: {
5328 const DoStmt *DS = cast<DoStmt>(S);
5329 bool Continue;
5330 do {
5331 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5332 if (ESR != ESR_Continue)
5333 return ESR;
5334 Case = nullptr;
5336 if (DS->getCond()->isValueDependent()) {
5337 EvaluateDependentExpr(DS->getCond(), Info);
5338 // Bailout as we don't know whether to keep going or terminate the loop.
5339 return ESR_Failed;
5341 FullExpressionRAII CondScope(Info);
5342 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5343 !CondScope.destroy())
5344 return ESR_Failed;
5345 } while (Continue);
5346 return ESR_Succeeded;
5349 case Stmt::ForStmtClass: {
5350 const ForStmt *FS = cast<ForStmt>(S);
5351 BlockScopeRAII ForScope(Info);
5352 if (FS->getInit()) {
5353 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5354 if (ESR != ESR_Succeeded) {
5355 if (ESR != ESR_Failed && !ForScope.destroy())
5356 return ESR_Failed;
5357 return ESR;
5360 while (true) {
5361 BlockScopeRAII IterScope(Info);
5362 bool Continue = true;
5363 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5364 FS->getCond(), Continue))
5365 return ESR_Failed;
5366 if (!Continue)
5367 break;
5369 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5370 if (ESR != ESR_Continue) {
5371 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5372 return ESR_Failed;
5373 return ESR;
5376 if (const auto *Inc = FS->getInc()) {
5377 if (Inc->isValueDependent()) {
5378 if (!EvaluateDependentExpr(Inc, Info))
5379 return ESR_Failed;
5380 } else {
5381 FullExpressionRAII IncScope(Info);
5382 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5383 return ESR_Failed;
5387 if (!IterScope.destroy())
5388 return ESR_Failed;
5390 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5393 case Stmt::CXXForRangeStmtClass: {
5394 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5395 BlockScopeRAII Scope(Info);
5397 // Evaluate the init-statement if present.
5398 if (FS->getInit()) {
5399 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5400 if (ESR != ESR_Succeeded) {
5401 if (ESR != ESR_Failed && !Scope.destroy())
5402 return ESR_Failed;
5403 return ESR;
5407 // Initialize the __range variable.
5408 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5409 if (ESR != ESR_Succeeded) {
5410 if (ESR != ESR_Failed && !Scope.destroy())
5411 return ESR_Failed;
5412 return ESR;
5415 // In error-recovery cases it's possible to get here even if we failed to
5416 // synthesize the __begin and __end variables.
5417 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5418 return ESR_Failed;
5420 // Create the __begin and __end iterators.
5421 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5422 if (ESR != ESR_Succeeded) {
5423 if (ESR != ESR_Failed && !Scope.destroy())
5424 return ESR_Failed;
5425 return ESR;
5427 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5428 if (ESR != ESR_Succeeded) {
5429 if (ESR != ESR_Failed && !Scope.destroy())
5430 return ESR_Failed;
5431 return ESR;
5434 while (true) {
5435 // Condition: __begin != __end.
5437 if (FS->getCond()->isValueDependent()) {
5438 EvaluateDependentExpr(FS->getCond(), Info);
5439 // We don't know whether to keep going or terminate the loop.
5440 return ESR_Failed;
5442 bool Continue = true;
5443 FullExpressionRAII CondExpr(Info);
5444 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5445 return ESR_Failed;
5446 if (!Continue)
5447 break;
5450 // User's variable declaration, initialized by *__begin.
5451 BlockScopeRAII InnerScope(Info);
5452 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5453 if (ESR != ESR_Succeeded) {
5454 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5455 return ESR_Failed;
5456 return ESR;
5459 // Loop body.
5460 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5461 if (ESR != ESR_Continue) {
5462 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5463 return ESR_Failed;
5464 return ESR;
5466 if (FS->getInc()->isValueDependent()) {
5467 if (!EvaluateDependentExpr(FS->getInc(), Info))
5468 return ESR_Failed;
5469 } else {
5470 // Increment: ++__begin
5471 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5472 return ESR_Failed;
5475 if (!InnerScope.destroy())
5476 return ESR_Failed;
5479 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5482 case Stmt::SwitchStmtClass:
5483 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5485 case Stmt::ContinueStmtClass:
5486 return ESR_Continue;
5488 case Stmt::BreakStmtClass:
5489 return ESR_Break;
5491 case Stmt::LabelStmtClass:
5492 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5494 case Stmt::AttributedStmtClass:
5495 // As a general principle, C++11 attributes can be ignored without
5496 // any semantic impact.
5497 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5498 Case);
5500 case Stmt::CaseStmtClass:
5501 case Stmt::DefaultStmtClass:
5502 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5503 case Stmt::CXXTryStmtClass:
5504 // Evaluate try blocks by evaluating all sub statements.
5505 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5509 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5510 /// default constructor. If so, we'll fold it whether or not it's marked as
5511 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5512 /// so we need special handling.
5513 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5514 const CXXConstructorDecl *CD,
5515 bool IsValueInitialization) {
5516 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5517 return false;
5519 // Value-initialization does not call a trivial default constructor, so such a
5520 // call is a core constant expression whether or not the constructor is
5521 // constexpr.
5522 if (!CD->isConstexpr() && !IsValueInitialization) {
5523 if (Info.getLangOpts().CPlusPlus11) {
5524 // FIXME: If DiagDecl is an implicitly-declared special member function,
5525 // we should be much more explicit about why it's not constexpr.
5526 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5527 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5528 Info.Note(CD->getLocation(), diag::note_declared_at);
5529 } else {
5530 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5533 return true;
5536 /// CheckConstexprFunction - Check that a function can be called in a constant
5537 /// expression.
5538 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5539 const FunctionDecl *Declaration,
5540 const FunctionDecl *Definition,
5541 const Stmt *Body) {
5542 // Potential constant expressions can contain calls to declared, but not yet
5543 // defined, constexpr functions.
5544 if (Info.checkingPotentialConstantExpression() && !Definition &&
5545 Declaration->isConstexpr())
5546 return false;
5548 // Bail out if the function declaration itself is invalid. We will
5549 // have produced a relevant diagnostic while parsing it, so just
5550 // note the problematic sub-expression.
5551 if (Declaration->isInvalidDecl()) {
5552 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5553 return false;
5556 // DR1872: An instantiated virtual constexpr function can't be called in a
5557 // constant expression (prior to C++20). We can still constant-fold such a
5558 // call.
5559 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5560 cast<CXXMethodDecl>(Declaration)->isVirtual())
5561 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5563 if (Definition && Definition->isInvalidDecl()) {
5564 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5565 return false;
5568 // Can we evaluate this function call?
5569 if (Definition && Definition->isConstexpr() && Body)
5570 return true;
5572 if (Info.getLangOpts().CPlusPlus11) {
5573 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5575 // If this function is not constexpr because it is an inherited
5576 // non-constexpr constructor, diagnose that directly.
5577 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5578 if (CD && CD->isInheritingConstructor()) {
5579 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5580 if (!Inherited->isConstexpr())
5581 DiagDecl = CD = Inherited;
5584 // FIXME: If DiagDecl is an implicitly-declared special member function
5585 // or an inheriting constructor, we should be much more explicit about why
5586 // it's not constexpr.
5587 if (CD && CD->isInheritingConstructor())
5588 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5589 << CD->getInheritedConstructor().getConstructor()->getParent();
5590 else
5591 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5592 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5593 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5594 } else {
5595 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5597 return false;
5600 namespace {
5601 struct CheckDynamicTypeHandler {
5602 AccessKinds AccessKind;
5603 typedef bool result_type;
5604 bool failed() { return false; }
5605 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5606 bool found(APSInt &Value, QualType SubobjType) { return true; }
5607 bool found(APFloat &Value, QualType SubobjType) { return true; }
5609 } // end anonymous namespace
5611 /// Check that we can access the notional vptr of an object / determine its
5612 /// dynamic type.
5613 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5614 AccessKinds AK, bool Polymorphic) {
5615 if (This.Designator.Invalid)
5616 return false;
5618 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5620 if (!Obj)
5621 return false;
5623 if (!Obj.Value) {
5624 // The object is not usable in constant expressions, so we can't inspect
5625 // its value to see if it's in-lifetime or what the active union members
5626 // are. We can still check for a one-past-the-end lvalue.
5627 if (This.Designator.isOnePastTheEnd() ||
5628 This.Designator.isMostDerivedAnUnsizedArray()) {
5629 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5630 ? diag::note_constexpr_access_past_end
5631 : diag::note_constexpr_access_unsized_array)
5632 << AK;
5633 return false;
5634 } else if (Polymorphic) {
5635 // Conservatively refuse to perform a polymorphic operation if we would
5636 // not be able to read a notional 'vptr' value.
5637 APValue Val;
5638 This.moveInto(Val);
5639 QualType StarThisType =
5640 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5641 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5642 << AK << Val.getAsString(Info.Ctx, StarThisType);
5643 return false;
5645 return true;
5648 CheckDynamicTypeHandler Handler{AK};
5649 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5652 /// Check that the pointee of the 'this' pointer in a member function call is
5653 /// either within its lifetime or in its period of construction or destruction.
5654 static bool
5655 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5656 const LValue &This,
5657 const CXXMethodDecl *NamedMember) {
5658 return checkDynamicType(
5659 Info, E, This,
5660 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5663 struct DynamicType {
5664 /// The dynamic class type of the object.
5665 const CXXRecordDecl *Type;
5666 /// The corresponding path length in the lvalue.
5667 unsigned PathLength;
5670 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5671 unsigned PathLength) {
5672 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5673 Designator.Entries.size() && "invalid path length");
5674 return (PathLength == Designator.MostDerivedPathLength)
5675 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5676 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5679 /// Determine the dynamic type of an object.
5680 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5681 LValue &This, AccessKinds AK) {
5682 // If we don't have an lvalue denoting an object of class type, there is no
5683 // meaningful dynamic type. (We consider objects of non-class type to have no
5684 // dynamic type.)
5685 if (!checkDynamicType(Info, E, This, AK, true))
5686 return None;
5688 // Refuse to compute a dynamic type in the presence of virtual bases. This
5689 // shouldn't happen other than in constant-folding situations, since literal
5690 // types can't have virtual bases.
5692 // Note that consumers of DynamicType assume that the type has no virtual
5693 // bases, and will need modifications if this restriction is relaxed.
5694 const CXXRecordDecl *Class =
5695 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5696 if (!Class || Class->getNumVBases()) {
5697 Info.FFDiag(E);
5698 return None;
5701 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5702 // binary search here instead. But the overwhelmingly common case is that
5703 // we're not in the middle of a constructor, so it probably doesn't matter
5704 // in practice.
5705 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5706 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5707 PathLength <= Path.size(); ++PathLength) {
5708 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5709 Path.slice(0, PathLength))) {
5710 case ConstructionPhase::Bases:
5711 case ConstructionPhase::DestroyingBases:
5712 // We're constructing or destroying a base class. This is not the dynamic
5713 // type.
5714 break;
5716 case ConstructionPhase::None:
5717 case ConstructionPhase::AfterBases:
5718 case ConstructionPhase::AfterFields:
5719 case ConstructionPhase::Destroying:
5720 // We've finished constructing the base classes and not yet started
5721 // destroying them again, so this is the dynamic type.
5722 return DynamicType{getBaseClassType(This.Designator, PathLength),
5723 PathLength};
5727 // CWG issue 1517: we're constructing a base class of the object described by
5728 // 'This', so that object has not yet begun its period of construction and
5729 // any polymorphic operation on it results in undefined behavior.
5730 Info.FFDiag(E);
5731 return None;
5734 /// Perform virtual dispatch.
5735 static const CXXMethodDecl *HandleVirtualDispatch(
5736 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5737 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5738 Optional<DynamicType> DynType = ComputeDynamicType(
5739 Info, E, This,
5740 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5741 if (!DynType)
5742 return nullptr;
5744 // Find the final overrider. It must be declared in one of the classes on the
5745 // path from the dynamic type to the static type.
5746 // FIXME: If we ever allow literal types to have virtual base classes, that
5747 // won't be true.
5748 const CXXMethodDecl *Callee = Found;
5749 unsigned PathLength = DynType->PathLength;
5750 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5751 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5752 const CXXMethodDecl *Overrider =
5753 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5754 if (Overrider) {
5755 Callee = Overrider;
5756 break;
5760 // C++2a [class.abstract]p6:
5761 // the effect of making a virtual call to a pure virtual function [...] is
5762 // undefined
5763 if (Callee->isPure()) {
5764 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5765 Info.Note(Callee->getLocation(), diag::note_declared_at);
5766 return nullptr;
5769 // If necessary, walk the rest of the path to determine the sequence of
5770 // covariant adjustment steps to apply.
5771 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5772 Found->getReturnType())) {
5773 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5774 for (unsigned CovariantPathLength = PathLength + 1;
5775 CovariantPathLength != This.Designator.Entries.size();
5776 ++CovariantPathLength) {
5777 const CXXRecordDecl *NextClass =
5778 getBaseClassType(This.Designator, CovariantPathLength);
5779 const CXXMethodDecl *Next =
5780 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5781 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5782 Next->getReturnType(), CovariantAdjustmentPath.back()))
5783 CovariantAdjustmentPath.push_back(Next->getReturnType());
5785 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5786 CovariantAdjustmentPath.back()))
5787 CovariantAdjustmentPath.push_back(Found->getReturnType());
5790 // Perform 'this' adjustment.
5791 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5792 return nullptr;
5794 return Callee;
5797 /// Perform the adjustment from a value returned by a virtual function to
5798 /// a value of the statically expected type, which may be a pointer or
5799 /// reference to a base class of the returned type.
5800 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5801 APValue &Result,
5802 ArrayRef<QualType> Path) {
5803 assert(Result.isLValue() &&
5804 "unexpected kind of APValue for covariant return");
5805 if (Result.isNullPointer())
5806 return true;
5808 LValue LVal;
5809 LVal.setFrom(Info.Ctx, Result);
5811 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5812 for (unsigned I = 1; I != Path.size(); ++I) {
5813 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5814 assert(OldClass && NewClass && "unexpected kind of covariant return");
5815 if (OldClass != NewClass &&
5816 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5817 return false;
5818 OldClass = NewClass;
5821 LVal.moveInto(Result);
5822 return true;
5825 /// Determine whether \p Base, which is known to be a direct base class of
5826 /// \p Derived, is a public base class.
5827 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5828 const CXXRecordDecl *Base) {
5829 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5830 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5831 if (BaseClass && declaresSameEntity(BaseClass, Base))
5832 return BaseSpec.getAccessSpecifier() == AS_public;
5834 llvm_unreachable("Base is not a direct base of Derived");
5837 /// Apply the given dynamic cast operation on the provided lvalue.
5839 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5840 /// to find a suitable target subobject.
5841 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5842 LValue &Ptr) {
5843 // We can't do anything with a non-symbolic pointer value.
5844 SubobjectDesignator &D = Ptr.Designator;
5845 if (D.Invalid)
5846 return false;
5848 // C++ [expr.dynamic.cast]p6:
5849 // If v is a null pointer value, the result is a null pointer value.
5850 if (Ptr.isNullPointer() && !E->isGLValue())
5851 return true;
5853 // For all the other cases, we need the pointer to point to an object within
5854 // its lifetime / period of construction / destruction, and we need to know
5855 // its dynamic type.
5856 Optional<DynamicType> DynType =
5857 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5858 if (!DynType)
5859 return false;
5861 // C++ [expr.dynamic.cast]p7:
5862 // If T is "pointer to cv void", then the result is a pointer to the most
5863 // derived object
5864 if (E->getType()->isVoidPointerType())
5865 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5867 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5868 assert(C && "dynamic_cast target is not void pointer nor class");
5869 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5871 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5872 // C++ [expr.dynamic.cast]p9:
5873 if (!E->isGLValue()) {
5874 // The value of a failed cast to pointer type is the null pointer value
5875 // of the required result type.
5876 Ptr.setNull(Info.Ctx, E->getType());
5877 return true;
5880 // A failed cast to reference type throws [...] std::bad_cast.
5881 unsigned DiagKind;
5882 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5883 DynType->Type->isDerivedFrom(C)))
5884 DiagKind = 0;
5885 else if (!Paths || Paths->begin() == Paths->end())
5886 DiagKind = 1;
5887 else if (Paths->isAmbiguous(CQT))
5888 DiagKind = 2;
5889 else {
5890 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5891 DiagKind = 3;
5893 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5894 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5895 << Info.Ctx.getRecordType(DynType->Type)
5896 << E->getType().getUnqualifiedType();
5897 return false;
5900 // Runtime check, phase 1:
5901 // Walk from the base subobject towards the derived object looking for the
5902 // target type.
5903 for (int PathLength = Ptr.Designator.Entries.size();
5904 PathLength >= (int)DynType->PathLength; --PathLength) {
5905 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5906 if (declaresSameEntity(Class, C))
5907 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5908 // We can only walk across public inheritance edges.
5909 if (PathLength > (int)DynType->PathLength &&
5910 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5911 Class))
5912 return RuntimeCheckFailed(nullptr);
5915 // Runtime check, phase 2:
5916 // Search the dynamic type for an unambiguous public base of type C.
5917 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5918 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5919 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5920 Paths.front().Access == AS_public) {
5921 // Downcast to the dynamic type...
5922 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5923 return false;
5924 // ... then upcast to the chosen base class subobject.
5925 for (CXXBasePathElement &Elem : Paths.front())
5926 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5927 return false;
5928 return true;
5931 // Otherwise, the runtime check fails.
5932 return RuntimeCheckFailed(&Paths);
5935 namespace {
5936 struct StartLifetimeOfUnionMemberHandler {
5937 EvalInfo &Info;
5938 const Expr *LHSExpr;
5939 const FieldDecl *Field;
5940 bool DuringInit;
5941 bool Failed = false;
5942 static const AccessKinds AccessKind = AK_Assign;
5944 typedef bool result_type;
5945 bool failed() { return Failed; }
5946 bool found(APValue &Subobj, QualType SubobjType) {
5947 // We are supposed to perform no initialization but begin the lifetime of
5948 // the object. We interpret that as meaning to do what default
5949 // initialization of the object would do if all constructors involved were
5950 // trivial:
5951 // * All base, non-variant member, and array element subobjects' lifetimes
5952 // begin
5953 // * No variant members' lifetimes begin
5954 // * All scalar subobjects whose lifetimes begin have indeterminate values
5955 assert(SubobjType->isUnionType());
5956 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5957 // This union member is already active. If it's also in-lifetime, there's
5958 // nothing to do.
5959 if (Subobj.getUnionValue().hasValue())
5960 return true;
5961 } else if (DuringInit) {
5962 // We're currently in the process of initializing a different union
5963 // member. If we carried on, that initialization would attempt to
5964 // store to an inactive union member, resulting in undefined behavior.
5965 Info.FFDiag(LHSExpr,
5966 diag::note_constexpr_union_member_change_during_init);
5967 return false;
5969 APValue Result;
5970 Failed = !getDefaultInitValue(Field->getType(), Result);
5971 Subobj.setUnion(Field, Result);
5972 return true;
5974 bool found(APSInt &Value, QualType SubobjType) {
5975 llvm_unreachable("wrong value kind for union object");
5977 bool found(APFloat &Value, QualType SubobjType) {
5978 llvm_unreachable("wrong value kind for union object");
5981 } // end anonymous namespace
5983 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5985 /// Handle a builtin simple-assignment or a call to a trivial assignment
5986 /// operator whose left-hand side might involve a union member access. If it
5987 /// does, implicitly start the lifetime of any accessed union elements per
5988 /// C++20 [class.union]5.
5989 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5990 const LValue &LHS) {
5991 if (LHS.InvalidBase || LHS.Designator.Invalid)
5992 return false;
5994 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5995 // C++ [class.union]p5:
5996 // define the set S(E) of subexpressions of E as follows:
5997 unsigned PathLength = LHS.Designator.Entries.size();
5998 for (const Expr *E = LHSExpr; E != nullptr;) {
5999 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6000 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6001 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6002 // Note that we can't implicitly start the lifetime of a reference,
6003 // so we don't need to proceed any further if we reach one.
6004 if (!FD || FD->getType()->isReferenceType())
6005 break;
6007 // ... and also contains A.B if B names a union member ...
6008 if (FD->getParent()->isUnion()) {
6009 // ... of a non-class, non-array type, or of a class type with a
6010 // trivial default constructor that is not deleted, or an array of
6011 // such types.
6012 auto *RD =
6013 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6014 if (!RD || RD->hasTrivialDefaultConstructor())
6015 UnionPathLengths.push_back({PathLength - 1, FD});
6018 E = ME->getBase();
6019 --PathLength;
6020 assert(declaresSameEntity(FD,
6021 LHS.Designator.Entries[PathLength]
6022 .getAsBaseOrMember().getPointer()));
6024 // -- If E is of the form A[B] and is interpreted as a built-in array
6025 // subscripting operator, S(E) is [S(the array operand, if any)].
6026 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6027 // Step over an ArrayToPointerDecay implicit cast.
6028 auto *Base = ASE->getBase()->IgnoreImplicit();
6029 if (!Base->getType()->isArrayType())
6030 break;
6032 E = Base;
6033 --PathLength;
6035 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6036 // Step over a derived-to-base conversion.
6037 E = ICE->getSubExpr();
6038 if (ICE->getCastKind() == CK_NoOp)
6039 continue;
6040 if (ICE->getCastKind() != CK_DerivedToBase &&
6041 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6042 break;
6043 // Walk path backwards as we walk up from the base to the derived class.
6044 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6045 --PathLength;
6046 (void)Elt;
6047 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6048 LHS.Designator.Entries[PathLength]
6049 .getAsBaseOrMember().getPointer()));
6052 // -- Otherwise, S(E) is empty.
6053 } else {
6054 break;
6058 // Common case: no unions' lifetimes are started.
6059 if (UnionPathLengths.empty())
6060 return true;
6062 // if modification of X [would access an inactive union member], an object
6063 // of the type of X is implicitly created
6064 CompleteObject Obj =
6065 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6066 if (!Obj)
6067 return false;
6068 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6069 llvm::reverse(UnionPathLengths)) {
6070 // Form a designator for the union object.
6071 SubobjectDesignator D = LHS.Designator;
6072 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6074 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6075 ConstructionPhase::AfterBases;
6076 StartLifetimeOfUnionMemberHandler StartLifetime{
6077 Info, LHSExpr, LengthAndField.second, DuringInit};
6078 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6079 return false;
6082 return true;
6085 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6086 CallRef Call, EvalInfo &Info,
6087 bool NonNull = false) {
6088 LValue LV;
6089 // Create the parameter slot and register its destruction. For a vararg
6090 // argument, create a temporary.
6091 // FIXME: For calling conventions that destroy parameters in the callee,
6092 // should we consider performing destruction when the function returns
6093 // instead?
6094 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6095 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6096 ScopeKind::Call, LV);
6097 if (!EvaluateInPlace(V, Info, LV, Arg))
6098 return false;
6100 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6101 // undefined behavior, so is non-constant.
6102 if (NonNull && V.isLValue() && V.isNullPointer()) {
6103 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6104 return false;
6107 return true;
6110 /// Evaluate the arguments to a function call.
6111 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6112 EvalInfo &Info, const FunctionDecl *Callee,
6113 bool RightToLeft = false) {
6114 bool Success = true;
6115 llvm::SmallBitVector ForbiddenNullArgs;
6116 if (Callee->hasAttr<NonNullAttr>()) {
6117 ForbiddenNullArgs.resize(Args.size());
6118 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6119 if (!Attr->args_size()) {
6120 ForbiddenNullArgs.set();
6121 break;
6122 } else
6123 for (auto Idx : Attr->args()) {
6124 unsigned ASTIdx = Idx.getASTIndex();
6125 if (ASTIdx >= Args.size())
6126 continue;
6127 ForbiddenNullArgs[ASTIdx] = true;
6131 for (unsigned I = 0; I < Args.size(); I++) {
6132 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6133 const ParmVarDecl *PVD =
6134 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6135 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6136 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6137 // If we're checking for a potential constant expression, evaluate all
6138 // initializers even if some of them fail.
6139 if (!Info.noteFailure())
6140 return false;
6141 Success = false;
6144 return Success;
6147 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6148 /// constructor or assignment operator.
6149 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6150 const Expr *E, APValue &Result,
6151 bool CopyObjectRepresentation) {
6152 // Find the reference argument.
6153 CallStackFrame *Frame = Info.CurrentCall;
6154 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6155 if (!RefValue) {
6156 Info.FFDiag(E);
6157 return false;
6160 // Copy out the contents of the RHS object.
6161 LValue RefLValue;
6162 RefLValue.setFrom(Info.Ctx, *RefValue);
6163 return handleLValueToRValueConversion(
6164 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6165 CopyObjectRepresentation);
6168 /// Evaluate a function call.
6169 static bool HandleFunctionCall(SourceLocation CallLoc,
6170 const FunctionDecl *Callee, const LValue *This,
6171 ArrayRef<const Expr *> Args, CallRef Call,
6172 const Stmt *Body, EvalInfo &Info,
6173 APValue &Result, const LValue *ResultSlot) {
6174 if (!Info.CheckCallLimit(CallLoc))
6175 return false;
6177 CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6179 // For a trivial copy or move assignment, perform an APValue copy. This is
6180 // essential for unions, where the operations performed by the assignment
6181 // operator cannot be represented as statements.
6183 // Skip this for non-union classes with no fields; in that case, the defaulted
6184 // copy/move does not actually read the object.
6185 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6186 if (MD && MD->isDefaulted() &&
6187 (MD->getParent()->isUnion() ||
6188 (MD->isTrivial() &&
6189 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6190 assert(This &&
6191 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6192 APValue RHSValue;
6193 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6194 MD->getParent()->isUnion()))
6195 return false;
6196 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6197 RHSValue))
6198 return false;
6199 This->moveInto(Result);
6200 return true;
6201 } else if (MD && isLambdaCallOperator(MD)) {
6202 // We're in a lambda; determine the lambda capture field maps unless we're
6203 // just constexpr checking a lambda's call operator. constexpr checking is
6204 // done before the captures have been added to the closure object (unless
6205 // we're inferring constexpr-ness), so we don't have access to them in this
6206 // case. But since we don't need the captures to constexpr check, we can
6207 // just ignore them.
6208 if (!Info.checkingPotentialConstantExpression())
6209 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6210 Frame.LambdaThisCaptureField);
6213 StmtResult Ret = {Result, ResultSlot};
6214 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6215 if (ESR == ESR_Succeeded) {
6216 if (Callee->getReturnType()->isVoidType())
6217 return true;
6218 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6220 return ESR == ESR_Returned;
6223 /// Evaluate a constructor call.
6224 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6225 CallRef Call,
6226 const CXXConstructorDecl *Definition,
6227 EvalInfo &Info, APValue &Result) {
6228 SourceLocation CallLoc = E->getExprLoc();
6229 if (!Info.CheckCallLimit(CallLoc))
6230 return false;
6232 const CXXRecordDecl *RD = Definition->getParent();
6233 if (RD->getNumVBases()) {
6234 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6235 return false;
6238 EvalInfo::EvaluatingConstructorRAII EvalObj(
6239 Info,
6240 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6241 RD->getNumBases());
6242 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6244 // FIXME: Creating an APValue just to hold a nonexistent return value is
6245 // wasteful.
6246 APValue RetVal;
6247 StmtResult Ret = {RetVal, nullptr};
6249 // If it's a delegating constructor, delegate.
6250 if (Definition->isDelegatingConstructor()) {
6251 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6252 if ((*I)->getInit()->isValueDependent()) {
6253 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6254 return false;
6255 } else {
6256 FullExpressionRAII InitScope(Info);
6257 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6258 !InitScope.destroy())
6259 return false;
6261 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6264 // For a trivial copy or move constructor, perform an APValue copy. This is
6265 // essential for unions (or classes with anonymous union members), where the
6266 // operations performed by the constructor cannot be represented by
6267 // ctor-initializers.
6269 // Skip this for empty non-union classes; we should not perform an
6270 // lvalue-to-rvalue conversion on them because their copy constructor does not
6271 // actually read them.
6272 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6273 (Definition->getParent()->isUnion() ||
6274 (Definition->isTrivial() &&
6275 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6276 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6277 Definition->getParent()->isUnion());
6280 // Reserve space for the struct members.
6281 if (!Result.hasValue()) {
6282 if (!RD->isUnion())
6283 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6284 std::distance(RD->field_begin(), RD->field_end()));
6285 else
6286 // A union starts with no active member.
6287 Result = APValue((const FieldDecl*)nullptr);
6290 if (RD->isInvalidDecl()) return false;
6291 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6293 // A scope for temporaries lifetime-extended by reference members.
6294 BlockScopeRAII LifetimeExtendedScope(Info);
6296 bool Success = true;
6297 unsigned BasesSeen = 0;
6298 #ifndef NDEBUG
6299 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6300 #endif
6301 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6302 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6303 // We might be initializing the same field again if this is an indirect
6304 // field initialization.
6305 if (FieldIt == RD->field_end() ||
6306 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6307 assert(Indirect && "fields out of order?");
6308 return;
6311 // Default-initialize any fields with no explicit initializer.
6312 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6313 assert(FieldIt != RD->field_end() && "missing field?");
6314 if (!FieldIt->isUnnamedBitfield())
6315 Success &= getDefaultInitValue(
6316 FieldIt->getType(),
6317 Result.getStructField(FieldIt->getFieldIndex()));
6319 ++FieldIt;
6321 for (const auto *I : Definition->inits()) {
6322 LValue Subobject = This;
6323 LValue SubobjectParent = This;
6324 APValue *Value = &Result;
6326 // Determine the subobject to initialize.
6327 FieldDecl *FD = nullptr;
6328 if (I->isBaseInitializer()) {
6329 QualType BaseType(I->getBaseClass(), 0);
6330 #ifndef NDEBUG
6331 // Non-virtual base classes are initialized in the order in the class
6332 // definition. We have already checked for virtual base classes.
6333 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6334 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6335 "base class initializers not in expected order");
6336 ++BaseIt;
6337 #endif
6338 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6339 BaseType->getAsCXXRecordDecl(), &Layout))
6340 return false;
6341 Value = &Result.getStructBase(BasesSeen++);
6342 } else if ((FD = I->getMember())) {
6343 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6344 return false;
6345 if (RD->isUnion()) {
6346 Result = APValue(FD);
6347 Value = &Result.getUnionValue();
6348 } else {
6349 SkipToField(FD, false);
6350 Value = &Result.getStructField(FD->getFieldIndex());
6352 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6353 // Walk the indirect field decl's chain to find the object to initialize,
6354 // and make sure we've initialized every step along it.
6355 auto IndirectFieldChain = IFD->chain();
6356 for (auto *C : IndirectFieldChain) {
6357 FD = cast<FieldDecl>(C);
6358 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6359 // Switch the union field if it differs. This happens if we had
6360 // preceding zero-initialization, and we're now initializing a union
6361 // subobject other than the first.
6362 // FIXME: In this case, the values of the other subobjects are
6363 // specified, since zero-initialization sets all padding bits to zero.
6364 if (!Value->hasValue() ||
6365 (Value->isUnion() && Value->getUnionField() != FD)) {
6366 if (CD->isUnion())
6367 *Value = APValue(FD);
6368 else
6369 // FIXME: This immediately starts the lifetime of all members of
6370 // an anonymous struct. It would be preferable to strictly start
6371 // member lifetime in initialization order.
6372 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6374 // Store Subobject as its parent before updating it for the last element
6375 // in the chain.
6376 if (C == IndirectFieldChain.back())
6377 SubobjectParent = Subobject;
6378 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6379 return false;
6380 if (CD->isUnion())
6381 Value = &Value->getUnionValue();
6382 else {
6383 if (C == IndirectFieldChain.front() && !RD->isUnion())
6384 SkipToField(FD, true);
6385 Value = &Value->getStructField(FD->getFieldIndex());
6388 } else {
6389 llvm_unreachable("unknown base initializer kind");
6392 // Need to override This for implicit field initializers as in this case
6393 // This refers to innermost anonymous struct/union containing initializer,
6394 // not to currently constructed class.
6395 const Expr *Init = I->getInit();
6396 if (Init->isValueDependent()) {
6397 if (!EvaluateDependentExpr(Init, Info))
6398 return false;
6399 } else {
6400 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6401 isa<CXXDefaultInitExpr>(Init));
6402 FullExpressionRAII InitScope(Info);
6403 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6404 (FD && FD->isBitField() &&
6405 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6406 // If we're checking for a potential constant expression, evaluate all
6407 // initializers even if some of them fail.
6408 if (!Info.noteFailure())
6409 return false;
6410 Success = false;
6414 // This is the point at which the dynamic type of the object becomes this
6415 // class type.
6416 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6417 EvalObj.finishedConstructingBases();
6420 // Default-initialize any remaining fields.
6421 if (!RD->isUnion()) {
6422 for (; FieldIt != RD->field_end(); ++FieldIt) {
6423 if (!FieldIt->isUnnamedBitfield())
6424 Success &= getDefaultInitValue(
6425 FieldIt->getType(),
6426 Result.getStructField(FieldIt->getFieldIndex()));
6430 EvalObj.finishedConstructingFields();
6432 return Success &&
6433 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6434 LifetimeExtendedScope.destroy();
6437 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6438 ArrayRef<const Expr*> Args,
6439 const CXXConstructorDecl *Definition,
6440 EvalInfo &Info, APValue &Result) {
6441 CallScopeRAII CallScope(Info);
6442 CallRef Call = Info.CurrentCall->createCall(Definition);
6443 if (!EvaluateArgs(Args, Call, Info, Definition))
6444 return false;
6446 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6447 CallScope.destroy();
6450 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6451 const LValue &This, APValue &Value,
6452 QualType T) {
6453 // Objects can only be destroyed while they're within their lifetimes.
6454 // FIXME: We have no representation for whether an object of type nullptr_t
6455 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6456 // as indeterminate instead?
6457 if (Value.isAbsent() && !T->isNullPtrType()) {
6458 APValue Printable;
6459 This.moveInto(Printable);
6460 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6461 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6462 return false;
6465 // Invent an expression for location purposes.
6466 // FIXME: We shouldn't need to do this.
6467 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6469 // For arrays, destroy elements right-to-left.
6470 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6471 uint64_t Size = CAT->getSize().getZExtValue();
6472 QualType ElemT = CAT->getElementType();
6474 LValue ElemLV = This;
6475 ElemLV.addArray(Info, &LocE, CAT);
6476 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6477 return false;
6479 // Ensure that we have actual array elements available to destroy; the
6480 // destructors might mutate the value, so we can't run them on the array
6481 // filler.
6482 if (Size && Size > Value.getArrayInitializedElts())
6483 expandArray(Value, Value.getArraySize() - 1);
6485 for (; Size != 0; --Size) {
6486 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6487 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6488 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6489 return false;
6492 // End the lifetime of this array now.
6493 Value = APValue();
6494 return true;
6497 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6498 if (!RD) {
6499 if (T.isDestructedType()) {
6500 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6501 return false;
6504 Value = APValue();
6505 return true;
6508 if (RD->getNumVBases()) {
6509 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6510 return false;
6513 const CXXDestructorDecl *DD = RD->getDestructor();
6514 if (!DD && !RD->hasTrivialDestructor()) {
6515 Info.FFDiag(CallLoc);
6516 return false;
6519 if (!DD || DD->isTrivial() ||
6520 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6521 // A trivial destructor just ends the lifetime of the object. Check for
6522 // this case before checking for a body, because we might not bother
6523 // building a body for a trivial destructor. Note that it doesn't matter
6524 // whether the destructor is constexpr in this case; all trivial
6525 // destructors are constexpr.
6527 // If an anonymous union would be destroyed, some enclosing destructor must
6528 // have been explicitly defined, and the anonymous union destruction should
6529 // have no effect.
6530 Value = APValue();
6531 return true;
6534 if (!Info.CheckCallLimit(CallLoc))
6535 return false;
6537 const FunctionDecl *Definition = nullptr;
6538 const Stmt *Body = DD->getBody(Definition);
6540 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6541 return false;
6543 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6545 // We're now in the period of destruction of this object.
6546 unsigned BasesLeft = RD->getNumBases();
6547 EvalInfo::EvaluatingDestructorRAII EvalObj(
6548 Info,
6549 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6550 if (!EvalObj.DidInsert) {
6551 // C++2a [class.dtor]p19:
6552 // the behavior is undefined if the destructor is invoked for an object
6553 // whose lifetime has ended
6554 // (Note that formally the lifetime ends when the period of destruction
6555 // begins, even though certain uses of the object remain valid until the
6556 // period of destruction ends.)
6557 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6558 return false;
6561 // FIXME: Creating an APValue just to hold a nonexistent return value is
6562 // wasteful.
6563 APValue RetVal;
6564 StmtResult Ret = {RetVal, nullptr};
6565 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6566 return false;
6568 // A union destructor does not implicitly destroy its members.
6569 if (RD->isUnion())
6570 return true;
6572 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6574 // We don't have a good way to iterate fields in reverse, so collect all the
6575 // fields first and then walk them backwards.
6576 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6577 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6578 if (FD->isUnnamedBitfield())
6579 continue;
6581 LValue Subobject = This;
6582 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6583 return false;
6585 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6586 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6587 FD->getType()))
6588 return false;
6591 if (BasesLeft != 0)
6592 EvalObj.startedDestroyingBases();
6594 // Destroy base classes in reverse order.
6595 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6596 --BasesLeft;
6598 QualType BaseType = Base.getType();
6599 LValue Subobject = This;
6600 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6601 BaseType->getAsCXXRecordDecl(), &Layout))
6602 return false;
6604 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6605 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6606 BaseType))
6607 return false;
6609 assert(BasesLeft == 0 && "NumBases was wrong?");
6611 // The period of destruction ends now. The object is gone.
6612 Value = APValue();
6613 return true;
6616 namespace {
6617 struct DestroyObjectHandler {
6618 EvalInfo &Info;
6619 const Expr *E;
6620 const LValue &This;
6621 const AccessKinds AccessKind;
6623 typedef bool result_type;
6624 bool failed() { return false; }
6625 bool found(APValue &Subobj, QualType SubobjType) {
6626 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6627 SubobjType);
6629 bool found(APSInt &Value, QualType SubobjType) {
6630 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6631 return false;
6633 bool found(APFloat &Value, QualType SubobjType) {
6634 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6635 return false;
6640 /// Perform a destructor or pseudo-destructor call on the given object, which
6641 /// might in general not be a complete object.
6642 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6643 const LValue &This, QualType ThisType) {
6644 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6645 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6646 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6649 /// Destroy and end the lifetime of the given complete object.
6650 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6651 APValue::LValueBase LVBase, APValue &Value,
6652 QualType T) {
6653 // If we've had an unmodeled side-effect, we can't rely on mutable state
6654 // (such as the object we're about to destroy) being correct.
6655 if (Info.EvalStatus.HasSideEffects)
6656 return false;
6658 LValue LV;
6659 LV.set({LVBase});
6660 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6663 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6664 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6665 LValue &Result) {
6666 if (Info.checkingPotentialConstantExpression() ||
6667 Info.SpeculativeEvaluationDepth)
6668 return false;
6670 // This is permitted only within a call to std::allocator<T>::allocate.
6671 auto Caller = Info.getStdAllocatorCaller("allocate");
6672 if (!Caller) {
6673 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6674 ? diag::note_constexpr_new_untyped
6675 : diag::note_constexpr_new);
6676 return false;
6679 QualType ElemType = Caller.ElemType;
6680 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6681 Info.FFDiag(E->getExprLoc(),
6682 diag::note_constexpr_new_not_complete_object_type)
6683 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6684 return false;
6687 APSInt ByteSize;
6688 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6689 return false;
6690 bool IsNothrow = false;
6691 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6692 EvaluateIgnoredValue(Info, E->getArg(I));
6693 IsNothrow |= E->getType()->isNothrowT();
6696 CharUnits ElemSize;
6697 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6698 return false;
6699 APInt Size, Remainder;
6700 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6701 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6702 if (Remainder != 0) {
6703 // This likely indicates a bug in the implementation of 'std::allocator'.
6704 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6705 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6706 return false;
6709 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6710 if (IsNothrow) {
6711 Result.setNull(Info.Ctx, E->getType());
6712 return true;
6715 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6716 return false;
6719 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6720 ArrayType::Normal, 0);
6721 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6722 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6723 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6724 return true;
6727 static bool hasVirtualDestructor(QualType T) {
6728 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6729 if (CXXDestructorDecl *DD = RD->getDestructor())
6730 return DD->isVirtual();
6731 return false;
6734 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6735 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6736 if (CXXDestructorDecl *DD = RD->getDestructor())
6737 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6738 return nullptr;
6741 /// Check that the given object is a suitable pointer to a heap allocation that
6742 /// still exists and is of the right kind for the purpose of a deletion.
6744 /// On success, returns the heap allocation to deallocate. On failure, produces
6745 /// a diagnostic and returns None.
6746 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6747 const LValue &Pointer,
6748 DynAlloc::Kind DeallocKind) {
6749 auto PointerAsString = [&] {
6750 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6753 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6754 if (!DA) {
6755 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6756 << PointerAsString();
6757 if (Pointer.Base)
6758 NoteLValueLocation(Info, Pointer.Base);
6759 return None;
6762 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6763 if (!Alloc) {
6764 Info.FFDiag(E, diag::note_constexpr_double_delete);
6765 return None;
6768 QualType AllocType = Pointer.Base.getDynamicAllocType();
6769 if (DeallocKind != (*Alloc)->getKind()) {
6770 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6771 << DeallocKind << (*Alloc)->getKind() << AllocType;
6772 NoteLValueLocation(Info, Pointer.Base);
6773 return None;
6776 bool Subobject = false;
6777 if (DeallocKind == DynAlloc::New) {
6778 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6779 Pointer.Designator.isOnePastTheEnd();
6780 } else {
6781 Subobject = Pointer.Designator.Entries.size() != 1 ||
6782 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6784 if (Subobject) {
6785 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6786 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6787 return None;
6790 return Alloc;
6793 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6794 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6795 if (Info.checkingPotentialConstantExpression() ||
6796 Info.SpeculativeEvaluationDepth)
6797 return false;
6799 // This is permitted only within a call to std::allocator<T>::deallocate.
6800 if (!Info.getStdAllocatorCaller("deallocate")) {
6801 Info.FFDiag(E->getExprLoc());
6802 return true;
6805 LValue Pointer;
6806 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6807 return false;
6808 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6809 EvaluateIgnoredValue(Info, E->getArg(I));
6811 if (Pointer.Designator.Invalid)
6812 return false;
6814 // Deleting a null pointer would have no effect, but it's not permitted by
6815 // std::allocator<T>::deallocate's contract.
6816 if (Pointer.isNullPointer()) {
6817 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6818 return true;
6821 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6822 return false;
6824 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6825 return true;
6828 //===----------------------------------------------------------------------===//
6829 // Generic Evaluation
6830 //===----------------------------------------------------------------------===//
6831 namespace {
6833 class BitCastBuffer {
6834 // FIXME: We're going to need bit-level granularity when we support
6835 // bit-fields.
6836 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6837 // we don't support a host or target where that is the case. Still, we should
6838 // use a more generic type in case we ever do.
6839 SmallVector<Optional<unsigned char>, 32> Bytes;
6841 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6842 "Need at least 8 bit unsigned char");
6844 bool TargetIsLittleEndian;
6846 public:
6847 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6848 : Bytes(Width.getQuantity()),
6849 TargetIsLittleEndian(TargetIsLittleEndian) {}
6851 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6852 SmallVectorImpl<unsigned char> &Output) const {
6853 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6854 // If a byte of an integer is uninitialized, then the whole integer is
6855 // uninitialized.
6856 if (!Bytes[I.getQuantity()])
6857 return false;
6858 Output.push_back(*Bytes[I.getQuantity()]);
6860 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6861 std::reverse(Output.begin(), Output.end());
6862 return true;
6865 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6866 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6867 std::reverse(Input.begin(), Input.end());
6869 size_t Index = 0;
6870 for (unsigned char Byte : Input) {
6871 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6872 Bytes[Offset.getQuantity() + Index] = Byte;
6873 ++Index;
6877 size_t size() { return Bytes.size(); }
6880 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6881 /// target would represent the value at runtime.
6882 class APValueToBufferConverter {
6883 EvalInfo &Info;
6884 BitCastBuffer Buffer;
6885 const CastExpr *BCE;
6887 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6888 const CastExpr *BCE)
6889 : Info(Info),
6890 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6891 BCE(BCE) {}
6893 bool visit(const APValue &Val, QualType Ty) {
6894 return visit(Val, Ty, CharUnits::fromQuantity(0));
6897 // Write out Val with type Ty into Buffer starting at Offset.
6898 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6899 assert((size_t)Offset.getQuantity() <= Buffer.size());
6901 // As a special case, nullptr_t has an indeterminate value.
6902 if (Ty->isNullPtrType())
6903 return true;
6905 // Dig through Src to find the byte at SrcOffset.
6906 switch (Val.getKind()) {
6907 case APValue::Indeterminate:
6908 case APValue::None:
6909 return true;
6911 case APValue::Int:
6912 return visitInt(Val.getInt(), Ty, Offset);
6913 case APValue::Float:
6914 return visitFloat(Val.getFloat(), Ty, Offset);
6915 case APValue::Array:
6916 return visitArray(Val, Ty, Offset);
6917 case APValue::Struct:
6918 return visitRecord(Val, Ty, Offset);
6920 case APValue::ComplexInt:
6921 case APValue::ComplexFloat:
6922 case APValue::Vector:
6923 case APValue::FixedPoint:
6924 // FIXME: We should support these.
6926 case APValue::Union:
6927 case APValue::MemberPointer:
6928 case APValue::AddrLabelDiff: {
6929 Info.FFDiag(BCE->getBeginLoc(),
6930 diag::note_constexpr_bit_cast_unsupported_type)
6931 << Ty;
6932 return false;
6935 case APValue::LValue:
6936 llvm_unreachable("LValue subobject in bit_cast?");
6938 llvm_unreachable("Unhandled APValue::ValueKind");
6941 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6942 const RecordDecl *RD = Ty->getAsRecordDecl();
6943 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6945 // Visit the base classes.
6946 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6947 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6948 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6949 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6951 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6952 Layout.getBaseClassOffset(BaseDecl) + Offset))
6953 return false;
6957 // Visit the fields.
6958 unsigned FieldIdx = 0;
6959 for (FieldDecl *FD : RD->fields()) {
6960 if (FD->isBitField()) {
6961 Info.FFDiag(BCE->getBeginLoc(),
6962 diag::note_constexpr_bit_cast_unsupported_bitfield);
6963 return false;
6966 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6968 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6969 "only bit-fields can have sub-char alignment");
6970 CharUnits FieldOffset =
6971 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6972 QualType FieldTy = FD->getType();
6973 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6974 return false;
6975 ++FieldIdx;
6978 return true;
6981 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6982 const auto *CAT =
6983 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6984 if (!CAT)
6985 return false;
6987 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6988 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6989 unsigned ArraySize = Val.getArraySize();
6990 // First, initialize the initialized elements.
6991 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6992 const APValue &SubObj = Val.getArrayInitializedElt(I);
6993 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6994 return false;
6997 // Next, initialize the rest of the array using the filler.
6998 if (Val.hasArrayFiller()) {
6999 const APValue &Filler = Val.getArrayFiller();
7000 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7001 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7002 return false;
7006 return true;
7009 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7010 APSInt AdjustedVal = Val;
7011 unsigned Width = AdjustedVal.getBitWidth();
7012 if (Ty->isBooleanType()) {
7013 Width = Info.Ctx.getTypeSize(Ty);
7014 AdjustedVal = AdjustedVal.extend(Width);
7017 SmallVector<unsigned char, 8> Bytes(Width / 8);
7018 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7019 Buffer.writeObject(Offset, Bytes);
7020 return true;
7023 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7024 APSInt AsInt(Val.bitcastToAPInt());
7025 return visitInt(AsInt, Ty, Offset);
7028 public:
7029 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7030 const CastExpr *BCE) {
7031 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7032 APValueToBufferConverter Converter(Info, DstSize, BCE);
7033 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7034 return None;
7035 return Converter.Buffer;
7039 /// Write an BitCastBuffer into an APValue.
7040 class BufferToAPValueConverter {
7041 EvalInfo &Info;
7042 const BitCastBuffer &Buffer;
7043 const CastExpr *BCE;
7045 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7046 const CastExpr *BCE)
7047 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7049 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7050 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7051 // Ideally this will be unreachable.
7052 llvm::NoneType unsupportedType(QualType Ty) {
7053 Info.FFDiag(BCE->getBeginLoc(),
7054 diag::note_constexpr_bit_cast_unsupported_type)
7055 << Ty;
7056 return None;
7059 llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7060 Info.FFDiag(BCE->getBeginLoc(),
7061 diag::note_constexpr_bit_cast_unrepresentable_value)
7062 << Ty << toString(Val, /*Radix=*/10);
7063 return None;
7066 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7067 const EnumType *EnumSugar = nullptr) {
7068 if (T->isNullPtrType()) {
7069 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7070 return APValue((Expr *)nullptr,
7071 /*Offset=*/CharUnits::fromQuantity(NullValue),
7072 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7075 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7077 // Work around floating point types that contain unused padding bytes. This
7078 // is really just `long double` on x86, which is the only fundamental type
7079 // with padding bytes.
7080 if (T->isRealFloatingType()) {
7081 const llvm::fltSemantics &Semantics =
7082 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7083 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7084 assert(NumBits % 8 == 0);
7085 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7086 if (NumBytes != SizeOf)
7087 SizeOf = NumBytes;
7090 SmallVector<uint8_t, 8> Bytes;
7091 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7092 // If this is std::byte or unsigned char, then its okay to store an
7093 // indeterminate value.
7094 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7095 bool IsUChar =
7096 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7097 T->isSpecificBuiltinType(BuiltinType::Char_U));
7098 if (!IsStdByte && !IsUChar) {
7099 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7100 Info.FFDiag(BCE->getExprLoc(),
7101 diag::note_constexpr_bit_cast_indet_dest)
7102 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7103 return None;
7106 return APValue::IndeterminateValue();
7109 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7110 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7112 if (T->isIntegralOrEnumerationType()) {
7113 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7115 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7116 if (IntWidth != Val.getBitWidth()) {
7117 APSInt Truncated = Val.trunc(IntWidth);
7118 if (Truncated.extend(Val.getBitWidth()) != Val)
7119 return unrepresentableValue(QualType(T, 0), Val);
7120 Val = Truncated;
7123 return APValue(Val);
7126 if (T->isRealFloatingType()) {
7127 const llvm::fltSemantics &Semantics =
7128 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7129 return APValue(APFloat(Semantics, Val));
7132 return unsupportedType(QualType(T, 0));
7135 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7136 const RecordDecl *RD = RTy->getAsRecordDecl();
7137 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7139 unsigned NumBases = 0;
7140 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7141 NumBases = CXXRD->getNumBases();
7143 APValue ResultVal(APValue::UninitStruct(), NumBases,
7144 std::distance(RD->field_begin(), RD->field_end()));
7146 // Visit the base classes.
7147 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7148 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7149 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7150 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7151 if (BaseDecl->isEmpty() ||
7152 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7153 continue;
7155 Optional<APValue> SubObj = visitType(
7156 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7157 if (!SubObj)
7158 return None;
7159 ResultVal.getStructBase(I) = *SubObj;
7163 // Visit the fields.
7164 unsigned FieldIdx = 0;
7165 for (FieldDecl *FD : RD->fields()) {
7166 // FIXME: We don't currently support bit-fields. A lot of the logic for
7167 // this is in CodeGen, so we need to factor it around.
7168 if (FD->isBitField()) {
7169 Info.FFDiag(BCE->getBeginLoc(),
7170 diag::note_constexpr_bit_cast_unsupported_bitfield);
7171 return None;
7174 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7175 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7177 CharUnits FieldOffset =
7178 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7179 Offset;
7180 QualType FieldTy = FD->getType();
7181 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7182 if (!SubObj)
7183 return None;
7184 ResultVal.getStructField(FieldIdx) = *SubObj;
7185 ++FieldIdx;
7188 return ResultVal;
7191 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7192 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7193 assert(!RepresentationType.isNull() &&
7194 "enum forward decl should be caught by Sema");
7195 const auto *AsBuiltin =
7196 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7197 // Recurse into the underlying type. Treat std::byte transparently as
7198 // unsigned char.
7199 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7202 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7203 size_t Size = Ty->getSize().getLimitedValue();
7204 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7206 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7207 for (size_t I = 0; I != Size; ++I) {
7208 Optional<APValue> ElementValue =
7209 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7210 if (!ElementValue)
7211 return None;
7212 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7215 return ArrayValue;
7218 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7219 return unsupportedType(QualType(Ty, 0));
7222 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7223 QualType Can = Ty.getCanonicalType();
7225 switch (Can->getTypeClass()) {
7226 #define TYPE(Class, Base) \
7227 case Type::Class: \
7228 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7229 #define ABSTRACT_TYPE(Class, Base)
7230 #define NON_CANONICAL_TYPE(Class, Base) \
7231 case Type::Class: \
7232 llvm_unreachable("non-canonical type should be impossible!");
7233 #define DEPENDENT_TYPE(Class, Base) \
7234 case Type::Class: \
7235 llvm_unreachable( \
7236 "dependent types aren't supported in the constant evaluator!");
7237 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7238 case Type::Class: \
7239 llvm_unreachable("either dependent or not canonical!");
7240 #include "clang/AST/TypeNodes.inc"
7242 llvm_unreachable("Unhandled Type::TypeClass");
7245 public:
7246 // Pull out a full value of type DstType.
7247 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7248 const CastExpr *BCE) {
7249 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7250 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7254 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7255 QualType Ty, EvalInfo *Info,
7256 const ASTContext &Ctx,
7257 bool CheckingDest) {
7258 Ty = Ty.getCanonicalType();
7260 auto diag = [&](int Reason) {
7261 if (Info)
7262 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7263 << CheckingDest << (Reason == 4) << Reason;
7264 return false;
7266 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7267 if (Info)
7268 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7269 << NoteTy << Construct << Ty;
7270 return false;
7273 if (Ty->isUnionType())
7274 return diag(0);
7275 if (Ty->isPointerType())
7276 return diag(1);
7277 if (Ty->isMemberPointerType())
7278 return diag(2);
7279 if (Ty.isVolatileQualified())
7280 return diag(3);
7282 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7283 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7284 for (CXXBaseSpecifier &BS : CXXRD->bases())
7285 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7286 CheckingDest))
7287 return note(1, BS.getType(), BS.getBeginLoc());
7289 for (FieldDecl *FD : Record->fields()) {
7290 if (FD->getType()->isReferenceType())
7291 return diag(4);
7292 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7293 CheckingDest))
7294 return note(0, FD->getType(), FD->getBeginLoc());
7298 if (Ty->isArrayType() &&
7299 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7300 Info, Ctx, CheckingDest))
7301 return false;
7303 return true;
7306 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7307 const ASTContext &Ctx,
7308 const CastExpr *BCE) {
7309 bool DestOK = checkBitCastConstexprEligibilityType(
7310 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7311 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7312 BCE->getBeginLoc(),
7313 BCE->getSubExpr()->getType(), Info, Ctx, false);
7314 return SourceOK;
7317 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7318 APValue &SourceValue,
7319 const CastExpr *BCE) {
7320 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7321 "no host or target supports non 8-bit chars");
7322 assert(SourceValue.isLValue() &&
7323 "LValueToRValueBitcast requires an lvalue operand!");
7325 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7326 return false;
7328 LValue SourceLValue;
7329 APValue SourceRValue;
7330 SourceLValue.setFrom(Info.Ctx, SourceValue);
7331 if (!handleLValueToRValueConversion(
7332 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7333 SourceRValue, /*WantObjectRepresentation=*/true))
7334 return false;
7336 // Read out SourceValue into a char buffer.
7337 Optional<BitCastBuffer> Buffer =
7338 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7339 if (!Buffer)
7340 return false;
7342 // Write out the buffer into a new APValue.
7343 Optional<APValue> MaybeDestValue =
7344 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7345 if (!MaybeDestValue)
7346 return false;
7348 DestValue = std::move(*MaybeDestValue);
7349 return true;
7352 template <class Derived>
7353 class ExprEvaluatorBase
7354 : public ConstStmtVisitor<Derived, bool> {
7355 private:
7356 Derived &getDerived() { return static_cast<Derived&>(*this); }
7357 bool DerivedSuccess(const APValue &V, const Expr *E) {
7358 return getDerived().Success(V, E);
7360 bool DerivedZeroInitialization(const Expr *E) {
7361 return getDerived().ZeroInitialization(E);
7364 // Check whether a conditional operator with a non-constant condition is a
7365 // potential constant expression. If neither arm is a potential constant
7366 // expression, then the conditional operator is not either.
7367 template<typename ConditionalOperator>
7368 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7369 assert(Info.checkingPotentialConstantExpression());
7371 // Speculatively evaluate both arms.
7372 SmallVector<PartialDiagnosticAt, 8> Diag;
7374 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7375 StmtVisitorTy::Visit(E->getFalseExpr());
7376 if (Diag.empty())
7377 return;
7381 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7382 Diag.clear();
7383 StmtVisitorTy::Visit(E->getTrueExpr());
7384 if (Diag.empty())
7385 return;
7388 Error(E, diag::note_constexpr_conditional_never_const);
7392 template<typename ConditionalOperator>
7393 bool HandleConditionalOperator(const ConditionalOperator *E) {
7394 bool BoolResult;
7395 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7396 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7397 CheckPotentialConstantConditional(E);
7398 return false;
7400 if (Info.noteFailure()) {
7401 StmtVisitorTy::Visit(E->getTrueExpr());
7402 StmtVisitorTy::Visit(E->getFalseExpr());
7404 return false;
7407 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7408 return StmtVisitorTy::Visit(EvalExpr);
7411 protected:
7412 EvalInfo &Info;
7413 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7414 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7416 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7417 return Info.CCEDiag(E, D);
7420 bool ZeroInitialization(const Expr *E) { return Error(E); }
7422 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7423 unsigned BuiltinOp = E->getBuiltinCallee();
7424 return BuiltinOp != 0 &&
7425 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7428 public:
7429 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7431 EvalInfo &getEvalInfo() { return Info; }
7433 /// Report an evaluation error. This should only be called when an error is
7434 /// first discovered. When propagating an error, just return false.
7435 bool Error(const Expr *E, diag::kind D) {
7436 Info.FFDiag(E, D);
7437 return false;
7439 bool Error(const Expr *E) {
7440 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7443 bool VisitStmt(const Stmt *) {
7444 llvm_unreachable("Expression evaluator should not be called on stmts");
7446 bool VisitExpr(const Expr *E) {
7447 return Error(E);
7450 bool VisitConstantExpr(const ConstantExpr *E) {
7451 if (E->hasAPValueResult())
7452 return DerivedSuccess(E->getAPValueResult(), E);
7454 return StmtVisitorTy::Visit(E->getSubExpr());
7457 bool VisitParenExpr(const ParenExpr *E)
7458 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7459 bool VisitUnaryExtension(const UnaryOperator *E)
7460 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7461 bool VisitUnaryPlus(const UnaryOperator *E)
7462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7463 bool VisitChooseExpr(const ChooseExpr *E)
7464 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7465 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7466 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7467 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7468 { return StmtVisitorTy::Visit(E->getReplacement()); }
7469 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7470 TempVersionRAII RAII(*Info.CurrentCall);
7471 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7472 return StmtVisitorTy::Visit(E->getExpr());
7474 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7475 TempVersionRAII RAII(*Info.CurrentCall);
7476 // The initializer may not have been parsed yet, or might be erroneous.
7477 if (!E->getExpr())
7478 return Error(E);
7479 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7480 return StmtVisitorTy::Visit(E->getExpr());
7483 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7484 FullExpressionRAII Scope(Info);
7485 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7488 // Temporaries are registered when created, so we don't care about
7489 // CXXBindTemporaryExpr.
7490 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7491 return StmtVisitorTy::Visit(E->getSubExpr());
7494 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7495 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7496 return static_cast<Derived*>(this)->VisitCastExpr(E);
7498 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7499 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7500 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7501 return static_cast<Derived*>(this)->VisitCastExpr(E);
7503 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7504 return static_cast<Derived*>(this)->VisitCastExpr(E);
7507 bool VisitBinaryOperator(const BinaryOperator *E) {
7508 switch (E->getOpcode()) {
7509 default:
7510 return Error(E);
7512 case BO_Comma:
7513 VisitIgnoredValue(E->getLHS());
7514 return StmtVisitorTy::Visit(E->getRHS());
7516 case BO_PtrMemD:
7517 case BO_PtrMemI: {
7518 LValue Obj;
7519 if (!HandleMemberPointerAccess(Info, E, Obj))
7520 return false;
7521 APValue Result;
7522 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7523 return false;
7524 return DerivedSuccess(Result, E);
7529 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7530 return StmtVisitorTy::Visit(E->getSemanticForm());
7533 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7534 // Evaluate and cache the common expression. We treat it as a temporary,
7535 // even though it's not quite the same thing.
7536 LValue CommonLV;
7537 if (!Evaluate(Info.CurrentCall->createTemporary(
7538 E->getOpaqueValue(),
7539 getStorageType(Info.Ctx, E->getOpaqueValue()),
7540 ScopeKind::FullExpression, CommonLV),
7541 Info, E->getCommon()))
7542 return false;
7544 return HandleConditionalOperator(E);
7547 bool VisitConditionalOperator(const ConditionalOperator *E) {
7548 bool IsBcpCall = false;
7549 // If the condition (ignoring parens) is a __builtin_constant_p call,
7550 // the result is a constant expression if it can be folded without
7551 // side-effects. This is an important GNU extension. See GCC PR38377
7552 // for discussion.
7553 if (const CallExpr *CallCE =
7554 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7555 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7556 IsBcpCall = true;
7558 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7559 // constant expression; we can't check whether it's potentially foldable.
7560 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7561 // it would return 'false' in this mode.
7562 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7563 return false;
7565 FoldConstant Fold(Info, IsBcpCall);
7566 if (!HandleConditionalOperator(E)) {
7567 Fold.keepDiagnostics();
7568 return false;
7571 return true;
7574 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7575 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7576 return DerivedSuccess(*Value, E);
7578 const Expr *Source = E->getSourceExpr();
7579 if (!Source)
7580 return Error(E);
7581 if (Source == E) {
7582 assert(0 && "OpaqueValueExpr recursively refers to itself");
7583 return Error(E);
7585 return StmtVisitorTy::Visit(Source);
7588 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7589 for (const Expr *SemE : E->semantics()) {
7590 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7591 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7592 // result expression: there could be two different LValues that would
7593 // refer to the same object in that case, and we can't model that.
7594 if (SemE == E->getResultExpr())
7595 return Error(E);
7597 // Unique OVEs get evaluated if and when we encounter them when
7598 // emitting the rest of the semantic form, rather than eagerly.
7599 if (OVE->isUnique())
7600 continue;
7602 LValue LV;
7603 if (!Evaluate(Info.CurrentCall->createTemporary(
7604 OVE, getStorageType(Info.Ctx, OVE),
7605 ScopeKind::FullExpression, LV),
7606 Info, OVE->getSourceExpr()))
7607 return false;
7608 } else if (SemE == E->getResultExpr()) {
7609 if (!StmtVisitorTy::Visit(SemE))
7610 return false;
7611 } else {
7612 if (!EvaluateIgnoredValue(Info, SemE))
7613 return false;
7616 return true;
7619 bool VisitCallExpr(const CallExpr *E) {
7620 APValue Result;
7621 if (!handleCallExpr(E, Result, nullptr))
7622 return false;
7623 return DerivedSuccess(Result, E);
7626 bool handleCallExpr(const CallExpr *E, APValue &Result,
7627 const LValue *ResultSlot) {
7628 CallScopeRAII CallScope(Info);
7630 const Expr *Callee = E->getCallee()->IgnoreParens();
7631 QualType CalleeType = Callee->getType();
7633 const FunctionDecl *FD = nullptr;
7634 LValue *This = nullptr, ThisVal;
7635 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7636 bool HasQualifier = false;
7638 CallRef Call;
7640 // Extract function decl and 'this' pointer from the callee.
7641 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7642 const CXXMethodDecl *Member = nullptr;
7643 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7644 // Explicit bound member calls, such as x.f() or p->g();
7645 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7646 return false;
7647 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7648 if (!Member)
7649 return Error(Callee);
7650 This = &ThisVal;
7651 HasQualifier = ME->hasQualifier();
7652 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7653 // Indirect bound member calls ('.*' or '->*').
7654 const ValueDecl *D =
7655 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7656 if (!D)
7657 return false;
7658 Member = dyn_cast<CXXMethodDecl>(D);
7659 if (!Member)
7660 return Error(Callee);
7661 This = &ThisVal;
7662 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7663 if (!Info.getLangOpts().CPlusPlus20)
7664 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7665 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7666 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7667 } else
7668 return Error(Callee);
7669 FD = Member;
7670 } else if (CalleeType->isFunctionPointerType()) {
7671 LValue CalleeLV;
7672 if (!EvaluatePointer(Callee, CalleeLV, Info))
7673 return false;
7675 if (!CalleeLV.getLValueOffset().isZero())
7676 return Error(Callee);
7677 FD = dyn_cast_or_null<FunctionDecl>(
7678 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7679 if (!FD)
7680 return Error(Callee);
7681 // Don't call function pointers which have been cast to some other type.
7682 // Per DR (no number yet), the caller and callee can differ in noexcept.
7683 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7684 CalleeType->getPointeeType(), FD->getType())) {
7685 return Error(E);
7688 // For an (overloaded) assignment expression, evaluate the RHS before the
7689 // LHS.
7690 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7691 if (OCE && OCE->isAssignmentOp()) {
7692 assert(Args.size() == 2 && "wrong number of arguments in assignment");
7693 Call = Info.CurrentCall->createCall(FD);
7694 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7695 Info, FD, /*RightToLeft=*/true))
7696 return false;
7699 // Overloaded operator calls to member functions are represented as normal
7700 // calls with '*this' as the first argument.
7701 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7702 if (MD && !MD->isStatic()) {
7703 // FIXME: When selecting an implicit conversion for an overloaded
7704 // operator delete, we sometimes try to evaluate calls to conversion
7705 // operators without a 'this' parameter!
7706 if (Args.empty())
7707 return Error(E);
7709 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7710 return false;
7711 This = &ThisVal;
7713 // If this is syntactically a simple assignment using a trivial
7714 // assignment operator, start the lifetimes of union members as needed,
7715 // per C++20 [class.union]5.
7716 if (Info.getLangOpts().CPlusPlus20 && OCE &&
7717 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7718 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7719 return false;
7721 Args = Args.slice(1);
7722 } else if (MD && MD->isLambdaStaticInvoker()) {
7723 // Map the static invoker for the lambda back to the call operator.
7724 // Conveniently, we don't have to slice out the 'this' argument (as is
7725 // being done for the non-static case), since a static member function
7726 // doesn't have an implicit argument passed in.
7727 const CXXRecordDecl *ClosureClass = MD->getParent();
7728 assert(
7729 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7730 "Number of captures must be zero for conversion to function-ptr");
7732 const CXXMethodDecl *LambdaCallOp =
7733 ClosureClass->getLambdaCallOperator();
7735 // Set 'FD', the function that will be called below, to the call
7736 // operator. If the closure object represents a generic lambda, find
7737 // the corresponding specialization of the call operator.
7739 if (ClosureClass->isGenericLambda()) {
7740 assert(MD->isFunctionTemplateSpecialization() &&
7741 "A generic lambda's static-invoker function must be a "
7742 "template specialization");
7743 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7744 FunctionTemplateDecl *CallOpTemplate =
7745 LambdaCallOp->getDescribedFunctionTemplate();
7746 void *InsertPos = nullptr;
7747 FunctionDecl *CorrespondingCallOpSpecialization =
7748 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7749 assert(CorrespondingCallOpSpecialization &&
7750 "We must always have a function call operator specialization "
7751 "that corresponds to our static invoker specialization");
7752 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7753 } else
7754 FD = LambdaCallOp;
7755 } else if (FD->isReplaceableGlobalAllocationFunction()) {
7756 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7757 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7758 LValue Ptr;
7759 if (!HandleOperatorNewCall(Info, E, Ptr))
7760 return false;
7761 Ptr.moveInto(Result);
7762 return CallScope.destroy();
7763 } else {
7764 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7767 } else
7768 return Error(E);
7770 // Evaluate the arguments now if we've not already done so.
7771 if (!Call) {
7772 Call = Info.CurrentCall->createCall(FD);
7773 if (!EvaluateArgs(Args, Call, Info, FD))
7774 return false;
7777 SmallVector<QualType, 4> CovariantAdjustmentPath;
7778 if (This) {
7779 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7780 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7781 // Perform virtual dispatch, if necessary.
7782 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7783 CovariantAdjustmentPath);
7784 if (!FD)
7785 return false;
7786 } else {
7787 // Check that the 'this' pointer points to an object of the right type.
7788 // FIXME: If this is an assignment operator call, we may need to change
7789 // the active union member before we check this.
7790 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7791 return false;
7795 // Destructor calls are different enough that they have their own codepath.
7796 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7797 assert(This && "no 'this' pointer for destructor call");
7798 return HandleDestruction(Info, E, *This,
7799 Info.Ctx.getRecordType(DD->getParent())) &&
7800 CallScope.destroy();
7803 const FunctionDecl *Definition = nullptr;
7804 Stmt *Body = FD->getBody(Definition);
7806 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7807 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7808 Body, Info, Result, ResultSlot))
7809 return false;
7811 if (!CovariantAdjustmentPath.empty() &&
7812 !HandleCovariantReturnAdjustment(Info, E, Result,
7813 CovariantAdjustmentPath))
7814 return false;
7816 return CallScope.destroy();
7819 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7820 return StmtVisitorTy::Visit(E->getInitializer());
7822 bool VisitInitListExpr(const InitListExpr *E) {
7823 if (E->getNumInits() == 0)
7824 return DerivedZeroInitialization(E);
7825 if (E->getNumInits() == 1)
7826 return StmtVisitorTy::Visit(E->getInit(0));
7827 return Error(E);
7829 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7830 return DerivedZeroInitialization(E);
7832 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7833 return DerivedZeroInitialization(E);
7835 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7836 return DerivedZeroInitialization(E);
7839 /// A member expression where the object is a prvalue is itself a prvalue.
7840 bool VisitMemberExpr(const MemberExpr *E) {
7841 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7842 "missing temporary materialization conversion");
7843 assert(!E->isArrow() && "missing call to bound member function?");
7845 APValue Val;
7846 if (!Evaluate(Val, Info, E->getBase()))
7847 return false;
7849 QualType BaseTy = E->getBase()->getType();
7851 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7852 if (!FD) return Error(E);
7853 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7854 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7855 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7857 // Note: there is no lvalue base here. But this case should only ever
7858 // happen in C or in C++98, where we cannot be evaluating a constexpr
7859 // constructor, which is the only case the base matters.
7860 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7861 SubobjectDesignator Designator(BaseTy);
7862 Designator.addDeclUnchecked(FD);
7864 APValue Result;
7865 return extractSubobject(Info, E, Obj, Designator, Result) &&
7866 DerivedSuccess(Result, E);
7869 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7870 APValue Val;
7871 if (!Evaluate(Val, Info, E->getBase()))
7872 return false;
7874 if (Val.isVector()) {
7875 SmallVector<uint32_t, 4> Indices;
7876 E->getEncodedElementAccess(Indices);
7877 if (Indices.size() == 1) {
7878 // Return scalar.
7879 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7880 } else {
7881 // Construct new APValue vector.
7882 SmallVector<APValue, 4> Elts;
7883 for (unsigned I = 0; I < Indices.size(); ++I) {
7884 Elts.push_back(Val.getVectorElt(Indices[I]));
7886 APValue VecResult(Elts.data(), Indices.size());
7887 return DerivedSuccess(VecResult, E);
7891 return false;
7894 bool VisitCastExpr(const CastExpr *E) {
7895 switch (E->getCastKind()) {
7896 default:
7897 break;
7899 case CK_AtomicToNonAtomic: {
7900 APValue AtomicVal;
7901 // This does not need to be done in place even for class/array types:
7902 // atomic-to-non-atomic conversion implies copying the object
7903 // representation.
7904 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7905 return false;
7906 return DerivedSuccess(AtomicVal, E);
7909 case CK_NoOp:
7910 case CK_UserDefinedConversion:
7911 return StmtVisitorTy::Visit(E->getSubExpr());
7913 case CK_LValueToRValue: {
7914 LValue LVal;
7915 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7916 return false;
7917 APValue RVal;
7918 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7919 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7920 LVal, RVal))
7921 return false;
7922 return DerivedSuccess(RVal, E);
7924 case CK_LValueToRValueBitCast: {
7925 APValue DestValue, SourceValue;
7926 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7927 return false;
7928 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7929 return false;
7930 return DerivedSuccess(DestValue, E);
7933 case CK_AddressSpaceConversion: {
7934 APValue Value;
7935 if (!Evaluate(Value, Info, E->getSubExpr()))
7936 return false;
7937 return DerivedSuccess(Value, E);
7941 return Error(E);
7944 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7945 return VisitUnaryPostIncDec(UO);
7947 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7948 return VisitUnaryPostIncDec(UO);
7950 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7951 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7952 return Error(UO);
7954 LValue LVal;
7955 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7956 return false;
7957 APValue RVal;
7958 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7959 UO->isIncrementOp(), &RVal))
7960 return false;
7961 return DerivedSuccess(RVal, UO);
7964 bool VisitStmtExpr(const StmtExpr *E) {
7965 // We will have checked the full-expressions inside the statement expression
7966 // when they were completed, and don't need to check them again now.
7967 llvm::SaveAndRestore<bool> NotCheckingForUB(
7968 Info.CheckingForUndefinedBehavior, false);
7970 const CompoundStmt *CS = E->getSubStmt();
7971 if (CS->body_empty())
7972 return true;
7974 BlockScopeRAII Scope(Info);
7975 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7976 BE = CS->body_end();
7977 /**/; ++BI) {
7978 if (BI + 1 == BE) {
7979 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7980 if (!FinalExpr) {
7981 Info.FFDiag((*BI)->getBeginLoc(),
7982 diag::note_constexpr_stmt_expr_unsupported);
7983 return false;
7985 return this->Visit(FinalExpr) && Scope.destroy();
7988 APValue ReturnValue;
7989 StmtResult Result = { ReturnValue, nullptr };
7990 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7991 if (ESR != ESR_Succeeded) {
7992 // FIXME: If the statement-expression terminated due to 'return',
7993 // 'break', or 'continue', it would be nice to propagate that to
7994 // the outer statement evaluation rather than bailing out.
7995 if (ESR != ESR_Failed)
7996 Info.FFDiag((*BI)->getBeginLoc(),
7997 diag::note_constexpr_stmt_expr_unsupported);
7998 return false;
8002 llvm_unreachable("Return from function from the loop above.");
8005 /// Visit a value which is evaluated, but whose value is ignored.
8006 void VisitIgnoredValue(const Expr *E) {
8007 EvaluateIgnoredValue(Info, E);
8010 /// Potentially visit a MemberExpr's base expression.
8011 void VisitIgnoredBaseExpression(const Expr *E) {
8012 // While MSVC doesn't evaluate the base expression, it does diagnose the
8013 // presence of side-effecting behavior.
8014 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8015 return;
8016 VisitIgnoredValue(E);
8020 } // namespace
8022 //===----------------------------------------------------------------------===//
8023 // Common base class for lvalue and temporary evaluation.
8024 //===----------------------------------------------------------------------===//
8025 namespace {
8026 template<class Derived>
8027 class LValueExprEvaluatorBase
8028 : public ExprEvaluatorBase<Derived> {
8029 protected:
8030 LValue &Result;
8031 bool InvalidBaseOK;
8032 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8033 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8035 bool Success(APValue::LValueBase B) {
8036 Result.set(B);
8037 return true;
8040 bool evaluatePointer(const Expr *E, LValue &Result) {
8041 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8044 public:
8045 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8046 : ExprEvaluatorBaseTy(Info), Result(Result),
8047 InvalidBaseOK(InvalidBaseOK) {}
8049 bool Success(const APValue &V, const Expr *E) {
8050 Result.setFrom(this->Info.Ctx, V);
8051 return true;
8054 bool VisitMemberExpr(const MemberExpr *E) {
8055 // Handle non-static data members.
8056 QualType BaseTy;
8057 bool EvalOK;
8058 if (E->isArrow()) {
8059 EvalOK = evaluatePointer(E->getBase(), Result);
8060 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8061 } else if (E->getBase()->isPRValue()) {
8062 assert(E->getBase()->getType()->isRecordType());
8063 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8064 BaseTy = E->getBase()->getType();
8065 } else {
8066 EvalOK = this->Visit(E->getBase());
8067 BaseTy = E->getBase()->getType();
8069 if (!EvalOK) {
8070 if (!InvalidBaseOK)
8071 return false;
8072 Result.setInvalid(E);
8073 return true;
8076 const ValueDecl *MD = E->getMemberDecl();
8077 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8078 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8079 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8080 (void)BaseTy;
8081 if (!HandleLValueMember(this->Info, E, Result, FD))
8082 return false;
8083 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8084 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8085 return false;
8086 } else
8087 return this->Error(E);
8089 if (MD->getType()->isReferenceType()) {
8090 APValue RefValue;
8091 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8092 RefValue))
8093 return false;
8094 return Success(RefValue, E);
8096 return true;
8099 bool VisitBinaryOperator(const BinaryOperator *E) {
8100 switch (E->getOpcode()) {
8101 default:
8102 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8104 case BO_PtrMemD:
8105 case BO_PtrMemI:
8106 return HandleMemberPointerAccess(this->Info, E, Result);
8110 bool VisitCastExpr(const CastExpr *E) {
8111 switch (E->getCastKind()) {
8112 default:
8113 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8115 case CK_DerivedToBase:
8116 case CK_UncheckedDerivedToBase:
8117 if (!this->Visit(E->getSubExpr()))
8118 return false;
8120 // Now figure out the necessary offset to add to the base LV to get from
8121 // the derived class to the base class.
8122 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8123 Result);
8129 //===----------------------------------------------------------------------===//
8130 // LValue Evaluation
8132 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8133 // function designators (in C), decl references to void objects (in C), and
8134 // temporaries (if building with -Wno-address-of-temporary).
8136 // LValue evaluation produces values comprising a base expression of one of the
8137 // following types:
8138 // - Declarations
8139 // * VarDecl
8140 // * FunctionDecl
8141 // - Literals
8142 // * CompoundLiteralExpr in C (and in global scope in C++)
8143 // * StringLiteral
8144 // * PredefinedExpr
8145 // * ObjCStringLiteralExpr
8146 // * ObjCEncodeExpr
8147 // * AddrLabelExpr
8148 // * BlockExpr
8149 // * CallExpr for a MakeStringConstant builtin
8150 // - typeid(T) expressions, as TypeInfoLValues
8151 // - Locals and temporaries
8152 // * MaterializeTemporaryExpr
8153 // * Any Expr, with a CallIndex indicating the function in which the temporary
8154 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
8155 // from the AST (FIXME).
8156 // * A MaterializeTemporaryExpr that has static storage duration, with no
8157 // CallIndex, for a lifetime-extended temporary.
8158 // * The ConstantExpr that is currently being evaluated during evaluation of an
8159 // immediate invocation.
8160 // plus an offset in bytes.
8161 //===----------------------------------------------------------------------===//
8162 namespace {
8163 class LValueExprEvaluator
8164 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8165 public:
8166 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8167 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8169 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8170 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8172 bool VisitCallExpr(const CallExpr *E);
8173 bool VisitDeclRefExpr(const DeclRefExpr *E);
8174 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8175 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8176 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8177 bool VisitMemberExpr(const MemberExpr *E);
8178 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8179 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8180 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8181 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8182 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8183 bool VisitUnaryDeref(const UnaryOperator *E);
8184 bool VisitUnaryReal(const UnaryOperator *E);
8185 bool VisitUnaryImag(const UnaryOperator *E);
8186 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8187 return VisitUnaryPreIncDec(UO);
8189 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8190 return VisitUnaryPreIncDec(UO);
8192 bool VisitBinAssign(const BinaryOperator *BO);
8193 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8195 bool VisitCastExpr(const CastExpr *E) {
8196 switch (E->getCastKind()) {
8197 default:
8198 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8200 case CK_LValueBitCast:
8201 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8202 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8203 if (!Visit(E->getSubExpr()))
8204 return false;
8205 Result.Designator.setInvalid();
8206 return true;
8208 case CK_BaseToDerived:
8209 if (!Visit(E->getSubExpr()))
8210 return false;
8211 return HandleBaseToDerivedCast(Info, E, Result);
8213 case CK_Dynamic:
8214 if (!Visit(E->getSubExpr()))
8215 return false;
8216 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8220 } // end anonymous namespace
8222 /// Evaluate an expression as an lvalue. This can be legitimately called on
8223 /// expressions which are not glvalues, in three cases:
8224 /// * function designators in C, and
8225 /// * "extern void" objects
8226 /// * @selector() expressions in Objective-C
8227 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8228 bool InvalidBaseOK) {
8229 assert(!E->isValueDependent());
8230 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8231 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8232 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8235 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8236 const NamedDecl *D = E->getDecl();
8237 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8238 UnnamedGlobalConstantDecl>(D))
8239 return Success(cast<ValueDecl>(D));
8240 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8241 return VisitVarDecl(E, VD);
8242 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8243 return Visit(BD->getBinding());
8244 return Error(E);
8248 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8250 // If we are within a lambda's call operator, check whether the 'VD' referred
8251 // to within 'E' actually represents a lambda-capture that maps to a
8252 // data-member/field within the closure object, and if so, evaluate to the
8253 // field or what the field refers to.
8254 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8255 isa<DeclRefExpr>(E) &&
8256 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8257 // We don't always have a complete capture-map when checking or inferring if
8258 // the function call operator meets the requirements of a constexpr function
8259 // - but we don't need to evaluate the captures to determine constexprness
8260 // (dcl.constexpr C++17).
8261 if (Info.checkingPotentialConstantExpression())
8262 return false;
8264 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8265 // Start with 'Result' referring to the complete closure object...
8266 Result = *Info.CurrentCall->This;
8267 // ... then update it to refer to the field of the closure object
8268 // that represents the capture.
8269 if (!HandleLValueMember(Info, E, Result, FD))
8270 return false;
8271 // And if the field is of reference type, update 'Result' to refer to what
8272 // the field refers to.
8273 if (FD->getType()->isReferenceType()) {
8274 APValue RVal;
8275 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8276 RVal))
8277 return false;
8278 Result.setFrom(Info.Ctx, RVal);
8280 return true;
8284 CallStackFrame *Frame = nullptr;
8285 unsigned Version = 0;
8286 if (VD->hasLocalStorage()) {
8287 // Only if a local variable was declared in the function currently being
8288 // evaluated, do we expect to be able to find its value in the current
8289 // frame. (Otherwise it was likely declared in an enclosing context and
8290 // could either have a valid evaluatable value (for e.g. a constexpr
8291 // variable) or be ill-formed (and trigger an appropriate evaluation
8292 // diagnostic)).
8293 CallStackFrame *CurrFrame = Info.CurrentCall;
8294 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8295 // Function parameters are stored in some caller's frame. (Usually the
8296 // immediate caller, but for an inherited constructor they may be more
8297 // distant.)
8298 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8299 if (CurrFrame->Arguments) {
8300 VD = CurrFrame->Arguments.getOrigParam(PVD);
8301 Frame =
8302 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8303 Version = CurrFrame->Arguments.Version;
8305 } else {
8306 Frame = CurrFrame;
8307 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8312 if (!VD->getType()->isReferenceType()) {
8313 if (Frame) {
8314 Result.set({VD, Frame->Index, Version});
8315 return true;
8317 return Success(VD);
8320 if (!Info.getLangOpts().CPlusPlus11) {
8321 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8322 << VD << VD->getType();
8323 Info.Note(VD->getLocation(), diag::note_declared_at);
8326 APValue *V;
8327 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8328 return false;
8329 if (!V->hasValue()) {
8330 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8331 // adjust the diagnostic to say that.
8332 if (!Info.checkingPotentialConstantExpression())
8333 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8334 return false;
8336 return Success(*V, E);
8339 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8340 if (!IsConstantEvaluatedBuiltinCall(E))
8341 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8343 switch (E->getBuiltinCallee()) {
8344 default:
8345 return false;
8346 case Builtin::BIas_const:
8347 case Builtin::BIforward:
8348 case Builtin::BImove:
8349 case Builtin::BImove_if_noexcept:
8350 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8351 return Visit(E->getArg(0));
8352 break;
8355 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8358 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8359 const MaterializeTemporaryExpr *E) {
8360 // Walk through the expression to find the materialized temporary itself.
8361 SmallVector<const Expr *, 2> CommaLHSs;
8362 SmallVector<SubobjectAdjustment, 2> Adjustments;
8363 const Expr *Inner =
8364 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8366 // If we passed any comma operators, evaluate their LHSs.
8367 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8368 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8369 return false;
8371 // A materialized temporary with static storage duration can appear within the
8372 // result of a constant expression evaluation, so we need to preserve its
8373 // value for use outside this evaluation.
8374 APValue *Value;
8375 if (E->getStorageDuration() == SD_Static) {
8376 // FIXME: What about SD_Thread?
8377 Value = E->getOrCreateValue(true);
8378 *Value = APValue();
8379 Result.set(E);
8380 } else {
8381 Value = &Info.CurrentCall->createTemporary(
8382 E, E->getType(),
8383 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8384 : ScopeKind::Block,
8385 Result);
8388 QualType Type = Inner->getType();
8390 // Materialize the temporary itself.
8391 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8392 *Value = APValue();
8393 return false;
8396 // Adjust our lvalue to refer to the desired subobject.
8397 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8398 --I;
8399 switch (Adjustments[I].Kind) {
8400 case SubobjectAdjustment::DerivedToBaseAdjustment:
8401 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8402 Type, Result))
8403 return false;
8404 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8405 break;
8407 case SubobjectAdjustment::FieldAdjustment:
8408 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8409 return false;
8410 Type = Adjustments[I].Field->getType();
8411 break;
8413 case SubobjectAdjustment::MemberPointerAdjustment:
8414 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8415 Adjustments[I].Ptr.RHS))
8416 return false;
8417 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8418 break;
8422 return true;
8425 bool
8426 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8427 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8428 "lvalue compound literal in c++?");
8429 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8430 // only see this when folding in C, so there's no standard to follow here.
8431 return Success(E);
8434 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8435 TypeInfoLValue TypeInfo;
8437 if (!E->isPotentiallyEvaluated()) {
8438 if (E->isTypeOperand())
8439 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8440 else
8441 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8442 } else {
8443 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8444 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8445 << E->getExprOperand()->getType()
8446 << E->getExprOperand()->getSourceRange();
8449 if (!Visit(E->getExprOperand()))
8450 return false;
8452 Optional<DynamicType> DynType =
8453 ComputeDynamicType(Info, E, Result, AK_TypeId);
8454 if (!DynType)
8455 return false;
8457 TypeInfo =
8458 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8461 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8464 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8465 return Success(E->getGuidDecl());
8468 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8469 // Handle static data members.
8470 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8471 VisitIgnoredBaseExpression(E->getBase());
8472 return VisitVarDecl(E, VD);
8475 // Handle static member functions.
8476 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8477 if (MD->isStatic()) {
8478 VisitIgnoredBaseExpression(E->getBase());
8479 return Success(MD);
8483 // Handle non-static data members.
8484 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8487 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8488 // FIXME: Deal with vectors as array subscript bases.
8489 if (E->getBase()->getType()->isVectorType() ||
8490 E->getBase()->getType()->isVLSTBuiltinType())
8491 return Error(E);
8493 APSInt Index;
8494 bool Success = true;
8496 // C++17's rules require us to evaluate the LHS first, regardless of which
8497 // side is the base.
8498 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8499 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8500 : !EvaluateInteger(SubExpr, Index, Info)) {
8501 if (!Info.noteFailure())
8502 return false;
8503 Success = false;
8507 return Success &&
8508 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8511 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8512 return evaluatePointer(E->getSubExpr(), Result);
8515 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8516 if (!Visit(E->getSubExpr()))
8517 return false;
8518 // __real is a no-op on scalar lvalues.
8519 if (E->getSubExpr()->getType()->isAnyComplexType())
8520 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8521 return true;
8524 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8525 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8526 "lvalue __imag__ on scalar?");
8527 if (!Visit(E->getSubExpr()))
8528 return false;
8529 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8530 return true;
8533 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8534 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8535 return Error(UO);
8537 if (!this->Visit(UO->getSubExpr()))
8538 return false;
8540 return handleIncDec(
8541 this->Info, UO, Result, UO->getSubExpr()->getType(),
8542 UO->isIncrementOp(), nullptr);
8545 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8546 const CompoundAssignOperator *CAO) {
8547 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8548 return Error(CAO);
8550 bool Success = true;
8552 // C++17 onwards require that we evaluate the RHS first.
8553 APValue RHS;
8554 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8555 if (!Info.noteFailure())
8556 return false;
8557 Success = false;
8560 // The overall lvalue result is the result of evaluating the LHS.
8561 if (!this->Visit(CAO->getLHS()) || !Success)
8562 return false;
8564 return handleCompoundAssignment(
8565 this->Info, CAO,
8566 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8567 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8570 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8571 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8572 return Error(E);
8574 bool Success = true;
8576 // C++17 onwards require that we evaluate the RHS first.
8577 APValue NewVal;
8578 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8579 if (!Info.noteFailure())
8580 return false;
8581 Success = false;
8584 if (!this->Visit(E->getLHS()) || !Success)
8585 return false;
8587 if (Info.getLangOpts().CPlusPlus20 &&
8588 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8589 return false;
8591 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8592 NewVal);
8595 //===----------------------------------------------------------------------===//
8596 // Pointer Evaluation
8597 //===----------------------------------------------------------------------===//
8599 /// Attempts to compute the number of bytes available at the pointer
8600 /// returned by a function with the alloc_size attribute. Returns true if we
8601 /// were successful. Places an unsigned number into `Result`.
8603 /// This expects the given CallExpr to be a call to a function with an
8604 /// alloc_size attribute.
8605 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8606 const CallExpr *Call,
8607 llvm::APInt &Result) {
8608 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8610 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8611 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8612 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8613 if (Call->getNumArgs() <= SizeArgNo)
8614 return false;
8616 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8617 Expr::EvalResult ExprResult;
8618 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8619 return false;
8620 Into = ExprResult.Val.getInt();
8621 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8622 return false;
8623 Into = Into.zext(BitsInSizeT);
8624 return true;
8627 APSInt SizeOfElem;
8628 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8629 return false;
8631 if (!AllocSize->getNumElemsParam().isValid()) {
8632 Result = std::move(SizeOfElem);
8633 return true;
8636 APSInt NumberOfElems;
8637 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8638 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8639 return false;
8641 bool Overflow;
8642 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8643 if (Overflow)
8644 return false;
8646 Result = std::move(BytesAvailable);
8647 return true;
8650 /// Convenience function. LVal's base must be a call to an alloc_size
8651 /// function.
8652 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8653 const LValue &LVal,
8654 llvm::APInt &Result) {
8655 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8656 "Can't get the size of a non alloc_size function");
8657 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8658 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8659 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8662 /// Attempts to evaluate the given LValueBase as the result of a call to
8663 /// a function with the alloc_size attribute. If it was possible to do so, this
8664 /// function will return true, make Result's Base point to said function call,
8665 /// and mark Result's Base as invalid.
8666 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8667 LValue &Result) {
8668 if (Base.isNull())
8669 return false;
8671 // Because we do no form of static analysis, we only support const variables.
8673 // Additionally, we can't support parameters, nor can we support static
8674 // variables (in the latter case, use-before-assign isn't UB; in the former,
8675 // we have no clue what they'll be assigned to).
8676 const auto *VD =
8677 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8678 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8679 return false;
8681 const Expr *Init = VD->getAnyInitializer();
8682 if (!Init || Init->getType().isNull())
8683 return false;
8685 const Expr *E = Init->IgnoreParens();
8686 if (!tryUnwrapAllocSizeCall(E))
8687 return false;
8689 // Store E instead of E unwrapped so that the type of the LValue's base is
8690 // what the user wanted.
8691 Result.setInvalid(E);
8693 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8694 Result.addUnsizedArray(Info, E, Pointee);
8695 return true;
8698 namespace {
8699 class PointerExprEvaluator
8700 : public ExprEvaluatorBase<PointerExprEvaluator> {
8701 LValue &Result;
8702 bool InvalidBaseOK;
8704 bool Success(const Expr *E) {
8705 Result.set(E);
8706 return true;
8709 bool evaluateLValue(const Expr *E, LValue &Result) {
8710 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8713 bool evaluatePointer(const Expr *E, LValue &Result) {
8714 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8717 bool visitNonBuiltinCallExpr(const CallExpr *E);
8718 public:
8720 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8721 : ExprEvaluatorBaseTy(info), Result(Result),
8722 InvalidBaseOK(InvalidBaseOK) {}
8724 bool Success(const APValue &V, const Expr *E) {
8725 Result.setFrom(Info.Ctx, V);
8726 return true;
8728 bool ZeroInitialization(const Expr *E) {
8729 Result.setNull(Info.Ctx, E->getType());
8730 return true;
8733 bool VisitBinaryOperator(const BinaryOperator *E);
8734 bool VisitCastExpr(const CastExpr* E);
8735 bool VisitUnaryAddrOf(const UnaryOperator *E);
8736 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8737 { return Success(E); }
8738 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8739 if (E->isExpressibleAsConstantInitializer())
8740 return Success(E);
8741 if (Info.noteFailure())
8742 EvaluateIgnoredValue(Info, E->getSubExpr());
8743 return Error(E);
8745 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8746 { return Success(E); }
8747 bool VisitCallExpr(const CallExpr *E);
8748 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8749 bool VisitBlockExpr(const BlockExpr *E) {
8750 if (!E->getBlockDecl()->hasCaptures())
8751 return Success(E);
8752 return Error(E);
8754 bool VisitCXXThisExpr(const CXXThisExpr *E) {
8755 // Can't look at 'this' when checking a potential constant expression.
8756 if (Info.checkingPotentialConstantExpression())
8757 return false;
8758 if (!Info.CurrentCall->This) {
8759 if (Info.getLangOpts().CPlusPlus11)
8760 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8761 else
8762 Info.FFDiag(E);
8763 return false;
8765 Result = *Info.CurrentCall->This;
8766 // If we are inside a lambda's call operator, the 'this' expression refers
8767 // to the enclosing '*this' object (either by value or reference) which is
8768 // either copied into the closure object's field that represents the '*this'
8769 // or refers to '*this'.
8770 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8771 // Ensure we actually have captured 'this'. (an error will have
8772 // been previously reported if not).
8773 if (!Info.CurrentCall->LambdaThisCaptureField)
8774 return false;
8776 // Update 'Result' to refer to the data member/field of the closure object
8777 // that represents the '*this' capture.
8778 if (!HandleLValueMember(Info, E, Result,
8779 Info.CurrentCall->LambdaThisCaptureField))
8780 return false;
8781 // If we captured '*this' by reference, replace the field with its referent.
8782 if (Info.CurrentCall->LambdaThisCaptureField->getType()
8783 ->isPointerType()) {
8784 APValue RVal;
8785 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8786 RVal))
8787 return false;
8789 Result.setFrom(Info.Ctx, RVal);
8792 return true;
8795 bool VisitCXXNewExpr(const CXXNewExpr *E);
8797 bool VisitSourceLocExpr(const SourceLocExpr *E) {
8798 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8799 APValue LValResult = E->EvaluateInContext(
8800 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8801 Result.setFrom(Info.Ctx, LValResult);
8802 return true;
8805 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8806 std::string ResultStr = E->ComputeName(Info.Ctx);
8808 QualType CharTy = Info.Ctx.CharTy.withConst();
8809 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8810 ResultStr.size() + 1);
8811 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8812 ArrayType::Normal, 0);
8814 StringLiteral *SL =
8815 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8816 /*Pascal*/ false, ArrayTy, E->getLocation());
8818 evaluateLValue(SL, Result);
8819 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8820 return true;
8823 // FIXME: Missing: @protocol, @selector
8825 } // end anonymous namespace
8827 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8828 bool InvalidBaseOK) {
8829 assert(!E->isValueDependent());
8830 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8831 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8834 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8835 if (E->getOpcode() != BO_Add &&
8836 E->getOpcode() != BO_Sub)
8837 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8839 const Expr *PExp = E->getLHS();
8840 const Expr *IExp = E->getRHS();
8841 if (IExp->getType()->isPointerType())
8842 std::swap(PExp, IExp);
8844 bool EvalPtrOK = evaluatePointer(PExp, Result);
8845 if (!EvalPtrOK && !Info.noteFailure())
8846 return false;
8848 llvm::APSInt Offset;
8849 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8850 return false;
8852 if (E->getOpcode() == BO_Sub)
8853 negateAsSigned(Offset);
8855 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8856 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8859 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8860 return evaluateLValue(E->getSubExpr(), Result);
8863 // Is the provided decl 'std::source_location::current'?
8864 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8865 if (!FD)
8866 return false;
8867 const IdentifierInfo *FnII = FD->getIdentifier();
8868 if (!FnII || !FnII->isStr("current"))
8869 return false;
8871 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8872 if (!RD)
8873 return false;
8875 const IdentifierInfo *ClassII = RD->getIdentifier();
8876 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8879 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8880 const Expr *SubExpr = E->getSubExpr();
8882 switch (E->getCastKind()) {
8883 default:
8884 break;
8885 case CK_BitCast:
8886 case CK_CPointerToObjCPointerCast:
8887 case CK_BlockPointerToObjCPointerCast:
8888 case CK_AnyPointerToBlockPointerCast:
8889 case CK_AddressSpaceConversion:
8890 if (!Visit(SubExpr))
8891 return false;
8892 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8893 // permitted in constant expressions in C++11. Bitcasts from cv void* are
8894 // also static_casts, but we disallow them as a resolution to DR1312.
8895 if (!E->getType()->isVoidPointerType()) {
8896 // In some circumstances, we permit casting from void* to cv1 T*, when the
8897 // actual pointee object is actually a cv2 T.
8898 bool VoidPtrCastMaybeOK =
8899 !Result.InvalidBase && !Result.Designator.Invalid &&
8900 !Result.IsNullPtr &&
8901 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8902 E->getType()->getPointeeType());
8903 // 1. We'll allow it in std::allocator::allocate, and anything which that
8904 // calls.
8905 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8906 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8907 // We'll allow it in the body of std::source_location::current. GCC's
8908 // implementation had a parameter of type `void*`, and casts from
8909 // that back to `const __impl*` in its body.
8910 if (VoidPtrCastMaybeOK &&
8911 (Info.getStdAllocatorCaller("allocate") ||
8912 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8913 // Permitted.
8914 } else {
8915 Result.Designator.setInvalid();
8916 if (SubExpr->getType()->isVoidPointerType())
8917 CCEDiag(E, diag::note_constexpr_invalid_cast)
8918 << 3 << SubExpr->getType();
8919 else
8920 CCEDiag(E, diag::note_constexpr_invalid_cast)
8921 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8924 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8925 ZeroInitialization(E);
8926 return true;
8928 case CK_DerivedToBase:
8929 case CK_UncheckedDerivedToBase:
8930 if (!evaluatePointer(E->getSubExpr(), Result))
8931 return false;
8932 if (!Result.Base && Result.Offset.isZero())
8933 return true;
8935 // Now figure out the necessary offset to add to the base LV to get from
8936 // the derived class to the base class.
8937 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8938 castAs<PointerType>()->getPointeeType(),
8939 Result);
8941 case CK_BaseToDerived:
8942 if (!Visit(E->getSubExpr()))
8943 return false;
8944 if (!Result.Base && Result.Offset.isZero())
8945 return true;
8946 return HandleBaseToDerivedCast(Info, E, Result);
8948 case CK_Dynamic:
8949 if (!Visit(E->getSubExpr()))
8950 return false;
8951 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8953 case CK_NullToPointer:
8954 VisitIgnoredValue(E->getSubExpr());
8955 return ZeroInitialization(E);
8957 case CK_IntegralToPointer: {
8958 CCEDiag(E, diag::note_constexpr_invalid_cast)
8959 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8961 APValue Value;
8962 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8963 break;
8965 if (Value.isInt()) {
8966 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8967 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8968 Result.Base = (Expr*)nullptr;
8969 Result.InvalidBase = false;
8970 Result.Offset = CharUnits::fromQuantity(N);
8971 Result.Designator.setInvalid();
8972 Result.IsNullPtr = false;
8973 return true;
8974 } else {
8975 // Cast is of an lvalue, no need to change value.
8976 Result.setFrom(Info.Ctx, Value);
8977 return true;
8981 case CK_ArrayToPointerDecay: {
8982 if (SubExpr->isGLValue()) {
8983 if (!evaluateLValue(SubExpr, Result))
8984 return false;
8985 } else {
8986 APValue &Value = Info.CurrentCall->createTemporary(
8987 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8988 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8989 return false;
8991 // The result is a pointer to the first element of the array.
8992 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8993 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8994 Result.addArray(Info, E, CAT);
8995 else
8996 Result.addUnsizedArray(Info, E, AT->getElementType());
8997 return true;
9000 case CK_FunctionToPointerDecay:
9001 return evaluateLValue(SubExpr, Result);
9003 case CK_LValueToRValue: {
9004 LValue LVal;
9005 if (!evaluateLValue(E->getSubExpr(), LVal))
9006 return false;
9008 APValue RVal;
9009 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9010 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9011 LVal, RVal))
9012 return InvalidBaseOK &&
9013 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9014 return Success(RVal, E);
9018 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9021 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9022 UnaryExprOrTypeTrait ExprKind) {
9023 // C++ [expr.alignof]p3:
9024 // When alignof is applied to a reference type, the result is the
9025 // alignment of the referenced type.
9026 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9027 T = Ref->getPointeeType();
9029 if (T.getQualifiers().hasUnaligned())
9030 return CharUnits::One();
9032 const bool AlignOfReturnsPreferred =
9033 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9035 // __alignof is defined to return the preferred alignment.
9036 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9037 // as well.
9038 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9039 return Info.Ctx.toCharUnitsFromBits(
9040 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9041 // alignof and _Alignof are defined to return the ABI alignment.
9042 else if (ExprKind == UETT_AlignOf)
9043 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9044 else
9045 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9048 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9049 UnaryExprOrTypeTrait ExprKind) {
9050 E = E->IgnoreParens();
9052 // The kinds of expressions that we have special-case logic here for
9053 // should be kept up to date with the special checks for those
9054 // expressions in Sema.
9056 // alignof decl is always accepted, even if it doesn't make sense: we default
9057 // to 1 in those cases.
9058 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9059 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9060 /*RefAsPointee*/true);
9062 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9063 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9064 /*RefAsPointee*/true);
9066 return GetAlignOfType(Info, E->getType(), ExprKind);
9069 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9070 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9071 return Info.Ctx.getDeclAlign(VD);
9072 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9073 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9074 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9077 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9078 /// __builtin_is_aligned and __builtin_assume_aligned.
9079 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9080 EvalInfo &Info, APSInt &Alignment) {
9081 if (!EvaluateInteger(E, Alignment, Info))
9082 return false;
9083 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9084 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9085 return false;
9087 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9088 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9089 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9090 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9091 << MaxValue << ForType << Alignment;
9092 return false;
9094 // Ensure both alignment and source value have the same bit width so that we
9095 // don't assert when computing the resulting value.
9096 APSInt ExtAlignment =
9097 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9098 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9099 "Alignment should not be changed by ext/trunc");
9100 Alignment = ExtAlignment;
9101 assert(Alignment.getBitWidth() == SrcWidth);
9102 return true;
9105 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9106 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9107 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9108 return true;
9110 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9111 return false;
9113 Result.setInvalid(E);
9114 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9115 Result.addUnsizedArray(Info, E, PointeeTy);
9116 return true;
9119 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9120 if (!IsConstantEvaluatedBuiltinCall(E))
9121 return visitNonBuiltinCallExpr(E);
9122 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9125 // Determine if T is a character type for which we guarantee that
9126 // sizeof(T) == 1.
9127 static bool isOneByteCharacterType(QualType T) {
9128 return T->isCharType() || T->isChar8Type();
9131 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9132 unsigned BuiltinOp) {
9133 if (IsNoOpCall(E))
9134 return Success(E);
9136 switch (BuiltinOp) {
9137 case Builtin::BIaddressof:
9138 case Builtin::BI__addressof:
9139 case Builtin::BI__builtin_addressof:
9140 return evaluateLValue(E->getArg(0), Result);
9141 case Builtin::BI__builtin_assume_aligned: {
9142 // We need to be very careful here because: if the pointer does not have the
9143 // asserted alignment, then the behavior is undefined, and undefined
9144 // behavior is non-constant.
9145 if (!evaluatePointer(E->getArg(0), Result))
9146 return false;
9148 LValue OffsetResult(Result);
9149 APSInt Alignment;
9150 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9151 Alignment))
9152 return false;
9153 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9155 if (E->getNumArgs() > 2) {
9156 APSInt Offset;
9157 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9158 return false;
9160 int64_t AdditionalOffset = -Offset.getZExtValue();
9161 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9164 // If there is a base object, then it must have the correct alignment.
9165 if (OffsetResult.Base) {
9166 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9168 if (BaseAlignment < Align) {
9169 Result.Designator.setInvalid();
9170 // FIXME: Add support to Diagnostic for long / long long.
9171 CCEDiag(E->getArg(0),
9172 diag::note_constexpr_baa_insufficient_alignment) << 0
9173 << (unsigned)BaseAlignment.getQuantity()
9174 << (unsigned)Align.getQuantity();
9175 return false;
9179 // The offset must also have the correct alignment.
9180 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9181 Result.Designator.setInvalid();
9183 (OffsetResult.Base
9184 ? CCEDiag(E->getArg(0),
9185 diag::note_constexpr_baa_insufficient_alignment) << 1
9186 : CCEDiag(E->getArg(0),
9187 diag::note_constexpr_baa_value_insufficient_alignment))
9188 << (int)OffsetResult.Offset.getQuantity()
9189 << (unsigned)Align.getQuantity();
9190 return false;
9193 return true;
9195 case Builtin::BI__builtin_align_up:
9196 case Builtin::BI__builtin_align_down: {
9197 if (!evaluatePointer(E->getArg(0), Result))
9198 return false;
9199 APSInt Alignment;
9200 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9201 Alignment))
9202 return false;
9203 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9204 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9205 // For align_up/align_down, we can return the same value if the alignment
9206 // is known to be greater or equal to the requested value.
9207 if (PtrAlign.getQuantity() >= Alignment)
9208 return true;
9210 // The alignment could be greater than the minimum at run-time, so we cannot
9211 // infer much about the resulting pointer value. One case is possible:
9212 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9213 // can infer the correct index if the requested alignment is smaller than
9214 // the base alignment so we can perform the computation on the offset.
9215 if (BaseAlignment.getQuantity() >= Alignment) {
9216 assert(Alignment.getBitWidth() <= 64 &&
9217 "Cannot handle > 64-bit address-space");
9218 uint64_t Alignment64 = Alignment.getZExtValue();
9219 CharUnits NewOffset = CharUnits::fromQuantity(
9220 BuiltinOp == Builtin::BI__builtin_align_down
9221 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9222 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9223 Result.adjustOffset(NewOffset - Result.Offset);
9224 // TODO: diagnose out-of-bounds values/only allow for arrays?
9225 return true;
9227 // Otherwise, we cannot constant-evaluate the result.
9228 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9229 << Alignment;
9230 return false;
9232 case Builtin::BI__builtin_operator_new:
9233 return HandleOperatorNewCall(Info, E, Result);
9234 case Builtin::BI__builtin_launder:
9235 return evaluatePointer(E->getArg(0), Result);
9236 case Builtin::BIstrchr:
9237 case Builtin::BIwcschr:
9238 case Builtin::BImemchr:
9239 case Builtin::BIwmemchr:
9240 if (Info.getLangOpts().CPlusPlus11)
9241 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9242 << /*isConstexpr*/0 << /*isConstructor*/0
9243 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9244 else
9245 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9246 [[fallthrough]];
9247 case Builtin::BI__builtin_strchr:
9248 case Builtin::BI__builtin_wcschr:
9249 case Builtin::BI__builtin_memchr:
9250 case Builtin::BI__builtin_char_memchr:
9251 case Builtin::BI__builtin_wmemchr: {
9252 if (!Visit(E->getArg(0)))
9253 return false;
9254 APSInt Desired;
9255 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9256 return false;
9257 uint64_t MaxLength = uint64_t(-1);
9258 if (BuiltinOp != Builtin::BIstrchr &&
9259 BuiltinOp != Builtin::BIwcschr &&
9260 BuiltinOp != Builtin::BI__builtin_strchr &&
9261 BuiltinOp != Builtin::BI__builtin_wcschr) {
9262 APSInt N;
9263 if (!EvaluateInteger(E->getArg(2), N, Info))
9264 return false;
9265 MaxLength = N.getExtValue();
9267 // We cannot find the value if there are no candidates to match against.
9268 if (MaxLength == 0u)
9269 return ZeroInitialization(E);
9270 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9271 Result.Designator.Invalid)
9272 return false;
9273 QualType CharTy = Result.Designator.getType(Info.Ctx);
9274 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9275 BuiltinOp == Builtin::BI__builtin_memchr;
9276 assert(IsRawByte ||
9277 Info.Ctx.hasSameUnqualifiedType(
9278 CharTy, E->getArg(0)->getType()->getPointeeType()));
9279 // Pointers to const void may point to objects of incomplete type.
9280 if (IsRawByte && CharTy->isIncompleteType()) {
9281 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9282 return false;
9284 // Give up on byte-oriented matching against multibyte elements.
9285 // FIXME: We can compare the bytes in the correct order.
9286 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9287 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9288 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9289 << CharTy;
9290 return false;
9292 // Figure out what value we're actually looking for (after converting to
9293 // the corresponding unsigned type if necessary).
9294 uint64_t DesiredVal;
9295 bool StopAtNull = false;
9296 switch (BuiltinOp) {
9297 case Builtin::BIstrchr:
9298 case Builtin::BI__builtin_strchr:
9299 // strchr compares directly to the passed integer, and therefore
9300 // always fails if given an int that is not a char.
9301 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9302 E->getArg(1)->getType(),
9303 Desired),
9304 Desired))
9305 return ZeroInitialization(E);
9306 StopAtNull = true;
9307 [[fallthrough]];
9308 case Builtin::BImemchr:
9309 case Builtin::BI__builtin_memchr:
9310 case Builtin::BI__builtin_char_memchr:
9311 // memchr compares by converting both sides to unsigned char. That's also
9312 // correct for strchr if we get this far (to cope with plain char being
9313 // unsigned in the strchr case).
9314 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9315 break;
9317 case Builtin::BIwcschr:
9318 case Builtin::BI__builtin_wcschr:
9319 StopAtNull = true;
9320 [[fallthrough]];
9321 case Builtin::BIwmemchr:
9322 case Builtin::BI__builtin_wmemchr:
9323 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9324 DesiredVal = Desired.getZExtValue();
9325 break;
9328 for (; MaxLength; --MaxLength) {
9329 APValue Char;
9330 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9331 !Char.isInt())
9332 return false;
9333 if (Char.getInt().getZExtValue() == DesiredVal)
9334 return true;
9335 if (StopAtNull && !Char.getInt())
9336 break;
9337 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9338 return false;
9340 // Not found: return nullptr.
9341 return ZeroInitialization(E);
9344 case Builtin::BImemcpy:
9345 case Builtin::BImemmove:
9346 case Builtin::BIwmemcpy:
9347 case Builtin::BIwmemmove:
9348 if (Info.getLangOpts().CPlusPlus11)
9349 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9350 << /*isConstexpr*/0 << /*isConstructor*/0
9351 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9352 else
9353 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9354 [[fallthrough]];
9355 case Builtin::BI__builtin_memcpy:
9356 case Builtin::BI__builtin_memmove:
9357 case Builtin::BI__builtin_wmemcpy:
9358 case Builtin::BI__builtin_wmemmove: {
9359 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9360 BuiltinOp == Builtin::BIwmemmove ||
9361 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9362 BuiltinOp == Builtin::BI__builtin_wmemmove;
9363 bool Move = BuiltinOp == Builtin::BImemmove ||
9364 BuiltinOp == Builtin::BIwmemmove ||
9365 BuiltinOp == Builtin::BI__builtin_memmove ||
9366 BuiltinOp == Builtin::BI__builtin_wmemmove;
9368 // The result of mem* is the first argument.
9369 if (!Visit(E->getArg(0)))
9370 return false;
9371 LValue Dest = Result;
9373 LValue Src;
9374 if (!EvaluatePointer(E->getArg(1), Src, Info))
9375 return false;
9377 APSInt N;
9378 if (!EvaluateInteger(E->getArg(2), N, Info))
9379 return false;
9380 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9382 // If the size is zero, we treat this as always being a valid no-op.
9383 // (Even if one of the src and dest pointers is null.)
9384 if (!N)
9385 return true;
9387 // Otherwise, if either of the operands is null, we can't proceed. Don't
9388 // try to determine the type of the copied objects, because there aren't
9389 // any.
9390 if (!Src.Base || !Dest.Base) {
9391 APValue Val;
9392 (!Src.Base ? Src : Dest).moveInto(Val);
9393 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9394 << Move << WChar << !!Src.Base
9395 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9396 return false;
9398 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9399 return false;
9401 // We require that Src and Dest are both pointers to arrays of
9402 // trivially-copyable type. (For the wide version, the designator will be
9403 // invalid if the designated object is not a wchar_t.)
9404 QualType T = Dest.Designator.getType(Info.Ctx);
9405 QualType SrcT = Src.Designator.getType(Info.Ctx);
9406 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9407 // FIXME: Consider using our bit_cast implementation to support this.
9408 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9409 return false;
9411 if (T->isIncompleteType()) {
9412 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9413 return false;
9415 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9416 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9417 return false;
9420 // Figure out how many T's we're copying.
9421 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9422 if (!WChar) {
9423 uint64_t Remainder;
9424 llvm::APInt OrigN = N;
9425 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9426 if (Remainder) {
9427 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9428 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9429 << (unsigned)TSize;
9430 return false;
9434 // Check that the copying will remain within the arrays, just so that we
9435 // can give a more meaningful diagnostic. This implicitly also checks that
9436 // N fits into 64 bits.
9437 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9438 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9439 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9440 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9441 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9442 << toString(N, 10, /*Signed*/false);
9443 return false;
9445 uint64_t NElems = N.getZExtValue();
9446 uint64_t NBytes = NElems * TSize;
9448 // Check for overlap.
9449 int Direction = 1;
9450 if (HasSameBase(Src, Dest)) {
9451 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9452 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9453 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9454 // Dest is inside the source region.
9455 if (!Move) {
9456 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9457 return false;
9459 // For memmove and friends, copy backwards.
9460 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9461 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9462 return false;
9463 Direction = -1;
9464 } else if (!Move && SrcOffset >= DestOffset &&
9465 SrcOffset - DestOffset < NBytes) {
9466 // Src is inside the destination region for memcpy: invalid.
9467 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9468 return false;
9472 while (true) {
9473 APValue Val;
9474 // FIXME: Set WantObjectRepresentation to true if we're copying a
9475 // char-like type?
9476 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9477 !handleAssignment(Info, E, Dest, T, Val))
9478 return false;
9479 // Do not iterate past the last element; if we're copying backwards, that
9480 // might take us off the start of the array.
9481 if (--NElems == 0)
9482 return true;
9483 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9484 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9485 return false;
9489 default:
9490 return false;
9494 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9495 APValue &Result, const InitListExpr *ILE,
9496 QualType AllocType);
9497 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9498 APValue &Result,
9499 const CXXConstructExpr *CCE,
9500 QualType AllocType);
9502 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9503 if (!Info.getLangOpts().CPlusPlus20)
9504 Info.CCEDiag(E, diag::note_constexpr_new);
9506 // We cannot speculatively evaluate a delete expression.
9507 if (Info.SpeculativeEvaluationDepth)
9508 return false;
9510 FunctionDecl *OperatorNew = E->getOperatorNew();
9512 bool IsNothrow = false;
9513 bool IsPlacement = false;
9514 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9515 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9516 // FIXME Support array placement new.
9517 assert(E->getNumPlacementArgs() == 1);
9518 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9519 return false;
9520 if (Result.Designator.Invalid)
9521 return false;
9522 IsPlacement = true;
9523 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9524 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9525 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9526 return false;
9527 } else if (E->getNumPlacementArgs()) {
9528 // The only new-placement list we support is of the form (std::nothrow).
9530 // FIXME: There is no restriction on this, but it's not clear that any
9531 // other form makes any sense. We get here for cases such as:
9533 // new (std::align_val_t{N}) X(int)
9535 // (which should presumably be valid only if N is a multiple of
9536 // alignof(int), and in any case can't be deallocated unless N is
9537 // alignof(X) and X has new-extended alignment).
9538 if (E->getNumPlacementArgs() != 1 ||
9539 !E->getPlacementArg(0)->getType()->isNothrowT())
9540 return Error(E, diag::note_constexpr_new_placement);
9542 LValue Nothrow;
9543 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9544 return false;
9545 IsNothrow = true;
9548 const Expr *Init = E->getInitializer();
9549 const InitListExpr *ResizedArrayILE = nullptr;
9550 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9551 bool ValueInit = false;
9553 QualType AllocType = E->getAllocatedType();
9554 if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9555 const Expr *Stripped = *ArraySize;
9556 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9557 Stripped = ICE->getSubExpr())
9558 if (ICE->getCastKind() != CK_NoOp &&
9559 ICE->getCastKind() != CK_IntegralCast)
9560 break;
9562 llvm::APSInt ArrayBound;
9563 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9564 return false;
9566 // C++ [expr.new]p9:
9567 // The expression is erroneous if:
9568 // -- [...] its value before converting to size_t [or] applying the
9569 // second standard conversion sequence is less than zero
9570 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9571 if (IsNothrow)
9572 return ZeroInitialization(E);
9574 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9575 << ArrayBound << (*ArraySize)->getSourceRange();
9576 return false;
9579 // -- its value is such that the size of the allocated object would
9580 // exceed the implementation-defined limit
9581 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9582 ArrayBound) >
9583 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9584 if (IsNothrow)
9585 return ZeroInitialization(E);
9587 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9588 << ArrayBound << (*ArraySize)->getSourceRange();
9589 return false;
9592 // -- the new-initializer is a braced-init-list and the number of
9593 // array elements for which initializers are provided [...]
9594 // exceeds the number of elements to initialize
9595 if (!Init) {
9596 // No initialization is performed.
9597 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9598 isa<ImplicitValueInitExpr>(Init)) {
9599 ValueInit = true;
9600 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9601 ResizedArrayCCE = CCE;
9602 } else {
9603 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9604 assert(CAT && "unexpected type for array initializer");
9606 unsigned Bits =
9607 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9608 llvm::APInt InitBound = CAT->getSize().zext(Bits);
9609 llvm::APInt AllocBound = ArrayBound.zext(Bits);
9610 if (InitBound.ugt(AllocBound)) {
9611 if (IsNothrow)
9612 return ZeroInitialization(E);
9614 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9615 << toString(AllocBound, 10, /*Signed=*/false)
9616 << toString(InitBound, 10, /*Signed=*/false)
9617 << (*ArraySize)->getSourceRange();
9618 return false;
9621 // If the sizes differ, we must have an initializer list, and we need
9622 // special handling for this case when we initialize.
9623 if (InitBound != AllocBound)
9624 ResizedArrayILE = cast<InitListExpr>(Init);
9627 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9628 ArrayType::Normal, 0);
9629 } else {
9630 assert(!AllocType->isArrayType() &&
9631 "array allocation with non-array new");
9634 APValue *Val;
9635 if (IsPlacement) {
9636 AccessKinds AK = AK_Construct;
9637 struct FindObjectHandler {
9638 EvalInfo &Info;
9639 const Expr *E;
9640 QualType AllocType;
9641 const AccessKinds AccessKind;
9642 APValue *Value;
9644 typedef bool result_type;
9645 bool failed() { return false; }
9646 bool found(APValue &Subobj, QualType SubobjType) {
9647 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9648 // old name of the object to be used to name the new object.
9649 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9650 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9651 SubobjType << AllocType;
9652 return false;
9654 Value = &Subobj;
9655 return true;
9657 bool found(APSInt &Value, QualType SubobjType) {
9658 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9659 return false;
9661 bool found(APFloat &Value, QualType SubobjType) {
9662 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9663 return false;
9665 } Handler = {Info, E, AllocType, AK, nullptr};
9667 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9668 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9669 return false;
9671 Val = Handler.Value;
9673 // [basic.life]p1:
9674 // The lifetime of an object o of type T ends when [...] the storage
9675 // which the object occupies is [...] reused by an object that is not
9676 // nested within o (6.6.2).
9677 *Val = APValue();
9678 } else {
9679 // Perform the allocation and obtain a pointer to the resulting object.
9680 Val = Info.createHeapAlloc(E, AllocType, Result);
9681 if (!Val)
9682 return false;
9685 if (ValueInit) {
9686 ImplicitValueInitExpr VIE(AllocType);
9687 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9688 return false;
9689 } else if (ResizedArrayILE) {
9690 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9691 AllocType))
9692 return false;
9693 } else if (ResizedArrayCCE) {
9694 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9695 AllocType))
9696 return false;
9697 } else if (Init) {
9698 if (!EvaluateInPlace(*Val, Info, Result, Init))
9699 return false;
9700 } else if (!getDefaultInitValue(AllocType, *Val)) {
9701 return false;
9704 // Array new returns a pointer to the first element, not a pointer to the
9705 // array.
9706 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9707 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9709 return true;
9711 //===----------------------------------------------------------------------===//
9712 // Member Pointer Evaluation
9713 //===----------------------------------------------------------------------===//
9715 namespace {
9716 class MemberPointerExprEvaluator
9717 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9718 MemberPtr &Result;
9720 bool Success(const ValueDecl *D) {
9721 Result = MemberPtr(D);
9722 return true;
9724 public:
9726 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9727 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9729 bool Success(const APValue &V, const Expr *E) {
9730 Result.setFrom(V);
9731 return true;
9733 bool ZeroInitialization(const Expr *E) {
9734 return Success((const ValueDecl*)nullptr);
9737 bool VisitCastExpr(const CastExpr *E);
9738 bool VisitUnaryAddrOf(const UnaryOperator *E);
9740 } // end anonymous namespace
9742 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9743 EvalInfo &Info) {
9744 assert(!E->isValueDependent());
9745 assert(E->isPRValue() && E->getType()->isMemberPointerType());
9746 return MemberPointerExprEvaluator(Info, Result).Visit(E);
9749 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9750 switch (E->getCastKind()) {
9751 default:
9752 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9754 case CK_NullToMemberPointer:
9755 VisitIgnoredValue(E->getSubExpr());
9756 return ZeroInitialization(E);
9758 case CK_BaseToDerivedMemberPointer: {
9759 if (!Visit(E->getSubExpr()))
9760 return false;
9761 if (E->path_empty())
9762 return true;
9763 // Base-to-derived member pointer casts store the path in derived-to-base
9764 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9765 // the wrong end of the derived->base arc, so stagger the path by one class.
9766 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9767 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9768 PathI != PathE; ++PathI) {
9769 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9770 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9771 if (!Result.castToDerived(Derived))
9772 return Error(E);
9774 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9775 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9776 return Error(E);
9777 return true;
9780 case CK_DerivedToBaseMemberPointer:
9781 if (!Visit(E->getSubExpr()))
9782 return false;
9783 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9784 PathE = E->path_end(); PathI != PathE; ++PathI) {
9785 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9786 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9787 if (!Result.castToBase(Base))
9788 return Error(E);
9790 return true;
9794 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9795 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9796 // member can be formed.
9797 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9800 //===----------------------------------------------------------------------===//
9801 // Record Evaluation
9802 //===----------------------------------------------------------------------===//
9804 namespace {
9805 class RecordExprEvaluator
9806 : public ExprEvaluatorBase<RecordExprEvaluator> {
9807 const LValue &This;
9808 APValue &Result;
9809 public:
9811 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9812 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9814 bool Success(const APValue &V, const Expr *E) {
9815 Result = V;
9816 return true;
9818 bool ZeroInitialization(const Expr *E) {
9819 return ZeroInitialization(E, E->getType());
9821 bool ZeroInitialization(const Expr *E, QualType T);
9823 bool VisitCallExpr(const CallExpr *E) {
9824 return handleCallExpr(E, Result, &This);
9826 bool VisitCastExpr(const CastExpr *E);
9827 bool VisitInitListExpr(const InitListExpr *E);
9828 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9829 return VisitCXXConstructExpr(E, E->getType());
9831 bool VisitLambdaExpr(const LambdaExpr *E);
9832 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9833 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9834 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9835 bool VisitBinCmp(const BinaryOperator *E);
9839 /// Perform zero-initialization on an object of non-union class type.
9840 /// C++11 [dcl.init]p5:
9841 /// To zero-initialize an object or reference of type T means:
9842 /// [...]
9843 /// -- if T is a (possibly cv-qualified) non-union class type,
9844 /// each non-static data member and each base-class subobject is
9845 /// zero-initialized
9846 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9847 const RecordDecl *RD,
9848 const LValue &This, APValue &Result) {
9849 assert(!RD->isUnion() && "Expected non-union class type");
9850 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9851 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9852 std::distance(RD->field_begin(), RD->field_end()));
9854 if (RD->isInvalidDecl()) return false;
9855 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9857 if (CD) {
9858 unsigned Index = 0;
9859 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9860 End = CD->bases_end(); I != End; ++I, ++Index) {
9861 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9862 LValue Subobject = This;
9863 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9864 return false;
9865 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9866 Result.getStructBase(Index)))
9867 return false;
9871 for (const auto *I : RD->fields()) {
9872 // -- if T is a reference type, no initialization is performed.
9873 if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9874 continue;
9876 LValue Subobject = This;
9877 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9878 return false;
9880 ImplicitValueInitExpr VIE(I->getType());
9881 if (!EvaluateInPlace(
9882 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9883 return false;
9886 return true;
9889 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9890 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9891 if (RD->isInvalidDecl()) return false;
9892 if (RD->isUnion()) {
9893 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9894 // object's first non-static named data member is zero-initialized
9895 RecordDecl::field_iterator I = RD->field_begin();
9896 while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9897 ++I;
9898 if (I == RD->field_end()) {
9899 Result = APValue((const FieldDecl*)nullptr);
9900 return true;
9903 LValue Subobject = This;
9904 if (!HandleLValueMember(Info, E, Subobject, *I))
9905 return false;
9906 Result = APValue(*I);
9907 ImplicitValueInitExpr VIE(I->getType());
9908 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9911 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9912 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9913 return false;
9916 return HandleClassZeroInitialization(Info, E, RD, This, Result);
9919 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9920 switch (E->getCastKind()) {
9921 default:
9922 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9924 case CK_ConstructorConversion:
9925 return Visit(E->getSubExpr());
9927 case CK_DerivedToBase:
9928 case CK_UncheckedDerivedToBase: {
9929 APValue DerivedObject;
9930 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9931 return false;
9932 if (!DerivedObject.isStruct())
9933 return Error(E->getSubExpr());
9935 // Derived-to-base rvalue conversion: just slice off the derived part.
9936 APValue *Value = &DerivedObject;
9937 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9938 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9939 PathE = E->path_end(); PathI != PathE; ++PathI) {
9940 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9941 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9942 Value = &Value->getStructBase(getBaseIndex(RD, Base));
9943 RD = Base;
9945 Result = *Value;
9946 return true;
9951 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9952 if (E->isTransparent())
9953 return Visit(E->getInit(0));
9955 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9956 if (RD->isInvalidDecl()) return false;
9957 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9958 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9960 EvalInfo::EvaluatingConstructorRAII EvalObj(
9961 Info,
9962 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9963 CXXRD && CXXRD->getNumBases());
9965 if (RD->isUnion()) {
9966 const FieldDecl *Field = E->getInitializedFieldInUnion();
9967 Result = APValue(Field);
9968 if (!Field)
9969 return true;
9971 // If the initializer list for a union does not contain any elements, the
9972 // first element of the union is value-initialized.
9973 // FIXME: The element should be initialized from an initializer list.
9974 // Is this difference ever observable for initializer lists which
9975 // we don't build?
9976 ImplicitValueInitExpr VIE(Field->getType());
9977 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9979 LValue Subobject = This;
9980 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9981 return false;
9983 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9984 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9985 isa<CXXDefaultInitExpr>(InitExpr));
9987 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9988 if (Field->isBitField())
9989 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9990 Field);
9991 return true;
9994 return false;
9997 if (!Result.hasValue())
9998 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9999 std::distance(RD->field_begin(), RD->field_end()));
10000 unsigned ElementNo = 0;
10001 bool Success = true;
10003 // Initialize base classes.
10004 if (CXXRD && CXXRD->getNumBases()) {
10005 for (const auto &Base : CXXRD->bases()) {
10006 assert(ElementNo < E->getNumInits() && "missing init for base class");
10007 const Expr *Init = E->getInit(ElementNo);
10009 LValue Subobject = This;
10010 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10011 return false;
10013 APValue &FieldVal = Result.getStructBase(ElementNo);
10014 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10015 if (!Info.noteFailure())
10016 return false;
10017 Success = false;
10019 ++ElementNo;
10022 EvalObj.finishedConstructingBases();
10025 // Initialize members.
10026 for (const auto *Field : RD->fields()) {
10027 // Anonymous bit-fields are not considered members of the class for
10028 // purposes of aggregate initialization.
10029 if (Field->isUnnamedBitfield())
10030 continue;
10032 LValue Subobject = This;
10034 bool HaveInit = ElementNo < E->getNumInits();
10036 // FIXME: Diagnostics here should point to the end of the initializer
10037 // list, not the start.
10038 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10039 Subobject, Field, &Layout))
10040 return false;
10042 // Perform an implicit value-initialization for members beyond the end of
10043 // the initializer list.
10044 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10045 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10047 if (Field->getType()->isIncompleteArrayType()) {
10048 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10049 if (!CAT->getSize().isZero()) {
10050 // Bail out for now. This might sort of "work", but the rest of the
10051 // code isn't really prepared to handle it.
10052 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10053 return false;
10058 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10059 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10060 isa<CXXDefaultInitExpr>(Init));
10062 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10063 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10064 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10065 FieldVal, Field))) {
10066 if (!Info.noteFailure())
10067 return false;
10068 Success = false;
10072 EvalObj.finishedConstructingFields();
10074 return Success;
10077 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10078 QualType T) {
10079 // Note that E's type is not necessarily the type of our class here; we might
10080 // be initializing an array element instead.
10081 const CXXConstructorDecl *FD = E->getConstructor();
10082 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10084 bool ZeroInit = E->requiresZeroInitialization();
10085 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10086 // If we've already performed zero-initialization, we're already done.
10087 if (Result.hasValue())
10088 return true;
10090 if (ZeroInit)
10091 return ZeroInitialization(E, T);
10093 return getDefaultInitValue(T, Result);
10096 const FunctionDecl *Definition = nullptr;
10097 auto Body = FD->getBody(Definition);
10099 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10100 return false;
10102 // Avoid materializing a temporary for an elidable copy/move constructor.
10103 if (E->isElidable() && !ZeroInit) {
10104 // FIXME: This only handles the simplest case, where the source object
10105 // is passed directly as the first argument to the constructor.
10106 // This should also handle stepping though implicit casts and
10107 // and conversion sequences which involve two steps, with a
10108 // conversion operator followed by a converting constructor.
10109 const Expr *SrcObj = E->getArg(0);
10110 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10111 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10112 if (const MaterializeTemporaryExpr *ME =
10113 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10114 return Visit(ME->getSubExpr());
10117 if (ZeroInit && !ZeroInitialization(E, T))
10118 return false;
10120 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10121 return HandleConstructorCall(E, This, Args,
10122 cast<CXXConstructorDecl>(Definition), Info,
10123 Result);
10126 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10127 const CXXInheritedCtorInitExpr *E) {
10128 if (!Info.CurrentCall) {
10129 assert(Info.checkingPotentialConstantExpression());
10130 return false;
10133 const CXXConstructorDecl *FD = E->getConstructor();
10134 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10135 return false;
10137 const FunctionDecl *Definition = nullptr;
10138 auto Body = FD->getBody(Definition);
10140 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10141 return false;
10143 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10144 cast<CXXConstructorDecl>(Definition), Info,
10145 Result);
10148 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10149 const CXXStdInitializerListExpr *E) {
10150 const ConstantArrayType *ArrayType =
10151 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10153 LValue Array;
10154 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10155 return false;
10157 // Get a pointer to the first element of the array.
10158 Array.addArray(Info, E, ArrayType);
10160 auto InvalidType = [&] {
10161 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10162 << E->getType();
10163 return false;
10166 // FIXME: Perform the checks on the field types in SemaInit.
10167 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10168 RecordDecl::field_iterator Field = Record->field_begin();
10169 if (Field == Record->field_end())
10170 return InvalidType();
10172 // Start pointer.
10173 if (!Field->getType()->isPointerType() ||
10174 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10175 ArrayType->getElementType()))
10176 return InvalidType();
10178 // FIXME: What if the initializer_list type has base classes, etc?
10179 Result = APValue(APValue::UninitStruct(), 0, 2);
10180 Array.moveInto(Result.getStructField(0));
10182 if (++Field == Record->field_end())
10183 return InvalidType();
10185 if (Field->getType()->isPointerType() &&
10186 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10187 ArrayType->getElementType())) {
10188 // End pointer.
10189 if (!HandleLValueArrayAdjustment(Info, E, Array,
10190 ArrayType->getElementType(),
10191 ArrayType->getSize().getZExtValue()))
10192 return false;
10193 Array.moveInto(Result.getStructField(1));
10194 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10195 // Length.
10196 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10197 else
10198 return InvalidType();
10200 if (++Field != Record->field_end())
10201 return InvalidType();
10203 return true;
10206 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10207 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10208 if (ClosureClass->isInvalidDecl())
10209 return false;
10211 const size_t NumFields =
10212 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10214 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10215 E->capture_init_end()) &&
10216 "The number of lambda capture initializers should equal the number of "
10217 "fields within the closure type");
10219 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10220 // Iterate through all the lambda's closure object's fields and initialize
10221 // them.
10222 auto *CaptureInitIt = E->capture_init_begin();
10223 bool Success = true;
10224 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10225 for (const auto *Field : ClosureClass->fields()) {
10226 assert(CaptureInitIt != E->capture_init_end());
10227 // Get the initializer for this field
10228 Expr *const CurFieldInit = *CaptureInitIt++;
10230 // If there is no initializer, either this is a VLA or an error has
10231 // occurred.
10232 if (!CurFieldInit)
10233 return Error(E);
10235 LValue Subobject = This;
10237 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10238 return false;
10240 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10241 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10242 if (!Info.keepEvaluatingAfterFailure())
10243 return false;
10244 Success = false;
10247 return Success;
10250 static bool EvaluateRecord(const Expr *E, const LValue &This,
10251 APValue &Result, EvalInfo &Info) {
10252 assert(!E->isValueDependent());
10253 assert(E->isPRValue() && E->getType()->isRecordType() &&
10254 "can't evaluate expression as a record rvalue");
10255 return RecordExprEvaluator(Info, This, Result).Visit(E);
10258 //===----------------------------------------------------------------------===//
10259 // Temporary Evaluation
10261 // Temporaries are represented in the AST as rvalues, but generally behave like
10262 // lvalues. The full-object of which the temporary is a subobject is implicitly
10263 // materialized so that a reference can bind to it.
10264 //===----------------------------------------------------------------------===//
10265 namespace {
10266 class TemporaryExprEvaluator
10267 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10268 public:
10269 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10270 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10272 /// Visit an expression which constructs the value of this temporary.
10273 bool VisitConstructExpr(const Expr *E) {
10274 APValue &Value = Info.CurrentCall->createTemporary(
10275 E, E->getType(), ScopeKind::FullExpression, Result);
10276 return EvaluateInPlace(Value, Info, Result, E);
10279 bool VisitCastExpr(const CastExpr *E) {
10280 switch (E->getCastKind()) {
10281 default:
10282 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10284 case CK_ConstructorConversion:
10285 return VisitConstructExpr(E->getSubExpr());
10288 bool VisitInitListExpr(const InitListExpr *E) {
10289 return VisitConstructExpr(E);
10291 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10292 return VisitConstructExpr(E);
10294 bool VisitCallExpr(const CallExpr *E) {
10295 return VisitConstructExpr(E);
10297 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10298 return VisitConstructExpr(E);
10300 bool VisitLambdaExpr(const LambdaExpr *E) {
10301 return VisitConstructExpr(E);
10304 } // end anonymous namespace
10306 /// Evaluate an expression of record type as a temporary.
10307 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10308 assert(!E->isValueDependent());
10309 assert(E->isPRValue() && E->getType()->isRecordType());
10310 return TemporaryExprEvaluator(Info, Result).Visit(E);
10313 //===----------------------------------------------------------------------===//
10314 // Vector Evaluation
10315 //===----------------------------------------------------------------------===//
10317 namespace {
10318 class VectorExprEvaluator
10319 : public ExprEvaluatorBase<VectorExprEvaluator> {
10320 APValue &Result;
10321 public:
10323 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10324 : ExprEvaluatorBaseTy(info), Result(Result) {}
10326 bool Success(ArrayRef<APValue> V, const Expr *E) {
10327 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10328 // FIXME: remove this APValue copy.
10329 Result = APValue(V.data(), V.size());
10330 return true;
10332 bool Success(const APValue &V, const Expr *E) {
10333 assert(V.isVector());
10334 Result = V;
10335 return true;
10337 bool ZeroInitialization(const Expr *E);
10339 bool VisitUnaryReal(const UnaryOperator *E)
10340 { return Visit(E->getSubExpr()); }
10341 bool VisitCastExpr(const CastExpr* E);
10342 bool VisitInitListExpr(const InitListExpr *E);
10343 bool VisitUnaryImag(const UnaryOperator *E);
10344 bool VisitBinaryOperator(const BinaryOperator *E);
10345 bool VisitUnaryOperator(const UnaryOperator *E);
10346 // FIXME: Missing: conditional operator (for GNU
10347 // conditional select), shufflevector, ExtVectorElementExpr
10349 } // end anonymous namespace
10351 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10352 assert(E->isPRValue() && E->getType()->isVectorType() &&
10353 "not a vector prvalue");
10354 return VectorExprEvaluator(Info, Result).Visit(E);
10357 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10358 const VectorType *VTy = E->getType()->castAs<VectorType>();
10359 unsigned NElts = VTy->getNumElements();
10361 const Expr *SE = E->getSubExpr();
10362 QualType SETy = SE->getType();
10364 switch (E->getCastKind()) {
10365 case CK_VectorSplat: {
10366 APValue Val = APValue();
10367 if (SETy->isIntegerType()) {
10368 APSInt IntResult;
10369 if (!EvaluateInteger(SE, IntResult, Info))
10370 return false;
10371 Val = APValue(std::move(IntResult));
10372 } else if (SETy->isRealFloatingType()) {
10373 APFloat FloatResult(0.0);
10374 if (!EvaluateFloat(SE, FloatResult, Info))
10375 return false;
10376 Val = APValue(std::move(FloatResult));
10377 } else {
10378 return Error(E);
10381 // Splat and create vector APValue.
10382 SmallVector<APValue, 4> Elts(NElts, Val);
10383 return Success(Elts, E);
10385 case CK_BitCast: {
10386 // Evaluate the operand into an APInt we can extract from.
10387 llvm::APInt SValInt;
10388 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10389 return false;
10390 // Extract the elements
10391 QualType EltTy = VTy->getElementType();
10392 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10393 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10394 SmallVector<APValue, 4> Elts;
10395 if (EltTy->isRealFloatingType()) {
10396 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10397 unsigned FloatEltSize = EltSize;
10398 if (&Sem == &APFloat::x87DoubleExtended())
10399 FloatEltSize = 80;
10400 for (unsigned i = 0; i < NElts; i++) {
10401 llvm::APInt Elt;
10402 if (BigEndian)
10403 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10404 else
10405 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10406 Elts.push_back(APValue(APFloat(Sem, Elt)));
10408 } else if (EltTy->isIntegerType()) {
10409 for (unsigned i = 0; i < NElts; i++) {
10410 llvm::APInt Elt;
10411 if (BigEndian)
10412 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10413 else
10414 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10415 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10417 } else {
10418 return Error(E);
10420 return Success(Elts, E);
10422 default:
10423 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10427 bool
10428 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10429 const VectorType *VT = E->getType()->castAs<VectorType>();
10430 unsigned NumInits = E->getNumInits();
10431 unsigned NumElements = VT->getNumElements();
10433 QualType EltTy = VT->getElementType();
10434 SmallVector<APValue, 4> Elements;
10436 // The number of initializers can be less than the number of
10437 // vector elements. For OpenCL, this can be due to nested vector
10438 // initialization. For GCC compatibility, missing trailing elements
10439 // should be initialized with zeroes.
10440 unsigned CountInits = 0, CountElts = 0;
10441 while (CountElts < NumElements) {
10442 // Handle nested vector initialization.
10443 if (CountInits < NumInits
10444 && E->getInit(CountInits)->getType()->isVectorType()) {
10445 APValue v;
10446 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10447 return Error(E);
10448 unsigned vlen = v.getVectorLength();
10449 for (unsigned j = 0; j < vlen; j++)
10450 Elements.push_back(v.getVectorElt(j));
10451 CountElts += vlen;
10452 } else if (EltTy->isIntegerType()) {
10453 llvm::APSInt sInt(32);
10454 if (CountInits < NumInits) {
10455 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10456 return false;
10457 } else // trailing integer zero.
10458 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10459 Elements.push_back(APValue(sInt));
10460 CountElts++;
10461 } else {
10462 llvm::APFloat f(0.0);
10463 if (CountInits < NumInits) {
10464 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10465 return false;
10466 } else // trailing float zero.
10467 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10468 Elements.push_back(APValue(f));
10469 CountElts++;
10471 CountInits++;
10473 return Success(Elements, E);
10476 bool
10477 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10478 const auto *VT = E->getType()->castAs<VectorType>();
10479 QualType EltTy = VT->getElementType();
10480 APValue ZeroElement;
10481 if (EltTy->isIntegerType())
10482 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10483 else
10484 ZeroElement =
10485 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10487 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10488 return Success(Elements, E);
10491 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10492 VisitIgnoredValue(E->getSubExpr());
10493 return ZeroInitialization(E);
10496 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10497 BinaryOperatorKind Op = E->getOpcode();
10498 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10499 "Operation not supported on vector types");
10501 if (Op == BO_Comma)
10502 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10504 Expr *LHS = E->getLHS();
10505 Expr *RHS = E->getRHS();
10507 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10508 "Must both be vector types");
10509 // Checking JUST the types are the same would be fine, except shifts don't
10510 // need to have their types be the same (since you always shift by an int).
10511 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10512 E->getType()->castAs<VectorType>()->getNumElements() &&
10513 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10514 E->getType()->castAs<VectorType>()->getNumElements() &&
10515 "All operands must be the same size.");
10517 APValue LHSValue;
10518 APValue RHSValue;
10519 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10520 if (!LHSOK && !Info.noteFailure())
10521 return false;
10522 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10523 return false;
10525 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10526 return false;
10528 return Success(LHSValue, E);
10531 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10532 QualType ResultTy,
10533 UnaryOperatorKind Op,
10534 APValue Elt) {
10535 switch (Op) {
10536 case UO_Plus:
10537 // Nothing to do here.
10538 return Elt;
10539 case UO_Minus:
10540 if (Elt.getKind() == APValue::Int) {
10541 Elt.getInt().negate();
10542 } else {
10543 assert(Elt.getKind() == APValue::Float &&
10544 "Vector can only be int or float type");
10545 Elt.getFloat().changeSign();
10547 return Elt;
10548 case UO_Not:
10549 // This is only valid for integral types anyway, so we don't have to handle
10550 // float here.
10551 assert(Elt.getKind() == APValue::Int &&
10552 "Vector operator ~ can only be int");
10553 Elt.getInt().flipAllBits();
10554 return Elt;
10555 case UO_LNot: {
10556 if (Elt.getKind() == APValue::Int) {
10557 Elt.getInt() = !Elt.getInt();
10558 // operator ! on vectors returns -1 for 'truth', so negate it.
10559 Elt.getInt().negate();
10560 return Elt;
10562 assert(Elt.getKind() == APValue::Float &&
10563 "Vector can only be int or float type");
10564 // Float types result in an int of the same size, but -1 for true, or 0 for
10565 // false.
10566 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10567 ResultTy->isUnsignedIntegerType()};
10568 if (Elt.getFloat().isZero())
10569 EltResult.setAllBits();
10570 else
10571 EltResult.clearAllBits();
10573 return APValue{EltResult};
10575 default:
10576 // FIXME: Implement the rest of the unary operators.
10577 return llvm::None;
10581 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10582 Expr *SubExpr = E->getSubExpr();
10583 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10584 // This result element type differs in the case of negating a floating point
10585 // vector, since the result type is the a vector of the equivilant sized
10586 // integer.
10587 const QualType ResultEltTy = VD->getElementType();
10588 UnaryOperatorKind Op = E->getOpcode();
10590 APValue SubExprValue;
10591 if (!Evaluate(SubExprValue, Info, SubExpr))
10592 return false;
10594 // FIXME: This vector evaluator someday needs to be changed to be LValue
10595 // aware/keep LValue information around, rather than dealing with just vector
10596 // types directly. Until then, we cannot handle cases where the operand to
10597 // these unary operators is an LValue. The only case I've been able to see
10598 // cause this is operator++ assigning to a member expression (only valid in
10599 // altivec compilations) in C mode, so this shouldn't limit us too much.
10600 if (SubExprValue.isLValue())
10601 return false;
10603 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10604 "Vector length doesn't match type?");
10606 SmallVector<APValue, 4> ResultElements;
10607 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10608 llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10609 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10610 if (!Elt)
10611 return false;
10612 ResultElements.push_back(*Elt);
10614 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10617 //===----------------------------------------------------------------------===//
10618 // Array Evaluation
10619 //===----------------------------------------------------------------------===//
10621 namespace {
10622 class ArrayExprEvaluator
10623 : public ExprEvaluatorBase<ArrayExprEvaluator> {
10624 const LValue &This;
10625 APValue &Result;
10626 public:
10628 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10629 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10631 bool Success(const APValue &V, const Expr *E) {
10632 assert(V.isArray() && "expected array");
10633 Result = V;
10634 return true;
10637 bool ZeroInitialization(const Expr *E) {
10638 const ConstantArrayType *CAT =
10639 Info.Ctx.getAsConstantArrayType(E->getType());
10640 if (!CAT) {
10641 if (E->getType()->isIncompleteArrayType()) {
10642 // We can be asked to zero-initialize a flexible array member; this
10643 // is represented as an ImplicitValueInitExpr of incomplete array
10644 // type. In this case, the array has zero elements.
10645 Result = APValue(APValue::UninitArray(), 0, 0);
10646 return true;
10648 // FIXME: We could handle VLAs here.
10649 return Error(E);
10652 Result = APValue(APValue::UninitArray(), 0,
10653 CAT->getSize().getZExtValue());
10654 if (!Result.hasArrayFiller())
10655 return true;
10657 // Zero-initialize all elements.
10658 LValue Subobject = This;
10659 Subobject.addArray(Info, E, CAT);
10660 ImplicitValueInitExpr VIE(CAT->getElementType());
10661 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10664 bool VisitCallExpr(const CallExpr *E) {
10665 return handleCallExpr(E, Result, &This);
10667 bool VisitInitListExpr(const InitListExpr *E,
10668 QualType AllocType = QualType());
10669 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10670 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10671 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10672 const LValue &Subobject,
10673 APValue *Value, QualType Type);
10674 bool VisitStringLiteral(const StringLiteral *E,
10675 QualType AllocType = QualType()) {
10676 expandStringLiteral(Info, E, Result, AllocType);
10677 return true;
10680 } // end anonymous namespace
10682 static bool EvaluateArray(const Expr *E, const LValue &This,
10683 APValue &Result, EvalInfo &Info) {
10684 assert(!E->isValueDependent());
10685 assert(E->isPRValue() && E->getType()->isArrayType() &&
10686 "not an array prvalue");
10687 return ArrayExprEvaluator(Info, This, Result).Visit(E);
10690 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10691 APValue &Result, const InitListExpr *ILE,
10692 QualType AllocType) {
10693 assert(!ILE->isValueDependent());
10694 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10695 "not an array prvalue");
10696 return ArrayExprEvaluator(Info, This, Result)
10697 .VisitInitListExpr(ILE, AllocType);
10700 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10701 APValue &Result,
10702 const CXXConstructExpr *CCE,
10703 QualType AllocType) {
10704 assert(!CCE->isValueDependent());
10705 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10706 "not an array prvalue");
10707 return ArrayExprEvaluator(Info, This, Result)
10708 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10711 // Return true iff the given array filler may depend on the element index.
10712 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10713 // For now, just allow non-class value-initialization and initialization
10714 // lists comprised of them.
10715 if (isa<ImplicitValueInitExpr>(FillerExpr))
10716 return false;
10717 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10718 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10719 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10720 return true;
10723 if (ILE->hasArrayFiller() &&
10724 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10725 return true;
10727 return false;
10729 return true;
10732 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10733 QualType AllocType) {
10734 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10735 AllocType.isNull() ? E->getType() : AllocType);
10736 if (!CAT)
10737 return Error(E);
10739 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10740 // an appropriately-typed string literal enclosed in braces.
10741 if (E->isStringLiteralInit()) {
10742 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10743 // FIXME: Support ObjCEncodeExpr here once we support it in
10744 // ArrayExprEvaluator generally.
10745 if (!SL)
10746 return Error(E);
10747 return VisitStringLiteral(SL, AllocType);
10749 // Any other transparent list init will need proper handling of the
10750 // AllocType; we can't just recurse to the inner initializer.
10751 assert(!E->isTransparent() &&
10752 "transparent array list initialization is not string literal init?");
10754 bool Success = true;
10756 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10757 "zero-initialized array shouldn't have any initialized elts");
10758 APValue Filler;
10759 if (Result.isArray() && Result.hasArrayFiller())
10760 Filler = Result.getArrayFiller();
10762 unsigned NumEltsToInit = E->getNumInits();
10763 unsigned NumElts = CAT->getSize().getZExtValue();
10764 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10766 // If the initializer might depend on the array index, run it for each
10767 // array element.
10768 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10769 NumEltsToInit = NumElts;
10771 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10772 << NumEltsToInit << ".\n");
10774 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10776 // If the array was previously zero-initialized, preserve the
10777 // zero-initialized values.
10778 if (Filler.hasValue()) {
10779 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10780 Result.getArrayInitializedElt(I) = Filler;
10781 if (Result.hasArrayFiller())
10782 Result.getArrayFiller() = Filler;
10785 LValue Subobject = This;
10786 Subobject.addArray(Info, E, CAT);
10787 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10788 const Expr *Init =
10789 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10790 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10791 Info, Subobject, Init) ||
10792 !HandleLValueArrayAdjustment(Info, Init, Subobject,
10793 CAT->getElementType(), 1)) {
10794 if (!Info.noteFailure())
10795 return false;
10796 Success = false;
10800 if (!Result.hasArrayFiller())
10801 return Success;
10803 // If we get here, we have a trivial filler, which we can just evaluate
10804 // once and splat over the rest of the array elements.
10805 assert(FillerExpr && "no array filler for incomplete init list");
10806 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10807 FillerExpr) && Success;
10810 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10811 LValue CommonLV;
10812 if (E->getCommonExpr() &&
10813 !Evaluate(Info.CurrentCall->createTemporary(
10814 E->getCommonExpr(),
10815 getStorageType(Info.Ctx, E->getCommonExpr()),
10816 ScopeKind::FullExpression, CommonLV),
10817 Info, E->getCommonExpr()->getSourceExpr()))
10818 return false;
10820 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10822 uint64_t Elements = CAT->getSize().getZExtValue();
10823 Result = APValue(APValue::UninitArray(), Elements, Elements);
10825 LValue Subobject = This;
10826 Subobject.addArray(Info, E, CAT);
10828 bool Success = true;
10829 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10830 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10831 Info, Subobject, E->getSubExpr()) ||
10832 !HandleLValueArrayAdjustment(Info, E, Subobject,
10833 CAT->getElementType(), 1)) {
10834 if (!Info.noteFailure())
10835 return false;
10836 Success = false;
10840 return Success;
10843 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10844 return VisitCXXConstructExpr(E, This, &Result, E->getType());
10847 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10848 const LValue &Subobject,
10849 APValue *Value,
10850 QualType Type) {
10851 bool HadZeroInit = Value->hasValue();
10853 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10854 unsigned FinalSize = CAT->getSize().getZExtValue();
10856 // Preserve the array filler if we had prior zero-initialization.
10857 APValue Filler =
10858 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10859 : APValue();
10861 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10862 if (FinalSize == 0)
10863 return true;
10865 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10866 Info, E->getExprLoc(), E->getConstructor(),
10867 E->requiresZeroInitialization());
10868 LValue ArrayElt = Subobject;
10869 ArrayElt.addArray(Info, E, CAT);
10870 // We do the whole initialization in two passes, first for just one element,
10871 // then for the whole array. It's possible we may find out we can't do const
10872 // init in the first pass, in which case we avoid allocating a potentially
10873 // large array. We don't do more passes because expanding array requires
10874 // copying the data, which is wasteful.
10875 for (const unsigned N : {1u, FinalSize}) {
10876 unsigned OldElts = Value->getArrayInitializedElts();
10877 if (OldElts == N)
10878 break;
10880 // Expand the array to appropriate size.
10881 APValue NewValue(APValue::UninitArray(), N, FinalSize);
10882 for (unsigned I = 0; I < OldElts; ++I)
10883 NewValue.getArrayInitializedElt(I).swap(
10884 Value->getArrayInitializedElt(I));
10885 Value->swap(NewValue);
10887 if (HadZeroInit)
10888 for (unsigned I = OldElts; I < N; ++I)
10889 Value->getArrayInitializedElt(I) = Filler;
10891 if (HasTrivialConstructor && N == FinalSize) {
10892 // If we have a trivial constructor, only evaluate it once and copy
10893 // the result into all the array elements.
10894 APValue &FirstResult = Value->getArrayInitializedElt(0);
10895 for (unsigned I = OldElts; I < FinalSize; ++I)
10896 Value->getArrayInitializedElt(I) = FirstResult;
10897 } else {
10898 for (unsigned I = OldElts; I < N; ++I) {
10899 if (!VisitCXXConstructExpr(E, ArrayElt,
10900 &Value->getArrayInitializedElt(I),
10901 CAT->getElementType()) ||
10902 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10903 CAT->getElementType(), 1))
10904 return false;
10905 // When checking for const initilization any diagnostic is considered
10906 // an error.
10907 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10908 !Info.keepEvaluatingAfterFailure())
10909 return false;
10914 return true;
10917 if (!Type->isRecordType())
10918 return Error(E);
10920 return RecordExprEvaluator(Info, Subobject, *Value)
10921 .VisitCXXConstructExpr(E, Type);
10924 //===----------------------------------------------------------------------===//
10925 // Integer Evaluation
10927 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10928 // types and back in constant folding. Integer values are thus represented
10929 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10930 //===----------------------------------------------------------------------===//
10932 namespace {
10933 class IntExprEvaluator
10934 : public ExprEvaluatorBase<IntExprEvaluator> {
10935 APValue &Result;
10936 public:
10937 IntExprEvaluator(EvalInfo &info, APValue &result)
10938 : ExprEvaluatorBaseTy(info), Result(result) {}
10940 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10941 assert(E->getType()->isIntegralOrEnumerationType() &&
10942 "Invalid evaluation result.");
10943 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10944 "Invalid evaluation result.");
10945 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10946 "Invalid evaluation result.");
10947 Result = APValue(SI);
10948 return true;
10950 bool Success(const llvm::APSInt &SI, const Expr *E) {
10951 return Success(SI, E, Result);
10954 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10955 assert(E->getType()->isIntegralOrEnumerationType() &&
10956 "Invalid evaluation result.");
10957 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10958 "Invalid evaluation result.");
10959 Result = APValue(APSInt(I));
10960 Result.getInt().setIsUnsigned(
10961 E->getType()->isUnsignedIntegerOrEnumerationType());
10962 return true;
10964 bool Success(const llvm::APInt &I, const Expr *E) {
10965 return Success(I, E, Result);
10968 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10969 assert(E->getType()->isIntegralOrEnumerationType() &&
10970 "Invalid evaluation result.");
10971 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10972 return true;
10974 bool Success(uint64_t Value, const Expr *E) {
10975 return Success(Value, E, Result);
10978 bool Success(CharUnits Size, const Expr *E) {
10979 return Success(Size.getQuantity(), E);
10982 bool Success(const APValue &V, const Expr *E) {
10983 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10984 Result = V;
10985 return true;
10987 return Success(V.getInt(), E);
10990 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10992 //===--------------------------------------------------------------------===//
10993 // Visitor Methods
10994 //===--------------------------------------------------------------------===//
10996 bool VisitIntegerLiteral(const IntegerLiteral *E) {
10997 return Success(E->getValue(), E);
10999 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11000 return Success(E->getValue(), E);
11003 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11004 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11005 if (CheckReferencedDecl(E, E->getDecl()))
11006 return true;
11008 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11010 bool VisitMemberExpr(const MemberExpr *E) {
11011 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11012 VisitIgnoredBaseExpression(E->getBase());
11013 return true;
11016 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11019 bool VisitCallExpr(const CallExpr *E);
11020 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11021 bool VisitBinaryOperator(const BinaryOperator *E);
11022 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11023 bool VisitUnaryOperator(const UnaryOperator *E);
11025 bool VisitCastExpr(const CastExpr* E);
11026 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11028 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11029 return Success(E->getValue(), E);
11032 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11033 return Success(E->getValue(), E);
11036 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11037 if (Info.ArrayInitIndex == uint64_t(-1)) {
11038 // We were asked to evaluate this subexpression independent of the
11039 // enclosing ArrayInitLoopExpr. We can't do that.
11040 Info.FFDiag(E);
11041 return false;
11043 return Success(Info.ArrayInitIndex, E);
11046 // Note, GNU defines __null as an integer, not a pointer.
11047 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11048 return ZeroInitialization(E);
11051 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11052 return Success(E->getValue(), E);
11055 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11056 return Success(E->getValue(), E);
11059 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11060 return Success(E->getValue(), E);
11063 bool VisitUnaryReal(const UnaryOperator *E);
11064 bool VisitUnaryImag(const UnaryOperator *E);
11066 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11067 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11068 bool VisitSourceLocExpr(const SourceLocExpr *E);
11069 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11070 bool VisitRequiresExpr(const RequiresExpr *E);
11071 // FIXME: Missing: array subscript of vector, member of vector
11074 class FixedPointExprEvaluator
11075 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11076 APValue &Result;
11078 public:
11079 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11080 : ExprEvaluatorBaseTy(info), Result(result) {}
11082 bool Success(const llvm::APInt &I, const Expr *E) {
11083 return Success(
11084 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11087 bool Success(uint64_t Value, const Expr *E) {
11088 return Success(
11089 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11092 bool Success(const APValue &V, const Expr *E) {
11093 return Success(V.getFixedPoint(), E);
11096 bool Success(const APFixedPoint &V, const Expr *E) {
11097 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11098 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11099 "Invalid evaluation result.");
11100 Result = APValue(V);
11101 return true;
11104 //===--------------------------------------------------------------------===//
11105 // Visitor Methods
11106 //===--------------------------------------------------------------------===//
11108 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11109 return Success(E->getValue(), E);
11112 bool VisitCastExpr(const CastExpr *E);
11113 bool VisitUnaryOperator(const UnaryOperator *E);
11114 bool VisitBinaryOperator(const BinaryOperator *E);
11116 } // end anonymous namespace
11118 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11119 /// produce either the integer value or a pointer.
11121 /// GCC has a heinous extension which folds casts between pointer types and
11122 /// pointer-sized integral types. We support this by allowing the evaluation of
11123 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11124 /// Some simple arithmetic on such values is supported (they are treated much
11125 /// like char*).
11126 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11127 EvalInfo &Info) {
11128 assert(!E->isValueDependent());
11129 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11130 return IntExprEvaluator(Info, Result).Visit(E);
11133 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11134 assert(!E->isValueDependent());
11135 APValue Val;
11136 if (!EvaluateIntegerOrLValue(E, Val, Info))
11137 return false;
11138 if (!Val.isInt()) {
11139 // FIXME: It would be better to produce the diagnostic for casting
11140 // a pointer to an integer.
11141 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11142 return false;
11144 Result = Val.getInt();
11145 return true;
11148 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11149 APValue Evaluated = E->EvaluateInContext(
11150 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11151 return Success(Evaluated, E);
11154 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11155 EvalInfo &Info) {
11156 assert(!E->isValueDependent());
11157 if (E->getType()->isFixedPointType()) {
11158 APValue Val;
11159 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11160 return false;
11161 if (!Val.isFixedPoint())
11162 return false;
11164 Result = Val.getFixedPoint();
11165 return true;
11167 return false;
11170 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11171 EvalInfo &Info) {
11172 assert(!E->isValueDependent());
11173 if (E->getType()->isIntegerType()) {
11174 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11175 APSInt Val;
11176 if (!EvaluateInteger(E, Val, Info))
11177 return false;
11178 Result = APFixedPoint(Val, FXSema);
11179 return true;
11180 } else if (E->getType()->isFixedPointType()) {
11181 return EvaluateFixedPoint(E, Result, Info);
11183 return false;
11186 /// Check whether the given declaration can be directly converted to an integral
11187 /// rvalue. If not, no diagnostic is produced; there are other things we can
11188 /// try.
11189 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11190 // Enums are integer constant exprs.
11191 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11192 // Check for signedness/width mismatches between E type and ECD value.
11193 bool SameSign = (ECD->getInitVal().isSigned()
11194 == E->getType()->isSignedIntegerOrEnumerationType());
11195 bool SameWidth = (ECD->getInitVal().getBitWidth()
11196 == Info.Ctx.getIntWidth(E->getType()));
11197 if (SameSign && SameWidth)
11198 return Success(ECD->getInitVal(), E);
11199 else {
11200 // Get rid of mismatch (otherwise Success assertions will fail)
11201 // by computing a new value matching the type of E.
11202 llvm::APSInt Val = ECD->getInitVal();
11203 if (!SameSign)
11204 Val.setIsSigned(!ECD->getInitVal().isSigned());
11205 if (!SameWidth)
11206 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11207 return Success(Val, E);
11210 return false;
11213 /// Values returned by __builtin_classify_type, chosen to match the values
11214 /// produced by GCC's builtin.
11215 enum class GCCTypeClass {
11216 None = -1,
11217 Void = 0,
11218 Integer = 1,
11219 // GCC reserves 2 for character types, but instead classifies them as
11220 // integers.
11221 Enum = 3,
11222 Bool = 4,
11223 Pointer = 5,
11224 // GCC reserves 6 for references, but appears to never use it (because
11225 // expressions never have reference type, presumably).
11226 PointerToDataMember = 7,
11227 RealFloat = 8,
11228 Complex = 9,
11229 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11230 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11231 // GCC claims to reserve 11 for pointers to member functions, but *actually*
11232 // uses 12 for that purpose, same as for a class or struct. Maybe it
11233 // internally implements a pointer to member as a struct? Who knows.
11234 PointerToMemberFunction = 12, // Not a bug, see above.
11235 ClassOrStruct = 12,
11236 Union = 13,
11237 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11238 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11239 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11240 // literals.
11243 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11244 /// as GCC.
11245 static GCCTypeClass
11246 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11247 assert(!T->isDependentType() && "unexpected dependent type");
11249 QualType CanTy = T.getCanonicalType();
11250 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11252 switch (CanTy->getTypeClass()) {
11253 #define TYPE(ID, BASE)
11254 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11255 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11256 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11257 #include "clang/AST/TypeNodes.inc"
11258 case Type::Auto:
11259 case Type::DeducedTemplateSpecialization:
11260 llvm_unreachable("unexpected non-canonical or dependent type");
11262 case Type::Builtin:
11263 switch (BT->getKind()) {
11264 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11265 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11266 case BuiltinType::ID: return GCCTypeClass::Integer;
11267 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11268 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11269 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11270 case BuiltinType::ID: break;
11271 #include "clang/AST/BuiltinTypes.def"
11272 case BuiltinType::Void:
11273 return GCCTypeClass::Void;
11275 case BuiltinType::Bool:
11276 return GCCTypeClass::Bool;
11278 case BuiltinType::Char_U:
11279 case BuiltinType::UChar:
11280 case BuiltinType::WChar_U:
11281 case BuiltinType::Char8:
11282 case BuiltinType::Char16:
11283 case BuiltinType::Char32:
11284 case BuiltinType::UShort:
11285 case BuiltinType::UInt:
11286 case BuiltinType::ULong:
11287 case BuiltinType::ULongLong:
11288 case BuiltinType::UInt128:
11289 return GCCTypeClass::Integer;
11291 case BuiltinType::UShortAccum:
11292 case BuiltinType::UAccum:
11293 case BuiltinType::ULongAccum:
11294 case BuiltinType::UShortFract:
11295 case BuiltinType::UFract:
11296 case BuiltinType::ULongFract:
11297 case BuiltinType::SatUShortAccum:
11298 case BuiltinType::SatUAccum:
11299 case BuiltinType::SatULongAccum:
11300 case BuiltinType::SatUShortFract:
11301 case BuiltinType::SatUFract:
11302 case BuiltinType::SatULongFract:
11303 return GCCTypeClass::None;
11305 case BuiltinType::NullPtr:
11307 case BuiltinType::ObjCId:
11308 case BuiltinType::ObjCClass:
11309 case BuiltinType::ObjCSel:
11310 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11311 case BuiltinType::Id:
11312 #include "clang/Basic/OpenCLImageTypes.def"
11313 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11314 case BuiltinType::Id:
11315 #include "clang/Basic/OpenCLExtensionTypes.def"
11316 case BuiltinType::OCLSampler:
11317 case BuiltinType::OCLEvent:
11318 case BuiltinType::OCLClkEvent:
11319 case BuiltinType::OCLQueue:
11320 case BuiltinType::OCLReserveID:
11321 #define SVE_TYPE(Name, Id, SingletonId) \
11322 case BuiltinType::Id:
11323 #include "clang/Basic/AArch64SVEACLETypes.def"
11324 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11325 case BuiltinType::Id:
11326 #include "clang/Basic/PPCTypes.def"
11327 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11328 #include "clang/Basic/RISCVVTypes.def"
11329 return GCCTypeClass::None;
11331 case BuiltinType::Dependent:
11332 llvm_unreachable("unexpected dependent type");
11334 llvm_unreachable("unexpected placeholder type");
11336 case Type::Enum:
11337 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11339 case Type::Pointer:
11340 case Type::ConstantArray:
11341 case Type::VariableArray:
11342 case Type::IncompleteArray:
11343 case Type::FunctionNoProto:
11344 case Type::FunctionProto:
11345 return GCCTypeClass::Pointer;
11347 case Type::MemberPointer:
11348 return CanTy->isMemberDataPointerType()
11349 ? GCCTypeClass::PointerToDataMember
11350 : GCCTypeClass::PointerToMemberFunction;
11352 case Type::Complex:
11353 return GCCTypeClass::Complex;
11355 case Type::Record:
11356 return CanTy->isUnionType() ? GCCTypeClass::Union
11357 : GCCTypeClass::ClassOrStruct;
11359 case Type::Atomic:
11360 // GCC classifies _Atomic T the same as T.
11361 return EvaluateBuiltinClassifyType(
11362 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11364 case Type::BlockPointer:
11365 case Type::Vector:
11366 case Type::ExtVector:
11367 case Type::ConstantMatrix:
11368 case Type::ObjCObject:
11369 case Type::ObjCInterface:
11370 case Type::ObjCObjectPointer:
11371 case Type::Pipe:
11372 case Type::BitInt:
11373 // GCC classifies vectors as None. We follow its lead and classify all
11374 // other types that don't fit into the regular classification the same way.
11375 return GCCTypeClass::None;
11377 case Type::LValueReference:
11378 case Type::RValueReference:
11379 llvm_unreachable("invalid type for expression");
11382 llvm_unreachable("unexpected type class");
11385 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11386 /// as GCC.
11387 static GCCTypeClass
11388 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11389 // If no argument was supplied, default to None. This isn't
11390 // ideal, however it is what gcc does.
11391 if (E->getNumArgs() == 0)
11392 return GCCTypeClass::None;
11394 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11395 // being an ICE, but still folds it to a constant using the type of the first
11396 // argument.
11397 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11400 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11401 /// __builtin_constant_p when applied to the given pointer.
11403 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11404 /// or it points to the first character of a string literal.
11405 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11406 APValue::LValueBase Base = LV.getLValueBase();
11407 if (Base.isNull()) {
11408 // A null base is acceptable.
11409 return true;
11410 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11411 if (!isa<StringLiteral>(E))
11412 return false;
11413 return LV.getLValueOffset().isZero();
11414 } else if (Base.is<TypeInfoLValue>()) {
11415 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11416 // evaluate to true.
11417 return true;
11418 } else {
11419 // Any other base is not constant enough for GCC.
11420 return false;
11424 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11425 /// GCC as we can manage.
11426 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11427 // This evaluation is not permitted to have side-effects, so evaluate it in
11428 // a speculative evaluation context.
11429 SpeculativeEvaluationRAII SpeculativeEval(Info);
11431 // Constant-folding is always enabled for the operand of __builtin_constant_p
11432 // (even when the enclosing evaluation context otherwise requires a strict
11433 // language-specific constant expression).
11434 FoldConstant Fold(Info, true);
11436 QualType ArgType = Arg->getType();
11438 // __builtin_constant_p always has one operand. The rules which gcc follows
11439 // are not precisely documented, but are as follows:
11441 // - If the operand is of integral, floating, complex or enumeration type,
11442 // and can be folded to a known value of that type, it returns 1.
11443 // - If the operand can be folded to a pointer to the first character
11444 // of a string literal (or such a pointer cast to an integral type)
11445 // or to a null pointer or an integer cast to a pointer, it returns 1.
11447 // Otherwise, it returns 0.
11449 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11450 // its support for this did not work prior to GCC 9 and is not yet well
11451 // understood.
11452 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11453 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11454 ArgType->isNullPtrType()) {
11455 APValue V;
11456 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11457 Fold.keepDiagnostics();
11458 return false;
11461 // For a pointer (possibly cast to integer), there are special rules.
11462 if (V.getKind() == APValue::LValue)
11463 return EvaluateBuiltinConstantPForLValue(V);
11465 // Otherwise, any constant value is good enough.
11466 return V.hasValue();
11469 // Anything else isn't considered to be sufficiently constant.
11470 return false;
11473 /// Retrieves the "underlying object type" of the given expression,
11474 /// as used by __builtin_object_size.
11475 static QualType getObjectType(APValue::LValueBase B) {
11476 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11477 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11478 return VD->getType();
11479 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11480 if (isa<CompoundLiteralExpr>(E))
11481 return E->getType();
11482 } else if (B.is<TypeInfoLValue>()) {
11483 return B.getTypeInfoType();
11484 } else if (B.is<DynamicAllocLValue>()) {
11485 return B.getDynamicAllocType();
11488 return QualType();
11491 /// A more selective version of E->IgnoreParenCasts for
11492 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11493 /// to change the type of E.
11494 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11496 /// Always returns an RValue with a pointer representation.
11497 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11498 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11500 auto *NoParens = E->IgnoreParens();
11501 auto *Cast = dyn_cast<CastExpr>(NoParens);
11502 if (Cast == nullptr)
11503 return NoParens;
11505 // We only conservatively allow a few kinds of casts, because this code is
11506 // inherently a simple solution that seeks to support the common case.
11507 auto CastKind = Cast->getCastKind();
11508 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11509 CastKind != CK_AddressSpaceConversion)
11510 return NoParens;
11512 auto *SubExpr = Cast->getSubExpr();
11513 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11514 return NoParens;
11515 return ignorePointerCastsAndParens(SubExpr);
11518 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11519 /// record layout. e.g.
11520 /// struct { struct { int a, b; } fst, snd; } obj;
11521 /// obj.fst // no
11522 /// obj.snd // yes
11523 /// obj.fst.a // no
11524 /// obj.fst.b // no
11525 /// obj.snd.a // no
11526 /// obj.snd.b // yes
11528 /// Please note: this function is specialized for how __builtin_object_size
11529 /// views "objects".
11531 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11532 /// correct result, it will always return true.
11533 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11534 assert(!LVal.Designator.Invalid);
11536 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11537 const RecordDecl *Parent = FD->getParent();
11538 Invalid = Parent->isInvalidDecl();
11539 if (Invalid || Parent->isUnion())
11540 return true;
11541 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11542 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11545 auto &Base = LVal.getLValueBase();
11546 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11547 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11548 bool Invalid;
11549 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11550 return Invalid;
11551 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11552 for (auto *FD : IFD->chain()) {
11553 bool Invalid;
11554 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11555 return Invalid;
11560 unsigned I = 0;
11561 QualType BaseType = getType(Base);
11562 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11563 // If we don't know the array bound, conservatively assume we're looking at
11564 // the final array element.
11565 ++I;
11566 if (BaseType->isIncompleteArrayType())
11567 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11568 else
11569 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11572 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11573 const auto &Entry = LVal.Designator.Entries[I];
11574 if (BaseType->isArrayType()) {
11575 // Because __builtin_object_size treats arrays as objects, we can ignore
11576 // the index iff this is the last array in the Designator.
11577 if (I + 1 == E)
11578 return true;
11579 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11580 uint64_t Index = Entry.getAsArrayIndex();
11581 if (Index + 1 != CAT->getSize())
11582 return false;
11583 BaseType = CAT->getElementType();
11584 } else if (BaseType->isAnyComplexType()) {
11585 const auto *CT = BaseType->castAs<ComplexType>();
11586 uint64_t Index = Entry.getAsArrayIndex();
11587 if (Index != 1)
11588 return false;
11589 BaseType = CT->getElementType();
11590 } else if (auto *FD = getAsField(Entry)) {
11591 bool Invalid;
11592 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11593 return Invalid;
11594 BaseType = FD->getType();
11595 } else {
11596 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11597 return false;
11600 return true;
11603 /// Tests to see if the LValue has a user-specified designator (that isn't
11604 /// necessarily valid). Note that this always returns 'true' if the LValue has
11605 /// an unsized array as its first designator entry, because there's currently no
11606 /// way to tell if the user typed *foo or foo[0].
11607 static bool refersToCompleteObject(const LValue &LVal) {
11608 if (LVal.Designator.Invalid)
11609 return false;
11611 if (!LVal.Designator.Entries.empty())
11612 return LVal.Designator.isMostDerivedAnUnsizedArray();
11614 if (!LVal.InvalidBase)
11615 return true;
11617 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11618 // the LValueBase.
11619 const auto *E = LVal.Base.dyn_cast<const Expr *>();
11620 return !E || !isa<MemberExpr>(E);
11623 /// Attempts to detect a user writing into a piece of memory that's impossible
11624 /// to figure out the size of by just using types.
11625 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11626 const SubobjectDesignator &Designator = LVal.Designator;
11627 // Notes:
11628 // - Users can only write off of the end when we have an invalid base. Invalid
11629 // bases imply we don't know where the memory came from.
11630 // - We used to be a bit more aggressive here; we'd only be conservative if
11631 // the array at the end was flexible, or if it had 0 or 1 elements. This
11632 // broke some common standard library extensions (PR30346), but was
11633 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11634 // with some sort of list. OTOH, it seems that GCC is always
11635 // conservative with the last element in structs (if it's an array), so our
11636 // current behavior is more compatible than an explicit list approach would
11637 // be.
11638 auto isFlexibleArrayMember = [&] {
11639 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11640 FAMKind StrictFlexArraysLevel =
11641 Ctx.getLangOpts().getStrictFlexArraysLevel();
11643 if (Designator.isMostDerivedAnUnsizedArray())
11644 return true;
11646 if (StrictFlexArraysLevel == FAMKind::Default)
11647 return true;
11649 if (Designator.getMostDerivedArraySize() == 0 &&
11650 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11651 return true;
11653 if (Designator.getMostDerivedArraySize() == 1 &&
11654 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11655 return true;
11657 return false;
11660 return LVal.InvalidBase &&
11661 Designator.Entries.size() == Designator.MostDerivedPathLength &&
11662 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11663 isDesignatorAtObjectEnd(Ctx, LVal);
11666 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11667 /// Fails if the conversion would cause loss of precision.
11668 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11669 CharUnits &Result) {
11670 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11671 if (Int.ugt(CharUnitsMax))
11672 return false;
11673 Result = CharUnits::fromQuantity(Int.getZExtValue());
11674 return true;
11677 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11678 /// determine how many bytes exist from the beginning of the object to either
11679 /// the end of the current subobject, or the end of the object itself, depending
11680 /// on what the LValue looks like + the value of Type.
11682 /// If this returns false, the value of Result is undefined.
11683 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11684 unsigned Type, const LValue &LVal,
11685 CharUnits &EndOffset) {
11686 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11688 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11689 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11690 return false;
11691 return HandleSizeof(Info, ExprLoc, Ty, Result);
11694 // We want to evaluate the size of the entire object. This is a valid fallback
11695 // for when Type=1 and the designator is invalid, because we're asked for an
11696 // upper-bound.
11697 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11698 // Type=3 wants a lower bound, so we can't fall back to this.
11699 if (Type == 3 && !DetermineForCompleteObject)
11700 return false;
11702 llvm::APInt APEndOffset;
11703 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11704 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11705 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11707 if (LVal.InvalidBase)
11708 return false;
11710 QualType BaseTy = getObjectType(LVal.getLValueBase());
11711 return CheckedHandleSizeof(BaseTy, EndOffset);
11714 // We want to evaluate the size of a subobject.
11715 const SubobjectDesignator &Designator = LVal.Designator;
11717 // The following is a moderately common idiom in C:
11719 // struct Foo { int a; char c[1]; };
11720 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11721 // strcpy(&F->c[0], Bar);
11723 // In order to not break too much legacy code, we need to support it.
11724 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11725 // If we can resolve this to an alloc_size call, we can hand that back,
11726 // because we know for certain how many bytes there are to write to.
11727 llvm::APInt APEndOffset;
11728 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11729 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11730 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11732 // If we cannot determine the size of the initial allocation, then we can't
11733 // given an accurate upper-bound. However, we are still able to give
11734 // conservative lower-bounds for Type=3.
11735 if (Type == 1)
11736 return false;
11739 CharUnits BytesPerElem;
11740 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11741 return false;
11743 // According to the GCC documentation, we want the size of the subobject
11744 // denoted by the pointer. But that's not quite right -- what we actually
11745 // want is the size of the immediately-enclosing array, if there is one.
11746 int64_t ElemsRemaining;
11747 if (Designator.MostDerivedIsArrayElement &&
11748 Designator.Entries.size() == Designator.MostDerivedPathLength) {
11749 uint64_t ArraySize = Designator.getMostDerivedArraySize();
11750 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11751 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11752 } else {
11753 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11756 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11757 return true;
11760 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11761 /// returns true and stores the result in @p Size.
11763 /// If @p WasError is non-null, this will report whether the failure to evaluate
11764 /// is to be treated as an Error in IntExprEvaluator.
11765 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11766 EvalInfo &Info, uint64_t &Size) {
11767 // Determine the denoted object.
11768 LValue LVal;
11770 // The operand of __builtin_object_size is never evaluated for side-effects.
11771 // If there are any, but we can determine the pointed-to object anyway, then
11772 // ignore the side-effects.
11773 SpeculativeEvaluationRAII SpeculativeEval(Info);
11774 IgnoreSideEffectsRAII Fold(Info);
11776 if (E->isGLValue()) {
11777 // It's possible for us to be given GLValues if we're called via
11778 // Expr::tryEvaluateObjectSize.
11779 APValue RVal;
11780 if (!EvaluateAsRValue(Info, E, RVal))
11781 return false;
11782 LVal.setFrom(Info.Ctx, RVal);
11783 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11784 /*InvalidBaseOK=*/true))
11785 return false;
11788 // If we point to before the start of the object, there are no accessible
11789 // bytes.
11790 if (LVal.getLValueOffset().isNegative()) {
11791 Size = 0;
11792 return true;
11795 CharUnits EndOffset;
11796 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11797 return false;
11799 // If we've fallen outside of the end offset, just pretend there's nothing to
11800 // write to/read from.
11801 if (EndOffset <= LVal.getLValueOffset())
11802 Size = 0;
11803 else
11804 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11805 return true;
11808 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11809 if (!IsConstantEvaluatedBuiltinCall(E))
11810 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11811 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11814 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11815 APValue &Val, APSInt &Alignment) {
11816 QualType SrcTy = E->getArg(0)->getType();
11817 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11818 return false;
11819 // Even though we are evaluating integer expressions we could get a pointer
11820 // argument for the __builtin_is_aligned() case.
11821 if (SrcTy->isPointerType()) {
11822 LValue Ptr;
11823 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11824 return false;
11825 Ptr.moveInto(Val);
11826 } else if (!SrcTy->isIntegralOrEnumerationType()) {
11827 Info.FFDiag(E->getArg(0));
11828 return false;
11829 } else {
11830 APSInt SrcInt;
11831 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11832 return false;
11833 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11834 "Bit widths must be the same");
11835 Val = APValue(SrcInt);
11837 assert(Val.hasValue());
11838 return true;
11841 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11842 unsigned BuiltinOp) {
11843 switch (BuiltinOp) {
11844 default:
11845 return false;
11847 case Builtin::BI__builtin_dynamic_object_size:
11848 case Builtin::BI__builtin_object_size: {
11849 // The type was checked when we built the expression.
11850 unsigned Type =
11851 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11852 assert(Type <= 3 && "unexpected type");
11854 uint64_t Size;
11855 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11856 return Success(Size, E);
11858 if (E->getArg(0)->HasSideEffects(Info.Ctx))
11859 return Success((Type & 2) ? 0 : -1, E);
11861 // Expression had no side effects, but we couldn't statically determine the
11862 // size of the referenced object.
11863 switch (Info.EvalMode) {
11864 case EvalInfo::EM_ConstantExpression:
11865 case EvalInfo::EM_ConstantFold:
11866 case EvalInfo::EM_IgnoreSideEffects:
11867 // Leave it to IR generation.
11868 return Error(E);
11869 case EvalInfo::EM_ConstantExpressionUnevaluated:
11870 // Reduce it to a constant now.
11871 return Success((Type & 2) ? 0 : -1, E);
11874 llvm_unreachable("unexpected EvalMode");
11877 case Builtin::BI__builtin_os_log_format_buffer_size: {
11878 analyze_os_log::OSLogBufferLayout Layout;
11879 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11880 return Success(Layout.size().getQuantity(), E);
11883 case Builtin::BI__builtin_is_aligned: {
11884 APValue Src;
11885 APSInt Alignment;
11886 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11887 return false;
11888 if (Src.isLValue()) {
11889 // If we evaluated a pointer, check the minimum known alignment.
11890 LValue Ptr;
11891 Ptr.setFrom(Info.Ctx, Src);
11892 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11893 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11894 // We can return true if the known alignment at the computed offset is
11895 // greater than the requested alignment.
11896 assert(PtrAlign.isPowerOfTwo());
11897 assert(Alignment.isPowerOf2());
11898 if (PtrAlign.getQuantity() >= Alignment)
11899 return Success(1, E);
11900 // If the alignment is not known to be sufficient, some cases could still
11901 // be aligned at run time. However, if the requested alignment is less or
11902 // equal to the base alignment and the offset is not aligned, we know that
11903 // the run-time value can never be aligned.
11904 if (BaseAlignment.getQuantity() >= Alignment &&
11905 PtrAlign.getQuantity() < Alignment)
11906 return Success(0, E);
11907 // Otherwise we can't infer whether the value is sufficiently aligned.
11908 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11909 // in cases where we can't fully evaluate the pointer.
11910 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11911 << Alignment;
11912 return false;
11914 assert(Src.isInt());
11915 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11917 case Builtin::BI__builtin_align_up: {
11918 APValue Src;
11919 APSInt Alignment;
11920 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11921 return false;
11922 if (!Src.isInt())
11923 return Error(E);
11924 APSInt AlignedVal =
11925 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11926 Src.getInt().isUnsigned());
11927 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11928 return Success(AlignedVal, E);
11930 case Builtin::BI__builtin_align_down: {
11931 APValue Src;
11932 APSInt Alignment;
11933 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11934 return false;
11935 if (!Src.isInt())
11936 return Error(E);
11937 APSInt AlignedVal =
11938 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11939 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11940 return Success(AlignedVal, E);
11943 case Builtin::BI__builtin_bitreverse8:
11944 case Builtin::BI__builtin_bitreverse16:
11945 case Builtin::BI__builtin_bitreverse32:
11946 case Builtin::BI__builtin_bitreverse64: {
11947 APSInt Val;
11948 if (!EvaluateInteger(E->getArg(0), Val, Info))
11949 return false;
11951 return Success(Val.reverseBits(), E);
11954 case Builtin::BI__builtin_bswap16:
11955 case Builtin::BI__builtin_bswap32:
11956 case Builtin::BI__builtin_bswap64: {
11957 APSInt Val;
11958 if (!EvaluateInteger(E->getArg(0), Val, Info))
11959 return false;
11961 return Success(Val.byteSwap(), E);
11964 case Builtin::BI__builtin_classify_type:
11965 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11967 case Builtin::BI__builtin_clrsb:
11968 case Builtin::BI__builtin_clrsbl:
11969 case Builtin::BI__builtin_clrsbll: {
11970 APSInt Val;
11971 if (!EvaluateInteger(E->getArg(0), Val, Info))
11972 return false;
11974 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11977 case Builtin::BI__builtin_clz:
11978 case Builtin::BI__builtin_clzl:
11979 case Builtin::BI__builtin_clzll:
11980 case Builtin::BI__builtin_clzs: {
11981 APSInt Val;
11982 if (!EvaluateInteger(E->getArg(0), Val, Info))
11983 return false;
11984 if (!Val)
11985 return Error(E);
11987 return Success(Val.countLeadingZeros(), E);
11990 case Builtin::BI__builtin_constant_p: {
11991 const Expr *Arg = E->getArg(0);
11992 if (EvaluateBuiltinConstantP(Info, Arg))
11993 return Success(true, E);
11994 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11995 // Outside a constant context, eagerly evaluate to false in the presence
11996 // of side-effects in order to avoid -Wunsequenced false-positives in
11997 // a branch on __builtin_constant_p(expr).
11998 return Success(false, E);
12000 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12001 return false;
12004 case Builtin::BI__builtin_is_constant_evaluated: {
12005 const auto *Callee = Info.CurrentCall->getCallee();
12006 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12007 (Info.CallStackDepth == 1 ||
12008 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12009 Callee->getIdentifier() &&
12010 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12011 // FIXME: Find a better way to avoid duplicated diagnostics.
12012 if (Info.EvalStatus.Diag)
12013 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12014 : Info.CurrentCall->CallLoc,
12015 diag::warn_is_constant_evaluated_always_true_constexpr)
12016 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12017 : "std::is_constant_evaluated");
12020 return Success(Info.InConstantContext, E);
12023 case Builtin::BI__builtin_ctz:
12024 case Builtin::BI__builtin_ctzl:
12025 case Builtin::BI__builtin_ctzll:
12026 case Builtin::BI__builtin_ctzs: {
12027 APSInt Val;
12028 if (!EvaluateInteger(E->getArg(0), Val, Info))
12029 return false;
12030 if (!Val)
12031 return Error(E);
12033 return Success(Val.countTrailingZeros(), E);
12036 case Builtin::BI__builtin_eh_return_data_regno: {
12037 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12038 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12039 return Success(Operand, E);
12042 case Builtin::BI__builtin_expect:
12043 case Builtin::BI__builtin_expect_with_probability:
12044 return Visit(E->getArg(0));
12046 case Builtin::BI__builtin_ffs:
12047 case Builtin::BI__builtin_ffsl:
12048 case Builtin::BI__builtin_ffsll: {
12049 APSInt Val;
12050 if (!EvaluateInteger(E->getArg(0), Val, Info))
12051 return false;
12053 unsigned N = Val.countTrailingZeros();
12054 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12057 case Builtin::BI__builtin_fpclassify: {
12058 APFloat Val(0.0);
12059 if (!EvaluateFloat(E->getArg(5), Val, Info))
12060 return false;
12061 unsigned Arg;
12062 switch (Val.getCategory()) {
12063 case APFloat::fcNaN: Arg = 0; break;
12064 case APFloat::fcInfinity: Arg = 1; break;
12065 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12066 case APFloat::fcZero: Arg = 4; break;
12068 return Visit(E->getArg(Arg));
12071 case Builtin::BI__builtin_isinf_sign: {
12072 APFloat Val(0.0);
12073 return EvaluateFloat(E->getArg(0), Val, Info) &&
12074 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12077 case Builtin::BI__builtin_isinf: {
12078 APFloat Val(0.0);
12079 return EvaluateFloat(E->getArg(0), Val, Info) &&
12080 Success(Val.isInfinity() ? 1 : 0, E);
12083 case Builtin::BI__builtin_isfinite: {
12084 APFloat Val(0.0);
12085 return EvaluateFloat(E->getArg(0), Val, Info) &&
12086 Success(Val.isFinite() ? 1 : 0, E);
12089 case Builtin::BI__builtin_isnan: {
12090 APFloat Val(0.0);
12091 return EvaluateFloat(E->getArg(0), Val, Info) &&
12092 Success(Val.isNaN() ? 1 : 0, E);
12095 case Builtin::BI__builtin_isnormal: {
12096 APFloat Val(0.0);
12097 return EvaluateFloat(E->getArg(0), Val, Info) &&
12098 Success(Val.isNormal() ? 1 : 0, E);
12101 case Builtin::BI__builtin_parity:
12102 case Builtin::BI__builtin_parityl:
12103 case Builtin::BI__builtin_parityll: {
12104 APSInt Val;
12105 if (!EvaluateInteger(E->getArg(0), Val, Info))
12106 return false;
12108 return Success(Val.countPopulation() % 2, E);
12111 case Builtin::BI__builtin_popcount:
12112 case Builtin::BI__builtin_popcountl:
12113 case Builtin::BI__builtin_popcountll: {
12114 APSInt Val;
12115 if (!EvaluateInteger(E->getArg(0), Val, Info))
12116 return false;
12118 return Success(Val.countPopulation(), E);
12121 case Builtin::BI__builtin_rotateleft8:
12122 case Builtin::BI__builtin_rotateleft16:
12123 case Builtin::BI__builtin_rotateleft32:
12124 case Builtin::BI__builtin_rotateleft64:
12125 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12126 case Builtin::BI_rotl16:
12127 case Builtin::BI_rotl:
12128 case Builtin::BI_lrotl:
12129 case Builtin::BI_rotl64: {
12130 APSInt Val, Amt;
12131 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12132 !EvaluateInteger(E->getArg(1), Amt, Info))
12133 return false;
12135 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12138 case Builtin::BI__builtin_rotateright8:
12139 case Builtin::BI__builtin_rotateright16:
12140 case Builtin::BI__builtin_rotateright32:
12141 case Builtin::BI__builtin_rotateright64:
12142 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12143 case Builtin::BI_rotr16:
12144 case Builtin::BI_rotr:
12145 case Builtin::BI_lrotr:
12146 case Builtin::BI_rotr64: {
12147 APSInt Val, Amt;
12148 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12149 !EvaluateInteger(E->getArg(1), Amt, Info))
12150 return false;
12152 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12155 case Builtin::BIstrlen:
12156 case Builtin::BIwcslen:
12157 // A call to strlen is not a constant expression.
12158 if (Info.getLangOpts().CPlusPlus11)
12159 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12160 << /*isConstexpr*/0 << /*isConstructor*/0
12161 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12162 else
12163 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12164 [[fallthrough]];
12165 case Builtin::BI__builtin_strlen:
12166 case Builtin::BI__builtin_wcslen: {
12167 // As an extension, we support __builtin_strlen() as a constant expression,
12168 // and support folding strlen() to a constant.
12169 uint64_t StrLen;
12170 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12171 return Success(StrLen, E);
12172 return false;
12175 case Builtin::BIstrcmp:
12176 case Builtin::BIwcscmp:
12177 case Builtin::BIstrncmp:
12178 case Builtin::BIwcsncmp:
12179 case Builtin::BImemcmp:
12180 case Builtin::BIbcmp:
12181 case Builtin::BIwmemcmp:
12182 // A call to strlen is not a constant expression.
12183 if (Info.getLangOpts().CPlusPlus11)
12184 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12185 << /*isConstexpr*/0 << /*isConstructor*/0
12186 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12187 else
12188 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12189 [[fallthrough]];
12190 case Builtin::BI__builtin_strcmp:
12191 case Builtin::BI__builtin_wcscmp:
12192 case Builtin::BI__builtin_strncmp:
12193 case Builtin::BI__builtin_wcsncmp:
12194 case Builtin::BI__builtin_memcmp:
12195 case Builtin::BI__builtin_bcmp:
12196 case Builtin::BI__builtin_wmemcmp: {
12197 LValue String1, String2;
12198 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12199 !EvaluatePointer(E->getArg(1), String2, Info))
12200 return false;
12202 uint64_t MaxLength = uint64_t(-1);
12203 if (BuiltinOp != Builtin::BIstrcmp &&
12204 BuiltinOp != Builtin::BIwcscmp &&
12205 BuiltinOp != Builtin::BI__builtin_strcmp &&
12206 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12207 APSInt N;
12208 if (!EvaluateInteger(E->getArg(2), N, Info))
12209 return false;
12210 MaxLength = N.getExtValue();
12213 // Empty substrings compare equal by definition.
12214 if (MaxLength == 0u)
12215 return Success(0, E);
12217 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12218 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12219 String1.Designator.Invalid || String2.Designator.Invalid)
12220 return false;
12222 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12223 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12225 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12226 BuiltinOp == Builtin::BIbcmp ||
12227 BuiltinOp == Builtin::BI__builtin_memcmp ||
12228 BuiltinOp == Builtin::BI__builtin_bcmp;
12230 assert(IsRawByte ||
12231 (Info.Ctx.hasSameUnqualifiedType(
12232 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12233 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12235 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12236 // 'char8_t', but no other types.
12237 if (IsRawByte &&
12238 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12239 // FIXME: Consider using our bit_cast implementation to support this.
12240 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12241 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12242 << CharTy1 << CharTy2;
12243 return false;
12246 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12247 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12248 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12249 Char1.isInt() && Char2.isInt();
12251 const auto &AdvanceElems = [&] {
12252 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12253 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12256 bool StopAtNull =
12257 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12258 BuiltinOp != Builtin::BIwmemcmp &&
12259 BuiltinOp != Builtin::BI__builtin_memcmp &&
12260 BuiltinOp != Builtin::BI__builtin_bcmp &&
12261 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12262 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12263 BuiltinOp == Builtin::BIwcsncmp ||
12264 BuiltinOp == Builtin::BIwmemcmp ||
12265 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12266 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12267 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12269 for (; MaxLength; --MaxLength) {
12270 APValue Char1, Char2;
12271 if (!ReadCurElems(Char1, Char2))
12272 return false;
12273 if (Char1.getInt().ne(Char2.getInt())) {
12274 if (IsWide) // wmemcmp compares with wchar_t signedness.
12275 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12276 // memcmp always compares unsigned chars.
12277 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12279 if (StopAtNull && !Char1.getInt())
12280 return Success(0, E);
12281 assert(!(StopAtNull && !Char2.getInt()));
12282 if (!AdvanceElems())
12283 return false;
12285 // We hit the strncmp / memcmp limit.
12286 return Success(0, E);
12289 case Builtin::BI__atomic_always_lock_free:
12290 case Builtin::BI__atomic_is_lock_free:
12291 case Builtin::BI__c11_atomic_is_lock_free: {
12292 APSInt SizeVal;
12293 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12294 return false;
12296 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12297 // of two less than or equal to the maximum inline atomic width, we know it
12298 // is lock-free. If the size isn't a power of two, or greater than the
12299 // maximum alignment where we promote atomics, we know it is not lock-free
12300 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12301 // the answer can only be determined at runtime; for example, 16-byte
12302 // atomics have lock-free implementations on some, but not all,
12303 // x86-64 processors.
12305 // Check power-of-two.
12306 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12307 if (Size.isPowerOfTwo()) {
12308 // Check against inlining width.
12309 unsigned InlineWidthBits =
12310 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12311 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12312 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12313 Size == CharUnits::One() ||
12314 E->getArg(1)->isNullPointerConstant(Info.Ctx,
12315 Expr::NPC_NeverValueDependent))
12316 // OK, we will inline appropriately-aligned operations of this size,
12317 // and _Atomic(T) is appropriately-aligned.
12318 return Success(1, E);
12320 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12321 castAs<PointerType>()->getPointeeType();
12322 if (!PointeeType->isIncompleteType() &&
12323 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12324 // OK, we will inline operations on this object.
12325 return Success(1, E);
12330 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12331 Success(0, E) : Error(E);
12333 case Builtin::BI__builtin_add_overflow:
12334 case Builtin::BI__builtin_sub_overflow:
12335 case Builtin::BI__builtin_mul_overflow:
12336 case Builtin::BI__builtin_sadd_overflow:
12337 case Builtin::BI__builtin_uadd_overflow:
12338 case Builtin::BI__builtin_uaddl_overflow:
12339 case Builtin::BI__builtin_uaddll_overflow:
12340 case Builtin::BI__builtin_usub_overflow:
12341 case Builtin::BI__builtin_usubl_overflow:
12342 case Builtin::BI__builtin_usubll_overflow:
12343 case Builtin::BI__builtin_umul_overflow:
12344 case Builtin::BI__builtin_umull_overflow:
12345 case Builtin::BI__builtin_umulll_overflow:
12346 case Builtin::BI__builtin_saddl_overflow:
12347 case Builtin::BI__builtin_saddll_overflow:
12348 case Builtin::BI__builtin_ssub_overflow:
12349 case Builtin::BI__builtin_ssubl_overflow:
12350 case Builtin::BI__builtin_ssubll_overflow:
12351 case Builtin::BI__builtin_smul_overflow:
12352 case Builtin::BI__builtin_smull_overflow:
12353 case Builtin::BI__builtin_smulll_overflow: {
12354 LValue ResultLValue;
12355 APSInt LHS, RHS;
12357 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12358 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12359 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12360 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12361 return false;
12363 APSInt Result;
12364 bool DidOverflow = false;
12366 // If the types don't have to match, enlarge all 3 to the largest of them.
12367 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12368 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12369 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12370 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12371 ResultType->isSignedIntegerOrEnumerationType();
12372 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12373 ResultType->isSignedIntegerOrEnumerationType();
12374 uint64_t LHSSize = LHS.getBitWidth();
12375 uint64_t RHSSize = RHS.getBitWidth();
12376 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12377 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12379 // Add an additional bit if the signedness isn't uniformly agreed to. We
12380 // could do this ONLY if there is a signed and an unsigned that both have
12381 // MaxBits, but the code to check that is pretty nasty. The issue will be
12382 // caught in the shrink-to-result later anyway.
12383 if (IsSigned && !AllSigned)
12384 ++MaxBits;
12386 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12387 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12388 Result = APSInt(MaxBits, !IsSigned);
12391 // Find largest int.
12392 switch (BuiltinOp) {
12393 default:
12394 llvm_unreachable("Invalid value for BuiltinOp");
12395 case Builtin::BI__builtin_add_overflow:
12396 case Builtin::BI__builtin_sadd_overflow:
12397 case Builtin::BI__builtin_saddl_overflow:
12398 case Builtin::BI__builtin_saddll_overflow:
12399 case Builtin::BI__builtin_uadd_overflow:
12400 case Builtin::BI__builtin_uaddl_overflow:
12401 case Builtin::BI__builtin_uaddll_overflow:
12402 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12403 : LHS.uadd_ov(RHS, DidOverflow);
12404 break;
12405 case Builtin::BI__builtin_sub_overflow:
12406 case Builtin::BI__builtin_ssub_overflow:
12407 case Builtin::BI__builtin_ssubl_overflow:
12408 case Builtin::BI__builtin_ssubll_overflow:
12409 case Builtin::BI__builtin_usub_overflow:
12410 case Builtin::BI__builtin_usubl_overflow:
12411 case Builtin::BI__builtin_usubll_overflow:
12412 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12413 : LHS.usub_ov(RHS, DidOverflow);
12414 break;
12415 case Builtin::BI__builtin_mul_overflow:
12416 case Builtin::BI__builtin_smul_overflow:
12417 case Builtin::BI__builtin_smull_overflow:
12418 case Builtin::BI__builtin_smulll_overflow:
12419 case Builtin::BI__builtin_umul_overflow:
12420 case Builtin::BI__builtin_umull_overflow:
12421 case Builtin::BI__builtin_umulll_overflow:
12422 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12423 : LHS.umul_ov(RHS, DidOverflow);
12424 break;
12427 // In the case where multiple sizes are allowed, truncate and see if
12428 // the values are the same.
12429 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12430 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12431 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12432 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12433 // since it will give us the behavior of a TruncOrSelf in the case where
12434 // its parameter <= its size. We previously set Result to be at least the
12435 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12436 // will work exactly like TruncOrSelf.
12437 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12438 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12440 if (!APSInt::isSameValue(Temp, Result))
12441 DidOverflow = true;
12442 Result = Temp;
12445 APValue APV{Result};
12446 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12447 return false;
12448 return Success(DidOverflow, E);
12453 /// Determine whether this is a pointer past the end of the complete
12454 /// object referred to by the lvalue.
12455 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12456 const LValue &LV) {
12457 // A null pointer can be viewed as being "past the end" but we don't
12458 // choose to look at it that way here.
12459 if (!LV.getLValueBase())
12460 return false;
12462 // If the designator is valid and refers to a subobject, we're not pointing
12463 // past the end.
12464 if (!LV.getLValueDesignator().Invalid &&
12465 !LV.getLValueDesignator().isOnePastTheEnd())
12466 return false;
12468 // A pointer to an incomplete type might be past-the-end if the type's size is
12469 // zero. We cannot tell because the type is incomplete.
12470 QualType Ty = getType(LV.getLValueBase());
12471 if (Ty->isIncompleteType())
12472 return true;
12474 // We're a past-the-end pointer if we point to the byte after the object,
12475 // no matter what our type or path is.
12476 auto Size = Ctx.getTypeSizeInChars(Ty);
12477 return LV.getLValueOffset() == Size;
12480 namespace {
12482 /// Data recursive integer evaluator of certain binary operators.
12484 /// We use a data recursive algorithm for binary operators so that we are able
12485 /// to handle extreme cases of chained binary operators without causing stack
12486 /// overflow.
12487 class DataRecursiveIntBinOpEvaluator {
12488 struct EvalResult {
12489 APValue Val;
12490 bool Failed;
12492 EvalResult() : Failed(false) { }
12494 void swap(EvalResult &RHS) {
12495 Val.swap(RHS.Val);
12496 Failed = RHS.Failed;
12497 RHS.Failed = false;
12501 struct Job {
12502 const Expr *E;
12503 EvalResult LHSResult; // meaningful only for binary operator expression.
12504 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12506 Job() = default;
12507 Job(Job &&) = default;
12509 void startSpeculativeEval(EvalInfo &Info) {
12510 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12513 private:
12514 SpeculativeEvaluationRAII SpecEvalRAII;
12517 SmallVector<Job, 16> Queue;
12519 IntExprEvaluator &IntEval;
12520 EvalInfo &Info;
12521 APValue &FinalResult;
12523 public:
12524 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12525 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12527 /// True if \param E is a binary operator that we are going to handle
12528 /// data recursively.
12529 /// We handle binary operators that are comma, logical, or that have operands
12530 /// with integral or enumeration type.
12531 static bool shouldEnqueue(const BinaryOperator *E) {
12532 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12533 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12534 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12535 E->getRHS()->getType()->isIntegralOrEnumerationType());
12538 bool Traverse(const BinaryOperator *E) {
12539 enqueue(E);
12540 EvalResult PrevResult;
12541 while (!Queue.empty())
12542 process(PrevResult);
12544 if (PrevResult.Failed) return false;
12546 FinalResult.swap(PrevResult.Val);
12547 return true;
12550 private:
12551 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12552 return IntEval.Success(Value, E, Result);
12554 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12555 return IntEval.Success(Value, E, Result);
12557 bool Error(const Expr *E) {
12558 return IntEval.Error(E);
12560 bool Error(const Expr *E, diag::kind D) {
12561 return IntEval.Error(E, D);
12564 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12565 return Info.CCEDiag(E, D);
12568 // Returns true if visiting the RHS is necessary, false otherwise.
12569 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12570 bool &SuppressRHSDiags);
12572 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12573 const BinaryOperator *E, APValue &Result);
12575 void EvaluateExpr(const Expr *E, EvalResult &Result) {
12576 Result.Failed = !Evaluate(Result.Val, Info, E);
12577 if (Result.Failed)
12578 Result.Val = APValue();
12581 void process(EvalResult &Result);
12583 void enqueue(const Expr *E) {
12584 E = E->IgnoreParens();
12585 Queue.resize(Queue.size()+1);
12586 Queue.back().E = E;
12587 Queue.back().Kind = Job::AnyExprKind;
12593 bool DataRecursiveIntBinOpEvaluator::
12594 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12595 bool &SuppressRHSDiags) {
12596 if (E->getOpcode() == BO_Comma) {
12597 // Ignore LHS but note if we could not evaluate it.
12598 if (LHSResult.Failed)
12599 return Info.noteSideEffect();
12600 return true;
12603 if (E->isLogicalOp()) {
12604 bool LHSAsBool;
12605 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12606 // We were able to evaluate the LHS, see if we can get away with not
12607 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12608 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12609 Success(LHSAsBool, E, LHSResult.Val);
12610 return false; // Ignore RHS
12612 } else {
12613 LHSResult.Failed = true;
12615 // Since we weren't able to evaluate the left hand side, it
12616 // might have had side effects.
12617 if (!Info.noteSideEffect())
12618 return false;
12620 // We can't evaluate the LHS; however, sometimes the result
12621 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12622 // Don't ignore RHS and suppress diagnostics from this arm.
12623 SuppressRHSDiags = true;
12626 return true;
12629 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12630 E->getRHS()->getType()->isIntegralOrEnumerationType());
12632 if (LHSResult.Failed && !Info.noteFailure())
12633 return false; // Ignore RHS;
12635 return true;
12638 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12639 bool IsSub) {
12640 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12641 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12642 // offsets.
12643 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12644 CharUnits &Offset = LVal.getLValueOffset();
12645 uint64_t Offset64 = Offset.getQuantity();
12646 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12647 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12648 : Offset64 + Index64);
12651 bool DataRecursiveIntBinOpEvaluator::
12652 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12653 const BinaryOperator *E, APValue &Result) {
12654 if (E->getOpcode() == BO_Comma) {
12655 if (RHSResult.Failed)
12656 return false;
12657 Result = RHSResult.Val;
12658 return true;
12661 if (E->isLogicalOp()) {
12662 bool lhsResult, rhsResult;
12663 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12664 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12666 if (LHSIsOK) {
12667 if (RHSIsOK) {
12668 if (E->getOpcode() == BO_LOr)
12669 return Success(lhsResult || rhsResult, E, Result);
12670 else
12671 return Success(lhsResult && rhsResult, E, Result);
12673 } else {
12674 if (RHSIsOK) {
12675 // We can't evaluate the LHS; however, sometimes the result
12676 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12677 if (rhsResult == (E->getOpcode() == BO_LOr))
12678 return Success(rhsResult, E, Result);
12682 return false;
12685 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12686 E->getRHS()->getType()->isIntegralOrEnumerationType());
12688 if (LHSResult.Failed || RHSResult.Failed)
12689 return false;
12691 const APValue &LHSVal = LHSResult.Val;
12692 const APValue &RHSVal = RHSResult.Val;
12694 // Handle cases like (unsigned long)&a + 4.
12695 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12696 Result = LHSVal;
12697 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12698 return true;
12701 // Handle cases like 4 + (unsigned long)&a
12702 if (E->getOpcode() == BO_Add &&
12703 RHSVal.isLValue() && LHSVal.isInt()) {
12704 Result = RHSVal;
12705 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12706 return true;
12709 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12710 // Handle (intptr_t)&&A - (intptr_t)&&B.
12711 if (!LHSVal.getLValueOffset().isZero() ||
12712 !RHSVal.getLValueOffset().isZero())
12713 return false;
12714 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12715 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12716 if (!LHSExpr || !RHSExpr)
12717 return false;
12718 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12719 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12720 if (!LHSAddrExpr || !RHSAddrExpr)
12721 return false;
12722 // Make sure both labels come from the same function.
12723 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12724 RHSAddrExpr->getLabel()->getDeclContext())
12725 return false;
12726 Result = APValue(LHSAddrExpr, RHSAddrExpr);
12727 return true;
12730 // All the remaining cases expect both operands to be an integer
12731 if (!LHSVal.isInt() || !RHSVal.isInt())
12732 return Error(E);
12734 // Set up the width and signedness manually, in case it can't be deduced
12735 // from the operation we're performing.
12736 // FIXME: Don't do this in the cases where we can deduce it.
12737 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12738 E->getType()->isUnsignedIntegerOrEnumerationType());
12739 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12740 RHSVal.getInt(), Value))
12741 return false;
12742 return Success(Value, E, Result);
12745 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12746 Job &job = Queue.back();
12748 switch (job.Kind) {
12749 case Job::AnyExprKind: {
12750 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12751 if (shouldEnqueue(Bop)) {
12752 job.Kind = Job::BinOpKind;
12753 enqueue(Bop->getLHS());
12754 return;
12758 EvaluateExpr(job.E, Result);
12759 Queue.pop_back();
12760 return;
12763 case Job::BinOpKind: {
12764 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12765 bool SuppressRHSDiags = false;
12766 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12767 Queue.pop_back();
12768 return;
12770 if (SuppressRHSDiags)
12771 job.startSpeculativeEval(Info);
12772 job.LHSResult.swap(Result);
12773 job.Kind = Job::BinOpVisitedLHSKind;
12774 enqueue(Bop->getRHS());
12775 return;
12778 case Job::BinOpVisitedLHSKind: {
12779 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12780 EvalResult RHS;
12781 RHS.swap(Result);
12782 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12783 Queue.pop_back();
12784 return;
12788 llvm_unreachable("Invalid Job::Kind!");
12791 namespace {
12792 enum class CmpResult {
12793 Unequal,
12794 Less,
12795 Equal,
12796 Greater,
12797 Unordered,
12801 template <class SuccessCB, class AfterCB>
12802 static bool
12803 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12804 SuccessCB &&Success, AfterCB &&DoAfter) {
12805 assert(!E->isValueDependent());
12806 assert(E->isComparisonOp() && "expected comparison operator");
12807 assert((E->getOpcode() == BO_Cmp ||
12808 E->getType()->isIntegralOrEnumerationType()) &&
12809 "unsupported binary expression evaluation");
12810 auto Error = [&](const Expr *E) {
12811 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12812 return false;
12815 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12816 bool IsEquality = E->isEqualityOp();
12818 QualType LHSTy = E->getLHS()->getType();
12819 QualType RHSTy = E->getRHS()->getType();
12821 if (LHSTy->isIntegralOrEnumerationType() &&
12822 RHSTy->isIntegralOrEnumerationType()) {
12823 APSInt LHS, RHS;
12824 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12825 if (!LHSOK && !Info.noteFailure())
12826 return false;
12827 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12828 return false;
12829 if (LHS < RHS)
12830 return Success(CmpResult::Less, E);
12831 if (LHS > RHS)
12832 return Success(CmpResult::Greater, E);
12833 return Success(CmpResult::Equal, E);
12836 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12837 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12838 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12840 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12841 if (!LHSOK && !Info.noteFailure())
12842 return false;
12843 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12844 return false;
12845 if (LHSFX < RHSFX)
12846 return Success(CmpResult::Less, E);
12847 if (LHSFX > RHSFX)
12848 return Success(CmpResult::Greater, E);
12849 return Success(CmpResult::Equal, E);
12852 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12853 ComplexValue LHS, RHS;
12854 bool LHSOK;
12855 if (E->isAssignmentOp()) {
12856 LValue LV;
12857 EvaluateLValue(E->getLHS(), LV, Info);
12858 LHSOK = false;
12859 } else if (LHSTy->isRealFloatingType()) {
12860 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12861 if (LHSOK) {
12862 LHS.makeComplexFloat();
12863 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12865 } else {
12866 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12868 if (!LHSOK && !Info.noteFailure())
12869 return false;
12871 if (E->getRHS()->getType()->isRealFloatingType()) {
12872 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12873 return false;
12874 RHS.makeComplexFloat();
12875 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12876 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12877 return false;
12879 if (LHS.isComplexFloat()) {
12880 APFloat::cmpResult CR_r =
12881 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12882 APFloat::cmpResult CR_i =
12883 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12884 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12885 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12886 } else {
12887 assert(IsEquality && "invalid complex comparison");
12888 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12889 LHS.getComplexIntImag() == RHS.getComplexIntImag();
12890 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12894 if (LHSTy->isRealFloatingType() &&
12895 RHSTy->isRealFloatingType()) {
12896 APFloat RHS(0.0), LHS(0.0);
12898 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12899 if (!LHSOK && !Info.noteFailure())
12900 return false;
12902 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12903 return false;
12905 assert(E->isComparisonOp() && "Invalid binary operator!");
12906 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12907 if (!Info.InConstantContext &&
12908 APFloatCmpResult == APFloat::cmpUnordered &&
12909 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12910 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12911 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12912 return false;
12914 auto GetCmpRes = [&]() {
12915 switch (APFloatCmpResult) {
12916 case APFloat::cmpEqual:
12917 return CmpResult::Equal;
12918 case APFloat::cmpLessThan:
12919 return CmpResult::Less;
12920 case APFloat::cmpGreaterThan:
12921 return CmpResult::Greater;
12922 case APFloat::cmpUnordered:
12923 return CmpResult::Unordered;
12925 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12927 return Success(GetCmpRes(), E);
12930 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12931 LValue LHSValue, RHSValue;
12933 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12934 if (!LHSOK && !Info.noteFailure())
12935 return false;
12937 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12938 return false;
12940 // Reject differing bases from the normal codepath; we special-case
12941 // comparisons to null.
12942 if (!HasSameBase(LHSValue, RHSValue)) {
12943 // Inequalities and subtractions between unrelated pointers have
12944 // unspecified or undefined behavior.
12945 if (!IsEquality) {
12946 Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12947 return false;
12949 // A constant address may compare equal to the address of a symbol.
12950 // The one exception is that address of an object cannot compare equal
12951 // to a null pointer constant.
12952 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12953 (!RHSValue.Base && !RHSValue.Offset.isZero()))
12954 return Error(E);
12955 // It's implementation-defined whether distinct literals will have
12956 // distinct addresses. In clang, the result of such a comparison is
12957 // unspecified, so it is not a constant expression. However, we do know
12958 // that the address of a literal will be non-null.
12959 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12960 LHSValue.Base && RHSValue.Base)
12961 return Error(E);
12962 // We can't tell whether weak symbols will end up pointing to the same
12963 // object.
12964 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12965 return Error(E);
12966 // We can't compare the address of the start of one object with the
12967 // past-the-end address of another object, per C++ DR1652.
12968 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12969 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12970 (RHSValue.Base && RHSValue.Offset.isZero() &&
12971 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12972 return Error(E);
12973 // We can't tell whether an object is at the same address as another
12974 // zero sized object.
12975 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12976 (LHSValue.Base && isZeroSized(RHSValue)))
12977 return Error(E);
12978 return Success(CmpResult::Unequal, E);
12981 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12982 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12984 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12985 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12987 // C++11 [expr.rel]p3:
12988 // Pointers to void (after pointer conversions) can be compared, with a
12989 // result defined as follows: If both pointers represent the same
12990 // address or are both the null pointer value, the result is true if the
12991 // operator is <= or >= and false otherwise; otherwise the result is
12992 // unspecified.
12993 // We interpret this as applying to pointers to *cv* void.
12994 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12995 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12997 // C++11 [expr.rel]p2:
12998 // - If two pointers point to non-static data members of the same object,
12999 // or to subobjects or array elements fo such members, recursively, the
13000 // pointer to the later declared member compares greater provided the
13001 // two members have the same access control and provided their class is
13002 // not a union.
13003 // [...]
13004 // - Otherwise pointer comparisons are unspecified.
13005 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13006 bool WasArrayIndex;
13007 unsigned Mismatch = FindDesignatorMismatch(
13008 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13009 // At the point where the designators diverge, the comparison has a
13010 // specified value if:
13011 // - we are comparing array indices
13012 // - we are comparing fields of a union, or fields with the same access
13013 // Otherwise, the result is unspecified and thus the comparison is not a
13014 // constant expression.
13015 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13016 Mismatch < RHSDesignator.Entries.size()) {
13017 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13018 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13019 if (!LF && !RF)
13020 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13021 else if (!LF)
13022 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13023 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13024 << RF->getParent() << RF;
13025 else if (!RF)
13026 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13027 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13028 << LF->getParent() << LF;
13029 else if (!LF->getParent()->isUnion() &&
13030 LF->getAccess() != RF->getAccess())
13031 Info.CCEDiag(E,
13032 diag::note_constexpr_pointer_comparison_differing_access)
13033 << LF << LF->getAccess() << RF << RF->getAccess()
13034 << LF->getParent();
13038 // The comparison here must be unsigned, and performed with the same
13039 // width as the pointer.
13040 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13041 uint64_t CompareLHS = LHSOffset.getQuantity();
13042 uint64_t CompareRHS = RHSOffset.getQuantity();
13043 assert(PtrSize <= 64 && "Unexpected pointer width");
13044 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13045 CompareLHS &= Mask;
13046 CompareRHS &= Mask;
13048 // If there is a base and this is a relational operator, we can only
13049 // compare pointers within the object in question; otherwise, the result
13050 // depends on where the object is located in memory.
13051 if (!LHSValue.Base.isNull() && IsRelational) {
13052 QualType BaseTy = getType(LHSValue.Base);
13053 if (BaseTy->isIncompleteType())
13054 return Error(E);
13055 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13056 uint64_t OffsetLimit = Size.getQuantity();
13057 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13058 return Error(E);
13061 if (CompareLHS < CompareRHS)
13062 return Success(CmpResult::Less, E);
13063 if (CompareLHS > CompareRHS)
13064 return Success(CmpResult::Greater, E);
13065 return Success(CmpResult::Equal, E);
13068 if (LHSTy->isMemberPointerType()) {
13069 assert(IsEquality && "unexpected member pointer operation");
13070 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13072 MemberPtr LHSValue, RHSValue;
13074 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13075 if (!LHSOK && !Info.noteFailure())
13076 return false;
13078 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13079 return false;
13081 // C++11 [expr.eq]p2:
13082 // If both operands are null, they compare equal. Otherwise if only one is
13083 // null, they compare unequal.
13084 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13085 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13086 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13089 // Otherwise if either is a pointer to a virtual member function, the
13090 // result is unspecified.
13091 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13092 if (MD->isVirtual())
13093 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13094 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13095 if (MD->isVirtual())
13096 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13098 // Otherwise they compare equal if and only if they would refer to the
13099 // same member of the same most derived object or the same subobject if
13100 // they were dereferenced with a hypothetical object of the associated
13101 // class type.
13102 bool Equal = LHSValue == RHSValue;
13103 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13106 if (LHSTy->isNullPtrType()) {
13107 assert(E->isComparisonOp() && "unexpected nullptr operation");
13108 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13109 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13110 // are compared, the result is true of the operator is <=, >= or ==, and
13111 // false otherwise.
13112 return Success(CmpResult::Equal, E);
13115 return DoAfter();
13118 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13119 if (!CheckLiteralType(Info, E))
13120 return false;
13122 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13123 ComparisonCategoryResult CCR;
13124 switch (CR) {
13125 case CmpResult::Unequal:
13126 llvm_unreachable("should never produce Unequal for three-way comparison");
13127 case CmpResult::Less:
13128 CCR = ComparisonCategoryResult::Less;
13129 break;
13130 case CmpResult::Equal:
13131 CCR = ComparisonCategoryResult::Equal;
13132 break;
13133 case CmpResult::Greater:
13134 CCR = ComparisonCategoryResult::Greater;
13135 break;
13136 case CmpResult::Unordered:
13137 CCR = ComparisonCategoryResult::Unordered;
13138 break;
13140 // Evaluation succeeded. Lookup the information for the comparison category
13141 // type and fetch the VarDecl for the result.
13142 const ComparisonCategoryInfo &CmpInfo =
13143 Info.Ctx.CompCategories.getInfoForType(E->getType());
13144 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13145 // Check and evaluate the result as a constant expression.
13146 LValue LV;
13147 LV.set(VD);
13148 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13149 return false;
13150 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13151 ConstantExprKind::Normal);
13153 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13154 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13158 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13159 // We don't support assignment in C. C++ assignments don't get here because
13160 // assignment is an lvalue in C++.
13161 if (E->isAssignmentOp()) {
13162 Error(E);
13163 if (!Info.noteFailure())
13164 return false;
13167 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13168 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13170 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13171 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13172 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13174 if (E->isComparisonOp()) {
13175 // Evaluate builtin binary comparisons by evaluating them as three-way
13176 // comparisons and then translating the result.
13177 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13178 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13179 "should only produce Unequal for equality comparisons");
13180 bool IsEqual = CR == CmpResult::Equal,
13181 IsLess = CR == CmpResult::Less,
13182 IsGreater = CR == CmpResult::Greater;
13183 auto Op = E->getOpcode();
13184 switch (Op) {
13185 default:
13186 llvm_unreachable("unsupported binary operator");
13187 case BO_EQ:
13188 case BO_NE:
13189 return Success(IsEqual == (Op == BO_EQ), E);
13190 case BO_LT:
13191 return Success(IsLess, E);
13192 case BO_GT:
13193 return Success(IsGreater, E);
13194 case BO_LE:
13195 return Success(IsEqual || IsLess, E);
13196 case BO_GE:
13197 return Success(IsEqual || IsGreater, E);
13200 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13201 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13205 QualType LHSTy = E->getLHS()->getType();
13206 QualType RHSTy = E->getRHS()->getType();
13208 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13209 E->getOpcode() == BO_Sub) {
13210 LValue LHSValue, RHSValue;
13212 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13213 if (!LHSOK && !Info.noteFailure())
13214 return false;
13216 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13217 return false;
13219 // Reject differing bases from the normal codepath; we special-case
13220 // comparisons to null.
13221 if (!HasSameBase(LHSValue, RHSValue)) {
13222 // Handle &&A - &&B.
13223 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13224 return Error(E);
13225 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13226 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13227 if (!LHSExpr || !RHSExpr)
13228 return Error(E);
13229 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13230 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13231 if (!LHSAddrExpr || !RHSAddrExpr)
13232 return Error(E);
13233 // Make sure both labels come from the same function.
13234 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13235 RHSAddrExpr->getLabel()->getDeclContext())
13236 return Error(E);
13237 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13239 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13240 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13242 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13243 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13245 // C++11 [expr.add]p6:
13246 // Unless both pointers point to elements of the same array object, or
13247 // one past the last element of the array object, the behavior is
13248 // undefined.
13249 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13250 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13251 RHSDesignator))
13252 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13254 QualType Type = E->getLHS()->getType();
13255 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13257 CharUnits ElementSize;
13258 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13259 return false;
13261 // As an extension, a type may have zero size (empty struct or union in
13262 // C, array of zero length). Pointer subtraction in such cases has
13263 // undefined behavior, so is not constant.
13264 if (ElementSize.isZero()) {
13265 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13266 << ElementType;
13267 return false;
13270 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13271 // and produce incorrect results when it overflows. Such behavior
13272 // appears to be non-conforming, but is common, so perhaps we should
13273 // assume the standard intended for such cases to be undefined behavior
13274 // and check for them.
13276 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13277 // overflow in the final conversion to ptrdiff_t.
13278 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13279 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13280 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13281 false);
13282 APSInt TrueResult = (LHS - RHS) / ElemSize;
13283 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13285 if (Result.extend(65) != TrueResult &&
13286 !HandleOverflow(Info, E, TrueResult, E->getType()))
13287 return false;
13288 return Success(Result, E);
13291 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13294 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13295 /// a result as the expression's type.
13296 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13297 const UnaryExprOrTypeTraitExpr *E) {
13298 switch(E->getKind()) {
13299 case UETT_PreferredAlignOf:
13300 case UETT_AlignOf: {
13301 if (E->isArgumentType())
13302 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13304 else
13305 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13309 case UETT_VecStep: {
13310 QualType Ty = E->getTypeOfArgument();
13312 if (Ty->isVectorType()) {
13313 unsigned n = Ty->castAs<VectorType>()->getNumElements();
13315 // The vec_step built-in functions that take a 3-component
13316 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13317 if (n == 3)
13318 n = 4;
13320 return Success(n, E);
13321 } else
13322 return Success(1, E);
13325 case UETT_SizeOf: {
13326 QualType SrcTy = E->getTypeOfArgument();
13327 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13328 // the result is the size of the referenced type."
13329 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13330 SrcTy = Ref->getPointeeType();
13332 CharUnits Sizeof;
13333 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13334 return false;
13335 return Success(Sizeof, E);
13337 case UETT_OpenMPRequiredSimdAlign:
13338 assert(E->isArgumentType());
13339 return Success(
13340 Info.Ctx.toCharUnitsFromBits(
13341 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13342 .getQuantity(),
13346 llvm_unreachable("unknown expr/type trait");
13349 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13350 CharUnits Result;
13351 unsigned n = OOE->getNumComponents();
13352 if (n == 0)
13353 return Error(OOE);
13354 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13355 for (unsigned i = 0; i != n; ++i) {
13356 OffsetOfNode ON = OOE->getComponent(i);
13357 switch (ON.getKind()) {
13358 case OffsetOfNode::Array: {
13359 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13360 APSInt IdxResult;
13361 if (!EvaluateInteger(Idx, IdxResult, Info))
13362 return false;
13363 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13364 if (!AT)
13365 return Error(OOE);
13366 CurrentType = AT->getElementType();
13367 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13368 Result += IdxResult.getSExtValue() * ElementSize;
13369 break;
13372 case OffsetOfNode::Field: {
13373 FieldDecl *MemberDecl = ON.getField();
13374 const RecordType *RT = CurrentType->getAs<RecordType>();
13375 if (!RT)
13376 return Error(OOE);
13377 RecordDecl *RD = RT->getDecl();
13378 if (RD->isInvalidDecl()) return false;
13379 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13380 unsigned i = MemberDecl->getFieldIndex();
13381 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13382 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13383 CurrentType = MemberDecl->getType().getNonReferenceType();
13384 break;
13387 case OffsetOfNode::Identifier:
13388 llvm_unreachable("dependent __builtin_offsetof");
13390 case OffsetOfNode::Base: {
13391 CXXBaseSpecifier *BaseSpec = ON.getBase();
13392 if (BaseSpec->isVirtual())
13393 return Error(OOE);
13395 // Find the layout of the class whose base we are looking into.
13396 const RecordType *RT = CurrentType->getAs<RecordType>();
13397 if (!RT)
13398 return Error(OOE);
13399 RecordDecl *RD = RT->getDecl();
13400 if (RD->isInvalidDecl()) return false;
13401 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13403 // Find the base class itself.
13404 CurrentType = BaseSpec->getType();
13405 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13406 if (!BaseRT)
13407 return Error(OOE);
13409 // Add the offset to the base.
13410 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13411 break;
13415 return Success(Result, OOE);
13418 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13419 switch (E->getOpcode()) {
13420 default:
13421 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13422 // See C99 6.6p3.
13423 return Error(E);
13424 case UO_Extension:
13425 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13426 // If so, we could clear the diagnostic ID.
13427 return Visit(E->getSubExpr());
13428 case UO_Plus:
13429 // The result is just the value.
13430 return Visit(E->getSubExpr());
13431 case UO_Minus: {
13432 if (!Visit(E->getSubExpr()))
13433 return false;
13434 if (!Result.isInt()) return Error(E);
13435 const APSInt &Value = Result.getInt();
13436 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13437 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13438 E->getType()))
13439 return false;
13440 return Success(-Value, E);
13442 case UO_Not: {
13443 if (!Visit(E->getSubExpr()))
13444 return false;
13445 if (!Result.isInt()) return Error(E);
13446 return Success(~Result.getInt(), E);
13448 case UO_LNot: {
13449 bool bres;
13450 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13451 return false;
13452 return Success(!bres, E);
13457 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13458 /// result type is integer.
13459 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13460 const Expr *SubExpr = E->getSubExpr();
13461 QualType DestType = E->getType();
13462 QualType SrcType = SubExpr->getType();
13464 switch (E->getCastKind()) {
13465 case CK_BaseToDerived:
13466 case CK_DerivedToBase:
13467 case CK_UncheckedDerivedToBase:
13468 case CK_Dynamic:
13469 case CK_ToUnion:
13470 case CK_ArrayToPointerDecay:
13471 case CK_FunctionToPointerDecay:
13472 case CK_NullToPointer:
13473 case CK_NullToMemberPointer:
13474 case CK_BaseToDerivedMemberPointer:
13475 case CK_DerivedToBaseMemberPointer:
13476 case CK_ReinterpretMemberPointer:
13477 case CK_ConstructorConversion:
13478 case CK_IntegralToPointer:
13479 case CK_ToVoid:
13480 case CK_VectorSplat:
13481 case CK_IntegralToFloating:
13482 case CK_FloatingCast:
13483 case CK_CPointerToObjCPointerCast:
13484 case CK_BlockPointerToObjCPointerCast:
13485 case CK_AnyPointerToBlockPointerCast:
13486 case CK_ObjCObjectLValueCast:
13487 case CK_FloatingRealToComplex:
13488 case CK_FloatingComplexToReal:
13489 case CK_FloatingComplexCast:
13490 case CK_FloatingComplexToIntegralComplex:
13491 case CK_IntegralRealToComplex:
13492 case CK_IntegralComplexCast:
13493 case CK_IntegralComplexToFloatingComplex:
13494 case CK_BuiltinFnToFnPtr:
13495 case CK_ZeroToOCLOpaqueType:
13496 case CK_NonAtomicToAtomic:
13497 case CK_AddressSpaceConversion:
13498 case CK_IntToOCLSampler:
13499 case CK_FloatingToFixedPoint:
13500 case CK_FixedPointToFloating:
13501 case CK_FixedPointCast:
13502 case CK_IntegralToFixedPoint:
13503 case CK_MatrixCast:
13504 llvm_unreachable("invalid cast kind for integral value");
13506 case CK_BitCast:
13507 case CK_Dependent:
13508 case CK_LValueBitCast:
13509 case CK_ARCProduceObject:
13510 case CK_ARCConsumeObject:
13511 case CK_ARCReclaimReturnedObject:
13512 case CK_ARCExtendBlockObject:
13513 case CK_CopyAndAutoreleaseBlockObject:
13514 return Error(E);
13516 case CK_UserDefinedConversion:
13517 case CK_LValueToRValue:
13518 case CK_AtomicToNonAtomic:
13519 case CK_NoOp:
13520 case CK_LValueToRValueBitCast:
13521 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13523 case CK_MemberPointerToBoolean:
13524 case CK_PointerToBoolean:
13525 case CK_IntegralToBoolean:
13526 case CK_FloatingToBoolean:
13527 case CK_BooleanToSignedIntegral:
13528 case CK_FloatingComplexToBoolean:
13529 case CK_IntegralComplexToBoolean: {
13530 bool BoolResult;
13531 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13532 return false;
13533 uint64_t IntResult = BoolResult;
13534 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13535 IntResult = (uint64_t)-1;
13536 return Success(IntResult, E);
13539 case CK_FixedPointToIntegral: {
13540 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13541 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13542 return false;
13543 bool Overflowed;
13544 llvm::APSInt Result = Src.convertToInt(
13545 Info.Ctx.getIntWidth(DestType),
13546 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13547 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13548 return false;
13549 return Success(Result, E);
13552 case CK_FixedPointToBoolean: {
13553 // Unsigned padding does not affect this.
13554 APValue Val;
13555 if (!Evaluate(Val, Info, SubExpr))
13556 return false;
13557 return Success(Val.getFixedPoint().getBoolValue(), E);
13560 case CK_IntegralCast: {
13561 if (!Visit(SubExpr))
13562 return false;
13564 if (!Result.isInt()) {
13565 // Allow casts of address-of-label differences if they are no-ops
13566 // or narrowing. (The narrowing case isn't actually guaranteed to
13567 // be constant-evaluatable except in some narrow cases which are hard
13568 // to detect here. We let it through on the assumption the user knows
13569 // what they are doing.)
13570 if (Result.isAddrLabelDiff())
13571 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13572 // Only allow casts of lvalues if they are lossless.
13573 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13576 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13577 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13578 DestType->isEnumeralType()) {
13580 bool ConstexprVar = true;
13582 // We know if we are here that we are in a context that we might require
13583 // a constant expression or a context that requires a constant
13584 // value. But if we are initializing a value we don't know if it is a
13585 // constexpr variable or not. We can check the EvaluatingDecl to determine
13586 // if it constexpr or not. If not then we don't want to emit a diagnostic.
13587 if (const auto *VD = dyn_cast_or_null<VarDecl>(
13588 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13589 ConstexprVar = VD->isConstexpr();
13591 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13592 const EnumDecl *ED = ET->getDecl();
13593 // Check that the value is within the range of the enumeration values.
13595 // This corressponds to [expr.static.cast]p10 which says:
13596 // A value of integral or enumeration type can be explicitly converted
13597 // to a complete enumeration type ... If the enumeration type does not
13598 // have a fixed underlying type, the value is unchanged if the original
13599 // value is within the range of the enumeration values ([dcl.enum]), and
13600 // otherwise, the behavior is undefined.
13602 // This was resolved as part of DR2338 which has CD5 status.
13603 if (!ED->isFixed()) {
13604 llvm::APInt Min;
13605 llvm::APInt Max;
13607 ED->getValueRange(Max, Min);
13608 --Max;
13610 if (ED->getNumNegativeBits() && ConstexprVar &&
13611 (Max.slt(Result.getInt().getSExtValue()) ||
13612 Min.sgt(Result.getInt().getSExtValue())))
13613 Info.Ctx.getDiagnostics().Report(
13614 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13615 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13616 << Max.getSExtValue();
13617 else if (!ED->getNumNegativeBits() && ConstexprVar &&
13618 Max.ult(Result.getInt().getZExtValue()))
13619 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13620 diag::warn_constexpr_unscoped_enum_out_of_range)
13621 << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
13625 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13626 Result.getInt()), E);
13629 case CK_PointerToIntegral: {
13630 CCEDiag(E, diag::note_constexpr_invalid_cast)
13631 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13633 LValue LV;
13634 if (!EvaluatePointer(SubExpr, LV, Info))
13635 return false;
13637 if (LV.getLValueBase()) {
13638 // Only allow based lvalue casts if they are lossless.
13639 // FIXME: Allow a larger integer size than the pointer size, and allow
13640 // narrowing back down to pointer width in subsequent integral casts.
13641 // FIXME: Check integer type's active bits, not its type size.
13642 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13643 return Error(E);
13645 LV.Designator.setInvalid();
13646 LV.moveInto(Result);
13647 return true;
13650 APSInt AsInt;
13651 APValue V;
13652 LV.moveInto(V);
13653 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13654 llvm_unreachable("Can't cast this!");
13656 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13659 case CK_IntegralComplexToReal: {
13660 ComplexValue C;
13661 if (!EvaluateComplex(SubExpr, C, Info))
13662 return false;
13663 return Success(C.getComplexIntReal(), E);
13666 case CK_FloatingToIntegral: {
13667 APFloat F(0.0);
13668 if (!EvaluateFloat(SubExpr, F, Info))
13669 return false;
13671 APSInt Value;
13672 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13673 return false;
13674 return Success(Value, E);
13678 llvm_unreachable("unknown cast resulting in integral value");
13681 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13682 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13683 ComplexValue LV;
13684 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13685 return false;
13686 if (!LV.isComplexInt())
13687 return Error(E);
13688 return Success(LV.getComplexIntReal(), E);
13691 return Visit(E->getSubExpr());
13694 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13695 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13696 ComplexValue LV;
13697 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13698 return false;
13699 if (!LV.isComplexInt())
13700 return Error(E);
13701 return Success(LV.getComplexIntImag(), E);
13704 VisitIgnoredValue(E->getSubExpr());
13705 return Success(0, E);
13708 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13709 return Success(E->getPackLength(), E);
13712 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13713 return Success(E->getValue(), E);
13716 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13717 const ConceptSpecializationExpr *E) {
13718 return Success(E->isSatisfied(), E);
13721 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13722 return Success(E->isSatisfied(), E);
13725 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13726 switch (E->getOpcode()) {
13727 default:
13728 // Invalid unary operators
13729 return Error(E);
13730 case UO_Plus:
13731 // The result is just the value.
13732 return Visit(E->getSubExpr());
13733 case UO_Minus: {
13734 if (!Visit(E->getSubExpr())) return false;
13735 if (!Result.isFixedPoint())
13736 return Error(E);
13737 bool Overflowed;
13738 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13739 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13740 return false;
13741 return Success(Negated, E);
13743 case UO_LNot: {
13744 bool bres;
13745 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13746 return false;
13747 return Success(!bres, E);
13752 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13753 const Expr *SubExpr = E->getSubExpr();
13754 QualType DestType = E->getType();
13755 assert(DestType->isFixedPointType() &&
13756 "Expected destination type to be a fixed point type");
13757 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13759 switch (E->getCastKind()) {
13760 case CK_FixedPointCast: {
13761 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13762 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13763 return false;
13764 bool Overflowed;
13765 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13766 if (Overflowed) {
13767 if (Info.checkingForUndefinedBehavior())
13768 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13769 diag::warn_fixedpoint_constant_overflow)
13770 << Result.toString() << E->getType();
13771 if (!HandleOverflow(Info, E, Result, E->getType()))
13772 return false;
13774 return Success(Result, E);
13776 case CK_IntegralToFixedPoint: {
13777 APSInt Src;
13778 if (!EvaluateInteger(SubExpr, Src, Info))
13779 return false;
13781 bool Overflowed;
13782 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13783 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13785 if (Overflowed) {
13786 if (Info.checkingForUndefinedBehavior())
13787 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13788 diag::warn_fixedpoint_constant_overflow)
13789 << IntResult.toString() << E->getType();
13790 if (!HandleOverflow(Info, E, IntResult, E->getType()))
13791 return false;
13794 return Success(IntResult, E);
13796 case CK_FloatingToFixedPoint: {
13797 APFloat Src(0.0);
13798 if (!EvaluateFloat(SubExpr, Src, Info))
13799 return false;
13801 bool Overflowed;
13802 APFixedPoint Result = APFixedPoint::getFromFloatValue(
13803 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13805 if (Overflowed) {
13806 if (Info.checkingForUndefinedBehavior())
13807 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13808 diag::warn_fixedpoint_constant_overflow)
13809 << Result.toString() << E->getType();
13810 if (!HandleOverflow(Info, E, Result, E->getType()))
13811 return false;
13814 return Success(Result, E);
13816 case CK_NoOp:
13817 case CK_LValueToRValue:
13818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13819 default:
13820 return Error(E);
13824 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13825 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13826 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13828 const Expr *LHS = E->getLHS();
13829 const Expr *RHS = E->getRHS();
13830 FixedPointSemantics ResultFXSema =
13831 Info.Ctx.getFixedPointSemantics(E->getType());
13833 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13834 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13835 return false;
13836 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13837 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13838 return false;
13840 bool OpOverflow = false, ConversionOverflow = false;
13841 APFixedPoint Result(LHSFX.getSemantics());
13842 switch (E->getOpcode()) {
13843 case BO_Add: {
13844 Result = LHSFX.add(RHSFX, &OpOverflow)
13845 .convert(ResultFXSema, &ConversionOverflow);
13846 break;
13848 case BO_Sub: {
13849 Result = LHSFX.sub(RHSFX, &OpOverflow)
13850 .convert(ResultFXSema, &ConversionOverflow);
13851 break;
13853 case BO_Mul: {
13854 Result = LHSFX.mul(RHSFX, &OpOverflow)
13855 .convert(ResultFXSema, &ConversionOverflow);
13856 break;
13858 case BO_Div: {
13859 if (RHSFX.getValue() == 0) {
13860 Info.FFDiag(E, diag::note_expr_divide_by_zero);
13861 return false;
13863 Result = LHSFX.div(RHSFX, &OpOverflow)
13864 .convert(ResultFXSema, &ConversionOverflow);
13865 break;
13867 case BO_Shl:
13868 case BO_Shr: {
13869 FixedPointSemantics LHSSema = LHSFX.getSemantics();
13870 llvm::APSInt RHSVal = RHSFX.getValue();
13872 unsigned ShiftBW =
13873 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13874 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13875 // Embedded-C 4.1.6.2.2:
13876 // The right operand must be nonnegative and less than the total number
13877 // of (nonpadding) bits of the fixed-point operand ...
13878 if (RHSVal.isNegative())
13879 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13880 else if (Amt != RHSVal)
13881 Info.CCEDiag(E, diag::note_constexpr_large_shift)
13882 << RHSVal << E->getType() << ShiftBW;
13884 if (E->getOpcode() == BO_Shl)
13885 Result = LHSFX.shl(Amt, &OpOverflow);
13886 else
13887 Result = LHSFX.shr(Amt, &OpOverflow);
13888 break;
13890 default:
13891 return false;
13893 if (OpOverflow || ConversionOverflow) {
13894 if (Info.checkingForUndefinedBehavior())
13895 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13896 diag::warn_fixedpoint_constant_overflow)
13897 << Result.toString() << E->getType();
13898 if (!HandleOverflow(Info, E, Result, E->getType()))
13899 return false;
13901 return Success(Result, E);
13904 //===----------------------------------------------------------------------===//
13905 // Float Evaluation
13906 //===----------------------------------------------------------------------===//
13908 namespace {
13909 class FloatExprEvaluator
13910 : public ExprEvaluatorBase<FloatExprEvaluator> {
13911 APFloat &Result;
13912 public:
13913 FloatExprEvaluator(EvalInfo &info, APFloat &result)
13914 : ExprEvaluatorBaseTy(info), Result(result) {}
13916 bool Success(const APValue &V, const Expr *e) {
13917 Result = V.getFloat();
13918 return true;
13921 bool ZeroInitialization(const Expr *E) {
13922 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13923 return true;
13926 bool VisitCallExpr(const CallExpr *E);
13928 bool VisitUnaryOperator(const UnaryOperator *E);
13929 bool VisitBinaryOperator(const BinaryOperator *E);
13930 bool VisitFloatingLiteral(const FloatingLiteral *E);
13931 bool VisitCastExpr(const CastExpr *E);
13933 bool VisitUnaryReal(const UnaryOperator *E);
13934 bool VisitUnaryImag(const UnaryOperator *E);
13936 // FIXME: Missing: array subscript of vector, member of vector
13938 } // end anonymous namespace
13940 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13941 assert(!E->isValueDependent());
13942 assert(E->isPRValue() && E->getType()->isRealFloatingType());
13943 return FloatExprEvaluator(Info, Result).Visit(E);
13946 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13947 QualType ResultTy,
13948 const Expr *Arg,
13949 bool SNaN,
13950 llvm::APFloat &Result) {
13951 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13952 if (!S) return false;
13954 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13956 llvm::APInt fill;
13958 // Treat empty strings as if they were zero.
13959 if (S->getString().empty())
13960 fill = llvm::APInt(32, 0);
13961 else if (S->getString().getAsInteger(0, fill))
13962 return false;
13964 if (Context.getTargetInfo().isNan2008()) {
13965 if (SNaN)
13966 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13967 else
13968 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13969 } else {
13970 // Prior to IEEE 754-2008, architectures were allowed to choose whether
13971 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13972 // a different encoding to what became a standard in 2008, and for pre-
13973 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13974 // sNaN. This is now known as "legacy NaN" encoding.
13975 if (SNaN)
13976 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13977 else
13978 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13981 return true;
13984 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13985 if (!IsConstantEvaluatedBuiltinCall(E))
13986 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13988 switch (E->getBuiltinCallee()) {
13989 default:
13990 return false;
13992 case Builtin::BI__builtin_huge_val:
13993 case Builtin::BI__builtin_huge_valf:
13994 case Builtin::BI__builtin_huge_vall:
13995 case Builtin::BI__builtin_huge_valf16:
13996 case Builtin::BI__builtin_huge_valf128:
13997 case Builtin::BI__builtin_inf:
13998 case Builtin::BI__builtin_inff:
13999 case Builtin::BI__builtin_infl:
14000 case Builtin::BI__builtin_inff16:
14001 case Builtin::BI__builtin_inff128: {
14002 const llvm::fltSemantics &Sem =
14003 Info.Ctx.getFloatTypeSemantics(E->getType());
14004 Result = llvm::APFloat::getInf(Sem);
14005 return true;
14008 case Builtin::BI__builtin_nans:
14009 case Builtin::BI__builtin_nansf:
14010 case Builtin::BI__builtin_nansl:
14011 case Builtin::BI__builtin_nansf16:
14012 case Builtin::BI__builtin_nansf128:
14013 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14014 true, Result))
14015 return Error(E);
14016 return true;
14018 case Builtin::BI__builtin_nan:
14019 case Builtin::BI__builtin_nanf:
14020 case Builtin::BI__builtin_nanl:
14021 case Builtin::BI__builtin_nanf16:
14022 case Builtin::BI__builtin_nanf128:
14023 // If this is __builtin_nan() turn this into a nan, otherwise we
14024 // can't constant fold it.
14025 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14026 false, Result))
14027 return Error(E);
14028 return true;
14030 case Builtin::BI__builtin_fabs:
14031 case Builtin::BI__builtin_fabsf:
14032 case Builtin::BI__builtin_fabsl:
14033 case Builtin::BI__builtin_fabsf128:
14034 // The C standard says "fabs raises no floating-point exceptions,
14035 // even if x is a signaling NaN. The returned value is independent of
14036 // the current rounding direction mode." Therefore constant folding can
14037 // proceed without regard to the floating point settings.
14038 // Reference, WG14 N2478 F.10.4.3
14039 if (!EvaluateFloat(E->getArg(0), Result, Info))
14040 return false;
14042 if (Result.isNegative())
14043 Result.changeSign();
14044 return true;
14046 case Builtin::BI__arithmetic_fence:
14047 return EvaluateFloat(E->getArg(0), Result, Info);
14049 // FIXME: Builtin::BI__builtin_powi
14050 // FIXME: Builtin::BI__builtin_powif
14051 // FIXME: Builtin::BI__builtin_powil
14053 case Builtin::BI__builtin_copysign:
14054 case Builtin::BI__builtin_copysignf:
14055 case Builtin::BI__builtin_copysignl:
14056 case Builtin::BI__builtin_copysignf128: {
14057 APFloat RHS(0.);
14058 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14059 !EvaluateFloat(E->getArg(1), RHS, Info))
14060 return false;
14061 Result.copySign(RHS);
14062 return true;
14065 case Builtin::BI__builtin_fmax:
14066 case Builtin::BI__builtin_fmaxf:
14067 case Builtin::BI__builtin_fmaxl:
14068 case Builtin::BI__builtin_fmaxf16:
14069 case Builtin::BI__builtin_fmaxf128: {
14070 // TODO: Handle sNaN.
14071 APFloat RHS(0.);
14072 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14073 !EvaluateFloat(E->getArg(1), RHS, Info))
14074 return false;
14075 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14076 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14077 Result = RHS;
14078 else if (Result.isNaN() || RHS > Result)
14079 Result = RHS;
14080 return true;
14083 case Builtin::BI__builtin_fmin:
14084 case Builtin::BI__builtin_fminf:
14085 case Builtin::BI__builtin_fminl:
14086 case Builtin::BI__builtin_fminf16:
14087 case Builtin::BI__builtin_fminf128: {
14088 // TODO: Handle sNaN.
14089 APFloat RHS(0.);
14090 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14091 !EvaluateFloat(E->getArg(1), RHS, Info))
14092 return false;
14093 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14094 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14095 Result = RHS;
14096 else if (Result.isNaN() || RHS < Result)
14097 Result = RHS;
14098 return true;
14103 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14104 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14105 ComplexValue CV;
14106 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14107 return false;
14108 Result = CV.FloatReal;
14109 return true;
14112 return Visit(E->getSubExpr());
14115 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14116 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14117 ComplexValue CV;
14118 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14119 return false;
14120 Result = CV.FloatImag;
14121 return true;
14124 VisitIgnoredValue(E->getSubExpr());
14125 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14126 Result = llvm::APFloat::getZero(Sem);
14127 return true;
14130 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14131 switch (E->getOpcode()) {
14132 default: return Error(E);
14133 case UO_Plus:
14134 return EvaluateFloat(E->getSubExpr(), Result, Info);
14135 case UO_Minus:
14136 // In C standard, WG14 N2478 F.3 p4
14137 // "the unary - raises no floating point exceptions,
14138 // even if the operand is signalling."
14139 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14140 return false;
14141 Result.changeSign();
14142 return true;
14146 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14147 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14148 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14150 APFloat RHS(0.0);
14151 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14152 if (!LHSOK && !Info.noteFailure())
14153 return false;
14154 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14155 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14158 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14159 Result = E->getValue();
14160 return true;
14163 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14164 const Expr* SubExpr = E->getSubExpr();
14166 switch (E->getCastKind()) {
14167 default:
14168 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14170 case CK_IntegralToFloating: {
14171 APSInt IntResult;
14172 const FPOptions FPO = E->getFPFeaturesInEffect(
14173 Info.Ctx.getLangOpts());
14174 return EvaluateInteger(SubExpr, IntResult, Info) &&
14175 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14176 IntResult, E->getType(), Result);
14179 case CK_FixedPointToFloating: {
14180 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14181 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14182 return false;
14183 Result =
14184 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14185 return true;
14188 case CK_FloatingCast: {
14189 if (!Visit(SubExpr))
14190 return false;
14191 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14192 Result);
14195 case CK_FloatingComplexToReal: {
14196 ComplexValue V;
14197 if (!EvaluateComplex(SubExpr, V, Info))
14198 return false;
14199 Result = V.getComplexFloatReal();
14200 return true;
14205 //===----------------------------------------------------------------------===//
14206 // Complex Evaluation (for float and integer)
14207 //===----------------------------------------------------------------------===//
14209 namespace {
14210 class ComplexExprEvaluator
14211 : public ExprEvaluatorBase<ComplexExprEvaluator> {
14212 ComplexValue &Result;
14214 public:
14215 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14216 : ExprEvaluatorBaseTy(info), Result(Result) {}
14218 bool Success(const APValue &V, const Expr *e) {
14219 Result.setFrom(V);
14220 return true;
14223 bool ZeroInitialization(const Expr *E);
14225 //===--------------------------------------------------------------------===//
14226 // Visitor Methods
14227 //===--------------------------------------------------------------------===//
14229 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14230 bool VisitCastExpr(const CastExpr *E);
14231 bool VisitBinaryOperator(const BinaryOperator *E);
14232 bool VisitUnaryOperator(const UnaryOperator *E);
14233 bool VisitInitListExpr(const InitListExpr *E);
14234 bool VisitCallExpr(const CallExpr *E);
14236 } // end anonymous namespace
14238 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14239 EvalInfo &Info) {
14240 assert(!E->isValueDependent());
14241 assert(E->isPRValue() && E->getType()->isAnyComplexType());
14242 return ComplexExprEvaluator(Info, Result).Visit(E);
14245 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14246 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14247 if (ElemTy->isRealFloatingType()) {
14248 Result.makeComplexFloat();
14249 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14250 Result.FloatReal = Zero;
14251 Result.FloatImag = Zero;
14252 } else {
14253 Result.makeComplexInt();
14254 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14255 Result.IntReal = Zero;
14256 Result.IntImag = Zero;
14258 return true;
14261 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14262 const Expr* SubExpr = E->getSubExpr();
14264 if (SubExpr->getType()->isRealFloatingType()) {
14265 Result.makeComplexFloat();
14266 APFloat &Imag = Result.FloatImag;
14267 if (!EvaluateFloat(SubExpr, Imag, Info))
14268 return false;
14270 Result.FloatReal = APFloat(Imag.getSemantics());
14271 return true;
14272 } else {
14273 assert(SubExpr->getType()->isIntegerType() &&
14274 "Unexpected imaginary literal.");
14276 Result.makeComplexInt();
14277 APSInt &Imag = Result.IntImag;
14278 if (!EvaluateInteger(SubExpr, Imag, Info))
14279 return false;
14281 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14282 return true;
14286 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14288 switch (E->getCastKind()) {
14289 case CK_BitCast:
14290 case CK_BaseToDerived:
14291 case CK_DerivedToBase:
14292 case CK_UncheckedDerivedToBase:
14293 case CK_Dynamic:
14294 case CK_ToUnion:
14295 case CK_ArrayToPointerDecay:
14296 case CK_FunctionToPointerDecay:
14297 case CK_NullToPointer:
14298 case CK_NullToMemberPointer:
14299 case CK_BaseToDerivedMemberPointer:
14300 case CK_DerivedToBaseMemberPointer:
14301 case CK_MemberPointerToBoolean:
14302 case CK_ReinterpretMemberPointer:
14303 case CK_ConstructorConversion:
14304 case CK_IntegralToPointer:
14305 case CK_PointerToIntegral:
14306 case CK_PointerToBoolean:
14307 case CK_ToVoid:
14308 case CK_VectorSplat:
14309 case CK_IntegralCast:
14310 case CK_BooleanToSignedIntegral:
14311 case CK_IntegralToBoolean:
14312 case CK_IntegralToFloating:
14313 case CK_FloatingToIntegral:
14314 case CK_FloatingToBoolean:
14315 case CK_FloatingCast:
14316 case CK_CPointerToObjCPointerCast:
14317 case CK_BlockPointerToObjCPointerCast:
14318 case CK_AnyPointerToBlockPointerCast:
14319 case CK_ObjCObjectLValueCast:
14320 case CK_FloatingComplexToReal:
14321 case CK_FloatingComplexToBoolean:
14322 case CK_IntegralComplexToReal:
14323 case CK_IntegralComplexToBoolean:
14324 case CK_ARCProduceObject:
14325 case CK_ARCConsumeObject:
14326 case CK_ARCReclaimReturnedObject:
14327 case CK_ARCExtendBlockObject:
14328 case CK_CopyAndAutoreleaseBlockObject:
14329 case CK_BuiltinFnToFnPtr:
14330 case CK_ZeroToOCLOpaqueType:
14331 case CK_NonAtomicToAtomic:
14332 case CK_AddressSpaceConversion:
14333 case CK_IntToOCLSampler:
14334 case CK_FloatingToFixedPoint:
14335 case CK_FixedPointToFloating:
14336 case CK_FixedPointCast:
14337 case CK_FixedPointToBoolean:
14338 case CK_FixedPointToIntegral:
14339 case CK_IntegralToFixedPoint:
14340 case CK_MatrixCast:
14341 llvm_unreachable("invalid cast kind for complex value");
14343 case CK_LValueToRValue:
14344 case CK_AtomicToNonAtomic:
14345 case CK_NoOp:
14346 case CK_LValueToRValueBitCast:
14347 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14349 case CK_Dependent:
14350 case CK_LValueBitCast:
14351 case CK_UserDefinedConversion:
14352 return Error(E);
14354 case CK_FloatingRealToComplex: {
14355 APFloat &Real = Result.FloatReal;
14356 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14357 return false;
14359 Result.makeComplexFloat();
14360 Result.FloatImag = APFloat(Real.getSemantics());
14361 return true;
14364 case CK_FloatingComplexCast: {
14365 if (!Visit(E->getSubExpr()))
14366 return false;
14368 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14369 QualType From
14370 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14372 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14373 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14376 case CK_FloatingComplexToIntegralComplex: {
14377 if (!Visit(E->getSubExpr()))
14378 return false;
14380 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14381 QualType From
14382 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14383 Result.makeComplexInt();
14384 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14385 To, Result.IntReal) &&
14386 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14387 To, Result.IntImag);
14390 case CK_IntegralRealToComplex: {
14391 APSInt &Real = Result.IntReal;
14392 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14393 return false;
14395 Result.makeComplexInt();
14396 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14397 return true;
14400 case CK_IntegralComplexCast: {
14401 if (!Visit(E->getSubExpr()))
14402 return false;
14404 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14405 QualType From
14406 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14408 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14409 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14410 return true;
14413 case CK_IntegralComplexToFloatingComplex: {
14414 if (!Visit(E->getSubExpr()))
14415 return false;
14417 const FPOptions FPO = E->getFPFeaturesInEffect(
14418 Info.Ctx.getLangOpts());
14419 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14420 QualType From
14421 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14422 Result.makeComplexFloat();
14423 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14424 To, Result.FloatReal) &&
14425 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14426 To, Result.FloatImag);
14430 llvm_unreachable("unknown cast resulting in complex value");
14433 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14434 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14435 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14437 // Track whether the LHS or RHS is real at the type system level. When this is
14438 // the case we can simplify our evaluation strategy.
14439 bool LHSReal = false, RHSReal = false;
14441 bool LHSOK;
14442 if (E->getLHS()->getType()->isRealFloatingType()) {
14443 LHSReal = true;
14444 APFloat &Real = Result.FloatReal;
14445 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14446 if (LHSOK) {
14447 Result.makeComplexFloat();
14448 Result.FloatImag = APFloat(Real.getSemantics());
14450 } else {
14451 LHSOK = Visit(E->getLHS());
14453 if (!LHSOK && !Info.noteFailure())
14454 return false;
14456 ComplexValue RHS;
14457 if (E->getRHS()->getType()->isRealFloatingType()) {
14458 RHSReal = true;
14459 APFloat &Real = RHS.FloatReal;
14460 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14461 return false;
14462 RHS.makeComplexFloat();
14463 RHS.FloatImag = APFloat(Real.getSemantics());
14464 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14465 return false;
14467 assert(!(LHSReal && RHSReal) &&
14468 "Cannot have both operands of a complex operation be real.");
14469 switch (E->getOpcode()) {
14470 default: return Error(E);
14471 case BO_Add:
14472 if (Result.isComplexFloat()) {
14473 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14474 APFloat::rmNearestTiesToEven);
14475 if (LHSReal)
14476 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14477 else if (!RHSReal)
14478 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14479 APFloat::rmNearestTiesToEven);
14480 } else {
14481 Result.getComplexIntReal() += RHS.getComplexIntReal();
14482 Result.getComplexIntImag() += RHS.getComplexIntImag();
14484 break;
14485 case BO_Sub:
14486 if (Result.isComplexFloat()) {
14487 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14488 APFloat::rmNearestTiesToEven);
14489 if (LHSReal) {
14490 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14491 Result.getComplexFloatImag().changeSign();
14492 } else if (!RHSReal) {
14493 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14494 APFloat::rmNearestTiesToEven);
14496 } else {
14497 Result.getComplexIntReal() -= RHS.getComplexIntReal();
14498 Result.getComplexIntImag() -= RHS.getComplexIntImag();
14500 break;
14501 case BO_Mul:
14502 if (Result.isComplexFloat()) {
14503 // This is an implementation of complex multiplication according to the
14504 // constraints laid out in C11 Annex G. The implementation uses the
14505 // following naming scheme:
14506 // (a + ib) * (c + id)
14507 ComplexValue LHS = Result;
14508 APFloat &A = LHS.getComplexFloatReal();
14509 APFloat &B = LHS.getComplexFloatImag();
14510 APFloat &C = RHS.getComplexFloatReal();
14511 APFloat &D = RHS.getComplexFloatImag();
14512 APFloat &ResR = Result.getComplexFloatReal();
14513 APFloat &ResI = Result.getComplexFloatImag();
14514 if (LHSReal) {
14515 assert(!RHSReal && "Cannot have two real operands for a complex op!");
14516 ResR = A * C;
14517 ResI = A * D;
14518 } else if (RHSReal) {
14519 ResR = C * A;
14520 ResI = C * B;
14521 } else {
14522 // In the fully general case, we need to handle NaNs and infinities
14523 // robustly.
14524 APFloat AC = A * C;
14525 APFloat BD = B * D;
14526 APFloat AD = A * D;
14527 APFloat BC = B * C;
14528 ResR = AC - BD;
14529 ResI = AD + BC;
14530 if (ResR.isNaN() && ResI.isNaN()) {
14531 bool Recalc = false;
14532 if (A.isInfinity() || B.isInfinity()) {
14533 A = APFloat::copySign(
14534 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14535 B = APFloat::copySign(
14536 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14537 if (C.isNaN())
14538 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14539 if (D.isNaN())
14540 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14541 Recalc = true;
14543 if (C.isInfinity() || D.isInfinity()) {
14544 C = APFloat::copySign(
14545 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14546 D = APFloat::copySign(
14547 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14548 if (A.isNaN())
14549 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14550 if (B.isNaN())
14551 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14552 Recalc = true;
14554 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14555 AD.isInfinity() || BC.isInfinity())) {
14556 if (A.isNaN())
14557 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14558 if (B.isNaN())
14559 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14560 if (C.isNaN())
14561 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14562 if (D.isNaN())
14563 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14564 Recalc = true;
14566 if (Recalc) {
14567 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14568 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14572 } else {
14573 ComplexValue LHS = Result;
14574 Result.getComplexIntReal() =
14575 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14576 LHS.getComplexIntImag() * RHS.getComplexIntImag());
14577 Result.getComplexIntImag() =
14578 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14579 LHS.getComplexIntImag() * RHS.getComplexIntReal());
14581 break;
14582 case BO_Div:
14583 if (Result.isComplexFloat()) {
14584 // This is an implementation of complex division according to the
14585 // constraints laid out in C11 Annex G. The implementation uses the
14586 // following naming scheme:
14587 // (a + ib) / (c + id)
14588 ComplexValue LHS = Result;
14589 APFloat &A = LHS.getComplexFloatReal();
14590 APFloat &B = LHS.getComplexFloatImag();
14591 APFloat &C = RHS.getComplexFloatReal();
14592 APFloat &D = RHS.getComplexFloatImag();
14593 APFloat &ResR = Result.getComplexFloatReal();
14594 APFloat &ResI = Result.getComplexFloatImag();
14595 if (RHSReal) {
14596 ResR = A / C;
14597 ResI = B / C;
14598 } else {
14599 if (LHSReal) {
14600 // No real optimizations we can do here, stub out with zero.
14601 B = APFloat::getZero(A.getSemantics());
14603 int DenomLogB = 0;
14604 APFloat MaxCD = maxnum(abs(C), abs(D));
14605 if (MaxCD.isFinite()) {
14606 DenomLogB = ilogb(MaxCD);
14607 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14608 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14610 APFloat Denom = C * C + D * D;
14611 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14612 APFloat::rmNearestTiesToEven);
14613 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14614 APFloat::rmNearestTiesToEven);
14615 if (ResR.isNaN() && ResI.isNaN()) {
14616 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14617 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14618 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14619 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14620 D.isFinite()) {
14621 A = APFloat::copySign(
14622 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14623 B = APFloat::copySign(
14624 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14625 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14626 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14627 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14628 C = APFloat::copySign(
14629 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14630 D = APFloat::copySign(
14631 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14632 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14633 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14637 } else {
14638 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14639 return Error(E, diag::note_expr_divide_by_zero);
14641 ComplexValue LHS = Result;
14642 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14643 RHS.getComplexIntImag() * RHS.getComplexIntImag();
14644 Result.getComplexIntReal() =
14645 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14646 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14647 Result.getComplexIntImag() =
14648 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14649 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14651 break;
14654 return true;
14657 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14658 // Get the operand value into 'Result'.
14659 if (!Visit(E->getSubExpr()))
14660 return false;
14662 switch (E->getOpcode()) {
14663 default:
14664 return Error(E);
14665 case UO_Extension:
14666 return true;
14667 case UO_Plus:
14668 // The result is always just the subexpr.
14669 return true;
14670 case UO_Minus:
14671 if (Result.isComplexFloat()) {
14672 Result.getComplexFloatReal().changeSign();
14673 Result.getComplexFloatImag().changeSign();
14675 else {
14676 Result.getComplexIntReal() = -Result.getComplexIntReal();
14677 Result.getComplexIntImag() = -Result.getComplexIntImag();
14679 return true;
14680 case UO_Not:
14681 if (Result.isComplexFloat())
14682 Result.getComplexFloatImag().changeSign();
14683 else
14684 Result.getComplexIntImag() = -Result.getComplexIntImag();
14685 return true;
14689 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14690 if (E->getNumInits() == 2) {
14691 if (E->getType()->isComplexType()) {
14692 Result.makeComplexFloat();
14693 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14694 return false;
14695 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14696 return false;
14697 } else {
14698 Result.makeComplexInt();
14699 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14700 return false;
14701 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14702 return false;
14704 return true;
14706 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14709 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14710 if (!IsConstantEvaluatedBuiltinCall(E))
14711 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14713 switch (E->getBuiltinCallee()) {
14714 case Builtin::BI__builtin_complex:
14715 Result.makeComplexFloat();
14716 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14717 return false;
14718 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14719 return false;
14720 return true;
14722 default:
14723 return false;
14727 //===----------------------------------------------------------------------===//
14728 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14729 // implicit conversion.
14730 //===----------------------------------------------------------------------===//
14732 namespace {
14733 class AtomicExprEvaluator :
14734 public ExprEvaluatorBase<AtomicExprEvaluator> {
14735 const LValue *This;
14736 APValue &Result;
14737 public:
14738 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14739 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14741 bool Success(const APValue &V, const Expr *E) {
14742 Result = V;
14743 return true;
14746 bool ZeroInitialization(const Expr *E) {
14747 ImplicitValueInitExpr VIE(
14748 E->getType()->castAs<AtomicType>()->getValueType());
14749 // For atomic-qualified class (and array) types in C++, initialize the
14750 // _Atomic-wrapped subobject directly, in-place.
14751 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14752 : Evaluate(Result, Info, &VIE);
14755 bool VisitCastExpr(const CastExpr *E) {
14756 switch (E->getCastKind()) {
14757 default:
14758 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14759 case CK_NonAtomicToAtomic:
14760 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14761 : Evaluate(Result, Info, E->getSubExpr());
14765 } // end anonymous namespace
14767 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14768 EvalInfo &Info) {
14769 assert(!E->isValueDependent());
14770 assert(E->isPRValue() && E->getType()->isAtomicType());
14771 return AtomicExprEvaluator(Info, This, Result).Visit(E);
14774 //===----------------------------------------------------------------------===//
14775 // Void expression evaluation, primarily for a cast to void on the LHS of a
14776 // comma operator
14777 //===----------------------------------------------------------------------===//
14779 namespace {
14780 class VoidExprEvaluator
14781 : public ExprEvaluatorBase<VoidExprEvaluator> {
14782 public:
14783 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14785 bool Success(const APValue &V, const Expr *e) { return true; }
14787 bool ZeroInitialization(const Expr *E) { return true; }
14789 bool VisitCastExpr(const CastExpr *E) {
14790 switch (E->getCastKind()) {
14791 default:
14792 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14793 case CK_ToVoid:
14794 VisitIgnoredValue(E->getSubExpr());
14795 return true;
14799 bool VisitCallExpr(const CallExpr *E) {
14800 if (!IsConstantEvaluatedBuiltinCall(E))
14801 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14803 switch (E->getBuiltinCallee()) {
14804 case Builtin::BI__assume:
14805 case Builtin::BI__builtin_assume:
14806 // The argument is not evaluated!
14807 return true;
14809 case Builtin::BI__builtin_operator_delete:
14810 return HandleOperatorDeleteCall(Info, E);
14812 default:
14813 return false;
14817 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14819 } // end anonymous namespace
14821 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14822 // We cannot speculatively evaluate a delete expression.
14823 if (Info.SpeculativeEvaluationDepth)
14824 return false;
14826 FunctionDecl *OperatorDelete = E->getOperatorDelete();
14827 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14828 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14829 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14830 return false;
14833 const Expr *Arg = E->getArgument();
14835 LValue Pointer;
14836 if (!EvaluatePointer(Arg, Pointer, Info))
14837 return false;
14838 if (Pointer.Designator.Invalid)
14839 return false;
14841 // Deleting a null pointer has no effect.
14842 if (Pointer.isNullPointer()) {
14843 // This is the only case where we need to produce an extension warning:
14844 // the only other way we can succeed is if we find a dynamic allocation,
14845 // and we will have warned when we allocated it in that case.
14846 if (!Info.getLangOpts().CPlusPlus20)
14847 Info.CCEDiag(E, diag::note_constexpr_new);
14848 return true;
14851 Optional<DynAlloc *> Alloc = CheckDeleteKind(
14852 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14853 if (!Alloc)
14854 return false;
14855 QualType AllocType = Pointer.Base.getDynamicAllocType();
14857 // For the non-array case, the designator must be empty if the static type
14858 // does not have a virtual destructor.
14859 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14860 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14861 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14862 << Arg->getType()->getPointeeType() << AllocType;
14863 return false;
14866 // For a class type with a virtual destructor, the selected operator delete
14867 // is the one looked up when building the destructor.
14868 if (!E->isArrayForm() && !E->isGlobalDelete()) {
14869 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14870 if (VirtualDelete &&
14871 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14872 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14873 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14874 return false;
14878 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14879 (*Alloc)->Value, AllocType))
14880 return false;
14882 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14883 // The element was already erased. This means the destructor call also
14884 // deleted the object.
14885 // FIXME: This probably results in undefined behavior before we get this
14886 // far, and should be diagnosed elsewhere first.
14887 Info.FFDiag(E, diag::note_constexpr_double_delete);
14888 return false;
14891 return true;
14894 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14895 assert(!E->isValueDependent());
14896 assert(E->isPRValue() && E->getType()->isVoidType());
14897 return VoidExprEvaluator(Info).Visit(E);
14900 //===----------------------------------------------------------------------===//
14901 // Top level Expr::EvaluateAsRValue method.
14902 //===----------------------------------------------------------------------===//
14904 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14905 assert(!E->isValueDependent());
14906 // In C, function designators are not lvalues, but we evaluate them as if they
14907 // are.
14908 QualType T = E->getType();
14909 if (E->isGLValue() || T->isFunctionType()) {
14910 LValue LV;
14911 if (!EvaluateLValue(E, LV, Info))
14912 return false;
14913 LV.moveInto(Result);
14914 } else if (T->isVectorType()) {
14915 if (!EvaluateVector(E, Result, Info))
14916 return false;
14917 } else if (T->isIntegralOrEnumerationType()) {
14918 if (!IntExprEvaluator(Info, Result).Visit(E))
14919 return false;
14920 } else if (T->hasPointerRepresentation()) {
14921 LValue LV;
14922 if (!EvaluatePointer(E, LV, Info))
14923 return false;
14924 LV.moveInto(Result);
14925 } else if (T->isRealFloatingType()) {
14926 llvm::APFloat F(0.0);
14927 if (!EvaluateFloat(E, F, Info))
14928 return false;
14929 Result = APValue(F);
14930 } else if (T->isAnyComplexType()) {
14931 ComplexValue C;
14932 if (!EvaluateComplex(E, C, Info))
14933 return false;
14934 C.moveInto(Result);
14935 } else if (T->isFixedPointType()) {
14936 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14937 } else if (T->isMemberPointerType()) {
14938 MemberPtr P;
14939 if (!EvaluateMemberPointer(E, P, Info))
14940 return false;
14941 P.moveInto(Result);
14942 return true;
14943 } else if (T->isArrayType()) {
14944 LValue LV;
14945 APValue &Value =
14946 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14947 if (!EvaluateArray(E, LV, Value, Info))
14948 return false;
14949 Result = Value;
14950 } else if (T->isRecordType()) {
14951 LValue LV;
14952 APValue &Value =
14953 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14954 if (!EvaluateRecord(E, LV, Value, Info))
14955 return false;
14956 Result = Value;
14957 } else if (T->isVoidType()) {
14958 if (!Info.getLangOpts().CPlusPlus11)
14959 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14960 << E->getType();
14961 if (!EvaluateVoid(E, Info))
14962 return false;
14963 } else if (T->isAtomicType()) {
14964 QualType Unqual = T.getAtomicUnqualifiedType();
14965 if (Unqual->isArrayType() || Unqual->isRecordType()) {
14966 LValue LV;
14967 APValue &Value = Info.CurrentCall->createTemporary(
14968 E, Unqual, ScopeKind::FullExpression, LV);
14969 if (!EvaluateAtomic(E, &LV, Value, Info))
14970 return false;
14971 } else {
14972 if (!EvaluateAtomic(E, nullptr, Result, Info))
14973 return false;
14975 } else if (Info.getLangOpts().CPlusPlus11) {
14976 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14977 return false;
14978 } else {
14979 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14980 return false;
14983 return true;
14986 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14987 /// cases, the in-place evaluation is essential, since later initializers for
14988 /// an object can indirectly refer to subobjects which were initialized earlier.
14989 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14990 const Expr *E, bool AllowNonLiteralTypes) {
14991 assert(!E->isValueDependent());
14993 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14994 return false;
14996 if (E->isPRValue()) {
14997 // Evaluate arrays and record types in-place, so that later initializers can
14998 // refer to earlier-initialized members of the object.
14999 QualType T = E->getType();
15000 if (T->isArrayType())
15001 return EvaluateArray(E, This, Result, Info);
15002 else if (T->isRecordType())
15003 return EvaluateRecord(E, This, Result, Info);
15004 else if (T->isAtomicType()) {
15005 QualType Unqual = T.getAtomicUnqualifiedType();
15006 if (Unqual->isArrayType() || Unqual->isRecordType())
15007 return EvaluateAtomic(E, &This, Result, Info);
15011 // For any other type, in-place evaluation is unimportant.
15012 return Evaluate(Result, Info, E);
15015 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15016 /// lvalue-to-rvalue cast if it is an lvalue.
15017 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15018 assert(!E->isValueDependent());
15020 if (E->getType().isNull())
15021 return false;
15023 if (!CheckLiteralType(Info, E))
15024 return false;
15026 if (Info.EnableNewConstInterp) {
15027 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15028 return false;
15029 } else {
15030 if (!::Evaluate(Result, Info, E))
15031 return false;
15034 // Implicit lvalue-to-rvalue cast.
15035 if (E->isGLValue()) {
15036 LValue LV;
15037 LV.setFrom(Info.Ctx, Result);
15038 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15039 return false;
15042 // Check this core constant expression is a constant expression.
15043 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15044 ConstantExprKind::Normal) &&
15045 CheckMemoryLeaks(Info);
15048 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15049 const ASTContext &Ctx, bool &IsConst) {
15050 // Fast-path evaluations of integer literals, since we sometimes see files
15051 // containing vast quantities of these.
15052 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15053 Result.Val = APValue(APSInt(L->getValue(),
15054 L->getType()->isUnsignedIntegerType()));
15055 IsConst = true;
15056 return true;
15059 // This case should be rare, but we need to check it before we check on
15060 // the type below.
15061 if (Exp->getType().isNull()) {
15062 IsConst = false;
15063 return true;
15066 // FIXME: Evaluating values of large array and record types can cause
15067 // performance problems. Only do so in C++11 for now.
15068 if (Exp->isPRValue() &&
15069 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15070 !Ctx.getLangOpts().CPlusPlus11) {
15071 IsConst = false;
15072 return true;
15074 return false;
15077 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15078 Expr::SideEffectsKind SEK) {
15079 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15080 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15083 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15084 const ASTContext &Ctx, EvalInfo &Info) {
15085 assert(!E->isValueDependent());
15086 bool IsConst;
15087 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15088 return IsConst;
15090 return EvaluateAsRValue(Info, E, Result.Val);
15093 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15094 const ASTContext &Ctx,
15095 Expr::SideEffectsKind AllowSideEffects,
15096 EvalInfo &Info) {
15097 assert(!E->isValueDependent());
15098 if (!E->getType()->isIntegralOrEnumerationType())
15099 return false;
15101 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15102 !ExprResult.Val.isInt() ||
15103 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15104 return false;
15106 return true;
15109 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15110 const ASTContext &Ctx,
15111 Expr::SideEffectsKind AllowSideEffects,
15112 EvalInfo &Info) {
15113 assert(!E->isValueDependent());
15114 if (!E->getType()->isFixedPointType())
15115 return false;
15117 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15118 return false;
15120 if (!ExprResult.Val.isFixedPoint() ||
15121 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15122 return false;
15124 return true;
15127 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15128 /// any crazy technique (that has nothing to do with language standards) that
15129 /// we want to. If this function returns true, it returns the folded constant
15130 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15131 /// will be applied to the result.
15132 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15133 bool InConstantContext) const {
15134 assert(!isValueDependent() &&
15135 "Expression evaluator can't be called on a dependent expression.");
15136 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15137 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15138 Info.InConstantContext = InConstantContext;
15139 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15142 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15143 bool InConstantContext) const {
15144 assert(!isValueDependent() &&
15145 "Expression evaluator can't be called on a dependent expression.");
15146 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15147 EvalResult Scratch;
15148 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15149 HandleConversionToBool(Scratch.Val, Result);
15152 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15153 SideEffectsKind AllowSideEffects,
15154 bool InConstantContext) const {
15155 assert(!isValueDependent() &&
15156 "Expression evaluator can't be called on a dependent expression.");
15157 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15158 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15159 Info.InConstantContext = InConstantContext;
15160 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15163 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15164 SideEffectsKind AllowSideEffects,
15165 bool InConstantContext) const {
15166 assert(!isValueDependent() &&
15167 "Expression evaluator can't be called on a dependent expression.");
15168 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15169 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15170 Info.InConstantContext = InConstantContext;
15171 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15174 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15175 SideEffectsKind AllowSideEffects,
15176 bool InConstantContext) const {
15177 assert(!isValueDependent() &&
15178 "Expression evaluator can't be called on a dependent expression.");
15180 if (!getType()->isRealFloatingType())
15181 return false;
15183 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15184 EvalResult ExprResult;
15185 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15186 !ExprResult.Val.isFloat() ||
15187 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15188 return false;
15190 Result = ExprResult.Val.getFloat();
15191 return true;
15194 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15195 bool InConstantContext) const {
15196 assert(!isValueDependent() &&
15197 "Expression evaluator can't be called on a dependent expression.");
15199 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15200 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15201 Info.InConstantContext = InConstantContext;
15202 LValue LV;
15203 CheckedTemporaries CheckedTemps;
15204 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15205 Result.HasSideEffects ||
15206 !CheckLValueConstantExpression(Info, getExprLoc(),
15207 Ctx.getLValueReferenceType(getType()), LV,
15208 ConstantExprKind::Normal, CheckedTemps))
15209 return false;
15211 LV.moveInto(Result.Val);
15212 return true;
15215 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15216 APValue DestroyedValue, QualType Type,
15217 SourceLocation Loc, Expr::EvalStatus &EStatus,
15218 bool IsConstantDestruction) {
15219 EvalInfo Info(Ctx, EStatus,
15220 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15221 : EvalInfo::EM_ConstantFold);
15222 Info.setEvaluatingDecl(Base, DestroyedValue,
15223 EvalInfo::EvaluatingDeclKind::Dtor);
15224 Info.InConstantContext = IsConstantDestruction;
15226 LValue LVal;
15227 LVal.set(Base);
15229 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15230 EStatus.HasSideEffects)
15231 return false;
15233 if (!Info.discardCleanups())
15234 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15236 return true;
15239 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15240 ConstantExprKind Kind) const {
15241 assert(!isValueDependent() &&
15242 "Expression evaluator can't be called on a dependent expression.");
15244 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15245 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15246 EvalInfo Info(Ctx, Result, EM);
15247 Info.InConstantContext = true;
15249 // The type of the object we're initializing is 'const T' for a class NTTP.
15250 QualType T = getType();
15251 if (Kind == ConstantExprKind::ClassTemplateArgument)
15252 T.addConst();
15254 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15255 // represent the result of the evaluation. CheckConstantExpression ensures
15256 // this doesn't escape.
15257 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15258 APValue::LValueBase Base(&BaseMTE);
15260 Info.setEvaluatingDecl(Base, Result.Val);
15261 LValue LVal;
15262 LVal.set(Base);
15264 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15265 return false;
15267 if (!Info.discardCleanups())
15268 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15270 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15271 Result.Val, Kind))
15272 return false;
15273 if (!CheckMemoryLeaks(Info))
15274 return false;
15276 // If this is a class template argument, it's required to have constant
15277 // destruction too.
15278 if (Kind == ConstantExprKind::ClassTemplateArgument &&
15279 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15280 true) ||
15281 Result.HasSideEffects)) {
15282 // FIXME: Prefix a note to indicate that the problem is lack of constant
15283 // destruction.
15284 return false;
15287 return true;
15290 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15291 const VarDecl *VD,
15292 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15293 bool IsConstantInitialization) const {
15294 assert(!isValueDependent() &&
15295 "Expression evaluator can't be called on a dependent expression.");
15297 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15298 std::string Name;
15299 llvm::raw_string_ostream OS(Name);
15300 VD->printQualifiedName(OS);
15301 return Name;
15304 // FIXME: Evaluating initializers for large array and record types can cause
15305 // performance problems. Only do so in C++11 for now.
15306 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15307 !Ctx.getLangOpts().CPlusPlus11)
15308 return false;
15310 Expr::EvalStatus EStatus;
15311 EStatus.Diag = &Notes;
15313 EvalInfo Info(Ctx, EStatus,
15314 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15315 ? EvalInfo::EM_ConstantExpression
15316 : EvalInfo::EM_ConstantFold);
15317 Info.setEvaluatingDecl(VD, Value);
15318 Info.InConstantContext = IsConstantInitialization;
15320 SourceLocation DeclLoc = VD->getLocation();
15321 QualType DeclTy = VD->getType();
15323 if (Info.EnableNewConstInterp) {
15324 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15325 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15326 return false;
15327 } else {
15328 LValue LVal;
15329 LVal.set(VD);
15331 if (!EvaluateInPlace(Value, Info, LVal, this,
15332 /*AllowNonLiteralTypes=*/true) ||
15333 EStatus.HasSideEffects)
15334 return false;
15336 // At this point, any lifetime-extended temporaries are completely
15337 // initialized.
15338 Info.performLifetimeExtension();
15340 if (!Info.discardCleanups())
15341 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15343 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15344 ConstantExprKind::Normal) &&
15345 CheckMemoryLeaks(Info);
15348 bool VarDecl::evaluateDestruction(
15349 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15350 Expr::EvalStatus EStatus;
15351 EStatus.Diag = &Notes;
15353 // Only treat the destruction as constant destruction if we formally have
15354 // constant initialization (or are usable in a constant expression).
15355 bool IsConstantDestruction = hasConstantInitialization();
15357 // Make a copy of the value for the destructor to mutate, if we know it.
15358 // Otherwise, treat the value as default-initialized; if the destructor works
15359 // anyway, then the destruction is constant (and must be essentially empty).
15360 APValue DestroyedValue;
15361 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15362 DestroyedValue = *getEvaluatedValue();
15363 else if (!getDefaultInitValue(getType(), DestroyedValue))
15364 return false;
15366 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15367 getType(), getLocation(), EStatus,
15368 IsConstantDestruction) ||
15369 EStatus.HasSideEffects)
15370 return false;
15372 ensureEvaluatedStmt()->HasConstantDestruction = true;
15373 return true;
15376 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15377 /// constant folded, but discard the result.
15378 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15379 assert(!isValueDependent() &&
15380 "Expression evaluator can't be called on a dependent expression.");
15382 EvalResult Result;
15383 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15384 !hasUnacceptableSideEffect(Result, SEK);
15387 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15388 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15389 assert(!isValueDependent() &&
15390 "Expression evaluator can't be called on a dependent expression.");
15392 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15393 EvalResult EVResult;
15394 EVResult.Diag = Diag;
15395 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15396 Info.InConstantContext = true;
15398 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15399 (void)Result;
15400 assert(Result && "Could not evaluate expression");
15401 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15403 return EVResult.Val.getInt();
15406 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15407 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15408 assert(!isValueDependent() &&
15409 "Expression evaluator can't be called on a dependent expression.");
15411 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15412 EvalResult EVResult;
15413 EVResult.Diag = Diag;
15414 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15415 Info.InConstantContext = true;
15416 Info.CheckingForUndefinedBehavior = true;
15418 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15419 (void)Result;
15420 assert(Result && "Could not evaluate expression");
15421 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15423 return EVResult.Val.getInt();
15426 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15427 assert(!isValueDependent() &&
15428 "Expression evaluator can't be called on a dependent expression.");
15430 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15431 bool IsConst;
15432 EvalResult EVResult;
15433 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15434 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15435 Info.CheckingForUndefinedBehavior = true;
15436 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15440 bool Expr::EvalResult::isGlobalLValue() const {
15441 assert(Val.isLValue());
15442 return IsGlobalLValue(Val.getLValueBase());
15445 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15446 /// an integer constant expression.
15448 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15449 /// comma, etc
15451 // CheckICE - This function does the fundamental ICE checking: the returned
15452 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15453 // and a (possibly null) SourceLocation indicating the location of the problem.
15455 // Note that to reduce code duplication, this helper does no evaluation
15456 // itself; the caller checks whether the expression is evaluatable, and
15457 // in the rare cases where CheckICE actually cares about the evaluated
15458 // value, it calls into Evaluate.
15460 namespace {
15462 enum ICEKind {
15463 /// This expression is an ICE.
15464 IK_ICE,
15465 /// This expression is not an ICE, but if it isn't evaluated, it's
15466 /// a legal subexpression for an ICE. This return value is used to handle
15467 /// the comma operator in C99 mode, and non-constant subexpressions.
15468 IK_ICEIfUnevaluated,
15469 /// This expression is not an ICE, and is not a legal subexpression for one.
15470 IK_NotICE
15473 struct ICEDiag {
15474 ICEKind Kind;
15475 SourceLocation Loc;
15477 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15482 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15484 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15486 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15487 Expr::EvalResult EVResult;
15488 Expr::EvalStatus Status;
15489 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15491 Info.InConstantContext = true;
15492 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15493 !EVResult.Val.isInt())
15494 return ICEDiag(IK_NotICE, E->getBeginLoc());
15496 return NoDiag();
15499 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15500 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15501 if (!E->getType()->isIntegralOrEnumerationType())
15502 return ICEDiag(IK_NotICE, E->getBeginLoc());
15504 switch (E->getStmtClass()) {
15505 #define ABSTRACT_STMT(Node)
15506 #define STMT(Node, Base) case Expr::Node##Class:
15507 #define EXPR(Node, Base)
15508 #include "clang/AST/StmtNodes.inc"
15509 case Expr::PredefinedExprClass:
15510 case Expr::FloatingLiteralClass:
15511 case Expr::ImaginaryLiteralClass:
15512 case Expr::StringLiteralClass:
15513 case Expr::ArraySubscriptExprClass:
15514 case Expr::MatrixSubscriptExprClass:
15515 case Expr::OMPArraySectionExprClass:
15516 case Expr::OMPArrayShapingExprClass:
15517 case Expr::OMPIteratorExprClass:
15518 case Expr::MemberExprClass:
15519 case Expr::CompoundAssignOperatorClass:
15520 case Expr::CompoundLiteralExprClass:
15521 case Expr::ExtVectorElementExprClass:
15522 case Expr::DesignatedInitExprClass:
15523 case Expr::ArrayInitLoopExprClass:
15524 case Expr::ArrayInitIndexExprClass:
15525 case Expr::NoInitExprClass:
15526 case Expr::DesignatedInitUpdateExprClass:
15527 case Expr::ImplicitValueInitExprClass:
15528 case Expr::ParenListExprClass:
15529 case Expr::VAArgExprClass:
15530 case Expr::AddrLabelExprClass:
15531 case Expr::StmtExprClass:
15532 case Expr::CXXMemberCallExprClass:
15533 case Expr::CUDAKernelCallExprClass:
15534 case Expr::CXXAddrspaceCastExprClass:
15535 case Expr::CXXDynamicCastExprClass:
15536 case Expr::CXXTypeidExprClass:
15537 case Expr::CXXUuidofExprClass:
15538 case Expr::MSPropertyRefExprClass:
15539 case Expr::MSPropertySubscriptExprClass:
15540 case Expr::CXXNullPtrLiteralExprClass:
15541 case Expr::UserDefinedLiteralClass:
15542 case Expr::CXXThisExprClass:
15543 case Expr::CXXThrowExprClass:
15544 case Expr::CXXNewExprClass:
15545 case Expr::CXXDeleteExprClass:
15546 case Expr::CXXPseudoDestructorExprClass:
15547 case Expr::UnresolvedLookupExprClass:
15548 case Expr::TypoExprClass:
15549 case Expr::RecoveryExprClass:
15550 case Expr::DependentScopeDeclRefExprClass:
15551 case Expr::CXXConstructExprClass:
15552 case Expr::CXXInheritedCtorInitExprClass:
15553 case Expr::CXXStdInitializerListExprClass:
15554 case Expr::CXXBindTemporaryExprClass:
15555 case Expr::ExprWithCleanupsClass:
15556 case Expr::CXXTemporaryObjectExprClass:
15557 case Expr::CXXUnresolvedConstructExprClass:
15558 case Expr::CXXDependentScopeMemberExprClass:
15559 case Expr::UnresolvedMemberExprClass:
15560 case Expr::ObjCStringLiteralClass:
15561 case Expr::ObjCBoxedExprClass:
15562 case Expr::ObjCArrayLiteralClass:
15563 case Expr::ObjCDictionaryLiteralClass:
15564 case Expr::ObjCEncodeExprClass:
15565 case Expr::ObjCMessageExprClass:
15566 case Expr::ObjCSelectorExprClass:
15567 case Expr::ObjCProtocolExprClass:
15568 case Expr::ObjCIvarRefExprClass:
15569 case Expr::ObjCPropertyRefExprClass:
15570 case Expr::ObjCSubscriptRefExprClass:
15571 case Expr::ObjCIsaExprClass:
15572 case Expr::ObjCAvailabilityCheckExprClass:
15573 case Expr::ShuffleVectorExprClass:
15574 case Expr::ConvertVectorExprClass:
15575 case Expr::BlockExprClass:
15576 case Expr::NoStmtClass:
15577 case Expr::OpaqueValueExprClass:
15578 case Expr::PackExpansionExprClass:
15579 case Expr::SubstNonTypeTemplateParmPackExprClass:
15580 case Expr::FunctionParmPackExprClass:
15581 case Expr::AsTypeExprClass:
15582 case Expr::ObjCIndirectCopyRestoreExprClass:
15583 case Expr::MaterializeTemporaryExprClass:
15584 case Expr::PseudoObjectExprClass:
15585 case Expr::AtomicExprClass:
15586 case Expr::LambdaExprClass:
15587 case Expr::CXXFoldExprClass:
15588 case Expr::CoawaitExprClass:
15589 case Expr::DependentCoawaitExprClass:
15590 case Expr::CoyieldExprClass:
15591 case Expr::SYCLUniqueStableNameExprClass:
15592 return ICEDiag(IK_NotICE, E->getBeginLoc());
15594 case Expr::InitListExprClass: {
15595 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15596 // form "T x = { a };" is equivalent to "T x = a;".
15597 // Unless we're initializing a reference, T is a scalar as it is known to be
15598 // of integral or enumeration type.
15599 if (E->isPRValue())
15600 if (cast<InitListExpr>(E)->getNumInits() == 1)
15601 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15602 return ICEDiag(IK_NotICE, E->getBeginLoc());
15605 case Expr::SizeOfPackExprClass:
15606 case Expr::GNUNullExprClass:
15607 case Expr::SourceLocExprClass:
15608 return NoDiag();
15610 case Expr::SubstNonTypeTemplateParmExprClass:
15611 return
15612 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15614 case Expr::ConstantExprClass:
15615 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15617 case Expr::ParenExprClass:
15618 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15619 case Expr::GenericSelectionExprClass:
15620 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15621 case Expr::IntegerLiteralClass:
15622 case Expr::FixedPointLiteralClass:
15623 case Expr::CharacterLiteralClass:
15624 case Expr::ObjCBoolLiteralExprClass:
15625 case Expr::CXXBoolLiteralExprClass:
15626 case Expr::CXXScalarValueInitExprClass:
15627 case Expr::TypeTraitExprClass:
15628 case Expr::ConceptSpecializationExprClass:
15629 case Expr::RequiresExprClass:
15630 case Expr::ArrayTypeTraitExprClass:
15631 case Expr::ExpressionTraitExprClass:
15632 case Expr::CXXNoexceptExprClass:
15633 return NoDiag();
15634 case Expr::CallExprClass:
15635 case Expr::CXXOperatorCallExprClass: {
15636 // C99 6.6/3 allows function calls within unevaluated subexpressions of
15637 // constant expressions, but they can never be ICEs because an ICE cannot
15638 // contain an operand of (pointer to) function type.
15639 const CallExpr *CE = cast<CallExpr>(E);
15640 if (CE->getBuiltinCallee())
15641 return CheckEvalInICE(E, Ctx);
15642 return ICEDiag(IK_NotICE, E->getBeginLoc());
15644 case Expr::CXXRewrittenBinaryOperatorClass:
15645 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15646 Ctx);
15647 case Expr::DeclRefExprClass: {
15648 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15649 if (isa<EnumConstantDecl>(D))
15650 return NoDiag();
15652 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15653 // integer variables in constant expressions:
15655 // C++ 7.1.5.1p2
15656 // A variable of non-volatile const-qualified integral or enumeration
15657 // type initialized by an ICE can be used in ICEs.
15659 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15660 // that mode, use of reference variables should not be allowed.
15661 const VarDecl *VD = dyn_cast<VarDecl>(D);
15662 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15663 !VD->getType()->isReferenceType())
15664 return NoDiag();
15666 return ICEDiag(IK_NotICE, E->getBeginLoc());
15668 case Expr::UnaryOperatorClass: {
15669 const UnaryOperator *Exp = cast<UnaryOperator>(E);
15670 switch (Exp->getOpcode()) {
15671 case UO_PostInc:
15672 case UO_PostDec:
15673 case UO_PreInc:
15674 case UO_PreDec:
15675 case UO_AddrOf:
15676 case UO_Deref:
15677 case UO_Coawait:
15678 // C99 6.6/3 allows increment and decrement within unevaluated
15679 // subexpressions of constant expressions, but they can never be ICEs
15680 // because an ICE cannot contain an lvalue operand.
15681 return ICEDiag(IK_NotICE, E->getBeginLoc());
15682 case UO_Extension:
15683 case UO_LNot:
15684 case UO_Plus:
15685 case UO_Minus:
15686 case UO_Not:
15687 case UO_Real:
15688 case UO_Imag:
15689 return CheckICE(Exp->getSubExpr(), Ctx);
15691 llvm_unreachable("invalid unary operator class");
15693 case Expr::OffsetOfExprClass: {
15694 // Note that per C99, offsetof must be an ICE. And AFAIK, using
15695 // EvaluateAsRValue matches the proposed gcc behavior for cases like
15696 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
15697 // compliance: we should warn earlier for offsetof expressions with
15698 // array subscripts that aren't ICEs, and if the array subscripts
15699 // are ICEs, the value of the offsetof must be an integer constant.
15700 return CheckEvalInICE(E, Ctx);
15702 case Expr::UnaryExprOrTypeTraitExprClass: {
15703 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15704 if ((Exp->getKind() == UETT_SizeOf) &&
15705 Exp->getTypeOfArgument()->isVariableArrayType())
15706 return ICEDiag(IK_NotICE, E->getBeginLoc());
15707 return NoDiag();
15709 case Expr::BinaryOperatorClass: {
15710 const BinaryOperator *Exp = cast<BinaryOperator>(E);
15711 switch (Exp->getOpcode()) {
15712 case BO_PtrMemD:
15713 case BO_PtrMemI:
15714 case BO_Assign:
15715 case BO_MulAssign:
15716 case BO_DivAssign:
15717 case BO_RemAssign:
15718 case BO_AddAssign:
15719 case BO_SubAssign:
15720 case BO_ShlAssign:
15721 case BO_ShrAssign:
15722 case BO_AndAssign:
15723 case BO_XorAssign:
15724 case BO_OrAssign:
15725 // C99 6.6/3 allows assignments within unevaluated subexpressions of
15726 // constant expressions, but they can never be ICEs because an ICE cannot
15727 // contain an lvalue operand.
15728 return ICEDiag(IK_NotICE, E->getBeginLoc());
15730 case BO_Mul:
15731 case BO_Div:
15732 case BO_Rem:
15733 case BO_Add:
15734 case BO_Sub:
15735 case BO_Shl:
15736 case BO_Shr:
15737 case BO_LT:
15738 case BO_GT:
15739 case BO_LE:
15740 case BO_GE:
15741 case BO_EQ:
15742 case BO_NE:
15743 case BO_And:
15744 case BO_Xor:
15745 case BO_Or:
15746 case BO_Comma:
15747 case BO_Cmp: {
15748 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15749 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15750 if (Exp->getOpcode() == BO_Div ||
15751 Exp->getOpcode() == BO_Rem) {
15752 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15753 // we don't evaluate one.
15754 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15755 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15756 if (REval == 0)
15757 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15758 if (REval.isSigned() && REval.isAllOnes()) {
15759 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15760 if (LEval.isMinSignedValue())
15761 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15765 if (Exp->getOpcode() == BO_Comma) {
15766 if (Ctx.getLangOpts().C99) {
15767 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15768 // if it isn't evaluated.
15769 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15770 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15771 } else {
15772 // In both C89 and C++, commas in ICEs are illegal.
15773 return ICEDiag(IK_NotICE, E->getBeginLoc());
15776 return Worst(LHSResult, RHSResult);
15778 case BO_LAnd:
15779 case BO_LOr: {
15780 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15781 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15782 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15783 // Rare case where the RHS has a comma "side-effect"; we need
15784 // to actually check the condition to see whether the side
15785 // with the comma is evaluated.
15786 if ((Exp->getOpcode() == BO_LAnd) !=
15787 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15788 return RHSResult;
15789 return NoDiag();
15792 return Worst(LHSResult, RHSResult);
15795 llvm_unreachable("invalid binary operator kind");
15797 case Expr::ImplicitCastExprClass:
15798 case Expr::CStyleCastExprClass:
15799 case Expr::CXXFunctionalCastExprClass:
15800 case Expr::CXXStaticCastExprClass:
15801 case Expr::CXXReinterpretCastExprClass:
15802 case Expr::CXXConstCastExprClass:
15803 case Expr::ObjCBridgedCastExprClass: {
15804 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15805 if (isa<ExplicitCastExpr>(E)) {
15806 if (const FloatingLiteral *FL
15807 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15808 unsigned DestWidth = Ctx.getIntWidth(E->getType());
15809 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15810 APSInt IgnoredVal(DestWidth, !DestSigned);
15811 bool Ignored;
15812 // If the value does not fit in the destination type, the behavior is
15813 // undefined, so we are not required to treat it as a constant
15814 // expression.
15815 if (FL->getValue().convertToInteger(IgnoredVal,
15816 llvm::APFloat::rmTowardZero,
15817 &Ignored) & APFloat::opInvalidOp)
15818 return ICEDiag(IK_NotICE, E->getBeginLoc());
15819 return NoDiag();
15822 switch (cast<CastExpr>(E)->getCastKind()) {
15823 case CK_LValueToRValue:
15824 case CK_AtomicToNonAtomic:
15825 case CK_NonAtomicToAtomic:
15826 case CK_NoOp:
15827 case CK_IntegralToBoolean:
15828 case CK_IntegralCast:
15829 return CheckICE(SubExpr, Ctx);
15830 default:
15831 return ICEDiag(IK_NotICE, E->getBeginLoc());
15834 case Expr::BinaryConditionalOperatorClass: {
15835 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15836 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15837 if (CommonResult.Kind == IK_NotICE) return CommonResult;
15838 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15839 if (FalseResult.Kind == IK_NotICE) return FalseResult;
15840 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15841 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15842 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15843 return FalseResult;
15845 case Expr::ConditionalOperatorClass: {
15846 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15847 // If the condition (ignoring parens) is a __builtin_constant_p call,
15848 // then only the true side is actually considered in an integer constant
15849 // expression, and it is fully evaluated. This is an important GNU
15850 // extension. See GCC PR38377 for discussion.
15851 if (const CallExpr *CallCE
15852 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15853 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15854 return CheckEvalInICE(E, Ctx);
15855 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15856 if (CondResult.Kind == IK_NotICE)
15857 return CondResult;
15859 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15860 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15862 if (TrueResult.Kind == IK_NotICE)
15863 return TrueResult;
15864 if (FalseResult.Kind == IK_NotICE)
15865 return FalseResult;
15866 if (CondResult.Kind == IK_ICEIfUnevaluated)
15867 return CondResult;
15868 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15869 return NoDiag();
15870 // Rare case where the diagnostics depend on which side is evaluated
15871 // Note that if we get here, CondResult is 0, and at least one of
15872 // TrueResult and FalseResult is non-zero.
15873 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15874 return FalseResult;
15875 return TrueResult;
15877 case Expr::CXXDefaultArgExprClass:
15878 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15879 case Expr::CXXDefaultInitExprClass:
15880 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15881 case Expr::ChooseExprClass: {
15882 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15884 case Expr::BuiltinBitCastExprClass: {
15885 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15886 return ICEDiag(IK_NotICE, E->getBeginLoc());
15887 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15891 llvm_unreachable("Invalid StmtClass!");
15894 /// Evaluate an expression as a C++11 integral constant expression.
15895 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15896 const Expr *E,
15897 llvm::APSInt *Value,
15898 SourceLocation *Loc) {
15899 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15900 if (Loc) *Loc = E->getExprLoc();
15901 return false;
15904 APValue Result;
15905 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15906 return false;
15908 if (!Result.isInt()) {
15909 if (Loc) *Loc = E->getExprLoc();
15910 return false;
15913 if (Value) *Value = Result.getInt();
15914 return true;
15917 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15918 SourceLocation *Loc) const {
15919 assert(!isValueDependent() &&
15920 "Expression evaluator can't be called on a dependent expression.");
15922 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
15924 if (Ctx.getLangOpts().CPlusPlus11)
15925 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15927 ICEDiag D = CheckICE(this, Ctx);
15928 if (D.Kind != IK_ICE) {
15929 if (Loc) *Loc = D.Loc;
15930 return false;
15932 return true;
15935 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15936 SourceLocation *Loc,
15937 bool isEvaluated) const {
15938 if (isValueDependent()) {
15939 // Expression evaluator can't succeed on a dependent expression.
15940 return None;
15943 APSInt Value;
15945 if (Ctx.getLangOpts().CPlusPlus11) {
15946 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15947 return Value;
15948 return None;
15951 if (!isIntegerConstantExpr(Ctx, Loc))
15952 return None;
15954 // The only possible side-effects here are due to UB discovered in the
15955 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15956 // required to treat the expression as an ICE, so we produce the folded
15957 // value.
15958 EvalResult ExprResult;
15959 Expr::EvalStatus Status;
15960 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15961 Info.InConstantContext = true;
15963 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15964 llvm_unreachable("ICE cannot be evaluated!");
15966 return ExprResult.Val.getInt();
15969 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15970 assert(!isValueDependent() &&
15971 "Expression evaluator can't be called on a dependent expression.");
15973 return CheckICE(this, Ctx).Kind == IK_ICE;
15976 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15977 SourceLocation *Loc) const {
15978 assert(!isValueDependent() &&
15979 "Expression evaluator can't be called on a dependent expression.");
15981 // We support this checking in C++98 mode in order to diagnose compatibility
15982 // issues.
15983 assert(Ctx.getLangOpts().CPlusPlus);
15985 // Build evaluation settings.
15986 Expr::EvalStatus Status;
15987 SmallVector<PartialDiagnosticAt, 8> Diags;
15988 Status.Diag = &Diags;
15989 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15991 APValue Scratch;
15992 bool IsConstExpr =
15993 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15994 // FIXME: We don't produce a diagnostic for this, but the callers that
15995 // call us on arbitrary full-expressions should generally not care.
15996 Info.discardCleanups() && !Status.HasSideEffects;
15998 if (!Diags.empty()) {
15999 IsConstExpr = false;
16000 if (Loc) *Loc = Diags[0].first;
16001 } else if (!IsConstExpr) {
16002 // FIXME: This shouldn't happen.
16003 if (Loc) *Loc = getExprLoc();
16006 return IsConstExpr;
16009 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16010 const FunctionDecl *Callee,
16011 ArrayRef<const Expr*> Args,
16012 const Expr *This) const {
16013 assert(!isValueDependent() &&
16014 "Expression evaluator can't be called on a dependent expression.");
16016 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16017 std::string Name;
16018 llvm::raw_string_ostream OS(Name);
16019 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16020 /*Qualified=*/true);
16021 return Name;
16024 Expr::EvalStatus Status;
16025 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16026 Info.InConstantContext = true;
16028 LValue ThisVal;
16029 const LValue *ThisPtr = nullptr;
16030 if (This) {
16031 #ifndef NDEBUG
16032 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16033 assert(MD && "Don't provide `this` for non-methods.");
16034 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
16035 #endif
16036 if (!This->isValueDependent() &&
16037 EvaluateObjectArgument(Info, This, ThisVal) &&
16038 !Info.EvalStatus.HasSideEffects)
16039 ThisPtr = &ThisVal;
16041 // Ignore any side-effects from a failed evaluation. This is safe because
16042 // they can't interfere with any other argument evaluation.
16043 Info.EvalStatus.HasSideEffects = false;
16046 CallRef Call = Info.CurrentCall->createCall(Callee);
16047 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16048 I != E; ++I) {
16049 unsigned Idx = I - Args.begin();
16050 if (Idx >= Callee->getNumParams())
16051 break;
16052 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16053 if ((*I)->isValueDependent() ||
16054 !EvaluateCallArg(PVD, *I, Call, Info) ||
16055 Info.EvalStatus.HasSideEffects) {
16056 // If evaluation fails, throw away the argument entirely.
16057 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16058 *Slot = APValue();
16061 // Ignore any side-effects from a failed evaluation. This is safe because
16062 // they can't interfere with any other argument evaluation.
16063 Info.EvalStatus.HasSideEffects = false;
16066 // Parameter cleanups happen in the caller and are not part of this
16067 // evaluation.
16068 Info.discardCleanups();
16069 Info.EvalStatus.HasSideEffects = false;
16071 // Build fake call to Callee.
16072 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16073 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16074 FullExpressionRAII Scope(Info);
16075 return Evaluate(Value, Info, this) && Scope.destroy() &&
16076 !Info.EvalStatus.HasSideEffects;
16079 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16080 SmallVectorImpl<
16081 PartialDiagnosticAt> &Diags) {
16082 // FIXME: It would be useful to check constexpr function templates, but at the
16083 // moment the constant expression evaluator cannot cope with the non-rigorous
16084 // ASTs which we build for dependent expressions.
16085 if (FD->isDependentContext())
16086 return true;
16088 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16089 std::string Name;
16090 llvm::raw_string_ostream OS(Name);
16091 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16092 /*Qualified=*/true);
16093 return Name;
16096 Expr::EvalStatus Status;
16097 Status.Diag = &Diags;
16099 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16100 Info.InConstantContext = true;
16101 Info.CheckingPotentialConstantExpression = true;
16103 // The constexpr VM attempts to compile all methods to bytecode here.
16104 if (Info.EnableNewConstInterp) {
16105 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16106 return Diags.empty();
16109 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16110 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16112 // Fabricate an arbitrary expression on the stack and pretend that it
16113 // is a temporary being used as the 'this' pointer.
16114 LValue This;
16115 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16116 This.set({&VIE, Info.CurrentCall->Index});
16118 ArrayRef<const Expr*> Args;
16120 APValue Scratch;
16121 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16122 // Evaluate the call as a constant initializer, to allow the construction
16123 // of objects of non-literal types.
16124 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16125 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16126 } else {
16127 SourceLocation Loc = FD->getLocation();
16128 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16129 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16132 return Diags.empty();
16135 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16136 const FunctionDecl *FD,
16137 SmallVectorImpl<
16138 PartialDiagnosticAt> &Diags) {
16139 assert(!E->isValueDependent() &&
16140 "Expression evaluator can't be called on a dependent expression.");
16142 Expr::EvalStatus Status;
16143 Status.Diag = &Diags;
16145 EvalInfo Info(FD->getASTContext(), Status,
16146 EvalInfo::EM_ConstantExpressionUnevaluated);
16147 Info.InConstantContext = true;
16148 Info.CheckingPotentialConstantExpression = true;
16150 // Fabricate a call stack frame to give the arguments a plausible cover story.
16151 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16153 APValue ResultScratch;
16154 Evaluate(ResultScratch, Info, E);
16155 return Diags.empty();
16158 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16159 unsigned Type) const {
16160 if (!getType()->isPointerType())
16161 return false;
16163 Expr::EvalStatus Status;
16164 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16165 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16168 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16169 EvalInfo &Info) {
16170 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16171 return false;
16173 LValue String;
16175 if (!EvaluatePointer(E, String, Info))
16176 return false;
16178 QualType CharTy = E->getType()->getPointeeType();
16180 // Fast path: if it's a string literal, search the string value.
16181 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16182 String.getLValueBase().dyn_cast<const Expr *>())) {
16183 StringRef Str = S->getBytes();
16184 int64_t Off = String.Offset.getQuantity();
16185 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16186 S->getCharByteWidth() == 1 &&
16187 // FIXME: Add fast-path for wchar_t too.
16188 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16189 Str = Str.substr(Off);
16191 StringRef::size_type Pos = Str.find(0);
16192 if (Pos != StringRef::npos)
16193 Str = Str.substr(0, Pos);
16195 Result = Str.size();
16196 return true;
16199 // Fall through to slow path.
16202 // Slow path: scan the bytes of the string looking for the terminating 0.
16203 for (uint64_t Strlen = 0; /**/; ++Strlen) {
16204 APValue Char;
16205 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16206 !Char.isInt())
16207 return false;
16208 if (!Char.getInt()) {
16209 Result = Strlen;
16210 return true;
16212 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16213 return false;
16217 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16218 Expr::EvalStatus Status;
16219 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16220 return EvaluateBuiltinStrLen(this, Result, Info);