clang 22.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/Type.h"
52#include "clang/AST/TypeLoc.h"
57#include "llvm/ADT/APFixedPoint.h"
58#include "llvm/ADT/Sequence.h"
59#include "llvm/ADT/SmallBitVector.h"
60#include "llvm/ADT/StringExtras.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include "llvm/Support/SipHash.h"
65#include "llvm/Support/TimeProfiler.h"
66#include "llvm/Support/raw_ostream.h"
67#include <cstring>
68#include <functional>
69#include <limits>
70#include <optional>
71
72#define DEBUG_TYPE "exprconstant"
73
74using namespace clang;
75using llvm::APFixedPoint;
76using llvm::APInt;
77using llvm::APSInt;
78using llvm::APFloat;
79using llvm::FixedPointSemantics;
80
81namespace {
82 struct LValue;
83 class CallStackFrame;
84 class EvalInfo;
85
86 using SourceLocExprScopeGuard =
88
90 return B.getType();
91 }
92
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field declaration.
95 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Get an LValue path entry, which is known to not be an array index, as a
99 /// base class declaration.
100 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
101 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
102 }
103 /// Determine whether this LValue path entry for a base class names a virtual
104 /// base class.
105 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
106 return E.getAsBaseOrMember().getInt();
107 }
108
109 /// Given an expression, determine the type used to store the result of
110 /// evaluating that expression.
111 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
112 if (E->isPRValue())
113 return E->getType();
114 return Ctx.getLValueReferenceType(E->getType());
115 }
116
117 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
118 /// This will look through a single cast.
119 ///
120 /// Returns null if we couldn't unwrap a function with alloc_size.
121 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
122 if (!E->getType()->isPointerType())
123 return nullptr;
124
125 E = E->IgnoreParens();
126 // If we're doing a variable assignment from e.g. malloc(N), there will
127 // probably be a cast of some kind. In exotic cases, we might also see a
128 // top-level ExprWithCleanups. Ignore them either way.
129 if (const auto *FE = dyn_cast<FullExpr>(E))
130 E = FE->getSubExpr()->IgnoreParens();
131
132 if (const auto *Cast = dyn_cast<CastExpr>(E))
133 E = Cast->getSubExpr()->IgnoreParens();
134
135 if (const auto *CE = dyn_cast<CallExpr>(E))
136 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
137 return nullptr;
138 }
139
140 /// Determines whether or not the given Base contains a call to a function
141 /// with the alloc_size attribute.
142 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
143 const auto *E = Base.dyn_cast<const Expr *>();
144 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
145 }
146
147 /// Determines whether the given kind of constant expression is only ever
148 /// used for name mangling. If so, it's permitted to reference things that we
149 /// can't generate code for (in particular, dllimported functions).
150 static bool isForManglingOnly(ConstantExprKind Kind) {
151 switch (Kind) {
152 case ConstantExprKind::Normal:
153 case ConstantExprKind::ClassTemplateArgument:
154 case ConstantExprKind::ImmediateInvocation:
155 // Note that non-type template arguments of class type are emitted as
156 // template parameter objects.
157 return false;
158
159 case ConstantExprKind::NonClassTemplateArgument:
160 return true;
161 }
162 llvm_unreachable("unknown ConstantExprKind");
163 }
164
165 static bool isTemplateArgument(ConstantExprKind Kind) {
166 switch (Kind) {
167 case ConstantExprKind::Normal:
168 case ConstantExprKind::ImmediateInvocation:
169 return false;
170
171 case ConstantExprKind::ClassTemplateArgument:
172 case ConstantExprKind::NonClassTemplateArgument:
173 return true;
174 }
175 llvm_unreachable("unknown ConstantExprKind");
176 }
177
178 /// The bound to claim that an array of unknown bound has.
179 /// The value in MostDerivedArraySize is undefined in this case. So, set it
180 /// to an arbitrary value that's likely to loudly break things if it's used.
181 static const uint64_t AssumedSizeForUnsizedArray =
182 std::numeric_limits<uint64_t>::max() / 2;
183
184 /// Determines if an LValue with the given LValueBase will have an unsized
185 /// array in its designator.
186 /// Find the path length and type of the most-derived subobject in the given
187 /// path, and find the size of the containing array, if any.
188 static unsigned
189 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
191 uint64_t &ArraySize, QualType &Type, bool &IsArray,
192 bool &FirstEntryIsUnsizedArray) {
193 // This only accepts LValueBases from APValues, and APValues don't support
194 // arrays that lack size info.
195 assert(!isBaseAnAllocSizeCall(Base) &&
196 "Unsized arrays shouldn't appear here");
197 unsigned MostDerivedLength = 0;
198 // The type of Base is a reference type if the base is a constexpr-unknown
199 // variable. In that case, look through the reference type.
200 Type = getType(Base).getNonReferenceType();
201
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;
208
209 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
210 ArraySize = CAT->getZExtSize();
211 } else {
212 assert(I == 0 && "unexpected unsized array designator");
213 FirstEntryIsUnsizedArray = true;
214 ArraySize = AssumedSizeForUnsizedArray;
215 }
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 auto *VT = Type->getAs<VectorType>()) {
223 Type = VT->getElementType();
224 ArraySize = VT->getNumElements();
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const FieldDecl *FD = getAsField(Path[I])) {
228 Type = FD->getType();
229 ArraySize = 0;
230 MostDerivedLength = I + 1;
231 IsArray = false;
232 } else {
233 // Path[I] describes a base class.
234 ArraySize = 0;
235 IsArray = false;
236 }
237 }
238 return MostDerivedLength;
239 }
240
241 /// A path from a glvalue to a subobject of that glvalue.
242 struct SubobjectDesignator {
243 /// True if the subobject was named in a manner not supported by C++11. Such
244 /// lvalues can still be folded, but they are not core constant expressions
245 /// and we cannot perform lvalue-to-rvalue conversions on them.
246 LLVM_PREFERRED_TYPE(bool)
247 unsigned Invalid : 1;
248
249 /// Is this a pointer one past the end of an object?
250 LLVM_PREFERRED_TYPE(bool)
251 unsigned IsOnePastTheEnd : 1;
252
253 /// Indicator of whether the first entry is an unsized array.
254 LLVM_PREFERRED_TYPE(bool)
255 unsigned FirstEntryIsAnUnsizedArray : 1;
256
257 /// Indicator of whether the most-derived object is an array element.
258 LLVM_PREFERRED_TYPE(bool)
259 unsigned MostDerivedIsArrayElement : 1;
260
261 /// The length of the path to the most-derived object of which this is a
262 /// subobject.
263 unsigned MostDerivedPathLength : 28;
264
265 /// The size of the array of which the most-derived object is an element.
266 /// This will always be 0 if the most-derived object is not an array
267 /// element. 0 is not an indicator of whether or not the most-derived object
268 /// is an array, however, because 0-length arrays are allowed.
269 ///
270 /// If the current array is an unsized array, the value of this is
271 /// undefined.
272 uint64_t MostDerivedArraySize;
273 /// The type of the most derived object referred to by this address.
274 QualType MostDerivedType;
275
276 typedef APValue::LValuePathEntry PathEntry;
277
278 /// The entries on the path from the glvalue to the designated subobject.
280
281 SubobjectDesignator() : Invalid(true) {}
282
283 explicit SubobjectDesignator(QualType T)
284 : Invalid(false), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0),
287 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
288
289 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
290 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
291 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
292 MostDerivedPathLength(0), MostDerivedArraySize(0) {
293 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
294 if (!Invalid) {
295 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
296 llvm::append_range(Entries, V.getLValuePath());
297 if (V.getLValueBase()) {
298 bool IsArray = false;
299 bool FirstIsUnsizedArray = false;
300 MostDerivedPathLength = findMostDerivedSubobject(
301 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
302 MostDerivedType, IsArray, FirstIsUnsizedArray);
303 MostDerivedIsArrayElement = IsArray;
304 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
305 }
306 }
307 }
308
309 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
310 unsigned NewLength) {
311 if (Invalid)
312 return;
313
314 assert(Base && "cannot truncate path for null pointer");
315 assert(NewLength <= Entries.size() && "not a truncation");
316
317 if (NewLength == Entries.size())
318 return;
319 Entries.resize(NewLength);
320
321 bool IsArray = false;
322 bool FirstIsUnsizedArray = false;
323 MostDerivedPathLength = findMostDerivedSubobject(
324 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
325 FirstIsUnsizedArray);
326 MostDerivedIsArrayElement = IsArray;
327 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
328 }
329
330 void setInvalid() {
331 Invalid = true;
332 Entries.clear();
333 }
334
335 /// Determine whether the most derived subobject is an array without a
336 /// known bound.
337 bool isMostDerivedAnUnsizedArray() const {
338 assert(!Invalid && "Calling this makes no sense on invalid designators");
339 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
340 }
341
342 /// Determine what the most derived array's size is. Results in an assertion
343 /// failure if the most derived array lacks a size.
344 uint64_t getMostDerivedArraySize() const {
345 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
346 return MostDerivedArraySize;
347 }
348
349 /// Determine whether this is a one-past-the-end pointer.
350 bool isOnePastTheEnd() const {
351 assert(!Invalid);
352 if (IsOnePastTheEnd)
353 return true;
354 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
355 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
356 MostDerivedArraySize)
357 return true;
358 return false;
359 }
360
361 /// Get the range of valid index adjustments in the form
362 /// {maximum value that can be subtracted from this pointer,
363 /// maximum value that can be added to this pointer}
364 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
365 if (Invalid || isMostDerivedAnUnsizedArray())
366 return {0, 0};
367
368 // [expr.add]p4: For the purposes of these operators, a pointer to a
369 // nonarray object behaves the same as a pointer to the first element of
370 // an array of length one with the type of the object as its element type.
371 bool IsArray = MostDerivedPathLength == Entries.size() &&
372 MostDerivedIsArrayElement;
373 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
374 : (uint64_t)IsOnePastTheEnd;
375 uint64_t ArraySize =
376 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 return {ArrayIndex, ArraySize - ArrayIndex};
378 }
379
380 /// Check that this refers to a valid subobject.
381 bool isValidSubobject() const {
382 if (Invalid)
383 return false;
384 return !isOnePastTheEnd();
385 }
386 /// Check that this refers to a valid subobject, and if not, produce a
387 /// relevant diagnostic and set the designator as invalid.
388 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
389
390 /// Get the type of the designated object.
391 QualType getType(ASTContext &Ctx) const {
392 assert(!Invalid && "invalid designator has no subobject type");
393 return MostDerivedPathLength == Entries.size()
394 ? MostDerivedType
395 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
396 }
397
398 /// Update this designator to refer to the first element within this array.
399 void addArrayUnchecked(const ConstantArrayType *CAT) {
400 Entries.push_back(PathEntry::ArrayIndex(0));
401
402 // This is a most-derived object.
403 MostDerivedType = CAT->getElementType();
404 MostDerivedIsArrayElement = true;
405 MostDerivedArraySize = CAT->getZExtSize();
406 MostDerivedPathLength = Entries.size();
407 }
408 /// Update this designator to refer to the first element within the array of
409 /// elements of type T. This is an array of unknown size.
410 void addUnsizedArrayUnchecked(QualType ElemTy) {
411 Entries.push_back(PathEntry::ArrayIndex(0));
412
413 MostDerivedType = ElemTy;
414 MostDerivedIsArrayElement = true;
415 // The value in MostDerivedArraySize is undefined in this case. So, set it
416 // to an arbitrary value that's likely to loudly break things if it's
417 // used.
418 MostDerivedArraySize = AssumedSizeForUnsizedArray;
419 MostDerivedPathLength = Entries.size();
420 }
421 /// Update this designator to refer to the given base or member of this
422 /// object.
423 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
424 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
425
426 // If this isn't a base class, it's a new most-derived object.
427 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
428 MostDerivedType = FD->getType();
429 MostDerivedIsArrayElement = false;
430 MostDerivedArraySize = 0;
431 MostDerivedPathLength = Entries.size();
432 }
433 }
434 /// Update this designator to refer to the given complex component.
435 void addComplexUnchecked(QualType EltTy, bool Imag) {
436 Entries.push_back(PathEntry::ArrayIndex(Imag));
437
438 // This is technically a most-derived object, though in practice this
439 // is unlikely to matter.
440 MostDerivedType = EltTy;
441 MostDerivedIsArrayElement = true;
442 MostDerivedArraySize = 2;
443 MostDerivedPathLength = Entries.size();
444 }
445
446 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
447 uint64_t Idx) {
448 Entries.push_back(PathEntry::ArrayIndex(Idx));
449 MostDerivedType = EltTy;
450 MostDerivedPathLength = Entries.size();
451 MostDerivedArraySize = 0;
452 MostDerivedIsArrayElement = false;
453 }
454
455 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
456 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
457 const APSInt &N);
458 /// Add N to the address of this subobject.
459 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
460 };
461
462 /// A scope at the end of which an object can need to be destroyed.
463 enum class ScopeKind {
464 Block,
465 FullExpression,
466 Call
467 };
468
469 /// A reference to a particular call and its arguments.
470 struct CallRef {
471 CallRef() : OrigCallee(), CallIndex(0), Version() {}
472 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
473 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
474
475 explicit operator bool() const { return OrigCallee; }
476
477 /// Get the parameter that the caller initialized, corresponding to the
478 /// given parameter in the callee.
479 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
480 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
481 : PVD;
482 }
483
484 /// The callee at the point where the arguments were evaluated. This might
485 /// be different from the actual callee (a different redeclaration, or a
486 /// virtual override), but this function's parameters are the ones that
487 /// appear in the parameter map.
488 const FunctionDecl *OrigCallee;
489 /// The call index of the frame that holds the argument values.
490 unsigned CallIndex;
491 /// The version of the parameters corresponding to this call.
492 unsigned Version;
493 };
494
495 /// A stack frame in the constexpr call stack.
496 class CallStackFrame : public interp::Frame {
497 public:
498 EvalInfo &Info;
499
500 /// Parent - The caller of this stack frame.
501 CallStackFrame *Caller;
502
503 /// Callee - The function which was called.
504 const FunctionDecl *Callee;
505
506 /// This - The binding for the this pointer in this call, if any.
507 const LValue *This;
508
509 /// CallExpr - The syntactical structure of member function calls
510 const Expr *CallExpr;
511
512 /// Information on how to find the arguments to this call. Our arguments
513 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
514 /// key and this value as the version.
515 CallRef Arguments;
516
517 /// Source location information about the default argument or default
518 /// initializer expression we're evaluating, if any.
519 CurrentSourceLocExprScope CurSourceLocExprScope;
520
521 // Note that we intentionally use std::map here so that references to
522 // values are stable.
523 typedef std::pair<const void *, unsigned> MapKeyTy;
524 typedef std::map<MapKeyTy, APValue> MapTy;
525 /// Temporaries - Temporary lvalues materialized within this stack frame.
526 MapTy Temporaries;
527
528 /// CallRange - The source range of the call expression for this call.
529 SourceRange CallRange;
530
531 /// Index - The call index of this call.
532 unsigned Index;
533
534 /// The stack of integers for tracking version numbers for temporaries.
535 SmallVector<unsigned, 2> TempVersionStack = {1};
536 unsigned CurTempVersion = TempVersionStack.back();
537
538 unsigned getTempVersion() const { return TempVersionStack.back(); }
539
540 void pushTempVersion() {
541 TempVersionStack.push_back(++CurTempVersion);
542 }
543
544 void popTempVersion() {
545 TempVersionStack.pop_back();
546 }
547
548 CallRef createCall(const FunctionDecl *Callee) {
549 return {Callee, Index, ++CurTempVersion};
550 }
551
552 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
553 // on the overall stack usage of deeply-recursing constexpr evaluations.
554 // (We should cache this map rather than recomputing it repeatedly.)
555 // But let's try this and see how it goes; we can look into caching the map
556 // as a later change.
557
558 /// LambdaCaptureFields - Mapping from captured variables/this to
559 /// corresponding data members in the closure class.
560 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
561 FieldDecl *LambdaThisCaptureField = nullptr;
562
563 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
564 const FunctionDecl *Callee, const LValue *This,
565 const Expr *CallExpr, CallRef Arguments);
566 ~CallStackFrame();
567
568 // Return the temporary for Key whose version number is Version.
569 APValue *getTemporary(const void *Key, unsigned Version) {
570 MapKeyTy KV(Key, Version);
571 auto LB = Temporaries.lower_bound(KV);
572 if (LB != Temporaries.end() && LB->first == KV)
573 return &LB->second;
574 return nullptr;
575 }
576
577 // Return the current temporary for Key in the map.
578 APValue *getCurrentTemporary(const void *Key) {
579 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
580 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
581 return &std::prev(UB)->second;
582 return nullptr;
583 }
584
585 // Return the version number of the current temporary for Key.
586 unsigned getCurrentTemporaryVersion(const void *Key) const {
587 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
588 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
589 return std::prev(UB)->first.second;
590 return 0;
591 }
592
593 /// Allocate storage for an object of type T in this stack frame.
594 /// Populates LV with a handle to the created object. Key identifies
595 /// the temporary within the stack frame, and must not be reused without
596 /// bumping the temporary version number.
597 template<typename KeyT>
598 APValue &createTemporary(const KeyT *Key, QualType T,
599 ScopeKind Scope, LValue &LV);
600
601 /// Allocate storage for a parameter of a function call made in this frame.
602 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
603
604 void describe(llvm::raw_ostream &OS) const override;
605
606 Frame *getCaller() const override { return Caller; }
607 SourceRange getCallRange() const override { return CallRange; }
608 const FunctionDecl *getCallee() const override { return Callee; }
609
610 bool isStdFunction() const {
611 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
612 if (DC->isStdNamespace())
613 return true;
614 return false;
615 }
616
617 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
618 /// permitted. See MSConstexprDocs for description of permitted contexts.
619 bool CanEvalMSConstexpr = false;
620
621 private:
622 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
623 ScopeKind Scope);
624 };
625
626 /// Temporarily override 'this'.
627 class ThisOverrideRAII {
628 public:
629 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
630 : Frame(Frame), OldThis(Frame.This) {
631 if (Enable)
632 Frame.This = NewThis;
633 }
634 ~ThisOverrideRAII() {
635 Frame.This = OldThis;
636 }
637 private:
638 CallStackFrame &Frame;
639 const LValue *OldThis;
640 };
641
642 // A shorthand time trace scope struct, prints source range, for example
643 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
644 class ExprTimeTraceScope {
645 public:
646 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
647 : TimeScope(Name, [E, &Ctx] {
649 }) {}
650
651 private:
652 llvm::TimeTraceScope TimeScope;
653 };
654
655 /// RAII object used to change the current ability of
656 /// [[msvc::constexpr]] evaulation.
657 struct MSConstexprContextRAII {
658 CallStackFrame &Frame;
659 bool OldValue;
660 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
661 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
662 Frame.CanEvalMSConstexpr = Value;
663 }
664
665 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
666 };
667}
668
669static bool HandleDestruction(EvalInfo &Info, const Expr *E,
670 const LValue &This, QualType ThisType);
671static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
673 QualType T);
674
675namespace {
676 /// A cleanup, and a flag indicating whether it is lifetime-extended.
677 class Cleanup {
678 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
679 APValue::LValueBase Base;
680 QualType T;
681
682 public:
683 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
684 ScopeKind Scope)
685 : Value(Val, Scope), Base(Base), T(T) {}
686
687 /// Determine whether this cleanup should be performed at the end of the
688 /// given kind of scope.
689 bool isDestroyedAtEndOf(ScopeKind K) const {
690 return (int)Value.getInt() >= (int)K;
691 }
692 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
693 if (RunDestructors) {
694 SourceLocation Loc;
695 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
696 Loc = VD->getLocation();
697 else if (const Expr *E = Base.dyn_cast<const Expr*>())
698 Loc = E->getExprLoc();
699 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
700 }
701 *Value.getPointer() = APValue();
702 return true;
703 }
704
705 bool hasSideEffect() {
706 return T.isDestructedType();
707 }
708 };
709
710 /// A reference to an object whose construction we are currently evaluating.
711 struct ObjectUnderConstruction {
712 APValue::LValueBase Base;
713 ArrayRef<APValue::LValuePathEntry> Path;
714 friend bool operator==(const ObjectUnderConstruction &LHS,
715 const ObjectUnderConstruction &RHS) {
716 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
717 }
718 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
719 return llvm::hash_combine(Obj.Base, Obj.Path);
720 }
721 };
722 enum class ConstructionPhase {
723 None,
724 Bases,
725 AfterBases,
726 AfterFields,
727 Destroying,
728 DestroyingBases
729 };
730}
731
732namespace llvm {
733template<> struct DenseMapInfo<ObjectUnderConstruction> {
734 using Base = DenseMapInfo<APValue::LValueBase>;
735 static ObjectUnderConstruction getEmptyKey() {
736 return {Base::getEmptyKey(), {}}; }
737 static ObjectUnderConstruction getTombstoneKey() {
738 return {Base::getTombstoneKey(), {}};
739 }
740 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
741 return hash_value(Object);
742 }
743 static bool isEqual(const ObjectUnderConstruction &LHS,
744 const ObjectUnderConstruction &RHS) {
745 return LHS == RHS;
746 }
747};
748}
749
750namespace {
751 /// A dynamically-allocated heap object.
752 struct DynAlloc {
753 /// The value of this heap-allocated object.
754 APValue Value;
755 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
756 /// or a CallExpr (the latter is for direct calls to operator new inside
757 /// std::allocator<T>::allocate).
758 const Expr *AllocExpr = nullptr;
759
760 enum Kind {
761 New,
762 ArrayNew,
763 StdAllocator
764 };
765
766 /// Get the kind of the allocation. This must match between allocation
767 /// and deallocation.
768 Kind getKind() const {
769 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
770 return NE->isArray() ? ArrayNew : New;
771 assert(isa<CallExpr>(AllocExpr));
772 return StdAllocator;
773 }
774 };
775
776 struct DynAllocOrder {
777 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
778 return L.getIndex() < R.getIndex();
779 }
780 };
781
782 /// EvalInfo - This is a private struct used by the evaluator to capture
783 /// information about a subexpression as it is folded. It retains information
784 /// about the AST context, but also maintains information about the folded
785 /// expression.
786 ///
787 /// If an expression could be evaluated, it is still possible it is not a C
788 /// "integer constant expression" or constant expression. If not, this struct
789 /// captures information about how and why not.
790 ///
791 /// One bit of information passed *into* the request for constant folding
792 /// indicates whether the subexpression is "evaluated" or not according to C
793 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
794 /// evaluate the expression regardless of what the RHS is, but C only allows
795 /// certain things in certain situations.
796 class EvalInfo : public interp::State {
797 public:
798 ASTContext &Ctx;
799
800 /// EvalStatus - Contains information about the evaluation.
801 Expr::EvalStatus &EvalStatus;
802
803 /// CurrentCall - The top of the constexpr call stack.
804 CallStackFrame *CurrentCall;
805
806 /// CallStackDepth - The number of calls in the call stack right now.
807 unsigned CallStackDepth;
808
809 /// NextCallIndex - The next call index to assign.
810 unsigned NextCallIndex;
811
812 /// StepsLeft - The remaining number of evaluation steps we're permitted
813 /// to perform. This is essentially a limit for the number of statements
814 /// we will evaluate.
815 unsigned StepsLeft;
816
817 /// Enable the experimental new constant interpreter. If an expression is
818 /// not supported by the interpreter, an error is triggered.
819 bool EnableNewConstInterp;
820
821 /// BottomFrame - The frame in which evaluation started. This must be
822 /// initialized after CurrentCall and CallStackDepth.
823 CallStackFrame BottomFrame;
824
825 /// A stack of values whose lifetimes end at the end of some surrounding
826 /// evaluation frame.
827 llvm::SmallVector<Cleanup, 16> CleanupStack;
828
829 /// EvaluatingDecl - This is the declaration whose initializer is being
830 /// evaluated, if any.
831 APValue::LValueBase EvaluatingDecl;
832
833 enum class EvaluatingDeclKind {
834 None,
835 /// We're evaluating the construction of EvaluatingDecl.
836 Ctor,
837 /// We're evaluating the destruction of EvaluatingDecl.
838 Dtor,
839 };
840 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
841
842 /// EvaluatingDeclValue - This is the value being constructed for the
843 /// declaration whose initializer is being evaluated, if any.
844 APValue *EvaluatingDeclValue;
845
846 /// Stack of loops and 'switch' statements which we're currently
847 /// breaking/continuing; null entries are used to mark unlabeled
848 /// break/continue.
849 SmallVector<const Stmt *> BreakContinueStack;
850
851 /// Set of objects that are currently being constructed.
852 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
853 ObjectsUnderConstruction;
854
855 /// Current heap allocations, along with the location where each was
856 /// allocated. We use std::map here because we need stable addresses
857 /// for the stored APValues.
858 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
859
860 /// The number of heap allocations performed so far in this evaluation.
861 unsigned NumHeapAllocs = 0;
862
863 struct EvaluatingConstructorRAII {
864 EvalInfo &EI;
865 ObjectUnderConstruction Object;
866 bool DidInsert;
867 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
868 bool HasBases)
869 : EI(EI), Object(Object) {
870 DidInsert =
871 EI.ObjectsUnderConstruction
872 .insert({Object, HasBases ? ConstructionPhase::Bases
873 : ConstructionPhase::AfterBases})
874 .second;
875 }
876 void finishedConstructingBases() {
877 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
878 }
879 void finishedConstructingFields() {
880 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
881 }
882 ~EvaluatingConstructorRAII() {
883 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
884 }
885 };
886
887 struct EvaluatingDestructorRAII {
888 EvalInfo &EI;
889 ObjectUnderConstruction Object;
890 bool DidInsert;
891 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
892 : EI(EI), Object(Object) {
893 DidInsert = EI.ObjectsUnderConstruction
894 .insert({Object, ConstructionPhase::Destroying})
895 .second;
896 }
897 void startedDestroyingBases() {
898 EI.ObjectsUnderConstruction[Object] =
899 ConstructionPhase::DestroyingBases;
900 }
901 ~EvaluatingDestructorRAII() {
902 if (DidInsert)
903 EI.ObjectsUnderConstruction.erase(Object);
904 }
905 };
906
907 ConstructionPhase
908 isEvaluatingCtorDtor(APValue::LValueBase Base,
909 ArrayRef<APValue::LValuePathEntry> Path) {
910 return ObjectsUnderConstruction.lookup({Base, Path});
911 }
912
913 /// If we're currently speculatively evaluating, the outermost call stack
914 /// depth at which we can mutate state, otherwise 0.
915 unsigned SpeculativeEvaluationDepth = 0;
916
917 /// The current array initialization index, if we're performing array
918 /// initialization.
919 uint64_t ArrayInitIndex = -1;
920
921 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
922 /// notes attached to it will also be stored, otherwise they will not be.
923 bool HasActiveDiagnostic;
924
925 /// Have we emitted a diagnostic explaining why we couldn't constant
926 /// fold (not just why it's not strictly a constant expression)?
927 bool HasFoldFailureDiagnostic;
928
929 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
930 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
931 CallStackDepth(0), NextCallIndex(1),
932 StepsLeft(C.getLangOpts().ConstexprStepLimit),
933 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
934 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
935 /*This=*/nullptr,
936 /*CallExpr=*/nullptr, CallRef()),
937 EvaluatingDecl((const ValueDecl *)nullptr),
938 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
939 HasFoldFailureDiagnostic(false) {
940 EvalMode = Mode;
941 }
942
943 ~EvalInfo() {
944 discardCleanups();
945 }
946
947 ASTContext &getASTContext() const override { return Ctx; }
948 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
949
950 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
951 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
952 EvaluatingDecl = Base;
953 IsEvaluatingDecl = EDK;
954 EvaluatingDeclValue = &Value;
955 }
956
957 bool CheckCallLimit(SourceLocation Loc) {
958 // Don't perform any constexpr calls (other than the call we're checking)
959 // when checking a potential constant expression.
960 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
961 return false;
962 if (NextCallIndex == 0) {
963 // NextCallIndex has wrapped around.
964 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
965 return false;
966 }
967 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
968 return true;
969 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
970 << getLangOpts().ConstexprCallDepth;
971 return false;
972 }
973
974 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
975 uint64_t ElemCount, bool Diag) {
976 // FIXME: GH63562
977 // APValue stores array extents as unsigned,
978 // so anything that is greater that unsigned would overflow when
979 // constructing the array, we catch this here.
980 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
981 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
982 if (Diag)
983 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
984 return false;
985 }
986
987 // FIXME: GH63562
988 // Arrays allocate an APValue per element.
989 // We use the number of constexpr steps as a proxy for the maximum size
990 // of arrays to avoid exhausting the system resources, as initialization
991 // of each element is likely to take some number of steps anyway.
992 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
993 if (ElemCount > Limit) {
994 if (Diag)
995 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
996 << ElemCount << Limit;
997 return false;
998 }
999 return true;
1000 }
1001
1002 std::pair<CallStackFrame *, unsigned>
1003 getCallFrameAndDepth(unsigned CallIndex) {
1004 assert(CallIndex && "no call index in getCallFrameAndDepth");
1005 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1006 // be null in this loop.
1007 unsigned Depth = CallStackDepth;
1008 CallStackFrame *Frame = CurrentCall;
1009 while (Frame->Index > CallIndex) {
1010 Frame = Frame->Caller;
1011 --Depth;
1012 }
1013 if (Frame->Index == CallIndex)
1014 return {Frame, Depth};
1015 return {nullptr, 0};
1016 }
1017
1018 bool nextStep(const Stmt *S) {
1019 if (!StepsLeft) {
1020 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1021 return false;
1022 }
1023 --StepsLeft;
1024 return true;
1025 }
1026
1027 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1028
1029 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1030 std::optional<DynAlloc *> Result;
1031 auto It = HeapAllocs.find(DA);
1032 if (It != HeapAllocs.end())
1033 Result = &It->second;
1034 return Result;
1035 }
1036
1037 /// Get the allocated storage for the given parameter of the given call.
1038 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1039 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1040 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1041 : nullptr;
1042 }
1043
1044 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1045 struct StdAllocatorCaller {
1046 unsigned FrameIndex;
1047 QualType ElemType;
1048 const Expr *Call;
1049 explicit operator bool() const { return FrameIndex != 0; };
1050 };
1051
1052 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1053 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1054 Call = Call->Caller) {
1055 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1056 if (!MD)
1057 continue;
1058 const IdentifierInfo *FnII = MD->getIdentifier();
1059 if (!FnII || !FnII->isStr(FnName))
1060 continue;
1061
1062 const auto *CTSD =
1063 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1064 if (!CTSD)
1065 continue;
1066
1067 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1068 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1069 if (CTSD->isInStdNamespace() && ClassII &&
1070 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1071 TAL[0].getKind() == TemplateArgument::Type)
1072 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1073 }
1074
1075 return {};
1076 }
1077
1078 void performLifetimeExtension() {
1079 // Disable the cleanups for lifetime-extended temporaries.
1080 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1081 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1082 });
1083 }
1084
1085 /// Throw away any remaining cleanups at the end of evaluation. If any
1086 /// cleanups would have had a side-effect, note that as an unmodeled
1087 /// side-effect and return false. Otherwise, return true.
1088 bool discardCleanups() {
1089 for (Cleanup &C : CleanupStack) {
1090 if (C.hasSideEffect() && !noteSideEffect()) {
1091 CleanupStack.clear();
1092 return false;
1093 }
1094 }
1095 CleanupStack.clear();
1096 return true;
1097 }
1098
1099 private:
1100 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1101 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1102
1103 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1104 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1105
1106 void setFoldFailureDiagnostic(bool Flag) override {
1107 HasFoldFailureDiagnostic = Flag;
1108 }
1109
1110 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1111
1112 // If we have a prior diagnostic, it will be noting that the expression
1113 // isn't a constant expression. This diagnostic is more important,
1114 // unless we require this evaluation to produce a constant expression.
1115 //
1116 // FIXME: We might want to show both diagnostics to the user in
1117 // EvaluationMode::ConstantFold mode.
1118 bool hasPriorDiagnostic() override {
1119 if (!EvalStatus.Diag->empty()) {
1120 switch (EvalMode) {
1121 case EvaluationMode::ConstantFold:
1122 case EvaluationMode::IgnoreSideEffects:
1123 if (!HasFoldFailureDiagnostic)
1124 break;
1125 // We've already failed to fold something. Keep that diagnostic.
1126 [[fallthrough]];
1127 case EvaluationMode::ConstantExpression:
1128 case EvaluationMode::ConstantExpressionUnevaluated:
1129 setActiveDiagnostic(false);
1130 return true;
1131 }
1132 }
1133 return false;
1134 }
1135
1136 unsigned getCallStackDepth() override { return CallStackDepth; }
1137
1138 public:
1139 /// Should we continue evaluation after encountering a side-effect that we
1140 /// couldn't model?
1141 bool keepEvaluatingAfterSideEffect() const override {
1142 switch (EvalMode) {
1143 case EvaluationMode::IgnoreSideEffects:
1144 return true;
1145
1146 case EvaluationMode::ConstantExpression:
1147 case EvaluationMode::ConstantExpressionUnevaluated:
1148 case EvaluationMode::ConstantFold:
1149 // By default, assume any side effect might be valid in some other
1150 // evaluation of this expression from a different context.
1151 return checkingPotentialConstantExpression() ||
1152 checkingForUndefinedBehavior();
1153 }
1154 llvm_unreachable("Missed EvalMode case");
1155 }
1156
1157 /// Note that we have had a side-effect, and determine whether we should
1158 /// keep evaluating.
1159 bool noteSideEffect() override {
1160 EvalStatus.HasSideEffects = true;
1161 return keepEvaluatingAfterSideEffect();
1162 }
1163
1164 /// Should we continue evaluation after encountering undefined behavior?
1165 bool keepEvaluatingAfterUndefinedBehavior() {
1166 switch (EvalMode) {
1167 case EvaluationMode::IgnoreSideEffects:
1168 case EvaluationMode::ConstantFold:
1169 return true;
1170
1171 case EvaluationMode::ConstantExpression:
1172 case EvaluationMode::ConstantExpressionUnevaluated:
1173 return checkingForUndefinedBehavior();
1174 }
1175 llvm_unreachable("Missed EvalMode case");
1176 }
1177
1178 /// Note that we hit something that was technically undefined behavior, but
1179 /// that we can evaluate past it (such as signed overflow or floating-point
1180 /// division by zero.)
1181 bool noteUndefinedBehavior() override {
1182 EvalStatus.HasUndefinedBehavior = true;
1183 return keepEvaluatingAfterUndefinedBehavior();
1184 }
1185
1186 /// Should we continue evaluation as much as possible after encountering a
1187 /// construct which can't be reduced to a value?
1188 bool keepEvaluatingAfterFailure() const override {
1189 if (!StepsLeft)
1190 return false;
1191
1192 switch (EvalMode) {
1193 case EvaluationMode::ConstantExpression:
1194 case EvaluationMode::ConstantExpressionUnevaluated:
1195 case EvaluationMode::ConstantFold:
1196 case EvaluationMode::IgnoreSideEffects:
1197 return checkingPotentialConstantExpression() ||
1198 checkingForUndefinedBehavior();
1199 }
1200 llvm_unreachable("Missed EvalMode case");
1201 }
1202
1203 /// Notes that we failed to evaluate an expression that other expressions
1204 /// directly depend on, and determine if we should keep evaluating. This
1205 /// should only be called if we actually intend to keep evaluating.
1206 ///
1207 /// Call noteSideEffect() instead if we may be able to ignore the value that
1208 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1209 ///
1210 /// (Foo(), 1) // use noteSideEffect
1211 /// (Foo() || true) // use noteSideEffect
1212 /// Foo() + 1 // use noteFailure
1213 [[nodiscard]] bool noteFailure() {
1214 // Failure when evaluating some expression often means there is some
1215 // subexpression whose evaluation was skipped. Therefore, (because we
1216 // don't track whether we skipped an expression when unwinding after an
1217 // evaluation failure) every evaluation failure that bubbles up from a
1218 // subexpression implies that a side-effect has potentially happened. We
1219 // skip setting the HasSideEffects flag to true until we decide to
1220 // continue evaluating after that point, which happens here.
1221 bool KeepGoing = keepEvaluatingAfterFailure();
1222 EvalStatus.HasSideEffects |= KeepGoing;
1223 return KeepGoing;
1224 }
1225
1226 class ArrayInitLoopIndex {
1227 EvalInfo &Info;
1228 uint64_t OuterIndex;
1229
1230 public:
1231 ArrayInitLoopIndex(EvalInfo &Info)
1232 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1233 Info.ArrayInitIndex = 0;
1234 }
1235 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1236
1237 operator uint64_t&() { return Info.ArrayInitIndex; }
1238 };
1239 };
1240
1241 /// Object used to treat all foldable expressions as constant expressions.
1242 struct FoldConstant {
1243 EvalInfo &Info;
1244 bool Enabled;
1245 bool HadNoPriorDiags;
1246 EvaluationMode OldMode;
1247
1248 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1249 : Info(Info),
1250 Enabled(Enabled),
1251 HadNoPriorDiags(Info.EvalStatus.Diag &&
1252 Info.EvalStatus.Diag->empty() &&
1253 !Info.EvalStatus.HasSideEffects),
1254 OldMode(Info.EvalMode) {
1255 if (Enabled)
1256 Info.EvalMode = EvaluationMode::ConstantFold;
1257 }
1258 void keepDiagnostics() { Enabled = false; }
1259 ~FoldConstant() {
1260 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1261 !Info.EvalStatus.HasSideEffects)
1262 Info.EvalStatus.Diag->clear();
1263 Info.EvalMode = OldMode;
1264 }
1265 };
1266
1267 /// RAII object used to set the current evaluation mode to ignore
1268 /// side-effects.
1269 struct IgnoreSideEffectsRAII {
1270 EvalInfo &Info;
1271 EvaluationMode OldMode;
1272 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1273 : Info(Info), OldMode(Info.EvalMode) {
1274 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1275 }
1276
1277 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1278 };
1279
1280 /// RAII object used to optionally suppress diagnostics and side-effects from
1281 /// a speculative evaluation.
1282 class SpeculativeEvaluationRAII {
1283 EvalInfo *Info = nullptr;
1284 Expr::EvalStatus OldStatus;
1285 unsigned OldSpeculativeEvaluationDepth = 0;
1286
1287 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1288 Info = Other.Info;
1289 OldStatus = Other.OldStatus;
1290 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1291 Other.Info = nullptr;
1292 }
1293
1294 void maybeRestoreState() {
1295 if (!Info)
1296 return;
1297
1298 Info->EvalStatus = OldStatus;
1299 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1300 }
1301
1302 public:
1303 SpeculativeEvaluationRAII() = default;
1304
1305 SpeculativeEvaluationRAII(
1306 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1307 : Info(&Info), OldStatus(Info.EvalStatus),
1308 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1309 Info.EvalStatus.Diag = NewDiag;
1310 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1311 }
1312
1313 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1314 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1315 moveFromAndCancel(std::move(Other));
1316 }
1317
1318 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1319 maybeRestoreState();
1320 moveFromAndCancel(std::move(Other));
1321 return *this;
1322 }
1323
1324 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1325 };
1326
1327 /// RAII object wrapping a full-expression or block scope, and handling
1328 /// the ending of the lifetime of temporaries created within it.
1329 template<ScopeKind Kind>
1330 class ScopeRAII {
1331 EvalInfo &Info;
1332 unsigned OldStackSize;
1333 public:
1334 ScopeRAII(EvalInfo &Info)
1335 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1336 // Push a new temporary version. This is needed to distinguish between
1337 // temporaries created in different iterations of a loop.
1338 Info.CurrentCall->pushTempVersion();
1339 }
1340 bool destroy(bool RunDestructors = true) {
1341 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1342 OldStackSize = std::numeric_limits<unsigned>::max();
1343 return OK;
1344 }
1345 ~ScopeRAII() {
1346 if (OldStackSize != std::numeric_limits<unsigned>::max())
1347 destroy(false);
1348 // Body moved to a static method to encourage the compiler to inline away
1349 // instances of this class.
1350 Info.CurrentCall->popTempVersion();
1351 }
1352 private:
1353 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1354 unsigned OldStackSize) {
1355 assert(OldStackSize <= Info.CleanupStack.size() &&
1356 "running cleanups out of order?");
1357
1358 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1359 // for a full-expression scope.
1360 bool Success = true;
1361 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1362 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1363 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1364 Success = false;
1365 break;
1366 }
1367 }
1368 }
1369
1370 // Compact any retained cleanups.
1371 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1372 if (Kind != ScopeKind::Block)
1373 NewEnd =
1374 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1375 return C.isDestroyedAtEndOf(Kind);
1376 });
1377 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1378 return Success;
1379 }
1380 };
1381 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1382 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1383 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1384}
1385
1386bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1387 CheckSubobjectKind CSK) {
1388 if (Invalid)
1389 return false;
1390 if (isOnePastTheEnd()) {
1391 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1392 << CSK;
1393 setInvalid();
1394 return false;
1395 }
1396 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1397 // must actually be at least one array element; even a VLA cannot have a
1398 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1399 return true;
1400}
1401
1402void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1403 const Expr *E) {
1404 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1405 // Do not set the designator as invalid: we can represent this situation,
1406 // and correct handling of __builtin_object_size requires us to do so.
1407}
1408
1409void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1410 const Expr *E,
1411 const APSInt &N) {
1412 // If we're complaining, we must be able to statically determine the size of
1413 // the most derived array.
1414 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1415 Info.CCEDiag(E, diag::note_constexpr_array_index)
1416 << N << /*array*/ 0
1417 << static_cast<unsigned>(getMostDerivedArraySize());
1418 else
1419 Info.CCEDiag(E, diag::note_constexpr_array_index)
1420 << N << /*non-array*/ 1;
1421 setInvalid();
1422}
1423
1424CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1425 const FunctionDecl *Callee, const LValue *This,
1426 const Expr *CallExpr, CallRef Call)
1427 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1428 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1429 Index(Info.NextCallIndex++) {
1430 Info.CurrentCall = this;
1431 ++Info.CallStackDepth;
1432}
1433
1434CallStackFrame::~CallStackFrame() {
1435 assert(Info.CurrentCall == this && "calls retired out of order");
1436 --Info.CallStackDepth;
1437 Info.CurrentCall = Caller;
1438}
1439
1440static bool isRead(AccessKinds AK) {
1441 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1442 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1443}
1444
1446 switch (AK) {
1447 case AK_Read:
1449 case AK_MemberCall:
1450 case AK_DynamicCast:
1451 case AK_TypeId:
1453 case AK_Dereference:
1454 return false;
1455 case AK_Assign:
1456 case AK_Increment:
1457 case AK_Decrement:
1458 case AK_Construct:
1459 case AK_Destroy:
1460 return true;
1461 }
1462 llvm_unreachable("unknown access kind");
1463}
1464
1465static bool isAnyAccess(AccessKinds AK) {
1466 return isRead(AK) || isModification(AK);
1467}
1468
1469/// Is this an access per the C++ definition?
1471 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1472 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1473}
1474
1475/// Is this kind of access valid on an indeterminate object value?
1477 switch (AK) {
1478 case AK_Read:
1479 case AK_Increment:
1480 case AK_Decrement:
1481 case AK_Dereference:
1482 // These need the object's value.
1483 return false;
1484
1487 case AK_Assign:
1488 case AK_Construct:
1489 case AK_Destroy:
1490 // Construction and destruction don't need the value.
1491 return true;
1492
1493 case AK_MemberCall:
1494 case AK_DynamicCast:
1495 case AK_TypeId:
1496 // These aren't really meaningful on scalars.
1497 return true;
1498 }
1499 llvm_unreachable("unknown access kind");
1500}
1501
1502namespace {
1503 struct ComplexValue {
1504 private:
1505 bool IsInt;
1506
1507 public:
1508 APSInt IntReal, IntImag;
1509 APFloat FloatReal, FloatImag;
1510
1511 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512
1513 void makeComplexFloat() { IsInt = false; }
1514 bool isComplexFloat() const { return !IsInt; }
1515 APFloat &getComplexFloatReal() { return FloatReal; }
1516 APFloat &getComplexFloatImag() { return FloatImag; }
1517
1518 void makeComplexInt() { IsInt = true; }
1519 bool isComplexInt() const { return IsInt; }
1520 APSInt &getComplexIntReal() { return IntReal; }
1521 APSInt &getComplexIntImag() { return IntImag; }
1522
1523 void moveInto(APValue &v) const {
1524 if (isComplexFloat())
1525 v = APValue(FloatReal, FloatImag);
1526 else
1527 v = APValue(IntReal, IntImag);
1528 }
1529 void setFrom(const APValue &v) {
1530 assert(v.isComplexFloat() || v.isComplexInt());
1531 if (v.isComplexFloat()) {
1532 makeComplexFloat();
1533 FloatReal = v.getComplexFloatReal();
1534 FloatImag = v.getComplexFloatImag();
1535 } else {
1536 makeComplexInt();
1537 IntReal = v.getComplexIntReal();
1538 IntImag = v.getComplexIntImag();
1539 }
1540 }
1541 };
1542
1543 struct LValue {
1544 APValue::LValueBase Base;
1545 CharUnits Offset;
1546 SubobjectDesignator Designator;
1547 bool IsNullPtr : 1;
1548 bool InvalidBase : 1;
1549 // P2280R4 track if we have an unknown reference or pointer.
1550 bool AllowConstexprUnknown = false;
1551
1552 const APValue::LValueBase getLValueBase() const { return Base; }
1553 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1554 CharUnits &getLValueOffset() { return Offset; }
1555 const CharUnits &getLValueOffset() const { return Offset; }
1556 SubobjectDesignator &getLValueDesignator() { return Designator; }
1557 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1558 bool isNullPointer() const { return IsNullPtr;}
1559
1560 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1561 unsigned getLValueVersion() const { return Base.getVersion(); }
1562
1563 void moveInto(APValue &V) const {
1564 if (Designator.Invalid)
1565 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1566 else {
1567 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1568 V = APValue(Base, Offset, Designator.Entries,
1569 Designator.IsOnePastTheEnd, IsNullPtr);
1570 }
1571 if (AllowConstexprUnknown)
1572 V.setConstexprUnknown();
1573 }
1574 void setFrom(const ASTContext &Ctx, const APValue &V) {
1575 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576 Base = V.getLValueBase();
1577 Offset = V.getLValueOffset();
1578 InvalidBase = false;
1579 Designator = SubobjectDesignator(Ctx, V);
1580 IsNullPtr = V.isNullPointer();
1581 AllowConstexprUnknown = V.allowConstexprUnknown();
1582 }
1583
1584 void set(APValue::LValueBase B, bool BInvalid = false) {
1585#ifndef NDEBUG
1586 // We only allow a few types of invalid bases. Enforce that here.
1587 if (BInvalid) {
1588 const auto *E = B.get<const Expr *>();
1589 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590 "Unexpected type of invalid base");
1591 }
1592#endif
1593
1594 Base = B;
1595 Offset = CharUnits::fromQuantity(0);
1596 InvalidBase = BInvalid;
1597 Designator = SubobjectDesignator(getType(B));
1598 IsNullPtr = false;
1599 AllowConstexprUnknown = false;
1600 }
1601
1602 void setNull(ASTContext &Ctx, QualType PointerTy) {
1603 Base = (const ValueDecl *)nullptr;
1604 Offset =
1606 InvalidBase = false;
1607 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1608 IsNullPtr = true;
1609 AllowConstexprUnknown = false;
1610 }
1611
1612 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1613 set(B, true);
1614 }
1615
1616 std::string toString(ASTContext &Ctx, QualType T) const {
1617 APValue Printable;
1618 moveInto(Printable);
1619 return Printable.getAsString(Ctx, T);
1620 }
1621
1622 private:
1623 // Check that this LValue is not based on a null pointer. If it is, produce
1624 // a diagnostic and mark the designator as invalid.
1625 template <typename GenDiagType>
1626 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1627 if (Designator.Invalid)
1628 return false;
1629 if (IsNullPtr) {
1630 GenDiag();
1631 Designator.setInvalid();
1632 return false;
1633 }
1634 return true;
1635 }
1636
1637 public:
1638 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1639 CheckSubobjectKind CSK) {
1640 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1641 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1642 });
1643 }
1644
1645 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1646 AccessKinds AK) {
1647 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1648 if (AK == AccessKinds::AK_Dereference)
1649 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1650 else
1651 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1652 });
1653 }
1654
1655 // Check this LValue refers to an object. If not, set the designator to be
1656 // invalid and emit a diagnostic.
1657 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1658 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1659 Designator.checkSubobject(Info, E, CSK);
1660 }
1661
1662 void addDecl(EvalInfo &Info, const Expr *E,
1663 const Decl *D, bool Virtual = false) {
1664 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1665 Designator.addDeclUnchecked(D, Virtual);
1666 }
1667 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1668 if (!Designator.Entries.empty()) {
1669 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1670 Designator.setInvalid();
1671 return;
1672 }
1673 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1674 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1675 getType(Base).getNonReferenceType()->isArrayType());
1676 Designator.FirstEntryIsAnUnsizedArray = true;
1677 Designator.addUnsizedArrayUnchecked(ElemTy);
1678 }
1679 }
1680 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1681 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1682 Designator.addArrayUnchecked(CAT);
1683 }
1684 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1685 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1686 Designator.addComplexUnchecked(EltTy, Imag);
1687 }
1688 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1689 uint64_t Size, uint64_t Idx) {
1690 if (checkSubobject(Info, E, CSK_VectorElement))
1691 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1692 }
1693 void clearIsNullPointer() {
1694 IsNullPtr = false;
1695 }
1696 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1697 const APSInt &Index, CharUnits ElementSize) {
1698 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1699 // but we're not required to diagnose it and it's valid in C++.)
1700 if (!Index)
1701 return;
1702
1703 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1704 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1705 // offsets.
1706 uint64_t Offset64 = Offset.getQuantity();
1707 uint64_t ElemSize64 = ElementSize.getQuantity();
1708 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1709 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1710
1711 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1712 Designator.adjustIndex(Info, E, Index, *this);
1713 clearIsNullPointer();
1714 }
1715 void adjustOffset(CharUnits N) {
1716 Offset += N;
1717 if (N.getQuantity())
1718 clearIsNullPointer();
1719 }
1720 };
1721
1722 struct MemberPtr {
1723 MemberPtr() {}
1724 explicit MemberPtr(const ValueDecl *Decl)
1725 : DeclAndIsDerivedMember(Decl, false) {}
1726
1727 /// The member or (direct or indirect) field referred to by this member
1728 /// pointer, or 0 if this is a null member pointer.
1729 const ValueDecl *getDecl() const {
1730 return DeclAndIsDerivedMember.getPointer();
1731 }
1732 /// Is this actually a member of some type derived from the relevant class?
1733 bool isDerivedMember() const {
1734 return DeclAndIsDerivedMember.getInt();
1735 }
1736 /// Get the class which the declaration actually lives in.
1737 const CXXRecordDecl *getContainingRecord() const {
1738 return cast<CXXRecordDecl>(
1739 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1740 }
1741
1742 void moveInto(APValue &V) const {
1743 V = APValue(getDecl(), isDerivedMember(), Path);
1744 }
1745 void setFrom(const APValue &V) {
1746 assert(V.isMemberPointer());
1747 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1748 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1749 Path.clear();
1750 llvm::append_range(Path, V.getMemberPointerPath());
1751 }
1752
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;
1760
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;
1778 }
1779 Path.pop_back();
1780 return true;
1781 }
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;
1789 }
1790 if (!castBack(Derived))
1791 return false;
1792 if (Path.empty())
1793 DeclAndIsDerivedMember.setInt(false);
1794 return true;
1795 }
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;
1805 }
1806 return castBack(Base);
1807 }
1808 };
1809
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;
1817 }
1818}
1819
1820void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1821 const LValue &LV) {
1822 if (Invalid || !N)
1823 return;
1824 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1825 if (isMostDerivedAnUnsizedArray()) {
1826 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1827 // Can't verify -- trust that the user is doing the right thing (or if
1828 // not, trust that the caller will catch the bad behavior).
1829 // FIXME: Should we reject if this overflows, at least?
1830 Entries.back() =
1831 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1832 return;
1833 }
1834
1835 // [expr.add]p4: For the purposes of these operators, a pointer to a
1836 // nonarray object behaves the same as a pointer to the first element of
1837 // an array of length one with the type of the object as its element type.
1838 bool IsArray =
1839 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1840 uint64_t ArrayIndex =
1841 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1842 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1843
1844 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1845 if (!Info.checkingPotentialConstantExpression() ||
1846 !LV.AllowConstexprUnknown) {
1847 // Calculate the actual index in a wide enough type, so we can include
1848 // it in the note.
1849 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1850 (llvm::APInt &)N += ArrayIndex;
1851 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1852 diagnosePointerArithmetic(Info, E, N);
1853 }
1854 setInvalid();
1855 return;
1856 }
1857
1858 ArrayIndex += TruncatedN;
1859 assert(ArrayIndex <= ArraySize &&
1860 "bounds check succeeded for out-of-bounds index");
1861
1862 if (IsArray)
1863 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1864 else
1865 IsOnePastTheEnd = (ArrayIndex != 0);
1866}
1867
1868static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1869static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1870 const LValue &This, const Expr *E,
1871 bool AllowNonLiteralTypes = false);
1872static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1873 bool InvalidBaseOK = false);
1874static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1875 bool InvalidBaseOK = false);
1876static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1877 EvalInfo &Info);
1878static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1879static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1880static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1881 EvalInfo &Info);
1882static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1883static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1884static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1885 EvalInfo &Info);
1886static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1887static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1888 EvalInfo &Info,
1889 std::string *StringResult = nullptr);
1890
1891/// Evaluate an integer or fixed point expression into an APResult.
1892static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1893 EvalInfo &Info);
1894
1895/// Evaluate only a fixed point expression into an APResult.
1896static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1897 EvalInfo &Info);
1898
1899//===----------------------------------------------------------------------===//
1900// Misc utilities
1901//===----------------------------------------------------------------------===//
1902
1903/// Negate an APSInt in place, converting it to a signed form if necessary, and
1904/// preserving its value (by extending by up to one bit as needed).
1905static void negateAsSigned(APSInt &Int) {
1906 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1907 Int = Int.extend(Int.getBitWidth() + 1);
1908 Int.setIsSigned(true);
1909 }
1910 Int = -Int;
1911}
1912
1913template<typename KeyT>
1914APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1915 ScopeKind Scope, LValue &LV) {
1916 unsigned Version = getTempVersion();
1917 APValue::LValueBase Base(Key, Index, Version);
1918 LV.set(Base);
1919 return createLocal(Base, Key, T, Scope);
1920}
1921
1922/// Allocate storage for a parameter of a function call made in this frame.
1923APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1924 LValue &LV) {
1925 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1926 APValue::LValueBase Base(PVD, Index, Args.Version);
1927 LV.set(Base);
1928 // We always destroy parameters at the end of the call, even if we'd allow
1929 // them to live to the end of the full-expression at runtime, in order to
1930 // give portable results and match other compilers.
1931 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1932}
1933
1934APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1935 QualType T, ScopeKind Scope) {
1936 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1937 unsigned Version = Base.getVersion();
1938 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1939 assert(Result.isAbsent() && "local created multiple times");
1940
1941 // If we're creating a local immediately in the operand of a speculative
1942 // evaluation, don't register a cleanup to be run outside the speculative
1943 // evaluation context, since we won't actually be able to initialize this
1944 // object.
1945 if (Index <= Info.SpeculativeEvaluationDepth) {
1946 if (T.isDestructedType())
1947 Info.noteSideEffect();
1948 } else {
1949 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1950 }
1951 return Result;
1952}
1953
1954APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1955 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1956 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1957 return nullptr;
1958 }
1959
1960 DynamicAllocLValue DA(NumHeapAllocs++);
1962 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1963 std::forward_as_tuple(DA), std::tuple<>());
1964 assert(Result.second && "reused a heap alloc index?");
1965 Result.first->second.AllocExpr = E;
1966 return &Result.first->second.Value;
1967}
1968
1969/// Produce a string describing the given constexpr call.
1970void CallStackFrame::describe(raw_ostream &Out) const {
1971 unsigned ArgIndex = 0;
1972 bool IsMemberCall =
1973 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1974 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1975
1976 if (!IsMemberCall)
1977 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1978 /*Qualified=*/false);
1979
1980 if (This && IsMemberCall) {
1981 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1984 /*Indentation=*/0);
1985 if (Object->getType()->isPointerType())
1986 Out << "->";
1987 else
1988 Out << ".";
1989 } else if (const auto *OCE =
1990 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1991 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1992 Info.Ctx.getPrintingPolicy(),
1993 /*Indentation=*/0);
1994 Out << ".";
1995 } else {
1996 APValue Val;
1997 This->moveInto(Val);
1998 Val.printPretty(
1999 Out, Info.Ctx,
2000 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2001 Out << ".";
2002 }
2003 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2004 /*Qualified=*/false);
2005 IsMemberCall = false;
2006 }
2007
2008 Out << '(';
2009
2010 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2011 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2012 if (ArgIndex > (unsigned)IsMemberCall)
2013 Out << ", ";
2014
2015 const ParmVarDecl *Param = *I;
2016 APValue *V = Info.getParamSlot(Arguments, Param);
2017 if (V)
2018 V->printPretty(Out, Info.Ctx, Param->getType());
2019 else
2020 Out << "<...>";
2021
2022 if (ArgIndex == 0 && IsMemberCall)
2023 Out << "->" << *Callee << '(';
2024 }
2025
2026 Out << ')';
2027}
2028
2029/// Evaluate an expression to see if it had side-effects, and discard its
2030/// result.
2031/// \return \c true if the caller should keep evaluating.
2032static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2033 assert(!E->isValueDependent());
2034 APValue Scratch;
2035 if (!Evaluate(Scratch, Info, E))
2036 // We don't need the value, but we might have skipped a side effect here.
2037 return Info.noteSideEffect();
2038 return true;
2039}
2040
2041/// Should this call expression be treated as forming an opaque constant?
2042static bool IsOpaqueConstantCall(const CallExpr *E) {
2043 unsigned Builtin = E->getBuiltinCallee();
2044 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2045 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2046 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2047 Builtin == Builtin::BI__builtin_function_start);
2048}
2049
2050static bool IsOpaqueConstantCall(const LValue &LVal) {
2051 const auto *BaseExpr =
2052 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2053 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2054}
2055
2057 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2058 // constant expression of pointer type that evaluates to...
2059
2060 // ... a null pointer value, or a prvalue core constant expression of type
2061 // std::nullptr_t.
2062 if (!B)
2063 return true;
2064
2065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2066 // ... the address of an object with static storage duration,
2067 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2068 return VD->hasGlobalStorage();
2070 return true;
2071 // ... the address of a function,
2072 // ... the address of a GUID [MS extension],
2073 // ... the address of an unnamed global constant
2075 }
2076
2077 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2078 return true;
2079
2080 const Expr *E = B.get<const Expr*>();
2081 switch (E->getStmtClass()) {
2082 default:
2083 return false;
2084 case Expr::CompoundLiteralExprClass: {
2086 return CLE->isFileScope() && CLE->isLValue();
2087 }
2088 case Expr::MaterializeTemporaryExprClass:
2089 // A materialized temporary might have been lifetime-extended to static
2090 // storage duration.
2091 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2092 // A string literal has static storage duration.
2093 case Expr::StringLiteralClass:
2094 case Expr::PredefinedExprClass:
2095 case Expr::ObjCStringLiteralClass:
2096 case Expr::ObjCEncodeExprClass:
2097 return true;
2098 case Expr::ObjCBoxedExprClass:
2099 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2100 case Expr::CallExprClass:
2102 // For GCC compatibility, &&label has static storage duration.
2103 case Expr::AddrLabelExprClass:
2104 return true;
2105 // A Block literal expression may be used as the initialization value for
2106 // Block variables at global or local static scope.
2107 case Expr::BlockExprClass:
2108 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2109 // The APValue generated from a __builtin_source_location will be emitted as a
2110 // literal.
2111 case Expr::SourceLocExprClass:
2112 return true;
2113 case Expr::ImplicitValueInitExprClass:
2114 // FIXME:
2115 // We can never form an lvalue with an implicit value initialization as its
2116 // base through expression evaluation, so these only appear in one case: the
2117 // implicit variable declaration we invent when checking whether a constexpr
2118 // constructor can produce a constant expression. We must assume that such
2119 // an expression might be a global lvalue.
2120 return true;
2121 }
2122}
2123
2124static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2125 return LVal.Base.dyn_cast<const ValueDecl*>();
2126}
2127
2128// Information about an LValueBase that is some kind of string.
2131 StringRef Bytes;
2133};
2134
2135// Gets the lvalue base of LVal as a string.
2136static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2137 LValueBaseString &AsString) {
2138 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2139 if (!BaseExpr)
2140 return false;
2141
2142 // For ObjCEncodeExpr, we need to compute and store the string.
2143 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2144 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2145 AsString.ObjCEncodeStorage);
2146 AsString.Bytes = AsString.ObjCEncodeStorage;
2147 AsString.CharWidth = 1;
2148 return true;
2149 }
2150
2151 // Otherwise, we have a StringLiteral.
2152 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2153 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2154 Lit = PE->getFunctionName();
2155
2156 if (!Lit)
2157 return false;
2158
2159 AsString.Bytes = Lit->getBytes();
2160 AsString.CharWidth = Lit->getCharByteWidth();
2161 return true;
2162}
2163
2164// Determine whether two string literals potentially overlap. This will be the
2165// case if they agree on the values of all the bytes on the overlapping region
2166// between them.
2167//
2168// The overlapping region is the portion of the two string literals that must
2169// overlap in memory if the pointers actually point to the same address at
2170// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2171// the overlapping region is "cdef\0", which in this case does agree, so the
2172// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2173// "bazbar" + 3, the overlapping region contains all of both strings, so they
2174// are not potentially overlapping, even though they agree from the given
2175// addresses onwards.
2176//
2177// See open core issue CWG2765 which is discussing the desired rule here.
2178static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2179 const LValue &LHS,
2180 const LValue &RHS) {
2181 LValueBaseString LHSString, RHSString;
2182 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2183 !GetLValueBaseAsString(Info, RHS, RHSString))
2184 return false;
2185
2186 // This is the byte offset to the location of the first character of LHS
2187 // within RHS. We don't need to look at the characters of one string that
2188 // would appear before the start of the other string if they were merged.
2189 CharUnits Offset = RHS.Offset - LHS.Offset;
2190 if (Offset.isNegative()) {
2191 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2192 return false;
2193 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2194 } else {
2195 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2196 return false;
2197 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2198 }
2199
2200 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2201 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2202 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2203 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2204
2205 // The null terminator isn't included in the string data, so check for it
2206 // manually. If the longer string doesn't have a null terminator where the
2207 // shorter string ends, they aren't potentially overlapping.
2208 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2209 if (Shorter.size() + NullByte >= Longer.size())
2210 break;
2211 if (Longer[Shorter.size() + NullByte])
2212 return false;
2213 }
2214
2215 // Otherwise, they're potentially overlapping if and only if the overlapping
2216 // region is the same.
2217 return Shorter == Longer.take_front(Shorter.size());
2218}
2219
2220static bool IsWeakLValue(const LValue &Value) {
2222 return Decl && Decl->isWeak();
2223}
2224
2225static bool isZeroSized(const LValue &Value) {
2227 if (isa_and_nonnull<VarDecl>(Decl)) {
2228 QualType Ty = Decl->getType();
2229 if (Ty->isArrayType())
2230 return Ty->isIncompleteType() ||
2231 Decl->getASTContext().getTypeSize(Ty) == 0;
2232 }
2233 return false;
2234}
2235
2236static bool HasSameBase(const LValue &A, const LValue &B) {
2237 if (!A.getLValueBase())
2238 return !B.getLValueBase();
2239 if (!B.getLValueBase())
2240 return false;
2241
2242 if (A.getLValueBase().getOpaqueValue() !=
2243 B.getLValueBase().getOpaqueValue())
2244 return false;
2245
2246 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2247 A.getLValueVersion() == B.getLValueVersion();
2248}
2249
2250static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2251 assert(Base && "no location for a null lvalue");
2252 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2253
2254 // For a parameter, find the corresponding call stack frame (if it still
2255 // exists), and point at the parameter of the function definition we actually
2256 // invoked.
2257 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2258 unsigned Idx = PVD->getFunctionScopeIndex();
2259 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2260 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2261 F->Arguments.Version == Base.getVersion() && F->Callee &&
2262 Idx < F->Callee->getNumParams()) {
2263 VD = F->Callee->getParamDecl(Idx);
2264 break;
2265 }
2266 }
2267 }
2268
2269 if (VD)
2270 Info.Note(VD->getLocation(), diag::note_declared_at);
2271 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2272 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2273 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2274 // FIXME: Produce a note for dangling pointers too.
2275 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2276 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2277 diag::note_constexpr_dynamic_alloc_here);
2278 }
2279
2280 // We have no information to show for a typeid(T) object.
2281}
2282
2287
2288/// Materialized temporaries that we've already checked to determine if they're
2289/// initializsed by a constant expression.
2292
2294 EvalInfo &Info, SourceLocation DiagLoc,
2295 QualType Type, const APValue &Value,
2296 ConstantExprKind Kind,
2297 const FieldDecl *SubobjectDecl,
2298 CheckedTemporaries &CheckedTemps);
2299
2300/// Check that this reference or pointer core constant expression is a valid
2301/// value for an address or reference constant expression. Return true if we
2302/// can fold this expression, whether or not it's a constant expression.
2303static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2304 QualType Type, const LValue &LVal,
2305 ConstantExprKind Kind,
2306 CheckedTemporaries &CheckedTemps) {
2307 bool IsReferenceType = Type->isReferenceType();
2308
2309 APValue::LValueBase Base = LVal.getLValueBase();
2310 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2311
2312 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2313 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2314
2315 // Additional restrictions apply in a template argument. We only enforce the
2316 // C++20 restrictions here; additional syntactic and semantic restrictions
2317 // are applied elsewhere.
2318 if (isTemplateArgument(Kind)) {
2319 int InvalidBaseKind = -1;
2320 StringRef Ident;
2321 if (Base.is<TypeInfoLValue>())
2322 InvalidBaseKind = 0;
2323 else if (isa_and_nonnull<StringLiteral>(BaseE))
2324 InvalidBaseKind = 1;
2325 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2326 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2327 InvalidBaseKind = 2;
2328 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2329 InvalidBaseKind = 3;
2330 Ident = PE->getIdentKindName();
2331 }
2332
2333 if (InvalidBaseKind != -1) {
2334 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2335 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2336 << Ident;
2337 return false;
2338 }
2339 }
2340
2341 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2342 FD && FD->isImmediateFunction()) {
2343 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2344 << !Type->isAnyPointerType();
2345 Info.Note(FD->getLocation(), diag::note_declared_at);
2346 return false;
2347 }
2348
2349 // Check that the object is a global. Note that the fake 'this' object we
2350 // manufacture when checking potential constant expressions is conservatively
2351 // assumed to be global here.
2352 if (!IsGlobalLValue(Base)) {
2353 if (Info.getLangOpts().CPlusPlus11) {
2354 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2355 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2356 << BaseVD;
2357 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2358 if (VarD && VarD->isConstexpr()) {
2359 // Non-static local constexpr variables have unintuitive semantics:
2360 // constexpr int a = 1;
2361 // constexpr const int *p = &a;
2362 // ... is invalid because the address of 'a' is not constant. Suggest
2363 // adding a 'static' in this case.
2364 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2365 << VarD
2366 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2367 } else {
2368 NoteLValueLocation(Info, Base);
2369 }
2370 } else {
2371 Info.FFDiag(Loc);
2372 }
2373 // Don't allow references to temporaries to escape.
2374 return false;
2375 }
2376 assert((Info.checkingPotentialConstantExpression() ||
2377 LVal.getLValueCallIndex() == 0) &&
2378 "have call index for global lvalue");
2379
2380 if (LVal.allowConstexprUnknown()) {
2381 if (BaseVD) {
2382 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2383 NoteLValueLocation(Info, Base);
2384 } else {
2385 Info.FFDiag(Loc);
2386 }
2387 return false;
2388 }
2389
2390 if (Base.is<DynamicAllocLValue>()) {
2391 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2392 << IsReferenceType << !Designator.Entries.empty();
2393 NoteLValueLocation(Info, Base);
2394 return false;
2395 }
2396
2397 if (BaseVD) {
2398 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2399 // Check if this is a thread-local variable.
2400 if (Var->getTLSKind())
2401 // FIXME: Diagnostic!
2402 return false;
2403
2404 // A dllimport variable never acts like a constant, unless we're
2405 // evaluating a value for use only in name mangling.
2406 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2407 // FIXME: Diagnostic!
2408 return false;
2409
2410 // In CUDA/HIP device compilation, only device side variables have
2411 // constant addresses.
2412 if (Info.getASTContext().getLangOpts().CUDA &&
2413 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2414 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2415 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2416 !Var->hasAttr<CUDAConstantAttr>() &&
2417 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2418 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2419 Var->hasAttr<HIPManagedAttr>())
2420 return false;
2421 }
2422 }
2423 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2424 // __declspec(dllimport) must be handled very carefully:
2425 // We must never initialize an expression with the thunk in C++.
2426 // Doing otherwise would allow the same id-expression to yield
2427 // different addresses for the same function in different translation
2428 // units. However, this means that we must dynamically initialize the
2429 // expression with the contents of the import address table at runtime.
2430 //
2431 // The C language has no notion of ODR; furthermore, it has no notion of
2432 // dynamic initialization. This means that we are permitted to
2433 // perform initialization with the address of the thunk.
2434 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2435 FD->hasAttr<DLLImportAttr>())
2436 // FIXME: Diagnostic!
2437 return false;
2438 }
2439 } else if (const auto *MTE =
2440 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2441 if (CheckedTemps.insert(MTE).second) {
2442 QualType TempType = getType(Base);
2443 if (TempType.isDestructedType()) {
2444 Info.FFDiag(MTE->getExprLoc(),
2445 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2446 << TempType;
2447 return false;
2448 }
2449
2450 APValue *V = MTE->getOrCreateValue(false);
2451 assert(V && "evasluation result refers to uninitialised temporary");
2453 Info, MTE->getExprLoc(), TempType, *V, Kind,
2454 /*SubobjectDecl=*/nullptr, CheckedTemps))
2455 return false;
2456 }
2457 }
2458
2459 // Allow address constant expressions to be past-the-end pointers. This is
2460 // an extension: the standard requires them to point to an object.
2461 if (!IsReferenceType)
2462 return true;
2463
2464 // A reference constant expression must refer to an object.
2465 if (!Base) {
2466 // FIXME: diagnostic
2467 Info.CCEDiag(Loc);
2468 return true;
2469 }
2470
2471 // Does this refer one past the end of some object?
2472 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2473 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2474 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2475 NoteLValueLocation(Info, Base);
2476 }
2477
2478 return true;
2479}
2480
2481/// Member pointers are constant expressions unless they point to a
2482/// non-virtual dllimport member function.
2483static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2484 SourceLocation Loc,
2485 QualType Type,
2486 const APValue &Value,
2487 ConstantExprKind Kind) {
2488 const ValueDecl *Member = Value.getMemberPointerDecl();
2489 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2490 if (!FD)
2491 return true;
2492 if (FD->isImmediateFunction()) {
2493 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2494 Info.Note(FD->getLocation(), diag::note_declared_at);
2495 return false;
2496 }
2497 return isForManglingOnly(Kind) || FD->isVirtual() ||
2498 !FD->hasAttr<DLLImportAttr>();
2499}
2500
2501/// Check that this core constant expression is of literal type, and if not,
2502/// produce an appropriate diagnostic.
2503static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2504 const LValue *This = nullptr) {
2505 // The restriction to literal types does not exist in C++23 anymore.
2506 if (Info.getLangOpts().CPlusPlus23)
2507 return true;
2508
2509 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2510 return true;
2511
2512 // C++1y: A constant initializer for an object o [...] may also invoke
2513 // constexpr constructors for o and its subobjects even if those objects
2514 // are of non-literal class types.
2515 //
2516 // C++11 missed this detail for aggregates, so classes like this:
2517 // struct foo_t { union { int i; volatile int j; } u; };
2518 // are not (obviously) initializable like so:
2519 // __attribute__((__require_constant_initialization__))
2520 // static const foo_t x = {{0}};
2521 // because "i" is a subobject with non-literal initialization (due to the
2522 // volatile member of the union). See:
2523 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2524 // Therefore, we use the C++1y behavior.
2525 if (This && Info.EvaluatingDecl == This->getLValueBase())
2526 return true;
2527
2528 // Prvalue constant expressions must be of literal types.
2529 if (Info.getLangOpts().CPlusPlus11)
2530 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2531 << E->getType();
2532 else
2533 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2534 return false;
2535}
2536
2538 EvalInfo &Info, SourceLocation DiagLoc,
2539 QualType Type, const APValue &Value,
2540 ConstantExprKind Kind,
2541 const FieldDecl *SubobjectDecl,
2542 CheckedTemporaries &CheckedTemps) {
2543 if (!Value.hasValue()) {
2544 if (SubobjectDecl) {
2545 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2546 << /*(name)*/ 1 << SubobjectDecl;
2547 Info.Note(SubobjectDecl->getLocation(),
2548 diag::note_constexpr_subobject_declared_here);
2549 } else {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*of type*/ 0 << Type;
2552 }
2553 return false;
2554 }
2555
2556 // We allow _Atomic(T) to be initialized from anything that T can be
2557 // initialized from.
2558 if (const AtomicType *AT = Type->getAs<AtomicType>())
2559 Type = AT->getValueType();
2560
2561 // Core issue 1454: For a literal constant expression of array or class type,
2562 // each subobject of its value shall have been initialized by a constant
2563 // expression.
2564 if (Value.isArray()) {
2566 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2567 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2568 Value.getArrayInitializedElt(I), Kind,
2569 SubobjectDecl, CheckedTemps))
2570 return false;
2571 }
2572 if (!Value.hasArrayFiller())
2573 return true;
2574 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2575 Value.getArrayFiller(), Kind, SubobjectDecl,
2576 CheckedTemps);
2577 }
2578 if (Value.isUnion() && Value.getUnionField()) {
2579 return CheckEvaluationResult(
2580 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2581 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2582 }
2583 if (Value.isStruct()) {
2584 auto *RD = Type->castAsRecordDecl();
2585 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2586 unsigned BaseIndex = 0;
2587 for (const CXXBaseSpecifier &BS : CD->bases()) {
2588 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2589 if (!BaseValue.hasValue()) {
2590 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2591 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2592 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2593 return false;
2594 }
2595 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2596 Kind, /*SubobjectDecl=*/nullptr,
2597 CheckedTemps))
2598 return false;
2599 ++BaseIndex;
2600 }
2601 }
2602 for (const auto *I : RD->fields()) {
2603 if (I->isUnnamedBitField())
2604 continue;
2605
2606 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2607 Value.getStructField(I->getFieldIndex()), Kind,
2608 I, CheckedTemps))
2609 return false;
2610 }
2611 }
2612
2613 if (Value.isLValue() &&
2615 LValue LVal;
2616 LVal.setFrom(Info.Ctx, Value);
2617 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2618 CheckedTemps);
2619 }
2620
2621 if (Value.isMemberPointer() &&
2623 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2624
2625 // Everything else is fine.
2626 return true;
2627}
2628
2629/// Check that this core constant expression value is a valid value for a
2630/// constant expression. If not, report an appropriate diagnostic. Does not
2631/// check that the expression is of literal type.
2632static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2633 QualType Type, const APValue &Value,
2634 ConstantExprKind Kind) {
2635 // Nothing to check for a constant expression of type 'cv void'.
2636 if (Type->isVoidType())
2637 return true;
2638
2639 CheckedTemporaries CheckedTemps;
2641 Info, DiagLoc, Type, Value, Kind,
2642 /*SubobjectDecl=*/nullptr, CheckedTemps);
2643}
2644
2645/// Check that this evaluated value is fully-initialized and can be loaded by
2646/// an lvalue-to-rvalue conversion.
2647static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2648 QualType Type, const APValue &Value) {
2649 CheckedTemporaries CheckedTemps;
2650 return CheckEvaluationResult(
2652 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2653}
2654
2655/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2656/// "the allocated storage is deallocated within the evaluation".
2657static bool CheckMemoryLeaks(EvalInfo &Info) {
2658 if (!Info.HeapAllocs.empty()) {
2659 // We can still fold to a constant despite a compile-time memory leak,
2660 // so long as the heap allocation isn't referenced in the result (we check
2661 // that in CheckConstantExpression).
2662 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2663 diag::note_constexpr_memory_leak)
2664 << unsigned(Info.HeapAllocs.size() - 1);
2665 }
2666 return true;
2667}
2668
2669static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2670 // A null base expression indicates a null pointer. These are always
2671 // evaluatable, and they are false unless the offset is zero.
2672 if (!Value.getLValueBase()) {
2673 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2674 Result = !Value.getLValueOffset().isZero();
2675 return true;
2676 }
2677
2678 // We have a non-null base. These are generally known to be true, but if it's
2679 // a weak declaration it can be null at runtime.
2680 Result = true;
2681 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2682 return !Decl || !Decl->isWeak();
2683}
2684
2685static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2686 // TODO: This function should produce notes if it fails.
2687 switch (Val.getKind()) {
2688 case APValue::None:
2690 return false;
2691 case APValue::Int:
2692 Result = Val.getInt().getBoolValue();
2693 return true;
2695 Result = Val.getFixedPoint().getBoolValue();
2696 return true;
2697 case APValue::Float:
2698 Result = !Val.getFloat().isZero();
2699 return true;
2701 Result = Val.getComplexIntReal().getBoolValue() ||
2702 Val.getComplexIntImag().getBoolValue();
2703 return true;
2705 Result = !Val.getComplexFloatReal().isZero() ||
2706 !Val.getComplexFloatImag().isZero();
2707 return true;
2708 case APValue::LValue:
2709 return EvalPointerValueAsBool(Val, Result);
2711 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2712 return false;
2713 }
2714 Result = Val.getMemberPointerDecl();
2715 return true;
2716 case APValue::Vector:
2717 case APValue::Array:
2718 case APValue::Struct:
2719 case APValue::Union:
2721 return false;
2722 }
2723
2724 llvm_unreachable("unknown APValue kind");
2725}
2726
2727static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2728 EvalInfo &Info) {
2729 assert(!E->isValueDependent());
2730 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2731 APValue Val;
2732 if (!Evaluate(Val, Info, E))
2733 return false;
2734 return HandleConversionToBool(Val, Result);
2735}
2736
2737template<typename T>
2738static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2739 const T &SrcValue, QualType DestType) {
2740 Info.CCEDiag(E, diag::note_constexpr_overflow)
2741 << SrcValue << DestType;
2742 return Info.noteUndefinedBehavior();
2743}
2744
2745static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2746 QualType SrcType, const APFloat &Value,
2747 QualType DestType, APSInt &Result) {
2748 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2749 // Determine whether we are converting to unsigned or signed.
2750 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2751
2752 Result = APSInt(DestWidth, !DestSigned);
2753 bool ignored;
2754 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2755 & APFloat::opInvalidOp)
2756 return HandleOverflow(Info, E, Value, DestType);
2757 return true;
2758}
2759
2760/// Get rounding mode to use in evaluation of the specified expression.
2761///
2762/// If rounding mode is unknown at compile time, still try to evaluate the
2763/// expression. If the result is exact, it does not depend on rounding mode.
2764/// So return "tonearest" mode instead of "dynamic".
2765static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2766 llvm::RoundingMode RM =
2768 if (RM == llvm::RoundingMode::Dynamic)
2769 RM = llvm::RoundingMode::NearestTiesToEven;
2770 return RM;
2771}
2772
2773/// Check if the given evaluation result is allowed for constant evaluation.
2774static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2775 APFloat::opStatus St) {
2776 // In a constant context, assume that any dynamic rounding mode or FP
2777 // exception state matches the default floating-point environment.
2778 if (Info.InConstantContext)
2779 return true;
2780
2781 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2782 if ((St & APFloat::opInexact) &&
2783 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2784 // Inexact result means that it depends on rounding mode. If the requested
2785 // mode is dynamic, the evaluation cannot be made in compile time.
2786 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2787 return false;
2788 }
2789
2790 if ((St != APFloat::opOK) &&
2791 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2793 FPO.getAllowFEnvAccess())) {
2794 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2795 return false;
2796 }
2797
2798 if ((St & APFloat::opStatus::opInvalidOp) &&
2800 // There is no usefully definable result.
2801 Info.FFDiag(E);
2802 return false;
2803 }
2804
2805 // FIXME: if:
2806 // - evaluation triggered other FP exception, and
2807 // - exception mode is not "ignore", and
2808 // - the expression being evaluated is not a part of global variable
2809 // initializer,
2810 // the evaluation probably need to be rejected.
2811 return true;
2812}
2813
2814static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2815 QualType SrcType, QualType DestType,
2816 APFloat &Result) {
2817 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2819 "HandleFloatToFloatCast has been checked with only CastExpr, "
2820 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2821 "the new expression or address the root cause of this usage.");
2822 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2823 APFloat::opStatus St;
2824 APFloat Value = Result;
2825 bool ignored;
2826 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2827 return checkFloatingPointResult(Info, E, St);
2828}
2829
2830static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2831 QualType DestType, QualType SrcType,
2832 const APSInt &Value) {
2833 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2834 // Figure out if this is a truncate, extend or noop cast.
2835 // If the input is signed, do a sign extend, noop, or truncate.
2836 APSInt Result = Value.extOrTrunc(DestWidth);
2837 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2838 if (DestType->isBooleanType())
2839 Result = Value.getBoolValue();
2840 return Result;
2841}
2842
2843static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2844 const FPOptions FPO,
2845 QualType SrcType, const APSInt &Value,
2846 QualType DestType, APFloat &Result) {
2847 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2848 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2850 return checkFloatingPointResult(Info, E, St);
2851}
2852
2853static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2854 APValue &Value, const FieldDecl *FD) {
2855 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2856
2857 if (!Value.isInt()) {
2858 // Trying to store a pointer-cast-to-integer into a bitfield.
2859 // FIXME: In this case, we should provide the diagnostic for casting
2860 // a pointer to an integer.
2861 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2862 Info.FFDiag(E);
2863 return false;
2864 }
2865
2866 APSInt &Int = Value.getInt();
2867 unsigned OldBitWidth = Int.getBitWidth();
2868 unsigned NewBitWidth = FD->getBitWidthValue();
2869 if (NewBitWidth < OldBitWidth)
2870 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2871 return true;
2872}
2873
2874/// Perform the given integer operation, which is known to need at most BitWidth
2875/// bits, and check for overflow in the original type (if that type was not an
2876/// unsigned type).
2877template<typename Operation>
2878static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2879 const APSInt &LHS, const APSInt &RHS,
2880 unsigned BitWidth, Operation Op,
2881 APSInt &Result) {
2882 if (LHS.isUnsigned()) {
2883 Result = Op(LHS, RHS);
2884 return true;
2885 }
2886
2887 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2888 Result = Value.trunc(LHS.getBitWidth());
2889 if (Result.extend(BitWidth) != Value) {
2890 if (Info.checkingForUndefinedBehavior())
2891 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2892 diag::warn_integer_constant_overflow)
2893 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2894 /*UpperCase=*/true, /*InsertSeparators=*/true)
2895 << E->getType() << E->getSourceRange();
2896 return HandleOverflow(Info, E, Value, E->getType());
2897 }
2898 return true;
2899}
2900
2901/// Perform the given binary integer operation.
2902static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2903 const APSInt &LHS, BinaryOperatorKind Opcode,
2904 APSInt RHS, APSInt &Result) {
2905 bool HandleOverflowResult = true;
2906 switch (Opcode) {
2907 default:
2908 Info.FFDiag(E);
2909 return false;
2910 case BO_Mul:
2911 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2912 std::multiplies<APSInt>(), Result);
2913 case BO_Add:
2914 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2915 std::plus<APSInt>(), Result);
2916 case BO_Sub:
2917 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2918 std::minus<APSInt>(), Result);
2919 case BO_And: Result = LHS & RHS; return true;
2920 case BO_Xor: Result = LHS ^ RHS; return true;
2921 case BO_Or: Result = LHS | RHS; return true;
2922 case BO_Div:
2923 case BO_Rem:
2924 if (RHS == 0) {
2925 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2926 << E->getRHS()->getSourceRange();
2927 return false;
2928 }
2929 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2930 // this operation and gives the two's complement result.
2931 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2932 LHS.isMinSignedValue())
2933 HandleOverflowResult = HandleOverflow(
2934 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2935 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2936 return HandleOverflowResult;
2937 case BO_Shl: {
2938 if (Info.getLangOpts().OpenCL)
2939 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2940 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2941 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2942 RHS.isUnsigned());
2943 else if (RHS.isSigned() && RHS.isNegative()) {
2944 // During constant-folding, a negative shift is an opposite shift. Such
2945 // a shift is not a constant expression.
2946 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2947 if (!Info.noteUndefinedBehavior())
2948 return false;
2949 RHS = -RHS;
2950 goto shift_right;
2951 }
2952 shift_left:
2953 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2954 // the shifted type.
2955 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2956 if (SA != RHS) {
2957 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2958 << RHS << E->getType() << LHS.getBitWidth();
2959 if (!Info.noteUndefinedBehavior())
2960 return false;
2961 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2962 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2963 // operand, and must not overflow the corresponding unsigned type.
2964 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2965 // E1 x 2^E2 module 2^N.
2966 if (LHS.isNegative()) {
2967 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2968 if (!Info.noteUndefinedBehavior())
2969 return false;
2970 } else if (LHS.countl_zero() < SA) {
2971 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2972 if (!Info.noteUndefinedBehavior())
2973 return false;
2974 }
2975 }
2976 Result = LHS << SA;
2977 return true;
2978 }
2979 case BO_Shr: {
2980 if (Info.getLangOpts().OpenCL)
2981 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2982 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2983 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2984 RHS.isUnsigned());
2985 else if (RHS.isSigned() && RHS.isNegative()) {
2986 // During constant-folding, a negative shift is an opposite shift. Such a
2987 // shift is not a constant expression.
2988 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2989 if (!Info.noteUndefinedBehavior())
2990 return false;
2991 RHS = -RHS;
2992 goto shift_left;
2993 }
2994 shift_right:
2995 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2996 // shifted type.
2997 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2998 if (SA != RHS) {
2999 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3000 << RHS << E->getType() << LHS.getBitWidth();
3001 if (!Info.noteUndefinedBehavior())
3002 return false;
3003 }
3004
3005 Result = LHS >> SA;
3006 return true;
3007 }
3008
3009 case BO_LT: Result = LHS < RHS; return true;
3010 case BO_GT: Result = LHS > RHS; return true;
3011 case BO_LE: Result = LHS <= RHS; return true;
3012 case BO_GE: Result = LHS >= RHS; return true;
3013 case BO_EQ: Result = LHS == RHS; return true;
3014 case BO_NE: Result = LHS != RHS; return true;
3015 case BO_Cmp:
3016 llvm_unreachable("BO_Cmp should be handled elsewhere");
3017 }
3018}
3019
3020/// Perform the given binary floating-point operation, in-place, on LHS.
3021static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3022 APFloat &LHS, BinaryOperatorKind Opcode,
3023 const APFloat &RHS) {
3024 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3025 APFloat::opStatus St;
3026 switch (Opcode) {
3027 default:
3028 Info.FFDiag(E);
3029 return false;
3030 case BO_Mul:
3031 St = LHS.multiply(RHS, RM);
3032 break;
3033 case BO_Add:
3034 St = LHS.add(RHS, RM);
3035 break;
3036 case BO_Sub:
3037 St = LHS.subtract(RHS, RM);
3038 break;
3039 case BO_Div:
3040 // [expr.mul]p4:
3041 // If the second operand of / or % is zero the behavior is undefined.
3042 if (RHS.isZero())
3043 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3044 St = LHS.divide(RHS, RM);
3045 break;
3046 }
3047
3048 // [expr.pre]p4:
3049 // If during the evaluation of an expression, the result is not
3050 // mathematically defined [...], the behavior is undefined.
3051 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3052 if (LHS.isNaN()) {
3053 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3054 return Info.noteUndefinedBehavior();
3055 }
3056
3057 return checkFloatingPointResult(Info, E, St);
3058}
3059
3060static bool handleLogicalOpForVector(const APInt &LHSValue,
3061 BinaryOperatorKind Opcode,
3062 const APInt &RHSValue, APInt &Result) {
3063 bool LHS = (LHSValue != 0);
3064 bool RHS = (RHSValue != 0);
3065
3066 if (Opcode == BO_LAnd)
3067 Result = LHS && RHS;
3068 else
3069 Result = LHS || RHS;
3070 return true;
3071}
3072static bool handleLogicalOpForVector(const APFloat &LHSValue,
3073 BinaryOperatorKind Opcode,
3074 const APFloat &RHSValue, APInt &Result) {
3075 bool LHS = !LHSValue.isZero();
3076 bool RHS = !RHSValue.isZero();
3077
3078 if (Opcode == BO_LAnd)
3079 Result = LHS && RHS;
3080 else
3081 Result = LHS || RHS;
3082 return true;
3083}
3084
3085static bool handleLogicalOpForVector(const APValue &LHSValue,
3086 BinaryOperatorKind Opcode,
3087 const APValue &RHSValue, APInt &Result) {
3088 // The result is always an int type, however operands match the first.
3089 if (LHSValue.getKind() == APValue::Int)
3090 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3091 RHSValue.getInt(), Result);
3092 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3093 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3094 RHSValue.getFloat(), Result);
3095}
3096
3097template <typename APTy>
3098static bool
3100 const APTy &RHSValue, APInt &Result) {
3101 switch (Opcode) {
3102 default:
3103 llvm_unreachable("unsupported binary operator");
3104 case BO_EQ:
3105 Result = (LHSValue == RHSValue);
3106 break;
3107 case BO_NE:
3108 Result = (LHSValue != RHSValue);
3109 break;
3110 case BO_LT:
3111 Result = (LHSValue < RHSValue);
3112 break;
3113 case BO_GT:
3114 Result = (LHSValue > RHSValue);
3115 break;
3116 case BO_LE:
3117 Result = (LHSValue <= RHSValue);
3118 break;
3119 case BO_GE:
3120 Result = (LHSValue >= RHSValue);
3121 break;
3122 }
3123
3124 // The boolean operations on these vector types use an instruction that
3125 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3126 // to -1 to make sure that we produce the correct value.
3127 Result.negate();
3128
3129 return true;
3130}
3131
3132static bool handleCompareOpForVector(const APValue &LHSValue,
3133 BinaryOperatorKind Opcode,
3134 const APValue &RHSValue, APInt &Result) {
3135 // The result is always an int type, however operands match the first.
3136 if (LHSValue.getKind() == APValue::Int)
3137 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3138 RHSValue.getInt(), Result);
3139 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3140 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3141 RHSValue.getFloat(), Result);
3142}
3143
3144// Perform binary operations for vector types, in place on the LHS.
3145static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3146 BinaryOperatorKind Opcode,
3147 APValue &LHSValue,
3148 const APValue &RHSValue) {
3149 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3150 "Operation not supported on vector types");
3151
3152 const auto *VT = E->getType()->castAs<VectorType>();
3153 unsigned NumElements = VT->getNumElements();
3154 QualType EltTy = VT->getElementType();
3155
3156 // In the cases (typically C as I've observed) where we aren't evaluating
3157 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3158 // just give up.
3159 if (!LHSValue.isVector()) {
3160 assert(LHSValue.isLValue() &&
3161 "A vector result that isn't a vector OR uncalculated LValue");
3162 Info.FFDiag(E);
3163 return false;
3164 }
3165
3166 assert(LHSValue.getVectorLength() == NumElements &&
3167 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3168
3169 SmallVector<APValue, 4> ResultElements;
3170
3171 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3172 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3173 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3174
3175 if (EltTy->isIntegerType()) {
3176 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3177 EltTy->isUnsignedIntegerType()};
3178 bool Success = true;
3179
3180 if (BinaryOperator::isLogicalOp(Opcode))
3181 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3182 else if (BinaryOperator::isComparisonOp(Opcode))
3183 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3184 else
3185 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3186 RHSElt.getInt(), EltResult);
3187
3188 if (!Success) {
3189 Info.FFDiag(E);
3190 return false;
3191 }
3192 ResultElements.emplace_back(EltResult);
3193
3194 } else if (EltTy->isFloatingType()) {
3195 assert(LHSElt.getKind() == APValue::Float &&
3196 RHSElt.getKind() == APValue::Float &&
3197 "Mismatched LHS/RHS/Result Type");
3198 APFloat LHSFloat = LHSElt.getFloat();
3199
3200 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3201 RHSElt.getFloat())) {
3202 Info.FFDiag(E);
3203 return false;
3204 }
3205
3206 ResultElements.emplace_back(LHSFloat);
3207 }
3208 }
3209
3210 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3211 return true;
3212}
3213
3214/// Cast an lvalue referring to a base subobject to a derived class, by
3215/// truncating the lvalue's path to the given length.
3216static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3217 const RecordDecl *TruncatedType,
3218 unsigned TruncatedElements) {
3219 SubobjectDesignator &D = Result.Designator;
3220
3221 // Check we actually point to a derived class object.
3222 if (TruncatedElements == D.Entries.size())
3223 return true;
3224 assert(TruncatedElements >= D.MostDerivedPathLength &&
3225 "not casting to a derived class");
3226 if (!Result.checkSubobject(Info, E, CSK_Derived))
3227 return false;
3228
3229 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3230 const RecordDecl *RD = TruncatedType;
3231 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3232 if (RD->isInvalidDecl()) return false;
3233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3234 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3235 if (isVirtualBaseClass(D.Entries[I]))
3236 Result.Offset -= Layout.getVBaseClassOffset(Base);
3237 else
3238 Result.Offset -= Layout.getBaseClassOffset(Base);
3239 RD = Base;
3240 }
3241 D.Entries.resize(TruncatedElements);
3242 return true;
3243}
3244
3245static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3246 const CXXRecordDecl *Derived,
3247 const CXXRecordDecl *Base,
3248 const ASTRecordLayout *RL = nullptr) {
3249 if (!RL) {
3250 if (Derived->isInvalidDecl()) return false;
3251 RL = &Info.Ctx.getASTRecordLayout(Derived);
3252 }
3253
3254 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3255 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3256 return true;
3257}
3258
3259static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3260 const CXXRecordDecl *DerivedDecl,
3261 const CXXBaseSpecifier *Base) {
3262 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3263
3264 if (!Base->isVirtual())
3265 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3266
3267 SubobjectDesignator &D = Obj.Designator;
3268 if (D.Invalid)
3269 return false;
3270
3271 // Extract most-derived object and corresponding type.
3272 // FIXME: After implementing P2280R4 it became possible to get references
3273 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3274 // locations and if we see crashes in those locations in the future
3275 // it may make more sense to move this fix into Lvalue::set.
3276 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3277 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3278 return false;
3279
3280 // Find the virtual base class.
3281 if (DerivedDecl->isInvalidDecl()) return false;
3282 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3283 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3284 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3285 return true;
3286}
3287
3288static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3289 QualType Type, LValue &Result) {
3290 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3291 PathE = E->path_end();
3292 PathI != PathE; ++PathI) {
3293 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3294 *PathI))
3295 return false;
3296 Type = (*PathI)->getType();
3297 }
3298 return true;
3299}
3300
3301/// Cast an lvalue referring to a derived class to a known base subobject.
3302static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3303 const CXXRecordDecl *DerivedRD,
3304 const CXXRecordDecl *BaseRD) {
3305 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3306 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3307 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3308 llvm_unreachable("Class must be derived from the passed in base class!");
3309
3310 for (CXXBasePathElement &Elem : Paths.front())
3311 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3312 return false;
3313 return true;
3314}
3315
3316/// Update LVal to refer to the given field, which must be a member of the type
3317/// currently described by LVal.
3318static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3319 const FieldDecl *FD,
3320 const ASTRecordLayout *RL = nullptr) {
3321 if (!RL) {
3322 if (FD->getParent()->isInvalidDecl()) return false;
3323 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3324 }
3325
3326 unsigned I = FD->getFieldIndex();
3327 LVal.addDecl(Info, E, FD);
3328 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3329 return true;
3330}
3331
3332/// Update LVal to refer to the given indirect field.
3333static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3334 LValue &LVal,
3335 const IndirectFieldDecl *IFD) {
3336 for (const auto *C : IFD->chain())
3337 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3338 return false;
3339 return true;
3340}
3341
3346
3347/// Get the size of the given type in char units.
3348static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3350 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3351 // extension.
3352 if (Type->isVoidType() || Type->isFunctionType()) {
3353 Size = CharUnits::One();
3354 return true;
3355 }
3356
3357 if (Type->isDependentType()) {
3358 Info.FFDiag(Loc);
3359 return false;
3360 }
3361
3362 if (!Type->isConstantSizeType()) {
3363 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3364 // FIXME: Better diagnostic.
3365 Info.FFDiag(Loc);
3366 return false;
3367 }
3368
3369 if (SOT == SizeOfType::SizeOf)
3370 Size = Info.Ctx.getTypeSizeInChars(Type);
3371 else
3372 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3373 return true;
3374}
3375
3376/// Update a pointer value to model pointer arithmetic.
3377/// \param Info - Information about the ongoing evaluation.
3378/// \param E - The expression being evaluated, for diagnostic purposes.
3379/// \param LVal - The pointer value to be updated.
3380/// \param EltTy - The pointee type represented by LVal.
3381/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3382static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3383 LValue &LVal, QualType EltTy,
3384 APSInt Adjustment) {
3385 CharUnits SizeOfPointee;
3386 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3387 return false;
3388
3389 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3390 return true;
3391}
3392
3393static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3394 LValue &LVal, QualType EltTy,
3395 int64_t Adjustment) {
3396 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3397 APSInt::get(Adjustment));
3398}
3399
3400/// Update an lvalue to refer to a component of a complex number.
3401/// \param Info - Information about the ongoing evaluation.
3402/// \param LVal - The lvalue to be updated.
3403/// \param EltTy - The complex number's component type.
3404/// \param Imag - False for the real component, true for the imaginary.
3405static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3406 LValue &LVal, QualType EltTy,
3407 bool Imag) {
3408 if (Imag) {
3409 CharUnits SizeOfComponent;
3410 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3411 return false;
3412 LVal.Offset += SizeOfComponent;
3413 }
3414 LVal.addComplex(Info, E, EltTy, Imag);
3415 return true;
3416}
3417
3418static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3419 LValue &LVal, QualType EltTy,
3420 uint64_t Size, uint64_t Idx) {
3421 if (Idx) {
3422 CharUnits SizeOfElement;
3423 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3424 return false;
3425 LVal.Offset += SizeOfElement * Idx;
3426 }
3427 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3428 return true;
3429}
3430
3431/// Try to evaluate the initializer for a variable declaration.
3432///
3433/// \param Info Information about the ongoing evaluation.
3434/// \param E An expression to be used when printing diagnostics.
3435/// \param VD The variable whose initializer should be obtained.
3436/// \param Version The version of the variable within the frame.
3437/// \param Frame The frame in which the variable was created. Must be null
3438/// if this variable is not local to the evaluation.
3439/// \param Result Filled in with a pointer to the value of the variable.
3440static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3441 const VarDecl *VD, CallStackFrame *Frame,
3442 unsigned Version, APValue *&Result) {
3443 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3444 // and pointers.
3445 bool AllowConstexprUnknown =
3446 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3447
3448 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3449
3450 auto CheckUninitReference = [&](bool IsLocalVariable) {
3451 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3452 // C++23 [expr.const]p8
3453 // ... For such an object that is not usable in constant expressions, the
3454 // dynamic type of the object is constexpr-unknown. For such a reference
3455 // that is not usable in constant expressions, the reference is treated
3456 // as binding to an unspecified object of the referenced type whose
3457 // lifetime and that of all subobjects includes the entire constant
3458 // evaluation and whose dynamic type is constexpr-unknown.
3459 //
3460 // Variables that are part of the current evaluation are not
3461 // constexpr-unknown.
3462 if (!AllowConstexprUnknown || IsLocalVariable) {
3463 if (!Info.checkingPotentialConstantExpression())
3464 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3465 return false;
3466 }
3467 Result = nullptr;
3468 }
3469 return true;
3470 };
3471
3472 // If this is a local variable, dig out its value.
3473 if (Frame) {
3474 Result = Frame->getTemporary(VD, Version);
3475 if (Result)
3476 return CheckUninitReference(/*IsLocalVariable=*/true);
3477
3478 if (!isa<ParmVarDecl>(VD)) {
3479 // Assume variables referenced within a lambda's call operator that were
3480 // not declared within the call operator are captures and during checking
3481 // of a potential constant expression, assume they are unknown constant
3482 // expressions.
3483 assert(isLambdaCallOperator(Frame->Callee) &&
3484 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3485 "missing value for local variable");
3486 if (Info.checkingPotentialConstantExpression())
3487 return false;
3488 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3489 // still reachable at all?
3490 Info.FFDiag(E->getBeginLoc(),
3491 diag::note_unimplemented_constexpr_lambda_feature_ast)
3492 << "captures not currently allowed";
3493 return false;
3494 }
3495 }
3496
3497 // If we're currently evaluating the initializer of this declaration, use that
3498 // in-flight value.
3499 if (Info.EvaluatingDecl == Base) {
3500 Result = Info.EvaluatingDeclValue;
3501 return CheckUninitReference(/*IsLocalVariable=*/false);
3502 }
3503
3504 // P2280R4 struck the restriction that variable of reference type lifetime
3505 // should begin within the evaluation of E
3506 // Used to be C++20 [expr.const]p5.12.2:
3507 // ... its lifetime began within the evaluation of E;
3508 if (isa<ParmVarDecl>(VD)) {
3509 if (AllowConstexprUnknown) {
3510 Result = nullptr;
3511 return true;
3512 }
3513
3514 // Assume parameters of a potential constant expression are usable in
3515 // constant expressions.
3516 if (!Info.checkingPotentialConstantExpression() ||
3517 !Info.CurrentCall->Callee ||
3518 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3519 if (Info.getLangOpts().CPlusPlus11) {
3520 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3521 << VD;
3522 NoteLValueLocation(Info, Base);
3523 } else {
3524 Info.FFDiag(E);
3525 }
3526 }
3527 return false;
3528 }
3529
3530 if (E->isValueDependent())
3531 return false;
3532
3533 // Dig out the initializer, and use the declaration which it's attached to.
3534 // FIXME: We should eventually check whether the variable has a reachable
3535 // initializing declaration.
3536 const Expr *Init = VD->getAnyInitializer(VD);
3537 // P2280R4 struck the restriction that variable of reference type should have
3538 // a preceding initialization.
3539 // Used to be C++20 [expr.const]p5.12:
3540 // ... reference has a preceding initialization and either ...
3541 if (!Init && !AllowConstexprUnknown) {
3542 // Don't diagnose during potential constant expression checking; an
3543 // initializer might be added later.
3544 if (!Info.checkingPotentialConstantExpression()) {
3545 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3546 << VD;
3547 NoteLValueLocation(Info, Base);
3548 }
3549 return false;
3550 }
3551
3552 // P2280R4 struck the initialization requirement for variables of reference
3553 // type so we can no longer assume we have an Init.
3554 // Used to be C++20 [expr.const]p5.12:
3555 // ... reference has a preceding initialization and either ...
3556 if (Init && Init->isValueDependent()) {
3557 // The DeclRefExpr is not value-dependent, but the variable it refers to
3558 // has a value-dependent initializer. This should only happen in
3559 // constant-folding cases, where the variable is not actually of a suitable
3560 // type for use in a constant expression (otherwise the DeclRefExpr would
3561 // have been value-dependent too), so diagnose that.
3562 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3563 if (!Info.checkingPotentialConstantExpression()) {
3564 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3565 ? diag::note_constexpr_ltor_non_constexpr
3566 : diag::note_constexpr_ltor_non_integral, 1)
3567 << VD << VD->getType();
3568 NoteLValueLocation(Info, Base);
3569 }
3570 return false;
3571 }
3572
3573 // Check that we can fold the initializer. In C++, we will have already done
3574 // this in the cases where it matters for conformance.
3575 // P2280R4 struck the initialization requirement for variables of reference
3576 // type so we can no longer assume we have an Init.
3577 // Used to be C++20 [expr.const]p5.12:
3578 // ... reference has a preceding initialization and either ...
3579 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3580 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3581 NoteLValueLocation(Info, Base);
3582 return false;
3583 }
3584
3585 // Check that the variable is actually usable in constant expressions. For a
3586 // const integral variable or a reference, we might have a non-constant
3587 // initializer that we can nonetheless evaluate the initializer for. Such
3588 // variables are not usable in constant expressions. In C++98, the
3589 // initializer also syntactically needs to be an ICE.
3590 //
3591 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3592 // expressions here; doing so would regress diagnostics for things like
3593 // reading from a volatile constexpr variable.
3594 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3595 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3596 !AllowConstexprUnknown) ||
3597 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3598 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3599 if (Init) {
3600 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3601 NoteLValueLocation(Info, Base);
3602 } else {
3603 Info.CCEDiag(E);
3604 }
3605 }
3606
3607 // Never use the initializer of a weak variable, not even for constant
3608 // folding. We can't be sure that this is the definition that will be used.
3609 if (VD->isWeak()) {
3610 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3611 NoteLValueLocation(Info, Base);
3612 return false;
3613 }
3614
3615 Result = VD->getEvaluatedValue();
3616
3617 if (!Result && !AllowConstexprUnknown)
3618 return false;
3619
3620 return CheckUninitReference(/*IsLocalVariable=*/false);
3621}
3622
3623/// Get the base index of the given base class within an APValue representing
3624/// the given derived class.
3625static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3626 const CXXRecordDecl *Base) {
3627 Base = Base->getCanonicalDecl();
3628 unsigned Index = 0;
3630 E = Derived->bases_end(); I != E; ++I, ++Index) {
3631 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3632 return Index;
3633 }
3634
3635 llvm_unreachable("base class missing from derived class's bases list");
3636}
3637
3638/// Extract the value of a character from a string literal.
3639static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3640 uint64_t Index) {
3641 assert(!isa<SourceLocExpr>(Lit) &&
3642 "SourceLocExpr should have already been converted to a StringLiteral");
3643
3644 // FIXME: Support MakeStringConstant
3645 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3646 std::string Str;
3647 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3648 assert(Index <= Str.size() && "Index too large");
3649 return APSInt::getUnsigned(Str.c_str()[Index]);
3650 }
3651
3652 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3653 Lit = PE->getFunctionName();
3654 const StringLiteral *S = cast<StringLiteral>(Lit);
3655 const ConstantArrayType *CAT =
3656 Info.Ctx.getAsConstantArrayType(S->getType());
3657 assert(CAT && "string literal isn't an array");
3658 QualType CharType = CAT->getElementType();
3659 assert(CharType->isIntegerType() && "unexpected character type");
3660 APSInt Value(Info.Ctx.getTypeSize(CharType),
3661 CharType->isUnsignedIntegerType());
3662 if (Index < S->getLength())
3663 Value = S->getCodeUnit(Index);
3664 return Value;
3665}
3666
3667// Expand a string literal into an array of characters.
3668//
3669// FIXME: This is inefficient; we should probably introduce something similar
3670// to the LLVM ConstantDataArray to make this cheaper.
3671static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3672 APValue &Result,
3673 QualType AllocType = QualType()) {
3674 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3675 AllocType.isNull() ? S->getType() : AllocType);
3676 assert(CAT && "string literal isn't an array");
3677 QualType CharType = CAT->getElementType();
3678 assert(CharType->isIntegerType() && "unexpected character type");
3679
3680 unsigned Elts = CAT->getZExtSize();
3681 Result = APValue(APValue::UninitArray(),
3682 std::min(S->getLength(), Elts), Elts);
3683 APSInt Value(Info.Ctx.getTypeSize(CharType),
3684 CharType->isUnsignedIntegerType());
3685 if (Result.hasArrayFiller())
3686 Result.getArrayFiller() = APValue(Value);
3687 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3688 Value = S->getCodeUnit(I);
3689 Result.getArrayInitializedElt(I) = APValue(Value);
3690 }
3691}
3692
3693// Expand an array so that it has more than Index filled elements.
3694static void expandArray(APValue &Array, unsigned Index) {
3695 unsigned Size = Array.getArraySize();
3696 assert(Index < Size);
3697
3698 // Always at least double the number of elements for which we store a value.
3699 unsigned OldElts = Array.getArrayInitializedElts();
3700 unsigned NewElts = std::max(Index+1, OldElts * 2);
3701 NewElts = std::min(Size, std::max(NewElts, 8u));
3702
3703 // Copy the data across.
3704 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3705 for (unsigned I = 0; I != OldElts; ++I)
3706 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3707 for (unsigned I = OldElts; I != NewElts; ++I)
3708 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3709 if (NewValue.hasArrayFiller())
3710 NewValue.getArrayFiller() = Array.getArrayFiller();
3711 Array.swap(NewValue);
3712}
3713
3714/// Determine whether a type would actually be read by an lvalue-to-rvalue
3715/// conversion. If it's of class type, we may assume that the copy operation
3716/// is trivial. Note that this is never true for a union type with fields
3717/// (because the copy always "reads" the active member) and always true for
3718/// a non-class type.
3719static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3721 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3722 return !RD || isReadByLvalueToRvalueConversion(RD);
3723}
3725 // FIXME: A trivial copy of a union copies the object representation, even if
3726 // the union is empty.
3727 if (RD->isUnion())
3728 return !RD->field_empty();
3729 if (RD->isEmpty())
3730 return false;
3731
3732 for (auto *Field : RD->fields())
3733 if (!Field->isUnnamedBitField() &&
3734 isReadByLvalueToRvalueConversion(Field->getType()))
3735 return true;
3736
3737 for (auto &BaseSpec : RD->bases())
3738 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3739 return true;
3740
3741 return false;
3742}
3743
3744/// Diagnose an attempt to read from any unreadable field within the specified
3745/// type, which might be a class type.
3746static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3747 QualType T) {
3748 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3749 if (!RD)
3750 return false;
3751
3752 if (!RD->hasMutableFields())
3753 return false;
3754
3755 for (auto *Field : RD->fields()) {
3756 // If we're actually going to read this field in some way, then it can't
3757 // be mutable. If we're in a union, then assigning to a mutable field
3758 // (even an empty one) can change the active member, so that's not OK.
3759 // FIXME: Add core issue number for the union case.
3760 if (Field->isMutable() &&
3761 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3762 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3763 Info.Note(Field->getLocation(), diag::note_declared_at);
3764 return true;
3765 }
3766
3767 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3768 return true;
3769 }
3770
3771 for (auto &BaseSpec : RD->bases())
3772 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3773 return true;
3774
3775 // All mutable fields were empty, and thus not actually read.
3776 return false;
3777}
3778
3779static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3781 bool MutableSubobject = false) {
3782 // A temporary or transient heap allocation we created.
3783 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3784 return true;
3785
3786 switch (Info.IsEvaluatingDecl) {
3787 case EvalInfo::EvaluatingDeclKind::None:
3788 return false;
3789
3790 case EvalInfo::EvaluatingDeclKind::Ctor:
3791 // The variable whose initializer we're evaluating.
3792 if (Info.EvaluatingDecl == Base)
3793 return true;
3794
3795 // A temporary lifetime-extended by the variable whose initializer we're
3796 // evaluating.
3797 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3798 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3799 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3800 return false;
3801
3802 case EvalInfo::EvaluatingDeclKind::Dtor:
3803 // C++2a [expr.const]p6:
3804 // [during constant destruction] the lifetime of a and its non-mutable
3805 // subobjects (but not its mutable subobjects) [are] considered to start
3806 // within e.
3807 if (MutableSubobject || Base != Info.EvaluatingDecl)
3808 return false;
3809 // FIXME: We can meaningfully extend this to cover non-const objects, but
3810 // we will need special handling: we should be able to access only
3811 // subobjects of such objects that are themselves declared const.
3813 return T.isConstQualified() || T->isReferenceType();
3814 }
3815
3816 llvm_unreachable("unknown evaluating decl kind");
3817}
3818
3819static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3820 SourceLocation CallLoc = {}) {
3821 return Info.CheckArraySize(
3822 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3823 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3824 /*Diag=*/true);
3825}
3826
3827namespace {
3828/// A handle to a complete object (an object that is not a subobject of
3829/// another object).
3830struct CompleteObject {
3831 /// The identity of the object.
3832 APValue::LValueBase Base;
3833 /// The value of the complete object.
3834 APValue *Value;
3835 /// The type of the complete object.
3836 QualType Type;
3837
3838 CompleteObject() : Value(nullptr) {}
3839 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3840 : Base(Base), Value(Value), Type(Type) {}
3841
3842 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3843 // If this isn't a "real" access (eg, if it's just accessing the type
3844 // info), allow it. We assume the type doesn't change dynamically for
3845 // subobjects of constexpr objects (even though we'd hit UB here if it
3846 // did). FIXME: Is this right?
3847 if (!isAnyAccess(AK))
3848 return true;
3849
3850 // In C++14 onwards, it is permitted to read a mutable member whose
3851 // lifetime began within the evaluation.
3852 // FIXME: Should we also allow this in C++11?
3853 if (!Info.getLangOpts().CPlusPlus14 &&
3854 AK != AccessKinds::AK_IsWithinLifetime)
3855 return false;
3856 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3857 }
3858
3859 explicit operator bool() const { return !Type.isNull(); }
3860};
3861} // end anonymous namespace
3862
3863static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3864 bool IsMutable = false) {
3865 // C++ [basic.type.qualifier]p1:
3866 // - A const object is an object of type const T or a non-mutable subobject
3867 // of a const object.
3868 if (ObjType.isConstQualified() && !IsMutable)
3869 SubobjType.addConst();
3870 // - A volatile object is an object of type const T or a subobject of a
3871 // volatile object.
3872 if (ObjType.isVolatileQualified())
3873 SubobjType.addVolatile();
3874 return SubobjType;
3875}
3876
3877/// Find the designated sub-object of an rvalue.
3878template <typename SubobjectHandler>
3879static typename SubobjectHandler::result_type
3880findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3881 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3882 if (Sub.Invalid)
3883 // A diagnostic will have already been produced.
3884 return handler.failed();
3885 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3886 if (Info.getLangOpts().CPlusPlus11)
3887 Info.FFDiag(E, Sub.isOnePastTheEnd()
3888 ? diag::note_constexpr_access_past_end
3889 : diag::note_constexpr_access_unsized_array)
3890 << handler.AccessKind;
3891 else
3892 Info.FFDiag(E);
3893 return handler.failed();
3894 }
3895
3896 APValue *O = Obj.Value;
3897 QualType ObjType = Obj.Type;
3898 const FieldDecl *LastField = nullptr;
3899 const FieldDecl *VolatileField = nullptr;
3900
3901 // Walk the designator's path to find the subobject.
3902 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3903 // Reading an indeterminate value is undefined, but assigning over one is OK.
3904 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3905 (O->isIndeterminate() &&
3906 !isValidIndeterminateAccess(handler.AccessKind))) {
3907 // Object has ended lifetime.
3908 // If I is non-zero, some subobject (member or array element) of a
3909 // complete object has ended its lifetime, so this is valid for
3910 // IsWithinLifetime, resulting in false.
3911 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3912 return false;
3913 if (!Info.checkingPotentialConstantExpression())
3914 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3915 << handler.AccessKind << O->isIndeterminate()
3916 << E->getSourceRange();
3917 return handler.failed();
3918 }
3919
3920 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3921 // const and volatile semantics are not applied on an object under
3922 // {con,de}struction.
3923 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3924 ObjType->isRecordType() &&
3925 Info.isEvaluatingCtorDtor(
3926 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3927 ConstructionPhase::None) {
3928 ObjType = Info.Ctx.getCanonicalType(ObjType);
3929 ObjType.removeLocalConst();
3930 ObjType.removeLocalVolatile();
3931 }
3932
3933 // If this is our last pass, check that the final object type is OK.
3934 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3935 // Accesses to volatile objects are prohibited.
3936 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3937 if (Info.getLangOpts().CPlusPlus) {
3938 int DiagKind;
3939 SourceLocation Loc;
3940 const NamedDecl *Decl = nullptr;
3941 if (VolatileField) {
3942 DiagKind = 2;
3943 Loc = VolatileField->getLocation();
3944 Decl = VolatileField;
3945 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3946 DiagKind = 1;
3947 Loc = VD->getLocation();
3948 Decl = VD;
3949 } else {
3950 DiagKind = 0;
3951 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3952 Loc = E->getExprLoc();
3953 }
3954 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3955 << handler.AccessKind << DiagKind << Decl;
3956 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3957 } else {
3958 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3959 }
3960 return handler.failed();
3961 }
3962
3963 // If we are reading an object of class type, there may still be more
3964 // things we need to check: if there are any mutable subobjects, we
3965 // cannot perform this read. (This only happens when performing a trivial
3966 // copy or assignment.)
3967 if (ObjType->isRecordType() &&
3968 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3969 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3970 return handler.failed();
3971 }
3972
3973 if (I == N) {
3974 if (!handler.found(*O, ObjType))
3975 return false;
3976
3977 // If we modified a bit-field, truncate it to the right width.
3978 if (isModification(handler.AccessKind) &&
3979 LastField && LastField->isBitField() &&
3980 !truncateBitfieldValue(Info, E, *O, LastField))
3981 return false;
3982
3983 return true;
3984 }
3985
3986 LastField = nullptr;
3987 if (ObjType->isArrayType()) {
3988 // Next subobject is an array element.
3989 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
3991 "vla in literal type?");
3992 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3993 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3994 CAT && CAT->getSize().ule(Index)) {
3995 // Note, it should not be possible to form a pointer with a valid
3996 // designator which points more than one past the end of the array.
3997 if (Info.getLangOpts().CPlusPlus11)
3998 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3999 << handler.AccessKind;
4000 else
4001 Info.FFDiag(E);
4002 return handler.failed();
4003 }
4004
4005 ObjType = AT->getElementType();
4006
4007 if (O->getArrayInitializedElts() > Index)
4008 O = &O->getArrayInitializedElt(Index);
4009 else if (!isRead(handler.AccessKind)) {
4010 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4011 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4012 return handler.failed();
4013
4014 expandArray(*O, Index);
4015 O = &O->getArrayInitializedElt(Index);
4016 } else
4017 O = &O->getArrayFiller();
4018 } else if (ObjType->isAnyComplexType()) {
4019 // Next subobject is a complex number.
4020 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4021 if (Index > 1) {
4022 if (Info.getLangOpts().CPlusPlus11)
4023 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4024 << handler.AccessKind;
4025 else
4026 Info.FFDiag(E);
4027 return handler.failed();
4028 }
4029
4030 ObjType = getSubobjectType(
4031 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4032
4033 assert(I == N - 1 && "extracting subobject of scalar?");
4034 if (O->isComplexInt()) {
4035 return handler.found(Index ? O->getComplexIntImag()
4036 : O->getComplexIntReal(), ObjType);
4037 } else {
4038 assert(O->isComplexFloat());
4039 return handler.found(Index ? O->getComplexFloatImag()
4040 : O->getComplexFloatReal(), ObjType);
4041 }
4042 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4043 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4044 unsigned NumElements = VT->getNumElements();
4045 if (Index == NumElements) {
4046 if (Info.getLangOpts().CPlusPlus11)
4047 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4048 << handler.AccessKind;
4049 else
4050 Info.FFDiag(E);
4051 return handler.failed();
4052 }
4053
4054 if (Index > NumElements) {
4055 Info.CCEDiag(E, diag::note_constexpr_array_index)
4056 << Index << /*array*/ 0 << NumElements;
4057 return handler.failed();
4058 }
4059
4060 ObjType = VT->getElementType();
4061 assert(I == N - 1 && "extracting subobject of scalar?");
4062 return handler.found(O->getVectorElt(Index), ObjType);
4063 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4064 if (Field->isMutable() &&
4065 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4066 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4067 << handler.AccessKind << Field;
4068 Info.Note(Field->getLocation(), diag::note_declared_at);
4069 return handler.failed();
4070 }
4071
4072 // Next subobject is a class, struct or union field.
4073 RecordDecl *RD =
4074 ObjType->castAsCanonical<RecordType>()->getOriginalDecl();
4075 if (RD->isUnion()) {
4076 const FieldDecl *UnionField = O->getUnionField();
4077 if (!UnionField ||
4078 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4079 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4080 // Placement new onto an inactive union member makes it active.
4081 O->setUnion(Field, APValue());
4082 } else {
4083 // Pointer to/into inactive union member: Not within lifetime
4084 if (handler.AccessKind == AK_IsWithinLifetime)
4085 return false;
4086 // FIXME: If O->getUnionValue() is absent, report that there's no
4087 // active union member rather than reporting the prior active union
4088 // member. We'll need to fix nullptr_t to not use APValue() as its
4089 // representation first.
4090 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4091 << handler.AccessKind << Field << !UnionField << UnionField;
4092 return handler.failed();
4093 }
4094 }
4095 O = &O->getUnionValue();
4096 } else
4097 O = &O->getStructField(Field->getFieldIndex());
4098
4099 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4100 LastField = Field;
4101 if (Field->getType().isVolatileQualified())
4102 VolatileField = Field;
4103 } else {
4104 // Next subobject is a base class.
4105 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4106 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4107 O = &O->getStructBase(getBaseIndex(Derived, Base));
4108
4109 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4110 }
4111 }
4112}
4113
4114namespace {
4115struct ExtractSubobjectHandler {
4116 EvalInfo &Info;
4117 const Expr *E;
4118 APValue &Result;
4119 const AccessKinds AccessKind;
4120
4121 typedef bool result_type;
4122 bool failed() { return false; }
4123 bool found(APValue &Subobj, QualType SubobjType) {
4124 Result = Subobj;
4125 if (AccessKind == AK_ReadObjectRepresentation)
4126 return true;
4127 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4128 }
4129 bool found(APSInt &Value, QualType SubobjType) {
4130 Result = APValue(Value);
4131 return true;
4132 }
4133 bool found(APFloat &Value, QualType SubobjType) {
4134 Result = APValue(Value);
4135 return true;
4136 }
4137};
4138} // end anonymous namespace
4139
4140/// Extract the designated sub-object of an rvalue.
4141static bool extractSubobject(EvalInfo &Info, const Expr *E,
4142 const CompleteObject &Obj,
4143 const SubobjectDesignator &Sub, APValue &Result,
4144 AccessKinds AK = AK_Read) {
4145 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4146 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4147 return findSubobject(Info, E, Obj, Sub, Handler);
4148}
4149
4150namespace {
4151struct ModifySubobjectHandler {
4152 EvalInfo &Info;
4153 APValue &NewVal;
4154 const Expr *E;
4155
4156 typedef bool result_type;
4157 static const AccessKinds AccessKind = AK_Assign;
4158
4159 bool checkConst(QualType QT) {
4160 // Assigning to a const object has undefined behavior.
4161 if (QT.isConstQualified()) {
4162 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4163 return false;
4164 }
4165 return true;
4166 }
4167
4168 bool failed() { return false; }
4169 bool found(APValue &Subobj, QualType SubobjType) {
4170 if (!checkConst(SubobjType))
4171 return false;
4172 // We've been given ownership of NewVal, so just swap it in.
4173 Subobj.swap(NewVal);
4174 return true;
4175 }
4176 bool found(APSInt &Value, QualType SubobjType) {
4177 if (!checkConst(SubobjType))
4178 return false;
4179 if (!NewVal.isInt()) {
4180 // Maybe trying to write a cast pointer value into a complex?
4181 Info.FFDiag(E);
4182 return false;
4183 }
4184 Value = NewVal.getInt();
4185 return true;
4186 }
4187 bool found(APFloat &Value, QualType SubobjType) {
4188 if (!checkConst(SubobjType))
4189 return false;
4190 Value = NewVal.getFloat();
4191 return true;
4192 }
4193};
4194} // end anonymous namespace
4195
4196const AccessKinds ModifySubobjectHandler::AccessKind;
4197
4198/// Update the designated sub-object of an rvalue to the given value.
4199static bool modifySubobject(EvalInfo &Info, const Expr *E,
4200 const CompleteObject &Obj,
4201 const SubobjectDesignator &Sub,
4202 APValue &NewVal) {
4203 ModifySubobjectHandler Handler = { Info, NewVal, E };
4204 return findSubobject(Info, E, Obj, Sub, Handler);
4205}
4206
4207/// Find the position where two subobject designators diverge, or equivalently
4208/// the length of the common initial subsequence.
4209static unsigned FindDesignatorMismatch(QualType ObjType,
4210 const SubobjectDesignator &A,
4211 const SubobjectDesignator &B,
4212 bool &WasArrayIndex) {
4213 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4214 for (/**/; I != N; ++I) {
4215 if (!ObjType.isNull() &&
4216 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4217 // Next subobject is an array element.
4218 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4219 WasArrayIndex = true;
4220 return I;
4221 }
4222 if (ObjType->isAnyComplexType())
4223 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4224 else
4225 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4226 } else {
4227 if (A.Entries[I].getAsBaseOrMember() !=
4228 B.Entries[I].getAsBaseOrMember()) {
4229 WasArrayIndex = false;
4230 return I;
4231 }
4232 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4233 // Next subobject is a field.
4234 ObjType = FD->getType();
4235 else
4236 // Next subobject is a base class.
4237 ObjType = QualType();
4238 }
4239 }
4240 WasArrayIndex = false;
4241 return I;
4242}
4243
4244/// Determine whether the given subobject designators refer to elements of the
4245/// same array object.
4247 const SubobjectDesignator &A,
4248 const SubobjectDesignator &B) {
4249 if (A.Entries.size() != B.Entries.size())
4250 return false;
4251
4252 bool IsArray = A.MostDerivedIsArrayElement;
4253 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4254 // A is a subobject of the array element.
4255 return false;
4256
4257 // If A (and B) designates an array element, the last entry will be the array
4258 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4259 // of length 1' case, and the entire path must match.
4260 bool WasArrayIndex;
4261 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4262 return CommonLength >= A.Entries.size() - IsArray;
4263}
4264
4265/// Find the complete object to which an LValue refers.
4266static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4267 AccessKinds AK, const LValue &LVal,
4268 QualType LValType) {
4269 if (LVal.InvalidBase) {
4270 Info.FFDiag(E);
4271 return CompleteObject();
4272 }
4273
4274 if (!LVal.Base) {
4276 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4277 else
4278 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4279 return CompleteObject();
4280 }
4281
4282 CallStackFrame *Frame = nullptr;
4283 unsigned Depth = 0;
4284 if (LVal.getLValueCallIndex()) {
4285 std::tie(Frame, Depth) =
4286 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4287 if (!Frame) {
4288 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4289 << AK << LVal.Base.is<const ValueDecl*>();
4290 NoteLValueLocation(Info, LVal.Base);
4291 return CompleteObject();
4292 }
4293 }
4294
4295 bool IsAccess = isAnyAccess(AK);
4296
4297 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4298 // is not a constant expression (even if the object is non-volatile). We also
4299 // apply this rule to C++98, in order to conform to the expected 'volatile'
4300 // semantics.
4301 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4302 if (Info.getLangOpts().CPlusPlus)
4303 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4304 << AK << LValType;
4305 else
4306 Info.FFDiag(E);
4307 return CompleteObject();
4308 }
4309
4310 // Compute value storage location and type of base object.
4311 APValue *BaseVal = nullptr;
4312 QualType BaseType = getType(LVal.Base);
4313
4314 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4315 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4316 // This is the object whose initializer we're evaluating, so its lifetime
4317 // started in the current evaluation.
4318 BaseVal = Info.EvaluatingDeclValue;
4319 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4320 // Allow reading from a GUID declaration.
4321 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4322 if (isModification(AK)) {
4323 // All the remaining cases do not permit modification of the object.
4324 Info.FFDiag(E, diag::note_constexpr_modify_global);
4325 return CompleteObject();
4326 }
4327 APValue &V = GD->getAsAPValue();
4328 if (V.isAbsent()) {
4329 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4330 << GD->getType();
4331 return CompleteObject();
4332 }
4333 return CompleteObject(LVal.Base, &V, GD->getType());
4334 }
4335
4336 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4337 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4338 if (isModification(AK)) {
4339 Info.FFDiag(E, diag::note_constexpr_modify_global);
4340 return CompleteObject();
4341 }
4342 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4343 GCD->getType());
4344 }
4345
4346 // Allow reading from template parameter objects.
4347 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4348 if (isModification(AK)) {
4349 Info.FFDiag(E, diag::note_constexpr_modify_global);
4350 return CompleteObject();
4351 }
4352 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4353 TPO->getType());
4354 }
4355
4356 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4357 // In C++11, constexpr, non-volatile variables initialized with constant
4358 // expressions are constant expressions too. Inside constexpr functions,
4359 // parameters are constant expressions even if they're non-const.
4360 // In C++1y, objects local to a constant expression (those with a Frame) are
4361 // both readable and writable inside constant expressions.
4362 // In C, such things can also be folded, although they are not ICEs.
4363 const VarDecl *VD = dyn_cast<VarDecl>(D);
4364 if (VD) {
4365 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4366 VD = VDef;
4367 }
4368 if (!VD || VD->isInvalidDecl()) {
4369 Info.FFDiag(E);
4370 return CompleteObject();
4371 }
4372
4373 bool IsConstant = BaseType.isConstant(Info.Ctx);
4374 bool ConstexprVar = false;
4375 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4376 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4377 ConstexprVar = VD->isConstexpr();
4378
4379 // Unless we're looking at a local variable or argument in a constexpr call,
4380 // the variable we're reading must be const (unless we are binding to a
4381 // reference).
4382 if (AK != clang::AK_Dereference && !Frame) {
4383 if (IsAccess && isa<ParmVarDecl>(VD)) {
4384 // Access of a parameter that's not associated with a frame isn't going
4385 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4386 // suitable diagnostic.
4387 } else if (Info.getLangOpts().CPlusPlus14 &&
4388 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4389 // OK, we can read and modify an object if we're in the process of
4390 // evaluating its initializer, because its lifetime began in this
4391 // evaluation.
4392 } else if (isModification(AK)) {
4393 // All the remaining cases do not permit modification of the object.
4394 Info.FFDiag(E, diag::note_constexpr_modify_global);
4395 return CompleteObject();
4396 } else if (VD->isConstexpr()) {
4397 // OK, we can read this variable.
4398 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4399 Info.FFDiag(E);
4400 return CompleteObject();
4401 } else if (BaseType->isIntegralOrEnumerationType()) {
4402 if (!IsConstant) {
4403 if (!IsAccess)
4404 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4405 if (Info.getLangOpts().CPlusPlus) {
4406 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4407 Info.Note(VD->getLocation(), diag::note_declared_at);
4408 } else {
4409 Info.FFDiag(E);
4410 }
4411 return CompleteObject();
4412 }
4413 } else if (!IsAccess) {
4414 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4415 } else if ((IsConstant || BaseType->isReferenceType()) &&
4416 Info.checkingPotentialConstantExpression() &&
4417 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4418 // This variable might end up being constexpr. Don't diagnose it yet.
4419 } else if (IsConstant) {
4420 // Keep evaluating to see what we can do. In particular, we support
4421 // folding of const floating-point types, in order to make static const
4422 // data members of such types (supported as an extension) more useful.
4423 if (Info.getLangOpts().CPlusPlus) {
4424 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4425 ? diag::note_constexpr_ltor_non_constexpr
4426 : diag::note_constexpr_ltor_non_integral, 1)
4427 << VD << BaseType;
4428 Info.Note(VD->getLocation(), diag::note_declared_at);
4429 } else {
4430 Info.CCEDiag(E);
4431 }
4432 } else {
4433 // Never allow reading a non-const value.
4434 if (Info.getLangOpts().CPlusPlus) {
4435 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4436 ? diag::note_constexpr_ltor_non_constexpr
4437 : diag::note_constexpr_ltor_non_integral, 1)
4438 << VD << BaseType;
4439 Info.Note(VD->getLocation(), diag::note_declared_at);
4440 } else {
4441 Info.FFDiag(E);
4442 }
4443 return CompleteObject();
4444 }
4445 }
4446
4447 // When binding to a reference, the variable does not need to be constexpr
4448 // or have constant initalization.
4449 if (AK != clang::AK_Dereference &&
4450 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4451 BaseVal))
4452 return CompleteObject();
4453 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4454 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4455 // we can't access a constexpr-unknown object.
4456 if (AK != clang::AK_Dereference && !BaseVal) {
4457 if (!Info.checkingPotentialConstantExpression()) {
4458 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4459 << AK << VD;
4460 Info.Note(VD->getLocation(), diag::note_declared_at);
4461 }
4462 return CompleteObject();
4463 }
4464 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4465 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4466 if (!Alloc) {
4467 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4468 return CompleteObject();
4469 }
4470 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4471 LVal.Base.getDynamicAllocType());
4472 }
4473 // When binding to a reference, the variable does not need to be
4474 // within its lifetime.
4475 else if (AK != clang::AK_Dereference) {
4476 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4477
4478 if (!Frame) {
4479 if (const MaterializeTemporaryExpr *MTE =
4480 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4481 assert(MTE->getStorageDuration() == SD_Static &&
4482 "should have a frame for a non-global materialized temporary");
4483
4484 // C++20 [expr.const]p4: [DR2126]
4485 // An object or reference is usable in constant expressions if it is
4486 // - a temporary object of non-volatile const-qualified literal type
4487 // whose lifetime is extended to that of a variable that is usable
4488 // in constant expressions
4489 //
4490 // C++20 [expr.const]p5:
4491 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4492 // - a non-volatile glvalue that refers to an object that is usable
4493 // in constant expressions, or
4494 // - a non-volatile glvalue of literal type that refers to a
4495 // non-volatile object whose lifetime began within the evaluation
4496 // of E;
4497 //
4498 // C++11 misses the 'began within the evaluation of e' check and
4499 // instead allows all temporaries, including things like:
4500 // int &&r = 1;
4501 // int x = ++r;
4502 // constexpr int k = r;
4503 // Therefore we use the C++14-onwards rules in C++11 too.
4504 //
4505 // Note that temporaries whose lifetimes began while evaluating a
4506 // variable's constructor are not usable while evaluating the
4507 // corresponding destructor, not even if they're of const-qualified
4508 // types.
4509 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4510 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4511 if (!IsAccess)
4512 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4513 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4514 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4515 return CompleteObject();
4516 }
4517
4518 BaseVal = MTE->getOrCreateValue(false);
4519 assert(BaseVal && "got reference to unevaluated temporary");
4520 } else if (const CompoundLiteralExpr *CLE =
4521 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4522 // According to GCC info page:
4523 //
4524 // 6.28 Compound Literals
4525 //
4526 // As an optimization, G++ sometimes gives array compound literals
4527 // longer lifetimes: when the array either appears outside a function or
4528 // has a const-qualified type. If foo and its initializer had elements
4529 // of type char *const rather than char *, or if foo were a global
4530 // variable, the array would have static storage duration. But it is
4531 // probably safest just to avoid the use of array compound literals in
4532 // C++ code.
4533 //
4534 // Obey that rule by checking constness for converted array types.
4535 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4536 !LValType->isArrayType() &&
4537 !CLETy.isConstant(Info.Ctx)) {
4538 Info.FFDiag(E);
4539 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4540 return CompleteObject();
4541 }
4542
4543 BaseVal = &CLE->getStaticValue();
4544 } else {
4545 if (!IsAccess)
4546 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4547 APValue Val;
4548 LVal.moveInto(Val);
4549 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4550 << AK
4551 << Val.getAsString(Info.Ctx,
4552 Info.Ctx.getLValueReferenceType(LValType));
4553 NoteLValueLocation(Info, LVal.Base);
4554 return CompleteObject();
4555 }
4556 } else if (AK != clang::AK_Dereference) {
4557 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4558 assert(BaseVal && "missing value for temporary");
4559 }
4560 }
4561
4562 // In C++14, we can't safely access any mutable state when we might be
4563 // evaluating after an unmodeled side effect. Parameters are modeled as state
4564 // in the caller, but aren't visible once the call returns, so they can be
4565 // modified in a speculatively-evaluated call.
4566 //
4567 // FIXME: Not all local state is mutable. Allow local constant subobjects
4568 // to be read here (but take care with 'mutable' fields).
4569 unsigned VisibleDepth = Depth;
4570 if (llvm::isa_and_nonnull<ParmVarDecl>(
4571 LVal.Base.dyn_cast<const ValueDecl *>()))
4572 ++VisibleDepth;
4573 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4574 Info.EvalStatus.HasSideEffects) ||
4575 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4576 return CompleteObject();
4577
4578 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4579}
4580
4581/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4582/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4583/// glvalue referred to by an entity of reference type.
4584///
4585/// \param Info - Information about the ongoing evaluation.
4586/// \param Conv - The expression for which we are performing the conversion.
4587/// Used for diagnostics.
4588/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4589/// case of a non-class type).
4590/// \param LVal - The glvalue on which we are attempting to perform this action.
4591/// \param RVal - The produced value will be placed here.
4592/// \param WantObjectRepresentation - If true, we're looking for the object
4593/// representation rather than the value, and in particular,
4594/// there is no requirement that the result be fully initialized.
4595static bool
4597 const LValue &LVal, APValue &RVal,
4598 bool WantObjectRepresentation = false) {
4599 if (LVal.Designator.Invalid)
4600 return false;
4601
4602 // Check for special cases where there is no existing APValue to look at.
4603 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4604
4605 AccessKinds AK =
4606 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4607
4608 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4610 // Special-case character extraction so we don't have to construct an
4611 // APValue for the whole string.
4612 assert(LVal.Designator.Entries.size() <= 1 &&
4613 "Can only read characters from string literals");
4614 if (LVal.Designator.Entries.empty()) {
4615 // Fail for now for LValue to RValue conversion of an array.
4616 // (This shouldn't show up in C/C++, but it could be triggered by a
4617 // weird EvaluateAsRValue call from a tool.)
4618 Info.FFDiag(Conv);
4619 return false;
4620 }
4621 if (LVal.Designator.isOnePastTheEnd()) {
4622 if (Info.getLangOpts().CPlusPlus11)
4623 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4624 else
4625 Info.FFDiag(Conv);
4626 return false;
4627 }
4628 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4629 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4630 return true;
4631 }
4632 }
4633
4634 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4635 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4636}
4637
4638/// Perform an assignment of Val to LVal. Takes ownership of Val.
4639static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4640 QualType LValType, APValue &Val) {
4641 if (LVal.Designator.Invalid)
4642 return false;
4643
4644 if (!Info.getLangOpts().CPlusPlus14) {
4645 Info.FFDiag(E);
4646 return false;
4647 }
4648
4649 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4650 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4651}
4652
4653namespace {
4654struct CompoundAssignSubobjectHandler {
4655 EvalInfo &Info;
4656 const CompoundAssignOperator *E;
4657 QualType PromotedLHSType;
4659 const APValue &RHS;
4660
4661 static const AccessKinds AccessKind = AK_Assign;
4662
4663 typedef bool result_type;
4664
4665 bool checkConst(QualType QT) {
4666 // Assigning to a const object has undefined behavior.
4667 if (QT.isConstQualified()) {
4668 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4669 return false;
4670 }
4671 return true;
4672 }
4673
4674 bool failed() { return false; }
4675 bool found(APValue &Subobj, QualType SubobjType) {
4676 switch (Subobj.getKind()) {
4677 case APValue::Int:
4678 return found(Subobj.getInt(), SubobjType);
4679 case APValue::Float:
4680 return found(Subobj.getFloat(), SubobjType);
4683 // FIXME: Implement complex compound assignment.
4684 Info.FFDiag(E);
4685 return false;
4686 case APValue::LValue:
4687 return foundPointer(Subobj, SubobjType);
4688 case APValue::Vector:
4689 return foundVector(Subobj, SubobjType);
4691 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4692 << /*read of=*/0 << /*uninitialized object=*/1
4693 << E->getLHS()->getSourceRange();
4694 return false;
4695 default:
4696 // FIXME: can this happen?
4697 Info.FFDiag(E);
4698 return false;
4699 }
4700 }
4701
4702 bool foundVector(APValue &Value, QualType SubobjType) {
4703 if (!checkConst(SubobjType))
4704 return false;
4705
4706 if (!SubobjType->isVectorType()) {
4707 Info.FFDiag(E);
4708 return false;
4709 }
4710 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4711 }
4712
4713 bool found(APSInt &Value, QualType SubobjType) {
4714 if (!checkConst(SubobjType))
4715 return false;
4716
4717 if (!SubobjType->isIntegerType()) {
4718 // We don't support compound assignment on integer-cast-to-pointer
4719 // values.
4720 Info.FFDiag(E);
4721 return false;
4722 }
4723
4724 if (RHS.isInt()) {
4725 APSInt LHS =
4726 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4727 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4728 return false;
4729 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4730 return true;
4731 } else if (RHS.isFloat()) {
4732 const FPOptions FPO = E->getFPFeaturesInEffect(
4733 Info.Ctx.getLangOpts());
4734 APFloat FValue(0.0);
4735 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4736 PromotedLHSType, FValue) &&
4737 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4738 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4739 Value);
4740 }
4741
4742 Info.FFDiag(E);
4743 return false;
4744 }
4745 bool found(APFloat &Value, QualType SubobjType) {
4746 return checkConst(SubobjType) &&
4747 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4748 Value) &&
4749 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4750 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4751 }
4752 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4753 if (!checkConst(SubobjType))
4754 return false;
4755
4756 QualType PointeeType;
4757 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4758 PointeeType = PT->getPointeeType();
4759
4760 if (PointeeType.isNull() || !RHS.isInt() ||
4761 (Opcode != BO_Add && Opcode != BO_Sub)) {
4762 Info.FFDiag(E);
4763 return false;
4764 }
4765
4766 APSInt Offset = RHS.getInt();
4767 if (Opcode == BO_Sub)
4768 negateAsSigned(Offset);
4769
4770 LValue LVal;
4771 LVal.setFrom(Info.Ctx, Subobj);
4772 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4773 return false;
4774 LVal.moveInto(Subobj);
4775 return true;
4776 }
4777};
4778} // end anonymous namespace
4779
4780const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4781
4782/// Perform a compound assignment of LVal <op>= RVal.
4783static bool handleCompoundAssignment(EvalInfo &Info,
4784 const CompoundAssignOperator *E,
4785 const LValue &LVal, QualType LValType,
4786 QualType PromotedLValType,
4787 BinaryOperatorKind Opcode,
4788 const APValue &RVal) {
4789 if (LVal.Designator.Invalid)
4790 return false;
4791
4792 if (!Info.getLangOpts().CPlusPlus14) {
4793 Info.FFDiag(E);
4794 return false;
4795 }
4796
4797 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4798 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4799 RVal };
4800 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4801}
4802
4803namespace {
4804struct IncDecSubobjectHandler {
4805 EvalInfo &Info;
4806 const UnaryOperator *E;
4808 APValue *Old;
4809
4810 typedef bool result_type;
4811
4812 bool checkConst(QualType QT) {
4813 // Assigning to a const object has undefined behavior.
4814 if (QT.isConstQualified()) {
4815 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4816 return false;
4817 }
4818 return true;
4819 }
4820
4821 bool failed() { return false; }
4822 bool found(APValue &Subobj, QualType SubobjType) {
4823 // Stash the old value. Also clear Old, so we don't clobber it later
4824 // if we're post-incrementing a complex.
4825 if (Old) {
4826 *Old = Subobj;
4827 Old = nullptr;
4828 }
4829
4830 switch (Subobj.getKind()) {
4831 case APValue::Int:
4832 return found(Subobj.getInt(), SubobjType);
4833 case APValue::Float:
4834 return found(Subobj.getFloat(), SubobjType);
4836 return found(Subobj.getComplexIntReal(),
4837 SubobjType->castAs<ComplexType>()->getElementType()
4838 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4840 return found(Subobj.getComplexFloatReal(),
4841 SubobjType->castAs<ComplexType>()->getElementType()
4842 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4843 case APValue::LValue:
4844 return foundPointer(Subobj, SubobjType);
4845 default:
4846 // FIXME: can this happen?
4847 Info.FFDiag(E);
4848 return false;
4849 }
4850 }
4851 bool found(APSInt &Value, QualType SubobjType) {
4852 if (!checkConst(SubobjType))
4853 return false;
4854
4855 if (!SubobjType->isIntegerType()) {
4856 // We don't support increment / decrement on integer-cast-to-pointer
4857 // values.
4858 Info.FFDiag(E);
4859 return false;
4860 }
4861
4862 if (Old) *Old = APValue(Value);
4863
4864 // bool arithmetic promotes to int, and the conversion back to bool
4865 // doesn't reduce mod 2^n, so special-case it.
4866 if (SubobjType->isBooleanType()) {
4867 if (AccessKind == AK_Increment)
4868 Value = 1;
4869 else
4870 Value = !Value;
4871 return true;
4872 }
4873
4874 bool WasNegative = Value.isNegative();
4875 if (AccessKind == AK_Increment) {
4876 ++Value;
4877
4878 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4879 APSInt ActualValue(Value, /*IsUnsigned*/true);
4880 return HandleOverflow(Info, E, ActualValue, SubobjType);
4881 }
4882 } else {
4883 --Value;
4884
4885 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4886 unsigned BitWidth = Value.getBitWidth();
4887 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4888 ActualValue.setBit(BitWidth);
4889 return HandleOverflow(Info, E, ActualValue, SubobjType);
4890 }
4891 }
4892 return true;
4893 }
4894 bool found(APFloat &Value, QualType SubobjType) {
4895 if (!checkConst(SubobjType))
4896 return false;
4897
4898 if (Old) *Old = APValue(Value);
4899
4900 APFloat One(Value.getSemantics(), 1);
4901 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4902 APFloat::opStatus St;
4903 if (AccessKind == AK_Increment)
4904 St = Value.add(One, RM);
4905 else
4906 St = Value.subtract(One, RM);
4907 return checkFloatingPointResult(Info, E, St);
4908 }
4909 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4910 if (!checkConst(SubobjType))
4911 return false;
4912
4913 QualType PointeeType;
4914 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4915 PointeeType = PT->getPointeeType();
4916 else {
4917 Info.FFDiag(E);
4918 return false;
4919 }
4920
4921 LValue LVal;
4922 LVal.setFrom(Info.Ctx, Subobj);
4923 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4924 AccessKind == AK_Increment ? 1 : -1))
4925 return false;
4926 LVal.moveInto(Subobj);
4927 return true;
4928 }
4929};
4930} // end anonymous namespace
4931
4932/// Perform an increment or decrement on LVal.
4933static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4934 QualType LValType, bool IsIncrement, APValue *Old) {
4935 if (LVal.Designator.Invalid)
4936 return false;
4937
4938 if (!Info.getLangOpts().CPlusPlus14) {
4939 Info.FFDiag(E);
4940 return false;
4941 }
4942
4943 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4944 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4945 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4946 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4947}
4948
4949/// Build an lvalue for the object argument of a member function call.
4950static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4951 LValue &This) {
4952 if (Object->getType()->isPointerType() && Object->isPRValue())
4953 return EvaluatePointer(Object, This, Info);
4954
4955 if (Object->isGLValue())
4956 return EvaluateLValue(Object, This, Info);
4957
4958 if (Object->getType()->isLiteralType(Info.Ctx))
4959 return EvaluateTemporary(Object, This, Info);
4960
4961 if (Object->getType()->isRecordType() && Object->isPRValue())
4962 return EvaluateTemporary(Object, This, Info);
4963
4964 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4965 return false;
4966}
4967
4968/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4969/// lvalue referring to the result.
4970///
4971/// \param Info - Information about the ongoing evaluation.
4972/// \param LV - An lvalue referring to the base of the member pointer.
4973/// \param RHS - The member pointer expression.
4974/// \param IncludeMember - Specifies whether the member itself is included in
4975/// the resulting LValue subobject designator. This is not possible when
4976/// creating a bound member function.
4977/// \return The field or method declaration to which the member pointer refers,
4978/// or 0 if evaluation fails.
4979static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4980 QualType LVType,
4981 LValue &LV,
4982 const Expr *RHS,
4983 bool IncludeMember = true) {
4984 MemberPtr MemPtr;
4985 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4986 return nullptr;
4987
4988 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4989 // member value, the behavior is undefined.
4990 if (!MemPtr.getDecl()) {
4991 // FIXME: Specific diagnostic.
4992 Info.FFDiag(RHS);
4993 return nullptr;
4994 }
4995
4996 if (MemPtr.isDerivedMember()) {
4997 // This is a member of some derived class. Truncate LV appropriately.
4998 // The end of the derived-to-base path for the base object must match the
4999 // derived-to-base path for the member pointer.
5000 // C++23 [expr.mptr.oper]p4:
5001 // If the result of E1 is an object [...] whose most derived object does
5002 // not contain the member to which E2 refers, the behavior is undefined.
5003 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5004 LV.Designator.Entries.size()) {
5005 Info.FFDiag(RHS);
5006 return nullptr;
5007 }
5008 unsigned PathLengthToMember =
5009 LV.Designator.Entries.size() - MemPtr.Path.size();
5010 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5011 const CXXRecordDecl *LVDecl = getAsBaseClass(
5012 LV.Designator.Entries[PathLengthToMember + I]);
5013 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5014 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5015 Info.FFDiag(RHS);
5016 return nullptr;
5017 }
5018 }
5019 // MemPtr.Path only contains the base classes of the class directly
5020 // containing the member E2. It is still necessary to check that the class
5021 // directly containing the member E2 lies on the derived-to-base path of E1
5022 // to avoid incorrectly permitting member pointer access into a sibling
5023 // class of the class containing the member E2. If this class would
5024 // correspond to the most-derived class of E1, it either isn't contained in
5025 // LV.Designator.Entries or the corresponding entry refers to an array
5026 // element instead. Therefore get the most derived class directly in this
5027 // case. Otherwise the previous entry should correpond to this class.
5028 const CXXRecordDecl *LastLVDecl =
5029 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5030 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5031 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5032 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5033 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5034 Info.FFDiag(RHS);
5035 return nullptr;
5036 }
5037
5038 // Truncate the lvalue to the appropriate derived class.
5039 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5040 PathLengthToMember))
5041 return nullptr;
5042 } else if (!MemPtr.Path.empty()) {
5043 // Extend the LValue path with the member pointer's path.
5044 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5045 MemPtr.Path.size() + IncludeMember);
5046
5047 // Walk down to the appropriate base class.
5048 if (const PointerType *PT = LVType->getAs<PointerType>())
5049 LVType = PT->getPointeeType();
5050 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5051 assert(RD && "member pointer access on non-class-type expression");
5052 // The first class in the path is that of the lvalue.
5053 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5054 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5055 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5056 return nullptr;
5057 RD = Base;
5058 }
5059 // Finally cast to the class containing the member.
5060 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5061 MemPtr.getContainingRecord()))
5062 return nullptr;
5063 }
5064
5065 // Add the member. Note that we cannot build bound member functions here.
5066 if (IncludeMember) {
5067 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5068 if (!HandleLValueMember(Info, RHS, LV, FD))
5069 return nullptr;
5070 } else if (const IndirectFieldDecl *IFD =
5071 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5072 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5073 return nullptr;
5074 } else {
5075 llvm_unreachable("can't construct reference to bound member function");
5076 }
5077 }
5078
5079 return MemPtr.getDecl();
5080}
5081
5082static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5083 const BinaryOperator *BO,
5084 LValue &LV,
5085 bool IncludeMember = true) {
5086 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5087
5088 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5089 if (Info.noteFailure()) {
5090 MemberPtr MemPtr;
5091 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5092 }
5093 return nullptr;
5094 }
5095
5096 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5097 BO->getRHS(), IncludeMember);
5098}
5099
5100/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5101/// the provided lvalue, which currently refers to the base object.
5102static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5103 LValue &Result) {
5104 SubobjectDesignator &D = Result.Designator;
5105 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5106 return false;
5107
5108 QualType TargetQT = E->getType();
5109 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5110 TargetQT = PT->getPointeeType();
5111
5112 auto InvalidCast = [&]() {
5113 if (!Info.checkingPotentialConstantExpression() ||
5114 !Result.AllowConstexprUnknown) {
5115 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5116 << D.MostDerivedType << TargetQT;
5117 }
5118 return false;
5119 };
5120
5121 // Check this cast lands within the final derived-to-base subobject path.
5122 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5123 return InvalidCast();
5124
5125 // Check the type of the final cast. We don't need to check the path,
5126 // since a cast can only be formed if the path is unique.
5127 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5128 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5129 const CXXRecordDecl *FinalType;
5130 if (NewEntriesSize == D.MostDerivedPathLength)
5131 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5132 else
5133 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5134 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5135 return InvalidCast();
5136
5137 // Truncate the lvalue to the appropriate derived class.
5138 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5139}
5140
5141/// Get the value to use for a default-initialized object of type T.
5142/// Return false if it encounters something invalid.
5144 bool Success = true;
5145
5146 // If there is already a value present don't overwrite it.
5147 if (!Result.isAbsent())
5148 return true;
5149
5150 if (auto *RD = T->getAsCXXRecordDecl()) {
5151 if (RD->isInvalidDecl()) {
5152 Result = APValue();
5153 return false;
5154 }
5155 if (RD->isUnion()) {
5156 Result = APValue((const FieldDecl *)nullptr);
5157 return true;
5158 }
5159 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5160 std::distance(RD->field_begin(), RD->field_end()));
5161
5162 unsigned Index = 0;
5163 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5164 End = RD->bases_end();
5165 I != End; ++I, ++Index)
5166 Success &=
5167 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5168
5169 for (const auto *I : RD->fields()) {
5170 if (I->isUnnamedBitField())
5171 continue;
5173 I->getType(), Result.getStructField(I->getFieldIndex()));
5174 }
5175 return Success;
5176 }
5177
5178 if (auto *AT =
5179 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5180 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5181 if (Result.hasArrayFiller())
5182 Success &=
5183 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5184
5185 return Success;
5186 }
5187
5188 Result = APValue::IndeterminateValue();
5189 return true;
5190}
5191
5192namespace {
5193enum EvalStmtResult {
5194 /// Evaluation failed.
5195 ESR_Failed,
5196 /// Hit a 'return' statement.
5197 ESR_Returned,
5198 /// Evaluation succeeded.
5199 ESR_Succeeded,
5200 /// Hit a 'continue' statement.
5201 ESR_Continue,
5202 /// Hit a 'break' statement.
5203 ESR_Break,
5204 /// Still scanning for 'case' or 'default' statement.
5205 ESR_CaseNotFound
5206};
5207}
5208/// Evaluates the initializer of a reference.
5209static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5210 const ValueDecl *D,
5211 const Expr *Init, LValue &Result,
5212 APValue &Val) {
5213 assert(Init->isGLValue() && D->getType()->isReferenceType());
5214 // A reference is an lvalue.
5215 if (!EvaluateLValue(Init, Result, Info))
5216 return false;
5217 // [C++26][decl.ref]
5218 // The object designated by such a glvalue can be outside its lifetime
5219 // Because a null pointer value or a pointer past the end of an object
5220 // does not point to an object, a reference in a well-defined program cannot
5221 // refer to such things;
5222 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5223 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5224 return false;
5225 }
5226
5227 // Save the result.
5228 Result.moveInto(Val);
5229 return true;
5230}
5231
5232static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5233 if (VD->isInvalidDecl())
5234 return false;
5235 // We don't need to evaluate the initializer for a static local.
5236 if (!VD->hasLocalStorage())
5237 return true;
5238
5239 LValue Result;
5240 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5241 ScopeKind::Block, Result);
5242
5243 const Expr *InitE = VD->getInit();
5244 if (!InitE) {
5245 if (VD->getType()->isDependentType())
5246 return Info.noteSideEffect();
5247 return handleDefaultInitValue(VD->getType(), Val);
5248 }
5249 if (InitE->isValueDependent())
5250 return false;
5251
5252 // For references to objects, check they do not designate a one-past-the-end
5253 // object.
5254 if (VD->getType()->isReferenceType()) {
5255 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5256 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5257 // Wipe out any partially-computed value, to allow tracking that this
5258 // evaluation failed.
5259 Val = APValue();
5260 return false;
5261 }
5262
5263 return true;
5264}
5265
5266static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5267 const DecompositionDecl *DD);
5268
5269static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5270 bool EvaluateConditionDecl = false) {
5271 bool OK = true;
5272 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5273 OK &= EvaluateVarDecl(Info, VD);
5274
5275 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5276 EvaluateConditionDecl && DD)
5277 OK &= EvaluateDecompositionDeclInit(Info, DD);
5278
5279 return OK;
5280}
5281
5282static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5283 const DecompositionDecl *DD) {
5284 bool OK = true;
5285 for (auto *BD : DD->flat_bindings())
5286 if (auto *VD = BD->getHoldingVar())
5287 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5288
5289 return OK;
5290}
5291
5292static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5293 const VarDecl *VD) {
5294 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5295 if (!EvaluateDecompositionDeclInit(Info, DD))
5296 return false;
5297 }
5298 return true;
5299}
5300
5301static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5302 assert(E->isValueDependent());
5303 if (Info.noteSideEffect())
5304 return true;
5305 assert(E->containsErrors() && "valid value-dependent expression should never "
5306 "reach invalid code path.");
5307 return false;
5308}
5309
5310/// Evaluate a condition (either a variable declaration or an expression).
5311static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5312 const Expr *Cond, bool &Result) {
5313 if (Cond->isValueDependent())
5314 return false;
5315 FullExpressionRAII Scope(Info);
5316 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5317 return false;
5318 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5319 return false;
5320 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5321 return false;
5322 return Scope.destroy();
5323}
5324
5325namespace {
5326/// A location where the result (returned value) of evaluating a
5327/// statement should be stored.
5328struct StmtResult {
5329 /// The APValue that should be filled in with the returned value.
5330 APValue &Value;
5331 /// The location containing the result, if any (used to support RVO).
5332 const LValue *Slot;
5333};
5334
5335struct TempVersionRAII {
5336 CallStackFrame &Frame;
5337
5338 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5339 Frame.pushTempVersion();
5340 }
5341
5342 ~TempVersionRAII() {
5343 Frame.popTempVersion();
5344 }
5345};
5346
5347}
5348
5349static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5350 const Stmt *S,
5351 const SwitchCase *SC = nullptr);
5352
5353/// Helper to implement named break/continue. Returns 'true' if the evaluation
5354/// result should be propagated up. Otherwise, it sets the evaluation result
5355/// to either Continue to continue the current loop, or Succeeded to break it.
5356static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5357 const Stmt *LoopOrSwitch,
5359 EvalStmtResult &ESR) {
5360 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5361
5362 // For loops, map Succeeded to Continue so we don't have to check for both.
5363 if (!IsSwitch && ESR == ESR_Succeeded) {
5364 ESR = ESR_Continue;
5365 return false;
5366 }
5367
5368 if (ESR != ESR_Break && ESR != ESR_Continue)
5369 return false;
5370
5371 // Are we breaking out of or continuing this statement?
5372 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5373 const Stmt *StackTop = Info.BreakContinueStack.back();
5374 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5375 Info.BreakContinueStack.pop_back();
5376 if (ESR == ESR_Break)
5377 ESR = ESR_Succeeded;
5378 return false;
5379 }
5380
5381 // We're not. Propagate the result up.
5382 for (BlockScopeRAII *S : Scopes) {
5383 if (!S->destroy()) {
5384 ESR = ESR_Failed;
5385 break;
5386 }
5387 }
5388 return true;
5389}
5390
5391/// Evaluate the body of a loop, and translate the result as appropriate.
5392static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5393 const Stmt *Body,
5394 const SwitchCase *Case = nullptr) {
5395 BlockScopeRAII Scope(Info);
5396
5397 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5398 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5399 ESR = ESR_Failed;
5400
5401 return ESR;
5402}
5403
5404/// Evaluate a switch statement.
5405static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5406 const SwitchStmt *SS) {
5407 BlockScopeRAII Scope(Info);
5408
5409 // Evaluate the switch condition.
5410 APSInt Value;
5411 {
5412 if (const Stmt *Init = SS->getInit()) {
5413 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 ESR = ESR_Failed;
5417 return ESR;
5418 }
5419 }
5420
5421 FullExpressionRAII CondScope(Info);
5422 if (SS->getConditionVariable() &&
5423 !EvaluateDecl(Info, SS->getConditionVariable()))
5424 return ESR_Failed;
5425 if (SS->getCond()->isValueDependent()) {
5426 // We don't know what the value is, and which branch should jump to.
5427 EvaluateDependentExpr(SS->getCond(), Info);
5428 return ESR_Failed;
5429 }
5430 if (!EvaluateInteger(SS->getCond(), Value, Info))
5431 return ESR_Failed;
5432
5434 return ESR_Failed;
5435
5436 if (!CondScope.destroy())
5437 return ESR_Failed;
5438 }
5439
5440 // Find the switch case corresponding to the value of the condition.
5441 // FIXME: Cache this lookup.
5442 const SwitchCase *Found = nullptr;
5443 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5444 SC = SC->getNextSwitchCase()) {
5445 if (isa<DefaultStmt>(SC)) {
5446 Found = SC;
5447 continue;
5448 }
5449
5450 const CaseStmt *CS = cast<CaseStmt>(SC);
5451 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5452 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5453 : LHS;
5454 if (LHS <= Value && Value <= RHS) {
5455 Found = SC;
5456 break;
5457 }
5458 }
5459
5460 if (!Found)
5461 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5462
5463 // Search the switch body for the switch case and evaluate it from there.
5464 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5465 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5466 return ESR_Failed;
5467 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5468 return ESR;
5469
5470 switch (ESR) {
5471 case ESR_Break:
5472 llvm_unreachable("Should have been converted to Succeeded");
5473 case ESR_Succeeded:
5474 case ESR_Continue:
5475 case ESR_Failed:
5476 case ESR_Returned:
5477 return ESR;
5478 case ESR_CaseNotFound:
5479 // This can only happen if the switch case is nested within a statement
5480 // expression. We have no intention of supporting that.
5481 Info.FFDiag(Found->getBeginLoc(),
5482 diag::note_constexpr_stmt_expr_unsupported);
5483 return ESR_Failed;
5484 }
5485 llvm_unreachable("Invalid EvalStmtResult!");
5486}
5487
5488static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5489 // An expression E is a core constant expression unless the evaluation of E
5490 // would evaluate one of the following: [C++23] - a control flow that passes
5491 // through a declaration of a variable with static or thread storage duration
5492 // unless that variable is usable in constant expressions.
5493 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5494 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5495 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5496 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5497 return false;
5498 }
5499 return true;
5500}
5501
5502// Evaluate a statement.
5503static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5504 const Stmt *S, const SwitchCase *Case) {
5505 if (!Info.nextStep(S))
5506 return ESR_Failed;
5507
5508 // If we're hunting down a 'case' or 'default' label, recurse through
5509 // substatements until we hit the label.
5510 if (Case) {
5511 switch (S->getStmtClass()) {
5512 case Stmt::CompoundStmtClass:
5513 // FIXME: Precompute which substatement of a compound statement we
5514 // would jump to, and go straight there rather than performing a
5515 // linear scan each time.
5516 case Stmt::LabelStmtClass:
5517 case Stmt::AttributedStmtClass:
5518 case Stmt::DoStmtClass:
5519 break;
5520
5521 case Stmt::CaseStmtClass:
5522 case Stmt::DefaultStmtClass:
5523 if (Case == S)
5524 Case = nullptr;
5525 break;
5526
5527 case Stmt::IfStmtClass: {
5528 // FIXME: Precompute which side of an 'if' we would jump to, and go
5529 // straight there rather than scanning both sides.
5530 const IfStmt *IS = cast<IfStmt>(S);
5531
5532 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5533 // preceded by our switch label.
5534 BlockScopeRAII Scope(Info);
5535
5536 // Step into the init statement in case it brings an (uninitialized)
5537 // variable into scope.
5538 if (const Stmt *Init = IS->getInit()) {
5539 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5540 if (ESR != ESR_CaseNotFound) {
5541 assert(ESR != ESR_Succeeded);
5542 return ESR;
5543 }
5544 }
5545
5546 // Condition variable must be initialized if it exists.
5547 // FIXME: We can skip evaluating the body if there's a condition
5548 // variable, as there can't be any case labels within it.
5549 // (The same is true for 'for' statements.)
5550
5551 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5552 if (ESR == ESR_Failed)
5553 return ESR;
5554 if (ESR != ESR_CaseNotFound)
5555 return Scope.destroy() ? ESR : ESR_Failed;
5556 if (!IS->getElse())
5557 return ESR_CaseNotFound;
5558
5559 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5560 if (ESR == ESR_Failed)
5561 return ESR;
5562 if (ESR != ESR_CaseNotFound)
5563 return Scope.destroy() ? ESR : ESR_Failed;
5564 return ESR_CaseNotFound;
5565 }
5566
5567 case Stmt::WhileStmtClass: {
5568 EvalStmtResult ESR =
5569 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5570 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5571 return ESR;
5572 if (ESR != ESR_Continue)
5573 return ESR;
5574 break;
5575 }
5576
5577 case Stmt::ForStmtClass: {
5578 const ForStmt *FS = cast<ForStmt>(S);
5579 BlockScopeRAII Scope(Info);
5580
5581 // Step into the init statement in case it brings an (uninitialized)
5582 // variable into scope.
5583 if (const Stmt *Init = FS->getInit()) {
5584 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5585 if (ESR != ESR_CaseNotFound) {
5586 assert(ESR != ESR_Succeeded);
5587 return ESR;
5588 }
5589 }
5590
5591 EvalStmtResult ESR =
5592 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5593 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5594 return ESR;
5595 if (ESR != ESR_Continue)
5596 return ESR;
5597 if (const auto *Inc = FS->getInc()) {
5598 if (Inc->isValueDependent()) {
5599 if (!EvaluateDependentExpr(Inc, Info))
5600 return ESR_Failed;
5601 } else {
5602 FullExpressionRAII IncScope(Info);
5603 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5604 return ESR_Failed;
5605 }
5606 }
5607 break;
5608 }
5609
5610 case Stmt::DeclStmtClass: {
5611 // Start the lifetime of any uninitialized variables we encounter. They
5612 // might be used by the selected branch of the switch.
5613 const DeclStmt *DS = cast<DeclStmt>(S);
5614 for (const auto *D : DS->decls()) {
5615 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5616 if (!CheckLocalVariableDeclaration(Info, VD))
5617 return ESR_Failed;
5618 if (VD->hasLocalStorage() && !VD->getInit())
5619 if (!EvaluateVarDecl(Info, VD))
5620 return ESR_Failed;
5621 // FIXME: If the variable has initialization that can't be jumped
5622 // over, bail out of any immediately-surrounding compound-statement
5623 // too. There can't be any case labels here.
5624 }
5625 }
5626 return ESR_CaseNotFound;
5627 }
5628
5629 default:
5630 return ESR_CaseNotFound;
5631 }
5632 }
5633
5634 switch (S->getStmtClass()) {
5635 default:
5636 if (const Expr *E = dyn_cast<Expr>(S)) {
5637 if (E->isValueDependent()) {
5638 if (!EvaluateDependentExpr(E, Info))
5639 return ESR_Failed;
5640 } else {
5641 // Don't bother evaluating beyond an expression-statement which couldn't
5642 // be evaluated.
5643 // FIXME: Do we need the FullExpressionRAII object here?
5644 // VisitExprWithCleanups should create one when necessary.
5645 FullExpressionRAII Scope(Info);
5646 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5647 return ESR_Failed;
5648 }
5649 return ESR_Succeeded;
5650 }
5651
5652 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5653 return ESR_Failed;
5654
5655 case Stmt::NullStmtClass:
5656 return ESR_Succeeded;
5657
5658 case Stmt::DeclStmtClass: {
5659 const DeclStmt *DS = cast<DeclStmt>(S);
5660 for (const auto *D : DS->decls()) {
5661 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5662 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5663 return ESR_Failed;
5664 // Each declaration initialization is its own full-expression.
5665 FullExpressionRAII Scope(Info);
5666 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5667 !Info.noteFailure())
5668 return ESR_Failed;
5669 if (!Scope.destroy())
5670 return ESR_Failed;
5671 }
5672 return ESR_Succeeded;
5673 }
5674
5675 case Stmt::ReturnStmtClass: {
5676 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5677 FullExpressionRAII Scope(Info);
5678 if (RetExpr && RetExpr->isValueDependent()) {
5679 EvaluateDependentExpr(RetExpr, Info);
5680 // We know we returned, but we don't know what the value is.
5681 return ESR_Failed;
5682 }
5683 if (RetExpr &&
5684 !(Result.Slot
5685 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5686 : Evaluate(Result.Value, Info, RetExpr)))
5687 return ESR_Failed;
5688 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5689 }
5690
5691 case Stmt::CompoundStmtClass: {
5692 BlockScopeRAII Scope(Info);
5693
5694 const CompoundStmt *CS = cast<CompoundStmt>(S);
5695 for (const auto *BI : CS->body()) {
5696 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5697 if (ESR == ESR_Succeeded)
5698 Case = nullptr;
5699 else if (ESR != ESR_CaseNotFound) {
5700 if (ESR != ESR_Failed && !Scope.destroy())
5701 return ESR_Failed;
5702 return ESR;
5703 }
5704 }
5705 if (Case)
5706 return ESR_CaseNotFound;
5707 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5708 }
5709
5710 case Stmt::IfStmtClass: {
5711 const IfStmt *IS = cast<IfStmt>(S);
5712
5713 // Evaluate the condition, as either a var decl or as an expression.
5714 BlockScopeRAII Scope(Info);
5715 if (const Stmt *Init = IS->getInit()) {
5716 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5717 if (ESR != ESR_Succeeded) {
5718 if (ESR != ESR_Failed && !Scope.destroy())
5719 return ESR_Failed;
5720 return ESR;
5721 }
5722 }
5723 bool Cond;
5724 if (IS->isConsteval()) {
5726 // If we are not in a constant context, if consteval should not evaluate
5727 // to true.
5728 if (!Info.InConstantContext)
5729 Cond = !Cond;
5730 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5731 Cond))
5732 return ESR_Failed;
5733
5734 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5735 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5736 if (ESR != ESR_Succeeded) {
5737 if (ESR != ESR_Failed && !Scope.destroy())
5738 return ESR_Failed;
5739 return ESR;
5740 }
5741 }
5742 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5743 }
5744
5745 case Stmt::WhileStmtClass: {
5746 const WhileStmt *WS = cast<WhileStmt>(S);
5747 while (true) {
5748 BlockScopeRAII Scope(Info);
5749 bool Continue;
5750 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5751 Continue))
5752 return ESR_Failed;
5753 if (!Continue)
5754 break;
5755
5756 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5757 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
5758 return ESR;
5759
5760 if (ESR != ESR_Continue) {
5761 if (ESR != ESR_Failed && !Scope.destroy())
5762 return ESR_Failed;
5763 return ESR;
5764 }
5765 if (!Scope.destroy())
5766 return ESR_Failed;
5767 }
5768 return ESR_Succeeded;
5769 }
5770
5771 case Stmt::DoStmtClass: {
5772 const DoStmt *DS = cast<DoStmt>(S);
5773 bool Continue;
5774 do {
5775 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5776 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
5777 return ESR;
5778 if (ESR != ESR_Continue)
5779 return ESR;
5780 Case = nullptr;
5781
5782 if (DS->getCond()->isValueDependent()) {
5783 EvaluateDependentExpr(DS->getCond(), Info);
5784 // Bailout as we don't know whether to keep going or terminate the loop.
5785 return ESR_Failed;
5786 }
5787 FullExpressionRAII CondScope(Info);
5788 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5789 !CondScope.destroy())
5790 return ESR_Failed;
5791 } while (Continue);
5792 return ESR_Succeeded;
5793 }
5794
5795 case Stmt::ForStmtClass: {
5796 const ForStmt *FS = cast<ForStmt>(S);
5797 BlockScopeRAII ForScope(Info);
5798 if (FS->getInit()) {
5799 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5800 if (ESR != ESR_Succeeded) {
5801 if (ESR != ESR_Failed && !ForScope.destroy())
5802 return ESR_Failed;
5803 return ESR;
5804 }
5805 }
5806 while (true) {
5807 BlockScopeRAII IterScope(Info);
5808 bool Continue = true;
5809 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5810 FS->getCond(), Continue))
5811 return ESR_Failed;
5812
5813 if (!Continue) {
5814 if (!IterScope.destroy())
5815 return ESR_Failed;
5816 break;
5817 }
5818
5819 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5820 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
5821 return ESR;
5822 if (ESR != ESR_Continue) {
5823 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5824 return ESR_Failed;
5825 return ESR;
5826 }
5827
5828 if (const auto *Inc = FS->getInc()) {
5829 if (Inc->isValueDependent()) {
5830 if (!EvaluateDependentExpr(Inc, Info))
5831 return ESR_Failed;
5832 } else {
5833 FullExpressionRAII IncScope(Info);
5834 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5835 return ESR_Failed;
5836 }
5837 }
5838
5839 if (!IterScope.destroy())
5840 return ESR_Failed;
5841 }
5842 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5843 }
5844
5845 case Stmt::CXXForRangeStmtClass: {
5847 BlockScopeRAII Scope(Info);
5848
5849 // Evaluate the init-statement if present.
5850 if (FS->getInit()) {
5851 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5852 if (ESR != ESR_Succeeded) {
5853 if (ESR != ESR_Failed && !Scope.destroy())
5854 return ESR_Failed;
5855 return ESR;
5856 }
5857 }
5858
5859 // Initialize the __range variable.
5860 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5861 if (ESR != ESR_Succeeded) {
5862 if (ESR != ESR_Failed && !Scope.destroy())
5863 return ESR_Failed;
5864 return ESR;
5865 }
5866
5867 // In error-recovery cases it's possible to get here even if we failed to
5868 // synthesize the __begin and __end variables.
5869 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5870 return ESR_Failed;
5871
5872 // Create the __begin and __end iterators.
5873 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5874 if (ESR != ESR_Succeeded) {
5875 if (ESR != ESR_Failed && !Scope.destroy())
5876 return ESR_Failed;
5877 return ESR;
5878 }
5879 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5880 if (ESR != ESR_Succeeded) {
5881 if (ESR != ESR_Failed && !Scope.destroy())
5882 return ESR_Failed;
5883 return ESR;
5884 }
5885
5886 while (true) {
5887 // Condition: __begin != __end.
5888 {
5889 if (FS->getCond()->isValueDependent()) {
5890 EvaluateDependentExpr(FS->getCond(), Info);
5891 // We don't know whether to keep going or terminate the loop.
5892 return ESR_Failed;
5893 }
5894 bool Continue = true;
5895 FullExpressionRAII CondExpr(Info);
5896 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5897 return ESR_Failed;
5898 if (!Continue)
5899 break;
5900 }
5901
5902 // User's variable declaration, initialized by *__begin.
5903 BlockScopeRAII InnerScope(Info);
5904 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5905 if (ESR != ESR_Succeeded) {
5906 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5907 return ESR_Failed;
5908 return ESR;
5909 }
5910
5911 // Loop body.
5912 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5913 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
5914 return ESR;
5915 if (ESR != ESR_Continue) {
5916 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5917 return ESR_Failed;
5918 return ESR;
5919 }
5920 if (FS->getInc()->isValueDependent()) {
5921 if (!EvaluateDependentExpr(FS->getInc(), Info))
5922 return ESR_Failed;
5923 } else {
5924 // Increment: ++__begin
5925 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5926 return ESR_Failed;
5927 }
5928
5929 if (!InnerScope.destroy())
5930 return ESR_Failed;
5931 }
5932
5933 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5934 }
5935
5936 case Stmt::SwitchStmtClass:
5937 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5938
5939 case Stmt::ContinueStmtClass:
5940 case Stmt::BreakStmtClass: {
5941 auto *B = cast<LoopControlStmt>(S);
5942 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
5943 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
5944 }
5945
5946 case Stmt::LabelStmtClass:
5947 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5948
5949 case Stmt::AttributedStmtClass: {
5950 const auto *AS = cast<AttributedStmt>(S);
5951 const auto *SS = AS->getSubStmt();
5952 MSConstexprContextRAII ConstexprContext(
5953 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5954 isa<ReturnStmt>(SS));
5955
5956 auto LO = Info.getASTContext().getLangOpts();
5957 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5958 for (auto *Attr : AS->getAttrs()) {
5959 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5960 if (!AA)
5961 continue;
5962
5963 auto *Assumption = AA->getAssumption();
5964 if (Assumption->isValueDependent())
5965 return ESR_Failed;
5966
5967 if (Assumption->HasSideEffects(Info.getASTContext()))
5968 continue;
5969
5970 bool Value;
5971 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5972 return ESR_Failed;
5973 if (!Value) {
5974 Info.CCEDiag(Assumption->getExprLoc(),
5975 diag::note_constexpr_assumption_failed);
5976 return ESR_Failed;
5977 }
5978 }
5979 }
5980
5981 return EvaluateStmt(Result, Info, SS, Case);
5982 }
5983
5984 case Stmt::CaseStmtClass:
5985 case Stmt::DefaultStmtClass:
5986 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5987 case Stmt::CXXTryStmtClass:
5988 // Evaluate try blocks by evaluating all sub statements.
5989 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5990 }
5991}
5992
5993/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5994/// default constructor. If so, we'll fold it whether or not it's marked as
5995/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5996/// so we need special handling.
5997static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5998 const CXXConstructorDecl *CD,
5999 bool IsValueInitialization) {
6000 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6001 return false;
6002
6003 // Value-initialization does not call a trivial default constructor, so such a
6004 // call is a core constant expression whether or not the constructor is
6005 // constexpr.
6006 if (!CD->isConstexpr() && !IsValueInitialization) {
6007 if (Info.getLangOpts().CPlusPlus11) {
6008 // FIXME: If DiagDecl is an implicitly-declared special member function,
6009 // we should be much more explicit about why it's not constexpr.
6010 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6011 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6012 Info.Note(CD->getLocation(), diag::note_declared_at);
6013 } else {
6014 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6015 }
6016 }
6017 return true;
6018}
6019
6020/// CheckConstexprFunction - Check that a function can be called in a constant
6021/// expression.
6022static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6024 const FunctionDecl *Definition,
6025 const Stmt *Body) {
6026 // Potential constant expressions can contain calls to declared, but not yet
6027 // defined, constexpr functions.
6028 if (Info.checkingPotentialConstantExpression() && !Definition &&
6029 Declaration->isConstexpr())
6030 return false;
6031
6032 // Bail out if the function declaration itself is invalid. We will
6033 // have produced a relevant diagnostic while parsing it, so just
6034 // note the problematic sub-expression.
6035 if (Declaration->isInvalidDecl()) {
6036 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6037 return false;
6038 }
6039
6040 // DR1872: An instantiated virtual constexpr function can't be called in a
6041 // constant expression (prior to C++20). We can still constant-fold such a
6042 // call.
6043 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6044 cast<CXXMethodDecl>(Declaration)->isVirtual())
6045 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6046
6047 if (Definition && Definition->isInvalidDecl()) {
6048 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6049 return false;
6050 }
6051
6052 // Can we evaluate this function call?
6053 if (Definition && Body &&
6054 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6055 Definition->hasAttr<MSConstexprAttr>())))
6056 return true;
6057
6058 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6059 // Special note for the assert() macro, as the normal error message falsely
6060 // implies we cannot use an assertion during constant evaluation.
6061 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6062 // FIXME: Instead of checking for an implementation-defined function,
6063 // check and evaluate the assert() macro.
6064 StringRef Name = DiagDecl->getName();
6065 bool AssertFailed =
6066 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6067 if (AssertFailed) {
6068 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6069 return false;
6070 }
6071 }
6072
6073 if (Info.getLangOpts().CPlusPlus11) {
6074 // If this function is not constexpr because it is an inherited
6075 // non-constexpr constructor, diagnose that directly.
6076 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6077 if (CD && CD->isInheritingConstructor()) {
6078 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6079 if (!Inherited->isConstexpr())
6080 DiagDecl = CD = Inherited;
6081 }
6082
6083 // FIXME: If DiagDecl is an implicitly-declared special member function
6084 // or an inheriting constructor, we should be much more explicit about why
6085 // it's not constexpr.
6086 if (CD && CD->isInheritingConstructor())
6087 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6088 << CD->getInheritedConstructor().getConstructor()->getParent();
6089 else
6090 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6091 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6092 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6093 } else {
6094 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6095 }
6096 return false;
6097}
6098
6099namespace {
6100struct CheckDynamicTypeHandler {
6102 typedef bool result_type;
6103 bool failed() { return false; }
6104 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6105 bool found(APSInt &Value, QualType SubobjType) { return true; }
6106 bool found(APFloat &Value, QualType SubobjType) { return true; }
6107};
6108} // end anonymous namespace
6109
6110/// Check that we can access the notional vptr of an object / determine its
6111/// dynamic type.
6112static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6113 AccessKinds AK, bool Polymorphic) {
6114 if (This.Designator.Invalid)
6115 return false;
6116
6117 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6118
6119 if (!Obj)
6120 return false;
6121
6122 if (!Obj.Value) {
6123 // The object is not usable in constant expressions, so we can't inspect
6124 // its value to see if it's in-lifetime or what the active union members
6125 // are. We can still check for a one-past-the-end lvalue.
6126 if (This.Designator.isOnePastTheEnd() ||
6127 This.Designator.isMostDerivedAnUnsizedArray()) {
6128 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6129 ? diag::note_constexpr_access_past_end
6130 : diag::note_constexpr_access_unsized_array)
6131 << AK;
6132 return false;
6133 } else if (Polymorphic) {
6134 // Conservatively refuse to perform a polymorphic operation if we would
6135 // not be able to read a notional 'vptr' value.
6136 if (!Info.checkingPotentialConstantExpression() ||
6137 !This.AllowConstexprUnknown) {
6138 APValue Val;
6139 This.moveInto(Val);
6140 QualType StarThisType =
6141 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6142 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6143 << AK << Val.getAsString(Info.Ctx, StarThisType);
6144 }
6145 return false;
6146 }
6147 return true;
6148 }
6149
6150 CheckDynamicTypeHandler Handler{AK};
6151 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6152}
6153
6154/// Check that the pointee of the 'this' pointer in a member function call is
6155/// either within its lifetime or in its period of construction or destruction.
6156static bool
6158 const LValue &This,
6159 const CXXMethodDecl *NamedMember) {
6160 return checkDynamicType(
6161 Info, E, This,
6162 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6163}
6164
6166 /// The dynamic class type of the object.
6168 /// The corresponding path length in the lvalue.
6169 unsigned PathLength;
6170};
6171
6172static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6173 unsigned PathLength) {
6174 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6175 Designator.Entries.size() && "invalid path length");
6176 return (PathLength == Designator.MostDerivedPathLength)
6177 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6178 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6179}
6180
6181/// Determine the dynamic type of an object.
6182static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6183 const Expr *E,
6184 LValue &This,
6185 AccessKinds AK) {
6186 // If we don't have an lvalue denoting an object of class type, there is no
6187 // meaningful dynamic type. (We consider objects of non-class type to have no
6188 // dynamic type.)
6189 if (!checkDynamicType(Info, E, This, AK,
6190 AK != AK_TypeId || This.AllowConstexprUnknown))
6191 return std::nullopt;
6192
6193 if (This.Designator.Invalid)
6194 return std::nullopt;
6195
6196 // Refuse to compute a dynamic type in the presence of virtual bases. This
6197 // shouldn't happen other than in constant-folding situations, since literal
6198 // types can't have virtual bases.
6199 //
6200 // Note that consumers of DynamicType assume that the type has no virtual
6201 // bases, and will need modifications if this restriction is relaxed.
6202 const CXXRecordDecl *Class =
6203 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6204 if (!Class || Class->getNumVBases()) {
6205 Info.FFDiag(E);
6206 return std::nullopt;
6207 }
6208
6209 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6210 // binary search here instead. But the overwhelmingly common case is that
6211 // we're not in the middle of a constructor, so it probably doesn't matter
6212 // in practice.
6213 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6214 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6215 PathLength <= Path.size(); ++PathLength) {
6216 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6217 Path.slice(0, PathLength))) {
6218 case ConstructionPhase::Bases:
6219 case ConstructionPhase::DestroyingBases:
6220 // We're constructing or destroying a base class. This is not the dynamic
6221 // type.
6222 break;
6223
6224 case ConstructionPhase::None:
6225 case ConstructionPhase::AfterBases:
6226 case ConstructionPhase::AfterFields:
6227 case ConstructionPhase::Destroying:
6228 // We've finished constructing the base classes and not yet started
6229 // destroying them again, so this is the dynamic type.
6230 return DynamicType{getBaseClassType(This.Designator, PathLength),
6231 PathLength};
6232 }
6233 }
6234
6235 // CWG issue 1517: we're constructing a base class of the object described by
6236 // 'This', so that object has not yet begun its period of construction and
6237 // any polymorphic operation on it results in undefined behavior.
6238 Info.FFDiag(E);
6239 return std::nullopt;
6240}
6241
6242/// Perform virtual dispatch.
6244 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6245 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6246 std::optional<DynamicType> DynType = ComputeDynamicType(
6247 Info, E, This,
6249 if (!DynType)
6250 return nullptr;
6251
6252 // Find the final overrider. It must be declared in one of the classes on the
6253 // path from the dynamic type to the static type.
6254 // FIXME: If we ever allow literal types to have virtual base classes, that
6255 // won't be true.
6256 const CXXMethodDecl *Callee = Found;
6257 unsigned PathLength = DynType->PathLength;
6258 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6259 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6260 const CXXMethodDecl *Overrider =
6261 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6262 if (Overrider) {
6263 Callee = Overrider;
6264 break;
6265 }
6266 }
6267
6268 // C++2a [class.abstract]p6:
6269 // the effect of making a virtual call to a pure virtual function [...] is
6270 // undefined
6271 if (Callee->isPureVirtual()) {
6272 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6273 Info.Note(Callee->getLocation(), diag::note_declared_at);
6274 return nullptr;
6275 }
6276
6277 // If necessary, walk the rest of the path to determine the sequence of
6278 // covariant adjustment steps to apply.
6279 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6280 Found->getReturnType())) {
6281 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6282 for (unsigned CovariantPathLength = PathLength + 1;
6283 CovariantPathLength != This.Designator.Entries.size();
6284 ++CovariantPathLength) {
6285 const CXXRecordDecl *NextClass =
6286 getBaseClassType(This.Designator, CovariantPathLength);
6287 const CXXMethodDecl *Next =
6288 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6289 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6290 Next->getReturnType(), CovariantAdjustmentPath.back()))
6291 CovariantAdjustmentPath.push_back(Next->getReturnType());
6292 }
6293 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6294 CovariantAdjustmentPath.back()))
6295 CovariantAdjustmentPath.push_back(Found->getReturnType());
6296 }
6297
6298 // Perform 'this' adjustment.
6299 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6300 return nullptr;
6301
6302 return Callee;
6303}
6304
6305/// Perform the adjustment from a value returned by a virtual function to
6306/// a value of the statically expected type, which may be a pointer or
6307/// reference to a base class of the returned type.
6308static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6309 APValue &Result,
6310 ArrayRef<QualType> Path) {
6311 assert(Result.isLValue() &&
6312 "unexpected kind of APValue for covariant return");
6313 if (Result.isNullPointer())
6314 return true;
6315
6316 LValue LVal;
6317 LVal.setFrom(Info.Ctx, Result);
6318
6319 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6320 for (unsigned I = 1; I != Path.size(); ++I) {
6321 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6322 assert(OldClass && NewClass && "unexpected kind of covariant return");
6323 if (OldClass != NewClass &&
6324 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6325 return false;
6326 OldClass = NewClass;
6327 }
6328
6329 LVal.moveInto(Result);
6330 return true;
6331}
6332
6333/// Determine whether \p Base, which is known to be a direct base class of
6334/// \p Derived, is a public base class.
6335static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6336 const CXXRecordDecl *Base) {
6337 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6338 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6339 if (BaseClass && declaresSameEntity(BaseClass, Base))
6340 return BaseSpec.getAccessSpecifier() == AS_public;
6341 }
6342 llvm_unreachable("Base is not a direct base of Derived");
6343}
6344
6345/// Apply the given dynamic cast operation on the provided lvalue.
6346///
6347/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6348/// to find a suitable target subobject.
6349static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6350 LValue &Ptr) {
6351 // We can't do anything with a non-symbolic pointer value.
6352 SubobjectDesignator &D = Ptr.Designator;
6353 if (D.Invalid)
6354 return false;
6355
6356 // C++ [expr.dynamic.cast]p6:
6357 // If v is a null pointer value, the result is a null pointer value.
6358 if (Ptr.isNullPointer() && !E->isGLValue())
6359 return true;
6360
6361 // For all the other cases, we need the pointer to point to an object within
6362 // its lifetime / period of construction / destruction, and we need to know
6363 // its dynamic type.
6364 std::optional<DynamicType> DynType =
6365 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6366 if (!DynType)
6367 return false;
6368
6369 // C++ [expr.dynamic.cast]p7:
6370 // If T is "pointer to cv void", then the result is a pointer to the most
6371 // derived object
6372 if (E->getType()->isVoidPointerType())
6373 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6374
6376 assert(C && "dynamic_cast target is not void pointer nor class");
6377 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6378
6379 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6380 // C++ [expr.dynamic.cast]p9:
6381 if (!E->isGLValue()) {
6382 // The value of a failed cast to pointer type is the null pointer value
6383 // of the required result type.
6384 Ptr.setNull(Info.Ctx, E->getType());
6385 return true;
6386 }
6387
6388 // A failed cast to reference type throws [...] std::bad_cast.
6389 unsigned DiagKind;
6390 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6391 DynType->Type->isDerivedFrom(C)))
6392 DiagKind = 0;
6393 else if (!Paths || Paths->begin() == Paths->end())
6394 DiagKind = 1;
6395 else if (Paths->isAmbiguous(CQT))
6396 DiagKind = 2;
6397 else {
6398 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6399 DiagKind = 3;
6400 }
6401 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6402 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6403 << Info.Ctx.getCanonicalTagType(DynType->Type)
6404 << E->getType().getUnqualifiedType();
6405 return false;
6406 };
6407
6408 // Runtime check, phase 1:
6409 // Walk from the base subobject towards the derived object looking for the
6410 // target type.
6411 for (int PathLength = Ptr.Designator.Entries.size();
6412 PathLength >= (int)DynType->PathLength; --PathLength) {
6413 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6414 if (declaresSameEntity(Class, C))
6415 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6416 // We can only walk across public inheritance edges.
6417 if (PathLength > (int)DynType->PathLength &&
6418 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6419 Class))
6420 return RuntimeCheckFailed(nullptr);
6421 }
6422
6423 // Runtime check, phase 2:
6424 // Search the dynamic type for an unambiguous public base of type C.
6425 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6426 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6427 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6428 Paths.front().Access == AS_public) {
6429 // Downcast to the dynamic type...
6430 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6431 return false;
6432 // ... then upcast to the chosen base class subobject.
6433 for (CXXBasePathElement &Elem : Paths.front())
6434 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6435 return false;
6436 return true;
6437 }
6438
6439 // Otherwise, the runtime check fails.
6440 return RuntimeCheckFailed(&Paths);
6441}
6442
6443namespace {
6444struct StartLifetimeOfUnionMemberHandler {
6445 EvalInfo &Info;
6446 const Expr *LHSExpr;
6447 const FieldDecl *Field;
6448 bool DuringInit;
6449 bool Failed = false;
6450 static const AccessKinds AccessKind = AK_Assign;
6451
6452 typedef bool result_type;
6453 bool failed() { return Failed; }
6454 bool found(APValue &Subobj, QualType SubobjType) {
6455 // We are supposed to perform no initialization but begin the lifetime of
6456 // the object. We interpret that as meaning to do what default
6457 // initialization of the object would do if all constructors involved were
6458 // trivial:
6459 // * All base, non-variant member, and array element subobjects' lifetimes
6460 // begin
6461 // * No variant members' lifetimes begin
6462 // * All scalar subobjects whose lifetimes begin have indeterminate values
6463 assert(SubobjType->isUnionType());
6464 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6465 // This union member is already active. If it's also in-lifetime, there's
6466 // nothing to do.
6467 if (Subobj.getUnionValue().hasValue())
6468 return true;
6469 } else if (DuringInit) {
6470 // We're currently in the process of initializing a different union
6471 // member. If we carried on, that initialization would attempt to
6472 // store to an inactive union member, resulting in undefined behavior.
6473 Info.FFDiag(LHSExpr,
6474 diag::note_constexpr_union_member_change_during_init);
6475 return false;
6476 }
6478 Failed = !handleDefaultInitValue(Field->getType(), Result);
6479 Subobj.setUnion(Field, Result);
6480 return true;
6481 }
6482 bool found(APSInt &Value, QualType SubobjType) {
6483 llvm_unreachable("wrong value kind for union object");
6484 }
6485 bool found(APFloat &Value, QualType SubobjType) {
6486 llvm_unreachable("wrong value kind for union object");
6487 }
6488};
6489} // end anonymous namespace
6490
6491const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6492
6493/// Handle a builtin simple-assignment or a call to a trivial assignment
6494/// operator whose left-hand side might involve a union member access. If it
6495/// does, implicitly start the lifetime of any accessed union elements per
6496/// C++20 [class.union]5.
6497static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6498 const Expr *LHSExpr,
6499 const LValue &LHS) {
6500 if (LHS.InvalidBase || LHS.Designator.Invalid)
6501 return false;
6502
6504 // C++ [class.union]p5:
6505 // define the set S(E) of subexpressions of E as follows:
6506 unsigned PathLength = LHS.Designator.Entries.size();
6507 for (const Expr *E = LHSExpr; E != nullptr;) {
6508 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6509 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6510 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6511 // Note that we can't implicitly start the lifetime of a reference,
6512 // so we don't need to proceed any further if we reach one.
6513 if (!FD || FD->getType()->isReferenceType())
6514 break;
6515
6516 // ... and also contains A.B if B names a union member ...
6517 if (FD->getParent()->isUnion()) {
6518 // ... of a non-class, non-array type, or of a class type with a
6519 // trivial default constructor that is not deleted, or an array of
6520 // such types.
6521 auto *RD =
6522 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6523 if (!RD || RD->hasTrivialDefaultConstructor())
6524 UnionPathLengths.push_back({PathLength - 1, FD});
6525 }
6526
6527 E = ME->getBase();
6528 --PathLength;
6529 assert(declaresSameEntity(FD,
6530 LHS.Designator.Entries[PathLength]
6531 .getAsBaseOrMember().getPointer()));
6532
6533 // -- If E is of the form A[B] and is interpreted as a built-in array
6534 // subscripting operator, S(E) is [S(the array operand, if any)].
6535 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6536 // Step over an ArrayToPointerDecay implicit cast.
6537 auto *Base = ASE->getBase()->IgnoreImplicit();
6538 if (!Base->getType()->isArrayType())
6539 break;
6540
6541 E = Base;
6542 --PathLength;
6543
6544 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6545 // Step over a derived-to-base conversion.
6546 E = ICE->getSubExpr();
6547 if (ICE->getCastKind() == CK_NoOp)
6548 continue;
6549 if (ICE->getCastKind() != CK_DerivedToBase &&
6550 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6551 break;
6552 // Walk path backwards as we walk up from the base to the derived class.
6553 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6554 if (Elt->isVirtual()) {
6555 // A class with virtual base classes never has a trivial default
6556 // constructor, so S(E) is empty in this case.
6557 E = nullptr;
6558 break;
6559 }
6560
6561 --PathLength;
6562 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6563 LHS.Designator.Entries[PathLength]
6564 .getAsBaseOrMember().getPointer()));
6565 }
6566
6567 // -- Otherwise, S(E) is empty.
6568 } else {
6569 break;
6570 }
6571 }
6572
6573 // Common case: no unions' lifetimes are started.
6574 if (UnionPathLengths.empty())
6575 return true;
6576
6577 // if modification of X [would access an inactive union member], an object
6578 // of the type of X is implicitly created
6579 CompleteObject Obj =
6580 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6581 if (!Obj)
6582 return false;
6583 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6584 llvm::reverse(UnionPathLengths)) {
6585 // Form a designator for the union object.
6586 SubobjectDesignator D = LHS.Designator;
6587 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6588
6589 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6590 ConstructionPhase::AfterBases;
6591 StartLifetimeOfUnionMemberHandler StartLifetime{
6592 Info, LHSExpr, LengthAndField.second, DuringInit};
6593 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6594 return false;
6595 }
6596
6597 return true;
6598}
6599
6600static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6601 CallRef Call, EvalInfo &Info, bool NonNull = false,
6602 APValue **EvaluatedArg = nullptr) {
6603 LValue LV;
6604 // Create the parameter slot and register its destruction. For a vararg
6605 // argument, create a temporary.
6606 // FIXME: For calling conventions that destroy parameters in the callee,
6607 // should we consider performing destruction when the function returns
6608 // instead?
6609 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6610 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6611 ScopeKind::Call, LV);
6612 if (!EvaluateInPlace(V, Info, LV, Arg))
6613 return false;
6614
6615 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6616 // undefined behavior, so is non-constant.
6617 if (NonNull && V.isLValue() && V.isNullPointer()) {
6618 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6619 return false;
6620 }
6621
6622 if (EvaluatedArg)
6623 *EvaluatedArg = &V;
6624
6625 return true;
6626}
6627
6628/// Evaluate the arguments to a function call.
6629static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6630 EvalInfo &Info, const FunctionDecl *Callee,
6631 bool RightToLeft = false,
6632 LValue *ObjectArg = nullptr) {
6633 bool Success = true;
6634 llvm::SmallBitVector ForbiddenNullArgs;
6635 if (Callee->hasAttr<NonNullAttr>()) {
6636 ForbiddenNullArgs.resize(Args.size());
6637 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6638 if (!Attr->args_size()) {
6639 ForbiddenNullArgs.set();
6640 break;
6641 } else
6642 for (auto Idx : Attr->args()) {
6643 unsigned ASTIdx = Idx.getASTIndex();
6644 if (ASTIdx >= Args.size())
6645 continue;
6646 ForbiddenNullArgs[ASTIdx] = true;
6647 }
6648 }
6649 }
6650 for (unsigned I = 0; I < Args.size(); I++) {
6651 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6652 const ParmVarDecl *PVD =
6653 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6654 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6655 APValue *That = nullptr;
6656 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6657 // If we're checking for a potential constant expression, evaluate all
6658 // initializers even if some of them fail.
6659 if (!Info.noteFailure())
6660 return false;
6661 Success = false;
6662 }
6663 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6664 ObjectArg->setFrom(Info.Ctx, *That);
6665 }
6666 return Success;
6667}
6668
6669/// Perform a trivial copy from Param, which is the parameter of a copy or move
6670/// constructor or assignment operator.
6671static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6672 const Expr *E, APValue &Result,
6673 bool CopyObjectRepresentation) {
6674 // Find the reference argument.
6675 CallStackFrame *Frame = Info.CurrentCall;
6676 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6677 if (!RefValue) {
6678 Info.FFDiag(E);
6679 return false;
6680 }
6681
6682 // Copy out the contents of the RHS object.
6683 LValue RefLValue;
6684 RefLValue.setFrom(Info.Ctx, *RefValue);
6686 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6687 CopyObjectRepresentation);
6688}
6689
6690/// Evaluate a function call.
6692 const FunctionDecl *Callee,
6693 const LValue *ObjectArg, const Expr *E,
6694 ArrayRef<const Expr *> Args, CallRef Call,
6695 const Stmt *Body, EvalInfo &Info,
6696 APValue &Result, const LValue *ResultSlot) {
6697 if (!Info.CheckCallLimit(CallLoc))
6698 return false;
6699
6700 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6701
6702 // For a trivial copy or move assignment, perform an APValue copy. This is
6703 // essential for unions, where the operations performed by the assignment
6704 // operator cannot be represented as statements.
6705 //
6706 // Skip this for non-union classes with no fields; in that case, the defaulted
6707 // copy/move does not actually read the object.
6708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6709 if (MD && MD->isDefaulted() &&
6710 (MD->getParent()->isUnion() ||
6711 (MD->isTrivial() &&
6713 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6714 assert(ObjectArg &&
6716 APValue RHSValue;
6717 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6718 MD->getParent()->isUnion()))
6719 return false;
6720
6721 LValue Obj;
6722 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6724 RHSValue))
6725 return false;
6726 ObjectArg->moveInto(Result);
6727 return true;
6728 } else if (MD && isLambdaCallOperator(MD)) {
6729 // We're in a lambda; determine the lambda capture field maps unless we're
6730 // just constexpr checking a lambda's call operator. constexpr checking is
6731 // done before the captures have been added to the closure object (unless
6732 // we're inferring constexpr-ness), so we don't have access to them in this
6733 // case. But since we don't need the captures to constexpr check, we can
6734 // just ignore them.
6735 if (!Info.checkingPotentialConstantExpression())
6736 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6737 Frame.LambdaThisCaptureField);
6738 }
6739
6740 StmtResult Ret = {Result, ResultSlot};
6741 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6742 if (ESR == ESR_Succeeded) {
6743 if (Callee->getReturnType()->isVoidType())
6744 return true;
6745 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6746 }
6747 return ESR == ESR_Returned;
6748}
6749
6750/// Evaluate a constructor call.
6751static bool HandleConstructorCall(const Expr *E, const LValue &This,
6752 CallRef Call,
6754 EvalInfo &Info, APValue &Result) {
6755 SourceLocation CallLoc = E->getExprLoc();
6756 if (!Info.CheckCallLimit(CallLoc))
6757 return false;
6758
6759 const CXXRecordDecl *RD = Definition->getParent();
6760 if (RD->getNumVBases()) {
6761 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6762 return false;
6763 }
6764
6765 EvalInfo::EvaluatingConstructorRAII EvalObj(
6766 Info,
6767 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6768 RD->getNumBases());
6769 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6770
6771 // FIXME: Creating an APValue just to hold a nonexistent return value is
6772 // wasteful.
6773 APValue RetVal;
6774 StmtResult Ret = {RetVal, nullptr};
6775
6776 // If it's a delegating constructor, delegate.
6777 if (Definition->isDelegatingConstructor()) {
6779 if ((*I)->getInit()->isValueDependent()) {
6780 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6781 return false;
6782 } else {
6783 FullExpressionRAII InitScope(Info);
6784 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6785 !InitScope.destroy())
6786 return false;
6787 }
6788 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6789 }
6790
6791 // For a trivial copy or move constructor, perform an APValue copy. This is
6792 // essential for unions (or classes with anonymous union members), where the
6793 // operations performed by the constructor cannot be represented by
6794 // ctor-initializers.
6795 //
6796 // Skip this for empty non-union classes; we should not perform an
6797 // lvalue-to-rvalue conversion on them because their copy constructor does not
6798 // actually read them.
6799 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6800 (Definition->getParent()->isUnion() ||
6801 (Definition->isTrivial() &&
6803 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6804 Definition->getParent()->isUnion());
6805 }
6806
6807 // Reserve space for the struct members.
6808 if (!Result.hasValue()) {
6809 if (!RD->isUnion())
6810 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6811 std::distance(RD->field_begin(), RD->field_end()));
6812 else
6813 // A union starts with no active member.
6814 Result = APValue((const FieldDecl*)nullptr);
6815 }
6816
6817 if (RD->isInvalidDecl()) return false;
6818 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6819
6820 // A scope for temporaries lifetime-extended by reference members.
6821 BlockScopeRAII LifetimeExtendedScope(Info);
6822
6823 bool Success = true;
6824 unsigned BasesSeen = 0;
6825#ifndef NDEBUG
6827#endif
6829 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6830 // We might be initializing the same field again if this is an indirect
6831 // field initialization.
6832 if (FieldIt == RD->field_end() ||
6833 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6834 assert(Indirect && "fields out of order?");
6835 return;
6836 }
6837
6838 // Default-initialize any fields with no explicit initializer.
6839 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6840 assert(FieldIt != RD->field_end() && "missing field?");
6841 if (!FieldIt->isUnnamedBitField())
6843 FieldIt->getType(),
6844 Result.getStructField(FieldIt->getFieldIndex()));
6845 }
6846 ++FieldIt;
6847 };
6848 for (const auto *I : Definition->inits()) {
6849 LValue Subobject = This;
6850 LValue SubobjectParent = This;
6851 APValue *Value = &Result;
6852
6853 // Determine the subobject to initialize.
6854 FieldDecl *FD = nullptr;
6855 if (I->isBaseInitializer()) {
6856 QualType BaseType(I->getBaseClass(), 0);
6857#ifndef NDEBUG
6858 // Non-virtual base classes are initialized in the order in the class
6859 // definition. We have already checked for virtual base classes.
6860 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6861 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6862 "base class initializers not in expected order");
6863 ++BaseIt;
6864#endif
6865 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6866 BaseType->getAsCXXRecordDecl(), &Layout))
6867 return false;
6868 Value = &Result.getStructBase(BasesSeen++);
6869 } else if ((FD = I->getMember())) {
6870 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6871 return false;
6872 if (RD->isUnion()) {
6873 Result = APValue(FD);
6874 Value = &Result.getUnionValue();
6875 } else {
6876 SkipToField(FD, false);
6877 Value = &Result.getStructField(FD->getFieldIndex());
6878 }
6879 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6880 // Walk the indirect field decl's chain to find the object to initialize,
6881 // and make sure we've initialized every step along it.
6882 auto IndirectFieldChain = IFD->chain();
6883 for (auto *C : IndirectFieldChain) {
6884 FD = cast<FieldDecl>(C);
6886 // Switch the union field if it differs. This happens if we had
6887 // preceding zero-initialization, and we're now initializing a union
6888 // subobject other than the first.
6889 // FIXME: In this case, the values of the other subobjects are
6890 // specified, since zero-initialization sets all padding bits to zero.
6891 if (!Value->hasValue() ||
6892 (Value->isUnion() &&
6893 !declaresSameEntity(Value->getUnionField(), FD))) {
6894 if (CD->isUnion())
6895 *Value = APValue(FD);
6896 else
6897 // FIXME: This immediately starts the lifetime of all members of
6898 // an anonymous struct. It would be preferable to strictly start
6899 // member lifetime in initialization order.
6901 *Value);
6902 }
6903 // Store Subobject as its parent before updating it for the last element
6904 // in the chain.
6905 if (C == IndirectFieldChain.back())
6906 SubobjectParent = Subobject;
6907 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6908 return false;
6909 if (CD->isUnion())
6910 Value = &Value->getUnionValue();
6911 else {
6912 if (C == IndirectFieldChain.front() && !RD->isUnion())
6913 SkipToField(FD, true);
6914 Value = &Value->getStructField(FD->getFieldIndex());
6915 }
6916 }
6917 } else {
6918 llvm_unreachable("unknown base initializer kind");
6919 }
6920
6921 // Need to override This for implicit field initializers as in this case
6922 // This refers to innermost anonymous struct/union containing initializer,
6923 // not to currently constructed class.
6924 const Expr *Init = I->getInit();
6925 if (Init->isValueDependent()) {
6926 if (!EvaluateDependentExpr(Init, Info))
6927 return false;
6928 } else {
6929 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6931 FullExpressionRAII InitScope(Info);
6932 if (FD && FD->getType()->isReferenceType() &&
6933 !FD->getType()->isFunctionReferenceType()) {
6934 LValue Result;
6935 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6936 *Value)) {
6937 if (!Info.noteFailure())
6938 return false;
6939 Success = false;
6940 }
6941 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6942 (FD && FD->isBitField() &&
6943 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6944 // If we're checking for a potential constant expression, evaluate all
6945 // initializers even if some of them fail.
6946 if (!Info.noteFailure())
6947 return false;
6948 Success = false;
6949 }
6950 }
6951
6952 // This is the point at which the dynamic type of the object becomes this
6953 // class type.
6954 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6955 EvalObj.finishedConstructingBases();
6956 }
6957
6958 // Default-initialize any remaining fields.
6959 if (!RD->isUnion()) {
6960 for (; FieldIt != RD->field_end(); ++FieldIt) {
6961 if (!FieldIt->isUnnamedBitField())
6963 FieldIt->getType(),
6964 Result.getStructField(FieldIt->getFieldIndex()));
6965 }
6966 }
6967
6968 EvalObj.finishedConstructingFields();
6969
6970 return Success &&
6971 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6972 LifetimeExtendedScope.destroy();
6973}
6974
6975static bool HandleConstructorCall(const Expr *E, const LValue &This,
6978 EvalInfo &Info, APValue &Result) {
6979 CallScopeRAII CallScope(Info);
6980 CallRef Call = Info.CurrentCall->createCall(Definition);
6981 if (!EvaluateArgs(Args, Call, Info, Definition))
6982 return false;
6983
6984 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6985 CallScope.destroy();
6986}
6987
6988static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6989 const LValue &This, APValue &Value,
6990 QualType T) {
6991 // Objects can only be destroyed while they're within their lifetimes.
6992 // FIXME: We have no representation for whether an object of type nullptr_t
6993 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6994 // as indeterminate instead?
6995 if (Value.isAbsent() && !T->isNullPtrType()) {
6996 APValue Printable;
6997 This.moveInto(Printable);
6998 Info.FFDiag(CallRange.getBegin(),
6999 diag::note_constexpr_destroy_out_of_lifetime)
7000 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7001 return false;
7002 }
7003
7004 // Invent an expression for location purposes.
7005 // FIXME: We shouldn't need to do this.
7006 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7007
7008 // For arrays, destroy elements right-to-left.
7009 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7010 uint64_t Size = CAT->getZExtSize();
7011 QualType ElemT = CAT->getElementType();
7012
7013 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7014 return false;
7015
7016 LValue ElemLV = This;
7017 ElemLV.addArray(Info, &LocE, CAT);
7018 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7019 return false;
7020
7021 // Ensure that we have actual array elements available to destroy; the
7022 // destructors might mutate the value, so we can't run them on the array
7023 // filler.
7024 if (Size && Size > Value.getArrayInitializedElts())
7025 expandArray(Value, Value.getArraySize() - 1);
7026
7027 // The size of the array might have been reduced by
7028 // a placement new.
7029 for (Size = Value.getArraySize(); Size != 0; --Size) {
7030 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7031 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7032 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7033 return false;
7034 }
7035
7036 // End the lifetime of this array now.
7037 Value = APValue();
7038 return true;
7039 }
7040
7041 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7042 if (!RD) {
7043 if (T.isDestructedType()) {
7044 Info.FFDiag(CallRange.getBegin(),
7045 diag::note_constexpr_unsupported_destruction)
7046 << T;
7047 return false;
7048 }
7049
7050 Value = APValue();
7051 return true;
7052 }
7053
7054 if (RD->getNumVBases()) {
7055 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7056 return false;
7057 }
7058
7059 const CXXDestructorDecl *DD = RD->getDestructor();
7060 if (!DD && !RD->hasTrivialDestructor()) {
7061 Info.FFDiag(CallRange.getBegin());
7062 return false;
7063 }
7064
7065 if (!DD || DD->isTrivial() ||
7066 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7067 // A trivial destructor just ends the lifetime of the object. Check for
7068 // this case before checking for a body, because we might not bother
7069 // building a body for a trivial destructor. Note that it doesn't matter
7070 // whether the destructor is constexpr in this case; all trivial
7071 // destructors are constexpr.
7072 //
7073 // If an anonymous union would be destroyed, some enclosing destructor must
7074 // have been explicitly defined, and the anonymous union destruction should
7075 // have no effect.
7076 Value = APValue();
7077 return true;
7078 }
7079
7080 if (!Info.CheckCallLimit(CallRange.getBegin()))
7081 return false;
7082
7083 const FunctionDecl *Definition = nullptr;
7084 const Stmt *Body = DD->getBody(Definition);
7085
7086 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7087 return false;
7088
7089 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7090 CallRef());
7091
7092 // We're now in the period of destruction of this object.
7093 unsigned BasesLeft = RD->getNumBases();
7094 EvalInfo::EvaluatingDestructorRAII EvalObj(
7095 Info,
7096 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7097 if (!EvalObj.DidInsert) {
7098 // C++2a [class.dtor]p19:
7099 // the behavior is undefined if the destructor is invoked for an object
7100 // whose lifetime has ended
7101 // (Note that formally the lifetime ends when the period of destruction
7102 // begins, even though certain uses of the object remain valid until the
7103 // period of destruction ends.)
7104 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7105 return false;
7106 }
7107
7108 // FIXME: Creating an APValue just to hold a nonexistent return value is
7109 // wasteful.
7110 APValue RetVal;
7111 StmtResult Ret = {RetVal, nullptr};
7112 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7113 return false;
7114
7115 // A union destructor does not implicitly destroy its members.
7116 if (RD->isUnion())
7117 return true;
7118
7119 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7120
7121 // We don't have a good way to iterate fields in reverse, so collect all the
7122 // fields first and then walk them backwards.
7123 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7124 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7125 if (FD->isUnnamedBitField())
7126 continue;
7127
7128 LValue Subobject = This;
7129 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7130 return false;
7131
7132 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7133 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7134 FD->getType()))
7135 return false;
7136 }
7137
7138 if (BasesLeft != 0)
7139 EvalObj.startedDestroyingBases();
7140
7141 // Destroy base classes in reverse order.
7142 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7143 --BasesLeft;
7144
7145 QualType BaseType = Base.getType();
7146 LValue Subobject = This;
7147 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7148 BaseType->getAsCXXRecordDecl(), &Layout))
7149 return false;
7150
7151 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7152 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7153 BaseType))
7154 return false;
7155 }
7156 assert(BasesLeft == 0 && "NumBases was wrong?");
7157
7158 // The period of destruction ends now. The object is gone.
7159 Value = APValue();
7160 return true;
7161}
7162
7163namespace {
7164struct DestroyObjectHandler {
7165 EvalInfo &Info;
7166 const Expr *E;
7167 const LValue &This;
7168 const AccessKinds AccessKind;
7169
7170 typedef bool result_type;
7171 bool failed() { return false; }
7172 bool found(APValue &Subobj, QualType SubobjType) {
7173 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7174 SubobjType);
7175 }
7176 bool found(APSInt &Value, QualType SubobjType) {
7177 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7178 return false;
7179 }
7180 bool found(APFloat &Value, QualType SubobjType) {
7181 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7182 return false;
7183 }
7184};
7185}
7186
7187/// Perform a destructor or pseudo-destructor call on the given object, which
7188/// might in general not be a complete object.
7189static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7190 const LValue &This, QualType ThisType) {
7191 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7192 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7193 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7194}
7195
7196/// Destroy and end the lifetime of the given complete object.
7197static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7199 QualType T) {
7200 // If we've had an unmodeled side-effect, we can't rely on mutable state
7201 // (such as the object we're about to destroy) being correct.
7202 if (Info.EvalStatus.HasSideEffects)
7203 return false;
7204
7205 LValue LV;
7206 LV.set({LVBase});
7207 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7208}
7209
7210/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7211static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7212 LValue &Result) {
7213 if (Info.checkingPotentialConstantExpression() ||
7214 Info.SpeculativeEvaluationDepth)
7215 return false;
7216
7217 // This is permitted only within a call to std::allocator<T>::allocate.
7218 auto Caller = Info.getStdAllocatorCaller("allocate");
7219 if (!Caller) {
7220 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7221 ? diag::note_constexpr_new_untyped
7222 : diag::note_constexpr_new);
7223 return false;
7224 }
7225
7226 QualType ElemType = Caller.ElemType;
7227 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7228 Info.FFDiag(E->getExprLoc(),
7229 diag::note_constexpr_new_not_complete_object_type)
7230 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7231 return false;
7232 }
7233
7234 APSInt ByteSize;
7235 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7236 return false;
7237 bool IsNothrow = false;
7238 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7239 EvaluateIgnoredValue(Info, E->getArg(I));
7240 IsNothrow |= E->getType()->isNothrowT();
7241 }
7242
7243 CharUnits ElemSize;
7244 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7245 return false;
7246 APInt Size, Remainder;
7247 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7248 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7249 if (Remainder != 0) {
7250 // This likely indicates a bug in the implementation of 'std::allocator'.
7251 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7252 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7253 return false;
7254 }
7255
7256 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7257 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7258 if (IsNothrow) {
7259 Result.setNull(Info.Ctx, E->getType());
7260 return true;
7261 }
7262 return false;
7263 }
7264
7265 QualType AllocType = Info.Ctx.getConstantArrayType(
7266 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7267 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7268 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7269 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7270 return true;
7271}
7272
7274 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7275 if (CXXDestructorDecl *DD = RD->getDestructor())
7276 return DD->isVirtual();
7277 return false;
7278}
7279
7281 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7282 if (CXXDestructorDecl *DD = RD->getDestructor())
7283 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7284 return nullptr;
7285}
7286
7287/// Check that the given object is a suitable pointer to a heap allocation that
7288/// still exists and is of the right kind for the purpose of a deletion.
7289///
7290/// On success, returns the heap allocation to deallocate. On failure, produces
7291/// a diagnostic and returns std::nullopt.
7292static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7293 const LValue &Pointer,
7294 DynAlloc::Kind DeallocKind) {
7295 auto PointerAsString = [&] {
7296 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7297 };
7298
7299 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7300 if (!DA) {
7301 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7302 << PointerAsString();
7303 if (Pointer.Base)
7304 NoteLValueLocation(Info, Pointer.Base);
7305 return std::nullopt;
7306 }
7307
7308 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7309 if (!Alloc) {
7310 Info.FFDiag(E, diag::note_constexpr_double_delete);
7311 return std::nullopt;
7312 }
7313
7314 if (DeallocKind != (*Alloc)->getKind()) {
7315 QualType AllocType = Pointer.Base.getDynamicAllocType();
7316 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7317 << DeallocKind << (*Alloc)->getKind() << AllocType;
7318 NoteLValueLocation(Info, Pointer.Base);
7319 return std::nullopt;
7320 }
7321
7322 bool Subobject = false;
7323 if (DeallocKind == DynAlloc::New) {
7324 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7325 Pointer.Designator.isOnePastTheEnd();
7326 } else {
7327 Subobject = Pointer.Designator.Entries.size() != 1 ||
7328 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7329 }
7330 if (Subobject) {
7331 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7332 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7333 return std::nullopt;
7334 }
7335
7336 return Alloc;
7337}
7338
7339// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7340static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7341 if (Info.checkingPotentialConstantExpression() ||
7342 Info.SpeculativeEvaluationDepth)
7343 return false;
7344
7345 // This is permitted only within a call to std::allocator<T>::deallocate.
7346 if (!Info.getStdAllocatorCaller("deallocate")) {
7347 Info.FFDiag(E->getExprLoc());
7348 return true;
7349 }
7350
7351 LValue Pointer;
7352 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7353 return false;
7354 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7355 EvaluateIgnoredValue(Info, E->getArg(I));
7356
7357 if (Pointer.Designator.Invalid)
7358 return false;
7359
7360 // Deleting a null pointer would have no effect, but it's not permitted by
7361 // std::allocator<T>::deallocate's contract.
7362 if (Pointer.isNullPointer()) {
7363 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7364 return true;
7365 }
7366
7367 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7368 return false;
7369
7370 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7371 return true;
7372}
7373
7374//===----------------------------------------------------------------------===//
7375// Generic Evaluation
7376//===----------------------------------------------------------------------===//
7377namespace {
7378
7379class BitCastBuffer {
7380 // FIXME: We're going to need bit-level granularity when we support
7381 // bit-fields.
7382 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7383 // we don't support a host or target where that is the case. Still, we should
7384 // use a more generic type in case we ever do.
7385 SmallVector<std::optional<unsigned char>, 32> Bytes;
7386
7387 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7388 "Need at least 8 bit unsigned char");
7389
7390 bool TargetIsLittleEndian;
7391
7392public:
7393 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7394 : Bytes(Width.getQuantity()),
7395 TargetIsLittleEndian(TargetIsLittleEndian) {}
7396
7397 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7398 SmallVectorImpl<unsigned char> &Output) const {
7399 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7400 // If a byte of an integer is uninitialized, then the whole integer is
7401 // uninitialized.
7402 if (!Bytes[I.getQuantity()])
7403 return false;
7404 Output.push_back(*Bytes[I.getQuantity()]);
7405 }
7406 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7407 std::reverse(Output.begin(), Output.end());
7408 return true;
7409 }
7410
7411 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7412 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7413 std::reverse(Input.begin(), Input.end());
7414
7415 size_t Index = 0;
7416 for (unsigned char Byte : Input) {
7417 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7418 Bytes[Offset.getQuantity() + Index] = Byte;
7419 ++Index;
7420 }
7421 }
7422
7423 size_t size() { return Bytes.size(); }
7424};
7425
7426/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7427/// target would represent the value at runtime.
7428class APValueToBufferConverter {
7429 EvalInfo &Info;
7430 BitCastBuffer Buffer;
7431 const CastExpr *BCE;
7432
7433 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7434 const CastExpr *BCE)
7435 : Info(Info),
7436 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7437 BCE(BCE) {}
7438
7439 bool visit(const APValue &Val, QualType Ty) {
7440 return visit(Val, Ty, CharUnits::fromQuantity(0));
7441 }
7442
7443 // Write out Val with type Ty into Buffer starting at Offset.
7444 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7445 assert((size_t)Offset.getQuantity() <= Buffer.size());
7446
7447 // As a special case, nullptr_t has an indeterminate value.
7448 if (Ty->isNullPtrType())
7449 return true;
7450
7451 // Dig through Src to find the byte at SrcOffset.
7452 switch (Val.getKind()) {
7454 case APValue::None:
7455 return true;
7456
7457 case APValue::Int:
7458 return visitInt(Val.getInt(), Ty, Offset);
7459 case APValue::Float:
7460 return visitFloat(Val.getFloat(), Ty, Offset);
7461 case APValue::Array:
7462 return visitArray(Val, Ty, Offset);
7463 case APValue::Struct:
7464 return visitRecord(Val, Ty, Offset);
7465 case APValue::Vector:
7466 return visitVector(Val, Ty, Offset);
7467
7470 return visitComplex(Val, Ty, Offset);
7472 // FIXME: We should support these.
7473
7474 case APValue::Union:
7477 Info.FFDiag(BCE->getBeginLoc(),
7478 diag::note_constexpr_bit_cast_unsupported_type)
7479 << Ty;
7480 return false;
7481 }
7482
7483 case APValue::LValue:
7484 llvm_unreachable("LValue subobject in bit_cast?");
7485 }
7486 llvm_unreachable("Unhandled APValue::ValueKind");
7487 }
7488
7489 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7490 const RecordDecl *RD = Ty->getAsRecordDecl();
7491 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7492
7493 // Visit the base classes.
7494 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7495 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7496 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7497 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7498 const APValue &Base = Val.getStructBase(I);
7499
7500 // Can happen in error cases.
7501 if (!Base.isStruct())
7502 return false;
7503
7504 if (!visitRecord(Base, BS.getType(),
7505 Layout.getBaseClassOffset(BaseDecl) + Offset))
7506 return false;
7507 }
7508 }
7509
7510 // Visit the fields.
7511 unsigned FieldIdx = 0;
7512 for (FieldDecl *FD : RD->fields()) {
7513 if (FD->isBitField()) {
7514 Info.FFDiag(BCE->getBeginLoc(),
7515 diag::note_constexpr_bit_cast_unsupported_bitfield);
7516 return false;
7517 }
7518
7519 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7520
7521 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7522 "only bit-fields can have sub-char alignment");
7523 CharUnits FieldOffset =
7524 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7525 QualType FieldTy = FD->getType();
7526 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7527 return false;
7528 ++FieldIdx;
7529 }
7530
7531 return true;
7532 }
7533
7534 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7535 const auto *CAT =
7536 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7537 if (!CAT)
7538 return false;
7539
7540 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7541 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7542 unsigned ArraySize = Val.getArraySize();
7543 // First, initialize the initialized elements.
7544 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7545 const APValue &SubObj = Val.getArrayInitializedElt(I);
7546 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7547 return false;
7548 }
7549
7550 // Next, initialize the rest of the array using the filler.
7551 if (Val.hasArrayFiller()) {
7552 const APValue &Filler = Val.getArrayFiller();
7553 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7554 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7555 return false;
7556 }
7557 }
7558
7559 return true;
7560 }
7561
7562 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7563 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7564 QualType EltTy = ComplexTy->getElementType();
7565 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7566 bool IsInt = Val.isComplexInt();
7567
7568 if (IsInt) {
7569 if (!visitInt(Val.getComplexIntReal(), EltTy,
7570 Offset + (0 * EltSizeChars)))
7571 return false;
7572 if (!visitInt(Val.getComplexIntImag(), EltTy,
7573 Offset + (1 * EltSizeChars)))
7574 return false;
7575 } else {
7576 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7577 Offset + (0 * EltSizeChars)))
7578 return false;
7579 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7580 Offset + (1 * EltSizeChars)))
7581 return false;
7582 }
7583
7584 return true;
7585 }
7586
7587 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7588 const VectorType *VTy = Ty->castAs<VectorType>();
7589 QualType EltTy = VTy->getElementType();
7590 unsigned NElts = VTy->getNumElements();
7591
7592 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7593 // Special handling for OpenCL bool vectors:
7594 // Since these vectors are stored as packed bits, but we can't write
7595 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7596 // together into an appropriately sized APInt and write them all out at
7597 // once. Because we don't accept vectors where NElts * EltSize isn't a
7598 // multiple of the char size, there will be no padding space, so we don't
7599 // have to worry about writing data which should have been left
7600 // uninitialized.
7601 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7602
7603 llvm::APInt Res = llvm::APInt::getZero(NElts);
7604 for (unsigned I = 0; I < NElts; ++I) {
7605 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7606 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7607 "bool vector element must be 1-bit unsigned integer!");
7608
7609 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7610 }
7611
7612 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7613 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7614 Buffer.writeObject(Offset, Bytes);
7615 } else {
7616 // Iterate over each of the elements and write them out to the buffer at
7617 // the appropriate offset.
7618 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7619 for (unsigned I = 0; I < NElts; ++I) {
7620 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7621 return false;
7622 }
7623 }
7624
7625 return true;
7626 }
7627
7628 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7629 APSInt AdjustedVal = Val;
7630 unsigned Width = AdjustedVal.getBitWidth();
7631 if (Ty->isBooleanType()) {
7632 Width = Info.Ctx.getTypeSize(Ty);
7633 AdjustedVal = AdjustedVal.extend(Width);
7634 }
7635
7636 SmallVector<uint8_t, 8> Bytes(Width / 8);
7637 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7638 Buffer.writeObject(Offset, Bytes);
7639 return true;
7640 }
7641
7642 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7643 APSInt AsInt(Val.bitcastToAPInt());
7644 return visitInt(AsInt, Ty, Offset);
7645 }
7646
7647public:
7648 static std::optional<BitCastBuffer>
7649 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7650 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7651 APValueToBufferConverter Converter(Info, DstSize, BCE);
7652 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7653 return std::nullopt;
7654 return Converter.Buffer;
7655 }
7656};
7657
7658/// Write an BitCastBuffer into an APValue.
7659class BufferToAPValueConverter {
7660 EvalInfo &Info;
7661 const BitCastBuffer &Buffer;
7662 const CastExpr *BCE;
7663
7664 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7665 const CastExpr *BCE)
7666 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7667
7668 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7669 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7670 // Ideally this will be unreachable.
7671 std::nullopt_t unsupportedType(QualType Ty) {
7672 Info.FFDiag(BCE->getBeginLoc(),
7673 diag::note_constexpr_bit_cast_unsupported_type)
7674 << Ty;
7675 return std::nullopt;
7676 }
7677
7678 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7679 Info.FFDiag(BCE->getBeginLoc(),
7680 diag::note_constexpr_bit_cast_unrepresentable_value)
7681 << Ty << toString(Val, /*Radix=*/10);
7682 return std::nullopt;
7683 }
7684
7685 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7686 const EnumType *EnumSugar = nullptr) {
7687 if (T->isNullPtrType()) {
7688 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7689 return APValue((Expr *)nullptr,
7690 /*Offset=*/CharUnits::fromQuantity(NullValue),
7691 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7692 }
7693
7694 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7695
7696 // Work around floating point types that contain unused padding bytes. This
7697 // is really just `long double` on x86, which is the only fundamental type
7698 // with padding bytes.
7699 if (T->isRealFloatingType()) {
7700 const llvm::fltSemantics &Semantics =
7701 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7702 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7703 assert(NumBits % 8 == 0);
7704 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7705 if (NumBytes != SizeOf)
7706 SizeOf = NumBytes;
7707 }
7708
7709 SmallVector<uint8_t, 8> Bytes;
7710 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7711 // If this is std::byte or unsigned char, then its okay to store an
7712 // indeterminate value.
7713 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7714 bool IsUChar =
7715 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7716 T->isSpecificBuiltinType(BuiltinType::Char_U));
7717 if (!IsStdByte && !IsUChar) {
7718 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7719 Info.FFDiag(BCE->getExprLoc(),
7720 diag::note_constexpr_bit_cast_indet_dest)
7721 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7722 return std::nullopt;
7723 }
7724
7726 }
7727
7728 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7729 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7730
7732 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7733
7734 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7735 if (IntWidth != Val.getBitWidth()) {
7736 APSInt Truncated = Val.trunc(IntWidth);
7737 if (Truncated.extend(Val.getBitWidth()) != Val)
7738 return unrepresentableValue(QualType(T, 0), Val);
7739 Val = Truncated;
7740 }
7741
7742 return APValue(Val);
7743 }
7744
7745 if (T->isRealFloatingType()) {
7746 const llvm::fltSemantics &Semantics =
7747 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7748 return APValue(APFloat(Semantics, Val));
7749 }
7750
7751 return unsupportedType(QualType(T, 0));
7752 }
7753
7754 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7755 const RecordDecl *RD = RTy->getAsRecordDecl();
7756 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7757
7758 unsigned NumBases = 0;
7759 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7760 NumBases = CXXRD->getNumBases();
7761
7762 APValue ResultVal(APValue::UninitStruct(), NumBases,
7763 std::distance(RD->field_begin(), RD->field_end()));
7764
7765 // Visit the base classes.
7766 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7767 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7768 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7769 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7770
7771 std::optional<APValue> SubObj = visitType(
7772 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7773 if (!SubObj)
7774 return std::nullopt;
7775 ResultVal.getStructBase(I) = *SubObj;
7776 }
7777 }
7778
7779 // Visit the fields.
7780 unsigned FieldIdx = 0;
7781 for (FieldDecl *FD : RD->fields()) {
7782 // FIXME: We don't currently support bit-fields. A lot of the logic for
7783 // this is in CodeGen, so we need to factor it around.
7784 if (FD->isBitField()) {
7785 Info.FFDiag(BCE->getBeginLoc(),
7786 diag::note_constexpr_bit_cast_unsupported_bitfield);
7787 return std::nullopt;
7788 }
7789
7790 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7791 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7792
7793 CharUnits FieldOffset =
7794 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7795 Offset;
7796 QualType FieldTy = FD->getType();
7797 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7798 if (!SubObj)
7799 return std::nullopt;
7800 ResultVal.getStructField(FieldIdx) = *SubObj;
7801 ++FieldIdx;
7802 }
7803
7804 return ResultVal;
7805 }
7806
7807 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7808 QualType RepresentationType =
7809 Ty->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
7810 assert(!RepresentationType.isNull() &&
7811 "enum forward decl should be caught by Sema");
7812 const auto *AsBuiltin =
7813 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7814 // Recurse into the underlying type. Treat std::byte transparently as
7815 // unsigned char.
7816 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7817 }
7818
7819 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7820 size_t Size = Ty->getLimitedSize();
7821 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7822
7823 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7824 for (size_t I = 0; I != Size; ++I) {
7825 std::optional<APValue> ElementValue =
7826 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7827 if (!ElementValue)
7828 return std::nullopt;
7829 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7830 }
7831
7832 return ArrayValue;
7833 }
7834
7835 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7836 QualType ElementType = Ty->getElementType();
7837 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7838 bool IsInt = ElementType->isIntegerType();
7839
7840 std::optional<APValue> Values[2];
7841 for (unsigned I = 0; I != 2; ++I) {
7842 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7843 if (!Values[I])
7844 return std::nullopt;
7845 }
7846
7847 if (IsInt)
7848 return APValue(Values[0]->getInt(), Values[1]->getInt());
7849 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7850 }
7851
7852 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7853 QualType EltTy = VTy->getElementType();
7854 unsigned NElts = VTy->getNumElements();
7855 unsigned EltSize =
7856 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7857
7858 SmallVector<APValue, 4> Elts;
7859 Elts.reserve(NElts);
7860 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7861 // Special handling for OpenCL bool vectors:
7862 // Since these vectors are stored as packed bits, but we can't read
7863 // individual bits from the BitCastBuffer, we'll buffer all of the
7864 // elements together into an appropriately sized APInt and write them all
7865 // out at once. Because we don't accept vectors where NElts * EltSize
7866 // isn't a multiple of the char size, there will be no padding space, so
7867 // we don't have to worry about reading any padding data which didn't
7868 // actually need to be accessed.
7869 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7870
7871 SmallVector<uint8_t, 8> Bytes;
7872 Bytes.reserve(NElts / 8);
7873 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7874 return std::nullopt;
7875
7876 APSInt SValInt(NElts, true);
7877 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7878
7879 for (unsigned I = 0; I < NElts; ++I) {
7880 llvm::APInt Elt =
7881 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7882 Elts.emplace_back(
7883 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7884 }
7885 } else {
7886 // Iterate over each of the elements and read them from the buffer at
7887 // the appropriate offset.
7888 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7889 for (unsigned I = 0; I < NElts; ++I) {
7890 std::optional<APValue> EltValue =
7891 visitType(EltTy, Offset + I * EltSizeChars);
7892 if (!EltValue)
7893 return std::nullopt;
7894 Elts.push_back(std::move(*EltValue));
7895 }
7896 }
7897
7898 return APValue(Elts.data(), Elts.size());
7899 }
7900
7901 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7902 return unsupportedType(QualType(Ty, 0));
7903 }
7904
7905 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7906 QualType Can = Ty.getCanonicalType();
7907
7908 switch (Can->getTypeClass()) {
7909#define TYPE(Class, Base) \
7910 case Type::Class: \
7911 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7912#define ABSTRACT_TYPE(Class, Base)
7913#define NON_CANONICAL_TYPE(Class, Base) \
7914 case Type::Class: \
7915 llvm_unreachable("non-canonical type should be impossible!");
7916#define DEPENDENT_TYPE(Class, Base) \
7917 case Type::Class: \
7918 llvm_unreachable( \
7919 "dependent types aren't supported in the constant evaluator!");
7920#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7921 case Type::Class: \
7922 llvm_unreachable("either dependent or not canonical!");
7923#include "clang/AST/TypeNodes.inc"
7924 }
7925 llvm_unreachable("Unhandled Type::TypeClass");
7926 }
7927
7928public:
7929 // Pull out a full value of type DstType.
7930 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7931 const CastExpr *BCE) {
7932 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7933 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7934 }
7935};
7936
7937static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7938 QualType Ty, EvalInfo *Info,
7939 const ASTContext &Ctx,
7940 bool CheckingDest) {
7941 Ty = Ty.getCanonicalType();
7942
7943 auto diag = [&](int Reason) {
7944 if (Info)
7945 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7946 << CheckingDest << (Reason == 4) << Reason;
7947 return false;
7948 };
7949 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7950 if (Info)
7951 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7952 << NoteTy << Construct << Ty;
7953 return false;
7954 };
7955
7956 if (Ty->isUnionType())
7957 return diag(0);
7958 if (Ty->isPointerType())
7959 return diag(1);
7960 if (Ty->isMemberPointerType())
7961 return diag(2);
7962 if (Ty.isVolatileQualified())
7963 return diag(3);
7964
7965 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7966 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7967 for (CXXBaseSpecifier &BS : CXXRD->bases())
7968 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7969 CheckingDest))
7970 return note(1, BS.getType(), BS.getBeginLoc());
7971 }
7972 for (FieldDecl *FD : Record->fields()) {
7973 if (FD->getType()->isReferenceType())
7974 return diag(4);
7975 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7976 CheckingDest))
7977 return note(0, FD->getType(), FD->getBeginLoc());
7978 }
7979 }
7980
7981 if (Ty->isArrayType() &&
7982 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7983 Info, Ctx, CheckingDest))
7984 return false;
7985
7986 if (const auto *VTy = Ty->getAs<VectorType>()) {
7987 QualType EltTy = VTy->getElementType();
7988 unsigned NElts = VTy->getNumElements();
7989 unsigned EltSize =
7990 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7991
7992 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7993 // The vector's size in bits is not a multiple of the target's byte size,
7994 // so its layout is unspecified. For now, we'll simply treat these cases
7995 // as unsupported (this should only be possible with OpenCL bool vectors
7996 // whose element count isn't a multiple of the byte size).
7997 if (Info)
7998 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7999 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8000 return false;
8001 }
8002
8003 if (EltTy->isRealFloatingType() &&
8004 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8005 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8006 // by both clang and LLVM, so for now we won't allow bit_casts involving
8007 // it in a constexpr context.
8008 if (Info)
8009 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8010 << EltTy;
8011 return false;
8012 }
8013 }
8014
8015 return true;
8016}
8017
8018static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8019 const ASTContext &Ctx,
8020 const CastExpr *BCE) {
8021 bool DestOK = checkBitCastConstexprEligibilityType(
8022 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8023 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8024 BCE->getBeginLoc(),
8025 BCE->getSubExpr()->getType(), Info, Ctx, false);
8026 return SourceOK;
8027}
8028
8029static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8030 const APValue &SourceRValue,
8031 const CastExpr *BCE) {
8032 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8033 "no host or target supports non 8-bit chars");
8034
8035 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8036 return false;
8037
8038 // Read out SourceValue into a char buffer.
8039 std::optional<BitCastBuffer> Buffer =
8040 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8041 if (!Buffer)
8042 return false;
8043
8044 // Write out the buffer into a new APValue.
8045 std::optional<APValue> MaybeDestValue =
8046 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8047 if (!MaybeDestValue)
8048 return false;
8049
8050 DestValue = std::move(*MaybeDestValue);
8051 return true;
8052}
8053
8054static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8055 APValue &SourceValue,
8056 const CastExpr *BCE) {
8057 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8058 "no host or target supports non 8-bit chars");
8059 assert(SourceValue.isLValue() &&
8060 "LValueToRValueBitcast requires an lvalue operand!");
8061
8062 LValue SourceLValue;
8063 APValue SourceRValue;
8064 SourceLValue.setFrom(Info.Ctx, SourceValue);
8066 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8067 SourceRValue, /*WantObjectRepresentation=*/true))
8068 return false;
8069
8070 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8071}
8072
8073template <class Derived>
8074class ExprEvaluatorBase
8075 : public ConstStmtVisitor<Derived, bool> {
8076private:
8077 Derived &getDerived() { return static_cast<Derived&>(*this); }
8078 bool DerivedSuccess(const APValue &V, const Expr *E) {
8079 return getDerived().Success(V, E);
8080 }
8081 bool DerivedZeroInitialization(const Expr *E) {
8082 return getDerived().ZeroInitialization(E);
8083 }
8084
8085 // Check whether a conditional operator with a non-constant condition is a
8086 // potential constant expression. If neither arm is a potential constant
8087 // expression, then the conditional operator is not either.
8088 template<typename ConditionalOperator>
8089 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8090 assert(Info.checkingPotentialConstantExpression());
8091
8092 // Speculatively evaluate both arms.
8093 SmallVector<PartialDiagnosticAt, 8> Diag;
8094 {
8095 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8096 StmtVisitorTy::Visit(E->getFalseExpr());
8097 if (Diag.empty())
8098 return;
8099 }
8100
8101 {
8102 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8103 Diag.clear();
8104 StmtVisitorTy::Visit(E->getTrueExpr());
8105 if (Diag.empty())
8106 return;
8107 }
8108
8109 Error(E, diag::note_constexpr_conditional_never_const);
8110 }
8111
8112
8113 template<typename ConditionalOperator>
8114 bool HandleConditionalOperator(const ConditionalOperator *E) {
8115 bool BoolResult;
8116 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8117 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8118 CheckPotentialConstantConditional(E);
8119 return false;
8120 }
8121 if (Info.noteFailure()) {
8122 StmtVisitorTy::Visit(E->getTrueExpr());
8123 StmtVisitorTy::Visit(E->getFalseExpr());
8124 }
8125 return false;
8126 }
8127
8128 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8129 return StmtVisitorTy::Visit(EvalExpr);
8130 }
8131
8132protected:
8133 EvalInfo &Info;
8134 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8135 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8136
8137 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8138 return Info.CCEDiag(E, D);
8139 }
8140
8141 bool ZeroInitialization(const Expr *E) { return Error(E); }
8142
8143 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8144 unsigned BuiltinOp = E->getBuiltinCallee();
8145 return BuiltinOp != 0 &&
8146 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8147 }
8148
8149public:
8150 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8151
8152 EvalInfo &getEvalInfo() { return Info; }
8153
8154 /// Report an evaluation error. This should only be called when an error is
8155 /// first discovered. When propagating an error, just return false.
8156 bool Error(const Expr *E, diag::kind D) {
8157 Info.FFDiag(E, D) << E->getSourceRange();
8158 return false;
8159 }
8160 bool Error(const Expr *E) {
8161 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8162 }
8163
8164 bool VisitStmt(const Stmt *) {
8165 llvm_unreachable("Expression evaluator should not be called on stmts");
8166 }
8167 bool VisitExpr(const Expr *E) {
8168 return Error(E);
8169 }
8170
8171 bool VisitEmbedExpr(const EmbedExpr *E) {
8172 const auto It = E->begin();
8173 return StmtVisitorTy::Visit(*It);
8174 }
8175
8176 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8177 return StmtVisitorTy::Visit(E->getFunctionName());
8178 }
8179 bool VisitConstantExpr(const ConstantExpr *E) {
8180 if (E->hasAPValueResult())
8181 return DerivedSuccess(E->getAPValueResult(), E);
8182
8183 return StmtVisitorTy::Visit(E->getSubExpr());
8184 }
8185
8186 bool VisitParenExpr(const ParenExpr *E)
8187 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8188 bool VisitUnaryExtension(const UnaryOperator *E)
8189 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8190 bool VisitUnaryPlus(const UnaryOperator *E)
8191 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8192 bool VisitChooseExpr(const ChooseExpr *E)
8193 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8194 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8195 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8196 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8197 { return StmtVisitorTy::Visit(E->getReplacement()); }
8198 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8199 TempVersionRAII RAII(*Info.CurrentCall);
8200 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8201 return StmtVisitorTy::Visit(E->getExpr());
8202 }
8203 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8204 TempVersionRAII RAII(*Info.CurrentCall);
8205 // The initializer may not have been parsed yet, or might be erroneous.
8206 if (!E->getExpr())
8207 return Error(E);
8208 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8209 return StmtVisitorTy::Visit(E->getExpr());
8210 }
8211
8212 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8213 FullExpressionRAII Scope(Info);
8214 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8215 }
8216
8217 // Temporaries are registered when created, so we don't care about
8218 // CXXBindTemporaryExpr.
8219 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8220 return StmtVisitorTy::Visit(E->getSubExpr());
8221 }
8222
8223 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8224 CCEDiag(E, diag::note_constexpr_invalid_cast)
8225 << diag::ConstexprInvalidCastKind::Reinterpret;
8226 return static_cast<Derived*>(this)->VisitCastExpr(E);
8227 }
8228 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8229 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8230 CCEDiag(E, diag::note_constexpr_invalid_cast)
8231 << diag::ConstexprInvalidCastKind::Dynamic;
8232 return static_cast<Derived*>(this)->VisitCastExpr(E);
8233 }
8234 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8235 return static_cast<Derived*>(this)->VisitCastExpr(E);
8236 }
8237
8238 bool VisitBinaryOperator(const BinaryOperator *E) {
8239 switch (E->getOpcode()) {
8240 default:
8241 return Error(E);
8242
8243 case BO_Comma:
8244 VisitIgnoredValue(E->getLHS());
8245 return StmtVisitorTy::Visit(E->getRHS());
8246
8247 case BO_PtrMemD:
8248 case BO_PtrMemI: {
8249 LValue Obj;
8250 if (!HandleMemberPointerAccess(Info, E, Obj))
8251 return false;
8253 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8254 return false;
8255 return DerivedSuccess(Result, E);
8256 }
8257 }
8258 }
8259
8260 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8261 return StmtVisitorTy::Visit(E->getSemanticForm());
8262 }
8263
8264 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8265 // Evaluate and cache the common expression. We treat it as a temporary,
8266 // even though it's not quite the same thing.
8267 LValue CommonLV;
8268 if (!Evaluate(Info.CurrentCall->createTemporary(
8269 E->getOpaqueValue(),
8270 getStorageType(Info.Ctx, E->getOpaqueValue()),
8271 ScopeKind::FullExpression, CommonLV),
8272 Info, E->getCommon()))
8273 return false;
8274
8275 return HandleConditionalOperator(E);
8276 }
8277
8278 bool VisitConditionalOperator(const ConditionalOperator *E) {
8279 bool IsBcpCall = false;
8280 // If the condition (ignoring parens) is a __builtin_constant_p call,
8281 // the result is a constant expression if it can be folded without
8282 // side-effects. This is an important GNU extension. See GCC PR38377
8283 // for discussion.
8284 if (const CallExpr *CallCE =
8285 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8286 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8287 IsBcpCall = true;
8288
8289 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8290 // constant expression; we can't check whether it's potentially foldable.
8291 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8292 // it would return 'false' in this mode.
8293 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8294 return false;
8295
8296 FoldConstant Fold(Info, IsBcpCall);
8297 if (!HandleConditionalOperator(E)) {
8298 Fold.keepDiagnostics();
8299 return false;
8300 }
8301
8302 return true;
8303 }
8304
8305 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8306 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8307 Value && !Value->isAbsent())
8308 return DerivedSuccess(*Value, E);
8309
8310 const Expr *Source = E->getSourceExpr();
8311 if (!Source)
8312 return Error(E);
8313 if (Source == E) {
8314 assert(0 && "OpaqueValueExpr recursively refers to itself");
8315 return Error(E);
8316 }
8317 return StmtVisitorTy::Visit(Source);
8318 }
8319
8320 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8321 for (const Expr *SemE : E->semantics()) {
8322 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8323 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8324 // result expression: there could be two different LValues that would
8325 // refer to the same object in that case, and we can't model that.
8326 if (SemE == E->getResultExpr())
8327 return Error(E);
8328
8329 // Unique OVEs get evaluated if and when we encounter them when
8330 // emitting the rest of the semantic form, rather than eagerly.
8331 if (OVE->isUnique())
8332 continue;
8333
8334 LValue LV;
8335 if (!Evaluate(Info.CurrentCall->createTemporary(
8336 OVE, getStorageType(Info.Ctx, OVE),
8337 ScopeKind::FullExpression, LV),
8338 Info, OVE->getSourceExpr()))
8339 return false;
8340 } else if (SemE == E->getResultExpr()) {
8341 if (!StmtVisitorTy::Visit(SemE))
8342 return false;
8343 } else {
8344 if (!EvaluateIgnoredValue(Info, SemE))
8345 return false;
8346 }
8347 }
8348 return true;
8349 }
8350
8351 bool VisitCallExpr(const CallExpr *E) {
8353 if (!handleCallExpr(E, Result, nullptr))
8354 return false;
8355 return DerivedSuccess(Result, E);
8356 }
8357
8358 bool handleCallExpr(const CallExpr *E, APValue &Result,
8359 const LValue *ResultSlot) {
8360 CallScopeRAII CallScope(Info);
8361
8362 const Expr *Callee = E->getCallee()->IgnoreParens();
8363 QualType CalleeType = Callee->getType();
8364
8365 const FunctionDecl *FD = nullptr;
8366 LValue *This = nullptr, ObjectArg;
8367 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8368 bool HasQualifier = false;
8369
8370 CallRef Call;
8371
8372 // Extract function decl and 'this' pointer from the callee.
8373 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8374 const CXXMethodDecl *Member = nullptr;
8375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8376 // Explicit bound member calls, such as x.f() or p->g();
8377 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8378 return false;
8379 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8380 if (!Member)
8381 return Error(Callee);
8382 This = &ObjectArg;
8383 HasQualifier = ME->hasQualifier();
8384 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8385 // Indirect bound member calls ('.*' or '->*').
8386 const ValueDecl *D =
8387 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8388 if (!D)
8389 return false;
8390 Member = dyn_cast<CXXMethodDecl>(D);
8391 if (!Member)
8392 return Error(Callee);
8393 This = &ObjectArg;
8394 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8395 if (!Info.getLangOpts().CPlusPlus20)
8396 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8397 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8398 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8399 } else
8400 return Error(Callee);
8401 FD = Member;
8402 } else if (CalleeType->isFunctionPointerType()) {
8403 LValue CalleeLV;
8404 if (!EvaluatePointer(Callee, CalleeLV, Info))
8405 return false;
8406
8407 if (!CalleeLV.getLValueOffset().isZero())
8408 return Error(Callee);
8409 if (CalleeLV.isNullPointer()) {
8410 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8411 << const_cast<Expr *>(Callee);
8412 return false;
8413 }
8414 FD = dyn_cast_or_null<FunctionDecl>(
8415 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8416 if (!FD)
8417 return Error(Callee);
8418 // Don't call function pointers which have been cast to some other type.
8419 // Per DR (no number yet), the caller and callee can differ in noexcept.
8421 CalleeType->getPointeeType(), FD->getType())) {
8422 return Error(E);
8423 }
8424
8425 // For an (overloaded) assignment expression, evaluate the RHS before the
8426 // LHS.
8427 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8428 if (OCE && OCE->isAssignmentOp()) {
8429 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8430 Call = Info.CurrentCall->createCall(FD);
8431 bool HasThis = false;
8432 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8433 HasThis = MD->isImplicitObjectMemberFunction();
8434 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8435 /*RightToLeft=*/true, &ObjectArg))
8436 return false;
8437 }
8438
8439 // Overloaded operator calls to member functions are represented as normal
8440 // calls with '*this' as the first argument.
8441 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8442 if (MD &&
8443 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8444 // FIXME: When selecting an implicit conversion for an overloaded
8445 // operator delete, we sometimes try to evaluate calls to conversion
8446 // operators without a 'this' parameter!
8447 if (Args.empty())
8448 return Error(E);
8449
8450 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8451 return false;
8452
8453 // If we are calling a static operator, the 'this' argument needs to be
8454 // ignored after being evaluated.
8455 if (MD->isInstance())
8456 This = &ObjectArg;
8457
8458 // If this is syntactically a simple assignment using a trivial
8459 // assignment operator, start the lifetimes of union members as needed,
8460 // per C++20 [class.union]5.
8461 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8462 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8463 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8464 return false;
8465
8466 Args = Args.slice(1);
8467 } else if (MD && MD->isLambdaStaticInvoker()) {
8468 // Map the static invoker for the lambda back to the call operator.
8469 // Conveniently, we don't have to slice out the 'this' argument (as is
8470 // being done for the non-static case), since a static member function
8471 // doesn't have an implicit argument passed in.
8472 const CXXRecordDecl *ClosureClass = MD->getParent();
8473 assert(
8474 ClosureClass->captures().empty() &&
8475 "Number of captures must be zero for conversion to function-ptr");
8476
8477 const CXXMethodDecl *LambdaCallOp =
8478 ClosureClass->getLambdaCallOperator();
8479
8480 // Set 'FD', the function that will be called below, to the call
8481 // operator. If the closure object represents a generic lambda, find
8482 // the corresponding specialization of the call operator.
8483
8484 if (ClosureClass->isGenericLambda()) {
8485 assert(MD->isFunctionTemplateSpecialization() &&
8486 "A generic lambda's static-invoker function must be a "
8487 "template specialization");
8488 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8489 FunctionTemplateDecl *CallOpTemplate =
8490 LambdaCallOp->getDescribedFunctionTemplate();
8491 void *InsertPos = nullptr;
8492 FunctionDecl *CorrespondingCallOpSpecialization =
8493 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8494 assert(CorrespondingCallOpSpecialization &&
8495 "We must always have a function call operator specialization "
8496 "that corresponds to our static invoker specialization");
8497 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8498 FD = CorrespondingCallOpSpecialization;
8499 } else
8500 FD = LambdaCallOp;
8502 if (FD->getDeclName().isAnyOperatorNew()) {
8503 LValue Ptr;
8504 if (!HandleOperatorNewCall(Info, E, Ptr))
8505 return false;
8506 Ptr.moveInto(Result);
8507 return CallScope.destroy();
8508 } else {
8509 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8510 }
8511 }
8512 } else
8513 return Error(E);
8514
8515 // Evaluate the arguments now if we've not already done so.
8516 if (!Call) {
8517 Call = Info.CurrentCall->createCall(FD);
8518 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8519 &ObjectArg))
8520 return false;
8521 }
8522
8523 SmallVector<QualType, 4> CovariantAdjustmentPath;
8524 if (This) {
8525 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8526 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8527 // Perform virtual dispatch, if necessary.
8528 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8529 CovariantAdjustmentPath);
8530 if (!FD)
8531 return false;
8532 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8533 // Check that the 'this' pointer points to an object of the right type.
8534 // FIXME: If this is an assignment operator call, we may need to change
8535 // the active union member before we check this.
8536 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8537 return false;
8538 }
8539 }
8540
8541 // Destructor calls are different enough that they have their own codepath.
8542 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8543 assert(This && "no 'this' pointer for destructor call");
8544 return HandleDestruction(Info, E, *This,
8545 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8546 CallScope.destroy();
8547 }
8548
8549 const FunctionDecl *Definition = nullptr;
8550 Stmt *Body = FD->getBody(Definition);
8551 SourceLocation Loc = E->getExprLoc();
8552
8553 // Treat the object argument as `this` when evaluating defaulted
8554 // special menmber functions
8556 This = &ObjectArg;
8557
8558 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8559 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8560 Result, ResultSlot))
8561 return false;
8562
8563 if (!CovariantAdjustmentPath.empty() &&
8565 CovariantAdjustmentPath))
8566 return false;
8567
8568 return CallScope.destroy();
8569 }
8570
8571 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8572 return StmtVisitorTy::Visit(E->getInitializer());
8573 }
8574 bool VisitInitListExpr(const InitListExpr *E) {
8575 if (E->getNumInits() == 0)
8576 return DerivedZeroInitialization(E);
8577 if (E->getNumInits() == 1)
8578 return StmtVisitorTy::Visit(E->getInit(0));
8579 return Error(E);
8580 }
8581 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8582 return DerivedZeroInitialization(E);
8583 }
8584 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8585 return DerivedZeroInitialization(E);
8586 }
8587 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8588 return DerivedZeroInitialization(E);
8589 }
8590
8591 /// A member expression where the object is a prvalue is itself a prvalue.
8592 bool VisitMemberExpr(const MemberExpr *E) {
8593 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8594 "missing temporary materialization conversion");
8595 assert(!E->isArrow() && "missing call to bound member function?");
8596
8597 APValue Val;
8598 if (!Evaluate(Val, Info, E->getBase()))
8599 return false;
8600
8601 QualType BaseTy = E->getBase()->getType();
8602
8603 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8604 if (!FD) return Error(E);
8605 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8606 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8607 FD->getParent()->getCanonicalDecl() &&
8608 "record / field mismatch");
8609
8610 // Note: there is no lvalue base here. But this case should only ever
8611 // happen in C or in C++98, where we cannot be evaluating a constexpr
8612 // constructor, which is the only case the base matters.
8613 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8614 SubobjectDesignator Designator(BaseTy);
8615 Designator.addDeclUnchecked(FD);
8616
8618 return extractSubobject(Info, E, Obj, Designator, Result) &&
8619 DerivedSuccess(Result, E);
8620 }
8621
8622 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8623 APValue Val;
8624 if (!Evaluate(Val, Info, E->getBase()))
8625 return false;
8626
8627 if (Val.isVector()) {
8628 SmallVector<uint32_t, 4> Indices;
8629 E->getEncodedElementAccess(Indices);
8630 if (Indices.size() == 1) {
8631 // Return scalar.
8632 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8633 } else {
8634 // Construct new APValue vector.
8635 SmallVector<APValue, 4> Elts;
8636 for (unsigned I = 0; I < Indices.size(); ++I) {
8637 Elts.push_back(Val.getVectorElt(Indices[I]));
8638 }
8639 APValue VecResult(Elts.data(), Indices.size());
8640 return DerivedSuccess(VecResult, E);
8641 }
8642 }
8643
8644 return false;
8645 }
8646
8647 bool VisitCastExpr(const CastExpr *E) {
8648 switch (E->getCastKind()) {
8649 default:
8650 break;
8651
8652 case CK_AtomicToNonAtomic: {
8653 APValue AtomicVal;
8654 // This does not need to be done in place even for class/array types:
8655 // atomic-to-non-atomic conversion implies copying the object
8656 // representation.
8657 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8658 return false;
8659 return DerivedSuccess(AtomicVal, E);
8660 }
8661
8662 case CK_NoOp:
8663 case CK_UserDefinedConversion:
8664 return StmtVisitorTy::Visit(E->getSubExpr());
8665
8666 case CK_LValueToRValue: {
8667 LValue LVal;
8668 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8669 return false;
8670 APValue RVal;
8671 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8673 LVal, RVal))
8674 return false;
8675 return DerivedSuccess(RVal, E);
8676 }
8677 case CK_LValueToRValueBitCast: {
8678 APValue DestValue, SourceValue;
8679 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8680 return false;
8681 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8682 return false;
8683 return DerivedSuccess(DestValue, E);
8684 }
8685
8686 case CK_AddressSpaceConversion: {
8687 APValue Value;
8688 if (!Evaluate(Value, Info, E->getSubExpr()))
8689 return false;
8690 return DerivedSuccess(Value, E);
8691 }
8692 }
8693
8694 return Error(E);
8695 }
8696
8697 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8698 return VisitUnaryPostIncDec(UO);
8699 }
8700 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8701 return VisitUnaryPostIncDec(UO);
8702 }
8703 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8704 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8705 return Error(UO);
8706
8707 LValue LVal;
8708 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8709 return false;
8710 APValue RVal;
8711 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8712 UO->isIncrementOp(), &RVal))
8713 return false;
8714 return DerivedSuccess(RVal, UO);
8715 }
8716
8717 bool VisitStmtExpr(const StmtExpr *E) {
8718 // We will have checked the full-expressions inside the statement expression
8719 // when they were completed, and don't need to check them again now.
8720 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8721 false);
8722
8723 const CompoundStmt *CS = E->getSubStmt();
8724 if (CS->body_empty())
8725 return true;
8726
8727 BlockScopeRAII Scope(Info);
8729 BE = CS->body_end();
8730 /**/; ++BI) {
8731 if (BI + 1 == BE) {
8732 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8733 if (!FinalExpr) {
8734 Info.FFDiag((*BI)->getBeginLoc(),
8735 diag::note_constexpr_stmt_expr_unsupported);
8736 return false;
8737 }
8738 return this->Visit(FinalExpr) && Scope.destroy();
8739 }
8740
8742 StmtResult Result = { ReturnValue, nullptr };
8743 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8744 if (ESR != ESR_Succeeded) {
8745 // FIXME: If the statement-expression terminated due to 'return',
8746 // 'break', or 'continue', it would be nice to propagate that to
8747 // the outer statement evaluation rather than bailing out.
8748 if (ESR != ESR_Failed)
8749 Info.FFDiag((*BI)->getBeginLoc(),
8750 diag::note_constexpr_stmt_expr_unsupported);
8751 return false;
8752 }
8753 }
8754
8755 llvm_unreachable("Return from function from the loop above.");
8756 }
8757
8758 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8759 return StmtVisitorTy::Visit(E->getSelectedExpr());
8760 }
8761
8762 /// Visit a value which is evaluated, but whose value is ignored.
8763 void VisitIgnoredValue(const Expr *E) {
8764 EvaluateIgnoredValue(Info, E);
8765 }
8766
8767 /// Potentially visit a MemberExpr's base expression.
8768 void VisitIgnoredBaseExpression(const Expr *E) {
8769 // While MSVC doesn't evaluate the base expression, it does diagnose the
8770 // presence of side-effecting behavior.
8771 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8772 return;
8773 VisitIgnoredValue(E);
8774 }
8775};
8776
8777} // namespace
8778
8779//===----------------------------------------------------------------------===//
8780// Common base class for lvalue and temporary evaluation.
8781//===----------------------------------------------------------------------===//
8782namespace {
8783template<class Derived>
8784class LValueExprEvaluatorBase
8785 : public ExprEvaluatorBase<Derived> {
8786protected:
8787 LValue &Result;
8788 bool InvalidBaseOK;
8789 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8790 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8791
8792 bool Success(APValue::LValueBase B) {
8793 Result.set(B);
8794 return true;
8795 }
8796
8797 bool evaluatePointer(const Expr *E, LValue &Result) {
8798 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8799 }
8800
8801public:
8802 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8803 : ExprEvaluatorBaseTy(Info), Result(Result),
8804 InvalidBaseOK(InvalidBaseOK) {}
8805
8806 bool Success(const APValue &V, const Expr *E) {
8807 Result.setFrom(this->Info.Ctx, V);
8808 return true;
8809 }
8810
8811 bool VisitMemberExpr(const MemberExpr *E) {
8812 // Handle non-static data members.
8813 QualType BaseTy;
8814 bool EvalOK;
8815 if (E->isArrow()) {
8816 EvalOK = evaluatePointer(E->getBase(), Result);
8817 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8818 } else if (E->getBase()->isPRValue()) {
8819 assert(E->getBase()->getType()->isRecordType());
8820 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8821 BaseTy = E->getBase()->getType();
8822 } else {
8823 EvalOK = this->Visit(E->getBase());
8824 BaseTy = E->getBase()->getType();
8825 }
8826 if (!EvalOK) {
8827 if (!InvalidBaseOK)
8828 return false;
8829 Result.setInvalid(E);
8830 return true;
8831 }
8832
8833 const ValueDecl *MD = E->getMemberDecl();
8834 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8835 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8836 FD->getParent()->getCanonicalDecl() &&
8837 "record / field mismatch");
8838 (void)BaseTy;
8839 if (!HandleLValueMember(this->Info, E, Result, FD))
8840 return false;
8841 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8842 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8843 return false;
8844 } else
8845 return this->Error(E);
8846
8847 if (MD->getType()->isReferenceType()) {
8848 APValue RefValue;
8849 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8850 RefValue))
8851 return false;
8852 return Success(RefValue, E);
8853 }
8854 return true;
8855 }
8856
8857 bool VisitBinaryOperator(const BinaryOperator *E) {
8858 switch (E->getOpcode()) {
8859 default:
8860 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8861
8862 case BO_PtrMemD:
8863 case BO_PtrMemI:
8864 return HandleMemberPointerAccess(this->Info, E, Result);
8865 }
8866 }
8867
8868 bool VisitCastExpr(const CastExpr *E) {
8869 switch (E->getCastKind()) {
8870 default:
8871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8872
8873 case CK_DerivedToBase:
8874 case CK_UncheckedDerivedToBase:
8875 if (!this->Visit(E->getSubExpr()))
8876 return false;
8877
8878 // Now figure out the necessary offset to add to the base LV to get from
8879 // the derived class to the base class.
8880 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8881 Result);
8882 }
8883 }
8884};
8885}
8886
8887//===----------------------------------------------------------------------===//
8888// LValue Evaluation
8889//
8890// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8891// function designators (in C), decl references to void objects (in C), and
8892// temporaries (if building with -Wno-address-of-temporary).
8893//
8894// LValue evaluation produces values comprising a base expression of one of the
8895// following types:
8896// - Declarations
8897// * VarDecl
8898// * FunctionDecl
8899// - Literals
8900// * CompoundLiteralExpr in C (and in global scope in C++)
8901// * StringLiteral
8902// * PredefinedExpr
8903// * ObjCStringLiteralExpr
8904// * ObjCEncodeExpr
8905// * AddrLabelExpr
8906// * BlockExpr
8907// * CallExpr for a MakeStringConstant builtin
8908// - typeid(T) expressions, as TypeInfoLValues
8909// - Locals and temporaries
8910// * MaterializeTemporaryExpr
8911// * Any Expr, with a CallIndex indicating the function in which the temporary
8912// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8913// from the AST (FIXME).
8914// * A MaterializeTemporaryExpr that has static storage duration, with no
8915// CallIndex, for a lifetime-extended temporary.
8916// * The ConstantExpr that is currently being evaluated during evaluation of an
8917// immediate invocation.
8918// plus an offset in bytes.
8919//===----------------------------------------------------------------------===//
8920namespace {
8921class LValueExprEvaluator
8922 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8923public:
8924 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8925 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8926
8927 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8928 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8929
8930 bool VisitCallExpr(const CallExpr *E);
8931 bool VisitDeclRefExpr(const DeclRefExpr *E);
8932 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8933 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8934 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8935 bool VisitMemberExpr(const MemberExpr *E);
8936 bool VisitStringLiteral(const StringLiteral *E) {
8937 return Success(APValue::LValueBase(
8938 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8939 }
8940 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8941 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8942 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8943 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8944 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8945 bool VisitUnaryDeref(const UnaryOperator *E);
8946 bool VisitUnaryReal(const UnaryOperator *E);
8947 bool VisitUnaryImag(const UnaryOperator *E);
8948 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8949 return VisitUnaryPreIncDec(UO);
8950 }
8951 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8952 return VisitUnaryPreIncDec(UO);
8953 }
8954 bool VisitBinAssign(const BinaryOperator *BO);
8955 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8956
8957 bool VisitCastExpr(const CastExpr *E) {
8958 switch (E->getCastKind()) {
8959 default:
8960 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8961
8962 case CK_LValueBitCast:
8963 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8964 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8965 << Info.Ctx.getLangOpts().CPlusPlus;
8966 if (!Visit(E->getSubExpr()))
8967 return false;
8968 Result.Designator.setInvalid();
8969 return true;
8970
8971 case CK_BaseToDerived:
8972 if (!Visit(E->getSubExpr()))
8973 return false;
8974 return HandleBaseToDerivedCast(Info, E, Result);
8975
8976 case CK_Dynamic:
8977 if (!Visit(E->getSubExpr()))
8978 return false;
8980 }
8981 }
8982};
8983} // end anonymous namespace
8984
8985/// Get an lvalue to a field of a lambda's closure type.
8986static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8987 const CXXMethodDecl *MD, const FieldDecl *FD,
8988 bool LValueToRValueConversion) {
8989 // Static lambda function call operators can't have captures. We already
8990 // diagnosed this, so bail out here.
8991 if (MD->isStatic()) {
8992 assert(Info.CurrentCall->This == nullptr &&
8993 "This should not be set for a static call operator");
8994 return false;
8995 }
8996
8997 // Start with 'Result' referring to the complete closure object...
8999 // Self may be passed by reference or by value.
9000 const ParmVarDecl *Self = MD->getParamDecl(0);
9001 if (Self->getType()->isReferenceType()) {
9002 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9003 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9004 Result.setFrom(Info.Ctx, *RefValue);
9005 } else {
9006 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9007 CallStackFrame *Frame =
9008 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9009 .first;
9010 unsigned Version = Info.CurrentCall->Arguments.Version;
9011 Result.set({VD, Frame->Index, Version});
9012 }
9013 } else
9014 Result = *Info.CurrentCall->This;
9015
9016 // ... then update it to refer to the field of the closure object
9017 // that represents the capture.
9018 if (!HandleLValueMember(Info, E, Result, FD))
9019 return false;
9020
9021 // And if the field is of reference type (or if we captured '*this' by
9022 // reference), update 'Result' to refer to what
9023 // the field refers to.
9024 if (LValueToRValueConversion) {
9025 APValue RVal;
9026 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9027 return false;
9028 Result.setFrom(Info.Ctx, RVal);
9029 }
9030 return true;
9031}
9032
9033/// Evaluate an expression as an lvalue. This can be legitimately called on
9034/// expressions which are not glvalues, in three cases:
9035/// * function designators in C, and
9036/// * "extern void" objects
9037/// * @selector() expressions in Objective-C
9038static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9039 bool InvalidBaseOK) {
9040 assert(!E->isValueDependent());
9041 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9043 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9044}
9045
9046bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9047 const ValueDecl *D = E->getDecl();
9048
9049 // If we are within a lambda's call operator, check whether the 'VD' referred
9050 // to within 'E' actually represents a lambda-capture that maps to a
9051 // data-member/field within the closure object, and if so, evaluate to the
9052 // field or what the field refers to.
9053 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9055 // We don't always have a complete capture-map when checking or inferring if
9056 // the function call operator meets the requirements of a constexpr function
9057 // - but we don't need to evaluate the captures to determine constexprness
9058 // (dcl.constexpr C++17).
9059 if (Info.checkingPotentialConstantExpression())
9060 return false;
9061
9062 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9063 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9064 return HandleLambdaCapture(Info, E, Result, MD, FD,
9065 FD->getType()->isReferenceType());
9066 }
9067 }
9068
9069 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9070 UnnamedGlobalConstantDecl>(D))
9071 return Success(cast<ValueDecl>(D));
9072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9073 return VisitVarDecl(E, VD);
9074 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9075 return Visit(BD->getBinding());
9076 return Error(E);
9077}
9078
9079bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9080 CallStackFrame *Frame = nullptr;
9081 unsigned Version = 0;
9082 if (VD->hasLocalStorage()) {
9083 // Only if a local variable was declared in the function currently being
9084 // evaluated, do we expect to be able to find its value in the current
9085 // frame. (Otherwise it was likely declared in an enclosing context and
9086 // could either have a valid evaluatable value (for e.g. a constexpr
9087 // variable) or be ill-formed (and trigger an appropriate evaluation
9088 // diagnostic)).
9089 CallStackFrame *CurrFrame = Info.CurrentCall;
9090 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9091 // Function parameters are stored in some caller's frame. (Usually the
9092 // immediate caller, but for an inherited constructor they may be more
9093 // distant.)
9094 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9095 if (CurrFrame->Arguments) {
9096 VD = CurrFrame->Arguments.getOrigParam(PVD);
9097 Frame =
9098 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9099 Version = CurrFrame->Arguments.Version;
9100 }
9101 } else {
9102 Frame = CurrFrame;
9103 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9104 }
9105 }
9106 }
9107
9108 if (!VD->getType()->isReferenceType()) {
9109 if (Frame) {
9110 Result.set({VD, Frame->Index, Version});
9111 return true;
9112 }
9113 return Success(VD);
9114 }
9115
9116 if (!Info.getLangOpts().CPlusPlus11) {
9117 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9118 << VD << VD->getType();
9119 Info.Note(VD->getLocation(), diag::note_declared_at);
9120 }
9121
9122 APValue *V;
9123 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9124 return false;
9125
9126 if (!V) {
9127 Result.set(VD);
9128 Result.AllowConstexprUnknown = true;
9129 return true;
9130 }
9131
9132 return Success(*V, E);
9133}
9134
9135bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9136 if (!IsConstantEvaluatedBuiltinCall(E))
9137 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9138
9139 switch (E->getBuiltinCallee()) {
9140 default:
9141 return false;
9142 case Builtin::BIas_const:
9143 case Builtin::BIforward:
9144 case Builtin::BIforward_like:
9145 case Builtin::BImove:
9146 case Builtin::BImove_if_noexcept:
9147 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9148 return Visit(E->getArg(0));
9149 break;
9150 }
9151
9152 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9153}
9154
9155bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9156 const MaterializeTemporaryExpr *E) {
9157 // Walk through the expression to find the materialized temporary itself.
9160 const Expr *Inner =
9161 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9162
9163 // If we passed any comma operators, evaluate their LHSs.
9164 for (const Expr *E : CommaLHSs)
9165 if (!EvaluateIgnoredValue(Info, E))
9166 return false;
9167
9168 // A materialized temporary with static storage duration can appear within the
9169 // result of a constant expression evaluation, so we need to preserve its
9170 // value for use outside this evaluation.
9171 APValue *Value;
9172 if (E->getStorageDuration() == SD_Static) {
9173 if (Info.EvalMode == EvaluationMode::ConstantFold)
9174 return false;
9175 // FIXME: What about SD_Thread?
9176 Value = E->getOrCreateValue(true);
9177 *Value = APValue();
9178 Result.set(E);
9179 } else {
9180 Value = &Info.CurrentCall->createTemporary(
9181 E, Inner->getType(),
9182 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9183 : ScopeKind::Block,
9184 Result);
9185 }
9186
9187 QualType Type = Inner->getType();
9188
9189 // Materialize the temporary itself.
9190 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9191 *Value = APValue();
9192 return false;
9193 }
9194
9195 // Adjust our lvalue to refer to the desired subobject.
9196 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9197 --I;
9198 switch (Adjustments[I].Kind) {
9200 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9201 Type, Result))
9202 return false;
9203 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9204 break;
9205
9207 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9208 return false;
9209 Type = Adjustments[I].Field->getType();
9210 break;
9211
9213 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9214 Adjustments[I].Ptr.RHS))
9215 return false;
9216 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9217 break;
9218 }
9219 }
9220
9221 return true;
9222}
9223
9224bool
9225LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9226 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9227 "lvalue compound literal in c++?");
9228 APValue *Lit;
9229 // If CompountLiteral has static storage, its value can be used outside
9230 // this expression. So evaluate it once and store it in ASTContext.
9231 if (E->hasStaticStorage()) {
9232 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9233 Result.set(E);
9234 // Reset any previously evaluated state, otherwise evaluation below might
9235 // fail.
9236 // FIXME: Should we just re-use the previously evaluated value instead?
9237 *Lit = APValue();
9238 } else {
9239 assert(!Info.getLangOpts().CPlusPlus);
9240 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9241 ScopeKind::Block, Result);
9242 }
9243 // FIXME: Evaluating in place isn't always right. We should figure out how to
9244 // use appropriate evaluation context here, see
9245 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9246 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9247 *Lit = APValue();
9248 return false;
9249 }
9250 return true;
9251}
9252
9253bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9254 TypeInfoLValue TypeInfo;
9255
9256 if (!E->isPotentiallyEvaluated()) {
9257 if (E->isTypeOperand())
9258 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9259 else
9260 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9261 } else {
9262 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9263 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9264 << E->getExprOperand()->getType()
9265 << E->getExprOperand()->getSourceRange();
9266 }
9267
9268 if (!Visit(E->getExprOperand()))
9269 return false;
9270
9271 std::optional<DynamicType> DynType =
9273 if (!DynType)
9274 return false;
9275
9276 TypeInfo = TypeInfoLValue(
9277 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9278 }
9279
9280 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9281}
9282
9283bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9284 return Success(E->getGuidDecl());
9285}
9286
9287bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9288 // Handle static data members.
9289 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9290 VisitIgnoredBaseExpression(E->getBase());
9291 return VisitVarDecl(E, VD);
9292 }
9293
9294 // Handle static member functions.
9295 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9296 if (MD->isStatic()) {
9297 VisitIgnoredBaseExpression(E->getBase());
9298 return Success(MD);
9299 }
9300 }
9301
9302 // Handle non-static data members.
9303 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9304}
9305
9306bool LValueExprEvaluator::VisitExtVectorElementExpr(
9307 const ExtVectorElementExpr *E) {
9308 bool Success = true;
9309
9310 APValue Val;
9311 if (!Evaluate(Val, Info, E->getBase())) {
9312 if (!Info.noteFailure())
9313 return false;
9314 Success = false;
9315 }
9316
9318 E->getEncodedElementAccess(Indices);
9319 // FIXME: support accessing more than one element
9320 if (Indices.size() > 1)
9321 return false;
9322
9323 if (Success) {
9324 Result.setFrom(Info.Ctx, Val);
9325 QualType BaseType = E->getBase()->getType();
9326 if (E->isArrow())
9327 BaseType = BaseType->getPointeeType();
9328 const auto *VT = BaseType->castAs<VectorType>();
9329 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9330 VT->getNumElements(), Indices[0]);
9331 }
9332
9333 return Success;
9334}
9335
9336bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9337 if (E->getBase()->getType()->isSveVLSBuiltinType())
9338 return Error(E);
9339
9340 APSInt Index;
9341 bool Success = true;
9342
9343 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9344 APValue Val;
9345 if (!Evaluate(Val, Info, E->getBase())) {
9346 if (!Info.noteFailure())
9347 return false;
9348 Success = false;
9349 }
9350
9351 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9352 if (!Info.noteFailure())
9353 return false;
9354 Success = false;
9355 }
9356
9357 if (Success) {
9358 Result.setFrom(Info.Ctx, Val);
9359 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9360 VT->getNumElements(), Index.getExtValue());
9361 }
9362
9363 return Success;
9364 }
9365
9366 // C++17's rules require us to evaluate the LHS first, regardless of which
9367 // side is the base.
9368 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9369 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9370 : !EvaluateInteger(SubExpr, Index, Info)) {
9371 if (!Info.noteFailure())
9372 return false;
9373 Success = false;
9374 }
9375 }
9376
9377 return Success &&
9378 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9379}
9380
9381bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9382 bool Success = evaluatePointer(E->getSubExpr(), Result);
9383 // [C++26][expr.unary.op]
9384 // If the operand points to an object or function, the result
9385 // denotes that object or function; otherwise, the behavior is undefined.
9386 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9387 // immediately.
9389 return Success;
9391 E->getType())) ||
9392 Info.noteUndefinedBehavior();
9393}
9394
9395bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9396 if (!Visit(E->getSubExpr()))
9397 return false;
9398 // __real is a no-op on scalar lvalues.
9399 if (E->getSubExpr()->getType()->isAnyComplexType())
9400 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9401 return true;
9402}
9403
9404bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9405 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9406 "lvalue __imag__ on scalar?");
9407 if (!Visit(E->getSubExpr()))
9408 return false;
9409 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9410 return true;
9411}
9412
9413bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9415 return Error(UO);
9416
9417 if (!this->Visit(UO->getSubExpr()))
9418 return false;
9419
9420 return handleIncDec(
9421 this->Info, UO, Result, UO->getSubExpr()->getType(),
9422 UO->isIncrementOp(), nullptr);
9423}
9424
9425bool LValueExprEvaluator::VisitCompoundAssignOperator(
9426 const CompoundAssignOperator *CAO) {
9427 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9428 return Error(CAO);
9429
9430 bool Success = true;
9431
9432 // C++17 onwards require that we evaluate the RHS first.
9433 APValue RHS;
9434 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9435 if (!Info.noteFailure())
9436 return false;
9437 Success = false;
9438 }
9439
9440 // The overall lvalue result is the result of evaluating the LHS.
9441 if (!this->Visit(CAO->getLHS()) || !Success)
9442 return false;
9443
9445 this->Info, CAO,
9446 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9447 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9448}
9449
9450bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9451 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9452 return Error(E);
9453
9454 bool Success = true;
9455
9456 // C++17 onwards require that we evaluate the RHS first.
9457 APValue NewVal;
9458 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9459 if (!Info.noteFailure())
9460 return false;
9461 Success = false;
9462 }
9463
9464 if (!this->Visit(E->getLHS()) || !Success)
9465 return false;
9466
9467 if (Info.getLangOpts().CPlusPlus20 &&
9469 return false;
9470
9471 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9472 NewVal);
9473}
9474
9475//===----------------------------------------------------------------------===//
9476// Pointer Evaluation
9477//===----------------------------------------------------------------------===//
9478
9479/// Convenience function. LVal's base must be a call to an alloc_size
9480/// function.
9482 const LValue &LVal,
9483 llvm::APInt &Result) {
9484 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9485 "Can't get the size of a non alloc_size function");
9486 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9487 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9488 std::optional<llvm::APInt> Size =
9489 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9490 if (!Size)
9491 return false;
9492
9493 Result = std::move(*Size);
9494 return true;
9495}
9496
9497/// Attempts to evaluate the given LValueBase as the result of a call to
9498/// a function with the alloc_size attribute. If it was possible to do so, this
9499/// function will return true, make Result's Base point to said function call,
9500/// and mark Result's Base as invalid.
9502 LValue &Result) {
9503 if (Base.isNull())
9504 return false;
9505
9506 // Because we do no form of static analysis, we only support const variables.
9507 //
9508 // Additionally, we can't support parameters, nor can we support static
9509 // variables (in the latter case, use-before-assign isn't UB; in the former,
9510 // we have no clue what they'll be assigned to).
9511 const auto *VD =
9512 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9513 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9514 return false;
9515
9516 const Expr *Init = VD->getAnyInitializer();
9517 if (!Init || Init->getType().isNull())
9518 return false;
9519
9520 const Expr *E = Init->IgnoreParens();
9521 if (!tryUnwrapAllocSizeCall(E))
9522 return false;
9523
9524 // Store E instead of E unwrapped so that the type of the LValue's base is
9525 // what the user wanted.
9526 Result.setInvalid(E);
9527
9528 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9529 Result.addUnsizedArray(Info, E, Pointee);
9530 return true;
9531}
9532
9533namespace {
9534class PointerExprEvaluator
9535 : public ExprEvaluatorBase<PointerExprEvaluator> {
9536 LValue &Result;
9537 bool InvalidBaseOK;
9538
9539 bool Success(const Expr *E) {
9540 Result.set(E);
9541 return true;
9542 }
9543
9544 bool evaluateLValue(const Expr *E, LValue &Result) {
9545 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9546 }
9547
9548 bool evaluatePointer(const Expr *E, LValue &Result) {
9549 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9550 }
9551
9552 bool visitNonBuiltinCallExpr(const CallExpr *E);
9553public:
9554
9555 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9556 : ExprEvaluatorBaseTy(info), Result(Result),
9557 InvalidBaseOK(InvalidBaseOK) {}
9558
9559 bool Success(const APValue &V, const Expr *E) {
9560 Result.setFrom(Info.Ctx, V);
9561 return true;
9562 }
9563 bool ZeroInitialization(const Expr *E) {
9564 Result.setNull(Info.Ctx, E->getType());
9565 return true;
9566 }
9567
9568 bool VisitBinaryOperator(const BinaryOperator *E);
9569 bool VisitCastExpr(const CastExpr* E);
9570 bool VisitUnaryAddrOf(const UnaryOperator *E);
9571 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9572 { return Success(E); }
9573 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9575 return Success(E);
9576 if (Info.noteFailure())
9577 EvaluateIgnoredValue(Info, E->getSubExpr());
9578 return Error(E);
9579 }
9580 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9581 { return Success(E); }
9582 bool VisitCallExpr(const CallExpr *E);
9583 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9584 bool VisitBlockExpr(const BlockExpr *E) {
9585 if (!E->getBlockDecl()->hasCaptures())
9586 return Success(E);
9587 return Error(E);
9588 }
9589 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9590 auto DiagnoseInvalidUseOfThis = [&] {
9591 if (Info.getLangOpts().CPlusPlus11)
9592 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9593 else
9594 Info.FFDiag(E);
9595 };
9596
9597 // Can't look at 'this' when checking a potential constant expression.
9598 if (Info.checkingPotentialConstantExpression())
9599 return false;
9600
9601 bool IsExplicitLambda =
9602 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9603 if (!IsExplicitLambda) {
9604 if (!Info.CurrentCall->This) {
9605 DiagnoseInvalidUseOfThis();
9606 return false;
9607 }
9608
9609 Result = *Info.CurrentCall->This;
9610 }
9611
9612 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9613 // Ensure we actually have captured 'this'. If something was wrong with
9614 // 'this' capture, the error would have been previously reported.
9615 // Otherwise we can be inside of a default initialization of an object
9616 // declared by lambda's body, so no need to return false.
9617 if (!Info.CurrentCall->LambdaThisCaptureField) {
9618 if (IsExplicitLambda && !Info.CurrentCall->This) {
9619 DiagnoseInvalidUseOfThis();
9620 return false;
9621 }
9622
9623 return true;
9624 }
9625
9626 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9627 return HandleLambdaCapture(
9628 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9629 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9630 }
9631 return true;
9632 }
9633
9634 bool VisitCXXNewExpr(const CXXNewExpr *E);
9635
9636 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9637 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9638 APValue LValResult = E->EvaluateInContext(
9639 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9640 Result.setFrom(Info.Ctx, LValResult);
9641 return true;
9642 }
9643
9644 bool VisitEmbedExpr(const EmbedExpr *E) {
9645 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9646 return true;
9647 }
9648
9649 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9650 std::string ResultStr = E->ComputeName(Info.Ctx);
9651
9652 QualType CharTy = Info.Ctx.CharTy.withConst();
9653 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9654 ResultStr.size() + 1);
9655 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9656 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9657
9658 StringLiteral *SL =
9659 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9660 /*Pascal*/ false, ArrayTy, E->getLocation());
9661
9662 evaluateLValue(SL, Result);
9663 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9664 return true;
9665 }
9666
9667 // FIXME: Missing: @protocol, @selector
9668};
9669} // end anonymous namespace
9670
9671static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9672 bool InvalidBaseOK) {
9673 assert(!E->isValueDependent());
9674 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9675 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9676}
9677
9678bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9679 if (E->getOpcode() != BO_Add &&
9680 E->getOpcode() != BO_Sub)
9681 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9682
9683 const Expr *PExp = E->getLHS();
9684 const Expr *IExp = E->getRHS();
9685 if (IExp->getType()->isPointerType())
9686 std::swap(PExp, IExp);
9687
9688 bool EvalPtrOK = evaluatePointer(PExp, Result);
9689 if (!EvalPtrOK && !Info.noteFailure())
9690 return false;
9691
9692 llvm::APSInt Offset;
9693 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9694 return false;
9695
9696 if (E->getOpcode() == BO_Sub)
9697 negateAsSigned(Offset);
9698
9699 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9700 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9701}
9702
9703bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9704 return evaluateLValue(E->getSubExpr(), Result);
9705}
9706
9707// Is the provided decl 'std::source_location::current'?
9709 if (!FD)
9710 return false;
9711 const IdentifierInfo *FnII = FD->getIdentifier();
9712 if (!FnII || !FnII->isStr("current"))
9713 return false;
9714
9715 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9716 if (!RD)
9717 return false;
9718
9719 const IdentifierInfo *ClassII = RD->getIdentifier();
9720 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9721}
9722
9723bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9724 const Expr *SubExpr = E->getSubExpr();
9725
9726 switch (E->getCastKind()) {
9727 default:
9728 break;
9729 case CK_BitCast:
9730 case CK_CPointerToObjCPointerCast:
9731 case CK_BlockPointerToObjCPointerCast:
9732 case CK_AnyPointerToBlockPointerCast:
9733 case CK_AddressSpaceConversion:
9734 if (!Visit(SubExpr))
9735 return false;
9736 if (E->getType()->isFunctionPointerType() ||
9737 SubExpr->getType()->isFunctionPointerType()) {
9738 // Casting between two function pointer types, or between a function
9739 // pointer and an object pointer, is always a reinterpret_cast.
9740 CCEDiag(E, diag::note_constexpr_invalid_cast)
9741 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9742 << Info.Ctx.getLangOpts().CPlusPlus;
9743 Result.Designator.setInvalid();
9744 } else if (!E->getType()->isVoidPointerType()) {
9745 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9746 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9747 // also static_casts, but we disallow them as a resolution to DR1312.
9748 //
9749 // In some circumstances, we permit casting from void* to cv1 T*, when the
9750 // actual pointee object is actually a cv2 T.
9751 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9752 !Result.IsNullPtr;
9753 bool VoidPtrCastMaybeOK =
9754 Result.IsNullPtr ||
9755 (HasValidResult &&
9756 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9757 E->getType()->getPointeeType()));
9758 // 1. We'll allow it in std::allocator::allocate, and anything which that
9759 // calls.
9760 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9761 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9762 // We'll allow it in the body of std::source_location::current. GCC's
9763 // implementation had a parameter of type `void*`, and casts from
9764 // that back to `const __impl*` in its body.
9765 if (VoidPtrCastMaybeOK &&
9766 (Info.getStdAllocatorCaller("allocate") ||
9767 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9768 Info.getLangOpts().CPlusPlus26)) {
9769 // Permitted.
9770 } else {
9771 if (SubExpr->getType()->isVoidPointerType() &&
9772 Info.getLangOpts().CPlusPlus) {
9773 if (HasValidResult)
9774 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9775 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9776 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9777 << E->getType()->getPointeeType();
9778 else
9779 CCEDiag(E, diag::note_constexpr_invalid_cast)
9780 << diag::ConstexprInvalidCastKind::CastFrom
9781 << SubExpr->getType();
9782 } else
9783 CCEDiag(E, diag::note_constexpr_invalid_cast)
9784 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9785 << Info.Ctx.getLangOpts().CPlusPlus;
9786 Result.Designator.setInvalid();
9787 }
9788 }
9789 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9790 ZeroInitialization(E);
9791 return true;
9792
9793 case CK_DerivedToBase:
9794 case CK_UncheckedDerivedToBase:
9795 if (!evaluatePointer(E->getSubExpr(), Result))
9796 return false;
9797 if (!Result.Base && Result.Offset.isZero())
9798 return true;
9799
9800 // Now figure out the necessary offset to add to the base LV to get from
9801 // the derived class to the base class.
9802 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9803 castAs<PointerType>()->getPointeeType(),
9804 Result);
9805
9806 case CK_BaseToDerived:
9807 if (!Visit(E->getSubExpr()))
9808 return false;
9809 if (!Result.Base && Result.Offset.isZero())
9810 return true;
9811 return HandleBaseToDerivedCast(Info, E, Result);
9812
9813 case CK_Dynamic:
9814 if (!Visit(E->getSubExpr()))
9815 return false;
9817
9818 case CK_NullToPointer:
9819 VisitIgnoredValue(E->getSubExpr());
9820 return ZeroInitialization(E);
9821
9822 case CK_IntegralToPointer: {
9823 CCEDiag(E, diag::note_constexpr_invalid_cast)
9824 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9825 << Info.Ctx.getLangOpts().CPlusPlus;
9826
9827 APValue Value;
9828 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9829 break;
9830
9831 if (Value.isInt()) {
9832 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9833 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9834 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9835 Result.setNull(Info.Ctx, E->getType());
9836 } else {
9837 Result.Base = (Expr *)nullptr;
9838 Result.InvalidBase = false;
9839 Result.Offset = CharUnits::fromQuantity(N);
9840 Result.Designator.setInvalid();
9841 Result.IsNullPtr = false;
9842 }
9843 return true;
9844 } else {
9845 // In rare instances, the value isn't an lvalue.
9846 // For example, when the value is the difference between the addresses of
9847 // two labels. We reject that as a constant expression because we can't
9848 // compute a valid offset to convert into a pointer.
9849 if (!Value.isLValue())
9850 return false;
9851
9852 // Cast is of an lvalue, no need to change value.
9853 Result.setFrom(Info.Ctx, Value);
9854 return true;
9855 }
9856 }
9857
9858 case CK_ArrayToPointerDecay: {
9859 if (SubExpr->isGLValue()) {
9860 if (!evaluateLValue(SubExpr, Result))
9861 return false;
9862 } else {
9863 APValue &Value = Info.CurrentCall->createTemporary(
9864 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9865 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9866 return false;
9867 }
9868 // The result is a pointer to the first element of the array.
9869 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9870 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9871 Result.addArray(Info, E, CAT);
9872 else
9873 Result.addUnsizedArray(Info, E, AT->getElementType());
9874 return true;
9875 }
9876
9877 case CK_FunctionToPointerDecay:
9878 return evaluateLValue(SubExpr, Result);
9879
9880 case CK_LValueToRValue: {
9881 LValue LVal;
9882 if (!evaluateLValue(E->getSubExpr(), LVal))
9883 return false;
9884
9885 APValue RVal;
9886 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9888 LVal, RVal))
9889 return InvalidBaseOK &&
9890 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9891 return Success(RVal, E);
9892 }
9893 }
9894
9895 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9896}
9897
9899 UnaryExprOrTypeTrait ExprKind) {
9900 // C++ [expr.alignof]p3:
9901 // When alignof is applied to a reference type, the result is the
9902 // alignment of the referenced type.
9903 T = T.getNonReferenceType();
9904
9905 if (T.getQualifiers().hasUnaligned())
9906 return CharUnits::One();
9907
9908 const bool AlignOfReturnsPreferred =
9909 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9910
9911 // __alignof is defined to return the preferred alignment.
9912 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9913 // as well.
9914 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9915 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9916 // alignof and _Alignof are defined to return the ABI alignment.
9917 else if (ExprKind == UETT_AlignOf)
9918 return Ctx.getTypeAlignInChars(T.getTypePtr());
9919 else
9920 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9921}
9922
9924 UnaryExprOrTypeTrait ExprKind) {
9925 E = E->IgnoreParens();
9926
9927 // The kinds of expressions that we have special-case logic here for
9928 // should be kept up to date with the special checks for those
9929 // expressions in Sema.
9930
9931 // alignof decl is always accepted, even if it doesn't make sense: we default
9932 // to 1 in those cases.
9933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9934 return Ctx.getDeclAlign(DRE->getDecl(),
9935 /*RefAsPointee*/ true);
9936
9937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9938 return Ctx.getDeclAlign(ME->getMemberDecl(),
9939 /*RefAsPointee*/ true);
9940
9941 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9942}
9943
9944static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9945 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9946 return Info.Ctx.getDeclAlign(VD);
9947 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9948 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9949 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9950}
9951
9952/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9953/// __builtin_is_aligned and __builtin_assume_aligned.
9954static bool getAlignmentArgument(const Expr *E, QualType ForType,
9955 EvalInfo &Info, APSInt &Alignment) {
9956 if (!EvaluateInteger(E, Alignment, Info))
9957 return false;
9958 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9959 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9960 return false;
9961 }
9962 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9963 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9964 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9965 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9966 << MaxValue << ForType << Alignment;
9967 return false;
9968 }
9969 // Ensure both alignment and source value have the same bit width so that we
9970 // don't assert when computing the resulting value.
9971 APSInt ExtAlignment =
9972 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9973 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9974 "Alignment should not be changed by ext/trunc");
9975 Alignment = ExtAlignment;
9976 assert(Alignment.getBitWidth() == SrcWidth);
9977 return true;
9978}
9979
9980// To be clear: this happily visits unsupported builtins. Better name welcomed.
9981bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9982 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9983 return true;
9984
9985 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
9986 return false;
9987
9988 Result.setInvalid(E);
9989 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9990 Result.addUnsizedArray(Info, E, PointeeTy);
9991 return true;
9992}
9993
9994bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9995 if (!IsConstantEvaluatedBuiltinCall(E))
9996 return visitNonBuiltinCallExpr(E);
9997 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9998}
9999
10000// Determine if T is a character type for which we guarantee that
10001// sizeof(T) == 1.
10003 return T->isCharType() || T->isChar8Type();
10004}
10005
10006bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10007 unsigned BuiltinOp) {
10008 if (IsOpaqueConstantCall(E))
10009 return Success(E);
10010
10011 switch (BuiltinOp) {
10012 case Builtin::BIaddressof:
10013 case Builtin::BI__addressof:
10014 case Builtin::BI__builtin_addressof:
10015 return evaluateLValue(E->getArg(0), Result);
10016 case Builtin::BI__builtin_assume_aligned: {
10017 // We need to be very careful here because: if the pointer does not have the
10018 // asserted alignment, then the behavior is undefined, and undefined
10019 // behavior is non-constant.
10020 if (!evaluatePointer(E->getArg(0), Result))
10021 return false;
10022
10023 LValue OffsetResult(Result);
10024 APSInt Alignment;
10025 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10026 Alignment))
10027 return false;
10028 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10029
10030 if (E->getNumArgs() > 2) {
10031 APSInt Offset;
10032 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10033 return false;
10034
10035 int64_t AdditionalOffset = -Offset.getZExtValue();
10036 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10037 }
10038
10039 // If there is a base object, then it must have the correct alignment.
10040 if (OffsetResult.Base) {
10041 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10042
10043 if (BaseAlignment < Align) {
10044 Result.Designator.setInvalid();
10045 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10046 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10047 return false;
10048 }
10049 }
10050
10051 // The offset must also have the correct alignment.
10052 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10053 Result.Designator.setInvalid();
10054
10055 (OffsetResult.Base
10056 ? CCEDiag(E->getArg(0),
10057 diag::note_constexpr_baa_insufficient_alignment)
10058 << 1
10059 : CCEDiag(E->getArg(0),
10060 diag::note_constexpr_baa_value_insufficient_alignment))
10061 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10062 return false;
10063 }
10064
10065 return true;
10066 }
10067 case Builtin::BI__builtin_align_up:
10068 case Builtin::BI__builtin_align_down: {
10069 if (!evaluatePointer(E->getArg(0), Result))
10070 return false;
10071 APSInt Alignment;
10072 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10073 Alignment))
10074 return false;
10075 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10076 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10077 // For align_up/align_down, we can return the same value if the alignment
10078 // is known to be greater or equal to the requested value.
10079 if (PtrAlign.getQuantity() >= Alignment)
10080 return true;
10081
10082 // The alignment could be greater than the minimum at run-time, so we cannot
10083 // infer much about the resulting pointer value. One case is possible:
10084 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10085 // can infer the correct index if the requested alignment is smaller than
10086 // the base alignment so we can perform the computation on the offset.
10087 if (BaseAlignment.getQuantity() >= Alignment) {
10088 assert(Alignment.getBitWidth() <= 64 &&
10089 "Cannot handle > 64-bit address-space");
10090 uint64_t Alignment64 = Alignment.getZExtValue();
10091 CharUnits NewOffset = CharUnits::fromQuantity(
10092 BuiltinOp == Builtin::BI__builtin_align_down
10093 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10094 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10095 Result.adjustOffset(NewOffset - Result.Offset);
10096 // TODO: diagnose out-of-bounds values/only allow for arrays?
10097 return true;
10098 }
10099 // Otherwise, we cannot constant-evaluate the result.
10100 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10101 << Alignment;
10102 return false;
10103 }
10104 case Builtin::BI__builtin_operator_new:
10105 return HandleOperatorNewCall(Info, E, Result);
10106 case Builtin::BI__builtin_launder:
10107 return evaluatePointer(E->getArg(0), Result);
10108 case Builtin::BIstrchr:
10109 case Builtin::BIwcschr:
10110 case Builtin::BImemchr:
10111 case Builtin::BIwmemchr:
10112 if (Info.getLangOpts().CPlusPlus11)
10113 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10114 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10115 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10116 else
10117 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10118 [[fallthrough]];
10119 case Builtin::BI__builtin_strchr:
10120 case Builtin::BI__builtin_wcschr:
10121 case Builtin::BI__builtin_memchr:
10122 case Builtin::BI__builtin_char_memchr:
10123 case Builtin::BI__builtin_wmemchr: {
10124 if (!Visit(E->getArg(0)))
10125 return false;
10126 APSInt Desired;
10127 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10128 return false;
10129 uint64_t MaxLength = uint64_t(-1);
10130 if (BuiltinOp != Builtin::BIstrchr &&
10131 BuiltinOp != Builtin::BIwcschr &&
10132 BuiltinOp != Builtin::BI__builtin_strchr &&
10133 BuiltinOp != Builtin::BI__builtin_wcschr) {
10134 APSInt N;
10135 if (!EvaluateInteger(E->getArg(2), N, Info))
10136 return false;
10137 MaxLength = N.getZExtValue();
10138 }
10139 // We cannot find the value if there are no candidates to match against.
10140 if (MaxLength == 0u)
10141 return ZeroInitialization(E);
10142 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10143 Result.Designator.Invalid)
10144 return false;
10145 QualType CharTy = Result.Designator.getType(Info.Ctx);
10146 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10147 BuiltinOp == Builtin::BI__builtin_memchr;
10148 assert(IsRawByte ||
10149 Info.Ctx.hasSameUnqualifiedType(
10150 CharTy, E->getArg(0)->getType()->getPointeeType()));
10151 // Pointers to const void may point to objects of incomplete type.
10152 if (IsRawByte && CharTy->isIncompleteType()) {
10153 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10154 return false;
10155 }
10156 // Give up on byte-oriented matching against multibyte elements.
10157 // FIXME: We can compare the bytes in the correct order.
10158 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10159 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10160 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10161 return false;
10162 }
10163 // Figure out what value we're actually looking for (after converting to
10164 // the corresponding unsigned type if necessary).
10165 uint64_t DesiredVal;
10166 bool StopAtNull = false;
10167 switch (BuiltinOp) {
10168 case Builtin::BIstrchr:
10169 case Builtin::BI__builtin_strchr:
10170 // strchr compares directly to the passed integer, and therefore
10171 // always fails if given an int that is not a char.
10172 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10173 E->getArg(1)->getType(),
10174 Desired),
10175 Desired))
10176 return ZeroInitialization(E);
10177 StopAtNull = true;
10178 [[fallthrough]];
10179 case Builtin::BImemchr:
10180 case Builtin::BI__builtin_memchr:
10181 case Builtin::BI__builtin_char_memchr:
10182 // memchr compares by converting both sides to unsigned char. That's also
10183 // correct for strchr if we get this far (to cope with plain char being
10184 // unsigned in the strchr case).
10185 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10186 break;
10187
10188 case Builtin::BIwcschr:
10189 case Builtin::BI__builtin_wcschr:
10190 StopAtNull = true;
10191 [[fallthrough]];
10192 case Builtin::BIwmemchr:
10193 case Builtin::BI__builtin_wmemchr:
10194 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10195 DesiredVal = Desired.getZExtValue();
10196 break;
10197 }
10198
10199 for (; MaxLength; --MaxLength) {
10200 APValue Char;
10201 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10202 !Char.isInt())
10203 return false;
10204 if (Char.getInt().getZExtValue() == DesiredVal)
10205 return true;
10206 if (StopAtNull && !Char.getInt())
10207 break;
10208 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10209 return false;
10210 }
10211 // Not found: return nullptr.
10212 return ZeroInitialization(E);
10213 }
10214
10215 case Builtin::BImemcpy:
10216 case Builtin::BImemmove:
10217 case Builtin::BIwmemcpy:
10218 case Builtin::BIwmemmove:
10219 if (Info.getLangOpts().CPlusPlus11)
10220 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10221 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10222 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10223 else
10224 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10225 [[fallthrough]];
10226 case Builtin::BI__builtin_memcpy:
10227 case Builtin::BI__builtin_memmove:
10228 case Builtin::BI__builtin_wmemcpy:
10229 case Builtin::BI__builtin_wmemmove: {
10230 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10231 BuiltinOp == Builtin::BIwmemmove ||
10232 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10233 BuiltinOp == Builtin::BI__builtin_wmemmove;
10234 bool Move = BuiltinOp == Builtin::BImemmove ||
10235 BuiltinOp == Builtin::BIwmemmove ||
10236 BuiltinOp == Builtin::BI__builtin_memmove ||
10237 BuiltinOp == Builtin::BI__builtin_wmemmove;
10238
10239 // The result of mem* is the first argument.
10240 if (!Visit(E->getArg(0)))
10241 return false;
10242 LValue Dest = Result;
10243
10244 LValue Src;
10245 if (!EvaluatePointer(E->getArg(1), Src, Info))
10246 return false;
10247
10248 APSInt N;
10249 if (!EvaluateInteger(E->getArg(2), N, Info))
10250 return false;
10251 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10252
10253 // If the size is zero, we treat this as always being a valid no-op.
10254 // (Even if one of the src and dest pointers is null.)
10255 if (!N)
10256 return true;
10257
10258 // Otherwise, if either of the operands is null, we can't proceed. Don't
10259 // try to determine the type of the copied objects, because there aren't
10260 // any.
10261 if (!Src.Base || !Dest.Base) {
10262 APValue Val;
10263 (!Src.Base ? Src : Dest).moveInto(Val);
10264 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10265 << Move << WChar << !!Src.Base
10266 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10267 return false;
10268 }
10269 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10270 return false;
10271
10272 // We require that Src and Dest are both pointers to arrays of
10273 // trivially-copyable type. (For the wide version, the designator will be
10274 // invalid if the designated object is not a wchar_t.)
10275 QualType T = Dest.Designator.getType(Info.Ctx);
10276 QualType SrcT = Src.Designator.getType(Info.Ctx);
10277 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10278 // FIXME: Consider using our bit_cast implementation to support this.
10279 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10280 return false;
10281 }
10282 if (T->isIncompleteType()) {
10283 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10284 return false;
10285 }
10286 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10287 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10288 return false;
10289 }
10290
10291 // Figure out how many T's we're copying.
10292 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10293 if (TSize == 0)
10294 return false;
10295 if (!WChar) {
10296 uint64_t Remainder;
10297 llvm::APInt OrigN = N;
10298 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10299 if (Remainder) {
10300 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10301 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10302 << (unsigned)TSize;
10303 return false;
10304 }
10305 }
10306
10307 // Check that the copying will remain within the arrays, just so that we
10308 // can give a more meaningful diagnostic. This implicitly also checks that
10309 // N fits into 64 bits.
10310 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10311 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10312 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10313 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10314 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10315 << toString(N, 10, /*Signed*/false);
10316 return false;
10317 }
10318 uint64_t NElems = N.getZExtValue();
10319 uint64_t NBytes = NElems * TSize;
10320
10321 // Check for overlap.
10322 int Direction = 1;
10323 if (HasSameBase(Src, Dest)) {
10324 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10325 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10326 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10327 // Dest is inside the source region.
10328 if (!Move) {
10329 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10330 return false;
10331 }
10332 // For memmove and friends, copy backwards.
10333 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10334 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10335 return false;
10336 Direction = -1;
10337 } else if (!Move && SrcOffset >= DestOffset &&
10338 SrcOffset - DestOffset < NBytes) {
10339 // Src is inside the destination region for memcpy: invalid.
10340 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10341 return false;
10342 }
10343 }
10344
10345 while (true) {
10346 APValue Val;
10347 // FIXME: Set WantObjectRepresentation to true if we're copying a
10348 // char-like type?
10349 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10350 !handleAssignment(Info, E, Dest, T, Val))
10351 return false;
10352 // Do not iterate past the last element; if we're copying backwards, that
10353 // might take us off the start of the array.
10354 if (--NElems == 0)
10355 return true;
10356 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10357 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10358 return false;
10359 }
10360 }
10361
10362 default:
10363 return false;
10364 }
10365}
10366
10367static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10368 APValue &Result, const InitListExpr *ILE,
10369 QualType AllocType);
10370static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10371 APValue &Result,
10372 const CXXConstructExpr *CCE,
10373 QualType AllocType);
10374
10375bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10376 if (!Info.getLangOpts().CPlusPlus20)
10377 Info.CCEDiag(E, diag::note_constexpr_new);
10378
10379 // We cannot speculatively evaluate a delete expression.
10380 if (Info.SpeculativeEvaluationDepth)
10381 return false;
10382
10383 FunctionDecl *OperatorNew = E->getOperatorNew();
10384 QualType AllocType = E->getAllocatedType();
10385 QualType TargetType = AllocType;
10386
10387 bool IsNothrow = false;
10388 bool IsPlacement = false;
10389
10390 if (E->getNumPlacementArgs() == 1 &&
10391 E->getPlacementArg(0)->getType()->isNothrowT()) {
10392 // The only new-placement list we support is of the form (std::nothrow).
10393 //
10394 // FIXME: There is no restriction on this, but it's not clear that any
10395 // other form makes any sense. We get here for cases such as:
10396 //
10397 // new (std::align_val_t{N}) X(int)
10398 //
10399 // (which should presumably be valid only if N is a multiple of
10400 // alignof(int), and in any case can't be deallocated unless N is
10401 // alignof(X) and X has new-extended alignment).
10402 LValue Nothrow;
10403 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10404 return false;
10405 IsNothrow = true;
10406 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10407 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10408 (Info.CurrentCall->CanEvalMSConstexpr &&
10409 OperatorNew->hasAttr<MSConstexprAttr>())) {
10410 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10411 return false;
10412 if (Result.Designator.Invalid)
10413 return false;
10414 TargetType = E->getPlacementArg(0)->getType();
10415 IsPlacement = true;
10416 } else {
10417 Info.FFDiag(E, diag::note_constexpr_new_placement)
10418 << /*C++26 feature*/ 1 << E->getSourceRange();
10419 return false;
10420 }
10421 } else if (E->getNumPlacementArgs()) {
10422 Info.FFDiag(E, diag::note_constexpr_new_placement)
10423 << /*Unsupported*/ 0 << E->getSourceRange();
10424 return false;
10425 } else if (!OperatorNew
10426 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10427 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10428 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10429 return false;
10430 }
10431
10432 const Expr *Init = E->getInitializer();
10433 const InitListExpr *ResizedArrayILE = nullptr;
10434 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10435 bool ValueInit = false;
10436
10437 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10438 const Expr *Stripped = *ArraySize;
10439 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10440 Stripped = ICE->getSubExpr())
10441 if (ICE->getCastKind() != CK_NoOp &&
10442 ICE->getCastKind() != CK_IntegralCast)
10443 break;
10444
10445 llvm::APSInt ArrayBound;
10446 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10447 return false;
10448
10449 // C++ [expr.new]p9:
10450 // The expression is erroneous if:
10451 // -- [...] its value before converting to size_t [or] applying the
10452 // second standard conversion sequence is less than zero
10453 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10454 if (IsNothrow)
10455 return ZeroInitialization(E);
10456
10457 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10458 << ArrayBound << (*ArraySize)->getSourceRange();
10459 return false;
10460 }
10461
10462 // -- its value is such that the size of the allocated object would
10463 // exceed the implementation-defined limit
10464 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10466 Info.Ctx, AllocType, ArrayBound),
10467 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10468 if (IsNothrow)
10469 return ZeroInitialization(E);
10470 return false;
10471 }
10472
10473 // -- the new-initializer is a braced-init-list and the number of
10474 // array elements for which initializers are provided [...]
10475 // exceeds the number of elements to initialize
10476 if (!Init) {
10477 // No initialization is performed.
10478 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10480 ValueInit = true;
10481 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10482 ResizedArrayCCE = CCE;
10483 } else {
10484 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10485 assert(CAT && "unexpected type for array initializer");
10486
10487 unsigned Bits =
10488 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10489 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10490 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10491 if (InitBound.ugt(AllocBound)) {
10492 if (IsNothrow)
10493 return ZeroInitialization(E);
10494
10495 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10496 << toString(AllocBound, 10, /*Signed=*/false)
10497 << toString(InitBound, 10, /*Signed=*/false)
10498 << (*ArraySize)->getSourceRange();
10499 return false;
10500 }
10501
10502 // If the sizes differ, we must have an initializer list, and we need
10503 // special handling for this case when we initialize.
10504 if (InitBound != AllocBound)
10505 ResizedArrayILE = cast<InitListExpr>(Init);
10506 }
10507
10508 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10509 ArraySizeModifier::Normal, 0);
10510 } else {
10511 assert(!AllocType->isArrayType() &&
10512 "array allocation with non-array new");
10513 }
10514
10515 APValue *Val;
10516 if (IsPlacement) {
10518 struct FindObjectHandler {
10519 EvalInfo &Info;
10520 const Expr *E;
10521 QualType AllocType;
10522 const AccessKinds AccessKind;
10523 APValue *Value;
10524
10525 typedef bool result_type;
10526 bool failed() { return false; }
10527 bool checkConst(QualType QT) {
10528 if (QT.isConstQualified()) {
10529 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10530 return false;
10531 }
10532 return true;
10533 }
10534 bool found(APValue &Subobj, QualType SubobjType) {
10535 if (!checkConst(SubobjType))
10536 return false;
10537 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10538 // old name of the object to be used to name the new object.
10539 unsigned SubobjectSize = 1;
10540 unsigned AllocSize = 1;
10541 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10542 AllocSize = CAT->getZExtSize();
10543 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10544 SubobjectSize = CAT->getZExtSize();
10545 if (SubobjectSize < AllocSize ||
10546 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10547 Info.Ctx.getBaseElementType(AllocType))) {
10548 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10549 << SubobjType << AllocType;
10550 return false;
10551 }
10552 Value = &Subobj;
10553 return true;
10554 }
10555 bool found(APSInt &Value, QualType SubobjType) {
10556 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10557 return false;
10558 }
10559 bool found(APFloat &Value, QualType SubobjType) {
10560 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10561 return false;
10562 }
10563 } Handler = {Info, E, AllocType, AK, nullptr};
10564
10565 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10566 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10567 return false;
10568
10569 Val = Handler.Value;
10570
10571 // [basic.life]p1:
10572 // The lifetime of an object o of type T ends when [...] the storage
10573 // which the object occupies is [...] reused by an object that is not
10574 // nested within o (6.6.2).
10575 *Val = APValue();
10576 } else {
10577 // Perform the allocation and obtain a pointer to the resulting object.
10578 Val = Info.createHeapAlloc(E, AllocType, Result);
10579 if (!Val)
10580 return false;
10581 }
10582
10583 if (ValueInit) {
10584 ImplicitValueInitExpr VIE(AllocType);
10585 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10586 return false;
10587 } else if (ResizedArrayILE) {
10588 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10589 AllocType))
10590 return false;
10591 } else if (ResizedArrayCCE) {
10592 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10593 AllocType))
10594 return false;
10595 } else if (Init) {
10596 if (!EvaluateInPlace(*Val, Info, Result, Init))
10597 return false;
10598 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10599 return false;
10600 }
10601
10602 // Array new returns a pointer to the first element, not a pointer to the
10603 // array.
10604 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10605 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10606
10607 return true;
10608}
10609//===----------------------------------------------------------------------===//
10610// Member Pointer Evaluation
10611//===----------------------------------------------------------------------===//
10612
10613namespace {
10614class MemberPointerExprEvaluator
10615 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10616 MemberPtr &Result;
10617
10618 bool Success(const ValueDecl *D) {
10619 Result = MemberPtr(D);
10620 return true;
10621 }
10622public:
10623
10624 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10625 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10626
10627 bool Success(const APValue &V, const Expr *E) {
10628 Result.setFrom(V);
10629 return true;
10630 }
10631 bool ZeroInitialization(const Expr *E) {
10632 return Success((const ValueDecl*)nullptr);
10633 }
10634
10635 bool VisitCastExpr(const CastExpr *E);
10636 bool VisitUnaryAddrOf(const UnaryOperator *E);
10637};
10638} // end anonymous namespace
10639
10640static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10641 EvalInfo &Info) {
10642 assert(!E->isValueDependent());
10643 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10644 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10645}
10646
10647bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10648 switch (E->getCastKind()) {
10649 default:
10650 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10651
10652 case CK_NullToMemberPointer:
10653 VisitIgnoredValue(E->getSubExpr());
10654 return ZeroInitialization(E);
10655
10656 case CK_BaseToDerivedMemberPointer: {
10657 if (!Visit(E->getSubExpr()))
10658 return false;
10659 if (E->path_empty())
10660 return true;
10661 // Base-to-derived member pointer casts store the path in derived-to-base
10662 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10663 // the wrong end of the derived->base arc, so stagger the path by one class.
10664 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10665 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10666 PathI != PathE; ++PathI) {
10667 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10668 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10669 if (!Result.castToDerived(Derived))
10670 return Error(E);
10671 }
10672 if (!Result.castToDerived(E->getType()
10673 ->castAs<MemberPointerType>()
10674 ->getMostRecentCXXRecordDecl()))
10675 return Error(E);
10676 return true;
10677 }
10678
10679 case CK_DerivedToBaseMemberPointer:
10680 if (!Visit(E->getSubExpr()))
10681 return false;
10682 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10683 PathE = E->path_end(); PathI != PathE; ++PathI) {
10684 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10685 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10686 if (!Result.castToBase(Base))
10687 return Error(E);
10688 }
10689 return true;
10690 }
10691}
10692
10693bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10694 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10695 // member can be formed.
10696 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10697}
10698
10699//===----------------------------------------------------------------------===//
10700// Record Evaluation
10701//===----------------------------------------------------------------------===//
10702
10703namespace {
10704 class RecordExprEvaluator
10705 : public ExprEvaluatorBase<RecordExprEvaluator> {
10706 const LValue &This;
10707 APValue &Result;
10708 public:
10709
10710 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10711 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10712
10713 bool Success(const APValue &V, const Expr *E) {
10714 Result = V;
10715 return true;
10716 }
10717 bool ZeroInitialization(const Expr *E) {
10718 return ZeroInitialization(E, E->getType());
10719 }
10720 bool ZeroInitialization(const Expr *E, QualType T);
10721
10722 bool VisitCallExpr(const CallExpr *E) {
10723 return handleCallExpr(E, Result, &This);
10724 }
10725 bool VisitCastExpr(const CastExpr *E);
10726 bool VisitInitListExpr(const InitListExpr *E);
10727 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10728 return VisitCXXConstructExpr(E, E->getType());
10729 }
10730 bool VisitLambdaExpr(const LambdaExpr *E);
10731 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10732 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10733 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10734 bool VisitBinCmp(const BinaryOperator *E);
10735 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10736 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10737 ArrayRef<Expr *> Args);
10738 };
10739}
10740
10741/// Perform zero-initialization on an object of non-union class type.
10742/// C++11 [dcl.init]p5:
10743/// To zero-initialize an object or reference of type T means:
10744/// [...]
10745/// -- if T is a (possibly cv-qualified) non-union class type,
10746/// each non-static data member and each base-class subobject is
10747/// zero-initialized
10748static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10749 const RecordDecl *RD,
10750 const LValue &This, APValue &Result) {
10751 assert(!RD->isUnion() && "Expected non-union class type");
10752 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10753 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10754 std::distance(RD->field_begin(), RD->field_end()));
10755
10756 if (RD->isInvalidDecl()) return false;
10757 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10758
10759 if (CD) {
10760 unsigned Index = 0;
10762 End = CD->bases_end(); I != End; ++I, ++Index) {
10763 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10764 LValue Subobject = This;
10765 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10766 return false;
10767 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10768 Result.getStructBase(Index)))
10769 return false;
10770 }
10771 }
10772
10773 for (const auto *I : RD->fields()) {
10774 // -- if T is a reference type, no initialization is performed.
10775 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10776 continue;
10777
10778 LValue Subobject = This;
10779 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10780 return false;
10781
10782 ImplicitValueInitExpr VIE(I->getType());
10783 if (!EvaluateInPlace(
10784 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10785 return false;
10786 }
10787
10788 return true;
10789}
10790
10791bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10792 const auto *RD = T->castAsRecordDecl();
10793 if (RD->isInvalidDecl()) return false;
10794 if (RD->isUnion()) {
10795 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10796 // object's first non-static named data member is zero-initialized
10798 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10799 ++I;
10800 if (I == RD->field_end()) {
10801 Result = APValue((const FieldDecl*)nullptr);
10802 return true;
10803 }
10804
10805 LValue Subobject = This;
10806 if (!HandleLValueMember(Info, E, Subobject, *I))
10807 return false;
10808 Result = APValue(*I);
10809 ImplicitValueInitExpr VIE(I->getType());
10810 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10811 }
10812
10813 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10814 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10815 return false;
10816 }
10817
10818 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10819}
10820
10821bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10822 switch (E->getCastKind()) {
10823 default:
10824 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10825
10826 case CK_ConstructorConversion:
10827 return Visit(E->getSubExpr());
10828
10829 case CK_DerivedToBase:
10830 case CK_UncheckedDerivedToBase: {
10831 APValue DerivedObject;
10832 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10833 return false;
10834 if (!DerivedObject.isStruct())
10835 return Error(E->getSubExpr());
10836
10837 // Derived-to-base rvalue conversion: just slice off the derived part.
10838 APValue *Value = &DerivedObject;
10839 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10840 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10841 PathE = E->path_end(); PathI != PathE; ++PathI) {
10842 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10843 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10844 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10845 RD = Base;
10846 }
10847 Result = *Value;
10848 return true;
10849 }
10850 }
10851}
10852
10853bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10854 if (E->isTransparent())
10855 return Visit(E->getInit(0));
10856 return VisitCXXParenListOrInitListExpr(E, E->inits());
10857}
10858
10859bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10860 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10861 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10862 if (RD->isInvalidDecl()) return false;
10863 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10864 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10865
10866 EvalInfo::EvaluatingConstructorRAII EvalObj(
10867 Info,
10868 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10869 CXXRD && CXXRD->getNumBases());
10870
10871 if (RD->isUnion()) {
10872 const FieldDecl *Field;
10873 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10874 Field = ILE->getInitializedFieldInUnion();
10875 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10876 Field = PLIE->getInitializedFieldInUnion();
10877 } else {
10878 llvm_unreachable(
10879 "Expression is neither an init list nor a C++ paren list");
10880 }
10881
10882 Result = APValue(Field);
10883 if (!Field)
10884 return true;
10885
10886 // If the initializer list for a union does not contain any elements, the
10887 // first element of the union is value-initialized.
10888 // FIXME: The element should be initialized from an initializer list.
10889 // Is this difference ever observable for initializer lists which
10890 // we don't build?
10891 ImplicitValueInitExpr VIE(Field->getType());
10892 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10893
10894 LValue Subobject = This;
10895 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10896 return false;
10897
10898 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10899 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10900 isa<CXXDefaultInitExpr>(InitExpr));
10901
10902 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10903 if (Field->isBitField())
10904 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10905 Field);
10906 return true;
10907 }
10908
10909 return false;
10910 }
10911
10912 if (!Result.hasValue())
10913 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10914 std::distance(RD->field_begin(), RD->field_end()));
10915 unsigned ElementNo = 0;
10916 bool Success = true;
10917
10918 // Initialize base classes.
10919 if (CXXRD && CXXRD->getNumBases()) {
10920 for (const auto &Base : CXXRD->bases()) {
10921 assert(ElementNo < Args.size() && "missing init for base class");
10922 const Expr *Init = Args[ElementNo];
10923
10924 LValue Subobject = This;
10925 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10926 return false;
10927
10928 APValue &FieldVal = Result.getStructBase(ElementNo);
10929 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10930 if (!Info.noteFailure())
10931 return false;
10932 Success = false;
10933 }
10934 ++ElementNo;
10935 }
10936
10937 EvalObj.finishedConstructingBases();
10938 }
10939
10940 // Initialize members.
10941 for (const auto *Field : RD->fields()) {
10942 // Anonymous bit-fields are not considered members of the class for
10943 // purposes of aggregate initialization.
10944 if (Field->isUnnamedBitField())
10945 continue;
10946
10947 LValue Subobject = This;
10948
10949 bool HaveInit = ElementNo < Args.size();
10950
10951 // FIXME: Diagnostics here should point to the end of the initializer
10952 // list, not the start.
10953 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10954 Subobject, Field, &Layout))
10955 return false;
10956
10957 // Perform an implicit value-initialization for members beyond the end of
10958 // the initializer list.
10959 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10960 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10961
10962 if (Field->getType()->isIncompleteArrayType()) {
10963 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10964 if (!CAT->isZeroSize()) {
10965 // Bail out for now. This might sort of "work", but the rest of the
10966 // code isn't really prepared to handle it.
10967 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10968 return false;
10969 }
10970 }
10971 }
10972
10973 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10974 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10976
10977 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10978 if (Field->getType()->isReferenceType()) {
10979 LValue Result;
10981 FieldVal)) {
10982 if (!Info.noteFailure())
10983 return false;
10984 Success = false;
10985 }
10986 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10987 (Field->isBitField() &&
10988 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
10989 if (!Info.noteFailure())
10990 return false;
10991 Success = false;
10992 }
10993 }
10994
10995 EvalObj.finishedConstructingFields();
10996
10997 return Success;
10998}
10999
11000bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11001 QualType T) {
11002 // Note that E's type is not necessarily the type of our class here; we might
11003 // be initializing an array element instead.
11004 const CXXConstructorDecl *FD = E->getConstructor();
11005 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11006
11007 bool ZeroInit = E->requiresZeroInitialization();
11008 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11009 if (ZeroInit)
11010 return ZeroInitialization(E, T);
11011
11013 }
11014
11015 const FunctionDecl *Definition = nullptr;
11016 auto Body = FD->getBody(Definition);
11017
11018 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11019 return false;
11020
11021 // Avoid materializing a temporary for an elidable copy/move constructor.
11022 if (E->isElidable() && !ZeroInit) {
11023 // FIXME: This only handles the simplest case, where the source object
11024 // is passed directly as the first argument to the constructor.
11025 // This should also handle stepping though implicit casts and
11026 // and conversion sequences which involve two steps, with a
11027 // conversion operator followed by a converting constructor.
11028 const Expr *SrcObj = E->getArg(0);
11029 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11030 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11031 if (const MaterializeTemporaryExpr *ME =
11032 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11033 return Visit(ME->getSubExpr());
11034 }
11035
11036 if (ZeroInit && !ZeroInitialization(E, T))
11037 return false;
11038
11039 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11040 return HandleConstructorCall(E, This, Args,
11042 Result);
11043}
11044
11045bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11046 const CXXInheritedCtorInitExpr *E) {
11047 if (!Info.CurrentCall) {
11048 assert(Info.checkingPotentialConstantExpression());
11049 return false;
11050 }
11051
11052 const CXXConstructorDecl *FD = E->getConstructor();
11053 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11054 return false;
11055
11056 const FunctionDecl *Definition = nullptr;
11057 auto Body = FD->getBody(Definition);
11058
11059 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11060 return false;
11061
11062 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11064 Result);
11065}
11066
11067bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11068 const CXXStdInitializerListExpr *E) {
11069 const ConstantArrayType *ArrayType =
11070 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11071
11072 LValue Array;
11073 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11074 return false;
11075
11076 assert(ArrayType && "unexpected type for array initializer");
11077
11078 // Get a pointer to the first element of the array.
11079 Array.addArray(Info, E, ArrayType);
11080
11081 // FIXME: What if the initializer_list type has base classes, etc?
11082 Result = APValue(APValue::UninitStruct(), 0, 2);
11083 Array.moveInto(Result.getStructField(0));
11084
11085 auto *Record = E->getType()->castAsRecordDecl();
11086 RecordDecl::field_iterator Field = Record->field_begin();
11087 assert(Field != Record->field_end() &&
11088 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11089 ArrayType->getElementType()) &&
11090 "Expected std::initializer_list first field to be const E *");
11091 ++Field;
11092 assert(Field != Record->field_end() &&
11093 "Expected std::initializer_list to have two fields");
11094
11095 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11096 // Length.
11097 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11098 } else {
11099 // End pointer.
11100 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11101 ArrayType->getElementType()) &&
11102 "Expected std::initializer_list second field to be const E *");
11103 if (!HandleLValueArrayAdjustment(Info, E, Array,
11104 ArrayType->getElementType(),
11105 ArrayType->getZExtSize()))
11106 return false;
11107 Array.moveInto(Result.getStructField(1));
11108 }
11109
11110 assert(++Field == Record->field_end() &&
11111 "Expected std::initializer_list to only have two fields");
11112
11113 return true;
11114}
11115
11116bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11117 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11118 if (ClosureClass->isInvalidDecl())
11119 return false;
11120
11121 const size_t NumFields =
11122 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11123
11124 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11125 E->capture_init_end()) &&
11126 "The number of lambda capture initializers should equal the number of "
11127 "fields within the closure type");
11128
11129 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11130 // Iterate through all the lambda's closure object's fields and initialize
11131 // them.
11132 auto *CaptureInitIt = E->capture_init_begin();
11133 bool Success = true;
11134 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11135 for (const auto *Field : ClosureClass->fields()) {
11136 assert(CaptureInitIt != E->capture_init_end());
11137 // Get the initializer for this field
11138 Expr *const CurFieldInit = *CaptureInitIt++;
11139
11140 // If there is no initializer, either this is a VLA or an error has
11141 // occurred.
11142 if (!CurFieldInit || CurFieldInit->containsErrors())
11143 return Error(E);
11144
11145 LValue Subobject = This;
11146
11147 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11148 return false;
11149
11150 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11151 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11152 if (!Info.keepEvaluatingAfterFailure())
11153 return false;
11154 Success = false;
11155 }
11156 }
11157 return Success;
11158}
11159
11160static bool EvaluateRecord(const Expr *E, const LValue &This,
11161 APValue &Result, EvalInfo &Info) {
11162 assert(!E->isValueDependent());
11163 assert(E->isPRValue() && E->getType()->isRecordType() &&
11164 "can't evaluate expression as a record rvalue");
11165 return RecordExprEvaluator(Info, This, Result).Visit(E);
11166}
11167
11168//===----------------------------------------------------------------------===//
11169// Temporary Evaluation
11170//
11171// Temporaries are represented in the AST as rvalues, but generally behave like
11172// lvalues. The full-object of which the temporary is a subobject is implicitly
11173// materialized so that a reference can bind to it.
11174//===----------------------------------------------------------------------===//
11175namespace {
11176class TemporaryExprEvaluator
11177 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11178public:
11179 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11180 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11181
11182 /// Visit an expression which constructs the value of this temporary.
11183 bool VisitConstructExpr(const Expr *E) {
11184 APValue &Value = Info.CurrentCall->createTemporary(
11185 E, E->getType(), ScopeKind::FullExpression, Result);
11186 return EvaluateInPlace(Value, Info, Result, E);
11187 }
11188
11189 bool VisitCastExpr(const CastExpr *E) {
11190 switch (E->getCastKind()) {
11191 default:
11192 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11193
11194 case CK_ConstructorConversion:
11195 return VisitConstructExpr(E->getSubExpr());
11196 }
11197 }
11198 bool VisitInitListExpr(const InitListExpr *E) {
11199 return VisitConstructExpr(E);
11200 }
11201 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11202 return VisitConstructExpr(E);
11203 }
11204 bool VisitCallExpr(const CallExpr *E) {
11205 return VisitConstructExpr(E);
11206 }
11207 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11208 return VisitConstructExpr(E);
11209 }
11210 bool VisitLambdaExpr(const LambdaExpr *E) {
11211 return VisitConstructExpr(E);
11212 }
11213};
11214} // end anonymous namespace
11215
11216/// Evaluate an expression of record type as a temporary.
11217static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11218 assert(!E->isValueDependent());
11219 assert(E->isPRValue() && E->getType()->isRecordType());
11220 return TemporaryExprEvaluator(Info, Result).Visit(E);
11221}
11222
11223//===----------------------------------------------------------------------===//
11224// Vector Evaluation
11225//===----------------------------------------------------------------------===//
11226
11227namespace {
11228 class VectorExprEvaluator
11229 : public ExprEvaluatorBase<VectorExprEvaluator> {
11230 APValue &Result;
11231 public:
11232
11233 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11234 : ExprEvaluatorBaseTy(info), Result(Result) {}
11235
11236 bool Success(ArrayRef<APValue> V, const Expr *E) {
11237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11238 // FIXME: remove this APValue copy.
11239 Result = APValue(V.data(), V.size());
11240 return true;
11241 }
11242 bool Success(const APValue &V, const Expr *E) {
11243 assert(V.isVector());
11244 Result = V;
11245 return true;
11246 }
11247 bool ZeroInitialization(const Expr *E);
11248
11249 bool VisitUnaryReal(const UnaryOperator *E)
11250 { return Visit(E->getSubExpr()); }
11251 bool VisitCastExpr(const CastExpr* E);
11252 bool VisitInitListExpr(const InitListExpr *E);
11253 bool VisitUnaryImag(const UnaryOperator *E);
11254 bool VisitBinaryOperator(const BinaryOperator *E);
11255 bool VisitUnaryOperator(const UnaryOperator *E);
11256 bool VisitCallExpr(const CallExpr *E);
11257 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11258 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11259
11260 // FIXME: Missing: conditional operator (for GNU
11261 // conditional select), ExtVectorElementExpr
11262 };
11263} // end anonymous namespace
11264
11265static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11266 assert(E->isPRValue() && E->getType()->isVectorType() &&
11267 "not a vector prvalue");
11268 return VectorExprEvaluator(Info, Result).Visit(E);
11269}
11270
11271static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11272 assert(Val.isVector() && "expected vector APValue");
11273 unsigned NumElts = Val.getVectorLength();
11274
11275 // Each element is one bit, so create an integer with NumElts bits.
11276 llvm::APInt Result(NumElts, 0);
11277
11278 for (unsigned I = 0; I < NumElts; ++I) {
11279 const APValue &Elt = Val.getVectorElt(I);
11280 assert(Elt.isInt() && "expected integer element in bool vector");
11281
11282 if (Elt.getInt().getBoolValue())
11283 Result.setBit(I);
11284 }
11285
11286 return Result;
11287}
11288
11289bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11290 const VectorType *VTy = E->getType()->castAs<VectorType>();
11291 unsigned NElts = VTy->getNumElements();
11292
11293 const Expr *SE = E->getSubExpr();
11294 QualType SETy = SE->getType();
11295
11296 switch (E->getCastKind()) {
11297 case CK_VectorSplat: {
11298 APValue Val = APValue();
11299 if (SETy->isIntegerType()) {
11300 APSInt IntResult;
11301 if (!EvaluateInteger(SE, IntResult, Info))
11302 return false;
11303 Val = APValue(std::move(IntResult));
11304 } else if (SETy->isRealFloatingType()) {
11305 APFloat FloatResult(0.0);
11306 if (!EvaluateFloat(SE, FloatResult, Info))
11307 return false;
11308 Val = APValue(std::move(FloatResult));
11309 } else {
11310 return Error(E);
11311 }
11312
11313 // Splat and create vector APValue.
11314 SmallVector<APValue, 4> Elts(NElts, Val);
11315 return Success(Elts, E);
11316 }
11317 case CK_BitCast: {
11318 APValue SVal;
11319 if (!Evaluate(SVal, Info, SE))
11320 return false;
11321
11322 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11323 // Give up if the input isn't an int, float, or vector. For example, we
11324 // reject "(v4i16)(intptr_t)&a".
11325 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11326 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11327 << Info.Ctx.getLangOpts().CPlusPlus;
11328 return false;
11329 }
11330
11331 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11332 return false;
11333
11334 return true;
11335 }
11336 case CK_HLSLVectorTruncation: {
11337 APValue Val;
11338 SmallVector<APValue, 4> Elements;
11339 if (!EvaluateVector(SE, Val, Info))
11340 return Error(E);
11341 for (unsigned I = 0; I < NElts; I++)
11342 Elements.push_back(Val.getVectorElt(I));
11343 return Success(Elements, E);
11344 }
11345 default:
11346 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11347 }
11348}
11349
11350bool
11351VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11352 const VectorType *VT = E->getType()->castAs<VectorType>();
11353 unsigned NumInits = E->getNumInits();
11354 unsigned NumElements = VT->getNumElements();
11355
11356 QualType EltTy = VT->getElementType();
11357 SmallVector<APValue, 4> Elements;
11358
11359 // MFloat8 type doesn't have constants and thus constant folding
11360 // is impossible.
11361 if (EltTy->isMFloat8Type())
11362 return false;
11363
11364 // The number of initializers can be less than the number of
11365 // vector elements. For OpenCL, this can be due to nested vector
11366 // initialization. For GCC compatibility, missing trailing elements
11367 // should be initialized with zeroes.
11368 unsigned CountInits = 0, CountElts = 0;
11369 while (CountElts < NumElements) {
11370 // Handle nested vector initialization.
11371 if (CountInits < NumInits
11372 && E->getInit(CountInits)->getType()->isVectorType()) {
11373 APValue v;
11374 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11375 return Error(E);
11376 unsigned vlen = v.getVectorLength();
11377 for (unsigned j = 0; j < vlen; j++)
11378 Elements.push_back(v.getVectorElt(j));
11379 CountElts += vlen;
11380 } else if (EltTy->isIntegerType()) {
11381 llvm::APSInt sInt(32);
11382 if (CountInits < NumInits) {
11383 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11384 return false;
11385 } else // trailing integer zero.
11386 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11387 Elements.push_back(APValue(sInt));
11388 CountElts++;
11389 } else {
11390 llvm::APFloat f(0.0);
11391 if (CountInits < NumInits) {
11392 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11393 return false;
11394 } else // trailing float zero.
11395 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11396 Elements.push_back(APValue(f));
11397 CountElts++;
11398 }
11399 CountInits++;
11400 }
11401 return Success(Elements, E);
11402}
11403
11404bool
11405VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11406 const auto *VT = E->getType()->castAs<VectorType>();
11407 QualType EltTy = VT->getElementType();
11408 APValue ZeroElement;
11409 if (EltTy->isIntegerType())
11410 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11411 else
11412 ZeroElement =
11413 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11414
11415 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11416 return Success(Elements, E);
11417}
11418
11419bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11420 VisitIgnoredValue(E->getSubExpr());
11421 return ZeroInitialization(E);
11422}
11423
11424bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11425 BinaryOperatorKind Op = E->getOpcode();
11426 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11427 "Operation not supported on vector types");
11428
11429 if (Op == BO_Comma)
11430 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11431
11432 Expr *LHS = E->getLHS();
11433 Expr *RHS = E->getRHS();
11434
11435 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11436 "Must both be vector types");
11437 // Checking JUST the types are the same would be fine, except shifts don't
11438 // need to have their types be the same (since you always shift by an int).
11439 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11440 E->getType()->castAs<VectorType>()->getNumElements() &&
11441 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11442 E->getType()->castAs<VectorType>()->getNumElements() &&
11443 "All operands must be the same size.");
11444
11445 APValue LHSValue;
11446 APValue RHSValue;
11447 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11448 if (!LHSOK && !Info.noteFailure())
11449 return false;
11450 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11451 return false;
11452
11453 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11454 return false;
11455
11456 return Success(LHSValue, E);
11457}
11458
11459static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11460 QualType ResultTy,
11462 APValue Elt) {
11463 switch (Op) {
11464 case UO_Plus:
11465 // Nothing to do here.
11466 return Elt;
11467 case UO_Minus:
11468 if (Elt.getKind() == APValue::Int) {
11469 Elt.getInt().negate();
11470 } else {
11471 assert(Elt.getKind() == APValue::Float &&
11472 "Vector can only be int or float type");
11473 Elt.getFloat().changeSign();
11474 }
11475 return Elt;
11476 case UO_Not:
11477 // This is only valid for integral types anyway, so we don't have to handle
11478 // float here.
11479 assert(Elt.getKind() == APValue::Int &&
11480 "Vector operator ~ can only be int");
11481 Elt.getInt().flipAllBits();
11482 return Elt;
11483 case UO_LNot: {
11484 if (Elt.getKind() == APValue::Int) {
11485 Elt.getInt() = !Elt.getInt();
11486 // operator ! on vectors returns -1 for 'truth', so negate it.
11487 Elt.getInt().negate();
11488 return Elt;
11489 }
11490 assert(Elt.getKind() == APValue::Float &&
11491 "Vector can only be int or float type");
11492 // Float types result in an int of the same size, but -1 for true, or 0 for
11493 // false.
11494 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11495 ResultTy->isUnsignedIntegerType()};
11496 if (Elt.getFloat().isZero())
11497 EltResult.setAllBits();
11498 else
11499 EltResult.clearAllBits();
11500
11501 return APValue{EltResult};
11502 }
11503 default:
11504 // FIXME: Implement the rest of the unary operators.
11505 return std::nullopt;
11506 }
11507}
11508
11509bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11510 Expr *SubExpr = E->getSubExpr();
11511 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11512 // This result element type differs in the case of negating a floating point
11513 // vector, since the result type is the a vector of the equivilant sized
11514 // integer.
11515 const QualType ResultEltTy = VD->getElementType();
11516 UnaryOperatorKind Op = E->getOpcode();
11517
11518 APValue SubExprValue;
11519 if (!Evaluate(SubExprValue, Info, SubExpr))
11520 return false;
11521
11522 // FIXME: This vector evaluator someday needs to be changed to be LValue
11523 // aware/keep LValue information around, rather than dealing with just vector
11524 // types directly. Until then, we cannot handle cases where the operand to
11525 // these unary operators is an LValue. The only case I've been able to see
11526 // cause this is operator++ assigning to a member expression (only valid in
11527 // altivec compilations) in C mode, so this shouldn't limit us too much.
11528 if (SubExprValue.isLValue())
11529 return false;
11530
11531 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11532 "Vector length doesn't match type?");
11533
11534 SmallVector<APValue, 4> ResultElements;
11535 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11536 std::optional<APValue> Elt = handleVectorUnaryOperator(
11537 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11538 if (!Elt)
11539 return false;
11540 ResultElements.push_back(*Elt);
11541 }
11542 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11543}
11544
11545static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11546 const Expr *E, QualType SourceTy,
11547 QualType DestTy, APValue const &Original,
11548 APValue &Result) {
11549 if (SourceTy->isIntegerType()) {
11550 if (DestTy->isRealFloatingType()) {
11551 Result = APValue(APFloat(0.0));
11552 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11553 DestTy, Result.getFloat());
11554 }
11555 if (DestTy->isIntegerType()) {
11556 Result = APValue(
11557 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11558 return true;
11559 }
11560 } else if (SourceTy->isRealFloatingType()) {
11561 if (DestTy->isRealFloatingType()) {
11562 Result = Original;
11563 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11564 Result.getFloat());
11565 }
11566 if (DestTy->isIntegerType()) {
11567 Result = APValue(APSInt());
11568 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11569 DestTy, Result.getInt());
11570 }
11571 }
11572
11573 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11574 << SourceTy << DestTy;
11575 return false;
11576}
11577
11578bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11579 if (!IsConstantEvaluatedBuiltinCall(E))
11580 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11581
11582 auto EvaluateBinOpExpr =
11583 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
11584 APValue SourceLHS, SourceRHS;
11585 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11586 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11587 return false;
11588
11589 auto *DestTy = E->getType()->castAs<VectorType>();
11590 QualType DestEltTy = DestTy->getElementType();
11591 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11592 unsigned SourceLen = SourceLHS.getVectorLength();
11593 SmallVector<APValue, 4> ResultElements;
11594 ResultElements.reserve(SourceLen);
11595
11596 if (SourceRHS.isInt()) {
11597 const APSInt &RHS = SourceRHS.getInt();
11598 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11599 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11600 ResultElements.push_back(
11601 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11602 }
11603 } else {
11604 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11605 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
11606 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
11607 ResultElements.push_back(
11608 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
11609 }
11610 }
11611 return Success(APValue(ResultElements.data(), SourceLen), E);
11612 };
11613
11614 switch (E->getBuiltinCallee()) {
11615 default:
11616 return false;
11617 case Builtin::BI__builtin_elementwise_popcount:
11618 case Builtin::BI__builtin_elementwise_bitreverse: {
11619 APValue Source;
11620 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11621 return false;
11622
11623 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11624 unsigned SourceLen = Source.getVectorLength();
11625 SmallVector<APValue, 4> ResultElements;
11626 ResultElements.reserve(SourceLen);
11627
11628 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11629 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11630 switch (E->getBuiltinCallee()) {
11631 case Builtin::BI__builtin_elementwise_popcount:
11632 ResultElements.push_back(APValue(
11633 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11634 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11635 break;
11636 case Builtin::BI__builtin_elementwise_bitreverse:
11637 ResultElements.push_back(
11638 APValue(APSInt(Elt.reverseBits(),
11639 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11640 break;
11641 }
11642 }
11643
11644 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11645 }
11646 case Builtin::BI__builtin_elementwise_abs: {
11647 APValue Source;
11648 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11649 return false;
11650
11651 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11652 unsigned SourceLen = Source.getVectorLength();
11653 SmallVector<APValue, 4> ResultElements;
11654 ResultElements.reserve(SourceLen);
11655
11656 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11657 APValue CurrentEle = Source.getVectorElt(EltNum);
11658 APValue Val = DestEltTy->isFloatingType()
11659 ? APValue(llvm::abs(CurrentEle.getFloat()))
11660 : APValue(APSInt(
11661 CurrentEle.getInt().abs(),
11662 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11663 ResultElements.push_back(Val);
11664 }
11665
11666 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11667 }
11668
11669 case Builtin::BI__builtin_elementwise_add_sat:
11670 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11671 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
11672 });
11673
11674 case Builtin::BI__builtin_elementwise_sub_sat:
11675 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11676 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
11677 });
11678
11679 case clang::X86::BI__builtin_ia32_pavgb128:
11680 case clang::X86::BI__builtin_ia32_pavgw128:
11681 case clang::X86::BI__builtin_ia32_pavgb256:
11682 case clang::X86::BI__builtin_ia32_pavgw256:
11683 case clang::X86::BI__builtin_ia32_pavgb512:
11684 case clang::X86::BI__builtin_ia32_pavgw512:
11685 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
11686
11687 case clang::X86::BI__builtin_ia32_pmulhuw128:
11688 case clang::X86::BI__builtin_ia32_pmulhuw256:
11689 case clang::X86::BI__builtin_ia32_pmulhuw512:
11690 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
11691
11692 case clang::X86::BI__builtin_ia32_pmulhw128:
11693 case clang::X86::BI__builtin_ia32_pmulhw256:
11694 case clang::X86::BI__builtin_ia32_pmulhw512:
11695 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
11696
11697 case clang::X86::BI__builtin_ia32_psllv2di:
11698 case clang::X86::BI__builtin_ia32_psllv4di:
11699 case clang::X86::BI__builtin_ia32_psllv4si:
11700 case clang::X86::BI__builtin_ia32_psllv8di:
11701 case clang::X86::BI__builtin_ia32_psllv8hi:
11702 case clang::X86::BI__builtin_ia32_psllv8si:
11703 case clang::X86::BI__builtin_ia32_psllv16hi:
11704 case clang::X86::BI__builtin_ia32_psllv16si:
11705 case clang::X86::BI__builtin_ia32_psllv32hi:
11706 case clang::X86::BI__builtin_ia32_psllwi128:
11707 case clang::X86::BI__builtin_ia32_pslldi128:
11708 case clang::X86::BI__builtin_ia32_psllqi128:
11709 case clang::X86::BI__builtin_ia32_psllwi256:
11710 case clang::X86::BI__builtin_ia32_pslldi256:
11711 case clang::X86::BI__builtin_ia32_psllqi256:
11712 case clang::X86::BI__builtin_ia32_psllwi512:
11713 case clang::X86::BI__builtin_ia32_pslldi512:
11714 case clang::X86::BI__builtin_ia32_psllqi512:
11715 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11716 if (RHS.uge(LHS.getBitWidth())) {
11717 return APInt::getZero(LHS.getBitWidth());
11718 }
11719 return LHS.shl(RHS.getZExtValue());
11720 });
11721
11722 case clang::X86::BI__builtin_ia32_psrav4si:
11723 case clang::X86::BI__builtin_ia32_psrav8di:
11724 case clang::X86::BI__builtin_ia32_psrav8hi:
11725 case clang::X86::BI__builtin_ia32_psrav8si:
11726 case clang::X86::BI__builtin_ia32_psrav16hi:
11727 case clang::X86::BI__builtin_ia32_psrav16si:
11728 case clang::X86::BI__builtin_ia32_psrav32hi:
11729 case clang::X86::BI__builtin_ia32_psravq128:
11730 case clang::X86::BI__builtin_ia32_psravq256:
11731 case clang::X86::BI__builtin_ia32_psrawi128:
11732 case clang::X86::BI__builtin_ia32_psradi128:
11733 case clang::X86::BI__builtin_ia32_psraqi128:
11734 case clang::X86::BI__builtin_ia32_psrawi256:
11735 case clang::X86::BI__builtin_ia32_psradi256:
11736 case clang::X86::BI__builtin_ia32_psraqi256:
11737 case clang::X86::BI__builtin_ia32_psrawi512:
11738 case clang::X86::BI__builtin_ia32_psradi512:
11739 case clang::X86::BI__builtin_ia32_psraqi512:
11740 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11741 if (RHS.uge(LHS.getBitWidth())) {
11742 return LHS.ashr(LHS.getBitWidth() - 1);
11743 }
11744 return LHS.ashr(RHS.getZExtValue());
11745 });
11746
11747 case clang::X86::BI__builtin_ia32_psrlv2di:
11748 case clang::X86::BI__builtin_ia32_psrlv4di:
11749 case clang::X86::BI__builtin_ia32_psrlv4si:
11750 case clang::X86::BI__builtin_ia32_psrlv8di:
11751 case clang::X86::BI__builtin_ia32_psrlv8hi:
11752 case clang::X86::BI__builtin_ia32_psrlv8si:
11753 case clang::X86::BI__builtin_ia32_psrlv16hi:
11754 case clang::X86::BI__builtin_ia32_psrlv16si:
11755 case clang::X86::BI__builtin_ia32_psrlv32hi:
11756 case clang::X86::BI__builtin_ia32_psrlwi128:
11757 case clang::X86::BI__builtin_ia32_psrldi128:
11758 case clang::X86::BI__builtin_ia32_psrlqi128:
11759 case clang::X86::BI__builtin_ia32_psrlwi256:
11760 case clang::X86::BI__builtin_ia32_psrldi256:
11761 case clang::X86::BI__builtin_ia32_psrlqi256:
11762 case clang::X86::BI__builtin_ia32_psrlwi512:
11763 case clang::X86::BI__builtin_ia32_psrldi512:
11764 case clang::X86::BI__builtin_ia32_psrlqi512:
11765 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
11766 if (RHS.uge(LHS.getBitWidth())) {
11767 return APInt::getZero(LHS.getBitWidth());
11768 }
11769 return LHS.lshr(RHS.getZExtValue());
11770 });
11771
11772 case clang::X86::BI__builtin_ia32_pmuldq128:
11773 case clang::X86::BI__builtin_ia32_pmuldq256:
11774 case clang::X86::BI__builtin_ia32_pmuldq512:
11775 case clang::X86::BI__builtin_ia32_pmuludq128:
11776 case clang::X86::BI__builtin_ia32_pmuludq256:
11777 case clang::X86::BI__builtin_ia32_pmuludq512: {
11778 APValue SourceLHS, SourceRHS;
11779 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11780 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11781 return false;
11782
11783 unsigned SourceLen = SourceLHS.getVectorLength();
11784 SmallVector<APValue, 4> ResultElements;
11785 ResultElements.reserve(SourceLen / 2);
11786
11787 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11788 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11789 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11790
11791 switch (E->getBuiltinCallee()) {
11792 case clang::X86::BI__builtin_ia32_pmuludq128:
11793 case clang::X86::BI__builtin_ia32_pmuludq256:
11794 case clang::X86::BI__builtin_ia32_pmuludq512:
11795 ResultElements.push_back(
11796 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
11797 break;
11798 case clang::X86::BI__builtin_ia32_pmuldq128:
11799 case clang::X86::BI__builtin_ia32_pmuldq256:
11800 case clang::X86::BI__builtin_ia32_pmuldq512:
11801 ResultElements.push_back(
11802 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
11803 break;
11804 }
11805 }
11806
11807 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11808 }
11809
11810 case clang::X86::BI__builtin_ia32_vprotbi:
11811 case clang::X86::BI__builtin_ia32_vprotdi:
11812 case clang::X86::BI__builtin_ia32_vprotqi:
11813 case clang::X86::BI__builtin_ia32_vprotwi:
11814 case clang::X86::BI__builtin_ia32_prold128:
11815 case clang::X86::BI__builtin_ia32_prold256:
11816 case clang::X86::BI__builtin_ia32_prold512:
11817 case clang::X86::BI__builtin_ia32_prolq128:
11818 case clang::X86::BI__builtin_ia32_prolq256:
11819 case clang::X86::BI__builtin_ia32_prolq512:
11820 return EvaluateBinOpExpr(
11821 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
11822
11823 case clang::X86::BI__builtin_ia32_prord128:
11824 case clang::X86::BI__builtin_ia32_prord256:
11825 case clang::X86::BI__builtin_ia32_prord512:
11826 case clang::X86::BI__builtin_ia32_prorq128:
11827 case clang::X86::BI__builtin_ia32_prorq256:
11828 case clang::X86::BI__builtin_ia32_prorq512:
11829 return EvaluateBinOpExpr(
11830 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
11831
11832 case Builtin::BI__builtin_elementwise_max:
11833 case Builtin::BI__builtin_elementwise_min: {
11834 APValue SourceLHS, SourceRHS;
11835 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11836 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11837 return false;
11838
11839 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11840
11841 if (!DestEltTy->isIntegerType())
11842 return false;
11843
11844 unsigned SourceLen = SourceLHS.getVectorLength();
11845 SmallVector<APValue, 4> ResultElements;
11846 ResultElements.reserve(SourceLen);
11847
11848 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11849 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11850 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11851 switch (E->getBuiltinCallee()) {
11852 case Builtin::BI__builtin_elementwise_max:
11853 ResultElements.push_back(
11854 APValue(APSInt(std::max(LHS, RHS),
11855 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11856 break;
11857 case Builtin::BI__builtin_elementwise_min:
11858 ResultElements.push_back(
11859 APValue(APSInt(std::min(LHS, RHS),
11860 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11861 break;
11862 }
11863 }
11864
11865 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11866 }
11867 case X86::BI__builtin_ia32_vpshldd128:
11868 case X86::BI__builtin_ia32_vpshldd256:
11869 case X86::BI__builtin_ia32_vpshldd512:
11870 case X86::BI__builtin_ia32_vpshldq128:
11871 case X86::BI__builtin_ia32_vpshldq256:
11872 case X86::BI__builtin_ia32_vpshldq512:
11873 case X86::BI__builtin_ia32_vpshldw128:
11874 case X86::BI__builtin_ia32_vpshldw256:
11875 case X86::BI__builtin_ia32_vpshldw512: {
11876 APValue SourceHi, SourceLo, SourceAmt;
11877 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
11878 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
11879 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
11880 return false;
11881
11882 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11883 unsigned SourceLen = SourceHi.getVectorLength();
11884 SmallVector<APValue, 32> ResultElements;
11885 ResultElements.reserve(SourceLen);
11886
11887 APInt Amt = SourceAmt.getInt();
11888 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11889 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
11890 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
11891 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
11892 ResultElements.push_back(
11894 }
11895
11896 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11897 }
11898 case X86::BI__builtin_ia32_vpshrdd128:
11899 case X86::BI__builtin_ia32_vpshrdd256:
11900 case X86::BI__builtin_ia32_vpshrdd512:
11901 case X86::BI__builtin_ia32_vpshrdq128:
11902 case X86::BI__builtin_ia32_vpshrdq256:
11903 case X86::BI__builtin_ia32_vpshrdq512:
11904 case X86::BI__builtin_ia32_vpshrdw128:
11905 case X86::BI__builtin_ia32_vpshrdw256:
11906 case X86::BI__builtin_ia32_vpshrdw512: {
11907 // NOTE: Reversed Hi/Lo operands.
11908 APValue SourceHi, SourceLo, SourceAmt;
11909 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
11910 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
11911 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
11912 return false;
11913
11914 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11915 unsigned SourceLen = SourceHi.getVectorLength();
11916 SmallVector<APValue, 32> ResultElements;
11917 ResultElements.reserve(SourceLen);
11918
11919 APInt Amt = SourceAmt.getInt();
11920 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11921 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
11922 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
11923 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
11924 ResultElements.push_back(
11926 }
11927
11928 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11929 }
11930 case X86::BI__builtin_ia32_blendpd:
11931 case X86::BI__builtin_ia32_blendpd256:
11932 case X86::BI__builtin_ia32_blendps:
11933 case X86::BI__builtin_ia32_blendps256:
11934 case X86::BI__builtin_ia32_pblendw128:
11935 case X86::BI__builtin_ia32_pblendw256:
11936 case X86::BI__builtin_ia32_pblendd128:
11937 case X86::BI__builtin_ia32_pblendd256: {
11938 APValue SourceF, SourceT, SourceC;
11939 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
11940 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
11941 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
11942 return false;
11943
11944 const APInt &C = SourceC.getInt();
11945 unsigned SourceLen = SourceF.getVectorLength();
11946 SmallVector<APValue, 32> ResultElements;
11947 ResultElements.reserve(SourceLen);
11948 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
11949 const APValue &F = SourceF.getVectorElt(EltNum);
11950 const APValue &T = SourceT.getVectorElt(EltNum);
11951 ResultElements.push_back(C[EltNum % 8] ? T : F);
11952 }
11953
11954 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11955 }
11956
11957 case X86::BI__builtin_ia32_blendvpd:
11958 case X86::BI__builtin_ia32_blendvpd256:
11959 case X86::BI__builtin_ia32_blendvps:
11960 case X86::BI__builtin_ia32_blendvps256:
11961 case X86::BI__builtin_ia32_pblendvb128:
11962 case X86::BI__builtin_ia32_pblendvb256: {
11963 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
11964 APValue SourceF, SourceT, SourceC;
11965 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
11966 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
11967 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
11968 return false;
11969
11970 unsigned SourceLen = SourceF.getVectorLength();
11971 SmallVector<APValue, 32> ResultElements;
11972 ResultElements.reserve(SourceLen);
11973
11974 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11975 const APValue &F = SourceF.getVectorElt(EltNum);
11976 const APValue &T = SourceT.getVectorElt(EltNum);
11977 const APValue &C = SourceC.getVectorElt(EltNum);
11978 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
11979 ResultElements.push_back(M.isNegative() ? T : F);
11980 }
11981
11982 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11983 }
11984 case X86::BI__builtin_ia32_selectb_128:
11985 case X86::BI__builtin_ia32_selectb_256:
11986 case X86::BI__builtin_ia32_selectb_512:
11987 case X86::BI__builtin_ia32_selectw_128:
11988 case X86::BI__builtin_ia32_selectw_256:
11989 case X86::BI__builtin_ia32_selectw_512:
11990 case X86::BI__builtin_ia32_selectd_128:
11991 case X86::BI__builtin_ia32_selectd_256:
11992 case X86::BI__builtin_ia32_selectd_512:
11993 case X86::BI__builtin_ia32_selectq_128:
11994 case X86::BI__builtin_ia32_selectq_256:
11995 case X86::BI__builtin_ia32_selectq_512:
11996 case X86::BI__builtin_ia32_selectph_128:
11997 case X86::BI__builtin_ia32_selectph_256:
11998 case X86::BI__builtin_ia32_selectph_512:
11999 case X86::BI__builtin_ia32_selectpbf_128:
12000 case X86::BI__builtin_ia32_selectpbf_256:
12001 case X86::BI__builtin_ia32_selectpbf_512:
12002 case X86::BI__builtin_ia32_selectps_128:
12003 case X86::BI__builtin_ia32_selectps_256:
12004 case X86::BI__builtin_ia32_selectps_512:
12005 case X86::BI__builtin_ia32_selectpd_128:
12006 case X86::BI__builtin_ia32_selectpd_256:
12007 case X86::BI__builtin_ia32_selectpd_512: {
12008 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12009 APValue SourceMask, SourceLHS, SourceRHS;
12010 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12011 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12012 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12013 return false;
12014
12015 APSInt Mask = SourceMask.getInt();
12016 unsigned SourceLen = SourceLHS.getVectorLength();
12017 SmallVector<APValue, 4> ResultElements;
12018 ResultElements.reserve(SourceLen);
12019
12020 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12021 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12022 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12023 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12024 }
12025
12026 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12027 }
12028 case Builtin::BI__builtin_elementwise_clzg:
12029 case Builtin::BI__builtin_elementwise_ctzg: {
12030 APValue SourceLHS;
12031 std::optional<APValue> Fallback;
12032 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
12033 return false;
12034 if (E->getNumArgs() > 1) {
12035 APValue FallbackTmp;
12036 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
12037 return false;
12038 Fallback = FallbackTmp;
12039 }
12040
12041 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12042 unsigned SourceLen = SourceLHS.getVectorLength();
12043 SmallVector<APValue, 4> ResultElements;
12044 ResultElements.reserve(SourceLen);
12045
12046 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12047 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12048 if (!LHS) {
12049 // Without a fallback, a zero element is undefined
12050 if (!Fallback) {
12051 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
12052 << /*IsTrailing=*/(E->getBuiltinCallee() ==
12053 Builtin::BI__builtin_elementwise_ctzg);
12054 return false;
12055 }
12056 ResultElements.push_back(Fallback->getVectorElt(EltNum));
12057 continue;
12058 }
12059 switch (E->getBuiltinCallee()) {
12060 case Builtin::BI__builtin_elementwise_clzg:
12061 ResultElements.push_back(APValue(
12062 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
12063 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12064 break;
12065 case Builtin::BI__builtin_elementwise_ctzg:
12066 ResultElements.push_back(APValue(
12067 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
12068 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12069 break;
12070 }
12071 }
12072
12073 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12074 }
12075
12076 case Builtin::BI__builtin_elementwise_fma: {
12077 APValue SourceX, SourceY, SourceZ;
12078 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
12079 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
12080 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
12081 return false;
12082
12083 unsigned SourceLen = SourceX.getVectorLength();
12084 SmallVector<APValue> ResultElements;
12085 ResultElements.reserve(SourceLen);
12086 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
12087 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12088 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
12089 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
12090 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
12091 APFloat Result(X);
12092 (void)Result.fusedMultiplyAdd(Y, Z, RM);
12093 ResultElements.push_back(APValue(Result));
12094 }
12095 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12096 }
12097
12098 case Builtin::BI__builtin_elementwise_fshl:
12099 case Builtin::BI__builtin_elementwise_fshr: {
12100 APValue SourceHi, SourceLo, SourceShift;
12101 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12102 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12103 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
12104 return false;
12105
12106 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12107 if (!DestEltTy->isIntegerType())
12108 return false;
12109
12110 unsigned SourceLen = SourceHi.getVectorLength();
12111 SmallVector<APValue> ResultElements;
12112 ResultElements.reserve(SourceLen);
12113 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12114 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
12115 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
12116 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
12117 switch (E->getBuiltinCallee()) {
12118 case Builtin::BI__builtin_elementwise_fshl:
12119 ResultElements.push_back(APValue(
12120 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
12121 break;
12122 case Builtin::BI__builtin_elementwise_fshr:
12123 ResultElements.push_back(APValue(
12124 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
12125 break;
12126 }
12127 }
12128
12129 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12130 }
12131
12132 case X86::BI__builtin_ia32_insertf32x4_256:
12133 case X86::BI__builtin_ia32_inserti32x4_256:
12134 case X86::BI__builtin_ia32_insertf64x2_256:
12135 case X86::BI__builtin_ia32_inserti64x2_256:
12136 case X86::BI__builtin_ia32_insertf32x4:
12137 case X86::BI__builtin_ia32_inserti32x4:
12138 case X86::BI__builtin_ia32_insertf64x2_512:
12139 case X86::BI__builtin_ia32_inserti64x2_512:
12140 case X86::BI__builtin_ia32_insertf32x8:
12141 case X86::BI__builtin_ia32_inserti32x8:
12142 case X86::BI__builtin_ia32_insertf64x4:
12143 case X86::BI__builtin_ia32_inserti64x4:
12144 case X86::BI__builtin_ia32_vinsertf128_ps256:
12145 case X86::BI__builtin_ia32_vinsertf128_pd256:
12146 case X86::BI__builtin_ia32_vinsertf128_si256:
12147 case X86::BI__builtin_ia32_insert128i256: {
12148 APValue SourceDst, SourceSub;
12149 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
12150 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
12151 return false;
12152
12153 APSInt Imm;
12154 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12155 return false;
12156
12157 assert(SourceDst.isVector() && SourceSub.isVector());
12158 unsigned DstLen = SourceDst.getVectorLength();
12159 unsigned SubLen = SourceSub.getVectorLength();
12160 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
12161 unsigned NumLanes = DstLen / SubLen;
12162 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
12163
12164 SmallVector<APValue, 16> ResultElements;
12165 ResultElements.reserve(DstLen);
12166
12167 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
12168 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
12169 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
12170 else
12171 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
12172 }
12173
12174 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12175 }
12176 }
12177}
12178
12179bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
12180 APValue Source;
12181 QualType SourceVecType = E->getSrcExpr()->getType();
12182 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
12183 return false;
12184
12185 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
12186 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
12187
12188 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12189
12190 auto SourceLen = Source.getVectorLength();
12191 SmallVector<APValue, 4> ResultElements;
12192 ResultElements.reserve(SourceLen);
12193 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12194 APValue Elt;
12195 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
12196 Source.getVectorElt(EltNum), Elt))
12197 return false;
12198 ResultElements.push_back(std::move(Elt));
12199 }
12200
12201 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12202}
12203
12204static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
12205 QualType ElemType, APValue const &VecVal1,
12206 APValue const &VecVal2, unsigned EltNum,
12207 APValue &Result) {
12208 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
12209 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
12210
12211 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
12212 int64_t index = IndexVal.getExtValue();
12213 // The spec says that -1 should be treated as undef for optimizations,
12214 // but in constexpr we'd have to produce an APValue::Indeterminate,
12215 // which is prohibited from being a top-level constant value. Emit a
12216 // diagnostic instead.
12217 if (index == -1) {
12218 Info.FFDiag(
12219 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
12220 << EltNum;
12221 return false;
12222 }
12223
12224 if (index < 0 ||
12225 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
12226 llvm_unreachable("Out of bounds shuffle index");
12227
12228 if (index >= TotalElementsInInputVector1)
12229 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
12230 else
12231 Result = VecVal1.getVectorElt(index);
12232 return true;
12233}
12234
12235bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
12236 // FIXME: Unary shuffle with mask not currently supported.
12237 if (E->getNumSubExprs() == 2)
12238 return Error(E);
12239 APValue VecVal1;
12240 const Expr *Vec1 = E->getExpr(0);
12241 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
12242 return false;
12243 APValue VecVal2;
12244 const Expr *Vec2 = E->getExpr(1);
12245 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
12246 return false;
12247
12248 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
12249 QualType DestElTy = DestVecTy->getElementType();
12250
12251 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
12252
12253 SmallVector<APValue, 4> ResultElements;
12254 ResultElements.reserve(TotalElementsInOutputVector);
12255 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
12256 APValue Elt;
12257 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
12258 return false;
12259 ResultElements.push_back(std::move(Elt));
12260 }
12261
12262 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12263}
12264
12265//===----------------------------------------------------------------------===//
12266// Array Evaluation
12267//===----------------------------------------------------------------------===//
12268
12269namespace {
12270 class ArrayExprEvaluator
12271 : public ExprEvaluatorBase<ArrayExprEvaluator> {
12272 const LValue &This;
12273 APValue &Result;
12274 public:
12275
12276 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
12277 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12278
12279 bool Success(const APValue &V, const Expr *E) {
12280 assert(V.isArray() && "expected array");
12281 Result = V;
12282 return true;
12283 }
12284
12285 bool ZeroInitialization(const Expr *E) {
12286 const ConstantArrayType *CAT =
12287 Info.Ctx.getAsConstantArrayType(E->getType());
12288 if (!CAT) {
12289 if (E->getType()->isIncompleteArrayType()) {
12290 // We can be asked to zero-initialize a flexible array member; this
12291 // is represented as an ImplicitValueInitExpr of incomplete array
12292 // type. In this case, the array has zero elements.
12293 Result = APValue(APValue::UninitArray(), 0, 0);
12294 return true;
12295 }
12296 // FIXME: We could handle VLAs here.
12297 return Error(E);
12298 }
12299
12300 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
12301 if (!Result.hasArrayFiller())
12302 return true;
12303
12304 // Zero-initialize all elements.
12305 LValue Subobject = This;
12306 Subobject.addArray(Info, E, CAT);
12307 ImplicitValueInitExpr VIE(CAT->getElementType());
12308 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
12309 }
12310
12311 bool VisitCallExpr(const CallExpr *E) {
12312 return handleCallExpr(E, Result, &This);
12313 }
12314 bool VisitInitListExpr(const InitListExpr *E,
12315 QualType AllocType = QualType());
12316 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
12317 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
12318 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
12319 const LValue &Subobject,
12320 APValue *Value, QualType Type);
12321 bool VisitStringLiteral(const StringLiteral *E,
12322 QualType AllocType = QualType()) {
12323 expandStringLiteral(Info, E, Result, AllocType);
12324 return true;
12325 }
12326 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
12327 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
12328 ArrayRef<Expr *> Args,
12329 const Expr *ArrayFiller,
12330 QualType AllocType = QualType());
12331 };
12332} // end anonymous namespace
12333
12334static bool EvaluateArray(const Expr *E, const LValue &This,
12335 APValue &Result, EvalInfo &Info) {
12336 assert(!E->isValueDependent());
12337 assert(E->isPRValue() && E->getType()->isArrayType() &&
12338 "not an array prvalue");
12339 return ArrayExprEvaluator(Info, This, Result).Visit(E);
12340}
12341
12342static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
12343 APValue &Result, const InitListExpr *ILE,
12344 QualType AllocType) {
12345 assert(!ILE->isValueDependent());
12346 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
12347 "not an array prvalue");
12348 return ArrayExprEvaluator(Info, This, Result)
12349 .VisitInitListExpr(ILE, AllocType);
12350}
12351
12352static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
12353 APValue &Result,
12354 const CXXConstructExpr *CCE,
12355 QualType AllocType) {
12356 assert(!CCE->isValueDependent());
12357 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
12358 "not an array prvalue");
12359 return ArrayExprEvaluator(Info, This, Result)
12360 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
12361}
12362
12363// Return true iff the given array filler may depend on the element index.
12364static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
12365 // For now, just allow non-class value-initialization and initialization
12366 // lists comprised of them.
12367 if (isa<ImplicitValueInitExpr>(FillerExpr))
12368 return false;
12369 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
12370 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
12371 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
12372 return true;
12373 }
12374
12375 if (ILE->hasArrayFiller() &&
12376 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
12377 return true;
12378
12379 return false;
12380 }
12381 return true;
12382}
12383
12384bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
12385 QualType AllocType) {
12386 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12387 AllocType.isNull() ? E->getType() : AllocType);
12388 if (!CAT)
12389 return Error(E);
12390
12391 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
12392 // an appropriately-typed string literal enclosed in braces.
12393 if (E->isStringLiteralInit()) {
12394 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
12395 // FIXME: Support ObjCEncodeExpr here once we support it in
12396 // ArrayExprEvaluator generally.
12397 if (!SL)
12398 return Error(E);
12399 return VisitStringLiteral(SL, AllocType);
12400 }
12401 // Any other transparent list init will need proper handling of the
12402 // AllocType; we can't just recurse to the inner initializer.
12403 assert(!E->isTransparent() &&
12404 "transparent array list initialization is not string literal init?");
12405
12406 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
12407 AllocType);
12408}
12409
12410bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
12411 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
12412 QualType AllocType) {
12413 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12414 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
12415
12416 bool Success = true;
12417
12418 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
12419 "zero-initialized array shouldn't have any initialized elts");
12420 APValue Filler;
12421 if (Result.isArray() && Result.hasArrayFiller())
12422 Filler = Result.getArrayFiller();
12423
12424 unsigned NumEltsToInit = Args.size();
12425 unsigned NumElts = CAT->getZExtSize();
12426
12427 // If the initializer might depend on the array index, run it for each
12428 // array element.
12429 if (NumEltsToInit != NumElts &&
12430 MaybeElementDependentArrayFiller(ArrayFiller)) {
12431 NumEltsToInit = NumElts;
12432 } else {
12433 for (auto *Init : Args) {
12434 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
12435 NumEltsToInit += EmbedS->getDataElementCount() - 1;
12436 }
12437 if (NumEltsToInit > NumElts)
12438 NumEltsToInit = NumElts;
12439 }
12440
12441 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
12442 << NumEltsToInit << ".\n");
12443
12444 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
12445
12446 // If the array was previously zero-initialized, preserve the
12447 // zero-initialized values.
12448 if (Filler.hasValue()) {
12449 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
12450 Result.getArrayInitializedElt(I) = Filler;
12451 if (Result.hasArrayFiller())
12452 Result.getArrayFiller() = Filler;
12453 }
12454
12455 LValue Subobject = This;
12456 Subobject.addArray(Info, ExprToVisit, CAT);
12457 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
12458 if (Init->isValueDependent())
12459 return EvaluateDependentExpr(Init, Info);
12460
12461 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
12462 Subobject, Init) ||
12463 !HandleLValueArrayAdjustment(Info, Init, Subobject,
12464 CAT->getElementType(), 1)) {
12465 if (!Info.noteFailure())
12466 return false;
12467 Success = false;
12468 }
12469 return true;
12470 };
12471 unsigned ArrayIndex = 0;
12472 QualType DestTy = CAT->getElementType();
12473 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
12474 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
12475 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
12476 if (ArrayIndex >= NumEltsToInit)
12477 break;
12478 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
12479 StringLiteral *SL = EmbedS->getDataStringLiteral();
12480 for (unsigned I = EmbedS->getStartingElementPos(),
12481 N = EmbedS->getDataElementCount();
12482 I != EmbedS->getStartingElementPos() + N; ++I) {
12483 Value = SL->getCodeUnit(I);
12484 if (DestTy->isIntegerType()) {
12485 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
12486 } else {
12487 assert(DestTy->isFloatingType() && "unexpected type");
12488 const FPOptions FPO =
12489 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12490 APFloat FValue(0.0);
12491 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
12492 DestTy, FValue))
12493 return false;
12494 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
12495 }
12496 ArrayIndex++;
12497 }
12498 } else {
12499 if (!Eval(Init, ArrayIndex))
12500 return false;
12501 ++ArrayIndex;
12502 }
12503 }
12504
12505 if (!Result.hasArrayFiller())
12506 return Success;
12507
12508 // If we get here, we have a trivial filler, which we can just evaluate
12509 // once and splat over the rest of the array elements.
12510 assert(ArrayFiller && "no array filler for incomplete init list");
12511 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
12512 ArrayFiller) &&
12513 Success;
12514}
12515
12516bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
12517 LValue CommonLV;
12518 if (E->getCommonExpr() &&
12519 !Evaluate(Info.CurrentCall->createTemporary(
12520 E->getCommonExpr(),
12521 getStorageType(Info.Ctx, E->getCommonExpr()),
12522 ScopeKind::FullExpression, CommonLV),
12523 Info, E->getCommonExpr()->getSourceExpr()))
12524 return false;
12525
12527
12528 uint64_t Elements = CAT->getZExtSize();
12529 Result = APValue(APValue::UninitArray(), Elements, Elements);
12530
12531 LValue Subobject = This;
12532 Subobject.addArray(Info, E, CAT);
12533
12534 bool Success = true;
12535 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
12536 // C++ [class.temporary]/5
12537 // There are four contexts in which temporaries are destroyed at a different
12538 // point than the end of the full-expression. [...] The second context is
12539 // when a copy constructor is called to copy an element of an array while
12540 // the entire array is copied [...]. In either case, if the constructor has
12541 // one or more default arguments, the destruction of every temporary created
12542 // in a default argument is sequenced before the construction of the next
12543 // array element, if any.
12544 FullExpressionRAII Scope(Info);
12545
12546 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
12547 Info, Subobject, E->getSubExpr()) ||
12548 !HandleLValueArrayAdjustment(Info, E, Subobject,
12549 CAT->getElementType(), 1)) {
12550 if (!Info.noteFailure())
12551 return false;
12552 Success = false;
12553 }
12554
12555 // Make sure we run the destructors too.
12556 Scope.destroy();
12557 }
12558
12559 return Success;
12560}
12561
12562bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
12563 return VisitCXXConstructExpr(E, This, &Result, E->getType());
12564}
12565
12566bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
12567 const LValue &Subobject,
12568 APValue *Value,
12569 QualType Type) {
12570 bool HadZeroInit = Value->hasValue();
12571
12572 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
12573 unsigned FinalSize = CAT->getZExtSize();
12574
12575 // Preserve the array filler if we had prior zero-initialization.
12576 APValue Filler =
12577 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
12578 : APValue();
12579
12580 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
12581 if (FinalSize == 0)
12582 return true;
12583
12584 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
12585 Info, E->getExprLoc(), E->getConstructor(),
12587 LValue ArrayElt = Subobject;
12588 ArrayElt.addArray(Info, E, CAT);
12589 // We do the whole initialization in two passes, first for just one element,
12590 // then for the whole array. It's possible we may find out we can't do const
12591 // init in the first pass, in which case we avoid allocating a potentially
12592 // large array. We don't do more passes because expanding array requires
12593 // copying the data, which is wasteful.
12594 for (const unsigned N : {1u, FinalSize}) {
12595 unsigned OldElts = Value->getArrayInitializedElts();
12596 if (OldElts == N)
12597 break;
12598
12599 // Expand the array to appropriate size.
12600 APValue NewValue(APValue::UninitArray(), N, FinalSize);
12601 for (unsigned I = 0; I < OldElts; ++I)
12602 NewValue.getArrayInitializedElt(I).swap(
12603 Value->getArrayInitializedElt(I));
12604 Value->swap(NewValue);
12605
12606 if (HadZeroInit)
12607 for (unsigned I = OldElts; I < N; ++I)
12608 Value->getArrayInitializedElt(I) = Filler;
12609
12610 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
12611 // If we have a trivial constructor, only evaluate it once and copy
12612 // the result into all the array elements.
12613 APValue &FirstResult = Value->getArrayInitializedElt(0);
12614 for (unsigned I = OldElts; I < FinalSize; ++I)
12615 Value->getArrayInitializedElt(I) = FirstResult;
12616 } else {
12617 for (unsigned I = OldElts; I < N; ++I) {
12618 if (!VisitCXXConstructExpr(E, ArrayElt,
12619 &Value->getArrayInitializedElt(I),
12620 CAT->getElementType()) ||
12621 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12622 CAT->getElementType(), 1))
12623 return false;
12624 // When checking for const initilization any diagnostic is considered
12625 // an error.
12626 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12627 !Info.keepEvaluatingAfterFailure())
12628 return false;
12629 }
12630 }
12631 }
12632
12633 return true;
12634 }
12635
12636 if (!Type->isRecordType())
12637 return Error(E);
12638
12639 return RecordExprEvaluator(Info, Subobject, *Value)
12640 .VisitCXXConstructExpr(E, Type);
12641}
12642
12643bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12644 const CXXParenListInitExpr *E) {
12645 assert(E->getType()->isConstantArrayType() &&
12646 "Expression result is not a constant array type");
12647
12648 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12649 E->getArrayFiller());
12650}
12651
12652//===----------------------------------------------------------------------===//
12653// Integer Evaluation
12654//
12655// As a GNU extension, we support casting pointers to sufficiently-wide integer
12656// types and back in constant folding. Integer values are thus represented
12657// either as an integer-valued APValue, or as an lvalue-valued APValue.
12658//===----------------------------------------------------------------------===//
12659
12660namespace {
12661class IntExprEvaluator
12662 : public ExprEvaluatorBase<IntExprEvaluator> {
12663 APValue &Result;
12664public:
12665 IntExprEvaluator(EvalInfo &info, APValue &result)
12666 : ExprEvaluatorBaseTy(info), Result(result) {}
12667
12668 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12669 assert(E->getType()->isIntegralOrEnumerationType() &&
12670 "Invalid evaluation result.");
12671 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12672 "Invalid evaluation result.");
12673 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12674 "Invalid evaluation result.");
12675 Result = APValue(SI);
12676 return true;
12677 }
12678 bool Success(const llvm::APSInt &SI, const Expr *E) {
12679 return Success(SI, E, Result);
12680 }
12681
12682 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
12683 assert(E->getType()->isIntegralOrEnumerationType() &&
12684 "Invalid evaluation result.");
12685 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12686 "Invalid evaluation result.");
12687 Result = APValue(APSInt(I));
12688 Result.getInt().setIsUnsigned(
12690 return true;
12691 }
12692 bool Success(const llvm::APInt &I, const Expr *E) {
12693 return Success(I, E, Result);
12694 }
12695
12696 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12697 assert(E->getType()->isIntegralOrEnumerationType() &&
12698 "Invalid evaluation result.");
12699 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
12700 return true;
12701 }
12702 bool Success(uint64_t Value, const Expr *E) {
12703 return Success(Value, E, Result);
12704 }
12705
12706 bool Success(CharUnits Size, const Expr *E) {
12707 return Success(Size.getQuantity(), E);
12708 }
12709
12710 bool Success(const APValue &V, const Expr *E) {
12711 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
12712 // pointer allow further evaluation of the value.
12713 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
12714 V.allowConstexprUnknown()) {
12715 Result = V;
12716 return true;
12717 }
12718 return Success(V.getInt(), E);
12719 }
12720
12721 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
12722
12723 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12724 const CallExpr *);
12725
12726 //===--------------------------------------------------------------------===//
12727 // Visitor Methods
12728 //===--------------------------------------------------------------------===//
12729
12730 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12731 return Success(E->getValue(), E);
12732 }
12733 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12734 return Success(E->getValue(), E);
12735 }
12736
12737 bool CheckReferencedDecl(const Expr *E, const Decl *D);
12738 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12739 if (CheckReferencedDecl(E, E->getDecl()))
12740 return true;
12741
12742 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12743 }
12744 bool VisitMemberExpr(const MemberExpr *E) {
12745 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12746 VisitIgnoredBaseExpression(E->getBase());
12747 return true;
12748 }
12749
12750 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12751 }
12752
12753 bool VisitCallExpr(const CallExpr *E);
12754 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12755 bool VisitBinaryOperator(const BinaryOperator *E);
12756 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12757 bool VisitUnaryOperator(const UnaryOperator *E);
12758
12759 bool VisitCastExpr(const CastExpr* E);
12760 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12761
12762 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12763 return Success(E->getValue(), E);
12764 }
12765
12766 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12767 return Success(E->getValue(), E);
12768 }
12769
12770 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12771 if (Info.ArrayInitIndex == uint64_t(-1)) {
12772 // We were asked to evaluate this subexpression independent of the
12773 // enclosing ArrayInitLoopExpr. We can't do that.
12774 Info.FFDiag(E);
12775 return false;
12776 }
12777 return Success(Info.ArrayInitIndex, E);
12778 }
12779
12780 // Note, GNU defines __null as an integer, not a pointer.
12781 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12782 return ZeroInitialization(E);
12783 }
12784
12785 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12786 if (E->isStoredAsBoolean())
12787 return Success(E->getBoolValue(), E);
12788 if (E->getAPValue().isAbsent())
12789 return false;
12790 assert(E->getAPValue().isInt() && "APValue type not supported");
12791 return Success(E->getAPValue().getInt(), E);
12792 }
12793
12794 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12795 return Success(E->getValue(), E);
12796 }
12797
12798 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12799 return Success(E->getValue(), E);
12800 }
12801
12802 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12803 // This should not be evaluated during constant expr evaluation, as it
12804 // should always be in an unevaluated context (the args list of a 'gang' or
12805 // 'tile' clause).
12806 return Error(E);
12807 }
12808
12809 bool VisitUnaryReal(const UnaryOperator *E);
12810 bool VisitUnaryImag(const UnaryOperator *E);
12811
12812 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12813 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12814 bool VisitSourceLocExpr(const SourceLocExpr *E);
12815 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12816 bool VisitRequiresExpr(const RequiresExpr *E);
12817 // FIXME: Missing: array subscript of vector, member of vector
12818};
12819
12820class FixedPointExprEvaluator
12821 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12822 APValue &Result;
12823
12824 public:
12825 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12826 : ExprEvaluatorBaseTy(info), Result(result) {}
12827
12828 bool Success(const llvm::APInt &I, const Expr *E) {
12829 return Success(
12830 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12831 }
12832
12833 bool Success(uint64_t Value, const Expr *E) {
12834 return Success(
12835 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12836 }
12837
12838 bool Success(const APValue &V, const Expr *E) {
12839 return Success(V.getFixedPoint(), E);
12840 }
12841
12842 bool Success(const APFixedPoint &V, const Expr *E) {
12843 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12844 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12845 "Invalid evaluation result.");
12846 Result = APValue(V);
12847 return true;
12848 }
12849
12850 bool ZeroInitialization(const Expr *E) {
12851 return Success(0, E);
12852 }
12853
12854 //===--------------------------------------------------------------------===//
12855 // Visitor Methods
12856 //===--------------------------------------------------------------------===//
12857
12858 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12859 return Success(E->getValue(), E);
12860 }
12861
12862 bool VisitCastExpr(const CastExpr *E);
12863 bool VisitUnaryOperator(const UnaryOperator *E);
12864 bool VisitBinaryOperator(const BinaryOperator *E);
12865};
12866} // end anonymous namespace
12867
12868/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12869/// produce either the integer value or a pointer.
12870///
12871/// GCC has a heinous extension which folds casts between pointer types and
12872/// pointer-sized integral types. We support this by allowing the evaluation of
12873/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12874/// Some simple arithmetic on such values is supported (they are treated much
12875/// like char*).
12876static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12877 EvalInfo &Info) {
12878 assert(!E->isValueDependent());
12879 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12880 return IntExprEvaluator(Info, Result).Visit(E);
12881}
12882
12883static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12884 assert(!E->isValueDependent());
12885 APValue Val;
12886 if (!EvaluateIntegerOrLValue(E, Val, Info))
12887 return false;
12888 if (!Val.isInt()) {
12889 // FIXME: It would be better to produce the diagnostic for casting
12890 // a pointer to an integer.
12891 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12892 return false;
12893 }
12894 Result = Val.getInt();
12895 return true;
12896}
12897
12898bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12900 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12901 return Success(Evaluated, E);
12902}
12903
12904static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12905 EvalInfo &Info) {
12906 assert(!E->isValueDependent());
12907 if (E->getType()->isFixedPointType()) {
12908 APValue Val;
12909 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12910 return false;
12911 if (!Val.isFixedPoint())
12912 return false;
12913
12914 Result = Val.getFixedPoint();
12915 return true;
12916 }
12917 return false;
12918}
12919
12920static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12921 EvalInfo &Info) {
12922 assert(!E->isValueDependent());
12923 if (E->getType()->isIntegerType()) {
12924 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12925 APSInt Val;
12926 if (!EvaluateInteger(E, Val, Info))
12927 return false;
12928 Result = APFixedPoint(Val, FXSema);
12929 return true;
12930 } else if (E->getType()->isFixedPointType()) {
12931 return EvaluateFixedPoint(E, Result, Info);
12932 }
12933 return false;
12934}
12935
12936/// Check whether the given declaration can be directly converted to an integral
12937/// rvalue. If not, no diagnostic is produced; there are other things we can
12938/// try.
12939bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12940 // Enums are integer constant exprs.
12941 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12942 // Check for signedness/width mismatches between E type and ECD value.
12943 bool SameSign = (ECD->getInitVal().isSigned()
12945 bool SameWidth = (ECD->getInitVal().getBitWidth()
12946 == Info.Ctx.getIntWidth(E->getType()));
12947 if (SameSign && SameWidth)
12948 return Success(ECD->getInitVal(), E);
12949 else {
12950 // Get rid of mismatch (otherwise Success assertions will fail)
12951 // by computing a new value matching the type of E.
12952 llvm::APSInt Val = ECD->getInitVal();
12953 if (!SameSign)
12954 Val.setIsSigned(!ECD->getInitVal().isSigned());
12955 if (!SameWidth)
12956 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12957 return Success(Val, E);
12958 }
12959 }
12960 return false;
12961}
12962
12963/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12964/// as GCC.
12966 const LangOptions &LangOpts) {
12967 assert(!T->isDependentType() && "unexpected dependent type");
12968
12969 QualType CanTy = T.getCanonicalType();
12970
12971 switch (CanTy->getTypeClass()) {
12972#define TYPE(ID, BASE)
12973#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12974#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12975#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12976#include "clang/AST/TypeNodes.inc"
12977 case Type::Auto:
12978 case Type::DeducedTemplateSpecialization:
12979 llvm_unreachable("unexpected non-canonical or dependent type");
12980
12981 case Type::Builtin:
12982 switch (cast<BuiltinType>(CanTy)->getKind()) {
12983#define BUILTIN_TYPE(ID, SINGLETON_ID)
12984#define SIGNED_TYPE(ID, SINGLETON_ID) \
12985 case BuiltinType::ID: return GCCTypeClass::Integer;
12986#define FLOATING_TYPE(ID, SINGLETON_ID) \
12987 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12988#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12989 case BuiltinType::ID: break;
12990#include "clang/AST/BuiltinTypes.def"
12991 case BuiltinType::Void:
12992 return GCCTypeClass::Void;
12993
12994 case BuiltinType::Bool:
12995 return GCCTypeClass::Bool;
12996
12997 case BuiltinType::Char_U:
12998 case BuiltinType::UChar:
12999 case BuiltinType::WChar_U:
13000 case BuiltinType::Char8:
13001 case BuiltinType::Char16:
13002 case BuiltinType::Char32:
13003 case BuiltinType::UShort:
13004 case BuiltinType::UInt:
13005 case BuiltinType::ULong:
13006 case BuiltinType::ULongLong:
13007 case BuiltinType::UInt128:
13008 return GCCTypeClass::Integer;
13009
13010 case BuiltinType::UShortAccum:
13011 case BuiltinType::UAccum:
13012 case BuiltinType::ULongAccum:
13013 case BuiltinType::UShortFract:
13014 case BuiltinType::UFract:
13015 case BuiltinType::ULongFract:
13016 case BuiltinType::SatUShortAccum:
13017 case BuiltinType::SatUAccum:
13018 case BuiltinType::SatULongAccum:
13019 case BuiltinType::SatUShortFract:
13020 case BuiltinType::SatUFract:
13021 case BuiltinType::SatULongFract:
13022 return GCCTypeClass::None;
13023
13024 case BuiltinType::NullPtr:
13025
13026 case BuiltinType::ObjCId:
13027 case BuiltinType::ObjCClass:
13028 case BuiltinType::ObjCSel:
13029#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
13030 case BuiltinType::Id:
13031#include "clang/Basic/OpenCLImageTypes.def"
13032#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
13033 case BuiltinType::Id:
13034#include "clang/Basic/OpenCLExtensionTypes.def"
13035 case BuiltinType::OCLSampler:
13036 case BuiltinType::OCLEvent:
13037 case BuiltinType::OCLClkEvent:
13038 case BuiltinType::OCLQueue:
13039 case BuiltinType::OCLReserveID:
13040#define SVE_TYPE(Name, Id, SingletonId) \
13041 case BuiltinType::Id:
13042#include "clang/Basic/AArch64ACLETypes.def"
13043#define PPC_VECTOR_TYPE(Name, Id, Size) \
13044 case BuiltinType::Id:
13045#include "clang/Basic/PPCTypes.def"
13046#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13047#include "clang/Basic/RISCVVTypes.def"
13048#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13049#include "clang/Basic/WebAssemblyReferenceTypes.def"
13050#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
13051#include "clang/Basic/AMDGPUTypes.def"
13052#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
13053#include "clang/Basic/HLSLIntangibleTypes.def"
13054 return GCCTypeClass::None;
13055
13056 case BuiltinType::Dependent:
13057 llvm_unreachable("unexpected dependent type");
13058 };
13059 llvm_unreachable("unexpected placeholder type");
13060
13061 case Type::Enum:
13062 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
13063
13064 case Type::Pointer:
13065 case Type::ConstantArray:
13066 case Type::VariableArray:
13067 case Type::IncompleteArray:
13068 case Type::FunctionNoProto:
13069 case Type::FunctionProto:
13070 case Type::ArrayParameter:
13071 return GCCTypeClass::Pointer;
13072
13073 case Type::MemberPointer:
13074 return CanTy->isMemberDataPointerType()
13077
13078 case Type::Complex:
13079 return GCCTypeClass::Complex;
13080
13081 case Type::Record:
13082 return CanTy->isUnionType() ? GCCTypeClass::Union
13084
13085 case Type::Atomic:
13086 // GCC classifies _Atomic T the same as T.
13088 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
13089
13090 case Type::Vector:
13091 case Type::ExtVector:
13092 return GCCTypeClass::Vector;
13093
13094 case Type::BlockPointer:
13095 case Type::ConstantMatrix:
13096 case Type::ObjCObject:
13097 case Type::ObjCInterface:
13098 case Type::ObjCObjectPointer:
13099 case Type::Pipe:
13100 case Type::HLSLAttributedResource:
13101 case Type::HLSLInlineSpirv:
13102 // Classify all other types that don't fit into the regular
13103 // classification the same way.
13104 return GCCTypeClass::None;
13105
13106 case Type::BitInt:
13107 return GCCTypeClass::BitInt;
13108
13109 case Type::LValueReference:
13110 case Type::RValueReference:
13111 llvm_unreachable("invalid type for expression");
13112 }
13113
13114 llvm_unreachable("unexpected type class");
13115}
13116
13117/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
13118/// as GCC.
13119static GCCTypeClass
13121 // If no argument was supplied, default to None. This isn't
13122 // ideal, however it is what gcc does.
13123 if (E->getNumArgs() == 0)
13124 return GCCTypeClass::None;
13125
13126 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
13127 // being an ICE, but still folds it to a constant using the type of the first
13128 // argument.
13129 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
13130}
13131
13132/// EvaluateBuiltinConstantPForLValue - Determine the result of
13133/// __builtin_constant_p when applied to the given pointer.
13134///
13135/// A pointer is only "constant" if it is null (or a pointer cast to integer)
13136/// or it points to the first character of a string literal.
13139 if (Base.isNull()) {
13140 // A null base is acceptable.
13141 return true;
13142 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
13143 if (!isa<StringLiteral>(E))
13144 return false;
13145 return LV.getLValueOffset().isZero();
13146 } else if (Base.is<TypeInfoLValue>()) {
13147 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
13148 // evaluate to true.
13149 return true;
13150 } else {
13151 // Any other base is not constant enough for GCC.
13152 return false;
13153 }
13154}
13155
13156/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
13157/// GCC as we can manage.
13158static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
13159 // This evaluation is not permitted to have side-effects, so evaluate it in
13160 // a speculative evaluation context.
13161 SpeculativeEvaluationRAII SpeculativeEval(Info);
13162
13163 // Constant-folding is always enabled for the operand of __builtin_constant_p
13164 // (even when the enclosing evaluation context otherwise requires a strict
13165 // language-specific constant expression).
13166 FoldConstant Fold(Info, true);
13167
13168 QualType ArgType = Arg->getType();
13169
13170 // __builtin_constant_p always has one operand. The rules which gcc follows
13171 // are not precisely documented, but are as follows:
13172 //
13173 // - If the operand is of integral, floating, complex or enumeration type,
13174 // and can be folded to a known value of that type, it returns 1.
13175 // - If the operand can be folded to a pointer to the first character
13176 // of a string literal (or such a pointer cast to an integral type)
13177 // or to a null pointer or an integer cast to a pointer, it returns 1.
13178 //
13179 // Otherwise, it returns 0.
13180 //
13181 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
13182 // its support for this did not work prior to GCC 9 and is not yet well
13183 // understood.
13184 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
13185 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
13186 ArgType->isNullPtrType()) {
13187 APValue V;
13188 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
13189 Fold.keepDiagnostics();
13190 return false;
13191 }
13192
13193 // For a pointer (possibly cast to integer), there are special rules.
13194 if (V.getKind() == APValue::LValue)
13196
13197 // Otherwise, any constant value is good enough.
13198 return V.hasValue();
13199 }
13200
13201 // Anything else isn't considered to be sufficiently constant.
13202 return false;
13203}
13204
13205/// Retrieves the "underlying object type" of the given expression,
13206/// as used by __builtin_object_size.
13208 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
13209 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
13210 return VD->getType();
13211 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
13213 return E->getType();
13214 } else if (B.is<TypeInfoLValue>()) {
13215 return B.getTypeInfoType();
13216 } else if (B.is<DynamicAllocLValue>()) {
13217 return B.getDynamicAllocType();
13218 }
13219
13220 return QualType();
13221}
13222
13223/// A more selective version of E->IgnoreParenCasts for
13224/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
13225/// to change the type of E.
13226/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
13227///
13228/// Always returns an RValue with a pointer representation.
13229static const Expr *ignorePointerCastsAndParens(const Expr *E) {
13230 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
13231
13232 const Expr *NoParens = E->IgnoreParens();
13233 const auto *Cast = dyn_cast<CastExpr>(NoParens);
13234 if (Cast == nullptr)
13235 return NoParens;
13236
13237 // We only conservatively allow a few kinds of casts, because this code is
13238 // inherently a simple solution that seeks to support the common case.
13239 auto CastKind = Cast->getCastKind();
13240 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
13241 CastKind != CK_AddressSpaceConversion)
13242 return NoParens;
13243
13244 const auto *SubExpr = Cast->getSubExpr();
13245 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
13246 return NoParens;
13247 return ignorePointerCastsAndParens(SubExpr);
13248}
13249
13250/// Checks to see if the given LValue's Designator is at the end of the LValue's
13251/// record layout. e.g.
13252/// struct { struct { int a, b; } fst, snd; } obj;
13253/// obj.fst // no
13254/// obj.snd // yes
13255/// obj.fst.a // no
13256/// obj.fst.b // no
13257/// obj.snd.a // no
13258/// obj.snd.b // yes
13259///
13260/// Please note: this function is specialized for how __builtin_object_size
13261/// views "objects".
13262///
13263/// If this encounters an invalid RecordDecl or otherwise cannot determine the
13264/// correct result, it will always return true.
13265static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
13266 assert(!LVal.Designator.Invalid);
13267
13268 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
13269 const RecordDecl *Parent = FD->getParent();
13270 if (Parent->isInvalidDecl() || Parent->isUnion())
13271 return true;
13272 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
13273 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
13274 };
13275
13276 auto &Base = LVal.getLValueBase();
13277 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
13278 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
13279 if (!IsLastOrInvalidFieldDecl(FD))
13280 return false;
13281 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
13282 for (auto *FD : IFD->chain()) {
13283 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
13284 return false;
13285 }
13286 }
13287 }
13288
13289 unsigned I = 0;
13290 QualType BaseType = getType(Base);
13291 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
13292 // If we don't know the array bound, conservatively assume we're looking at
13293 // the final array element.
13294 ++I;
13295 if (BaseType->isIncompleteArrayType())
13296 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
13297 else
13298 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
13299 }
13300
13301 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
13302 const auto &Entry = LVal.Designator.Entries[I];
13303 if (BaseType->isArrayType()) {
13304 // Because __builtin_object_size treats arrays as objects, we can ignore
13305 // the index iff this is the last array in the Designator.
13306 if (I + 1 == E)
13307 return true;
13308 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
13309 uint64_t Index = Entry.getAsArrayIndex();
13310 if (Index + 1 != CAT->getZExtSize())
13311 return false;
13312 BaseType = CAT->getElementType();
13313 } else if (BaseType->isAnyComplexType()) {
13314 const auto *CT = BaseType->castAs<ComplexType>();
13315 uint64_t Index = Entry.getAsArrayIndex();
13316 if (Index != 1)
13317 return false;
13318 BaseType = CT->getElementType();
13319 } else if (auto *FD = getAsField(Entry)) {
13320 if (!IsLastOrInvalidFieldDecl(FD))
13321 return false;
13322 BaseType = FD->getType();
13323 } else {
13324 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
13325 return false;
13326 }
13327 }
13328 return true;
13329}
13330
13331/// Tests to see if the LValue has a user-specified designator (that isn't
13332/// necessarily valid). Note that this always returns 'true' if the LValue has
13333/// an unsized array as its first designator entry, because there's currently no
13334/// way to tell if the user typed *foo or foo[0].
13335static bool refersToCompleteObject(const LValue &LVal) {
13336 if (LVal.Designator.Invalid)
13337 return false;
13338
13339 if (!LVal.Designator.Entries.empty())
13340 return LVal.Designator.isMostDerivedAnUnsizedArray();
13341
13342 if (!LVal.InvalidBase)
13343 return true;
13344
13345 // If `E` is a MemberExpr, then the first part of the designator is hiding in
13346 // the LValueBase.
13347 const auto *E = LVal.Base.dyn_cast<const Expr *>();
13348 return !E || !isa<MemberExpr>(E);
13349}
13350
13351/// Attempts to detect a user writing into a piece of memory that's impossible
13352/// to figure out the size of by just using types.
13353static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
13354 const SubobjectDesignator &Designator = LVal.Designator;
13355 // Notes:
13356 // - Users can only write off of the end when we have an invalid base. Invalid
13357 // bases imply we don't know where the memory came from.
13358 // - We used to be a bit more aggressive here; we'd only be conservative if
13359 // the array at the end was flexible, or if it had 0 or 1 elements. This
13360 // broke some common standard library extensions (PR30346), but was
13361 // otherwise seemingly fine. It may be useful to reintroduce this behavior
13362 // with some sort of list. OTOH, it seems that GCC is always
13363 // conservative with the last element in structs (if it's an array), so our
13364 // current behavior is more compatible than an explicit list approach would
13365 // be.
13366 auto isFlexibleArrayMember = [&] {
13368 FAMKind StrictFlexArraysLevel =
13369 Ctx.getLangOpts().getStrictFlexArraysLevel();
13370
13371 if (Designator.isMostDerivedAnUnsizedArray())
13372 return true;
13373
13374 if (StrictFlexArraysLevel == FAMKind::Default)
13375 return true;
13376
13377 if (Designator.getMostDerivedArraySize() == 0 &&
13378 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
13379 return true;
13380
13381 if (Designator.getMostDerivedArraySize() == 1 &&
13382 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
13383 return true;
13384
13385 return false;
13386 };
13387
13388 return LVal.InvalidBase &&
13389 Designator.Entries.size() == Designator.MostDerivedPathLength &&
13390 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
13391 isDesignatorAtObjectEnd(Ctx, LVal);
13392}
13393
13394/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
13395/// Fails if the conversion would cause loss of precision.
13396static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
13397 CharUnits &Result) {
13398 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
13399 if (Int.ugt(CharUnitsMax))
13400 return false;
13401 Result = CharUnits::fromQuantity(Int.getZExtValue());
13402 return true;
13403}
13404
13405/// If we're evaluating the object size of an instance of a struct that
13406/// contains a flexible array member, add the size of the initializer.
13407static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
13408 const LValue &LV, CharUnits &Size) {
13409 if (!T.isNull() && T->isStructureType() &&
13410 T->castAsRecordDecl()->hasFlexibleArrayMember())
13411 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
13412 if (const auto *VD = dyn_cast<VarDecl>(V))
13413 if (VD->hasInit())
13414 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
13415}
13416
13417/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
13418/// determine how many bytes exist from the beginning of the object to either
13419/// the end of the current subobject, or the end of the object itself, depending
13420/// on what the LValue looks like + the value of Type.
13421///
13422/// If this returns false, the value of Result is undefined.
13423static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
13424 unsigned Type, const LValue &LVal,
13425 CharUnits &EndOffset) {
13426 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
13427
13428 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
13429 if (Ty.isNull())
13430 return false;
13431
13432 Ty = Ty.getNonReferenceType();
13433
13434 if (Ty->isIncompleteType() || Ty->isFunctionType())
13435 return false;
13436
13437 return HandleSizeof(Info, ExprLoc, Ty, Result);
13438 };
13439
13440 // We want to evaluate the size of the entire object. This is a valid fallback
13441 // for when Type=1 and the designator is invalid, because we're asked for an
13442 // upper-bound.
13443 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
13444 // Type=3 wants a lower bound, so we can't fall back to this.
13445 if (Type == 3 && !DetermineForCompleteObject)
13446 return false;
13447
13448 llvm::APInt APEndOffset;
13449 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13450 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13451 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13452
13453 if (LVal.InvalidBase)
13454 return false;
13455
13456 QualType BaseTy = getObjectType(LVal.getLValueBase());
13457 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
13458 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
13459 return Ret;
13460 }
13461
13462 // We want to evaluate the size of a subobject.
13463 const SubobjectDesignator &Designator = LVal.Designator;
13464
13465 // The following is a moderately common idiom in C:
13466 //
13467 // struct Foo { int a; char c[1]; };
13468 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
13469 // strcpy(&F->c[0], Bar);
13470 //
13471 // In order to not break too much legacy code, we need to support it.
13472 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
13473 // If we can resolve this to an alloc_size call, we can hand that back,
13474 // because we know for certain how many bytes there are to write to.
13475 llvm::APInt APEndOffset;
13476 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13477 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13478 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13479
13480 // If we cannot determine the size of the initial allocation, then we can't
13481 // given an accurate upper-bound. However, we are still able to give
13482 // conservative lower-bounds for Type=3.
13483 if (Type == 1)
13484 return false;
13485 }
13486
13487 CharUnits BytesPerElem;
13488 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
13489 return false;
13490
13491 // According to the GCC documentation, we want the size of the subobject
13492 // denoted by the pointer. But that's not quite right -- what we actually
13493 // want is the size of the immediately-enclosing array, if there is one.
13494 int64_t ElemsRemaining;
13495 if (Designator.MostDerivedIsArrayElement &&
13496 Designator.Entries.size() == Designator.MostDerivedPathLength) {
13497 uint64_t ArraySize = Designator.getMostDerivedArraySize();
13498 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
13499 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
13500 } else {
13501 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
13502 }
13503
13504 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
13505 return true;
13506}
13507
13508/// Tries to evaluate the __builtin_object_size for @p E. If successful,
13509/// returns true and stores the result in @p Size.
13510///
13511/// If @p WasError is non-null, this will report whether the failure to evaluate
13512/// is to be treated as an Error in IntExprEvaluator.
13513static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
13514 EvalInfo &Info, uint64_t &Size) {
13515 // Determine the denoted object.
13516 LValue LVal;
13517 {
13518 // The operand of __builtin_object_size is never evaluated for side-effects.
13519 // If there are any, but we can determine the pointed-to object anyway, then
13520 // ignore the side-effects.
13521 SpeculativeEvaluationRAII SpeculativeEval(Info);
13522 IgnoreSideEffectsRAII Fold(Info);
13523
13524 if (E->isGLValue()) {
13525 // It's possible for us to be given GLValues if we're called via
13526 // Expr::tryEvaluateObjectSize.
13527 APValue RVal;
13528 if (!EvaluateAsRValue(Info, E, RVal))
13529 return false;
13530 LVal.setFrom(Info.Ctx, RVal);
13531 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
13532 /*InvalidBaseOK=*/true))
13533 return false;
13534 }
13535
13536 // If we point to before the start of the object, there are no accessible
13537 // bytes.
13538 if (LVal.getLValueOffset().isNegative()) {
13539 Size = 0;
13540 return true;
13541 }
13542
13543 CharUnits EndOffset;
13544 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
13545 return false;
13546
13547 // If we've fallen outside of the end offset, just pretend there's nothing to
13548 // write to/read from.
13549 if (EndOffset <= LVal.getLValueOffset())
13550 Size = 0;
13551 else
13552 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
13553 return true;
13554}
13555
13556bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
13557 if (!IsConstantEvaluatedBuiltinCall(E))
13558 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13559 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
13560}
13561
13562static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
13563 APValue &Val, APSInt &Alignment) {
13564 QualType SrcTy = E->getArg(0)->getType();
13565 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
13566 return false;
13567 // Even though we are evaluating integer expressions we could get a pointer
13568 // argument for the __builtin_is_aligned() case.
13569 if (SrcTy->isPointerType()) {
13570 LValue Ptr;
13571 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
13572 return false;
13573 Ptr.moveInto(Val);
13574 } else if (!SrcTy->isIntegralOrEnumerationType()) {
13575 Info.FFDiag(E->getArg(0));
13576 return false;
13577 } else {
13578 APSInt SrcInt;
13579 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
13580 return false;
13581 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
13582 "Bit widths must be the same");
13583 Val = APValue(SrcInt);
13584 }
13585 assert(Val.hasValue());
13586 return true;
13587}
13588
13589bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
13590 unsigned BuiltinOp) {
13591 switch (BuiltinOp) {
13592 default:
13593 return false;
13594
13595 case Builtin::BI__builtin_dynamic_object_size:
13596 case Builtin::BI__builtin_object_size: {
13597 // The type was checked when we built the expression.
13598 unsigned Type =
13599 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13600 assert(Type <= 3 && "unexpected type");
13601
13602 uint64_t Size;
13603 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
13604 return Success(Size, E);
13605
13606 if (E->getArg(0)->HasSideEffects(Info.Ctx))
13607 return Success((Type & 2) ? 0 : -1, E);
13608
13609 // Expression had no side effects, but we couldn't statically determine the
13610 // size of the referenced object.
13611 switch (Info.EvalMode) {
13612 case EvaluationMode::ConstantExpression:
13613 case EvaluationMode::ConstantFold:
13614 case EvaluationMode::IgnoreSideEffects:
13615 // Leave it to IR generation.
13616 return Error(E);
13617 case EvaluationMode::ConstantExpressionUnevaluated:
13618 // Reduce it to a constant now.
13619 return Success((Type & 2) ? 0 : -1, E);
13620 }
13621
13622 llvm_unreachable("unexpected EvalMode");
13623 }
13624
13625 case Builtin::BI__builtin_os_log_format_buffer_size: {
13626 analyze_os_log::OSLogBufferLayout Layout;
13627 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
13628 return Success(Layout.size().getQuantity(), E);
13629 }
13630
13631 case Builtin::BI__builtin_is_aligned: {
13632 APValue Src;
13633 APSInt Alignment;
13634 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13635 return false;
13636 if (Src.isLValue()) {
13637 // If we evaluated a pointer, check the minimum known alignment.
13638 LValue Ptr;
13639 Ptr.setFrom(Info.Ctx, Src);
13640 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13641 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13642 // We can return true if the known alignment at the computed offset is
13643 // greater than the requested alignment.
13644 assert(PtrAlign.isPowerOfTwo());
13645 assert(Alignment.isPowerOf2());
13646 if (PtrAlign.getQuantity() >= Alignment)
13647 return Success(1, E);
13648 // If the alignment is not known to be sufficient, some cases could still
13649 // be aligned at run time. However, if the requested alignment is less or
13650 // equal to the base alignment and the offset is not aligned, we know that
13651 // the run-time value can never be aligned.
13652 if (BaseAlignment.getQuantity() >= Alignment &&
13653 PtrAlign.getQuantity() < Alignment)
13654 return Success(0, E);
13655 // Otherwise we can't infer whether the value is sufficiently aligned.
13656 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13657 // in cases where we can't fully evaluate the pointer.
13658 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13659 << Alignment;
13660 return false;
13661 }
13662 assert(Src.isInt());
13663 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13664 }
13665 case Builtin::BI__builtin_align_up: {
13666 APValue Src;
13667 APSInt Alignment;
13668 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13669 return false;
13670 if (!Src.isInt())
13671 return Error(E);
13672 APSInt AlignedVal =
13673 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
13674 Src.getInt().isUnsigned());
13675 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13676 return Success(AlignedVal, E);
13677 }
13678 case Builtin::BI__builtin_align_down: {
13679 APValue Src;
13680 APSInt Alignment;
13681 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13682 return false;
13683 if (!Src.isInt())
13684 return Error(E);
13685 APSInt AlignedVal =
13686 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
13687 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13688 return Success(AlignedVal, E);
13689 }
13690
13691 case Builtin::BI__builtin_bitreverse8:
13692 case Builtin::BI__builtin_bitreverse16:
13693 case Builtin::BI__builtin_bitreverse32:
13694 case Builtin::BI__builtin_bitreverse64:
13695 case Builtin::BI__builtin_elementwise_bitreverse: {
13696 APSInt Val;
13697 if (!EvaluateInteger(E->getArg(0), Val, Info))
13698 return false;
13699
13700 return Success(Val.reverseBits(), E);
13701 }
13702
13703 case Builtin::BI__builtin_bswap16:
13704 case Builtin::BI__builtin_bswap32:
13705 case Builtin::BI__builtin_bswap64: {
13706 APSInt Val;
13707 if (!EvaluateInteger(E->getArg(0), Val, Info))
13708 return false;
13709
13710 return Success(Val.byteSwap(), E);
13711 }
13712
13713 case Builtin::BI__builtin_classify_type:
13714 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
13715
13716 case Builtin::BI__builtin_clrsb:
13717 case Builtin::BI__builtin_clrsbl:
13718 case Builtin::BI__builtin_clrsbll: {
13719 APSInt Val;
13720 if (!EvaluateInteger(E->getArg(0), Val, Info))
13721 return false;
13722
13723 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
13724 }
13725
13726 case Builtin::BI__builtin_clz:
13727 case Builtin::BI__builtin_clzl:
13728 case Builtin::BI__builtin_clzll:
13729 case Builtin::BI__builtin_clzs:
13730 case Builtin::BI__builtin_clzg:
13731 case Builtin::BI__builtin_elementwise_clzg:
13732 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13733 case Builtin::BI__lzcnt:
13734 case Builtin::BI__lzcnt64: {
13735 APSInt Val;
13736 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13737 APValue Vec;
13738 if (!EvaluateVector(E->getArg(0), Vec, Info))
13739 return false;
13740 Val = ConvertBoolVectorToInt(Vec);
13741 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13742 return false;
13743 }
13744
13745 std::optional<APSInt> Fallback;
13746 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
13747 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
13748 E->getNumArgs() > 1) {
13749 APSInt FallbackTemp;
13750 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13751 return false;
13752 Fallback = FallbackTemp;
13753 }
13754
13755 if (!Val) {
13756 if (Fallback)
13757 return Success(*Fallback, E);
13758
13759 // When the argument is 0, the result of GCC builtins is undefined,
13760 // whereas for Microsoft intrinsics, the result is the bit-width of the
13761 // argument.
13762 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13763 BuiltinOp != Builtin::BI__lzcnt &&
13764 BuiltinOp != Builtin::BI__lzcnt64;
13765
13766 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
13767 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13768 << /*IsTrailing=*/false;
13769 }
13770
13771 if (ZeroIsUndefined)
13772 return Error(E);
13773 }
13774
13775 return Success(Val.countl_zero(), E);
13776 }
13777
13778 case Builtin::BI__builtin_constant_p: {
13779 const Expr *Arg = E->getArg(0);
13780 if (EvaluateBuiltinConstantP(Info, Arg))
13781 return Success(true, E);
13782 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13783 // Outside a constant context, eagerly evaluate to false in the presence
13784 // of side-effects in order to avoid -Wunsequenced false-positives in
13785 // a branch on __builtin_constant_p(expr).
13786 return Success(false, E);
13787 }
13788 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13789 return false;
13790 }
13791
13792 case Builtin::BI__noop:
13793 // __noop always evaluates successfully and returns 0.
13794 return Success(0, E);
13795
13796 case Builtin::BI__builtin_is_constant_evaluated: {
13797 const auto *Callee = Info.CurrentCall->getCallee();
13798 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13799 (Info.CallStackDepth == 1 ||
13800 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13801 Callee->getIdentifier() &&
13802 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13803 // FIXME: Find a better way to avoid duplicated diagnostics.
13804 if (Info.EvalStatus.Diag)
13805 Info.report((Info.CallStackDepth == 1)
13806 ? E->getExprLoc()
13807 : Info.CurrentCall->getCallRange().getBegin(),
13808 diag::warn_is_constant_evaluated_always_true_constexpr)
13809 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13810 : "std::is_constant_evaluated");
13811 }
13812
13813 return Success(Info.InConstantContext, E);
13814 }
13815
13816 case Builtin::BI__builtin_is_within_lifetime:
13817 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13818 return Success(*result, E);
13819 return false;
13820
13821 case Builtin::BI__builtin_ctz:
13822 case Builtin::BI__builtin_ctzl:
13823 case Builtin::BI__builtin_ctzll:
13824 case Builtin::BI__builtin_ctzs:
13825 case Builtin::BI__builtin_ctzg:
13826 case Builtin::BI__builtin_elementwise_ctzg: {
13827 APSInt Val;
13828 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13829 APValue Vec;
13830 if (!EvaluateVector(E->getArg(0), Vec, Info))
13831 return false;
13832 Val = ConvertBoolVectorToInt(Vec);
13833 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13834 return false;
13835 }
13836
13837 std::optional<APSInt> Fallback;
13838 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
13839 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
13840 E->getNumArgs() > 1) {
13841 APSInt FallbackTemp;
13842 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13843 return false;
13844 Fallback = FallbackTemp;
13845 }
13846
13847 if (!Val) {
13848 if (Fallback)
13849 return Success(*Fallback, E);
13850
13851 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
13852 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13853 << /*IsTrailing=*/true;
13854 }
13855 return Error(E);
13856 }
13857
13858 return Success(Val.countr_zero(), E);
13859 }
13860
13861 case Builtin::BI__builtin_eh_return_data_regno: {
13862 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13863 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13864 return Success(Operand, E);
13865 }
13866
13867 case Builtin::BI__builtin_elementwise_abs: {
13868 APSInt Val;
13869 if (!EvaluateInteger(E->getArg(0), Val, Info))
13870 return false;
13871
13872 return Success(Val.abs(), E);
13873 }
13874
13875 case Builtin::BI__builtin_expect:
13876 case Builtin::BI__builtin_expect_with_probability:
13877 return Visit(E->getArg(0));
13878
13879 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13880 const auto *Literal =
13882 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13883 return Success(Result, E);
13884 }
13885
13886 case Builtin::BI__builtin_ffs:
13887 case Builtin::BI__builtin_ffsl:
13888 case Builtin::BI__builtin_ffsll: {
13889 APSInt Val;
13890 if (!EvaluateInteger(E->getArg(0), Val, Info))
13891 return false;
13892
13893 unsigned N = Val.countr_zero();
13894 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13895 }
13896
13897 case Builtin::BI__builtin_fpclassify: {
13898 APFloat Val(0.0);
13899 if (!EvaluateFloat(E->getArg(5), Val, Info))
13900 return false;
13901 unsigned Arg;
13902 switch (Val.getCategory()) {
13903 case APFloat::fcNaN: Arg = 0; break;
13904 case APFloat::fcInfinity: Arg = 1; break;
13905 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13906 case APFloat::fcZero: Arg = 4; break;
13907 }
13908 return Visit(E->getArg(Arg));
13909 }
13910
13911 case Builtin::BI__builtin_isinf_sign: {
13912 APFloat Val(0.0);
13913 return EvaluateFloat(E->getArg(0), Val, Info) &&
13914 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13915 }
13916
13917 case Builtin::BI__builtin_isinf: {
13918 APFloat Val(0.0);
13919 return EvaluateFloat(E->getArg(0), Val, Info) &&
13920 Success(Val.isInfinity() ? 1 : 0, E);
13921 }
13922
13923 case Builtin::BI__builtin_isfinite: {
13924 APFloat Val(0.0);
13925 return EvaluateFloat(E->getArg(0), Val, Info) &&
13926 Success(Val.isFinite() ? 1 : 0, E);
13927 }
13928
13929 case Builtin::BI__builtin_isnan: {
13930 APFloat Val(0.0);
13931 return EvaluateFloat(E->getArg(0), Val, Info) &&
13932 Success(Val.isNaN() ? 1 : 0, E);
13933 }
13934
13935 case Builtin::BI__builtin_isnormal: {
13936 APFloat Val(0.0);
13937 return EvaluateFloat(E->getArg(0), Val, Info) &&
13938 Success(Val.isNormal() ? 1 : 0, E);
13939 }
13940
13941 case Builtin::BI__builtin_issubnormal: {
13942 APFloat Val(0.0);
13943 return EvaluateFloat(E->getArg(0), Val, Info) &&
13944 Success(Val.isDenormal() ? 1 : 0, E);
13945 }
13946
13947 case Builtin::BI__builtin_iszero: {
13948 APFloat Val(0.0);
13949 return EvaluateFloat(E->getArg(0), Val, Info) &&
13950 Success(Val.isZero() ? 1 : 0, E);
13951 }
13952
13953 case Builtin::BI__builtin_signbit:
13954 case Builtin::BI__builtin_signbitf:
13955 case Builtin::BI__builtin_signbitl: {
13956 APFloat Val(0.0);
13957 return EvaluateFloat(E->getArg(0), Val, Info) &&
13958 Success(Val.isNegative() ? 1 : 0, E);
13959 }
13960
13961 case Builtin::BI__builtin_isgreater:
13962 case Builtin::BI__builtin_isgreaterequal:
13963 case Builtin::BI__builtin_isless:
13964 case Builtin::BI__builtin_islessequal:
13965 case Builtin::BI__builtin_islessgreater:
13966 case Builtin::BI__builtin_isunordered: {
13967 APFloat LHS(0.0);
13968 APFloat RHS(0.0);
13969 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13970 !EvaluateFloat(E->getArg(1), RHS, Info))
13971 return false;
13972
13973 return Success(
13974 [&] {
13975 switch (BuiltinOp) {
13976 case Builtin::BI__builtin_isgreater:
13977 return LHS > RHS;
13978 case Builtin::BI__builtin_isgreaterequal:
13979 return LHS >= RHS;
13980 case Builtin::BI__builtin_isless:
13981 return LHS < RHS;
13982 case Builtin::BI__builtin_islessequal:
13983 return LHS <= RHS;
13984 case Builtin::BI__builtin_islessgreater: {
13985 APFloat::cmpResult cmp = LHS.compare(RHS);
13986 return cmp == APFloat::cmpResult::cmpLessThan ||
13987 cmp == APFloat::cmpResult::cmpGreaterThan;
13988 }
13989 case Builtin::BI__builtin_isunordered:
13990 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13991 default:
13992 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13993 "point comparison function");
13994 }
13995 }()
13996 ? 1
13997 : 0,
13998 E);
13999 }
14000
14001 case Builtin::BI__builtin_issignaling: {
14002 APFloat Val(0.0);
14003 return EvaluateFloat(E->getArg(0), Val, Info) &&
14004 Success(Val.isSignaling() ? 1 : 0, E);
14005 }
14006
14007 case Builtin::BI__builtin_isfpclass: {
14008 APSInt MaskVal;
14009 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
14010 return false;
14011 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
14012 APFloat Val(0.0);
14013 return EvaluateFloat(E->getArg(0), Val, Info) &&
14014 Success((Val.classify() & Test) ? 1 : 0, E);
14015 }
14016
14017 case Builtin::BI__builtin_parity:
14018 case Builtin::BI__builtin_parityl:
14019 case Builtin::BI__builtin_parityll: {
14020 APSInt Val;
14021 if (!EvaluateInteger(E->getArg(0), Val, Info))
14022 return false;
14023
14024 return Success(Val.popcount() % 2, E);
14025 }
14026
14027 case Builtin::BI__builtin_abs:
14028 case Builtin::BI__builtin_labs:
14029 case Builtin::BI__builtin_llabs: {
14030 APSInt Val;
14031 if (!EvaluateInteger(E->getArg(0), Val, Info))
14032 return false;
14033 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
14034 /*IsUnsigned=*/false))
14035 return false;
14036 if (Val.isNegative())
14037 Val.negate();
14038 return Success(Val, E);
14039 }
14040
14041 case Builtin::BI__builtin_popcount:
14042 case Builtin::BI__builtin_popcountl:
14043 case Builtin::BI__builtin_popcountll:
14044 case Builtin::BI__builtin_popcountg:
14045 case Builtin::BI__builtin_elementwise_popcount:
14046 case Builtin::BI__popcnt16: // Microsoft variants of popcount
14047 case Builtin::BI__popcnt:
14048 case Builtin::BI__popcnt64: {
14049 APSInt Val;
14050 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
14051 APValue Vec;
14052 if (!EvaluateVector(E->getArg(0), Vec, Info))
14053 return false;
14054 Val = ConvertBoolVectorToInt(Vec);
14055 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
14056 return false;
14057 }
14058
14059 return Success(Val.popcount(), E);
14060 }
14061
14062 case Builtin::BI__builtin_rotateleft8:
14063 case Builtin::BI__builtin_rotateleft16:
14064 case Builtin::BI__builtin_rotateleft32:
14065 case Builtin::BI__builtin_rotateleft64:
14066 case Builtin::BI_rotl8: // Microsoft variants of rotate right
14067 case Builtin::BI_rotl16:
14068 case Builtin::BI_rotl:
14069 case Builtin::BI_lrotl:
14070 case Builtin::BI_rotl64: {
14071 APSInt Val, Amt;
14072 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14073 !EvaluateInteger(E->getArg(1), Amt, Info))
14074 return false;
14075
14076 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
14077 }
14078
14079 case Builtin::BI__builtin_rotateright8:
14080 case Builtin::BI__builtin_rotateright16:
14081 case Builtin::BI__builtin_rotateright32:
14082 case Builtin::BI__builtin_rotateright64:
14083 case Builtin::BI_rotr8: // Microsoft variants of rotate right
14084 case Builtin::BI_rotr16:
14085 case Builtin::BI_rotr:
14086 case Builtin::BI_lrotr:
14087 case Builtin::BI_rotr64: {
14088 APSInt Val, Amt;
14089 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14090 !EvaluateInteger(E->getArg(1), Amt, Info))
14091 return false;
14092
14093 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
14094 }
14095
14096 case Builtin::BI__builtin_elementwise_add_sat: {
14097 APSInt LHS, RHS;
14098 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14099 !EvaluateInteger(E->getArg(1), RHS, Info))
14100 return false;
14101
14102 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
14103 return Success(APSInt(Result, !LHS.isSigned()), E);
14104 }
14105 case Builtin::BI__builtin_elementwise_sub_sat: {
14106 APSInt LHS, RHS;
14107 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14108 !EvaluateInteger(E->getArg(1), RHS, Info))
14109 return false;
14110
14111 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
14112 return Success(APSInt(Result, !LHS.isSigned()), E);
14113 }
14114 case Builtin::BI__builtin_elementwise_max: {
14115 APSInt LHS, RHS;
14116 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14117 !EvaluateInteger(E->getArg(1), RHS, Info))
14118 return false;
14119
14120 APInt Result = std::max(LHS, RHS);
14121 return Success(APSInt(Result, !LHS.isSigned()), E);
14122 }
14123 case Builtin::BI__builtin_elementwise_min: {
14124 APSInt LHS, RHS;
14125 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14126 !EvaluateInteger(E->getArg(1), RHS, Info))
14127 return false;
14128
14129 APInt Result = std::min(LHS, RHS);
14130 return Success(APSInt(Result, !LHS.isSigned()), E);
14131 }
14132 case Builtin::BI__builtin_elementwise_fshl:
14133 case Builtin::BI__builtin_elementwise_fshr: {
14134 APSInt Hi, Lo, Shift;
14135 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
14136 !EvaluateInteger(E->getArg(1), Lo, Info) ||
14137 !EvaluateInteger(E->getArg(2), Shift, Info))
14138 return false;
14139
14140 switch (BuiltinOp) {
14141 case Builtin::BI__builtin_elementwise_fshl: {
14142 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
14143 return Success(Result, E);
14144 }
14145 case Builtin::BI__builtin_elementwise_fshr: {
14146 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
14147 return Success(Result, E);
14148 }
14149 }
14150 llvm_unreachable("Fully covered switch above");
14151 }
14152 case Builtin::BIstrlen:
14153 case Builtin::BIwcslen:
14154 // A call to strlen is not a constant expression.
14155 if (Info.getLangOpts().CPlusPlus11)
14156 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14157 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14158 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14159 else
14160 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14161 [[fallthrough]];
14162 case Builtin::BI__builtin_strlen:
14163 case Builtin::BI__builtin_wcslen: {
14164 // As an extension, we support __builtin_strlen() as a constant expression,
14165 // and support folding strlen() to a constant.
14166 uint64_t StrLen;
14167 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
14168 return Success(StrLen, E);
14169 return false;
14170 }
14171
14172 case Builtin::BIstrcmp:
14173 case Builtin::BIwcscmp:
14174 case Builtin::BIstrncmp:
14175 case Builtin::BIwcsncmp:
14176 case Builtin::BImemcmp:
14177 case Builtin::BIbcmp:
14178 case Builtin::BIwmemcmp:
14179 // A call to strlen is not a constant expression.
14180 if (Info.getLangOpts().CPlusPlus11)
14181 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
14182 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
14183 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
14184 else
14185 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
14186 [[fallthrough]];
14187 case Builtin::BI__builtin_strcmp:
14188 case Builtin::BI__builtin_wcscmp:
14189 case Builtin::BI__builtin_strncmp:
14190 case Builtin::BI__builtin_wcsncmp:
14191 case Builtin::BI__builtin_memcmp:
14192 case Builtin::BI__builtin_bcmp:
14193 case Builtin::BI__builtin_wmemcmp: {
14194 LValue String1, String2;
14195 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
14196 !EvaluatePointer(E->getArg(1), String2, Info))
14197 return false;
14198
14199 uint64_t MaxLength = uint64_t(-1);
14200 if (BuiltinOp != Builtin::BIstrcmp &&
14201 BuiltinOp != Builtin::BIwcscmp &&
14202 BuiltinOp != Builtin::BI__builtin_strcmp &&
14203 BuiltinOp != Builtin::BI__builtin_wcscmp) {
14204 APSInt N;
14205 if (!EvaluateInteger(E->getArg(2), N, Info))
14206 return false;
14207 MaxLength = N.getZExtValue();
14208 }
14209
14210 // Empty substrings compare equal by definition.
14211 if (MaxLength == 0u)
14212 return Success(0, E);
14213
14214 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14215 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14216 String1.Designator.Invalid || String2.Designator.Invalid)
14217 return false;
14218
14219 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
14220 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
14221
14222 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
14223 BuiltinOp == Builtin::BIbcmp ||
14224 BuiltinOp == Builtin::BI__builtin_memcmp ||
14225 BuiltinOp == Builtin::BI__builtin_bcmp;
14226
14227 assert(IsRawByte ||
14228 (Info.Ctx.hasSameUnqualifiedType(
14229 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
14230 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
14231
14232 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
14233 // 'char8_t', but no other types.
14234 if (IsRawByte &&
14235 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
14236 // FIXME: Consider using our bit_cast implementation to support this.
14237 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
14238 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
14239 << CharTy2;
14240 return false;
14241 }
14242
14243 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
14244 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
14245 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
14246 Char1.isInt() && Char2.isInt();
14247 };
14248 const auto &AdvanceElems = [&] {
14249 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
14250 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
14251 };
14252
14253 bool StopAtNull =
14254 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
14255 BuiltinOp != Builtin::BIwmemcmp &&
14256 BuiltinOp != Builtin::BI__builtin_memcmp &&
14257 BuiltinOp != Builtin::BI__builtin_bcmp &&
14258 BuiltinOp != Builtin::BI__builtin_wmemcmp);
14259 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
14260 BuiltinOp == Builtin::BIwcsncmp ||
14261 BuiltinOp == Builtin::BIwmemcmp ||
14262 BuiltinOp == Builtin::BI__builtin_wcscmp ||
14263 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
14264 BuiltinOp == Builtin::BI__builtin_wmemcmp;
14265
14266 for (; MaxLength; --MaxLength) {
14267 APValue Char1, Char2;
14268 if (!ReadCurElems(Char1, Char2))
14269 return false;
14270 if (Char1.getInt().ne(Char2.getInt())) {
14271 if (IsWide) // wmemcmp compares with wchar_t signedness.
14272 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
14273 // memcmp always compares unsigned chars.
14274 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
14275 }
14276 if (StopAtNull && !Char1.getInt())
14277 return Success(0, E);
14278 assert(!(StopAtNull && !Char2.getInt()));
14279 if (!AdvanceElems())
14280 return false;
14281 }
14282 // We hit the strncmp / memcmp limit.
14283 return Success(0, E);
14284 }
14285
14286 case Builtin::BI__atomic_always_lock_free:
14287 case Builtin::BI__atomic_is_lock_free:
14288 case Builtin::BI__c11_atomic_is_lock_free: {
14289 APSInt SizeVal;
14290 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
14291 return false;
14292
14293 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
14294 // of two less than or equal to the maximum inline atomic width, we know it
14295 // is lock-free. If the size isn't a power of two, or greater than the
14296 // maximum alignment where we promote atomics, we know it is not lock-free
14297 // (at least not in the sense of atomic_is_lock_free). Otherwise,
14298 // the answer can only be determined at runtime; for example, 16-byte
14299 // atomics have lock-free implementations on some, but not all,
14300 // x86-64 processors.
14301
14302 // Check power-of-two.
14303 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
14304 if (Size.isPowerOfTwo()) {
14305 // Check against inlining width.
14306 unsigned InlineWidthBits =
14308 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
14309 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
14310 Size == CharUnits::One())
14311 return Success(1, E);
14312
14313 // If the pointer argument can be evaluated to a compile-time constant
14314 // integer (or nullptr), check if that value is appropriately aligned.
14315 const Expr *PtrArg = E->getArg(1);
14316 Expr::EvalResult ExprResult;
14317 APSInt IntResult;
14318 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
14319 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
14320 Info.Ctx) &&
14321 IntResult.isAligned(Size.getAsAlign()))
14322 return Success(1, E);
14323
14324 // Otherwise, check if the type's alignment against Size.
14325 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
14326 // Drop the potential implicit-cast to 'const volatile void*', getting
14327 // the underlying type.
14328 if (ICE->getCastKind() == CK_BitCast)
14329 PtrArg = ICE->getSubExpr();
14330 }
14331
14332 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
14333 QualType PointeeType = PtrTy->getPointeeType();
14334 if (!PointeeType->isIncompleteType() &&
14335 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
14336 // OK, we will inline operations on this object.
14337 return Success(1, E);
14338 }
14339 }
14340 }
14341 }
14342
14343 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
14344 Success(0, E) : Error(E);
14345 }
14346 case Builtin::BI__builtin_addcb:
14347 case Builtin::BI__builtin_addcs:
14348 case Builtin::BI__builtin_addc:
14349 case Builtin::BI__builtin_addcl:
14350 case Builtin::BI__builtin_addcll:
14351 case Builtin::BI__builtin_subcb:
14352 case Builtin::BI__builtin_subcs:
14353 case Builtin::BI__builtin_subc:
14354 case Builtin::BI__builtin_subcl:
14355 case Builtin::BI__builtin_subcll: {
14356 LValue CarryOutLValue;
14357 APSInt LHS, RHS, CarryIn, CarryOut, Result;
14358 QualType ResultType = E->getArg(0)->getType();
14359 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14360 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14361 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
14362 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
14363 return false;
14364 // Copy the number of bits and sign.
14365 Result = LHS;
14366 CarryOut = LHS;
14367
14368 bool FirstOverflowed = false;
14369 bool SecondOverflowed = false;
14370 switch (BuiltinOp) {
14371 default:
14372 llvm_unreachable("Invalid value for BuiltinOp");
14373 case Builtin::BI__builtin_addcb:
14374 case Builtin::BI__builtin_addcs:
14375 case Builtin::BI__builtin_addc:
14376 case Builtin::BI__builtin_addcl:
14377 case Builtin::BI__builtin_addcll:
14378 Result =
14379 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
14380 break;
14381 case Builtin::BI__builtin_subcb:
14382 case Builtin::BI__builtin_subcs:
14383 case Builtin::BI__builtin_subc:
14384 case Builtin::BI__builtin_subcl:
14385 case Builtin::BI__builtin_subcll:
14386 Result =
14387 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
14388 break;
14389 }
14390
14391 // It is possible for both overflows to happen but CGBuiltin uses an OR so
14392 // this is consistent.
14393 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
14394 APValue APV{CarryOut};
14395 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
14396 return false;
14397 return Success(Result, E);
14398 }
14399 case Builtin::BI__builtin_add_overflow:
14400 case Builtin::BI__builtin_sub_overflow:
14401 case Builtin::BI__builtin_mul_overflow:
14402 case Builtin::BI__builtin_sadd_overflow:
14403 case Builtin::BI__builtin_uadd_overflow:
14404 case Builtin::BI__builtin_uaddl_overflow:
14405 case Builtin::BI__builtin_uaddll_overflow:
14406 case Builtin::BI__builtin_usub_overflow:
14407 case Builtin::BI__builtin_usubl_overflow:
14408 case Builtin::BI__builtin_usubll_overflow:
14409 case Builtin::BI__builtin_umul_overflow:
14410 case Builtin::BI__builtin_umull_overflow:
14411 case Builtin::BI__builtin_umulll_overflow:
14412 case Builtin::BI__builtin_saddl_overflow:
14413 case Builtin::BI__builtin_saddll_overflow:
14414 case Builtin::BI__builtin_ssub_overflow:
14415 case Builtin::BI__builtin_ssubl_overflow:
14416 case Builtin::BI__builtin_ssubll_overflow:
14417 case Builtin::BI__builtin_smul_overflow:
14418 case Builtin::BI__builtin_smull_overflow:
14419 case Builtin::BI__builtin_smulll_overflow: {
14420 LValue ResultLValue;
14421 APSInt LHS, RHS;
14422
14423 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
14424 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14425 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14426 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
14427 return false;
14428
14429 APSInt Result;
14430 bool DidOverflow = false;
14431
14432 // If the types don't have to match, enlarge all 3 to the largest of them.
14433 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14434 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14435 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14436 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
14438 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
14440 uint64_t LHSSize = LHS.getBitWidth();
14441 uint64_t RHSSize = RHS.getBitWidth();
14442 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
14443 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
14444
14445 // Add an additional bit if the signedness isn't uniformly agreed to. We
14446 // could do this ONLY if there is a signed and an unsigned that both have
14447 // MaxBits, but the code to check that is pretty nasty. The issue will be
14448 // caught in the shrink-to-result later anyway.
14449 if (IsSigned && !AllSigned)
14450 ++MaxBits;
14451
14452 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
14453 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
14454 Result = APSInt(MaxBits, !IsSigned);
14455 }
14456
14457 // Find largest int.
14458 switch (BuiltinOp) {
14459 default:
14460 llvm_unreachable("Invalid value for BuiltinOp");
14461 case Builtin::BI__builtin_add_overflow:
14462 case Builtin::BI__builtin_sadd_overflow:
14463 case Builtin::BI__builtin_saddl_overflow:
14464 case Builtin::BI__builtin_saddll_overflow:
14465 case Builtin::BI__builtin_uadd_overflow:
14466 case Builtin::BI__builtin_uaddl_overflow:
14467 case Builtin::BI__builtin_uaddll_overflow:
14468 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
14469 : LHS.uadd_ov(RHS, DidOverflow);
14470 break;
14471 case Builtin::BI__builtin_sub_overflow:
14472 case Builtin::BI__builtin_ssub_overflow:
14473 case Builtin::BI__builtin_ssubl_overflow:
14474 case Builtin::BI__builtin_ssubll_overflow:
14475 case Builtin::BI__builtin_usub_overflow:
14476 case Builtin::BI__builtin_usubl_overflow:
14477 case Builtin::BI__builtin_usubll_overflow:
14478 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
14479 : LHS.usub_ov(RHS, DidOverflow);
14480 break;
14481 case Builtin::BI__builtin_mul_overflow:
14482 case Builtin::BI__builtin_smul_overflow:
14483 case Builtin::BI__builtin_smull_overflow:
14484 case Builtin::BI__builtin_smulll_overflow:
14485 case Builtin::BI__builtin_umul_overflow:
14486 case Builtin::BI__builtin_umull_overflow:
14487 case Builtin::BI__builtin_umulll_overflow:
14488 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
14489 : LHS.umul_ov(RHS, DidOverflow);
14490 break;
14491 }
14492
14493 // In the case where multiple sizes are allowed, truncate and see if
14494 // the values are the same.
14495 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14496 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14497 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14498 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
14499 // since it will give us the behavior of a TruncOrSelf in the case where
14500 // its parameter <= its size. We previously set Result to be at least the
14501 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
14502 // will work exactly like TruncOrSelf.
14503 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
14504 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
14505
14506 if (!APSInt::isSameValue(Temp, Result))
14507 DidOverflow = true;
14508 Result = Temp;
14509 }
14510
14511 APValue APV{Result};
14512 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14513 return false;
14514 return Success(DidOverflow, E);
14515 }
14516
14517 case Builtin::BI__builtin_reduce_add:
14518 case Builtin::BI__builtin_reduce_mul:
14519 case Builtin::BI__builtin_reduce_and:
14520 case Builtin::BI__builtin_reduce_or:
14521 case Builtin::BI__builtin_reduce_xor:
14522 case Builtin::BI__builtin_reduce_min:
14523 case Builtin::BI__builtin_reduce_max: {
14524 APValue Source;
14525 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
14526 return false;
14527
14528 unsigned SourceLen = Source.getVectorLength();
14529 APSInt Reduced = Source.getVectorElt(0).getInt();
14530 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
14531 switch (BuiltinOp) {
14532 default:
14533 return false;
14534 case Builtin::BI__builtin_reduce_add: {
14536 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14537 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
14538 return false;
14539 break;
14540 }
14541 case Builtin::BI__builtin_reduce_mul: {
14543 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14544 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
14545 return false;
14546 break;
14547 }
14548 case Builtin::BI__builtin_reduce_and: {
14549 Reduced &= Source.getVectorElt(EltNum).getInt();
14550 break;
14551 }
14552 case Builtin::BI__builtin_reduce_or: {
14553 Reduced |= Source.getVectorElt(EltNum).getInt();
14554 break;
14555 }
14556 case Builtin::BI__builtin_reduce_xor: {
14557 Reduced ^= Source.getVectorElt(EltNum).getInt();
14558 break;
14559 }
14560 case Builtin::BI__builtin_reduce_min: {
14561 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
14562 break;
14563 }
14564 case Builtin::BI__builtin_reduce_max: {
14565 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
14566 break;
14567 }
14568 }
14569 }
14570
14571 return Success(Reduced, E);
14572 }
14573
14574 case clang::X86::BI__builtin_ia32_addcarryx_u32:
14575 case clang::X86::BI__builtin_ia32_addcarryx_u64:
14576 case clang::X86::BI__builtin_ia32_subborrow_u32:
14577 case clang::X86::BI__builtin_ia32_subborrow_u64: {
14578 LValue ResultLValue;
14579 APSInt CarryIn, LHS, RHS;
14580 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
14581 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
14582 !EvaluateInteger(E->getArg(1), LHS, Info) ||
14583 !EvaluateInteger(E->getArg(2), RHS, Info) ||
14584 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
14585 return false;
14586
14587 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
14588 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
14589
14590 unsigned BitWidth = LHS.getBitWidth();
14591 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
14592 APInt ExResult =
14593 IsAdd
14594 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
14595 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
14596
14597 APInt Result = ExResult.extractBits(BitWidth, 0);
14598 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
14599
14600 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
14601 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14602 return false;
14603 return Success(CarryOut, E);
14604 }
14605
14606 case clang::X86::BI__builtin_ia32_bextr_u32:
14607 case clang::X86::BI__builtin_ia32_bextr_u64:
14608 case clang::X86::BI__builtin_ia32_bextri_u32:
14609 case clang::X86::BI__builtin_ia32_bextri_u64: {
14610 APSInt Val, Idx;
14611 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14612 !EvaluateInteger(E->getArg(1), Idx, Info))
14613 return false;
14614
14615 unsigned BitWidth = Val.getBitWidth();
14616 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
14617 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
14618 Length = Length > BitWidth ? BitWidth : Length;
14619
14620 // Handle out of bounds cases.
14621 if (Length == 0 || Shift >= BitWidth)
14622 return Success(0, E);
14623
14624 uint64_t Result = Val.getZExtValue() >> Shift;
14625 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
14626 return Success(Result, E);
14627 }
14628
14629 case clang::X86::BI__builtin_ia32_bzhi_si:
14630 case clang::X86::BI__builtin_ia32_bzhi_di: {
14631 APSInt Val, Idx;
14632 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14633 !EvaluateInteger(E->getArg(1), Idx, Info))
14634 return false;
14635
14636 unsigned BitWidth = Val.getBitWidth();
14637 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
14638 if (Index < BitWidth)
14639 Val.clearHighBits(BitWidth - Index);
14640 return Success(Val, E);
14641 }
14642
14643 case clang::X86::BI__builtin_ia32_lzcnt_u16:
14644 case clang::X86::BI__builtin_ia32_lzcnt_u32:
14645 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
14646 APSInt Val;
14647 if (!EvaluateInteger(E->getArg(0), Val, Info))
14648 return false;
14649 return Success(Val.countLeadingZeros(), E);
14650 }
14651
14652 case clang::X86::BI__builtin_ia32_tzcnt_u16:
14653 case clang::X86::BI__builtin_ia32_tzcnt_u32:
14654 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
14655 APSInt Val;
14656 if (!EvaluateInteger(E->getArg(0), Val, Info))
14657 return false;
14658 return Success(Val.countTrailingZeros(), E);
14659 }
14660
14661 case clang::X86::BI__builtin_ia32_pdep_si:
14662 case clang::X86::BI__builtin_ia32_pdep_di: {
14663 APSInt Val, Msk;
14664 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14665 !EvaluateInteger(E->getArg(1), Msk, Info))
14666 return false;
14667
14668 unsigned BitWidth = Val.getBitWidth();
14669 APInt Result = APInt::getZero(BitWidth);
14670 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14671 if (Msk[I])
14672 Result.setBitVal(I, Val[P++]);
14673 return Success(Result, E);
14674 }
14675
14676 case clang::X86::BI__builtin_ia32_pext_si:
14677 case clang::X86::BI__builtin_ia32_pext_di: {
14678 APSInt Val, Msk;
14679 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14680 !EvaluateInteger(E->getArg(1), Msk, Info))
14681 return false;
14682
14683 unsigned BitWidth = Val.getBitWidth();
14684 APInt Result = APInt::getZero(BitWidth);
14685 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14686 if (Msk[I])
14687 Result.setBitVal(P++, Val[I]);
14688 return Success(Result, E);
14689 }
14690 }
14691}
14692
14693/// Determine whether this is a pointer past the end of the complete
14694/// object referred to by the lvalue.
14696 const LValue &LV) {
14697 // A null pointer can be viewed as being "past the end" but we don't
14698 // choose to look at it that way here.
14699 if (!LV.getLValueBase())
14700 return false;
14701
14702 // If the designator is valid and refers to a subobject, we're not pointing
14703 // past the end.
14704 if (!LV.getLValueDesignator().Invalid &&
14705 !LV.getLValueDesignator().isOnePastTheEnd())
14706 return false;
14707
14708 // A pointer to an incomplete type might be past-the-end if the type's size is
14709 // zero. We cannot tell because the type is incomplete.
14710 QualType Ty = getType(LV.getLValueBase());
14711 if (Ty->isIncompleteType())
14712 return true;
14713
14714 // Can't be past the end of an invalid object.
14715 if (LV.getLValueDesignator().Invalid)
14716 return false;
14717
14718 // We're a past-the-end pointer if we point to the byte after the object,
14719 // no matter what our type or path is.
14720 auto Size = Ctx.getTypeSizeInChars(Ty);
14721 return LV.getLValueOffset() == Size;
14722}
14723
14724namespace {
14725
14726/// Data recursive integer evaluator of certain binary operators.
14727///
14728/// We use a data recursive algorithm for binary operators so that we are able
14729/// to handle extreme cases of chained binary operators without causing stack
14730/// overflow.
14731class DataRecursiveIntBinOpEvaluator {
14732 struct EvalResult {
14733 APValue Val;
14734 bool Failed = false;
14735
14736 EvalResult() = default;
14737
14738 void swap(EvalResult &RHS) {
14739 Val.swap(RHS.Val);
14740 Failed = RHS.Failed;
14741 RHS.Failed = false;
14742 }
14743 };
14744
14745 struct Job {
14746 const Expr *E;
14747 EvalResult LHSResult; // meaningful only for binary operator expression.
14748 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
14749
14750 Job() = default;
14751 Job(Job &&) = default;
14752
14753 void startSpeculativeEval(EvalInfo &Info) {
14754 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
14755 }
14756
14757 private:
14758 SpeculativeEvaluationRAII SpecEvalRAII;
14759 };
14760
14761 SmallVector<Job, 16> Queue;
14762
14763 IntExprEvaluator &IntEval;
14764 EvalInfo &Info;
14765 APValue &FinalResult;
14766
14767public:
14768 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
14769 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
14770
14771 /// True if \param E is a binary operator that we are going to handle
14772 /// data recursively.
14773 /// We handle binary operators that are comma, logical, or that have operands
14774 /// with integral or enumeration type.
14775 static bool shouldEnqueue(const BinaryOperator *E) {
14776 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
14780 }
14781
14782 bool Traverse(const BinaryOperator *E) {
14783 enqueue(E);
14784 EvalResult PrevResult;
14785 while (!Queue.empty())
14786 process(PrevResult);
14787
14788 if (PrevResult.Failed) return false;
14789
14790 FinalResult.swap(PrevResult.Val);
14791 return true;
14792 }
14793
14794private:
14795 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14796 return IntEval.Success(Value, E, Result);
14797 }
14798 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
14799 return IntEval.Success(Value, E, Result);
14800 }
14801 bool Error(const Expr *E) {
14802 return IntEval.Error(E);
14803 }
14804 bool Error(const Expr *E, diag::kind D) {
14805 return IntEval.Error(E, D);
14806 }
14807
14808 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14809 return Info.CCEDiag(E, D);
14810 }
14811
14812 // Returns true if visiting the RHS is necessary, false otherwise.
14813 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14814 bool &SuppressRHSDiags);
14815
14816 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14817 const BinaryOperator *E, APValue &Result);
14818
14819 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14820 Result.Failed = !Evaluate(Result.Val, Info, E);
14821 if (Result.Failed)
14822 Result.Val = APValue();
14823 }
14824
14825 void process(EvalResult &Result);
14826
14827 void enqueue(const Expr *E) {
14828 E = E->IgnoreParens();
14829 Queue.resize(Queue.size()+1);
14830 Queue.back().E = E;
14831 Queue.back().Kind = Job::AnyExprKind;
14832 }
14833};
14834
14835}
14836
14837bool DataRecursiveIntBinOpEvaluator::
14838 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14839 bool &SuppressRHSDiags) {
14840 if (E->getOpcode() == BO_Comma) {
14841 // Ignore LHS but note if we could not evaluate it.
14842 if (LHSResult.Failed)
14843 return Info.noteSideEffect();
14844 return true;
14845 }
14846
14847 if (E->isLogicalOp()) {
14848 bool LHSAsBool;
14849 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14850 // We were able to evaluate the LHS, see if we can get away with not
14851 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14852 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14853 Success(LHSAsBool, E, LHSResult.Val);
14854 return false; // Ignore RHS
14855 }
14856 } else {
14857 LHSResult.Failed = true;
14858
14859 // Since we weren't able to evaluate the left hand side, it
14860 // might have had side effects.
14861 if (!Info.noteSideEffect())
14862 return false;
14863
14864 // We can't evaluate the LHS; however, sometimes the result
14865 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14866 // Don't ignore RHS and suppress diagnostics from this arm.
14867 SuppressRHSDiags = true;
14868 }
14869
14870 return true;
14871 }
14872
14873 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14875
14876 if (LHSResult.Failed && !Info.noteFailure())
14877 return false; // Ignore RHS;
14878
14879 return true;
14880}
14881
14882static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14883 bool IsSub) {
14884 // Compute the new offset in the appropriate width, wrapping at 64 bits.
14885 // FIXME: When compiling for a 32-bit target, we should use 32-bit
14886 // offsets.
14887 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14888 CharUnits &Offset = LVal.getLValueOffset();
14889 uint64_t Offset64 = Offset.getQuantity();
14890 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14891 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14892 : Offset64 + Index64);
14893}
14894
14895bool DataRecursiveIntBinOpEvaluator::
14896 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14897 const BinaryOperator *E, APValue &Result) {
14898 if (E->getOpcode() == BO_Comma) {
14899 if (RHSResult.Failed)
14900 return false;
14901 Result = RHSResult.Val;
14902 return true;
14903 }
14904
14905 if (E->isLogicalOp()) {
14906 bool lhsResult, rhsResult;
14907 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14908 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14909
14910 if (LHSIsOK) {
14911 if (RHSIsOK) {
14912 if (E->getOpcode() == BO_LOr)
14913 return Success(lhsResult || rhsResult, E, Result);
14914 else
14915 return Success(lhsResult && rhsResult, E, Result);
14916 }
14917 } else {
14918 if (RHSIsOK) {
14919 // We can't evaluate the LHS; however, sometimes the result
14920 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14921 if (rhsResult == (E->getOpcode() == BO_LOr))
14922 return Success(rhsResult, E, Result);
14923 }
14924 }
14925
14926 return false;
14927 }
14928
14929 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14931
14932 if (LHSResult.Failed || RHSResult.Failed)
14933 return false;
14934
14935 const APValue &LHSVal = LHSResult.Val;
14936 const APValue &RHSVal = RHSResult.Val;
14937
14938 // Handle cases like (unsigned long)&a + 4.
14939 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14940 Result = LHSVal;
14941 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14942 return true;
14943 }
14944
14945 // Handle cases like 4 + (unsigned long)&a
14946 if (E->getOpcode() == BO_Add &&
14947 RHSVal.isLValue() && LHSVal.isInt()) {
14948 Result = RHSVal;
14949 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14950 return true;
14951 }
14952
14953 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14954 // Handle (intptr_t)&&A - (intptr_t)&&B.
14955 if (!LHSVal.getLValueOffset().isZero() ||
14956 !RHSVal.getLValueOffset().isZero())
14957 return false;
14958 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14959 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14960 if (!LHSExpr || !RHSExpr)
14961 return false;
14962 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14963 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14964 if (!LHSAddrExpr || !RHSAddrExpr)
14965 return false;
14966 // Make sure both labels come from the same function.
14967 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14968 RHSAddrExpr->getLabel()->getDeclContext())
14969 return false;
14970 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14971 return true;
14972 }
14973
14974 // All the remaining cases expect both operands to be an integer
14975 if (!LHSVal.isInt() || !RHSVal.isInt())
14976 return Error(E);
14977
14978 // Set up the width and signedness manually, in case it can't be deduced
14979 // from the operation we're performing.
14980 // FIXME: Don't do this in the cases where we can deduce it.
14981 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14983 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14984 RHSVal.getInt(), Value))
14985 return false;
14986 return Success(Value, E, Result);
14987}
14988
14989void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14990 Job &job = Queue.back();
14991
14992 switch (job.Kind) {
14993 case Job::AnyExprKind: {
14994 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14995 if (shouldEnqueue(Bop)) {
14996 job.Kind = Job::BinOpKind;
14997 enqueue(Bop->getLHS());
14998 return;
14999 }
15000 }
15001
15002 EvaluateExpr(job.E, Result);
15003 Queue.pop_back();
15004 return;
15005 }
15006
15007 case Job::BinOpKind: {
15008 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15009 bool SuppressRHSDiags = false;
15010 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
15011 Queue.pop_back();
15012 return;
15013 }
15014 if (SuppressRHSDiags)
15015 job.startSpeculativeEval(Info);
15016 job.LHSResult.swap(Result);
15017 job.Kind = Job::BinOpVisitedLHSKind;
15018 enqueue(Bop->getRHS());
15019 return;
15020 }
15021
15022 case Job::BinOpVisitedLHSKind: {
15023 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
15024 EvalResult RHS;
15025 RHS.swap(Result);
15026 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
15027 Queue.pop_back();
15028 return;
15029 }
15030 }
15031
15032 llvm_unreachable("Invalid Job::Kind!");
15033}
15034
15035namespace {
15036enum class CmpResult {
15037 Unequal,
15038 Less,
15039 Equal,
15040 Greater,
15041 Unordered,
15042};
15043}
15044
15045template <class SuccessCB, class AfterCB>
15046static bool
15048 SuccessCB &&Success, AfterCB &&DoAfter) {
15049 assert(!E->isValueDependent());
15050 assert(E->isComparisonOp() && "expected comparison operator");
15051 assert((E->getOpcode() == BO_Cmp ||
15053 "unsupported binary expression evaluation");
15054 auto Error = [&](const Expr *E) {
15055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15056 return false;
15057 };
15058
15059 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
15060 bool IsEquality = E->isEqualityOp();
15061
15062 QualType LHSTy = E->getLHS()->getType();
15063 QualType RHSTy = E->getRHS()->getType();
15064
15065 if (LHSTy->isIntegralOrEnumerationType() &&
15066 RHSTy->isIntegralOrEnumerationType()) {
15067 APSInt LHS, RHS;
15068 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
15069 if (!LHSOK && !Info.noteFailure())
15070 return false;
15071 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
15072 return false;
15073 if (LHS < RHS)
15074 return Success(CmpResult::Less, E);
15075 if (LHS > RHS)
15076 return Success(CmpResult::Greater, E);
15077 return Success(CmpResult::Equal, E);
15078 }
15079
15080 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
15081 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
15082 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
15083
15084 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
15085 if (!LHSOK && !Info.noteFailure())
15086 return false;
15087 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
15088 return false;
15089 if (LHSFX < RHSFX)
15090 return Success(CmpResult::Less, E);
15091 if (LHSFX > RHSFX)
15092 return Success(CmpResult::Greater, E);
15093 return Success(CmpResult::Equal, E);
15094 }
15095
15096 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
15097 ComplexValue LHS, RHS;
15098 bool LHSOK;
15099 if (E->isAssignmentOp()) {
15100 LValue LV;
15101 EvaluateLValue(E->getLHS(), LV, Info);
15102 LHSOK = false;
15103 } else if (LHSTy->isRealFloatingType()) {
15104 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
15105 if (LHSOK) {
15106 LHS.makeComplexFloat();
15107 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
15108 }
15109 } else {
15110 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
15111 }
15112 if (!LHSOK && !Info.noteFailure())
15113 return false;
15114
15115 if (E->getRHS()->getType()->isRealFloatingType()) {
15116 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
15117 return false;
15118 RHS.makeComplexFloat();
15119 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
15120 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15121 return false;
15122
15123 if (LHS.isComplexFloat()) {
15124 APFloat::cmpResult CR_r =
15125 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
15126 APFloat::cmpResult CR_i =
15127 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
15128 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
15129 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15130 } else {
15131 assert(IsEquality && "invalid complex comparison");
15132 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
15133 LHS.getComplexIntImag() == RHS.getComplexIntImag();
15134 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
15135 }
15136 }
15137
15138 if (LHSTy->isRealFloatingType() &&
15139 RHSTy->isRealFloatingType()) {
15140 APFloat RHS(0.0), LHS(0.0);
15141
15142 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
15143 if (!LHSOK && !Info.noteFailure())
15144 return false;
15145
15146 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
15147 return false;
15148
15149 assert(E->isComparisonOp() && "Invalid binary operator!");
15150 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
15151 if (!Info.InConstantContext &&
15152 APFloatCmpResult == APFloat::cmpUnordered &&
15154 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
15155 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
15156 return false;
15157 }
15158 auto GetCmpRes = [&]() {
15159 switch (APFloatCmpResult) {
15160 case APFloat::cmpEqual:
15161 return CmpResult::Equal;
15162 case APFloat::cmpLessThan:
15163 return CmpResult::Less;
15164 case APFloat::cmpGreaterThan:
15165 return CmpResult::Greater;
15166 case APFloat::cmpUnordered:
15167 return CmpResult::Unordered;
15168 }
15169 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
15170 };
15171 return Success(GetCmpRes(), E);
15172 }
15173
15174 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
15175 LValue LHSValue, RHSValue;
15176
15177 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15178 if (!LHSOK && !Info.noteFailure())
15179 return false;
15180
15181 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15182 return false;
15183
15184 // Reject differing bases from the normal codepath; we special-case
15185 // comparisons to null.
15186 if (!HasSameBase(LHSValue, RHSValue)) {
15187 // Bail out early if we're checking potential constant expression.
15188 // Otherwise, prefer to diagnose other issues.
15189 if (Info.checkingPotentialConstantExpression() &&
15190 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15191 return false;
15192 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
15193 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15194 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15195 Info.FFDiag(E, DiagID)
15196 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
15197 return false;
15198 };
15199 // Inequalities and subtractions between unrelated pointers have
15200 // unspecified or undefined behavior.
15201 if (!IsEquality)
15202 return DiagComparison(
15203 diag::note_constexpr_pointer_comparison_unspecified);
15204 // A constant address may compare equal to the address of a symbol.
15205 // The one exception is that address of an object cannot compare equal
15206 // to a null pointer constant.
15207 // TODO: Should we restrict this to actual null pointers, and exclude the
15208 // case of zero cast to pointer type?
15209 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
15210 (!RHSValue.Base && !RHSValue.Offset.isZero()))
15211 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
15212 !RHSValue.Base);
15213 // C++2c [intro.object]/10:
15214 // Two objects [...] may have the same address if [...] they are both
15215 // potentially non-unique objects.
15216 // C++2c [intro.object]/9:
15217 // An object is potentially non-unique if it is a string literal object,
15218 // the backing array of an initializer list, or a subobject thereof.
15219 //
15220 // This makes the comparison result unspecified, so it's not a constant
15221 // expression.
15222 //
15223 // TODO: Do we need to handle the initializer list case here?
15224 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15225 return DiagComparison(diag::note_constexpr_literal_comparison);
15226 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
15227 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
15228 !IsOpaqueConstantCall(LHSValue));
15229 // We can't tell whether weak symbols will end up pointing to the same
15230 // object.
15231 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
15232 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
15233 !IsWeakLValue(LHSValue));
15234 // We can't compare the address of the start of one object with the
15235 // past-the-end address of another object, per C++ DR1652.
15236 if (LHSValue.Base && LHSValue.Offset.isZero() &&
15237 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
15238 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15239 true);
15240 if (RHSValue.Base && RHSValue.Offset.isZero() &&
15241 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
15242 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15243 false);
15244 // We can't tell whether an object is at the same address as another
15245 // zero sized object.
15246 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
15247 (LHSValue.Base && isZeroSized(RHSValue)))
15248 return DiagComparison(
15249 diag::note_constexpr_pointer_comparison_zero_sized);
15250 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
15251 return DiagComparison(
15252 diag::note_constexpr_pointer_comparison_unspecified);
15253 // FIXME: Verify both variables are live.
15254 return Success(CmpResult::Unequal, E);
15255 }
15256
15257 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15258 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15259
15260 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15261 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15262
15263 // C++11 [expr.rel]p2:
15264 // - If two pointers point to non-static data members of the same object,
15265 // or to subobjects or array elements fo such members, recursively, the
15266 // pointer to the later declared member compares greater provided the
15267 // two members have the same access control and provided their class is
15268 // not a union.
15269 // [...]
15270 // - Otherwise pointer comparisons are unspecified.
15271 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
15272 bool WasArrayIndex;
15273 unsigned Mismatch = FindDesignatorMismatch(
15274 LHSValue.Base.isNull() ? QualType()
15275 : getType(LHSValue.Base).getNonReferenceType(),
15276 LHSDesignator, RHSDesignator, WasArrayIndex);
15277 // At the point where the designators diverge, the comparison has a
15278 // specified value if:
15279 // - we are comparing array indices
15280 // - we are comparing fields of a union, or fields with the same access
15281 // Otherwise, the result is unspecified and thus the comparison is not a
15282 // constant expression.
15283 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
15284 Mismatch < RHSDesignator.Entries.size()) {
15285 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
15286 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
15287 if (!LF && !RF)
15288 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
15289 else if (!LF)
15290 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15291 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
15292 << RF->getParent() << RF;
15293 else if (!RF)
15294 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15295 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
15296 << LF->getParent() << LF;
15297 else if (!LF->getParent()->isUnion() &&
15298 LF->getAccess() != RF->getAccess())
15299 Info.CCEDiag(E,
15300 diag::note_constexpr_pointer_comparison_differing_access)
15301 << LF << LF->getAccess() << RF << RF->getAccess()
15302 << LF->getParent();
15303 }
15304 }
15305
15306 // The comparison here must be unsigned, and performed with the same
15307 // width as the pointer.
15308 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
15309 uint64_t CompareLHS = LHSOffset.getQuantity();
15310 uint64_t CompareRHS = RHSOffset.getQuantity();
15311 assert(PtrSize <= 64 && "Unexpected pointer width");
15312 uint64_t Mask = ~0ULL >> (64 - PtrSize);
15313 CompareLHS &= Mask;
15314 CompareRHS &= Mask;
15315
15316 // If there is a base and this is a relational operator, we can only
15317 // compare pointers within the object in question; otherwise, the result
15318 // depends on where the object is located in memory.
15319 if (!LHSValue.Base.isNull() && IsRelational) {
15320 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
15321 if (BaseTy->isIncompleteType())
15322 return Error(E);
15323 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
15324 uint64_t OffsetLimit = Size.getQuantity();
15325 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
15326 return Error(E);
15327 }
15328
15329 if (CompareLHS < CompareRHS)
15330 return Success(CmpResult::Less, E);
15331 if (CompareLHS > CompareRHS)
15332 return Success(CmpResult::Greater, E);
15333 return Success(CmpResult::Equal, E);
15334 }
15335
15336 if (LHSTy->isMemberPointerType()) {
15337 assert(IsEquality && "unexpected member pointer operation");
15338 assert(RHSTy->isMemberPointerType() && "invalid comparison");
15339
15340 MemberPtr LHSValue, RHSValue;
15341
15342 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
15343 if (!LHSOK && !Info.noteFailure())
15344 return false;
15345
15346 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15347 return false;
15348
15349 // If either operand is a pointer to a weak function, the comparison is not
15350 // constant.
15351 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
15352 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15353 << LHSValue.getDecl();
15354 return false;
15355 }
15356 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
15357 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15358 << RHSValue.getDecl();
15359 return false;
15360 }
15361
15362 // C++11 [expr.eq]p2:
15363 // If both operands are null, they compare equal. Otherwise if only one is
15364 // null, they compare unequal.
15365 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
15366 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
15367 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15368 }
15369
15370 // Otherwise if either is a pointer to a virtual member function, the
15371 // result is unspecified.
15372 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
15373 if (MD->isVirtual())
15374 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15375 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
15376 if (MD->isVirtual())
15377 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15378
15379 // Otherwise they compare equal if and only if they would refer to the
15380 // same member of the same most derived object or the same subobject if
15381 // they were dereferenced with a hypothetical object of the associated
15382 // class type.
15383 bool Equal = LHSValue == RHSValue;
15384 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15385 }
15386
15387 if (LHSTy->isNullPtrType()) {
15388 assert(E->isComparisonOp() && "unexpected nullptr operation");
15389 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
15390 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
15391 // are compared, the result is true of the operator is <=, >= or ==, and
15392 // false otherwise.
15393 LValue Res;
15394 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
15395 !EvaluatePointer(E->getRHS(), Res, Info))
15396 return false;
15397 return Success(CmpResult::Equal, E);
15398 }
15399
15400 return DoAfter();
15401}
15402
15403bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
15404 if (!CheckLiteralType(Info, E))
15405 return false;
15406
15407 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15409 switch (CR) {
15410 case CmpResult::Unequal:
15411 llvm_unreachable("should never produce Unequal for three-way comparison");
15412 case CmpResult::Less:
15413 CCR = ComparisonCategoryResult::Less;
15414 break;
15415 case CmpResult::Equal:
15416 CCR = ComparisonCategoryResult::Equal;
15417 break;
15418 case CmpResult::Greater:
15419 CCR = ComparisonCategoryResult::Greater;
15420 break;
15421 case CmpResult::Unordered:
15422 CCR = ComparisonCategoryResult::Unordered;
15423 break;
15424 }
15425 // Evaluation succeeded. Lookup the information for the comparison category
15426 // type and fetch the VarDecl for the result.
15427 const ComparisonCategoryInfo &CmpInfo =
15428 Info.Ctx.CompCategories.getInfoForType(E->getType());
15429 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
15430 // Check and evaluate the result as a constant expression.
15431 LValue LV;
15432 LV.set(VD);
15433 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15434 return false;
15435 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15436 ConstantExprKind::Normal);
15437 };
15438 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15439 return ExprEvaluatorBaseTy::VisitBinCmp(E);
15440 });
15441}
15442
15443bool RecordExprEvaluator::VisitCXXParenListInitExpr(
15444 const CXXParenListInitExpr *E) {
15445 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
15446}
15447
15448bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15449 // We don't support assignment in C. C++ assignments don't get here because
15450 // assignment is an lvalue in C++.
15451 if (E->isAssignmentOp()) {
15452 Error(E);
15453 if (!Info.noteFailure())
15454 return false;
15455 }
15456
15457 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
15458 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
15459
15460 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
15462 "DataRecursiveIntBinOpEvaluator should have handled integral types");
15463
15464 if (E->isComparisonOp()) {
15465 // Evaluate builtin binary comparisons by evaluating them as three-way
15466 // comparisons and then translating the result.
15467 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15468 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
15469 "should only produce Unequal for equality comparisons");
15470 bool IsEqual = CR == CmpResult::Equal,
15471 IsLess = CR == CmpResult::Less,
15472 IsGreater = CR == CmpResult::Greater;
15473 auto Op = E->getOpcode();
15474 switch (Op) {
15475 default:
15476 llvm_unreachable("unsupported binary operator");
15477 case BO_EQ:
15478 case BO_NE:
15479 return Success(IsEqual == (Op == BO_EQ), E);
15480 case BO_LT:
15481 return Success(IsLess, E);
15482 case BO_GT:
15483 return Success(IsGreater, E);
15484 case BO_LE:
15485 return Success(IsEqual || IsLess, E);
15486 case BO_GE:
15487 return Success(IsEqual || IsGreater, E);
15488 }
15489 };
15490 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15491 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15492 });
15493 }
15494
15495 QualType LHSTy = E->getLHS()->getType();
15496 QualType RHSTy = E->getRHS()->getType();
15497
15498 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
15499 E->getOpcode() == BO_Sub) {
15500 LValue LHSValue, RHSValue;
15501
15502 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15503 if (!LHSOK && !Info.noteFailure())
15504 return false;
15505
15506 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15507 return false;
15508
15509 // Reject differing bases from the normal codepath; we special-case
15510 // comparisons to null.
15511 if (!HasSameBase(LHSValue, RHSValue)) {
15512 if (Info.checkingPotentialConstantExpression() &&
15513 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
15514 return false;
15515
15516 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
15517 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
15518
15519 auto DiagArith = [&](unsigned DiagID) {
15520 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15521 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15522 Info.FFDiag(E, DiagID) << LHS << RHS;
15523 if (LHSExpr && LHSExpr == RHSExpr)
15524 Info.Note(LHSExpr->getExprLoc(),
15525 diag::note_constexpr_repeated_literal_eval)
15526 << LHSExpr->getSourceRange();
15527 return false;
15528 };
15529
15530 if (!LHSExpr || !RHSExpr)
15531 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
15532
15533 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15534 return DiagArith(diag::note_constexpr_literal_arith);
15535
15536 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15537 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15538 if (!LHSAddrExpr || !RHSAddrExpr)
15539 return Error(E);
15540 // Make sure both labels come from the same function.
15541 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15542 RHSAddrExpr->getLabel()->getDeclContext())
15543 return Error(E);
15544 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
15545 }
15546 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15547 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15548
15549 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15550 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15551
15552 // C++11 [expr.add]p6:
15553 // Unless both pointers point to elements of the same array object, or
15554 // one past the last element of the array object, the behavior is
15555 // undefined.
15556 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
15557 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
15558 RHSDesignator))
15559 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
15560
15561 QualType Type = E->getLHS()->getType();
15562 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
15563
15564 CharUnits ElementSize;
15565 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
15566 return false;
15567
15568 // As an extension, a type may have zero size (empty struct or union in
15569 // C, array of zero length). Pointer subtraction in such cases has
15570 // undefined behavior, so is not constant.
15571 if (ElementSize.isZero()) {
15572 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
15573 << ElementType;
15574 return false;
15575 }
15576
15577 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
15578 // and produce incorrect results when it overflows. Such behavior
15579 // appears to be non-conforming, but is common, so perhaps we should
15580 // assume the standard intended for such cases to be undefined behavior
15581 // and check for them.
15582
15583 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
15584 // overflow in the final conversion to ptrdiff_t.
15585 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
15586 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
15587 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
15588 false);
15589 APSInt TrueResult = (LHS - RHS) / ElemSize;
15590 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
15591
15592 if (Result.extend(65) != TrueResult &&
15593 !HandleOverflow(Info, E, TrueResult, E->getType()))
15594 return false;
15595 return Success(Result, E);
15596 }
15597
15598 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15599}
15600
15601/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
15602/// a result as the expression's type.
15603bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
15604 const UnaryExprOrTypeTraitExpr *E) {
15605 switch(E->getKind()) {
15606 case UETT_PreferredAlignOf:
15607 case UETT_AlignOf: {
15608 if (E->isArgumentType())
15609 return Success(
15610 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
15611 else
15612 return Success(
15613 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
15614 }
15615
15616 case UETT_PtrAuthTypeDiscriminator: {
15617 if (E->getArgumentType()->isDependentType())
15618 return false;
15619 return Success(
15621 }
15622 case UETT_VecStep: {
15623 QualType Ty = E->getTypeOfArgument();
15624
15625 if (Ty->isVectorType()) {
15626 unsigned n = Ty->castAs<VectorType>()->getNumElements();
15627
15628 // The vec_step built-in functions that take a 3-component
15629 // vector return 4. (OpenCL 1.1 spec 6.11.12)
15630 if (n == 3)
15631 n = 4;
15632
15633 return Success(n, E);
15634 } else
15635 return Success(1, E);
15636 }
15637
15638 case UETT_DataSizeOf:
15639 case UETT_SizeOf: {
15640 QualType SrcTy = E->getTypeOfArgument();
15641 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
15642 // the result is the size of the referenced type."
15643 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
15644 SrcTy = Ref->getPointeeType();
15645
15646 CharUnits Sizeof;
15647 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
15648 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
15649 : SizeOfType::SizeOf)) {
15650 return false;
15651 }
15652 return Success(Sizeof, E);
15653 }
15654 case UETT_OpenMPRequiredSimdAlign:
15655 assert(E->isArgumentType());
15656 return Success(
15657 Info.Ctx.toCharUnitsFromBits(
15659 .getQuantity(),
15660 E);
15661 case UETT_VectorElements: {
15662 QualType Ty = E->getTypeOfArgument();
15663 // If the vector has a fixed size, we can determine the number of elements
15664 // at compile time.
15665 if (const auto *VT = Ty->getAs<VectorType>())
15666 return Success(VT->getNumElements(), E);
15667
15668 assert(Ty->isSizelessVectorType());
15669 if (Info.InConstantContext)
15670 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
15671 << E->getSourceRange();
15672
15673 return false;
15674 }
15675 case UETT_CountOf: {
15676 QualType Ty = E->getTypeOfArgument();
15677 assert(Ty->isArrayType());
15678
15679 // We don't need to worry about array element qualifiers, so getting the
15680 // unsafe array type is fine.
15681 if (const auto *CAT =
15682 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
15683 return Success(CAT->getSize(), E);
15684 }
15685
15686 assert(!Ty->isConstantSizeType());
15687
15688 // If it's a variable-length array type, we need to check whether it is a
15689 // multidimensional array. If so, we need to check the size expression of
15690 // the VLA to see if it's a constant size. If so, we can return that value.
15691 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
15692 assert(VAT);
15693 if (VAT->getElementType()->isArrayType()) {
15694 // Variable array size expression could be missing (e.g. int a[*][10]) In
15695 // that case, it can't be a constant expression.
15696 if (!VAT->getSizeExpr()) {
15697 Info.FFDiag(E->getBeginLoc());
15698 return false;
15699 }
15700
15701 std::optional<APSInt> Res =
15702 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
15703 if (Res) {
15704 // The resulting value always has type size_t, so we need to make the
15705 // returned APInt have the correct sign and bit-width.
15706 APInt Val{
15707 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
15708 Res->getZExtValue()};
15709 return Success(Val, E);
15710 }
15711 }
15712
15713 // Definitely a variable-length type, which is not an ICE.
15714 // FIXME: Better diagnostic.
15715 Info.FFDiag(E->getBeginLoc());
15716 return false;
15717 }
15718 }
15719
15720 llvm_unreachable("unknown expr/type trait");
15721}
15722
15723bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
15724 CharUnits Result;
15725 unsigned n = OOE->getNumComponents();
15726 if (n == 0)
15727 return Error(OOE);
15728 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
15729 for (unsigned i = 0; i != n; ++i) {
15730 OffsetOfNode ON = OOE->getComponent(i);
15731 switch (ON.getKind()) {
15732 case OffsetOfNode::Array: {
15733 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
15734 APSInt IdxResult;
15735 if (!EvaluateInteger(Idx, IdxResult, Info))
15736 return false;
15737 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
15738 if (!AT)
15739 return Error(OOE);
15740 CurrentType = AT->getElementType();
15741 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
15742 Result += IdxResult.getSExtValue() * ElementSize;
15743 break;
15744 }
15745
15746 case OffsetOfNode::Field: {
15747 FieldDecl *MemberDecl = ON.getField();
15748 const auto *RD = CurrentType->getAsRecordDecl();
15749 if (!RD)
15750 return Error(OOE);
15751 if (RD->isInvalidDecl()) return false;
15752 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15753 unsigned i = MemberDecl->getFieldIndex();
15754 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
15755 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
15756 CurrentType = MemberDecl->getType().getNonReferenceType();
15757 break;
15758 }
15759
15761 llvm_unreachable("dependent __builtin_offsetof");
15762
15763 case OffsetOfNode::Base: {
15764 CXXBaseSpecifier *BaseSpec = ON.getBase();
15765 if (BaseSpec->isVirtual())
15766 return Error(OOE);
15767
15768 // Find the layout of the class whose base we are looking into.
15769 const auto *RD = CurrentType->getAsCXXRecordDecl();
15770 if (!RD)
15771 return Error(OOE);
15772 if (RD->isInvalidDecl()) return false;
15773 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15774
15775 // Find the base class itself.
15776 CurrentType = BaseSpec->getType();
15777 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
15778 if (!BaseRD)
15779 return Error(OOE);
15780
15781 // Add the offset to the base.
15782 Result += RL.getBaseClassOffset(BaseRD);
15783 break;
15784 }
15785 }
15786 }
15787 return Success(Result, OOE);
15788}
15789
15790bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15791 switch (E->getOpcode()) {
15792 default:
15793 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
15794 // See C99 6.6p3.
15795 return Error(E);
15796 case UO_Extension:
15797 // FIXME: Should extension allow i-c-e extension expressions in its scope?
15798 // If so, we could clear the diagnostic ID.
15799 return Visit(E->getSubExpr());
15800 case UO_Plus:
15801 // The result is just the value.
15802 return Visit(E->getSubExpr());
15803 case UO_Minus: {
15804 if (!Visit(E->getSubExpr()))
15805 return false;
15806 if (!Result.isInt()) return Error(E);
15807 const APSInt &Value = Result.getInt();
15808 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
15809 if (Info.checkingForUndefinedBehavior())
15810 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15811 diag::warn_integer_constant_overflow)
15812 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
15813 /*UpperCase=*/true, /*InsertSeparators=*/true)
15814 << E->getType() << E->getSourceRange();
15815
15816 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
15817 E->getType()))
15818 return false;
15819 }
15820 return Success(-Value, E);
15821 }
15822 case UO_Not: {
15823 if (!Visit(E->getSubExpr()))
15824 return false;
15825 if (!Result.isInt()) return Error(E);
15826 return Success(~Result.getInt(), E);
15827 }
15828 case UO_LNot: {
15829 bool bres;
15830 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15831 return false;
15832 return Success(!bres, E);
15833 }
15834 }
15835}
15836
15837/// HandleCast - This is used to evaluate implicit or explicit casts where the
15838/// result type is integer.
15839bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
15840 const Expr *SubExpr = E->getSubExpr();
15841 QualType DestType = E->getType();
15842 QualType SrcType = SubExpr->getType();
15843
15844 switch (E->getCastKind()) {
15845 case CK_BaseToDerived:
15846 case CK_DerivedToBase:
15847 case CK_UncheckedDerivedToBase:
15848 case CK_Dynamic:
15849 case CK_ToUnion:
15850 case CK_ArrayToPointerDecay:
15851 case CK_FunctionToPointerDecay:
15852 case CK_NullToPointer:
15853 case CK_NullToMemberPointer:
15854 case CK_BaseToDerivedMemberPointer:
15855 case CK_DerivedToBaseMemberPointer:
15856 case CK_ReinterpretMemberPointer:
15857 case CK_ConstructorConversion:
15858 case CK_IntegralToPointer:
15859 case CK_ToVoid:
15860 case CK_VectorSplat:
15861 case CK_IntegralToFloating:
15862 case CK_FloatingCast:
15863 case CK_CPointerToObjCPointerCast:
15864 case CK_BlockPointerToObjCPointerCast:
15865 case CK_AnyPointerToBlockPointerCast:
15866 case CK_ObjCObjectLValueCast:
15867 case CK_FloatingRealToComplex:
15868 case CK_FloatingComplexToReal:
15869 case CK_FloatingComplexCast:
15870 case CK_FloatingComplexToIntegralComplex:
15871 case CK_IntegralRealToComplex:
15872 case CK_IntegralComplexCast:
15873 case CK_IntegralComplexToFloatingComplex:
15874 case CK_BuiltinFnToFnPtr:
15875 case CK_ZeroToOCLOpaqueType:
15876 case CK_NonAtomicToAtomic:
15877 case CK_AddressSpaceConversion:
15878 case CK_IntToOCLSampler:
15879 case CK_FloatingToFixedPoint:
15880 case CK_FixedPointToFloating:
15881 case CK_FixedPointCast:
15882 case CK_IntegralToFixedPoint:
15883 case CK_MatrixCast:
15884 case CK_HLSLAggregateSplatCast:
15885 llvm_unreachable("invalid cast kind for integral value");
15886
15887 case CK_BitCast:
15888 case CK_Dependent:
15889 case CK_LValueBitCast:
15890 case CK_ARCProduceObject:
15891 case CK_ARCConsumeObject:
15892 case CK_ARCReclaimReturnedObject:
15893 case CK_ARCExtendBlockObject:
15894 case CK_CopyAndAutoreleaseBlockObject:
15895 return Error(E);
15896
15897 case CK_UserDefinedConversion:
15898 case CK_LValueToRValue:
15899 case CK_AtomicToNonAtomic:
15900 case CK_NoOp:
15901 case CK_LValueToRValueBitCast:
15902 case CK_HLSLArrayRValue:
15903 case CK_HLSLElementwiseCast:
15904 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15905
15906 case CK_MemberPointerToBoolean:
15907 case CK_PointerToBoolean:
15908 case CK_IntegralToBoolean:
15909 case CK_FloatingToBoolean:
15910 case CK_BooleanToSignedIntegral:
15911 case CK_FloatingComplexToBoolean:
15912 case CK_IntegralComplexToBoolean: {
15913 bool BoolResult;
15914 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15915 return false;
15916 uint64_t IntResult = BoolResult;
15917 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15918 IntResult = (uint64_t)-1;
15919 return Success(IntResult, E);
15920 }
15921
15922 case CK_FixedPointToIntegral: {
15923 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15924 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15925 return false;
15926 bool Overflowed;
15927 llvm::APSInt Result = Src.convertToInt(
15928 Info.Ctx.getIntWidth(DestType),
15929 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15930 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15931 return false;
15932 return Success(Result, E);
15933 }
15934
15935 case CK_FixedPointToBoolean: {
15936 // Unsigned padding does not affect this.
15937 APValue Val;
15938 if (!Evaluate(Val, Info, SubExpr))
15939 return false;
15940 return Success(Val.getFixedPoint().getBoolValue(), E);
15941 }
15942
15943 case CK_IntegralCast: {
15944 if (!Visit(SubExpr))
15945 return false;
15946
15947 if (!Result.isInt()) {
15948 // Allow casts of address-of-label differences if they are no-ops
15949 // or narrowing. (The narrowing case isn't actually guaranteed to
15950 // be constant-evaluatable except in some narrow cases which are hard
15951 // to detect here. We let it through on the assumption the user knows
15952 // what they are doing.)
15953 if (Result.isAddrLabelDiff())
15954 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15955 // Only allow casts of lvalues if they are lossless.
15956 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15957 }
15958
15959 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
15960 const auto *ED = DestType->getAsEnumDecl();
15961 // Check that the value is within the range of the enumeration values.
15962 //
15963 // This corressponds to [expr.static.cast]p10 which says:
15964 // A value of integral or enumeration type can be explicitly converted
15965 // to a complete enumeration type ... If the enumeration type does not
15966 // have a fixed underlying type, the value is unchanged if the original
15967 // value is within the range of the enumeration values ([dcl.enum]), and
15968 // otherwise, the behavior is undefined.
15969 //
15970 // This was resolved as part of DR2338 which has CD5 status.
15971 if (!ED->isFixed()) {
15972 llvm::APInt Min;
15973 llvm::APInt Max;
15974
15975 ED->getValueRange(Max, Min);
15976 --Max;
15977
15978 if (ED->getNumNegativeBits() &&
15979 (Max.slt(Result.getInt().getSExtValue()) ||
15980 Min.sgt(Result.getInt().getSExtValue())))
15981 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15982 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15983 << Max.getSExtValue() << ED;
15984 else if (!ED->getNumNegativeBits() &&
15985 Max.ult(Result.getInt().getZExtValue()))
15986 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15987 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15988 << Max.getZExtValue() << ED;
15989 }
15990 }
15991
15992 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15993 Result.getInt()), E);
15994 }
15995
15996 case CK_PointerToIntegral: {
15997 CCEDiag(E, diag::note_constexpr_invalid_cast)
15998 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
15999 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
16000
16001 LValue LV;
16002 if (!EvaluatePointer(SubExpr, LV, Info))
16003 return false;
16004
16005 if (LV.getLValueBase()) {
16006 // Only allow based lvalue casts if they are lossless.
16007 // FIXME: Allow a larger integer size than the pointer size, and allow
16008 // narrowing back down to pointer width in subsequent integral casts.
16009 // FIXME: Check integer type's active bits, not its type size.
16010 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
16011 return Error(E);
16012
16013 LV.Designator.setInvalid();
16014 LV.moveInto(Result);
16015 return true;
16016 }
16017
16018 APSInt AsInt;
16019 APValue V;
16020 LV.moveInto(V);
16021 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
16022 llvm_unreachable("Can't cast this!");
16023
16024 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
16025 }
16026
16027 case CK_IntegralComplexToReal: {
16028 ComplexValue C;
16029 if (!EvaluateComplex(SubExpr, C, Info))
16030 return false;
16031 return Success(C.getComplexIntReal(), E);
16032 }
16033
16034 case CK_FloatingToIntegral: {
16035 APFloat F(0.0);
16036 if (!EvaluateFloat(SubExpr, F, Info))
16037 return false;
16038
16039 APSInt Value;
16040 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
16041 return false;
16042 return Success(Value, E);
16043 }
16044 case CK_HLSLVectorTruncation: {
16045 APValue Val;
16046 if (!EvaluateVector(SubExpr, Val, Info))
16047 return Error(E);
16048 return Success(Val.getVectorElt(0), E);
16049 }
16050 }
16051
16052 llvm_unreachable("unknown cast resulting in integral value");
16053}
16054
16055bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16056 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16057 ComplexValue LV;
16058 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16059 return false;
16060 if (!LV.isComplexInt())
16061 return Error(E);
16062 return Success(LV.getComplexIntReal(), E);
16063 }
16064
16065 return Visit(E->getSubExpr());
16066}
16067
16068bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16069 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
16070 ComplexValue LV;
16071 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
16072 return false;
16073 if (!LV.isComplexInt())
16074 return Error(E);
16075 return Success(LV.getComplexIntImag(), E);
16076 }
16077
16078 VisitIgnoredValue(E->getSubExpr());
16079 return Success(0, E);
16080}
16081
16082bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
16083 return Success(E->getPackLength(), E);
16084}
16085
16086bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
16087 return Success(E->getValue(), E);
16088}
16089
16090bool IntExprEvaluator::VisitConceptSpecializationExpr(
16091 const ConceptSpecializationExpr *E) {
16092 return Success(E->isSatisfied(), E);
16093}
16094
16095bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
16096 return Success(E->isSatisfied(), E);
16097}
16098
16099bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16100 switch (E->getOpcode()) {
16101 default:
16102 // Invalid unary operators
16103 return Error(E);
16104 case UO_Plus:
16105 // The result is just the value.
16106 return Visit(E->getSubExpr());
16107 case UO_Minus: {
16108 if (!Visit(E->getSubExpr())) return false;
16109 if (!Result.isFixedPoint())
16110 return Error(E);
16111 bool Overflowed;
16112 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
16113 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
16114 return false;
16115 return Success(Negated, E);
16116 }
16117 case UO_LNot: {
16118 bool bres;
16119 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
16120 return false;
16121 return Success(!bres, E);
16122 }
16123 }
16124}
16125
16126bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
16127 const Expr *SubExpr = E->getSubExpr();
16128 QualType DestType = E->getType();
16129 assert(DestType->isFixedPointType() &&
16130 "Expected destination type to be a fixed point type");
16131 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
16132
16133 switch (E->getCastKind()) {
16134 case CK_FixedPointCast: {
16135 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16136 if (!EvaluateFixedPoint(SubExpr, Src, Info))
16137 return false;
16138 bool Overflowed;
16139 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
16140 if (Overflowed) {
16141 if (Info.checkingForUndefinedBehavior())
16142 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16143 diag::warn_fixedpoint_constant_overflow)
16144 << Result.toString() << E->getType();
16145 if (!HandleOverflow(Info, E, Result, E->getType()))
16146 return false;
16147 }
16148 return Success(Result, E);
16149 }
16150 case CK_IntegralToFixedPoint: {
16151 APSInt Src;
16152 if (!EvaluateInteger(SubExpr, Src, Info))
16153 return false;
16154
16155 bool Overflowed;
16156 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
16157 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16158
16159 if (Overflowed) {
16160 if (Info.checkingForUndefinedBehavior())
16161 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16162 diag::warn_fixedpoint_constant_overflow)
16163 << IntResult.toString() << E->getType();
16164 if (!HandleOverflow(Info, E, IntResult, E->getType()))
16165 return false;
16166 }
16167
16168 return Success(IntResult, E);
16169 }
16170 case CK_FloatingToFixedPoint: {
16171 APFloat Src(0.0);
16172 if (!EvaluateFloat(SubExpr, Src, Info))
16173 return false;
16174
16175 bool Overflowed;
16176 APFixedPoint Result = APFixedPoint::getFromFloatValue(
16177 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
16178
16179 if (Overflowed) {
16180 if (Info.checkingForUndefinedBehavior())
16181 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16182 diag::warn_fixedpoint_constant_overflow)
16183 << Result.toString() << E->getType();
16184 if (!HandleOverflow(Info, E, Result, E->getType()))
16185 return false;
16186 }
16187
16188 return Success(Result, E);
16189 }
16190 case CK_NoOp:
16191 case CK_LValueToRValue:
16192 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16193 default:
16194 return Error(E);
16195 }
16196}
16197
16198bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16199 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16200 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16201
16202 const Expr *LHS = E->getLHS();
16203 const Expr *RHS = E->getRHS();
16204 FixedPointSemantics ResultFXSema =
16205 Info.Ctx.getFixedPointSemantics(E->getType());
16206
16207 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
16208 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
16209 return false;
16210 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
16211 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
16212 return false;
16213
16214 bool OpOverflow = false, ConversionOverflow = false;
16215 APFixedPoint Result(LHSFX.getSemantics());
16216 switch (E->getOpcode()) {
16217 case BO_Add: {
16218 Result = LHSFX.add(RHSFX, &OpOverflow)
16219 .convert(ResultFXSema, &ConversionOverflow);
16220 break;
16221 }
16222 case BO_Sub: {
16223 Result = LHSFX.sub(RHSFX, &OpOverflow)
16224 .convert(ResultFXSema, &ConversionOverflow);
16225 break;
16226 }
16227 case BO_Mul: {
16228 Result = LHSFX.mul(RHSFX, &OpOverflow)
16229 .convert(ResultFXSema, &ConversionOverflow);
16230 break;
16231 }
16232 case BO_Div: {
16233 if (RHSFX.getValue() == 0) {
16234 Info.FFDiag(E, diag::note_expr_divide_by_zero);
16235 return false;
16236 }
16237 Result = LHSFX.div(RHSFX, &OpOverflow)
16238 .convert(ResultFXSema, &ConversionOverflow);
16239 break;
16240 }
16241 case BO_Shl:
16242 case BO_Shr: {
16243 FixedPointSemantics LHSSema = LHSFX.getSemantics();
16244 llvm::APSInt RHSVal = RHSFX.getValue();
16245
16246 unsigned ShiftBW =
16247 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
16248 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
16249 // Embedded-C 4.1.6.2.2:
16250 // The right operand must be nonnegative and less than the total number
16251 // of (nonpadding) bits of the fixed-point operand ...
16252 if (RHSVal.isNegative())
16253 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
16254 else if (Amt != RHSVal)
16255 Info.CCEDiag(E, diag::note_constexpr_large_shift)
16256 << RHSVal << E->getType() << ShiftBW;
16257
16258 if (E->getOpcode() == BO_Shl)
16259 Result = LHSFX.shl(Amt, &OpOverflow);
16260 else
16261 Result = LHSFX.shr(Amt, &OpOverflow);
16262 break;
16263 }
16264 default:
16265 return false;
16266 }
16267 if (OpOverflow || ConversionOverflow) {
16268 if (Info.checkingForUndefinedBehavior())
16269 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16270 diag::warn_fixedpoint_constant_overflow)
16271 << Result.toString() << E->getType();
16272 if (!HandleOverflow(Info, E, Result, E->getType()))
16273 return false;
16274 }
16275 return Success(Result, E);
16276}
16277
16278//===----------------------------------------------------------------------===//
16279// Float Evaluation
16280//===----------------------------------------------------------------------===//
16281
16282namespace {
16283class FloatExprEvaluator
16284 : public ExprEvaluatorBase<FloatExprEvaluator> {
16285 APFloat &Result;
16286public:
16287 FloatExprEvaluator(EvalInfo &info, APFloat &result)
16288 : ExprEvaluatorBaseTy(info), Result(result) {}
16289
16290 bool Success(const APValue &V, const Expr *e) {
16291 Result = V.getFloat();
16292 return true;
16293 }
16294
16295 bool ZeroInitialization(const Expr *E) {
16296 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
16297 return true;
16298 }
16299
16300 bool VisitCallExpr(const CallExpr *E);
16301
16302 bool VisitUnaryOperator(const UnaryOperator *E);
16303 bool VisitBinaryOperator(const BinaryOperator *E);
16304 bool VisitFloatingLiteral(const FloatingLiteral *E);
16305 bool VisitCastExpr(const CastExpr *E);
16306
16307 bool VisitUnaryReal(const UnaryOperator *E);
16308 bool VisitUnaryImag(const UnaryOperator *E);
16309
16310 // FIXME: Missing: array subscript of vector, member of vector
16311};
16312} // end anonymous namespace
16313
16314static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
16315 assert(!E->isValueDependent());
16316 assert(E->isPRValue() && E->getType()->isRealFloatingType());
16317 return FloatExprEvaluator(Info, Result).Visit(E);
16318}
16319
16320static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
16321 QualType ResultTy,
16322 const Expr *Arg,
16323 bool SNaN,
16324 llvm::APFloat &Result) {
16325 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
16326 if (!S) return false;
16327
16328 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
16329
16330 llvm::APInt fill;
16331
16332 // Treat empty strings as if they were zero.
16333 if (S->getString().empty())
16334 fill = llvm::APInt(32, 0);
16335 else if (S->getString().getAsInteger(0, fill))
16336 return false;
16337
16338 if (Context.getTargetInfo().isNan2008()) {
16339 if (SNaN)
16340 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16341 else
16342 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16343 } else {
16344 // Prior to IEEE 754-2008, architectures were allowed to choose whether
16345 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
16346 // a different encoding to what became a standard in 2008, and for pre-
16347 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
16348 // sNaN. This is now known as "legacy NaN" encoding.
16349 if (SNaN)
16350 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16351 else
16352 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16353 }
16354
16355 return true;
16356}
16357
16358bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
16359 if (!IsConstantEvaluatedBuiltinCall(E))
16360 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16361
16362 switch (E->getBuiltinCallee()) {
16363 default:
16364 return false;
16365
16366 case Builtin::BI__builtin_huge_val:
16367 case Builtin::BI__builtin_huge_valf:
16368 case Builtin::BI__builtin_huge_vall:
16369 case Builtin::BI__builtin_huge_valf16:
16370 case Builtin::BI__builtin_huge_valf128:
16371 case Builtin::BI__builtin_inf:
16372 case Builtin::BI__builtin_inff:
16373 case Builtin::BI__builtin_infl:
16374 case Builtin::BI__builtin_inff16:
16375 case Builtin::BI__builtin_inff128: {
16376 const llvm::fltSemantics &Sem =
16377 Info.Ctx.getFloatTypeSemantics(E->getType());
16378 Result = llvm::APFloat::getInf(Sem);
16379 return true;
16380 }
16381
16382 case Builtin::BI__builtin_nans:
16383 case Builtin::BI__builtin_nansf:
16384 case Builtin::BI__builtin_nansl:
16385 case Builtin::BI__builtin_nansf16:
16386 case Builtin::BI__builtin_nansf128:
16387 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16388 true, Result))
16389 return Error(E);
16390 return true;
16391
16392 case Builtin::BI__builtin_nan:
16393 case Builtin::BI__builtin_nanf:
16394 case Builtin::BI__builtin_nanl:
16395 case Builtin::BI__builtin_nanf16:
16396 case Builtin::BI__builtin_nanf128:
16397 // If this is __builtin_nan() turn this into a nan, otherwise we
16398 // can't constant fold it.
16399 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16400 false, Result))
16401 return Error(E);
16402 return true;
16403
16404 case Builtin::BI__builtin_elementwise_abs:
16405 case Builtin::BI__builtin_fabs:
16406 case Builtin::BI__builtin_fabsf:
16407 case Builtin::BI__builtin_fabsl:
16408 case Builtin::BI__builtin_fabsf128:
16409 // The C standard says "fabs raises no floating-point exceptions,
16410 // even if x is a signaling NaN. The returned value is independent of
16411 // the current rounding direction mode." Therefore constant folding can
16412 // proceed without regard to the floating point settings.
16413 // Reference, WG14 N2478 F.10.4.3
16414 if (!EvaluateFloat(E->getArg(0), Result, Info))
16415 return false;
16416
16417 if (Result.isNegative())
16418 Result.changeSign();
16419 return true;
16420
16421 case Builtin::BI__arithmetic_fence:
16422 return EvaluateFloat(E->getArg(0), Result, Info);
16423
16424 // FIXME: Builtin::BI__builtin_powi
16425 // FIXME: Builtin::BI__builtin_powif
16426 // FIXME: Builtin::BI__builtin_powil
16427
16428 case Builtin::BI__builtin_copysign:
16429 case Builtin::BI__builtin_copysignf:
16430 case Builtin::BI__builtin_copysignl:
16431 case Builtin::BI__builtin_copysignf128: {
16432 APFloat RHS(0.);
16433 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16434 !EvaluateFloat(E->getArg(1), RHS, Info))
16435 return false;
16436 Result.copySign(RHS);
16437 return true;
16438 }
16439
16440 case Builtin::BI__builtin_fmax:
16441 case Builtin::BI__builtin_fmaxf:
16442 case Builtin::BI__builtin_fmaxl:
16443 case Builtin::BI__builtin_fmaxf16:
16444 case Builtin::BI__builtin_fmaxf128: {
16445 APFloat RHS(0.);
16446 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16447 !EvaluateFloat(E->getArg(1), RHS, Info))
16448 return false;
16449 Result = maxnum(Result, RHS);
16450 return true;
16451 }
16452
16453 case Builtin::BI__builtin_fmin:
16454 case Builtin::BI__builtin_fminf:
16455 case Builtin::BI__builtin_fminl:
16456 case Builtin::BI__builtin_fminf16:
16457 case Builtin::BI__builtin_fminf128: {
16458 APFloat RHS(0.);
16459 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16460 !EvaluateFloat(E->getArg(1), RHS, Info))
16461 return false;
16462 Result = minnum(Result, RHS);
16463 return true;
16464 }
16465
16466 case Builtin::BI__builtin_fmaximum_num:
16467 case Builtin::BI__builtin_fmaximum_numf:
16468 case Builtin::BI__builtin_fmaximum_numl:
16469 case Builtin::BI__builtin_fmaximum_numf16:
16470 case Builtin::BI__builtin_fmaximum_numf128: {
16471 APFloat RHS(0.);
16472 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16473 !EvaluateFloat(E->getArg(1), RHS, Info))
16474 return false;
16475 Result = maximumnum(Result, RHS);
16476 return true;
16477 }
16478
16479 case Builtin::BI__builtin_fminimum_num:
16480 case Builtin::BI__builtin_fminimum_numf:
16481 case Builtin::BI__builtin_fminimum_numl:
16482 case Builtin::BI__builtin_fminimum_numf16:
16483 case Builtin::BI__builtin_fminimum_numf128: {
16484 APFloat RHS(0.);
16485 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16486 !EvaluateFloat(E->getArg(1), RHS, Info))
16487 return false;
16488 Result = minimumnum(Result, RHS);
16489 return true;
16490 }
16491
16492 case Builtin::BI__builtin_elementwise_fma: {
16493 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
16494 !E->getArg(2)->isPRValue()) {
16495 return false;
16496 }
16497 APFloat SourceY(0.), SourceZ(0.);
16498 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16499 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
16500 !EvaluateFloat(E->getArg(2), SourceZ, Info))
16501 return false;
16502 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
16503 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
16504 return true;
16505 }
16506 }
16507}
16508
16509bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16510 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16511 ComplexValue CV;
16512 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16513 return false;
16514 Result = CV.FloatReal;
16515 return true;
16516 }
16517
16518 return Visit(E->getSubExpr());
16519}
16520
16521bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16522 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16523 ComplexValue CV;
16524 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16525 return false;
16526 Result = CV.FloatImag;
16527 return true;
16528 }
16529
16530 VisitIgnoredValue(E->getSubExpr());
16531 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
16532 Result = llvm::APFloat::getZero(Sem);
16533 return true;
16534}
16535
16536bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16537 switch (E->getOpcode()) {
16538 default: return Error(E);
16539 case UO_Plus:
16540 return EvaluateFloat(E->getSubExpr(), Result, Info);
16541 case UO_Minus:
16542 // In C standard, WG14 N2478 F.3 p4
16543 // "the unary - raises no floating point exceptions,
16544 // even if the operand is signalling."
16545 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
16546 return false;
16547 Result.changeSign();
16548 return true;
16549 }
16550}
16551
16552bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16553 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16554 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16555
16556 APFloat RHS(0.0);
16557 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
16558 if (!LHSOK && !Info.noteFailure())
16559 return false;
16560 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
16561 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
16562}
16563
16564bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
16565 Result = E->getValue();
16566 return true;
16567}
16568
16569bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
16570 const Expr* SubExpr = E->getSubExpr();
16571
16572 switch (E->getCastKind()) {
16573 default:
16574 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16575
16576 case CK_IntegralToFloating: {
16577 APSInt IntResult;
16578 const FPOptions FPO = E->getFPFeaturesInEffect(
16579 Info.Ctx.getLangOpts());
16580 return EvaluateInteger(SubExpr, IntResult, Info) &&
16581 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
16582 IntResult, E->getType(), Result);
16583 }
16584
16585 case CK_FixedPointToFloating: {
16586 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16587 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
16588 return false;
16589 Result =
16590 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
16591 return true;
16592 }
16593
16594 case CK_FloatingCast: {
16595 if (!Visit(SubExpr))
16596 return false;
16597 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
16598 Result);
16599 }
16600
16601 case CK_FloatingComplexToReal: {
16602 ComplexValue V;
16603 if (!EvaluateComplex(SubExpr, V, Info))
16604 return false;
16605 Result = V.getComplexFloatReal();
16606 return true;
16607 }
16608 case CK_HLSLVectorTruncation: {
16609 APValue Val;
16610 if (!EvaluateVector(SubExpr, Val, Info))
16611 return Error(E);
16612 return Success(Val.getVectorElt(0), E);
16613 }
16614 }
16615}
16616
16617//===----------------------------------------------------------------------===//
16618// Complex Evaluation (for float and integer)
16619//===----------------------------------------------------------------------===//
16620
16621namespace {
16622class ComplexExprEvaluator
16623 : public ExprEvaluatorBase<ComplexExprEvaluator> {
16624 ComplexValue &Result;
16625
16626public:
16627 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
16628 : ExprEvaluatorBaseTy(info), Result(Result) {}
16629
16630 bool Success(const APValue &V, const Expr *e) {
16631 Result.setFrom(V);
16632 return true;
16633 }
16634
16635 bool ZeroInitialization(const Expr *E);
16636
16637 //===--------------------------------------------------------------------===//
16638 // Visitor Methods
16639 //===--------------------------------------------------------------------===//
16640
16641 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
16642 bool VisitCastExpr(const CastExpr *E);
16643 bool VisitBinaryOperator(const BinaryOperator *E);
16644 bool VisitUnaryOperator(const UnaryOperator *E);
16645 bool VisitInitListExpr(const InitListExpr *E);
16646 bool VisitCallExpr(const CallExpr *E);
16647};
16648} // end anonymous namespace
16649
16650static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
16651 EvalInfo &Info) {
16652 assert(!E->isValueDependent());
16653 assert(E->isPRValue() && E->getType()->isAnyComplexType());
16654 return ComplexExprEvaluator(Info, Result).Visit(E);
16655}
16656
16657bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
16658 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
16659 if (ElemTy->isRealFloatingType()) {
16660 Result.makeComplexFloat();
16661 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
16662 Result.FloatReal = Zero;
16663 Result.FloatImag = Zero;
16664 } else {
16665 Result.makeComplexInt();
16666 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
16667 Result.IntReal = Zero;
16668 Result.IntImag = Zero;
16669 }
16670 return true;
16671}
16672
16673bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
16674 const Expr* SubExpr = E->getSubExpr();
16675
16676 if (SubExpr->getType()->isRealFloatingType()) {
16677 Result.makeComplexFloat();
16678 APFloat &Imag = Result.FloatImag;
16679 if (!EvaluateFloat(SubExpr, Imag, Info))
16680 return false;
16681
16682 Result.FloatReal = APFloat(Imag.getSemantics());
16683 return true;
16684 } else {
16685 assert(SubExpr->getType()->isIntegerType() &&
16686 "Unexpected imaginary literal.");
16687
16688 Result.makeComplexInt();
16689 APSInt &Imag = Result.IntImag;
16690 if (!EvaluateInteger(SubExpr, Imag, Info))
16691 return false;
16692
16693 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
16694 return true;
16695 }
16696}
16697
16698bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
16699
16700 switch (E->getCastKind()) {
16701 case CK_BitCast:
16702 case CK_BaseToDerived:
16703 case CK_DerivedToBase:
16704 case CK_UncheckedDerivedToBase:
16705 case CK_Dynamic:
16706 case CK_ToUnion:
16707 case CK_ArrayToPointerDecay:
16708 case CK_FunctionToPointerDecay:
16709 case CK_NullToPointer:
16710 case CK_NullToMemberPointer:
16711 case CK_BaseToDerivedMemberPointer:
16712 case CK_DerivedToBaseMemberPointer:
16713 case CK_MemberPointerToBoolean:
16714 case CK_ReinterpretMemberPointer:
16715 case CK_ConstructorConversion:
16716 case CK_IntegralToPointer:
16717 case CK_PointerToIntegral:
16718 case CK_PointerToBoolean:
16719 case CK_ToVoid:
16720 case CK_VectorSplat:
16721 case CK_IntegralCast:
16722 case CK_BooleanToSignedIntegral:
16723 case CK_IntegralToBoolean:
16724 case CK_IntegralToFloating:
16725 case CK_FloatingToIntegral:
16726 case CK_FloatingToBoolean:
16727 case CK_FloatingCast:
16728 case CK_CPointerToObjCPointerCast:
16729 case CK_BlockPointerToObjCPointerCast:
16730 case CK_AnyPointerToBlockPointerCast:
16731 case CK_ObjCObjectLValueCast:
16732 case CK_FloatingComplexToReal:
16733 case CK_FloatingComplexToBoolean:
16734 case CK_IntegralComplexToReal:
16735 case CK_IntegralComplexToBoolean:
16736 case CK_ARCProduceObject:
16737 case CK_ARCConsumeObject:
16738 case CK_ARCReclaimReturnedObject:
16739 case CK_ARCExtendBlockObject:
16740 case CK_CopyAndAutoreleaseBlockObject:
16741 case CK_BuiltinFnToFnPtr:
16742 case CK_ZeroToOCLOpaqueType:
16743 case CK_NonAtomicToAtomic:
16744 case CK_AddressSpaceConversion:
16745 case CK_IntToOCLSampler:
16746 case CK_FloatingToFixedPoint:
16747 case CK_FixedPointToFloating:
16748 case CK_FixedPointCast:
16749 case CK_FixedPointToBoolean:
16750 case CK_FixedPointToIntegral:
16751 case CK_IntegralToFixedPoint:
16752 case CK_MatrixCast:
16753 case CK_HLSLVectorTruncation:
16754 case CK_HLSLElementwiseCast:
16755 case CK_HLSLAggregateSplatCast:
16756 llvm_unreachable("invalid cast kind for complex value");
16757
16758 case CK_LValueToRValue:
16759 case CK_AtomicToNonAtomic:
16760 case CK_NoOp:
16761 case CK_LValueToRValueBitCast:
16762 case CK_HLSLArrayRValue:
16763 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16764
16765 case CK_Dependent:
16766 case CK_LValueBitCast:
16767 case CK_UserDefinedConversion:
16768 return Error(E);
16769
16770 case CK_FloatingRealToComplex: {
16771 APFloat &Real = Result.FloatReal;
16772 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
16773 return false;
16774
16775 Result.makeComplexFloat();
16776 Result.FloatImag = APFloat(Real.getSemantics());
16777 return true;
16778 }
16779
16780 case CK_FloatingComplexCast: {
16781 if (!Visit(E->getSubExpr()))
16782 return false;
16783
16784 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16785 QualType From
16786 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16787
16788 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
16789 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
16790 }
16791
16792 case CK_FloatingComplexToIntegralComplex: {
16793 if (!Visit(E->getSubExpr()))
16794 return false;
16795
16796 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16797 QualType From
16798 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16799 Result.makeComplexInt();
16800 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
16801 To, Result.IntReal) &&
16802 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
16803 To, Result.IntImag);
16804 }
16805
16806 case CK_IntegralRealToComplex: {
16807 APSInt &Real = Result.IntReal;
16808 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
16809 return false;
16810
16811 Result.makeComplexInt();
16812 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
16813 return true;
16814 }
16815
16816 case CK_IntegralComplexCast: {
16817 if (!Visit(E->getSubExpr()))
16818 return false;
16819
16820 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16821 QualType From
16822 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16823
16824 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
16825 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
16826 return true;
16827 }
16828
16829 case CK_IntegralComplexToFloatingComplex: {
16830 if (!Visit(E->getSubExpr()))
16831 return false;
16832
16833 const FPOptions FPO = E->getFPFeaturesInEffect(
16834 Info.Ctx.getLangOpts());
16835 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16836 QualType From
16837 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16838 Result.makeComplexFloat();
16839 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
16840 To, Result.FloatReal) &&
16841 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
16842 To, Result.FloatImag);
16843 }
16844 }
16845
16846 llvm_unreachable("unknown cast resulting in complex value");
16847}
16848
16849void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16850 APFloat &ResR, APFloat &ResI) {
16851 // This is an implementation of complex multiplication according to the
16852 // constraints laid out in C11 Annex G. The implementation uses the
16853 // following naming scheme:
16854 // (a + ib) * (c + id)
16855
16856 APFloat AC = A * C;
16857 APFloat BD = B * D;
16858 APFloat AD = A * D;
16859 APFloat BC = B * C;
16860 ResR = AC - BD;
16861 ResI = AD + BC;
16862 if (ResR.isNaN() && ResI.isNaN()) {
16863 bool Recalc = false;
16864 if (A.isInfinity() || B.isInfinity()) {
16865 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16866 A);
16867 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16868 B);
16869 if (C.isNaN())
16870 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16871 if (D.isNaN())
16872 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16873 Recalc = true;
16874 }
16875 if (C.isInfinity() || D.isInfinity()) {
16876 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16877 C);
16878 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16879 D);
16880 if (A.isNaN())
16881 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16882 if (B.isNaN())
16883 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16884 Recalc = true;
16885 }
16886 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16887 BC.isInfinity())) {
16888 if (A.isNaN())
16889 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16890 if (B.isNaN())
16891 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16892 if (C.isNaN())
16893 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16894 if (D.isNaN())
16895 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16896 Recalc = true;
16897 }
16898 if (Recalc) {
16899 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16900 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16901 }
16902 }
16903}
16904
16905void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16906 APFloat &ResR, APFloat &ResI) {
16907 // This is an implementation of complex division according to the
16908 // constraints laid out in C11 Annex G. The implementation uses the
16909 // following naming scheme:
16910 // (a + ib) / (c + id)
16911
16912 int DenomLogB = 0;
16913 APFloat MaxCD = maxnum(abs(C), abs(D));
16914 if (MaxCD.isFinite()) {
16915 DenomLogB = ilogb(MaxCD);
16916 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16917 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16918 }
16919 APFloat Denom = C * C + D * D;
16920 ResR =
16921 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16922 ResI =
16923 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16924 if (ResR.isNaN() && ResI.isNaN()) {
16925 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16926 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16927 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16928 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16929 D.isFinite()) {
16930 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16931 A);
16932 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16933 B);
16934 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16935 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16936 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16937 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16938 C);
16939 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16940 D);
16941 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16942 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16943 }
16944 }
16945}
16946
16947bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16948 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16949 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16950
16951 // Track whether the LHS or RHS is real at the type system level. When this is
16952 // the case we can simplify our evaluation strategy.
16953 bool LHSReal = false, RHSReal = false;
16954
16955 bool LHSOK;
16956 if (E->getLHS()->getType()->isRealFloatingType()) {
16957 LHSReal = true;
16958 APFloat &Real = Result.FloatReal;
16959 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16960 if (LHSOK) {
16961 Result.makeComplexFloat();
16962 Result.FloatImag = APFloat(Real.getSemantics());
16963 }
16964 } else {
16965 LHSOK = Visit(E->getLHS());
16966 }
16967 if (!LHSOK && !Info.noteFailure())
16968 return false;
16969
16970 ComplexValue RHS;
16971 if (E->getRHS()->getType()->isRealFloatingType()) {
16972 RHSReal = true;
16973 APFloat &Real = RHS.FloatReal;
16974 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16975 return false;
16976 RHS.makeComplexFloat();
16977 RHS.FloatImag = APFloat(Real.getSemantics());
16978 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16979 return false;
16980
16981 assert(!(LHSReal && RHSReal) &&
16982 "Cannot have both operands of a complex operation be real.");
16983 switch (E->getOpcode()) {
16984 default: return Error(E);
16985 case BO_Add:
16986 if (Result.isComplexFloat()) {
16987 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16988 APFloat::rmNearestTiesToEven);
16989 if (LHSReal)
16990 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16991 else if (!RHSReal)
16992 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16993 APFloat::rmNearestTiesToEven);
16994 } else {
16995 Result.getComplexIntReal() += RHS.getComplexIntReal();
16996 Result.getComplexIntImag() += RHS.getComplexIntImag();
16997 }
16998 break;
16999 case BO_Sub:
17000 if (Result.isComplexFloat()) {
17001 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
17002 APFloat::rmNearestTiesToEven);
17003 if (LHSReal) {
17004 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
17005 Result.getComplexFloatImag().changeSign();
17006 } else if (!RHSReal) {
17007 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
17008 APFloat::rmNearestTiesToEven);
17009 }
17010 } else {
17011 Result.getComplexIntReal() -= RHS.getComplexIntReal();
17012 Result.getComplexIntImag() -= RHS.getComplexIntImag();
17013 }
17014 break;
17015 case BO_Mul:
17016 if (Result.isComplexFloat()) {
17017 // This is an implementation of complex multiplication according to the
17018 // constraints laid out in C11 Annex G. The implementation uses the
17019 // following naming scheme:
17020 // (a + ib) * (c + id)
17021 ComplexValue LHS = Result;
17022 APFloat &A = LHS.getComplexFloatReal();
17023 APFloat &B = LHS.getComplexFloatImag();
17024 APFloat &C = RHS.getComplexFloatReal();
17025 APFloat &D = RHS.getComplexFloatImag();
17026 APFloat &ResR = Result.getComplexFloatReal();
17027 APFloat &ResI = Result.getComplexFloatImag();
17028 if (LHSReal) {
17029 assert(!RHSReal && "Cannot have two real operands for a complex op!");
17030 ResR = A;
17031 ResI = A;
17032 // ResR = A * C;
17033 // ResI = A * D;
17034 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
17035 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
17036 return false;
17037 } else if (RHSReal) {
17038 // ResR = C * A;
17039 // ResI = C * B;
17040 ResR = C;
17041 ResI = C;
17042 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
17043 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
17044 return false;
17045 } else {
17046 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
17047 }
17048 } else {
17049 ComplexValue LHS = Result;
17050 Result.getComplexIntReal() =
17051 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
17052 LHS.getComplexIntImag() * RHS.getComplexIntImag());
17053 Result.getComplexIntImag() =
17054 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
17055 LHS.getComplexIntImag() * RHS.getComplexIntReal());
17056 }
17057 break;
17058 case BO_Div:
17059 if (Result.isComplexFloat()) {
17060 // This is an implementation of complex division according to the
17061 // constraints laid out in C11 Annex G. The implementation uses the
17062 // following naming scheme:
17063 // (a + ib) / (c + id)
17064 ComplexValue LHS = Result;
17065 APFloat &A = LHS.getComplexFloatReal();
17066 APFloat &B = LHS.getComplexFloatImag();
17067 APFloat &C = RHS.getComplexFloatReal();
17068 APFloat &D = RHS.getComplexFloatImag();
17069 APFloat &ResR = Result.getComplexFloatReal();
17070 APFloat &ResI = Result.getComplexFloatImag();
17071 if (RHSReal) {
17072 ResR = A;
17073 ResI = B;
17074 // ResR = A / C;
17075 // ResI = B / C;
17076 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
17077 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
17078 return false;
17079 } else {
17080 if (LHSReal) {
17081 // No real optimizations we can do here, stub out with zero.
17082 B = APFloat::getZero(A.getSemantics());
17083 }
17084 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
17085 }
17086 } else {
17087 ComplexValue LHS = Result;
17088 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
17089 RHS.getComplexIntImag() * RHS.getComplexIntImag();
17090 if (Den.isZero())
17091 return Error(E, diag::note_expr_divide_by_zero);
17092
17093 Result.getComplexIntReal() =
17094 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
17095 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
17096 Result.getComplexIntImag() =
17097 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
17098 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
17099 }
17100 break;
17101 }
17102
17103 return true;
17104}
17105
17106bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17107 // Get the operand value into 'Result'.
17108 if (!Visit(E->getSubExpr()))
17109 return false;
17110
17111 switch (E->getOpcode()) {
17112 default:
17113 return Error(E);
17114 case UO_Extension:
17115 return true;
17116 case UO_Plus:
17117 // The result is always just the subexpr.
17118 return true;
17119 case UO_Minus:
17120 if (Result.isComplexFloat()) {
17121 Result.getComplexFloatReal().changeSign();
17122 Result.getComplexFloatImag().changeSign();
17123 }
17124 else {
17125 Result.getComplexIntReal() = -Result.getComplexIntReal();
17126 Result.getComplexIntImag() = -Result.getComplexIntImag();
17127 }
17128 return true;
17129 case UO_Not:
17130 if (Result.isComplexFloat())
17131 Result.getComplexFloatImag().changeSign();
17132 else
17133 Result.getComplexIntImag() = -Result.getComplexIntImag();
17134 return true;
17135 }
17136}
17137
17138bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
17139 if (E->getNumInits() == 2) {
17140 if (E->getType()->isComplexType()) {
17141 Result.makeComplexFloat();
17142 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
17143 return false;
17144 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
17145 return false;
17146 } else {
17147 Result.makeComplexInt();
17148 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
17149 return false;
17150 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
17151 return false;
17152 }
17153 return true;
17154 }
17155 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
17156}
17157
17158bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
17159 if (!IsConstantEvaluatedBuiltinCall(E))
17160 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17161
17162 switch (E->getBuiltinCallee()) {
17163 case Builtin::BI__builtin_complex:
17164 Result.makeComplexFloat();
17165 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
17166 return false;
17167 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
17168 return false;
17169 return true;
17170
17171 default:
17172 return false;
17173 }
17174}
17175
17176//===----------------------------------------------------------------------===//
17177// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
17178// implicit conversion.
17179//===----------------------------------------------------------------------===//
17180
17181namespace {
17182class AtomicExprEvaluator :
17183 public ExprEvaluatorBase<AtomicExprEvaluator> {
17184 const LValue *This;
17185 APValue &Result;
17186public:
17187 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
17188 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
17189
17190 bool Success(const APValue &V, const Expr *E) {
17191 Result = V;
17192 return true;
17193 }
17194
17195 bool ZeroInitialization(const Expr *E) {
17196 ImplicitValueInitExpr VIE(
17197 E->getType()->castAs<AtomicType>()->getValueType());
17198 // For atomic-qualified class (and array) types in C++, initialize the
17199 // _Atomic-wrapped subobject directly, in-place.
17200 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
17201 : Evaluate(Result, Info, &VIE);
17202 }
17203
17204 bool VisitCastExpr(const CastExpr *E) {
17205 switch (E->getCastKind()) {
17206 default:
17207 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17208 case CK_NullToPointer:
17209 VisitIgnoredValue(E->getSubExpr());
17210 return ZeroInitialization(E);
17211 case CK_NonAtomicToAtomic:
17212 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
17213 : Evaluate(Result, Info, E->getSubExpr());
17214 }
17215 }
17216};
17217} // end anonymous namespace
17218
17219static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
17220 EvalInfo &Info) {
17221 assert(!E->isValueDependent());
17222 assert(E->isPRValue() && E->getType()->isAtomicType());
17223 return AtomicExprEvaluator(Info, This, Result).Visit(E);
17224}
17225
17226//===----------------------------------------------------------------------===//
17227// Void expression evaluation, primarily for a cast to void on the LHS of a
17228// comma operator
17229//===----------------------------------------------------------------------===//
17230
17231namespace {
17232class VoidExprEvaluator
17233 : public ExprEvaluatorBase<VoidExprEvaluator> {
17234public:
17235 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
17236
17237 bool Success(const APValue &V, const Expr *e) { return true; }
17238
17239 bool ZeroInitialization(const Expr *E) { return true; }
17240
17241 bool VisitCastExpr(const CastExpr *E) {
17242 switch (E->getCastKind()) {
17243 default:
17244 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17245 case CK_ToVoid:
17246 VisitIgnoredValue(E->getSubExpr());
17247 return true;
17248 }
17249 }
17250
17251 bool VisitCallExpr(const CallExpr *E) {
17252 if (!IsConstantEvaluatedBuiltinCall(E))
17253 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17254
17255 switch (E->getBuiltinCallee()) {
17256 case Builtin::BI__assume:
17257 case Builtin::BI__builtin_assume:
17258 // The argument is not evaluated!
17259 return true;
17260
17261 case Builtin::BI__builtin_operator_delete:
17262 return HandleOperatorDeleteCall(Info, E);
17263
17264 default:
17265 return false;
17266 }
17267 }
17268
17269 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
17270};
17271} // end anonymous namespace
17272
17273bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
17274 // We cannot speculatively evaluate a delete expression.
17275 if (Info.SpeculativeEvaluationDepth)
17276 return false;
17277
17278 FunctionDecl *OperatorDelete = E->getOperatorDelete();
17279 if (!OperatorDelete
17280 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17281 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17282 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
17283 return false;
17284 }
17285
17286 const Expr *Arg = E->getArgument();
17287
17288 LValue Pointer;
17289 if (!EvaluatePointer(Arg, Pointer, Info))
17290 return false;
17291 if (Pointer.Designator.Invalid)
17292 return false;
17293
17294 // Deleting a null pointer has no effect.
17295 if (Pointer.isNullPointer()) {
17296 // This is the only case where we need to produce an extension warning:
17297 // the only other way we can succeed is if we find a dynamic allocation,
17298 // and we will have warned when we allocated it in that case.
17299 if (!Info.getLangOpts().CPlusPlus20)
17300 Info.CCEDiag(E, diag::note_constexpr_new);
17301 return true;
17302 }
17303
17304 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
17305 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
17306 if (!Alloc)
17307 return false;
17308 QualType AllocType = Pointer.Base.getDynamicAllocType();
17309
17310 // For the non-array case, the designator must be empty if the static type
17311 // does not have a virtual destructor.
17312 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
17314 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
17315 << Arg->getType()->getPointeeType() << AllocType;
17316 return false;
17317 }
17318
17319 // For a class type with a virtual destructor, the selected operator delete
17320 // is the one looked up when building the destructor.
17321 if (!E->isArrayForm() && !E->isGlobalDelete()) {
17322 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
17323 if (VirtualDelete &&
17324 !VirtualDelete
17325 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17326 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17327 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
17328 return false;
17329 }
17330 }
17331
17332 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
17333 (*Alloc)->Value, AllocType))
17334 return false;
17335
17336 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
17337 // The element was already erased. This means the destructor call also
17338 // deleted the object.
17339 // FIXME: This probably results in undefined behavior before we get this
17340 // far, and should be diagnosed elsewhere first.
17341 Info.FFDiag(E, diag::note_constexpr_double_delete);
17342 return false;
17343 }
17344
17345 return true;
17346}
17347
17348static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
17349 assert(!E->isValueDependent());
17350 assert(E->isPRValue() && E->getType()->isVoidType());
17351 return VoidExprEvaluator(Info).Visit(E);
17352}
17353
17354//===----------------------------------------------------------------------===//
17355// Top level Expr::EvaluateAsRValue method.
17356//===----------------------------------------------------------------------===//
17357
17358static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
17359 assert(!E->isValueDependent());
17360 // In C, function designators are not lvalues, but we evaluate them as if they
17361 // are.
17362 QualType T = E->getType();
17363 if (E->isGLValue() || T->isFunctionType()) {
17364 LValue LV;
17365 if (!EvaluateLValue(E, LV, Info))
17366 return false;
17367 LV.moveInto(Result);
17368 } else if (T->isVectorType()) {
17369 if (!EvaluateVector(E, Result, Info))
17370 return false;
17371 } else if (T->isIntegralOrEnumerationType()) {
17372 if (!IntExprEvaluator(Info, Result).Visit(E))
17373 return false;
17374 } else if (T->hasPointerRepresentation()) {
17375 LValue LV;
17376 if (!EvaluatePointer(E, LV, Info))
17377 return false;
17378 LV.moveInto(Result);
17379 } else if (T->isRealFloatingType()) {
17380 llvm::APFloat F(0.0);
17381 if (!EvaluateFloat(E, F, Info))
17382 return false;
17383 Result = APValue(F);
17384 } else if (T->isAnyComplexType()) {
17385 ComplexValue C;
17386 if (!EvaluateComplex(E, C, Info))
17387 return false;
17388 C.moveInto(Result);
17389 } else if (T->isFixedPointType()) {
17390 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
17391 } else if (T->isMemberPointerType()) {
17392 MemberPtr P;
17393 if (!EvaluateMemberPointer(E, P, Info))
17394 return false;
17395 P.moveInto(Result);
17396 return true;
17397 } else if (T->isArrayType()) {
17398 LValue LV;
17399 APValue &Value =
17400 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17401 if (!EvaluateArray(E, LV, Value, Info))
17402 return false;
17403 Result = Value;
17404 } else if (T->isRecordType()) {
17405 LValue LV;
17406 APValue &Value =
17407 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17408 if (!EvaluateRecord(E, LV, Value, Info))
17409 return false;
17410 Result = Value;
17411 } else if (T->isVoidType()) {
17412 if (!Info.getLangOpts().CPlusPlus11)
17413 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
17414 << E->getType();
17415 if (!EvaluateVoid(E, Info))
17416 return false;
17417 } else if (T->isAtomicType()) {
17418 QualType Unqual = T.getAtomicUnqualifiedType();
17419 if (Unqual->isArrayType() || Unqual->isRecordType()) {
17420 LValue LV;
17421 APValue &Value = Info.CurrentCall->createTemporary(
17422 E, Unqual, ScopeKind::FullExpression, LV);
17423 if (!EvaluateAtomic(E, &LV, Value, Info))
17424 return false;
17425 Result = Value;
17426 } else {
17427 if (!EvaluateAtomic(E, nullptr, Result, Info))
17428 return false;
17429 }
17430 } else if (Info.getLangOpts().CPlusPlus11) {
17431 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
17432 return false;
17433 } else {
17434 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17435 return false;
17436 }
17437
17438 return true;
17439}
17440
17441/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
17442/// cases, the in-place evaluation is essential, since later initializers for
17443/// an object can indirectly refer to subobjects which were initialized earlier.
17444static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
17445 const Expr *E, bool AllowNonLiteralTypes) {
17446 assert(!E->isValueDependent());
17447
17448 // Normally expressions passed to EvaluateInPlace have a type, but not when
17449 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
17450 // replaced with a CXXConstructExpr. This can happen in LLDB.
17451 if (E->getType().isNull())
17452 return false;
17453
17454 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
17455 return false;
17456
17457 if (E->isPRValue()) {
17458 // Evaluate arrays and record types in-place, so that later initializers can
17459 // refer to earlier-initialized members of the object.
17460 QualType T = E->getType();
17461 if (T->isArrayType())
17462 return EvaluateArray(E, This, Result, Info);
17463 else if (T->isRecordType())
17464 return EvaluateRecord(E, This, Result, Info);
17465 else if (T->isAtomicType()) {
17466 QualType Unqual = T.getAtomicUnqualifiedType();
17467 if (Unqual->isArrayType() || Unqual->isRecordType())
17468 return EvaluateAtomic(E, &This, Result, Info);
17469 }
17470 }
17471
17472 // For any other type, in-place evaluation is unimportant.
17473 return Evaluate(Result, Info, E);
17474}
17475
17476/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
17477/// lvalue-to-rvalue cast if it is an lvalue.
17478static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
17479 assert(!E->isValueDependent());
17480
17481 if (E->getType().isNull())
17482 return false;
17483
17484 if (!CheckLiteralType(Info, E))
17485 return false;
17486
17487 if (Info.EnableNewConstInterp) {
17488 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
17489 return false;
17490 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17491 ConstantExprKind::Normal);
17492 }
17493
17494 if (!::Evaluate(Result, Info, E))
17495 return false;
17496
17497 // Implicit lvalue-to-rvalue cast.
17498 if (E->isGLValue()) {
17499 LValue LV;
17500 LV.setFrom(Info.Ctx, Result);
17501 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17502 return false;
17503 }
17504
17505 // Check this core constant expression is a constant expression.
17506 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17507 ConstantExprKind::Normal) &&
17508 CheckMemoryLeaks(Info);
17509}
17510
17511static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
17512 const ASTContext &Ctx, bool &IsConst) {
17513 // Fast-path evaluations of integer literals, since we sometimes see files
17514 // containing vast quantities of these.
17515 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
17516 Result =
17517 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
17518 IsConst = true;
17519 return true;
17520 }
17521
17522 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
17523 Result = APValue(APSInt(APInt(1, L->getValue())));
17524 IsConst = true;
17525 return true;
17526 }
17527
17528 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
17529 Result = APValue(FL->getValue());
17530 IsConst = true;
17531 return true;
17532 }
17533
17534 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
17535 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
17536 IsConst = true;
17537 return true;
17538 }
17539
17540 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
17541 if (CE->hasAPValueResult()) {
17542 APValue APV = CE->getAPValueResult();
17543 if (!APV.isLValue()) {
17544 Result = std::move(APV);
17545 IsConst = true;
17546 return true;
17547 }
17548 }
17549
17550 // The SubExpr is usually just an IntegerLiteral.
17551 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
17552 }
17553
17554 // This case should be rare, but we need to check it before we check on
17555 // the type below.
17556 if (Exp->getType().isNull()) {
17557 IsConst = false;
17558 return true;
17559 }
17560
17561 return false;
17562}
17563
17566 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
17567 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
17568}
17569
17570static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
17571 const ASTContext &Ctx, EvalInfo &Info) {
17572 assert(!E->isValueDependent());
17573 bool IsConst;
17574 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
17575 return IsConst;
17576
17577 return EvaluateAsRValue(Info, E, Result.Val);
17578}
17579
17581 const ASTContext &Ctx,
17582 Expr::SideEffectsKind AllowSideEffects,
17583 EvalInfo &Info) {
17584 assert(!E->isValueDependent());
17586 return false;
17587
17588 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
17589 !ExprResult.Val.isInt() ||
17590 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17591 return false;
17592
17593 return true;
17594}
17595
17597 const ASTContext &Ctx,
17598 Expr::SideEffectsKind AllowSideEffects,
17599 EvalInfo &Info) {
17600 assert(!E->isValueDependent());
17601 if (!E->getType()->isFixedPointType())
17602 return false;
17603
17604 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
17605 return false;
17606
17607 if (!ExprResult.Val.isFixedPoint() ||
17608 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17609 return false;
17610
17611 return true;
17612}
17613
17614/// EvaluateAsRValue - Return true if this is a constant which we can fold using
17615/// any crazy technique (that has nothing to do with language standards) that
17616/// we want to. If this function returns true, it returns the folded constant
17617/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
17618/// will be applied to the result.
17620 bool InConstantContext) const {
17621 assert(!isValueDependent() &&
17622 "Expression evaluator can't be called on a dependent expression.");
17623 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
17624 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17625 Info.InConstantContext = InConstantContext;
17626 return ::EvaluateAsRValue(this, Result, Ctx, Info);
17627}
17628
17630 bool InConstantContext) const {
17631 assert(!isValueDependent() &&
17632 "Expression evaluator can't be called on a dependent expression.");
17633 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
17634 EvalResult Scratch;
17635 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
17636 HandleConversionToBool(Scratch.Val, Result);
17637}
17638
17640 SideEffectsKind AllowSideEffects,
17641 bool InConstantContext) const {
17642 assert(!isValueDependent() &&
17643 "Expression evaluator can't be called on a dependent expression.");
17644 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
17645 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17646 Info.InConstantContext = InConstantContext;
17647 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
17648}
17649
17651 SideEffectsKind AllowSideEffects,
17652 bool InConstantContext) const {
17653 assert(!isValueDependent() &&
17654 "Expression evaluator can't be called on a dependent expression.");
17655 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
17656 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
17657 Info.InConstantContext = InConstantContext;
17658 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
17659}
17660
17661bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
17662 SideEffectsKind AllowSideEffects,
17663 bool InConstantContext) const {
17664 assert(!isValueDependent() &&
17665 "Expression evaluator can't be called on a dependent expression.");
17666
17667 if (!getType()->isRealFloatingType())
17668 return false;
17669
17670 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
17672 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
17673 !ExprResult.Val.isFloat() ||
17674 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17675 return false;
17676
17677 Result = ExprResult.Val.getFloat();
17678 return true;
17679}
17680
17682 bool InConstantContext) const {
17683 assert(!isValueDependent() &&
17684 "Expression evaluator can't be called on a dependent expression.");
17685
17686 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
17687 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
17688 Info.InConstantContext = InConstantContext;
17689 LValue LV;
17690 CheckedTemporaries CheckedTemps;
17691
17692 if (Info.EnableNewConstInterp) {
17693 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
17694 ConstantExprKind::Normal))
17695 return false;
17696
17697 LV.setFrom(Ctx, Result.Val);
17699 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
17700 ConstantExprKind::Normal, CheckedTemps);
17701 }
17702
17703 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
17704 Result.HasSideEffects ||
17707 ConstantExprKind::Normal, CheckedTemps))
17708 return false;
17709
17710 LV.moveInto(Result.Val);
17711 return true;
17712}
17713
17715 APValue DestroyedValue, QualType Type,
17716 SourceLocation Loc, Expr::EvalStatus &EStatus,
17717 bool IsConstantDestruction) {
17718 EvalInfo Info(Ctx, EStatus,
17719 IsConstantDestruction ? EvaluationMode::ConstantExpression
17721 Info.setEvaluatingDecl(Base, DestroyedValue,
17722 EvalInfo::EvaluatingDeclKind::Dtor);
17723 Info.InConstantContext = IsConstantDestruction;
17724
17725 LValue LVal;
17726 LVal.set(Base);
17727
17728 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
17729 EStatus.HasSideEffects)
17730 return false;
17731
17732 if (!Info.discardCleanups())
17733 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17734
17735 return true;
17736}
17737
17739 ConstantExprKind Kind) const {
17740 assert(!isValueDependent() &&
17741 "Expression evaluator can't be called on a dependent expression.");
17742 bool IsConst;
17743 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
17744 Result.Val.hasValue())
17745 return true;
17746
17747 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
17749 EvalInfo Info(Ctx, Result, EM);
17750 Info.InConstantContext = true;
17751
17752 if (Info.EnableNewConstInterp) {
17753 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
17754 return false;
17755 return CheckConstantExpression(Info, getExprLoc(),
17756 getStorageType(Ctx, this), Result.Val, Kind);
17757 }
17758
17759 // The type of the object we're initializing is 'const T' for a class NTTP.
17760 QualType T = getType();
17761 if (Kind == ConstantExprKind::ClassTemplateArgument)
17762 T.addConst();
17763
17764 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
17765 // represent the result of the evaluation. CheckConstantExpression ensures
17766 // this doesn't escape.
17767 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
17768 APValue::LValueBase Base(&BaseMTE);
17769 Info.setEvaluatingDecl(Base, Result.Val);
17770
17771 LValue LVal;
17772 LVal.set(Base);
17773 // C++23 [intro.execution]/p5
17774 // A full-expression is [...] a constant-expression
17775 // So we need to make sure temporary objects are destroyed after having
17776 // evaluating the expression (per C++23 [class.temporary]/p4).
17777 FullExpressionRAII Scope(Info);
17778 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
17779 Result.HasSideEffects || !Scope.destroy())
17780 return false;
17781
17782 if (!Info.discardCleanups())
17783 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17784
17785 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
17786 Result.Val, Kind))
17787 return false;
17788 if (!CheckMemoryLeaks(Info))
17789 return false;
17790
17791 // If this is a class template argument, it's required to have constant
17792 // destruction too.
17793 if (Kind == ConstantExprKind::ClassTemplateArgument &&
17795 true) ||
17796 Result.HasSideEffects)) {
17797 // FIXME: Prefix a note to indicate that the problem is lack of constant
17798 // destruction.
17799 return false;
17800 }
17801
17802 return true;
17803}
17804
17806 const VarDecl *VD,
17808 bool IsConstantInitialization) const {
17809 assert(!isValueDependent() &&
17810 "Expression evaluator can't be called on a dependent expression.");
17811 assert(VD && "Need a valid VarDecl");
17812
17813 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
17814 std::string Name;
17815 llvm::raw_string_ostream OS(Name);
17816 VD->printQualifiedName(OS);
17817 return Name;
17818 });
17819
17820 Expr::EvalStatus EStatus;
17821 EStatus.Diag = &Notes;
17822
17823 EvalInfo Info(Ctx, EStatus,
17824 (IsConstantInitialization &&
17825 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
17828 Info.setEvaluatingDecl(VD, Value);
17829 Info.InConstantContext = IsConstantInitialization;
17830
17831 SourceLocation DeclLoc = VD->getLocation();
17832 QualType DeclTy = VD->getType();
17833
17834 if (Info.EnableNewConstInterp) {
17835 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
17836 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
17837 return false;
17838
17839 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17840 ConstantExprKind::Normal);
17841 } else {
17842 LValue LVal;
17843 LVal.set(VD);
17844
17845 {
17846 // C++23 [intro.execution]/p5
17847 // A full-expression is ... an init-declarator ([dcl.decl]) or a
17848 // mem-initializer.
17849 // So we need to make sure temporary objects are destroyed after having
17850 // evaluated the expression (per C++23 [class.temporary]/p4).
17851 //
17852 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
17853 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
17854 // outermost FullExpr, such as ExprWithCleanups.
17855 FullExpressionRAII Scope(Info);
17856 if (!EvaluateInPlace(Value, Info, LVal, this,
17857 /*AllowNonLiteralTypes=*/true) ||
17858 EStatus.HasSideEffects)
17859 return false;
17860 }
17861
17862 // At this point, any lifetime-extended temporaries are completely
17863 // initialized.
17864 Info.performLifetimeExtension();
17865
17866 if (!Info.discardCleanups())
17867 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17868 }
17869
17870 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17871 ConstantExprKind::Normal) &&
17872 CheckMemoryLeaks(Info);
17873}
17874
17877 Expr::EvalStatus EStatus;
17878 EStatus.Diag = &Notes;
17879
17880 // Only treat the destruction as constant destruction if we formally have
17881 // constant initialization (or are usable in a constant expression).
17882 bool IsConstantDestruction = hasConstantInitialization();
17883
17884 // Make a copy of the value for the destructor to mutate, if we know it.
17885 // Otherwise, treat the value as default-initialized; if the destructor works
17886 // anyway, then the destruction is constant (and must be essentially empty).
17887 APValue DestroyedValue;
17888 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17889 DestroyedValue = *getEvaluatedValue();
17890 else if (!handleDefaultInitValue(getType(), DestroyedValue))
17891 return false;
17892
17893 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17894 getType(), getLocation(), EStatus,
17895 IsConstantDestruction) ||
17896 EStatus.HasSideEffects)
17897 return false;
17898
17899 ensureEvaluatedStmt()->HasConstantDestruction = true;
17900 return true;
17901}
17902
17903/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17904/// constant folded, but discard the result.
17906 assert(!isValueDependent() &&
17907 "Expression evaluator can't be called on a dependent expression.");
17908
17910 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17912}
17913
17914APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
17915 assert(!isValueDependent() &&
17916 "Expression evaluator can't be called on a dependent expression.");
17917
17918 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17919 EvalResult EVResult;
17920 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
17921 Info.InConstantContext = true;
17922
17923 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17924 (void)Result;
17925 assert(Result && "Could not evaluate expression");
17926 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17927
17928 return EVResult.Val.getInt();
17929}
17930
17933 assert(!isValueDependent() &&
17934 "Expression evaluator can't be called on a dependent expression.");
17935
17936 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17937 EvalResult EVResult;
17938 EVResult.Diag = Diag;
17939 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
17940 Info.InConstantContext = true;
17941 Info.CheckingForUndefinedBehavior = true;
17942
17943 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17944 (void)Result;
17945 assert(Result && "Could not evaluate expression");
17946 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17947
17948 return EVResult.Val.getInt();
17949}
17950
17952 assert(!isValueDependent() &&
17953 "Expression evaluator can't be called on a dependent expression.");
17954
17955 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17956 bool IsConst;
17957 EvalResult EVResult;
17958 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
17959 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
17960 Info.CheckingForUndefinedBehavior = true;
17961 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17962 }
17963}
17964
17966 assert(Val.isLValue());
17967 return IsGlobalLValue(Val.getLValueBase());
17968}
17969
17970/// isIntegerConstantExpr - this recursive routine will test if an expression is
17971/// an integer constant expression.
17972
17973/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17974/// comma, etc
17975
17976// CheckICE - This function does the fundamental ICE checking: the returned
17977// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
17978//
17979// Note that to reduce code duplication, this helper does no evaluation
17980// itself; the caller checks whether the expression is evaluatable, and
17981// in the rare cases where CheckICE actually cares about the evaluated
17982// value, it calls into Evaluate.
17983
17984namespace {
17985
17986enum ICEKind {
17987 /// This expression is an ICE.
17988 IK_ICE,
17989 /// This expression is not an ICE, but if it isn't evaluated, it's
17990 /// a legal subexpression for an ICE. This return value is used to handle
17991 /// the comma operator in C99 mode, and non-constant subexpressions.
17992 IK_ICEIfUnevaluated,
17993 /// This expression is not an ICE, and is not a legal subexpression for one.
17994 IK_NotICE
17995};
17996
17997struct ICEDiag {
17998 ICEKind Kind;
17999 SourceLocation Loc;
18000
18001 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
18002};
18003
18004}
18005
18006static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
18007
18008static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
18009
18010static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
18011 Expr::EvalResult EVResult;
18012 Expr::EvalStatus Status;
18013 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18014
18015 Info.InConstantContext = true;
18016 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
18017 !EVResult.Val.isInt())
18018 return ICEDiag(IK_NotICE, E->getBeginLoc());
18019
18020 return NoDiag();
18021}
18022
18023static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
18024 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
18026 return ICEDiag(IK_NotICE, E->getBeginLoc());
18027
18028 switch (E->getStmtClass()) {
18029#define ABSTRACT_STMT(Node)
18030#define STMT(Node, Base) case Expr::Node##Class:
18031#define EXPR(Node, Base)
18032#include "clang/AST/StmtNodes.inc"
18033 case Expr::PredefinedExprClass:
18034 case Expr::FloatingLiteralClass:
18035 case Expr::ImaginaryLiteralClass:
18036 case Expr::StringLiteralClass:
18037 case Expr::ArraySubscriptExprClass:
18038 case Expr::MatrixSubscriptExprClass:
18039 case Expr::ArraySectionExprClass:
18040 case Expr::OMPArrayShapingExprClass:
18041 case Expr::OMPIteratorExprClass:
18042 case Expr::MemberExprClass:
18043 case Expr::CompoundAssignOperatorClass:
18044 case Expr::CompoundLiteralExprClass:
18045 case Expr::ExtVectorElementExprClass:
18046 case Expr::DesignatedInitExprClass:
18047 case Expr::ArrayInitLoopExprClass:
18048 case Expr::ArrayInitIndexExprClass:
18049 case Expr::NoInitExprClass:
18050 case Expr::DesignatedInitUpdateExprClass:
18051 case Expr::ImplicitValueInitExprClass:
18052 case Expr::ParenListExprClass:
18053 case Expr::VAArgExprClass:
18054 case Expr::AddrLabelExprClass:
18055 case Expr::StmtExprClass:
18056 case Expr::CXXMemberCallExprClass:
18057 case Expr::CUDAKernelCallExprClass:
18058 case Expr::CXXAddrspaceCastExprClass:
18059 case Expr::CXXDynamicCastExprClass:
18060 case Expr::CXXTypeidExprClass:
18061 case Expr::CXXUuidofExprClass:
18062 case Expr::MSPropertyRefExprClass:
18063 case Expr::MSPropertySubscriptExprClass:
18064 case Expr::CXXNullPtrLiteralExprClass:
18065 case Expr::UserDefinedLiteralClass:
18066 case Expr::CXXThisExprClass:
18067 case Expr::CXXThrowExprClass:
18068 case Expr::CXXNewExprClass:
18069 case Expr::CXXDeleteExprClass:
18070 case Expr::CXXPseudoDestructorExprClass:
18071 case Expr::UnresolvedLookupExprClass:
18072 case Expr::RecoveryExprClass:
18073 case Expr::DependentScopeDeclRefExprClass:
18074 case Expr::CXXConstructExprClass:
18075 case Expr::CXXInheritedCtorInitExprClass:
18076 case Expr::CXXStdInitializerListExprClass:
18077 case Expr::CXXBindTemporaryExprClass:
18078 case Expr::ExprWithCleanupsClass:
18079 case Expr::CXXTemporaryObjectExprClass:
18080 case Expr::CXXUnresolvedConstructExprClass:
18081 case Expr::CXXDependentScopeMemberExprClass:
18082 case Expr::UnresolvedMemberExprClass:
18083 case Expr::ObjCStringLiteralClass:
18084 case Expr::ObjCBoxedExprClass:
18085 case Expr::ObjCArrayLiteralClass:
18086 case Expr::ObjCDictionaryLiteralClass:
18087 case Expr::ObjCEncodeExprClass:
18088 case Expr::ObjCMessageExprClass:
18089 case Expr::ObjCSelectorExprClass:
18090 case Expr::ObjCProtocolExprClass:
18091 case Expr::ObjCIvarRefExprClass:
18092 case Expr::ObjCPropertyRefExprClass:
18093 case Expr::ObjCSubscriptRefExprClass:
18094 case Expr::ObjCIsaExprClass:
18095 case Expr::ObjCAvailabilityCheckExprClass:
18096 case Expr::ShuffleVectorExprClass:
18097 case Expr::ConvertVectorExprClass:
18098 case Expr::BlockExprClass:
18099 case Expr::NoStmtClass:
18100 case Expr::OpaqueValueExprClass:
18101 case Expr::PackExpansionExprClass:
18102 case Expr::SubstNonTypeTemplateParmPackExprClass:
18103 case Expr::FunctionParmPackExprClass:
18104 case Expr::AsTypeExprClass:
18105 case Expr::ObjCIndirectCopyRestoreExprClass:
18106 case Expr::MaterializeTemporaryExprClass:
18107 case Expr::PseudoObjectExprClass:
18108 case Expr::AtomicExprClass:
18109 case Expr::LambdaExprClass:
18110 case Expr::CXXFoldExprClass:
18111 case Expr::CoawaitExprClass:
18112 case Expr::DependentCoawaitExprClass:
18113 case Expr::CoyieldExprClass:
18114 case Expr::SYCLUniqueStableNameExprClass:
18115 case Expr::CXXParenListInitExprClass:
18116 case Expr::HLSLOutArgExprClass:
18117 return ICEDiag(IK_NotICE, E->getBeginLoc());
18118
18119 case Expr::InitListExprClass: {
18120 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
18121 // form "T x = { a };" is equivalent to "T x = a;".
18122 // Unless we're initializing a reference, T is a scalar as it is known to be
18123 // of integral or enumeration type.
18124 if (E->isPRValue())
18125 if (cast<InitListExpr>(E)->getNumInits() == 1)
18126 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
18127 return ICEDiag(IK_NotICE, E->getBeginLoc());
18128 }
18129
18130 case Expr::SizeOfPackExprClass:
18131 case Expr::GNUNullExprClass:
18132 case Expr::SourceLocExprClass:
18133 case Expr::EmbedExprClass:
18134 case Expr::OpenACCAsteriskSizeExprClass:
18135 return NoDiag();
18136
18137 case Expr::PackIndexingExprClass:
18138 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
18139
18140 case Expr::SubstNonTypeTemplateParmExprClass:
18141 return
18142 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
18143
18144 case Expr::ConstantExprClass:
18145 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
18146
18147 case Expr::ParenExprClass:
18148 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
18149 case Expr::GenericSelectionExprClass:
18150 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
18151 case Expr::IntegerLiteralClass:
18152 case Expr::FixedPointLiteralClass:
18153 case Expr::CharacterLiteralClass:
18154 case Expr::ObjCBoolLiteralExprClass:
18155 case Expr::CXXBoolLiteralExprClass:
18156 case Expr::CXXScalarValueInitExprClass:
18157 case Expr::TypeTraitExprClass:
18158 case Expr::ConceptSpecializationExprClass:
18159 case Expr::RequiresExprClass:
18160 case Expr::ArrayTypeTraitExprClass:
18161 case Expr::ExpressionTraitExprClass:
18162 case Expr::CXXNoexceptExprClass:
18163 return NoDiag();
18164 case Expr::CallExprClass:
18165 case Expr::CXXOperatorCallExprClass: {
18166 // C99 6.6/3 allows function calls within unevaluated subexpressions of
18167 // constant expressions, but they can never be ICEs because an ICE cannot
18168 // contain an operand of (pointer to) function type.
18169 const CallExpr *CE = cast<CallExpr>(E);
18170 if (CE->getBuiltinCallee())
18171 return CheckEvalInICE(E, Ctx);
18172 return ICEDiag(IK_NotICE, E->getBeginLoc());
18173 }
18174 case Expr::CXXRewrittenBinaryOperatorClass:
18175 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
18176 Ctx);
18177 case Expr::DeclRefExprClass: {
18178 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
18179 if (isa<EnumConstantDecl>(D))
18180 return NoDiag();
18181
18182 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
18183 // integer variables in constant expressions:
18184 //
18185 // C++ 7.1.5.1p2
18186 // A variable of non-volatile const-qualified integral or enumeration
18187 // type initialized by an ICE can be used in ICEs.
18188 //
18189 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
18190 // that mode, use of reference variables should not be allowed.
18191 const VarDecl *VD = dyn_cast<VarDecl>(D);
18192 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
18193 !VD->getType()->isReferenceType())
18194 return NoDiag();
18195
18196 return ICEDiag(IK_NotICE, E->getBeginLoc());
18197 }
18198 case Expr::UnaryOperatorClass: {
18199 const UnaryOperator *Exp = cast<UnaryOperator>(E);
18200 switch (Exp->getOpcode()) {
18201 case UO_PostInc:
18202 case UO_PostDec:
18203 case UO_PreInc:
18204 case UO_PreDec:
18205 case UO_AddrOf:
18206 case UO_Deref:
18207 case UO_Coawait:
18208 // C99 6.6/3 allows increment and decrement within unevaluated
18209 // subexpressions of constant expressions, but they can never be ICEs
18210 // because an ICE cannot contain an lvalue operand.
18211 return ICEDiag(IK_NotICE, E->getBeginLoc());
18212 case UO_Extension:
18213 case UO_LNot:
18214 case UO_Plus:
18215 case UO_Minus:
18216 case UO_Not:
18217 case UO_Real:
18218 case UO_Imag:
18219 return CheckICE(Exp->getSubExpr(), Ctx);
18220 }
18221 llvm_unreachable("invalid unary operator class");
18222 }
18223 case Expr::OffsetOfExprClass: {
18224 // Note that per C99, offsetof must be an ICE. And AFAIK, using
18225 // EvaluateAsRValue matches the proposed gcc behavior for cases like
18226 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
18227 // compliance: we should warn earlier for offsetof expressions with
18228 // array subscripts that aren't ICEs, and if the array subscripts
18229 // are ICEs, the value of the offsetof must be an integer constant.
18230 return CheckEvalInICE(E, Ctx);
18231 }
18232 case Expr::UnaryExprOrTypeTraitExprClass: {
18234 if ((Exp->getKind() == UETT_SizeOf) &&
18236 return ICEDiag(IK_NotICE, E->getBeginLoc());
18237 if (Exp->getKind() == UETT_CountOf) {
18238 QualType ArgTy = Exp->getTypeOfArgument();
18239 if (ArgTy->isVariableArrayType()) {
18240 // We need to look whether the array is multidimensional. If it is,
18241 // then we want to check the size expression manually to see whether
18242 // it is an ICE or not.
18243 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
18244 if (VAT->getElementType()->isArrayType())
18245 // Variable array size expression could be missing (e.g. int a[*][10])
18246 // In that case, it can't be a constant expression.
18247 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
18248 : ICEDiag(IK_NotICE, E->getBeginLoc());
18249
18250 // Otherwise, this is a regular VLA, which is definitely not an ICE.
18251 return ICEDiag(IK_NotICE, E->getBeginLoc());
18252 }
18253 }
18254 return NoDiag();
18255 }
18256 case Expr::BinaryOperatorClass: {
18257 const BinaryOperator *Exp = cast<BinaryOperator>(E);
18258 switch (Exp->getOpcode()) {
18259 case BO_PtrMemD:
18260 case BO_PtrMemI:
18261 case BO_Assign:
18262 case BO_MulAssign:
18263 case BO_DivAssign:
18264 case BO_RemAssign:
18265 case BO_AddAssign:
18266 case BO_SubAssign:
18267 case BO_ShlAssign:
18268 case BO_ShrAssign:
18269 case BO_AndAssign:
18270 case BO_XorAssign:
18271 case BO_OrAssign:
18272 // C99 6.6/3 allows assignments within unevaluated subexpressions of
18273 // constant expressions, but they can never be ICEs because an ICE cannot
18274 // contain an lvalue operand.
18275 return ICEDiag(IK_NotICE, E->getBeginLoc());
18276
18277 case BO_Mul:
18278 case BO_Div:
18279 case BO_Rem:
18280 case BO_Add:
18281 case BO_Sub:
18282 case BO_Shl:
18283 case BO_Shr:
18284 case BO_LT:
18285 case BO_GT:
18286 case BO_LE:
18287 case BO_GE:
18288 case BO_EQ:
18289 case BO_NE:
18290 case BO_And:
18291 case BO_Xor:
18292 case BO_Or:
18293 case BO_Comma:
18294 case BO_Cmp: {
18295 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18296 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18297 if (Exp->getOpcode() == BO_Div ||
18298 Exp->getOpcode() == BO_Rem) {
18299 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
18300 // we don't evaluate one.
18301 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
18302 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
18303 if (REval == 0)
18304 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18305 if (REval.isSigned() && REval.isAllOnes()) {
18306 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
18307 if (LEval.isMinSignedValue())
18308 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18309 }
18310 }
18311 }
18312 if (Exp->getOpcode() == BO_Comma) {
18313 if (Ctx.getLangOpts().C99) {
18314 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
18315 // if it isn't evaluated.
18316 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
18317 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18318 } else {
18319 // In both C89 and C++, commas in ICEs are illegal.
18320 return ICEDiag(IK_NotICE, E->getBeginLoc());
18321 }
18322 }
18323 return Worst(LHSResult, RHSResult);
18324 }
18325 case BO_LAnd:
18326 case BO_LOr: {
18327 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18328 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18329 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
18330 // Rare case where the RHS has a comma "side-effect"; we need
18331 // to actually check the condition to see whether the side
18332 // with the comma is evaluated.
18333 if ((Exp->getOpcode() == BO_LAnd) !=
18334 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
18335 return RHSResult;
18336 return NoDiag();
18337 }
18338
18339 return Worst(LHSResult, RHSResult);
18340 }
18341 }
18342 llvm_unreachable("invalid binary operator kind");
18343 }
18344 case Expr::ImplicitCastExprClass:
18345 case Expr::CStyleCastExprClass:
18346 case Expr::CXXFunctionalCastExprClass:
18347 case Expr::CXXStaticCastExprClass:
18348 case Expr::CXXReinterpretCastExprClass:
18349 case Expr::CXXConstCastExprClass:
18350 case Expr::ObjCBridgedCastExprClass: {
18351 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
18352 if (isa<ExplicitCastExpr>(E)) {
18353 if (const FloatingLiteral *FL
18354 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
18355 unsigned DestWidth = Ctx.getIntWidth(E->getType());
18356 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
18357 APSInt IgnoredVal(DestWidth, !DestSigned);
18358 bool Ignored;
18359 // If the value does not fit in the destination type, the behavior is
18360 // undefined, so we are not required to treat it as a constant
18361 // expression.
18362 if (FL->getValue().convertToInteger(IgnoredVal,
18363 llvm::APFloat::rmTowardZero,
18364 &Ignored) & APFloat::opInvalidOp)
18365 return ICEDiag(IK_NotICE, E->getBeginLoc());
18366 return NoDiag();
18367 }
18368 }
18369 switch (cast<CastExpr>(E)->getCastKind()) {
18370 case CK_LValueToRValue:
18371 case CK_AtomicToNonAtomic:
18372 case CK_NonAtomicToAtomic:
18373 case CK_NoOp:
18374 case CK_IntegralToBoolean:
18375 case CK_IntegralCast:
18376 return CheckICE(SubExpr, Ctx);
18377 default:
18378 return ICEDiag(IK_NotICE, E->getBeginLoc());
18379 }
18380 }
18381 case Expr::BinaryConditionalOperatorClass: {
18383 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
18384 if (CommonResult.Kind == IK_NotICE) return CommonResult;
18385 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18386 if (FalseResult.Kind == IK_NotICE) return FalseResult;
18387 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
18388 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
18389 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
18390 return FalseResult;
18391 }
18392 case Expr::ConditionalOperatorClass: {
18394 // If the condition (ignoring parens) is a __builtin_constant_p call,
18395 // then only the true side is actually considered in an integer constant
18396 // expression, and it is fully evaluated. This is an important GNU
18397 // extension. See GCC PR38377 for discussion.
18398 if (const CallExpr *CallCE
18399 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
18400 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
18401 return CheckEvalInICE(E, Ctx);
18402 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
18403 if (CondResult.Kind == IK_NotICE)
18404 return CondResult;
18405
18406 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
18407 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18408
18409 if (TrueResult.Kind == IK_NotICE)
18410 return TrueResult;
18411 if (FalseResult.Kind == IK_NotICE)
18412 return FalseResult;
18413 if (CondResult.Kind == IK_ICEIfUnevaluated)
18414 return CondResult;
18415 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
18416 return NoDiag();
18417 // Rare case where the diagnostics depend on which side is evaluated
18418 // Note that if we get here, CondResult is 0, and at least one of
18419 // TrueResult and FalseResult is non-zero.
18420 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
18421 return FalseResult;
18422 return TrueResult;
18423 }
18424 case Expr::CXXDefaultArgExprClass:
18425 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
18426 case Expr::CXXDefaultInitExprClass:
18427 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
18428 case Expr::ChooseExprClass: {
18429 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
18430 }
18431 case Expr::BuiltinBitCastExprClass: {
18432 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
18433 return ICEDiag(IK_NotICE, E->getBeginLoc());
18434 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
18435 }
18436 }
18437
18438 llvm_unreachable("Invalid StmtClass!");
18439}
18440
18441/// Evaluate an expression as a C++11 integral constant expression.
18443 const Expr *E,
18444 llvm::APSInt *Value) {
18446 return false;
18447
18448 APValue Result;
18449 if (!E->isCXX11ConstantExpr(Ctx, &Result))
18450 return false;
18451
18452 if (!Result.isInt())
18453 return false;
18454
18455 if (Value) *Value = Result.getInt();
18456 return true;
18457}
18458
18460 assert(!isValueDependent() &&
18461 "Expression evaluator can't be called on a dependent expression.");
18462
18463 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
18464
18465 if (Ctx.getLangOpts().CPlusPlus11)
18466 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
18467
18468 ICEDiag D = CheckICE(this, Ctx);
18469 if (D.Kind != IK_ICE)
18470 return false;
18471 return true;
18472}
18473
18474std::optional<llvm::APSInt>
18476 if (isValueDependent()) {
18477 // Expression evaluator can't succeed on a dependent expression.
18478 return std::nullopt;
18479 }
18480
18481 if (Ctx.getLangOpts().CPlusPlus11) {
18482 APSInt Value;
18484 return Value;
18485 return std::nullopt;
18486 }
18487
18488 if (!isIntegerConstantExpr(Ctx))
18489 return std::nullopt;
18490
18491 // The only possible side-effects here are due to UB discovered in the
18492 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
18493 // required to treat the expression as an ICE, so we produce the folded
18494 // value.
18496 Expr::EvalStatus Status;
18497 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
18498 Info.InConstantContext = true;
18499
18500 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
18501 llvm_unreachable("ICE cannot be evaluated!");
18502
18503 return ExprResult.Val.getInt();
18504}
18505
18507 assert(!isValueDependent() &&
18508 "Expression evaluator can't be called on a dependent expression.");
18509
18510 return CheckICE(this, Ctx).Kind == IK_ICE;
18511}
18512
18514 assert(!isValueDependent() &&
18515 "Expression evaluator can't be called on a dependent expression.");
18516
18517 // We support this checking in C++98 mode in order to diagnose compatibility
18518 // issues.
18519 assert(Ctx.getLangOpts().CPlusPlus);
18520
18521 bool IsConst;
18522 APValue Scratch;
18523 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
18524 if (Result)
18525 *Result = Scratch;
18526 return true;
18527 }
18528
18529 // Build evaluation settings.
18530 Expr::EvalStatus Status;
18532 Status.Diag = &Diags;
18533 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18534
18535 bool IsConstExpr =
18536 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
18537 // FIXME: We don't produce a diagnostic for this, but the callers that
18538 // call us on arbitrary full-expressions should generally not care.
18539 Info.discardCleanups() && !Status.HasSideEffects;
18540
18541 return IsConstExpr && Diags.empty();
18542}
18543
18545 const FunctionDecl *Callee,
18547 const Expr *This) const {
18548 assert(!isValueDependent() &&
18549 "Expression evaluator can't be called on a dependent expression.");
18550
18551 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
18552 std::string Name;
18553 llvm::raw_string_ostream OS(Name);
18554 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
18555 /*Qualified=*/true);
18556 return Name;
18557 });
18558
18559 Expr::EvalStatus Status;
18560 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
18561 Info.InConstantContext = true;
18562
18563 LValue ThisVal;
18564 const LValue *ThisPtr = nullptr;
18565 if (This) {
18566#ifndef NDEBUG
18567 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
18568 assert(MD && "Don't provide `this` for non-methods.");
18569 assert(MD->isImplicitObjectMemberFunction() &&
18570 "Don't provide `this` for methods without an implicit object.");
18571#endif
18572 if (!This->isValueDependent() &&
18573 EvaluateObjectArgument(Info, This, ThisVal) &&
18574 !Info.EvalStatus.HasSideEffects)
18575 ThisPtr = &ThisVal;
18576
18577 // Ignore any side-effects from a failed evaluation. This is safe because
18578 // they can't interfere with any other argument evaluation.
18579 Info.EvalStatus.HasSideEffects = false;
18580 }
18581
18582 CallRef Call = Info.CurrentCall->createCall(Callee);
18583 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
18584 I != E; ++I) {
18585 unsigned Idx = I - Args.begin();
18586 if (Idx >= Callee->getNumParams())
18587 break;
18588 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
18589 if ((*I)->isValueDependent() ||
18590 !EvaluateCallArg(PVD, *I, Call, Info) ||
18591 Info.EvalStatus.HasSideEffects) {
18592 // If evaluation fails, throw away the argument entirely.
18593 if (APValue *Slot = Info.getParamSlot(Call, PVD))
18594 *Slot = APValue();
18595 }
18596
18597 // Ignore any side-effects from a failed evaluation. This is safe because
18598 // they can't interfere with any other argument evaluation.
18599 Info.EvalStatus.HasSideEffects = false;
18600 }
18601
18602 // Parameter cleanups happen in the caller and are not part of this
18603 // evaluation.
18604 Info.discardCleanups();
18605 Info.EvalStatus.HasSideEffects = false;
18606
18607 // Build fake call to Callee.
18608 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
18609 Call);
18610 // FIXME: Missing ExprWithCleanups in enable_if conditions?
18611 FullExpressionRAII Scope(Info);
18612 return Evaluate(Value, Info, this) && Scope.destroy() &&
18613 !Info.EvalStatus.HasSideEffects;
18614}
18615
18618 PartialDiagnosticAt> &Diags) {
18619 // FIXME: It would be useful to check constexpr function templates, but at the
18620 // moment the constant expression evaluator cannot cope with the non-rigorous
18621 // ASTs which we build for dependent expressions.
18622 if (FD->isDependentContext())
18623 return true;
18624
18625 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
18626 std::string Name;
18627 llvm::raw_string_ostream OS(Name);
18629 /*Qualified=*/true);
18630 return Name;
18631 });
18632
18633 Expr::EvalStatus Status;
18634 Status.Diag = &Diags;
18635
18636 EvalInfo Info(FD->getASTContext(), Status,
18638 Info.InConstantContext = true;
18639 Info.CheckingPotentialConstantExpression = true;
18640
18641 // The constexpr VM attempts to compile all methods to bytecode here.
18642 if (Info.EnableNewConstInterp) {
18643 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
18644 return Diags.empty();
18645 }
18646
18647 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
18648 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
18649
18650 // Fabricate an arbitrary expression on the stack and pretend that it
18651 // is a temporary being used as the 'this' pointer.
18652 LValue This;
18653 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
18654 : Info.Ctx.IntTy);
18655 This.set({&VIE, Info.CurrentCall->Index});
18656
18658
18659 APValue Scratch;
18660 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
18661 // Evaluate the call as a constant initializer, to allow the construction
18662 // of objects of non-literal types.
18663 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
18664 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
18665 } else {
18666 SourceLocation Loc = FD->getLocation();
18668 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
18669 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
18670 /*ResultSlot=*/nullptr);
18671 }
18672
18673 return Diags.empty();
18674}
18675
18677 const FunctionDecl *FD,
18679 PartialDiagnosticAt> &Diags) {
18680 assert(!E->isValueDependent() &&
18681 "Expression evaluator can't be called on a dependent expression.");
18682
18683 Expr::EvalStatus Status;
18684 Status.Diag = &Diags;
18685
18686 EvalInfo Info(FD->getASTContext(), Status,
18688 Info.InConstantContext = true;
18689 Info.CheckingPotentialConstantExpression = true;
18690
18691 if (Info.EnableNewConstInterp) {
18693 return Diags.empty();
18694 }
18695
18696 // Fabricate a call stack frame to give the arguments a plausible cover story.
18697 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
18698 /*CallExpr=*/nullptr, CallRef());
18699
18700 APValue ResultScratch;
18701 Evaluate(ResultScratch, Info, E);
18702 return Diags.empty();
18703}
18704
18706 unsigned Type) const {
18707 if (!getType()->isPointerType())
18708 return false;
18709
18710 Expr::EvalStatus Status;
18711 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18712 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
18713}
18714
18715static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
18716 EvalInfo &Info, std::string *StringResult) {
18717 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
18718 return false;
18719
18720 LValue String;
18721
18722 if (!EvaluatePointer(E, String, Info))
18723 return false;
18724
18725 QualType CharTy = E->getType()->getPointeeType();
18726
18727 // Fast path: if it's a string literal, search the string value.
18728 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
18729 String.getLValueBase().dyn_cast<const Expr *>())) {
18730 StringRef Str = S->getBytes();
18731 int64_t Off = String.Offset.getQuantity();
18732 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
18733 S->getCharByteWidth() == 1 &&
18734 // FIXME: Add fast-path for wchar_t too.
18735 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
18736 Str = Str.substr(Off);
18737
18738 StringRef::size_type Pos = Str.find(0);
18739 if (Pos != StringRef::npos)
18740 Str = Str.substr(0, Pos);
18741
18742 Result = Str.size();
18743 if (StringResult)
18744 *StringResult = Str;
18745 return true;
18746 }
18747
18748 // Fall through to slow path.
18749 }
18750
18751 // Slow path: scan the bytes of the string looking for the terminating 0.
18752 for (uint64_t Strlen = 0; /**/; ++Strlen) {
18753 APValue Char;
18754 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
18755 !Char.isInt())
18756 return false;
18757 if (!Char.getInt()) {
18758 Result = Strlen;
18759 return true;
18760 } else if (StringResult)
18761 StringResult->push_back(Char.getInt().getExtValue());
18762 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
18763 return false;
18764 }
18765}
18766
18767std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
18768 Expr::EvalStatus Status;
18769 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18770 uint64_t Result;
18771 std::string StringResult;
18772
18773 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
18774 return StringResult;
18775 return {};
18776}
18777
18778template <typename T>
18779static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
18780 const Expr *SizeExpression,
18781 const Expr *PtrExpression,
18782 ASTContext &Ctx,
18783 Expr::EvalResult &Status) {
18784 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
18785 Info.InConstantContext = true;
18786
18787 if (Info.EnableNewConstInterp)
18788 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
18789 PtrExpression, Result);
18790
18791 LValue String;
18792 FullExpressionRAII Scope(Info);
18793 APSInt SizeValue;
18794 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
18795 return false;
18796
18797 uint64_t Size = SizeValue.getZExtValue();
18798
18799 // FIXME: better protect against invalid or excessive sizes
18800 if constexpr (std::is_same_v<APValue, T>)
18801 Result = APValue(APValue::UninitArray{}, Size, Size);
18802 else {
18803 if (Size < Result.max_size())
18804 Result.reserve(Size);
18805 }
18806 if (!::EvaluatePointer(PtrExpression, String, Info))
18807 return false;
18808
18809 QualType CharTy = PtrExpression->getType()->getPointeeType();
18810 for (uint64_t I = 0; I < Size; ++I) {
18811 APValue Char;
18812 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
18813 Char))
18814 return false;
18815
18816 if constexpr (std::is_same_v<APValue, T>) {
18817 Result.getArrayInitializedElt(I) = std::move(Char);
18818 } else {
18819 APSInt C = Char.getInt();
18820
18821 assert(C.getBitWidth() <= 8 &&
18822 "string element not representable in char");
18823
18824 Result.push_back(static_cast<char>(C.getExtValue()));
18825 }
18826
18827 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
18828 return false;
18829 }
18830
18831 return Scope.destroy() && CheckMemoryLeaks(Info);
18832}
18833
18835 const Expr *SizeExpression,
18836 const Expr *PtrExpression, ASTContext &Ctx,
18837 EvalResult &Status) const {
18838 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18839 PtrExpression, Ctx, Status);
18840}
18841
18843 const Expr *SizeExpression,
18844 const Expr *PtrExpression, ASTContext &Ctx,
18845 EvalResult &Status) const {
18846 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18847 PtrExpression, Ctx, Status);
18848}
18849
18850bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
18851 Expr::EvalStatus Status;
18852 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
18853
18854 if (Info.EnableNewConstInterp)
18855 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
18856
18857 return EvaluateBuiltinStrLen(this, Result, Info);
18858}
18859
18860namespace {
18861struct IsWithinLifetimeHandler {
18862 EvalInfo &Info;
18863 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
18864 using result_type = std::optional<bool>;
18865 std::optional<bool> failed() { return std::nullopt; }
18866 template <typename T>
18867 std::optional<bool> found(T &Subobj, QualType SubobjType) {
18868 return true;
18869 }
18870};
18871
18872std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
18873 const CallExpr *E) {
18874 EvalInfo &Info = IEE.Info;
18875 // Sometimes this is called during some sorts of constant folding / early
18876 // evaluation. These are meant for non-constant expressions and are not
18877 // necessary since this consteval builtin will never be evaluated at runtime.
18878 // Just fail to evaluate when not in a constant context.
18879 if (!Info.InConstantContext)
18880 return std::nullopt;
18881 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
18882 const Expr *Arg = E->getArg(0);
18883 if (Arg->isValueDependent())
18884 return std::nullopt;
18885 LValue Val;
18886 if (!EvaluatePointer(Arg, Val, Info))
18887 return std::nullopt;
18888
18889 if (Val.allowConstexprUnknown())
18890 return true;
18891
18892 auto Error = [&](int Diag) {
18893 bool CalledFromStd = false;
18894 const auto *Callee = Info.CurrentCall->getCallee();
18895 if (Callee && Callee->isInStdNamespace()) {
18896 const IdentifierInfo *Identifier = Callee->getIdentifier();
18897 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
18898 }
18899 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
18900 : E->getExprLoc(),
18901 diag::err_invalid_is_within_lifetime)
18902 << (CalledFromStd ? "std::is_within_lifetime"
18903 : "__builtin_is_within_lifetime")
18904 << Diag;
18905 return std::nullopt;
18906 };
18907 // C++2c [meta.const.eval]p4:
18908 // During the evaluation of an expression E as a core constant expression, a
18909 // call to this function is ill-formed unless p points to an object that is
18910 // usable in constant expressions or whose complete object's lifetime began
18911 // within E.
18912
18913 // Make sure it points to an object
18914 // nullptr does not point to an object
18915 if (Val.isNullPointer() || Val.getLValueBase().isNull())
18916 return Error(0);
18917 QualType T = Val.getLValueBase().getType();
18918 assert(!T->isFunctionType() &&
18919 "Pointers to functions should have been typed as function pointers "
18920 "which would have been rejected earlier");
18921 assert(T->isObjectType());
18922 // Hypothetical array element is not an object
18923 if (Val.getLValueDesignator().isOnePastTheEnd())
18924 return Error(1);
18925 assert(Val.getLValueDesignator().isValidSubobject() &&
18926 "Unchecked case for valid subobject");
18927 // All other ill-formed values should have failed EvaluatePointer, so the
18928 // object should be a pointer to an object that is usable in a constant
18929 // expression or whose complete lifetime began within the expression
18930 CompleteObject CO =
18931 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18932 // The lifetime hasn't begun yet if we are still evaluating the
18933 // initializer ([basic.life]p(1.2))
18934 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18935 return Error(2);
18936
18937 if (!CO)
18938 return false;
18939 IsWithinLifetimeHandler handler{Info};
18940 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18941}
18942} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
llvm::APSInt APSInt
Definition Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:584
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isAbsent() const
Definition APValue.h:463
bool isComplexInt() const
Definition APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:204
ValueKind getKind() const
Definition APValue.h:461
unsigned getArrayInitializedElts() const
Definition APValue.h:595
static APValue IndeterminateValue()
Definition APValue.h:432
bool isFloat() const
Definition APValue.h:468
APFixedPoint & getFixedPoint()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:465
bool hasLValuePath() const
Definition APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
CharUnits & getLValueOffset()
Definition APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
APValue & getArrayFiller()
Definition APValue.h:587
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1059
bool isIndeterminate() const
Definition APValue.h:464
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool allowConstexprUnknown() const
Definition APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
bool isFixedPoint() const
Definition APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
APValue & getStructBase(unsigned i)
Definition APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
SourceManager & getSourceManager()
Definition ASTContext.h:798
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
CanQualType VoidPtrTy
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:739
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
CanQualType CharTy
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType IntTy
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:790
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:856
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4507
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
uint64_t getValue() const
Definition ExprCXX.h:3038
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
QualType getElementType() const
Definition TypeBase.h:3732
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8084
Attr - This represents one attribute.
Definition Attr.h:44
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4387
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4425
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4422
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4066
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4072
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4119
SourceLocation getExprLoc() const
Definition Expr.h:4013
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4049
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4108
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4770
const BlockDecl * getBlockDecl() const
Definition Expr.h:6570
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:431
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1618
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2690
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2659
bool isArrayForm() const
Definition ExprCXX.h:2646
bool isGlobalDelete() const
Definition ExprCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1790
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isInstance() const
Definition DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2845
QualType getAllocatedType() const
Definition ExprCXX.h:2428
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2463
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2497
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2488
SourceRange getSourceRange() const
Definition ExprCXX.h:2604
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2453
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2527
bool getValue() const
Definition ExprCXX.h:4326
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5175
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1673
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1784
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
bool isImplicit() const
Definition ExprCXX.h:1178
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3569
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1588
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
Decl * getCalleeDecl()
Definition Expr.h:3054
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
Expr * getLHS()
Definition Stmt.h:2003
Expr * getRHS()
Definition Stmt.h:2015
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
unsigned path_size() const
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3677
bool path_empty() const
Definition Expr.h:3678
Expr * getSubExpr()
Definition Expr.h:3660
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3724
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1629
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4818
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4234
QualType getComputationLHSType() const
Definition Expr.h:4268
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
bool hasStaticStorage() const
Definition Expr.h:3584
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5538
bool isFileScope() const
Definition Expr.h:3571
const Expr * getInitializer() const
Definition Expr.h:3567
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
bool body_empty() const
Definition Stmt.h:1764
Stmt *const * const_body_iterator
Definition Stmt.h:1792
body_iterator body_end()
Definition Stmt.h:1785
body_range body()
Definition Stmt.h:1783
body_iterator body_begin()
Definition Stmt.h:1784
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4357
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4348
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4352
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3821
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:254
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3847
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3828
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3854
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
APValue getAPValueResult() const
Definition Expr.cpp:409
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4730
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4743
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
ValueDecl * getDecl()
Definition Expr.h:1338
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
decl_range decls()
Definition Stmt.h:1659
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:427
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
A decomposition declaration.
Definition DeclCXX.h:4249
auto flat_bindings() const
Definition DeclCXX.h:4292
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2832
Stmt * getBody()
Definition Stmt.h:2857
Expr * getCond()
Definition Stmt.h:2850
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
ChildElementIter< false > begin()
Definition Expr.h:5166
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3889
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:80
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:670
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:672
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3963
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3665
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3248
Expr()=delete
ConstantExprKind
Definition Expr.h:749
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4412
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4444
const Expr * getBase() const
Definition Expr.h:6515
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3404
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1575
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Stmt * getInit()
Definition Stmt.h:2903
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1078
Stmt * getBody()
Definition Stmt.h:2932
Expr * getInc()
Definition Stmt.h:2931
Expr * getCond()
Definition Stmt.h:2930
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3271
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2780
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3414
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:3117
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6396
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2259
Stmt * getThen()
Definition Stmt.h:2348
Stmt * getInit()
Definition Stmt.h:2409
bool isNonNegatedConsteval() const
Definition Stmt.h:2444
Expr * getCond()
Definition Stmt.h:2336
Stmt * getElse()
Definition Stmt.h:2357
bool isConsteval() const
Definition Stmt.h:2439
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1026
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3485
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2457
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2443
unsigned getNumInits() const
Definition Expr.h:5263
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
ArrayRef< Expr * > inits()
Definition Expr.h:5283
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2108
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2096
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4914
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4939
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4931
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4947
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
This represents a decl that may have a name.
Definition Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2586
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2574
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2567
unsigned getNumComponents() const
Definition Expr.h:2582
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2479
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2426
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2430
@ Field
A field.
Definition Expr.h:2428
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2433
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2475
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
Expr * getSelectedExpr() const
Definition ExprCXX.h:4633
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
bool isExplicitObjectParameter() const
Definition Decl.h:1877
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6738
ArrayRef< Expr * > semantics()
Definition Expr.h:6762
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8470
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
void removeLocalVolatile()
Definition TypeBase.h:8401
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8393
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8331
Represents a struct/union/class.
Definition Decl.h:4309
field_iterator field_end() const
Definition Decl.h:4515
field_range fields() const
Definition Decl.h:4512
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4361
bool field_empty() const
Definition Decl.h:4520
field_iterator field_begin() const
Definition Decl.cpp:5154
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2155
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:583
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4577
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4629
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4610
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4616
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4509
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2277
bool isIntType() const
Definition Expr.h:4975
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Definition Expr.h:4546
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
unsigned getLength() const
Definition Expr.h:1909
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1875
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
unsigned getCharByteWidth() const
Definition Expr.h:1910
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1893
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
Expr * getCond()
Definition Stmt.h:2572
Stmt * getBody()
Definition Stmt.h:2584
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1144
Stmt * getInit()
Definition Stmt.h:2589
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2640
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
unsigned getCharWidth() const
Definition TargetInfo.h:517
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
bool getBoolValue() const
Definition ExprCXX.h:2941
const APValue & getAPValue() const
Definition ExprCXX.h:2946
bool isStoredAsBoolean() const
Definition ExprCXX.h:2937
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isFunctionReferenceType() const
Definition TypeBase.h:8596
bool isMFloat8Type() const
Definition TypeBase.h:8903
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:418
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9174
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8625
bool isNothrowT() const
Definition Type.cpp:3171
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8633
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool isExtVectorBoolType() const
Definition TypeBase.h:8669
bool isMemberDataPointerType() const
Definition TypeBase.h:8614
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8657
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isAtomicType() const
Definition TypeBase.h:8704
bool isComplexIntegerType() const
Definition Type.cpp:730
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isVectorType() const
Definition TypeBase.h:8661
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9042
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
QualType getArgumentType() const
Definition Expr.h:2668
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2704
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2694
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2326
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2298
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:925
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1568
bool hasInit() const
Definition Decl.cpp:2398
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2636
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1577
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2575
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2877
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2648
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2486
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2557
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1176
const Expr * getInit() const
Definition Decl.h:1367
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2628
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1183
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1252
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2528
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1357
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
Expr * getCond()
Definition Stmt.h:2749
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1205
Stmt * getBody()
Definition Stmt.h:2761
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:223
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:239
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:56
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:36
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:69
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:99
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1260
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:41
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2814
llvm::APFloat APFloat
Definition Floating.h:27
llvm::APInt APInt
Definition FixedPoint.h:19
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3477
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:42
@ CSK_ArrayToPointer
Definition State.h:46
@ CSK_Derived
Definition State.h:44
@ CSK_Base
Definition State.h:43
@ CSK_Real
Definition State.h:48
@ CSK_ArrayIndex
Definition State.h:47
@ CSK_Imag
Definition State.h:49
@ CSK_VectorElement
Definition State.h:50
@ CSK_Field
Definition State.h:45
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:26
@ AK_TypeId
Definition State.h:34
@ AK_Construct
Definition State.h:35
@ AK_Increment
Definition State.h:30
@ AK_DynamicCast
Definition State.h:33
@ AK_Read
Definition State.h:27
@ AK_Assign
Definition State.h:29
@ AK_IsWithinLifetime
Definition State.h:37
@ AK_MemberCall
Definition State.h:32
@ AK_ReadObjectRepresentation
Definition State.h:28
@ AK_Dereference
Definition State.h:38
@ AK_Destroy
Definition State.h:36
@ AK_Decrement
Definition State.h:31
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:146
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:609
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165