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
89 static QualType getType(APValue::LValueBase B) {
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(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(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) {
460 if (Invalid || !N) return;
461 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
462 if (isMostDerivedAnUnsizedArray()) {
463 diagnoseUnsizedArrayPointerArithmetic(Info, E);
464 // Can't verify -- trust that the user is doing the right thing (or if
465 // not, trust that the caller will catch the bad behavior).
466 // FIXME: Should we reject if this overflows, at least?
467 Entries.back() = PathEntry::ArrayIndex(
468 Entries.back().getAsArrayIndex() + TruncatedN);
469 return;
470 }
471
472 // [expr.add]p4: For the purposes of these operators, a pointer to a
473 // nonarray object behaves the same as a pointer to the first element of
474 // an array of length one with the type of the object as its element type.
475 bool IsArray = MostDerivedPathLength == Entries.size() &&
476 MostDerivedIsArrayElement;
477 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
478 : (uint64_t)IsOnePastTheEnd;
479 uint64_t ArraySize =
480 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
481
482 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
483 // Calculate the actual index in a wide enough type, so we can include
484 // it in the note.
485 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
486 (llvm::APInt&)N += ArrayIndex;
487 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
488 diagnosePointerArithmetic(Info, E, N);
489 setInvalid();
490 return;
491 }
492
493 ArrayIndex += TruncatedN;
494 assert(ArrayIndex <= ArraySize &&
495 "bounds check succeeded for out-of-bounds index");
496
497 if (IsArray)
498 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
499 else
500 IsOnePastTheEnd = (ArrayIndex != 0);
501 }
502 };
503
504 /// A scope at the end of which an object can need to be destroyed.
505 enum class ScopeKind {
506 Block,
507 FullExpression,
508 Call
509 };
510
511 /// A reference to a particular call and its arguments.
512 struct CallRef {
513 CallRef() : OrigCallee(), CallIndex(0), Version() {}
514 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
515 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
516
517 explicit operator bool() const { return OrigCallee; }
518
519 /// Get the parameter that the caller initialized, corresponding to the
520 /// given parameter in the callee.
521 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
522 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
523 : PVD;
524 }
525
526 /// The callee at the point where the arguments were evaluated. This might
527 /// be different from the actual callee (a different redeclaration, or a
528 /// virtual override), but this function's parameters are the ones that
529 /// appear in the parameter map.
530 const FunctionDecl *OrigCallee;
531 /// The call index of the frame that holds the argument values.
532 unsigned CallIndex;
533 /// The version of the parameters corresponding to this call.
534 unsigned Version;
535 };
536
537 /// A stack frame in the constexpr call stack.
538 class CallStackFrame : public interp::Frame {
539 public:
540 EvalInfo &Info;
541
542 /// Parent - The caller of this stack frame.
543 CallStackFrame *Caller;
544
545 /// Callee - The function which was called.
546 const FunctionDecl *Callee;
547
548 /// This - The binding for the this pointer in this call, if any.
549 const LValue *This;
550
551 /// CallExpr - The syntactical structure of member function calls
552 const Expr *CallExpr;
553
554 /// Information on how to find the arguments to this call. Our arguments
555 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
556 /// key and this value as the version.
557 CallRef Arguments;
558
559 /// Source location information about the default argument or default
560 /// initializer expression we're evaluating, if any.
561 CurrentSourceLocExprScope CurSourceLocExprScope;
562
563 // Note that we intentionally use std::map here so that references to
564 // values are stable.
565 typedef std::pair<const void *, unsigned> MapKeyTy;
566 typedef std::map<MapKeyTy, APValue> MapTy;
567 /// Temporaries - Temporary lvalues materialized within this stack frame.
568 MapTy Temporaries;
569
570 /// CallRange - The source range of the call expression for this call.
571 SourceRange CallRange;
572
573 /// Index - The call index of this call.
574 unsigned Index;
575
576 /// The stack of integers for tracking version numbers for temporaries.
577 SmallVector<unsigned, 2> TempVersionStack = {1};
578 unsigned CurTempVersion = TempVersionStack.back();
579
580 unsigned getTempVersion() const { return TempVersionStack.back(); }
581
582 void pushTempVersion() {
583 TempVersionStack.push_back(++CurTempVersion);
584 }
585
586 void popTempVersion() {
587 TempVersionStack.pop_back();
588 }
589
590 CallRef createCall(const FunctionDecl *Callee) {
591 return {Callee, Index, ++CurTempVersion};
592 }
593
594 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
595 // on the overall stack usage of deeply-recursing constexpr evaluations.
596 // (We should cache this map rather than recomputing it repeatedly.)
597 // But let's try this and see how it goes; we can look into caching the map
598 // as a later change.
599
600 /// LambdaCaptureFields - Mapping from captured variables/this to
601 /// corresponding data members in the closure class.
602 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
603 FieldDecl *LambdaThisCaptureField = nullptr;
604
605 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
606 const FunctionDecl *Callee, const LValue *This,
607 const Expr *CallExpr, CallRef Arguments);
608 ~CallStackFrame();
609
610 // Return the temporary for Key whose version number is Version.
611 APValue *getTemporary(const void *Key, unsigned Version) {
612 MapKeyTy KV(Key, Version);
613 auto LB = Temporaries.lower_bound(KV);
614 if (LB != Temporaries.end() && LB->first == KV)
615 return &LB->second;
616 return nullptr;
617 }
618
619 // Return the current temporary for Key in the map.
620 APValue *getCurrentTemporary(const void *Key) {
621 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
622 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
623 return &std::prev(UB)->second;
624 return nullptr;
625 }
626
627 // Return the version number of the current temporary for Key.
628 unsigned getCurrentTemporaryVersion(const void *Key) const {
629 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
630 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
631 return std::prev(UB)->first.second;
632 return 0;
633 }
634
635 /// Allocate storage for an object of type T in this stack frame.
636 /// Populates LV with a handle to the created object. Key identifies
637 /// the temporary within the stack frame, and must not be reused without
638 /// bumping the temporary version number.
639 template<typename KeyT>
640 APValue &createTemporary(const KeyT *Key, QualType T,
641 ScopeKind Scope, LValue &LV);
642
643 /// Allocate storage for a parameter of a function call made in this frame.
644 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
645
646 void describe(llvm::raw_ostream &OS) const override;
647
648 Frame *getCaller() const override { return Caller; }
649 SourceRange getCallRange() const override { return CallRange; }
650 const FunctionDecl *getCallee() const override { return Callee; }
651
652 bool isStdFunction() const {
653 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
654 if (DC->isStdNamespace())
655 return true;
656 return false;
657 }
658
659 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
660 /// permitted. See MSConstexprDocs for description of permitted contexts.
661 bool CanEvalMSConstexpr = false;
662
663 private:
664 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
665 ScopeKind Scope);
666 };
667
668 /// Temporarily override 'this'.
669 class ThisOverrideRAII {
670 public:
671 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
672 : Frame(Frame), OldThis(Frame.This) {
673 if (Enable)
674 Frame.This = NewThis;
675 }
676 ~ThisOverrideRAII() {
677 Frame.This = OldThis;
678 }
679 private:
680 CallStackFrame &Frame;
681 const LValue *OldThis;
682 };
683
684 // A shorthand time trace scope struct, prints source range, for example
685 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
686 class ExprTimeTraceScope {
687 public:
688 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
689 : TimeScope(Name, [E, &Ctx] {
690 return E->getSourceRange().printToString(Ctx.getSourceManager());
691 }) {}
692
693 private:
694 llvm::TimeTraceScope TimeScope;
695 };
696
697 /// RAII object used to change the current ability of
698 /// [[msvc::constexpr]] evaulation.
699 struct MSConstexprContextRAII {
700 CallStackFrame &Frame;
701 bool OldValue;
702 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
703 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
704 Frame.CanEvalMSConstexpr = Value;
705 }
706
707 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
708 };
709}
710
711static bool HandleDestruction(EvalInfo &Info, const Expr *E,
712 const LValue &This, QualType ThisType);
713static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
715 QualType T);
716
717namespace {
718 /// A cleanup, and a flag indicating whether it is lifetime-extended.
719 class Cleanup {
720 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
722 QualType T;
723
724 public:
725 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
726 ScopeKind Scope)
727 : Value(Val, Scope), Base(Base), T(T) {}
728
729 /// Determine whether this cleanup should be performed at the end of the
730 /// given kind of scope.
731 bool isDestroyedAtEndOf(ScopeKind K) const {
732 return (int)Value.getInt() >= (int)K;
733 }
734 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
735 if (RunDestructors) {
737 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
738 Loc = VD->getLocation();
739 else if (const Expr *E = Base.dyn_cast<const Expr*>())
740 Loc = E->getExprLoc();
741 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
742 }
743 *Value.getPointer() = APValue();
744 return true;
745 }
746
747 bool hasSideEffect() {
748 return T.isDestructedType();
749 }
750 };
751
752 /// A reference to an object whose construction we are currently evaluating.
753 struct ObjectUnderConstruction {
756 friend bool operator==(const ObjectUnderConstruction &LHS,
757 const ObjectUnderConstruction &RHS) {
758 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
759 }
760 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
761 return llvm::hash_combine(Obj.Base, Obj.Path);
762 }
763 };
764 enum class ConstructionPhase {
765 None,
766 Bases,
767 AfterBases,
768 AfterFields,
769 Destroying,
770 DestroyingBases
771 };
772}
773
774namespace llvm {
775template<> struct DenseMapInfo<ObjectUnderConstruction> {
776 using Base = DenseMapInfo<APValue::LValueBase>;
777 static ObjectUnderConstruction getEmptyKey() {
778 return {Base::getEmptyKey(), {}}; }
779 static ObjectUnderConstruction getTombstoneKey() {
780 return {Base::getTombstoneKey(), {}};
781 }
782 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
783 return hash_value(Object);
784 }
785 static bool isEqual(const ObjectUnderConstruction &LHS,
786 const ObjectUnderConstruction &RHS) {
787 return LHS == RHS;
788 }
789};
790}
791
792namespace {
793 /// A dynamically-allocated heap object.
794 struct DynAlloc {
795 /// The value of this heap-allocated object.
797 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
798 /// or a CallExpr (the latter is for direct calls to operator new inside
799 /// std::allocator<T>::allocate).
800 const Expr *AllocExpr = nullptr;
801
802 enum Kind {
803 New,
804 ArrayNew,
805 StdAllocator
806 };
807
808 /// Get the kind of the allocation. This must match between allocation
809 /// and deallocation.
810 Kind getKind() const {
811 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
812 return NE->isArray() ? ArrayNew : New;
813 assert(isa<CallExpr>(AllocExpr));
814 return StdAllocator;
815 }
816 };
817
818 struct DynAllocOrder {
819 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
820 return L.getIndex() < R.getIndex();
821 }
822 };
823
824 /// EvalInfo - This is a private struct used by the evaluator to capture
825 /// information about a subexpression as it is folded. It retains information
826 /// about the AST context, but also maintains information about the folded
827 /// expression.
828 ///
829 /// If an expression could be evaluated, it is still possible it is not a C
830 /// "integer constant expression" or constant expression. If not, this struct
831 /// captures information about how and why not.
832 ///
833 /// One bit of information passed *into* the request for constant folding
834 /// indicates whether the subexpression is "evaluated" or not according to C
835 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
836 /// evaluate the expression regardless of what the RHS is, but C only allows
837 /// certain things in certain situations.
838 class EvalInfo : public interp::State {
839 public:
840 ASTContext &Ctx;
841
842 /// EvalStatus - Contains information about the evaluation.
843 Expr::EvalStatus &EvalStatus;
844
845 /// CurrentCall - The top of the constexpr call stack.
846 CallStackFrame *CurrentCall;
847
848 /// CallStackDepth - The number of calls in the call stack right now.
849 unsigned CallStackDepth;
850
851 /// NextCallIndex - The next call index to assign.
852 unsigned NextCallIndex;
853
854 /// StepsLeft - The remaining number of evaluation steps we're permitted
855 /// to perform. This is essentially a limit for the number of statements
856 /// we will evaluate.
857 unsigned StepsLeft;
858
859 /// Enable the experimental new constant interpreter. If an expression is
860 /// not supported by the interpreter, an error is triggered.
861 bool EnableNewConstInterp;
862
863 /// BottomFrame - The frame in which evaluation started. This must be
864 /// initialized after CurrentCall and CallStackDepth.
865 CallStackFrame BottomFrame;
866
867 /// A stack of values whose lifetimes end at the end of some surrounding
868 /// evaluation frame.
870
871 /// EvaluatingDecl - This is the declaration whose initializer is being
872 /// evaluated, if any.
873 APValue::LValueBase EvaluatingDecl;
874
875 enum class EvaluatingDeclKind {
876 None,
877 /// We're evaluating the construction of EvaluatingDecl.
878 Ctor,
879 /// We're evaluating the destruction of EvaluatingDecl.
880 Dtor,
881 };
882 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
883
884 /// EvaluatingDeclValue - This is the value being constructed for the
885 /// declaration whose initializer is being evaluated, if any.
886 APValue *EvaluatingDeclValue;
887
888 /// Set of objects that are currently being constructed.
889 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
890 ObjectsUnderConstruction;
891
892 /// Current heap allocations, along with the location where each was
893 /// allocated. We use std::map here because we need stable addresses
894 /// for the stored APValues.
895 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
896
897 /// The number of heap allocations performed so far in this evaluation.
898 unsigned NumHeapAllocs = 0;
899
900 struct EvaluatingConstructorRAII {
901 EvalInfo &EI;
902 ObjectUnderConstruction Object;
903 bool DidInsert;
904 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
905 bool HasBases)
906 : EI(EI), Object(Object) {
907 DidInsert =
908 EI.ObjectsUnderConstruction
909 .insert({Object, HasBases ? ConstructionPhase::Bases
910 : ConstructionPhase::AfterBases})
911 .second;
912 }
913 void finishedConstructingBases() {
914 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
915 }
916 void finishedConstructingFields() {
917 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
918 }
919 ~EvaluatingConstructorRAII() {
920 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
921 }
922 };
923
924 struct EvaluatingDestructorRAII {
925 EvalInfo &EI;
926 ObjectUnderConstruction Object;
927 bool DidInsert;
928 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
929 : EI(EI), Object(Object) {
930 DidInsert = EI.ObjectsUnderConstruction
931 .insert({Object, ConstructionPhase::Destroying})
932 .second;
933 }
934 void startedDestroyingBases() {
935 EI.ObjectsUnderConstruction[Object] =
936 ConstructionPhase::DestroyingBases;
937 }
938 ~EvaluatingDestructorRAII() {
939 if (DidInsert)
940 EI.ObjectsUnderConstruction.erase(Object);
941 }
942 };
943
944 ConstructionPhase
945 isEvaluatingCtorDtor(APValue::LValueBase Base,
947 return ObjectsUnderConstruction.lookup({Base, Path});
948 }
949
950 /// If we're currently speculatively evaluating, the outermost call stack
951 /// depth at which we can mutate state, otherwise 0.
952 unsigned SpeculativeEvaluationDepth = 0;
953
954 /// The current array initialization index, if we're performing array
955 /// initialization.
956 uint64_t ArrayInitIndex = -1;
957
958 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
959 /// notes attached to it will also be stored, otherwise they will not be.
960 bool HasActiveDiagnostic;
961
962 /// Have we emitted a diagnostic explaining why we couldn't constant
963 /// fold (not just why it's not strictly a constant expression)?
964 bool HasFoldFailureDiagnostic;
965
966 /// Whether we're checking that an expression is a potential constant
967 /// expression. If so, do not fail on constructs that could become constant
968 /// later on (such as a use of an undefined global).
969 bool CheckingPotentialConstantExpression = false;
970
971 /// Whether we're checking for an expression that has undefined behavior.
972 /// If so, we will produce warnings if we encounter an operation that is
973 /// always undefined.
974 ///
975 /// Note that we still need to evaluate the expression normally when this
976 /// is set; this is used when evaluating ICEs in C.
977 bool CheckingForUndefinedBehavior = false;
978
979 enum EvaluationMode {
980 /// Evaluate as a constant expression. Stop if we find that the expression
981 /// is not a constant expression.
982 EM_ConstantExpression,
983
984 /// Evaluate as a constant expression. Stop if we find that the expression
985 /// is not a constant expression. Some expressions can be retried in the
986 /// optimizer if we don't constant fold them here, but in an unevaluated
987 /// context we try to fold them immediately since the optimizer never
988 /// gets a chance to look at it.
989 EM_ConstantExpressionUnevaluated,
990
991 /// Fold the expression to a constant. Stop if we hit a side-effect that
992 /// we can't model.
993 EM_ConstantFold,
994
995 /// Evaluate in any way we know how. Don't worry about side-effects that
996 /// can't be modeled.
997 EM_IgnoreSideEffects,
998 } EvalMode;
999
1000 /// Are we checking whether the expression is a potential constant
1001 /// expression?
1002 bool checkingPotentialConstantExpression() const override {
1003 return CheckingPotentialConstantExpression;
1004 }
1005
1006 /// Are we checking an expression for overflow?
1007 // FIXME: We should check for any kind of undefined or suspicious behavior
1008 // in such constructs, not just overflow.
1009 bool checkingForUndefinedBehavior() const override {
1010 return CheckingForUndefinedBehavior;
1011 }
1012
1013 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1014 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1015 CallStackDepth(0), NextCallIndex(1),
1016 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1017 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1018 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1019 /*This=*/nullptr,
1020 /*CallExpr=*/nullptr, CallRef()),
1021 EvaluatingDecl((const ValueDecl *)nullptr),
1022 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1023 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1024
1025 ~EvalInfo() {
1026 discardCleanups();
1027 }
1028
1029 ASTContext &getASTContext() const override { return Ctx; }
1030
1031 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1032 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1033 EvaluatingDecl = Base;
1034 IsEvaluatingDecl = EDK;
1035 EvaluatingDeclValue = &Value;
1036 }
1037
1038 bool CheckCallLimit(SourceLocation Loc) {
1039 // Don't perform any constexpr calls (other than the call we're checking)
1040 // when checking a potential constant expression.
1041 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1042 return false;
1043 if (NextCallIndex == 0) {
1044 // NextCallIndex has wrapped around.
1045 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1046 return false;
1047 }
1048 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1049 return true;
1050 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1051 << getLangOpts().ConstexprCallDepth;
1052 return false;
1053 }
1054
1055 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1056 uint64_t ElemCount, bool Diag) {
1057 // FIXME: GH63562
1058 // APValue stores array extents as unsigned,
1059 // so anything that is greater that unsigned would overflow when
1060 // constructing the array, we catch this here.
1061 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1062 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1063 if (Diag)
1064 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1065 return false;
1066 }
1067
1068 // FIXME: GH63562
1069 // Arrays allocate an APValue per element.
1070 // We use the number of constexpr steps as a proxy for the maximum size
1071 // of arrays to avoid exhausting the system resources, as initialization
1072 // of each element is likely to take some number of steps anyway.
1073 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1074 if (ElemCount > Limit) {
1075 if (Diag)
1076 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1077 << ElemCount << Limit;
1078 return false;
1079 }
1080 return true;
1081 }
1082
1083 std::pair<CallStackFrame *, unsigned>
1084 getCallFrameAndDepth(unsigned CallIndex) {
1085 assert(CallIndex && "no call index in getCallFrameAndDepth");
1086 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1087 // be null in this loop.
1088 unsigned Depth = CallStackDepth;
1089 CallStackFrame *Frame = CurrentCall;
1090 while (Frame->Index > CallIndex) {
1091 Frame = Frame->Caller;
1092 --Depth;
1093 }
1094 if (Frame->Index == CallIndex)
1095 return {Frame, Depth};
1096 return {nullptr, 0};
1097 }
1098
1099 bool nextStep(const Stmt *S) {
1100 if (!StepsLeft) {
1101 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1102 return false;
1103 }
1104 --StepsLeft;
1105 return true;
1106 }
1107
1108 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1109
1110 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1111 std::optional<DynAlloc *> Result;
1112 auto It = HeapAllocs.find(DA);
1113 if (It != HeapAllocs.end())
1114 Result = &It->second;
1115 return Result;
1116 }
1117
1118 /// Get the allocated storage for the given parameter of the given call.
1119 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1120 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1121 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1122 : nullptr;
1123 }
1124
1125 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1126 struct StdAllocatorCaller {
1127 unsigned FrameIndex;
1128 QualType ElemType;
1129 const Expr *Call;
1130 explicit operator bool() const { return FrameIndex != 0; };
1131 };
1132
1133 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1134 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1135 Call = Call->Caller) {
1136 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1137 if (!MD)
1138 continue;
1139 const IdentifierInfo *FnII = MD->getIdentifier();
1140 if (!FnII || !FnII->isStr(FnName))
1141 continue;
1142
1143 const auto *CTSD =
1144 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1145 if (!CTSD)
1146 continue;
1147
1148 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1149 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1150 if (CTSD->isInStdNamespace() && ClassII &&
1151 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1152 TAL[0].getKind() == TemplateArgument::Type)
1153 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1154 }
1155
1156 return {};
1157 }
1158
1159 void performLifetimeExtension() {
1160 // Disable the cleanups for lifetime-extended temporaries.
1161 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1162 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1163 });
1164 }
1165
1166 /// Throw away any remaining cleanups at the end of evaluation. If any
1167 /// cleanups would have had a side-effect, note that as an unmodeled
1168 /// side-effect and return false. Otherwise, return true.
1169 bool discardCleanups() {
1170 for (Cleanup &C : CleanupStack) {
1171 if (C.hasSideEffect() && !noteSideEffect()) {
1172 CleanupStack.clear();
1173 return false;
1174 }
1175 }
1176 CleanupStack.clear();
1177 return true;
1178 }
1179
1180 private:
1181 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1182 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1183
1184 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1185 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1186
1187 void setFoldFailureDiagnostic(bool Flag) override {
1188 HasFoldFailureDiagnostic = Flag;
1189 }
1190
1191 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1192
1193 // If we have a prior diagnostic, it will be noting that the expression
1194 // isn't a constant expression. This diagnostic is more important,
1195 // unless we require this evaluation to produce a constant expression.
1196 //
1197 // FIXME: We might want to show both diagnostics to the user in
1198 // EM_ConstantFold mode.
1199 bool hasPriorDiagnostic() override {
1200 if (!EvalStatus.Diag->empty()) {
1201 switch (EvalMode) {
1202 case EM_ConstantFold:
1203 case EM_IgnoreSideEffects:
1204 if (!HasFoldFailureDiagnostic)
1205 break;
1206 // We've already failed to fold something. Keep that diagnostic.
1207 [[fallthrough]];
1208 case EM_ConstantExpression:
1209 case EM_ConstantExpressionUnevaluated:
1210 setActiveDiagnostic(false);
1211 return true;
1212 }
1213 }
1214 return false;
1215 }
1216
1217 unsigned getCallStackDepth() override { return CallStackDepth; }
1218
1219 public:
1220 /// Should we continue evaluation after encountering a side-effect that we
1221 /// couldn't model?
1222 bool keepEvaluatingAfterSideEffect() const override {
1223 switch (EvalMode) {
1224 case EM_IgnoreSideEffects:
1225 return true;
1226
1227 case EM_ConstantExpression:
1228 case EM_ConstantExpressionUnevaluated:
1229 case EM_ConstantFold:
1230 // By default, assume any side effect might be valid in some other
1231 // evaluation of this expression from a different context.
1232 return checkingPotentialConstantExpression() ||
1233 checkingForUndefinedBehavior();
1234 }
1235 llvm_unreachable("Missed EvalMode case");
1236 }
1237
1238 /// Note that we have had a side-effect, and determine whether we should
1239 /// keep evaluating.
1240 bool noteSideEffect() override {
1241 EvalStatus.HasSideEffects = true;
1242 return keepEvaluatingAfterSideEffect();
1243 }
1244
1245 /// Should we continue evaluation after encountering undefined behavior?
1246 bool keepEvaluatingAfterUndefinedBehavior() {
1247 switch (EvalMode) {
1248 case EM_IgnoreSideEffects:
1249 case EM_ConstantFold:
1250 return true;
1251
1252 case EM_ConstantExpression:
1253 case EM_ConstantExpressionUnevaluated:
1254 return checkingForUndefinedBehavior();
1255 }
1256 llvm_unreachable("Missed EvalMode case");
1257 }
1258
1259 /// Note that we hit something that was technically undefined behavior, but
1260 /// that we can evaluate past it (such as signed overflow or floating-point
1261 /// division by zero.)
1262 bool noteUndefinedBehavior() override {
1263 EvalStatus.HasUndefinedBehavior = true;
1264 return keepEvaluatingAfterUndefinedBehavior();
1265 }
1266
1267 /// Should we continue evaluation as much as possible after encountering a
1268 /// construct which can't be reduced to a value?
1269 bool keepEvaluatingAfterFailure() const override {
1270 if (!StepsLeft)
1271 return false;
1272
1273 switch (EvalMode) {
1274 case EM_ConstantExpression:
1275 case EM_ConstantExpressionUnevaluated:
1276 case EM_ConstantFold:
1277 case EM_IgnoreSideEffects:
1278 return checkingPotentialConstantExpression() ||
1279 checkingForUndefinedBehavior();
1280 }
1281 llvm_unreachable("Missed EvalMode case");
1282 }
1283
1284 /// Notes that we failed to evaluate an expression that other expressions
1285 /// directly depend on, and determine if we should keep evaluating. This
1286 /// should only be called if we actually intend to keep evaluating.
1287 ///
1288 /// Call noteSideEffect() instead if we may be able to ignore the value that
1289 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1290 ///
1291 /// (Foo(), 1) // use noteSideEffect
1292 /// (Foo() || true) // use noteSideEffect
1293 /// Foo() + 1 // use noteFailure
1294 [[nodiscard]] bool noteFailure() {
1295 // Failure when evaluating some expression often means there is some
1296 // subexpression whose evaluation was skipped. Therefore, (because we
1297 // don't track whether we skipped an expression when unwinding after an
1298 // evaluation failure) every evaluation failure that bubbles up from a
1299 // subexpression implies that a side-effect has potentially happened. We
1300 // skip setting the HasSideEffects flag to true until we decide to
1301 // continue evaluating after that point, which happens here.
1302 bool KeepGoing = keepEvaluatingAfterFailure();
1303 EvalStatus.HasSideEffects |= KeepGoing;
1304 return KeepGoing;
1305 }
1306
1307 class ArrayInitLoopIndex {
1308 EvalInfo &Info;
1309 uint64_t OuterIndex;
1310
1311 public:
1312 ArrayInitLoopIndex(EvalInfo &Info)
1313 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1314 Info.ArrayInitIndex = 0;
1315 }
1316 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1317
1318 operator uint64_t&() { return Info.ArrayInitIndex; }
1319 };
1320 };
1321
1322 /// Object used to treat all foldable expressions as constant expressions.
1323 struct FoldConstant {
1324 EvalInfo &Info;
1325 bool Enabled;
1326 bool HadNoPriorDiags;
1327 EvalInfo::EvaluationMode OldMode;
1328
1329 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1330 : Info(Info),
1331 Enabled(Enabled),
1332 HadNoPriorDiags(Info.EvalStatus.Diag &&
1333 Info.EvalStatus.Diag->empty() &&
1334 !Info.EvalStatus.HasSideEffects),
1335 OldMode(Info.EvalMode) {
1336 if (Enabled)
1337 Info.EvalMode = EvalInfo::EM_ConstantFold;
1338 }
1339 void keepDiagnostics() { Enabled = false; }
1340 ~FoldConstant() {
1341 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1342 !Info.EvalStatus.HasSideEffects)
1343 Info.EvalStatus.Diag->clear();
1344 Info.EvalMode = OldMode;
1345 }
1346 };
1347
1348 /// RAII object used to set the current evaluation mode to ignore
1349 /// side-effects.
1350 struct IgnoreSideEffectsRAII {
1351 EvalInfo &Info;
1352 EvalInfo::EvaluationMode OldMode;
1353 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1354 : Info(Info), OldMode(Info.EvalMode) {
1355 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1356 }
1357
1358 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1359 };
1360
1361 /// RAII object used to optionally suppress diagnostics and side-effects from
1362 /// a speculative evaluation.
1363 class SpeculativeEvaluationRAII {
1364 EvalInfo *Info = nullptr;
1365 Expr::EvalStatus OldStatus;
1366 unsigned OldSpeculativeEvaluationDepth = 0;
1367
1368 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1369 Info = Other.Info;
1370 OldStatus = Other.OldStatus;
1371 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1372 Other.Info = nullptr;
1373 }
1374
1375 void maybeRestoreState() {
1376 if (!Info)
1377 return;
1378
1379 Info->EvalStatus = OldStatus;
1380 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1381 }
1382
1383 public:
1384 SpeculativeEvaluationRAII() = default;
1385
1386 SpeculativeEvaluationRAII(
1387 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1388 : Info(&Info), OldStatus(Info.EvalStatus),
1389 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1390 Info.EvalStatus.Diag = NewDiag;
1391 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1392 }
1393
1394 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1395 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1396 moveFromAndCancel(std::move(Other));
1397 }
1398
1399 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1400 maybeRestoreState();
1401 moveFromAndCancel(std::move(Other));
1402 return *this;
1403 }
1404
1405 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1406 };
1407
1408 /// RAII object wrapping a full-expression or block scope, and handling
1409 /// the ending of the lifetime of temporaries created within it.
1410 template<ScopeKind Kind>
1411 class ScopeRAII {
1412 EvalInfo &Info;
1413 unsigned OldStackSize;
1414 public:
1415 ScopeRAII(EvalInfo &Info)
1416 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1417 // Push a new temporary version. This is needed to distinguish between
1418 // temporaries created in different iterations of a loop.
1419 Info.CurrentCall->pushTempVersion();
1420 }
1421 bool destroy(bool RunDestructors = true) {
1422 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1423 OldStackSize = std::numeric_limits<unsigned>::max();
1424 return OK;
1425 }
1426 ~ScopeRAII() {
1427 if (OldStackSize != std::numeric_limits<unsigned>::max())
1428 destroy(false);
1429 // Body moved to a static method to encourage the compiler to inline away
1430 // instances of this class.
1431 Info.CurrentCall->popTempVersion();
1432 }
1433 private:
1434 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1435 unsigned OldStackSize) {
1436 assert(OldStackSize <= Info.CleanupStack.size() &&
1437 "running cleanups out of order?");
1438
1439 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1440 // for a full-expression scope.
1441 bool Success = true;
1442 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1443 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1444 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1445 Success = false;
1446 break;
1447 }
1448 }
1449 }
1450
1451 // Compact any retained cleanups.
1452 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1453 if (Kind != ScopeKind::Block)
1454 NewEnd =
1455 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1456 return C.isDestroyedAtEndOf(Kind);
1457 });
1458 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1459 return Success;
1460 }
1461 };
1462 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1463 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1464 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1465}
1466
1467bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1468 CheckSubobjectKind CSK) {
1469 if (Invalid)
1470 return false;
1471 if (isOnePastTheEnd()) {
1472 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1473 << CSK;
1474 setInvalid();
1475 return false;
1476 }
1477 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1478 // must actually be at least one array element; even a VLA cannot have a
1479 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1480 return true;
1481}
1482
1483void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1484 const Expr *E) {
1485 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1486 // Do not set the designator as invalid: we can represent this situation,
1487 // and correct handling of __builtin_object_size requires us to do so.
1488}
1489
1490void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1491 const Expr *E,
1492 const APSInt &N) {
1493 // If we're complaining, we must be able to statically determine the size of
1494 // the most derived array.
1495 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1496 Info.CCEDiag(E, diag::note_constexpr_array_index)
1497 << N << /*array*/ 0
1498 << static_cast<unsigned>(getMostDerivedArraySize());
1499 else
1500 Info.CCEDiag(E, diag::note_constexpr_array_index)
1501 << N << /*non-array*/ 1;
1502 setInvalid();
1503}
1504
1505CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1506 const FunctionDecl *Callee, const LValue *This,
1507 const Expr *CallExpr, CallRef Call)
1508 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1509 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1510 Index(Info.NextCallIndex++) {
1511 Info.CurrentCall = this;
1512 ++Info.CallStackDepth;
1513}
1514
1515CallStackFrame::~CallStackFrame() {
1516 assert(Info.CurrentCall == this && "calls retired out of order");
1517 --Info.CallStackDepth;
1518 Info.CurrentCall = Caller;
1519}
1520
1521static bool isRead(AccessKinds AK) {
1522 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1523 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1524}
1525
1527 switch (AK) {
1528 case AK_Read:
1530 case AK_MemberCall:
1531 case AK_DynamicCast:
1532 case AK_TypeId:
1534 case AK_Dereference:
1535 return false;
1536 case AK_Assign:
1537 case AK_Increment:
1538 case AK_Decrement:
1539 case AK_Construct:
1540 case AK_Destroy:
1541 return true;
1542 }
1543 llvm_unreachable("unknown access kind");
1544}
1545
1546static bool isAnyAccess(AccessKinds AK) {
1547 return isRead(AK) || isModification(AK);
1548}
1549
1550/// Is this an access per the C++ definition?
1552 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1553 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1554}
1555
1556/// Is this kind of access valid on an indeterminate object value?
1558 switch (AK) {
1559 case AK_Read:
1560 case AK_Increment:
1561 case AK_Decrement:
1562 case AK_Dereference:
1563 // These need the object's value.
1564 return false;
1565
1568 case AK_Assign:
1569 case AK_Construct:
1570 case AK_Destroy:
1571 // Construction and destruction don't need the value.
1572 return true;
1573
1574 case AK_MemberCall:
1575 case AK_DynamicCast:
1576 case AK_TypeId:
1577 // These aren't really meaningful on scalars.
1578 return true;
1579 }
1580 llvm_unreachable("unknown access kind");
1581}
1582
1583namespace {
1584 struct ComplexValue {
1585 private:
1586 bool IsInt;
1587
1588 public:
1589 APSInt IntReal, IntImag;
1590 APFloat FloatReal, FloatImag;
1591
1592 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1593
1594 void makeComplexFloat() { IsInt = false; }
1595 bool isComplexFloat() const { return !IsInt; }
1596 APFloat &getComplexFloatReal() { return FloatReal; }
1597 APFloat &getComplexFloatImag() { return FloatImag; }
1598
1599 void makeComplexInt() { IsInt = true; }
1600 bool isComplexInt() const { return IsInt; }
1601 APSInt &getComplexIntReal() { return IntReal; }
1602 APSInt &getComplexIntImag() { return IntImag; }
1603
1604 void moveInto(APValue &v) const {
1605 if (isComplexFloat())
1606 v = APValue(FloatReal, FloatImag);
1607 else
1608 v = APValue(IntReal, IntImag);
1609 }
1610 void setFrom(const APValue &v) {
1611 assert(v.isComplexFloat() || v.isComplexInt());
1612 if (v.isComplexFloat()) {
1613 makeComplexFloat();
1614 FloatReal = v.getComplexFloatReal();
1615 FloatImag = v.getComplexFloatImag();
1616 } else {
1617 makeComplexInt();
1618 IntReal = v.getComplexIntReal();
1619 IntImag = v.getComplexIntImag();
1620 }
1621 }
1622 };
1623
1624 struct LValue {
1626 CharUnits Offset;
1627 SubobjectDesignator Designator;
1628 bool IsNullPtr : 1;
1629 bool InvalidBase : 1;
1630 // P2280R4 track if we have an unknown reference or pointer.
1631 bool AllowConstexprUnknown = false;
1632
1633 const APValue::LValueBase getLValueBase() const { return Base; }
1634 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1635 CharUnits &getLValueOffset() { return Offset; }
1636 const CharUnits &getLValueOffset() const { return Offset; }
1637 SubobjectDesignator &getLValueDesignator() { return Designator; }
1638 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1639 bool isNullPointer() const { return IsNullPtr;}
1640
1641 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1642 unsigned getLValueVersion() const { return Base.getVersion(); }
1643
1644 void moveInto(APValue &V) const {
1645 if (Designator.Invalid)
1646 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1647 else {
1648 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1649 V = APValue(Base, Offset, Designator.Entries,
1650 Designator.IsOnePastTheEnd, IsNullPtr);
1651 }
1652 if (AllowConstexprUnknown)
1653 V.setConstexprUnknown();
1654 }
1655 void setFrom(ASTContext &Ctx, const APValue &V) {
1656 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1657 Base = V.getLValueBase();
1658 Offset = V.getLValueOffset();
1659 InvalidBase = false;
1660 Designator = SubobjectDesignator(Ctx, V);
1661 IsNullPtr = V.isNullPointer();
1662 AllowConstexprUnknown = V.allowConstexprUnknown();
1663 }
1664
1665 void set(APValue::LValueBase B, bool BInvalid = false) {
1666#ifndef NDEBUG
1667 // We only allow a few types of invalid bases. Enforce that here.
1668 if (BInvalid) {
1669 const auto *E = B.get<const Expr *>();
1670 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1671 "Unexpected type of invalid base");
1672 }
1673#endif
1674
1675 Base = B;
1676 Offset = CharUnits::fromQuantity(0);
1677 InvalidBase = BInvalid;
1678 Designator = SubobjectDesignator(getType(B));
1679 IsNullPtr = false;
1680 AllowConstexprUnknown = false;
1681 }
1682
1683 void setNull(ASTContext &Ctx, QualType PointerTy) {
1684 Base = (const ValueDecl *)nullptr;
1685 Offset =
1687 InvalidBase = false;
1688 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1689 IsNullPtr = true;
1690 AllowConstexprUnknown = false;
1691 }
1692
1693 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1694 set(B, true);
1695 }
1696
1697 std::string toString(ASTContext &Ctx, QualType T) const {
1698 APValue Printable;
1699 moveInto(Printable);
1700 return Printable.getAsString(Ctx, T);
1701 }
1702
1703 private:
1704 // Check that this LValue is not based on a null pointer. If it is, produce
1705 // a diagnostic and mark the designator as invalid.
1706 template <typename GenDiagType>
1707 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1708 if (Designator.Invalid)
1709 return false;
1710 if (IsNullPtr) {
1711 GenDiag();
1712 Designator.setInvalid();
1713 return false;
1714 }
1715 return true;
1716 }
1717
1718 public:
1719 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1720 CheckSubobjectKind CSK) {
1721 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1722 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1723 });
1724 }
1725
1726 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1727 AccessKinds AK) {
1728 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1729 if (AK == AccessKinds::AK_Dereference)
1730 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1731 else
1732 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1733 });
1734 }
1735
1736 // Check this LValue refers to an object. If not, set the designator to be
1737 // invalid and emit a diagnostic.
1738 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1739 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1740 Designator.checkSubobject(Info, E, CSK);
1741 }
1742
1743 void addDecl(EvalInfo &Info, const Expr *E,
1744 const Decl *D, bool Virtual = false) {
1745 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1746 Designator.addDeclUnchecked(D, Virtual);
1747 }
1748 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1749 if (!Designator.Entries.empty()) {
1750 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1751 Designator.setInvalid();
1752 return;
1753 }
1754 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1755 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1756 getType(Base).getNonReferenceType()->isArrayType());
1757 Designator.FirstEntryIsAnUnsizedArray = true;
1758 Designator.addUnsizedArrayUnchecked(ElemTy);
1759 }
1760 }
1761 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1762 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1763 Designator.addArrayUnchecked(CAT);
1764 }
1765 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1766 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1767 Designator.addComplexUnchecked(EltTy, Imag);
1768 }
1769 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1770 uint64_t Size, uint64_t Idx) {
1771 if (checkSubobject(Info, E, CSK_VectorElement))
1772 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1773 }
1774 void clearIsNullPointer() {
1775 IsNullPtr = false;
1776 }
1777 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1778 const APSInt &Index, CharUnits ElementSize) {
1779 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1780 // but we're not required to diagnose it and it's valid in C++.)
1781 if (!Index)
1782 return;
1783
1784 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1785 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1786 // offsets.
1787 uint64_t Offset64 = Offset.getQuantity();
1788 uint64_t ElemSize64 = ElementSize.getQuantity();
1789 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1790 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1791
1792 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1793 Designator.adjustIndex(Info, E, Index);
1794 clearIsNullPointer();
1795 }
1796 void adjustOffset(CharUnits N) {
1797 Offset += N;
1798 if (N.getQuantity())
1799 clearIsNullPointer();
1800 }
1801 };
1802
1803 struct MemberPtr {
1804 MemberPtr() {}
1805 explicit MemberPtr(const ValueDecl *Decl)
1806 : DeclAndIsDerivedMember(Decl, false) {}
1807
1808 /// The member or (direct or indirect) field referred to by this member
1809 /// pointer, or 0 if this is a null member pointer.
1810 const ValueDecl *getDecl() const {
1811 return DeclAndIsDerivedMember.getPointer();
1812 }
1813 /// Is this actually a member of some type derived from the relevant class?
1814 bool isDerivedMember() const {
1815 return DeclAndIsDerivedMember.getInt();
1816 }
1817 /// Get the class which the declaration actually lives in.
1818 const CXXRecordDecl *getContainingRecord() const {
1819 return cast<CXXRecordDecl>(
1820 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1821 }
1822
1823 void moveInto(APValue &V) const {
1824 V = APValue(getDecl(), isDerivedMember(), Path);
1825 }
1826 void setFrom(const APValue &V) {
1827 assert(V.isMemberPointer());
1828 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1829 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1830 Path.clear();
1831 llvm::append_range(Path, V.getMemberPointerPath());
1832 }
1833
1834 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1835 /// whether the member is a member of some class derived from the class type
1836 /// of the member pointer.
1837 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1838 /// Path - The path of base/derived classes from the member declaration's
1839 /// class (exclusive) to the class type of the member pointer (inclusive).
1841
1842 /// Perform a cast towards the class of the Decl (either up or down the
1843 /// hierarchy).
1844 bool castBack(const CXXRecordDecl *Class) {
1845 assert(!Path.empty());
1846 const CXXRecordDecl *Expected;
1847 if (Path.size() >= 2)
1848 Expected = Path[Path.size() - 2];
1849 else
1850 Expected = getContainingRecord();
1851 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1852 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1853 // if B does not contain the original member and is not a base or
1854 // derived class of the class containing the original member, the result
1855 // of the cast is undefined.
1856 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1857 // (D::*). We consider that to be a language defect.
1858 return false;
1859 }
1860 Path.pop_back();
1861 return true;
1862 }
1863 /// Perform a base-to-derived member pointer cast.
1864 bool castToDerived(const CXXRecordDecl *Derived) {
1865 if (!getDecl())
1866 return true;
1867 if (!isDerivedMember()) {
1868 Path.push_back(Derived);
1869 return true;
1870 }
1871 if (!castBack(Derived))
1872 return false;
1873 if (Path.empty())
1874 DeclAndIsDerivedMember.setInt(false);
1875 return true;
1876 }
1877 /// Perform a derived-to-base member pointer cast.
1878 bool castToBase(const CXXRecordDecl *Base) {
1879 if (!getDecl())
1880 return true;
1881 if (Path.empty())
1882 DeclAndIsDerivedMember.setInt(true);
1883 if (isDerivedMember()) {
1884 Path.push_back(Base);
1885 return true;
1886 }
1887 return castBack(Base);
1888 }
1889 };
1890
1891 /// Compare two member pointers, which are assumed to be of the same type.
1892 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1893 if (!LHS.getDecl() || !RHS.getDecl())
1894 return !LHS.getDecl() && !RHS.getDecl();
1895 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1896 return false;
1897 return LHS.Path == RHS.Path;
1898 }
1899}
1900
1901static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1902static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1903 const LValue &This, const Expr *E,
1904 bool AllowNonLiteralTypes = false);
1905static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1906 bool InvalidBaseOK = false);
1907static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1908 bool InvalidBaseOK = false);
1909static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1910 EvalInfo &Info);
1911static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1912static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1913static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1914 EvalInfo &Info);
1915static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1916static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1917static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1918 EvalInfo &Info);
1919static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1920static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1921 EvalInfo &Info,
1922 std::string *StringResult = nullptr);
1923
1924/// Evaluate an integer or fixed point expression into an APResult.
1925static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1926 EvalInfo &Info);
1927
1928/// Evaluate only a fixed point expression into an APResult.
1929static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1930 EvalInfo &Info);
1931
1932//===----------------------------------------------------------------------===//
1933// Misc utilities
1934//===----------------------------------------------------------------------===//
1935
1936/// Negate an APSInt in place, converting it to a signed form if necessary, and
1937/// preserving its value (by extending by up to one bit as needed).
1938static void negateAsSigned(APSInt &Int) {
1939 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1940 Int = Int.extend(Int.getBitWidth() + 1);
1941 Int.setIsSigned(true);
1942 }
1943 Int = -Int;
1944}
1945
1946template<typename KeyT>
1947APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1948 ScopeKind Scope, LValue &LV) {
1949 unsigned Version = getTempVersion();
1950 APValue::LValueBase Base(Key, Index, Version);
1951 LV.set(Base);
1952 return createLocal(Base, Key, T, Scope);
1953}
1954
1955/// Allocate storage for a parameter of a function call made in this frame.
1956APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1957 LValue &LV) {
1958 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1959 APValue::LValueBase Base(PVD, Index, Args.Version);
1960 LV.set(Base);
1961 // We always destroy parameters at the end of the call, even if we'd allow
1962 // them to live to the end of the full-expression at runtime, in order to
1963 // give portable results and match other compilers.
1964 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1965}
1966
1967APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1968 QualType T, ScopeKind Scope) {
1969 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1970 unsigned Version = Base.getVersion();
1971 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1972 assert(Result.isAbsent() && "local created multiple times");
1973
1974 // If we're creating a local immediately in the operand of a speculative
1975 // evaluation, don't register a cleanup to be run outside the speculative
1976 // evaluation context, since we won't actually be able to initialize this
1977 // object.
1978 if (Index <= Info.SpeculativeEvaluationDepth) {
1979 if (T.isDestructedType())
1980 Info.noteSideEffect();
1981 } else {
1982 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1983 }
1984 return Result;
1985}
1986
1987APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1988 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1989 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1990 return nullptr;
1991 }
1992
1993 DynamicAllocLValue DA(NumHeapAllocs++);
1995 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1996 std::forward_as_tuple(DA), std::tuple<>());
1997 assert(Result.second && "reused a heap alloc index?");
1998 Result.first->second.AllocExpr = E;
1999 return &Result.first->second.Value;
2000}
2001
2002/// Produce a string describing the given constexpr call.
2003void CallStackFrame::describe(raw_ostream &Out) const {
2004 unsigned ArgIndex = 0;
2005 bool IsMemberCall =
2006 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
2007 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2008
2009 if (!IsMemberCall)
2010 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2011 /*Qualified=*/false);
2012
2013 if (This && IsMemberCall) {
2014 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2015 const Expr *Object = MCE->getImplicitObjectArgument();
2016 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2017 /*Indentation=*/0);
2018 if (Object->getType()->isPointerType())
2019 Out << "->";
2020 else
2021 Out << ".";
2022 } else if (const auto *OCE =
2023 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2024 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2025 Info.Ctx.getPrintingPolicy(),
2026 /*Indentation=*/0);
2027 Out << ".";
2028 } else {
2029 APValue Val;
2030 This->moveInto(Val);
2031 Val.printPretty(
2032 Out, Info.Ctx,
2033 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2034 Out << ".";
2035 }
2036 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2037 /*Qualified=*/false);
2038 IsMemberCall = false;
2039 }
2040
2041 Out << '(';
2042
2043 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2044 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2045 if (ArgIndex > (unsigned)IsMemberCall)
2046 Out << ", ";
2047
2048 const ParmVarDecl *Param = *I;
2049 APValue *V = Info.getParamSlot(Arguments, Param);
2050 if (V)
2051 V->printPretty(Out, Info.Ctx, Param->getType());
2052 else
2053 Out << "<...>";
2054
2055 if (ArgIndex == 0 && IsMemberCall)
2056 Out << "->" << *Callee << '(';
2057 }
2058
2059 Out << ')';
2060}
2061
2062/// Evaluate an expression to see if it had side-effects, and discard its
2063/// result.
2064/// \return \c true if the caller should keep evaluating.
2065static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2066 assert(!E->isValueDependent());
2067 APValue Scratch;
2068 if (!Evaluate(Scratch, Info, E))
2069 // We don't need the value, but we might have skipped a side effect here.
2070 return Info.noteSideEffect();
2071 return true;
2072}
2073
2074/// Should this call expression be treated as forming an opaque constant?
2075static bool IsOpaqueConstantCall(const CallExpr *E) {
2076 unsigned Builtin = E->getBuiltinCallee();
2077 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2078 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2079 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2080 Builtin == Builtin::BI__builtin_function_start);
2081}
2082
2083static bool IsOpaqueConstantCall(const LValue &LVal) {
2084 const auto *BaseExpr =
2085 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2086 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2087}
2088
2090 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2091 // constant expression of pointer type that evaluates to...
2092
2093 // ... a null pointer value, or a prvalue core constant expression of type
2094 // std::nullptr_t.
2095 if (!B)
2096 return true;
2097
2098 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2099 // ... the address of an object with static storage duration,
2100 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2101 return VD->hasGlobalStorage();
2102 if (isa<TemplateParamObjectDecl>(D))
2103 return true;
2104 // ... the address of a function,
2105 // ... the address of a GUID [MS extension],
2106 // ... the address of an unnamed global constant
2107 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2108 }
2109
2110 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2111 return true;
2112
2113 const Expr *E = B.get<const Expr*>();
2114 switch (E->getStmtClass()) {
2115 default:
2116 return false;
2117 case Expr::CompoundLiteralExprClass: {
2118 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2119 return CLE->isFileScope() && CLE->isLValue();
2120 }
2121 case Expr::MaterializeTemporaryExprClass:
2122 // A materialized temporary might have been lifetime-extended to static
2123 // storage duration.
2124 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2125 // A string literal has static storage duration.
2126 case Expr::StringLiteralClass:
2127 case Expr::PredefinedExprClass:
2128 case Expr::ObjCStringLiteralClass:
2129 case Expr::ObjCEncodeExprClass:
2130 return true;
2131 case Expr::ObjCBoxedExprClass:
2132 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2133 case Expr::CallExprClass:
2134 return IsOpaqueConstantCall(cast<CallExpr>(E));
2135 // For GCC compatibility, &&label has static storage duration.
2136 case Expr::AddrLabelExprClass:
2137 return true;
2138 // A Block literal expression may be used as the initialization value for
2139 // Block variables at global or local static scope.
2140 case Expr::BlockExprClass:
2141 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2142 // The APValue generated from a __builtin_source_location will be emitted as a
2143 // literal.
2144 case Expr::SourceLocExprClass:
2145 return true;
2146 case Expr::ImplicitValueInitExprClass:
2147 // FIXME:
2148 // We can never form an lvalue with an implicit value initialization as its
2149 // base through expression evaluation, so these only appear in one case: the
2150 // implicit variable declaration we invent when checking whether a constexpr
2151 // constructor can produce a constant expression. We must assume that such
2152 // an expression might be a global lvalue.
2153 return true;
2154 }
2155}
2156
2157static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2158 return LVal.Base.dyn_cast<const ValueDecl*>();
2159}
2160
2161// Information about an LValueBase that is some kind of string.
2164 StringRef Bytes;
2166};
2167
2168// Gets the lvalue base of LVal as a string.
2169static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2170 LValueBaseString &AsString) {
2171 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2172 if (!BaseExpr)
2173 return false;
2174
2175 // For ObjCEncodeExpr, we need to compute and store the string.
2176 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2177 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2178 AsString.ObjCEncodeStorage);
2179 AsString.Bytes = AsString.ObjCEncodeStorage;
2180 AsString.CharWidth = 1;
2181 return true;
2182 }
2183
2184 // Otherwise, we have a StringLiteral.
2185 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2186 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2187 Lit = PE->getFunctionName();
2188
2189 if (!Lit)
2190 return false;
2191
2192 AsString.Bytes = Lit->getBytes();
2193 AsString.CharWidth = Lit->getCharByteWidth();
2194 return true;
2195}
2196
2197// Determine whether two string literals potentially overlap. This will be the
2198// case if they agree on the values of all the bytes on the overlapping region
2199// between them.
2200//
2201// The overlapping region is the portion of the two string literals that must
2202// overlap in memory if the pointers actually point to the same address at
2203// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2204// the overlapping region is "cdef\0", which in this case does agree, so the
2205// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2206// "bazbar" + 3, the overlapping region contains all of both strings, so they
2207// are not potentially overlapping, even though they agree from the given
2208// addresses onwards.
2209//
2210// See open core issue CWG2765 which is discussing the desired rule here.
2211static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2212 const LValue &LHS,
2213 const LValue &RHS) {
2214 LValueBaseString LHSString, RHSString;
2215 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2216 !GetLValueBaseAsString(Info, RHS, RHSString))
2217 return false;
2218
2219 // This is the byte offset to the location of the first character of LHS
2220 // within RHS. We don't need to look at the characters of one string that
2221 // would appear before the start of the other string if they were merged.
2222 CharUnits Offset = RHS.Offset - LHS.Offset;
2223 if (Offset.isNegative()) {
2224 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2225 return false;
2226 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2227 } else {
2228 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2229 return false;
2230 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2231 }
2232
2233 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2234 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2235 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2236 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2237
2238 // The null terminator isn't included in the string data, so check for it
2239 // manually. If the longer string doesn't have a null terminator where the
2240 // shorter string ends, they aren't potentially overlapping.
2241 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2242 if (Shorter.size() + NullByte >= Longer.size())
2243 break;
2244 if (Longer[Shorter.size() + NullByte])
2245 return false;
2246 }
2247
2248 // Otherwise, they're potentially overlapping if and only if the overlapping
2249 // region is the same.
2250 return Shorter == Longer.take_front(Shorter.size());
2251}
2252
2253static bool IsWeakLValue(const LValue &Value) {
2255 return Decl && Decl->isWeak();
2256}
2257
2258static bool isZeroSized(const LValue &Value) {
2260 if (isa_and_nonnull<VarDecl>(Decl)) {
2261 QualType Ty = Decl->getType();
2262 if (Ty->isArrayType())
2263 return Ty->isIncompleteType() ||
2264 Decl->getASTContext().getTypeSize(Ty) == 0;
2265 }
2266 return false;
2267}
2268
2269static bool HasSameBase(const LValue &A, const LValue &B) {
2270 if (!A.getLValueBase())
2271 return !B.getLValueBase();
2272 if (!B.getLValueBase())
2273 return false;
2274
2275 if (A.getLValueBase().getOpaqueValue() !=
2276 B.getLValueBase().getOpaqueValue())
2277 return false;
2278
2279 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2280 A.getLValueVersion() == B.getLValueVersion();
2281}
2282
2283static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2284 assert(Base && "no location for a null lvalue");
2285 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2286
2287 // For a parameter, find the corresponding call stack frame (if it still
2288 // exists), and point at the parameter of the function definition we actually
2289 // invoked.
2290 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2291 unsigned Idx = PVD->getFunctionScopeIndex();
2292 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2293 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2294 F->Arguments.Version == Base.getVersion() && F->Callee &&
2295 Idx < F->Callee->getNumParams()) {
2296 VD = F->Callee->getParamDecl(Idx);
2297 break;
2298 }
2299 }
2300 }
2301
2302 if (VD)
2303 Info.Note(VD->getLocation(), diag::note_declared_at);
2304 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2305 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2306 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2307 // FIXME: Produce a note for dangling pointers too.
2308 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2309 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2310 diag::note_constexpr_dynamic_alloc_here);
2311 }
2312
2313 // We have no information to show for a typeid(T) object.
2314}
2315
2319};
2320
2321/// Materialized temporaries that we've already checked to determine if they're
2322/// initializsed by a constant expression.
2325
2327 EvalInfo &Info, SourceLocation DiagLoc,
2328 QualType Type, const APValue &Value,
2329 ConstantExprKind Kind,
2330 const FieldDecl *SubobjectDecl,
2331 CheckedTemporaries &CheckedTemps);
2332
2333/// Check that this reference or pointer core constant expression is a valid
2334/// value for an address or reference constant expression. Return true if we
2335/// can fold this expression, whether or not it's a constant expression.
2337 QualType Type, const LValue &LVal,
2338 ConstantExprKind Kind,
2339 CheckedTemporaries &CheckedTemps) {
2340 bool IsReferenceType = Type->isReferenceType();
2341
2342 APValue::LValueBase Base = LVal.getLValueBase();
2343 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2344
2345 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2346 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2347
2348 // Additional restrictions apply in a template argument. We only enforce the
2349 // C++20 restrictions here; additional syntactic and semantic restrictions
2350 // are applied elsewhere.
2351 if (isTemplateArgument(Kind)) {
2352 int InvalidBaseKind = -1;
2353 StringRef Ident;
2354 if (Base.is<TypeInfoLValue>())
2355 InvalidBaseKind = 0;
2356 else if (isa_and_nonnull<StringLiteral>(BaseE))
2357 InvalidBaseKind = 1;
2358 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2359 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2360 InvalidBaseKind = 2;
2361 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2362 InvalidBaseKind = 3;
2363 Ident = PE->getIdentKindName();
2364 }
2365
2366 if (InvalidBaseKind != -1) {
2367 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2368 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2369 << Ident;
2370 return false;
2371 }
2372 }
2373
2374 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2375 FD && FD->isImmediateFunction()) {
2376 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2377 << !Type->isAnyPointerType();
2378 Info.Note(FD->getLocation(), diag::note_declared_at);
2379 return false;
2380 }
2381
2382 // Check that the object is a global. Note that the fake 'this' object we
2383 // manufacture when checking potential constant expressions is conservatively
2384 // assumed to be global here.
2385 if (!IsGlobalLValue(Base)) {
2386 if (Info.getLangOpts().CPlusPlus11) {
2387 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2388 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2389 << BaseVD;
2390 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2391 if (VarD && VarD->isConstexpr()) {
2392 // Non-static local constexpr variables have unintuitive semantics:
2393 // constexpr int a = 1;
2394 // constexpr const int *p = &a;
2395 // ... is invalid because the address of 'a' is not constant. Suggest
2396 // adding a 'static' in this case.
2397 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2398 << VarD
2399 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2400 } else {
2401 NoteLValueLocation(Info, Base);
2402 }
2403 } else {
2404 Info.FFDiag(Loc);
2405 }
2406 // Don't allow references to temporaries to escape.
2407 return false;
2408 }
2409 assert((Info.checkingPotentialConstantExpression() ||
2410 LVal.getLValueCallIndex() == 0) &&
2411 "have call index for global lvalue");
2412
2413 if (LVal.allowConstexprUnknown()) {
2414 if (BaseVD) {
2415 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2416 NoteLValueLocation(Info, Base);
2417 } else {
2418 Info.FFDiag(Loc);
2419 }
2420 return false;
2421 }
2422
2423 if (Base.is<DynamicAllocLValue>()) {
2424 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2425 << IsReferenceType << !Designator.Entries.empty();
2426 NoteLValueLocation(Info, Base);
2427 return false;
2428 }
2429
2430 if (BaseVD) {
2431 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2432 // Check if this is a thread-local variable.
2433 if (Var->getTLSKind())
2434 // FIXME: Diagnostic!
2435 return false;
2436
2437 // A dllimport variable never acts like a constant, unless we're
2438 // evaluating a value for use only in name mangling.
2439 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2440 // FIXME: Diagnostic!
2441 return false;
2442
2443 // In CUDA/HIP device compilation, only device side variables have
2444 // constant addresses.
2445 if (Info.getASTContext().getLangOpts().CUDA &&
2446 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2447 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2448 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2449 !Var->hasAttr<CUDAConstantAttr>() &&
2450 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2451 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2452 Var->hasAttr<HIPManagedAttr>())
2453 return false;
2454 }
2455 }
2456 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2457 // __declspec(dllimport) must be handled very carefully:
2458 // We must never initialize an expression with the thunk in C++.
2459 // Doing otherwise would allow the same id-expression to yield
2460 // different addresses for the same function in different translation
2461 // units. However, this means that we must dynamically initialize the
2462 // expression with the contents of the import address table at runtime.
2463 //
2464 // The C language has no notion of ODR; furthermore, it has no notion of
2465 // dynamic initialization. This means that we are permitted to
2466 // perform initialization with the address of the thunk.
2467 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2468 FD->hasAttr<DLLImportAttr>())
2469 // FIXME: Diagnostic!
2470 return false;
2471 }
2472 } else if (const auto *MTE =
2473 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2474 if (CheckedTemps.insert(MTE).second) {
2475 QualType TempType = getType(Base);
2476 if (TempType.isDestructedType()) {
2477 Info.FFDiag(MTE->getExprLoc(),
2478 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2479 << TempType;
2480 return false;
2481 }
2482
2483 APValue *V = MTE->getOrCreateValue(false);
2484 assert(V && "evasluation result refers to uninitialised temporary");
2485 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2486 Info, MTE->getExprLoc(), TempType, *V, Kind,
2487 /*SubobjectDecl=*/nullptr, CheckedTemps))
2488 return false;
2489 }
2490 }
2491
2492 // Allow address constant expressions to be past-the-end pointers. This is
2493 // an extension: the standard requires them to point to an object.
2494 if (!IsReferenceType)
2495 return true;
2496
2497 // A reference constant expression must refer to an object.
2498 if (!Base) {
2499 // FIXME: diagnostic
2500 Info.CCEDiag(Loc);
2501 return true;
2502 }
2503
2504 // Does this refer one past the end of some object?
2505 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2506 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2507 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2508 NoteLValueLocation(Info, Base);
2509 }
2510
2511 return true;
2512}
2513
2514/// Member pointers are constant expressions unless they point to a
2515/// non-virtual dllimport member function.
2516static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2518 QualType Type,
2519 const APValue &Value,
2520 ConstantExprKind Kind) {
2521 const ValueDecl *Member = Value.getMemberPointerDecl();
2522 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2523 if (!FD)
2524 return true;
2525 if (FD->isImmediateFunction()) {
2526 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2527 Info.Note(FD->getLocation(), diag::note_declared_at);
2528 return false;
2529 }
2530 return isForManglingOnly(Kind) || FD->isVirtual() ||
2531 !FD->hasAttr<DLLImportAttr>();
2532}
2533
2534/// Check that this core constant expression is of literal type, and if not,
2535/// produce an appropriate diagnostic.
2536static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2537 const LValue *This = nullptr) {
2538 // The restriction to literal types does not exist in C++23 anymore.
2539 if (Info.getLangOpts().CPlusPlus23)
2540 return true;
2541
2542 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2543 return true;
2544
2545 // C++1y: A constant initializer for an object o [...] may also invoke
2546 // constexpr constructors for o and its subobjects even if those objects
2547 // are of non-literal class types.
2548 //
2549 // C++11 missed this detail for aggregates, so classes like this:
2550 // struct foo_t { union { int i; volatile int j; } u; };
2551 // are not (obviously) initializable like so:
2552 // __attribute__((__require_constant_initialization__))
2553 // static const foo_t x = {{0}};
2554 // because "i" is a subobject with non-literal initialization (due to the
2555 // volatile member of the union). See:
2556 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2557 // Therefore, we use the C++1y behavior.
2558 if (This && Info.EvaluatingDecl == This->getLValueBase())
2559 return true;
2560
2561 // Prvalue constant expressions must be of literal types.
2562 if (Info.getLangOpts().CPlusPlus11)
2563 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2564 << E->getType();
2565 else
2566 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2567 return false;
2568}
2569
2571 EvalInfo &Info, SourceLocation DiagLoc,
2572 QualType Type, const APValue &Value,
2573 ConstantExprKind Kind,
2574 const FieldDecl *SubobjectDecl,
2575 CheckedTemporaries &CheckedTemps) {
2576 if (!Value.hasValue()) {
2577 if (SubobjectDecl) {
2578 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2579 << /*(name)*/ 1 << SubobjectDecl;
2580 Info.Note(SubobjectDecl->getLocation(),
2581 diag::note_constexpr_subobject_declared_here);
2582 } else {
2583 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2584 << /*of type*/ 0 << Type;
2585 }
2586 return false;
2587 }
2588
2589 // We allow _Atomic(T) to be initialized from anything that T can be
2590 // initialized from.
2591 if (const AtomicType *AT = Type->getAs<AtomicType>())
2592 Type = AT->getValueType();
2593
2594 // Core issue 1454: For a literal constant expression of array or class type,
2595 // each subobject of its value shall have been initialized by a constant
2596 // expression.
2597 if (Value.isArray()) {
2599 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2600 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2601 Value.getArrayInitializedElt(I), Kind,
2602 SubobjectDecl, CheckedTemps))
2603 return false;
2604 }
2605 if (!Value.hasArrayFiller())
2606 return true;
2607 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2608 Value.getArrayFiller(), Kind, SubobjectDecl,
2609 CheckedTemps);
2610 }
2611 if (Value.isUnion() && Value.getUnionField()) {
2612 return CheckEvaluationResult(
2613 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2614 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2615 }
2616 if (Value.isStruct()) {
2617 auto *RD = Type->castAsRecordDecl();
2618 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2619 unsigned BaseIndex = 0;
2620 for (const CXXBaseSpecifier &BS : CD->bases()) {
2621 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2622 if (!BaseValue.hasValue()) {
2623 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2624 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2625 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2626 return false;
2627 }
2628 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2629 Kind, /*SubobjectDecl=*/nullptr,
2630 CheckedTemps))
2631 return false;
2632 ++BaseIndex;
2633 }
2634 }
2635 for (const auto *I : RD->fields()) {
2636 if (I->isUnnamedBitField())
2637 continue;
2638
2639 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2640 Value.getStructField(I->getFieldIndex()), Kind,
2641 I, CheckedTemps))
2642 return false;
2643 }
2644 }
2645
2646 if (Value.isLValue() &&
2647 CERK == CheckEvaluationResultKind::ConstantExpression) {
2648 LValue LVal;
2649 LVal.setFrom(Info.Ctx, Value);
2650 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2651 CheckedTemps);
2652 }
2653
2654 if (Value.isMemberPointer() &&
2655 CERK == CheckEvaluationResultKind::ConstantExpression)
2656 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2657
2658 // Everything else is fine.
2659 return true;
2660}
2661
2662/// Check that this core constant expression value is a valid value for a
2663/// constant expression. If not, report an appropriate diagnostic. Does not
2664/// check that the expression is of literal type.
2665static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2666 QualType Type, const APValue &Value,
2667 ConstantExprKind Kind) {
2668 // Nothing to check for a constant expression of type 'cv void'.
2669 if (Type->isVoidType())
2670 return true;
2671
2672 CheckedTemporaries CheckedTemps;
2673 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2674 Info, DiagLoc, Type, Value, Kind,
2675 /*SubobjectDecl=*/nullptr, CheckedTemps);
2676}
2677
2678/// Check that this evaluated value is fully-initialized and can be loaded by
2679/// an lvalue-to-rvalue conversion.
2680static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2681 QualType Type, const APValue &Value) {
2682 CheckedTemporaries CheckedTemps;
2683 return CheckEvaluationResult(
2684 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2685 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2686}
2687
2688/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2689/// "the allocated storage is deallocated within the evaluation".
2690static bool CheckMemoryLeaks(EvalInfo &Info) {
2691 if (!Info.HeapAllocs.empty()) {
2692 // We can still fold to a constant despite a compile-time memory leak,
2693 // so long as the heap allocation isn't referenced in the result (we check
2694 // that in CheckConstantExpression).
2695 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2696 diag::note_constexpr_memory_leak)
2697 << unsigned(Info.HeapAllocs.size() - 1);
2698 }
2699 return true;
2700}
2701
2702static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2703 // A null base expression indicates a null pointer. These are always
2704 // evaluatable, and they are false unless the offset is zero.
2705 if (!Value.getLValueBase()) {
2706 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2707 Result = !Value.getLValueOffset().isZero();
2708 return true;
2709 }
2710
2711 // We have a non-null base. These are generally known to be true, but if it's
2712 // a weak declaration it can be null at runtime.
2713 Result = true;
2714 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2715 return !Decl || !Decl->isWeak();
2716}
2717
2718static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2719 // TODO: This function should produce notes if it fails.
2720 switch (Val.getKind()) {
2721 case APValue::None:
2723 return false;
2724 case APValue::Int:
2725 Result = Val.getInt().getBoolValue();
2726 return true;
2728 Result = Val.getFixedPoint().getBoolValue();
2729 return true;
2730 case APValue::Float:
2731 Result = !Val.getFloat().isZero();
2732 return true;
2734 Result = Val.getComplexIntReal().getBoolValue() ||
2735 Val.getComplexIntImag().getBoolValue();
2736 return true;
2738 Result = !Val.getComplexFloatReal().isZero() ||
2739 !Val.getComplexFloatImag().isZero();
2740 return true;
2741 case APValue::LValue:
2742 return EvalPointerValueAsBool(Val, Result);
2744 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2745 return false;
2746 }
2747 Result = Val.getMemberPointerDecl();
2748 return true;
2749 case APValue::Vector:
2750 case APValue::Array:
2751 case APValue::Struct:
2752 case APValue::Union:
2754 return false;
2755 }
2756
2757 llvm_unreachable("unknown APValue kind");
2758}
2759
2760static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2761 EvalInfo &Info) {
2762 assert(!E->isValueDependent());
2763 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2764 APValue Val;
2765 if (!Evaluate(Val, Info, E))
2766 return false;
2767 return HandleConversionToBool(Val, Result);
2768}
2769
2770template<typename T>
2771static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2772 const T &SrcValue, QualType DestType) {
2773 Info.CCEDiag(E, diag::note_constexpr_overflow)
2774 << SrcValue << DestType;
2775 return Info.noteUndefinedBehavior();
2776}
2777
2778static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2779 QualType SrcType, const APFloat &Value,
2780 QualType DestType, APSInt &Result) {
2781 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2782 // Determine whether we are converting to unsigned or signed.
2783 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2784
2785 Result = APSInt(DestWidth, !DestSigned);
2786 bool ignored;
2787 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2788 & APFloat::opInvalidOp)
2789 return HandleOverflow(Info, E, Value, DestType);
2790 return true;
2791}
2792
2793/// Get rounding mode to use in evaluation of the specified expression.
2794///
2795/// If rounding mode is unknown at compile time, still try to evaluate the
2796/// expression. If the result is exact, it does not depend on rounding mode.
2797/// So return "tonearest" mode instead of "dynamic".
2798static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2799 llvm::RoundingMode RM =
2800 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2801 if (RM == llvm::RoundingMode::Dynamic)
2802 RM = llvm::RoundingMode::NearestTiesToEven;
2803 return RM;
2804}
2805
2806/// Check if the given evaluation result is allowed for constant evaluation.
2807static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2808 APFloat::opStatus St) {
2809 // In a constant context, assume that any dynamic rounding mode or FP
2810 // exception state matches the default floating-point environment.
2811 if (Info.InConstantContext)
2812 return true;
2813
2814 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2815 if ((St & APFloat::opInexact) &&
2816 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2817 // Inexact result means that it depends on rounding mode. If the requested
2818 // mode is dynamic, the evaluation cannot be made in compile time.
2819 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2820 return false;
2821 }
2822
2823 if ((St != APFloat::opOK) &&
2824 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2825 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2826 FPO.getAllowFEnvAccess())) {
2827 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2828 return false;
2829 }
2830
2831 if ((St & APFloat::opStatus::opInvalidOp) &&
2832 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2833 // There is no usefully definable result.
2834 Info.FFDiag(E);
2835 return false;
2836 }
2837
2838 // FIXME: if:
2839 // - evaluation triggered other FP exception, and
2840 // - exception mode is not "ignore", and
2841 // - the expression being evaluated is not a part of global variable
2842 // initializer,
2843 // the evaluation probably need to be rejected.
2844 return true;
2845}
2846
2847static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2848 QualType SrcType, QualType DestType,
2849 APFloat &Result) {
2850 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2851 isa<ConvertVectorExpr>(E)) &&
2852 "HandleFloatToFloatCast has been checked with only CastExpr, "
2853 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2854 "the new expression or address the root cause of this usage.");
2855 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2856 APFloat::opStatus St;
2857 APFloat Value = Result;
2858 bool ignored;
2859 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2860 return checkFloatingPointResult(Info, E, St);
2861}
2862
2863static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2864 QualType DestType, QualType SrcType,
2865 const APSInt &Value) {
2866 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2867 // Figure out if this is a truncate, extend or noop cast.
2868 // If the input is signed, do a sign extend, noop, or truncate.
2869 APSInt Result = Value.extOrTrunc(DestWidth);
2870 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2871 if (DestType->isBooleanType())
2872 Result = Value.getBoolValue();
2873 return Result;
2874}
2875
2876static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2877 const FPOptions FPO,
2878 QualType SrcType, const APSInt &Value,
2879 QualType DestType, APFloat &Result) {
2880 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2881 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2882 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2883 return checkFloatingPointResult(Info, E, St);
2884}
2885
2886static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2887 APValue &Value, const FieldDecl *FD) {
2888 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2889
2890 if (!Value.isInt()) {
2891 // Trying to store a pointer-cast-to-integer into a bitfield.
2892 // FIXME: In this case, we should provide the diagnostic for casting
2893 // a pointer to an integer.
2894 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2895 Info.FFDiag(E);
2896 return false;
2897 }
2898
2899 APSInt &Int = Value.getInt();
2900 unsigned OldBitWidth = Int.getBitWidth();
2901 unsigned NewBitWidth = FD->getBitWidthValue();
2902 if (NewBitWidth < OldBitWidth)
2903 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2904 return true;
2905}
2906
2907/// Perform the given integer operation, which is known to need at most BitWidth
2908/// bits, and check for overflow in the original type (if that type was not an
2909/// unsigned type).
2910template<typename Operation>
2911static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2912 const APSInt &LHS, const APSInt &RHS,
2913 unsigned BitWidth, Operation Op,
2914 APSInt &Result) {
2915 if (LHS.isUnsigned()) {
2916 Result = Op(LHS, RHS);
2917 return true;
2918 }
2919
2920 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2921 Result = Value.trunc(LHS.getBitWidth());
2922 if (Result.extend(BitWidth) != Value) {
2923 if (Info.checkingForUndefinedBehavior())
2924 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2925 diag::warn_integer_constant_overflow)
2926 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2927 /*UpperCase=*/true, /*InsertSeparators=*/true)
2928 << E->getType() << E->getSourceRange();
2929 return HandleOverflow(Info, E, Value, E->getType());
2930 }
2931 return true;
2932}
2933
2934/// Perform the given binary integer operation.
2935static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2936 const APSInt &LHS, BinaryOperatorKind Opcode,
2937 APSInt RHS, APSInt &Result) {
2938 bool HandleOverflowResult = true;
2939 switch (Opcode) {
2940 default:
2941 Info.FFDiag(E);
2942 return false;
2943 case BO_Mul:
2944 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2945 std::multiplies<APSInt>(), Result);
2946 case BO_Add:
2947 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2948 std::plus<APSInt>(), Result);
2949 case BO_Sub:
2950 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2951 std::minus<APSInt>(), Result);
2952 case BO_And: Result = LHS & RHS; return true;
2953 case BO_Xor: Result = LHS ^ RHS; return true;
2954 case BO_Or: Result = LHS | RHS; return true;
2955 case BO_Div:
2956 case BO_Rem:
2957 if (RHS == 0) {
2958 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2959 << E->getRHS()->getSourceRange();
2960 return false;
2961 }
2962 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2963 // this operation and gives the two's complement result.
2964 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2965 LHS.isMinSignedValue())
2966 HandleOverflowResult = HandleOverflow(
2967 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2968 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2969 return HandleOverflowResult;
2970 case BO_Shl: {
2971 if (Info.getLangOpts().OpenCL)
2972 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2973 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2974 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2975 RHS.isUnsigned());
2976 else if (RHS.isSigned() && RHS.isNegative()) {
2977 // During constant-folding, a negative shift is an opposite shift. Such
2978 // a shift is not a constant expression.
2979 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2980 if (!Info.noteUndefinedBehavior())
2981 return false;
2982 RHS = -RHS;
2983 goto shift_right;
2984 }
2985 shift_left:
2986 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2987 // the shifted type.
2988 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2989 if (SA != RHS) {
2990 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2991 << RHS << E->getType() << LHS.getBitWidth();
2992 if (!Info.noteUndefinedBehavior())
2993 return false;
2994 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2995 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2996 // operand, and must not overflow the corresponding unsigned type.
2997 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2998 // E1 x 2^E2 module 2^N.
2999 if (LHS.isNegative()) {
3000 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
3001 if (!Info.noteUndefinedBehavior())
3002 return false;
3003 } else if (LHS.countl_zero() < SA) {
3004 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
3005 if (!Info.noteUndefinedBehavior())
3006 return false;
3007 }
3008 }
3009 Result = LHS << SA;
3010 return true;
3011 }
3012 case BO_Shr: {
3013 if (Info.getLangOpts().OpenCL)
3014 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3015 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
3016 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
3017 RHS.isUnsigned());
3018 else if (RHS.isSigned() && RHS.isNegative()) {
3019 // During constant-folding, a negative shift is an opposite shift. Such a
3020 // shift is not a constant expression.
3021 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
3022 if (!Info.noteUndefinedBehavior())
3023 return false;
3024 RHS = -RHS;
3025 goto shift_left;
3026 }
3027 shift_right:
3028 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3029 // shifted type.
3030 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3031 if (SA != RHS) {
3032 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3033 << RHS << E->getType() << LHS.getBitWidth();
3034 if (!Info.noteUndefinedBehavior())
3035 return false;
3036 }
3037
3038 Result = LHS >> SA;
3039 return true;
3040 }
3041
3042 case BO_LT: Result = LHS < RHS; return true;
3043 case BO_GT: Result = LHS > RHS; return true;
3044 case BO_LE: Result = LHS <= RHS; return true;
3045 case BO_GE: Result = LHS >= RHS; return true;
3046 case BO_EQ: Result = LHS == RHS; return true;
3047 case BO_NE: Result = LHS != RHS; return true;
3048 case BO_Cmp:
3049 llvm_unreachable("BO_Cmp should be handled elsewhere");
3050 }
3051}
3052
3053/// Perform the given binary floating-point operation, in-place, on LHS.
3054static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3055 APFloat &LHS, BinaryOperatorKind Opcode,
3056 const APFloat &RHS) {
3057 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3058 APFloat::opStatus St;
3059 switch (Opcode) {
3060 default:
3061 Info.FFDiag(E);
3062 return false;
3063 case BO_Mul:
3064 St = LHS.multiply(RHS, RM);
3065 break;
3066 case BO_Add:
3067 St = LHS.add(RHS, RM);
3068 break;
3069 case BO_Sub:
3070 St = LHS.subtract(RHS, RM);
3071 break;
3072 case BO_Div:
3073 // [expr.mul]p4:
3074 // If the second operand of / or % is zero the behavior is undefined.
3075 if (RHS.isZero())
3076 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3077 St = LHS.divide(RHS, RM);
3078 break;
3079 }
3080
3081 // [expr.pre]p4:
3082 // If during the evaluation of an expression, the result is not
3083 // mathematically defined [...], the behavior is undefined.
3084 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3085 if (LHS.isNaN()) {
3086 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3087 return Info.noteUndefinedBehavior();
3088 }
3089
3090 return checkFloatingPointResult(Info, E, St);
3091}
3092
3093static bool handleLogicalOpForVector(const APInt &LHSValue,
3094 BinaryOperatorKind Opcode,
3095 const APInt &RHSValue, APInt &Result) {
3096 bool LHS = (LHSValue != 0);
3097 bool RHS = (RHSValue != 0);
3098
3099 if (Opcode == BO_LAnd)
3100 Result = LHS && RHS;
3101 else
3102 Result = LHS || RHS;
3103 return true;
3104}
3105static bool handleLogicalOpForVector(const APFloat &LHSValue,
3106 BinaryOperatorKind Opcode,
3107 const APFloat &RHSValue, APInt &Result) {
3108 bool LHS = !LHSValue.isZero();
3109 bool RHS = !RHSValue.isZero();
3110
3111 if (Opcode == BO_LAnd)
3112 Result = LHS && RHS;
3113 else
3114 Result = LHS || RHS;
3115 return true;
3116}
3117
3118static bool handleLogicalOpForVector(const APValue &LHSValue,
3119 BinaryOperatorKind Opcode,
3120 const APValue &RHSValue, APInt &Result) {
3121 // The result is always an int type, however operands match the first.
3122 if (LHSValue.getKind() == APValue::Int)
3123 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3124 RHSValue.getInt(), Result);
3125 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3126 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3127 RHSValue.getFloat(), Result);
3128}
3129
3130template <typename APTy>
3131static bool
3133 const APTy &RHSValue, APInt &Result) {
3134 switch (Opcode) {
3135 default:
3136 llvm_unreachable("unsupported binary operator");
3137 case BO_EQ:
3138 Result = (LHSValue == RHSValue);
3139 break;
3140 case BO_NE:
3141 Result = (LHSValue != RHSValue);
3142 break;
3143 case BO_LT:
3144 Result = (LHSValue < RHSValue);
3145 break;
3146 case BO_GT:
3147 Result = (LHSValue > RHSValue);
3148 break;
3149 case BO_LE:
3150 Result = (LHSValue <= RHSValue);
3151 break;
3152 case BO_GE:
3153 Result = (LHSValue >= RHSValue);
3154 break;
3155 }
3156
3157 // The boolean operations on these vector types use an instruction that
3158 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3159 // to -1 to make sure that we produce the correct value.
3160 Result.negate();
3161
3162 return true;
3163}
3164
3165static bool handleCompareOpForVector(const APValue &LHSValue,
3166 BinaryOperatorKind Opcode,
3167 const APValue &RHSValue, APInt &Result) {
3168 // The result is always an int type, however operands match the first.
3169 if (LHSValue.getKind() == APValue::Int)
3170 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3171 RHSValue.getInt(), Result);
3172 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3173 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3174 RHSValue.getFloat(), Result);
3175}
3176
3177// Perform binary operations for vector types, in place on the LHS.
3178static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3179 BinaryOperatorKind Opcode,
3180 APValue &LHSValue,
3181 const APValue &RHSValue) {
3182 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3183 "Operation not supported on vector types");
3184
3185 const auto *VT = E->getType()->castAs<VectorType>();
3186 unsigned NumElements = VT->getNumElements();
3187 QualType EltTy = VT->getElementType();
3188
3189 // In the cases (typically C as I've observed) where we aren't evaluating
3190 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3191 // just give up.
3192 if (!LHSValue.isVector()) {
3193 assert(LHSValue.isLValue() &&
3194 "A vector result that isn't a vector OR uncalculated LValue");
3195 Info.FFDiag(E);
3196 return false;
3197 }
3198
3199 assert(LHSValue.getVectorLength() == NumElements &&
3200 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3201
3202 SmallVector<APValue, 4> ResultElements;
3203
3204 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3205 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3206 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3207
3208 if (EltTy->isIntegerType()) {
3209 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3210 EltTy->isUnsignedIntegerType()};
3211 bool Success = true;
3212
3213 if (BinaryOperator::isLogicalOp(Opcode))
3214 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3215 else if (BinaryOperator::isComparisonOp(Opcode))
3216 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3217 else
3218 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3219 RHSElt.getInt(), EltResult);
3220
3221 if (!Success) {
3222 Info.FFDiag(E);
3223 return false;
3224 }
3225 ResultElements.emplace_back(EltResult);
3226
3227 } else if (EltTy->isFloatingType()) {
3228 assert(LHSElt.getKind() == APValue::Float &&
3229 RHSElt.getKind() == APValue::Float &&
3230 "Mismatched LHS/RHS/Result Type");
3231 APFloat LHSFloat = LHSElt.getFloat();
3232
3233 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3234 RHSElt.getFloat())) {
3235 Info.FFDiag(E);
3236 return false;
3237 }
3238
3239 ResultElements.emplace_back(LHSFloat);
3240 }
3241 }
3242
3243 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3244 return true;
3245}
3246
3247/// Cast an lvalue referring to a base subobject to a derived class, by
3248/// truncating the lvalue's path to the given length.
3249static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3250 const RecordDecl *TruncatedType,
3251 unsigned TruncatedElements) {
3252 SubobjectDesignator &D = Result.Designator;
3253
3254 // Check we actually point to a derived class object.
3255 if (TruncatedElements == D.Entries.size())
3256 return true;
3257 assert(TruncatedElements >= D.MostDerivedPathLength &&
3258 "not casting to a derived class");
3259 if (!Result.checkSubobject(Info, E, CSK_Derived))
3260 return false;
3261
3262 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3263 const RecordDecl *RD = TruncatedType;
3264 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3265 if (RD->isInvalidDecl()) return false;
3266 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3267 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3268 if (isVirtualBaseClass(D.Entries[I]))
3269 Result.Offset -= Layout.getVBaseClassOffset(Base);
3270 else
3271 Result.Offset -= Layout.getBaseClassOffset(Base);
3272 RD = Base;
3273 }
3274 D.Entries.resize(TruncatedElements);
3275 return true;
3276}
3277
3278static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3279 const CXXRecordDecl *Derived,
3280 const CXXRecordDecl *Base,
3281 const ASTRecordLayout *RL = nullptr) {
3282 if (!RL) {
3283 if (Derived->isInvalidDecl()) return false;
3284 RL = &Info.Ctx.getASTRecordLayout(Derived);
3285 }
3286
3287 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3288 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3289 return true;
3290}
3291
3292static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3293 const CXXRecordDecl *DerivedDecl,
3294 const CXXBaseSpecifier *Base) {
3295 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3296
3297 if (!Base->isVirtual())
3298 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3299
3300 SubobjectDesignator &D = Obj.Designator;
3301 if (D.Invalid)
3302 return false;
3303
3304 // Extract most-derived object and corresponding type.
3305 // FIXME: After implementing P2280R4 it became possible to get references
3306 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3307 // locations and if we see crashes in those locations in the future
3308 // it may make more sense to move this fix into Lvalue::set.
3309 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3310 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3311 return false;
3312
3313 // Find the virtual base class.
3314 if (DerivedDecl->isInvalidDecl()) return false;
3315 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3316 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3317 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3318 return true;
3319}
3320
3321static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3322 QualType Type, LValue &Result) {
3323 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3324 PathE = E->path_end();
3325 PathI != PathE; ++PathI) {
3326 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3327 *PathI))
3328 return false;
3329 Type = (*PathI)->getType();
3330 }
3331 return true;
3332}
3333
3334/// Cast an lvalue referring to a derived class to a known base subobject.
3335static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3336 const CXXRecordDecl *DerivedRD,
3337 const CXXRecordDecl *BaseRD) {
3338 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3339 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3340 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3341 llvm_unreachable("Class must be derived from the passed in base class!");
3342
3343 for (CXXBasePathElement &Elem : Paths.front())
3344 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3345 return false;
3346 return true;
3347}
3348
3349/// Update LVal to refer to the given field, which must be a member of the type
3350/// currently described by LVal.
3351static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3352 const FieldDecl *FD,
3353 const ASTRecordLayout *RL = nullptr) {
3354 if (!RL) {
3355 if (FD->getParent()->isInvalidDecl()) return false;
3356 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3357 }
3358
3359 unsigned I = FD->getFieldIndex();
3360 LVal.addDecl(Info, E, FD);
3361 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3362 return true;
3363}
3364
3365/// Update LVal to refer to the given indirect field.
3366static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3367 LValue &LVal,
3368 const IndirectFieldDecl *IFD) {
3369 for (const auto *C : IFD->chain())
3370 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3371 return false;
3372 return true;
3373}
3374
3375enum class SizeOfType {
3376 SizeOf,
3377 DataSizeOf,
3378};
3379
3380/// Get the size of the given type in char units.
3381static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3382 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3383 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3384 // extension.
3385 if (Type->isVoidType() || Type->isFunctionType()) {
3386 Size = CharUnits::One();
3387 return true;
3388 }
3389
3390 if (Type->isDependentType()) {
3391 Info.FFDiag(Loc);
3392 return false;
3393 }
3394
3395 if (!Type->isConstantSizeType()) {
3396 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3397 // FIXME: Better diagnostic.
3398 Info.FFDiag(Loc);
3399 return false;
3400 }
3401
3402 if (SOT == SizeOfType::SizeOf)
3403 Size = Info.Ctx.getTypeSizeInChars(Type);
3404 else
3405 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3406 return true;
3407}
3408
3409/// Update a pointer value to model pointer arithmetic.
3410/// \param Info - Information about the ongoing evaluation.
3411/// \param E - The expression being evaluated, for diagnostic purposes.
3412/// \param LVal - The pointer value to be updated.
3413/// \param EltTy - The pointee type represented by LVal.
3414/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3415static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3416 LValue &LVal, QualType EltTy,
3417 APSInt Adjustment) {
3418 CharUnits SizeOfPointee;
3419 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3420 return false;
3421
3422 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3423 return true;
3424}
3425
3426static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3427 LValue &LVal, QualType EltTy,
3428 int64_t Adjustment) {
3429 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3430 APSInt::get(Adjustment));
3431}
3432
3433/// Update an lvalue to refer to a component of a complex number.
3434/// \param Info - Information about the ongoing evaluation.
3435/// \param LVal - The lvalue to be updated.
3436/// \param EltTy - The complex number's component type.
3437/// \param Imag - False for the real component, true for the imaginary.
3438static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3439 LValue &LVal, QualType EltTy,
3440 bool Imag) {
3441 if (Imag) {
3442 CharUnits SizeOfComponent;
3443 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3444 return false;
3445 LVal.Offset += SizeOfComponent;
3446 }
3447 LVal.addComplex(Info, E, EltTy, Imag);
3448 return true;
3449}
3450
3451static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3452 LValue &LVal, QualType EltTy,
3453 uint64_t Size, uint64_t Idx) {
3454 if (Idx) {
3455 CharUnits SizeOfElement;
3456 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3457 return false;
3458 LVal.Offset += SizeOfElement * Idx;
3459 }
3460 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3461 return true;
3462}
3463
3464/// Try to evaluate the initializer for a variable declaration.
3465///
3466/// \param Info Information about the ongoing evaluation.
3467/// \param E An expression to be used when printing diagnostics.
3468/// \param VD The variable whose initializer should be obtained.
3469/// \param Version The version of the variable within the frame.
3470/// \param Frame The frame in which the variable was created. Must be null
3471/// if this variable is not local to the evaluation.
3472/// \param Result Filled in with a pointer to the value of the variable.
3473static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3474 const VarDecl *VD, CallStackFrame *Frame,
3475 unsigned Version, APValue *&Result) {
3476 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3477 // and pointers.
3478 bool AllowConstexprUnknown =
3479 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3480
3481 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3482
3483 auto CheckUninitReference = [&](bool IsLocalVariable) {
3484 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3485 // C++23 [expr.const]p8
3486 // ... For such an object that is not usable in constant expressions, the
3487 // dynamic type of the object is constexpr-unknown. For such a reference
3488 // that is not usable in constant expressions, the reference is treated
3489 // as binding to an unspecified object of the referenced type whose
3490 // lifetime and that of all subobjects includes the entire constant
3491 // evaluation and whose dynamic type is constexpr-unknown.
3492 //
3493 // Variables that are part of the current evaluation are not
3494 // constexpr-unknown.
3495 if (!AllowConstexprUnknown || IsLocalVariable) {
3496 if (!Info.checkingPotentialConstantExpression())
3497 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3498 return false;
3499 }
3500 Result = nullptr;
3501 }
3502 return true;
3503 };
3504
3505 // If this is a local variable, dig out its value.
3506 if (Frame) {
3507 Result = Frame->getTemporary(VD, Version);
3508 if (Result)
3509 return CheckUninitReference(/*IsLocalVariable=*/true);
3510
3511 if (!isa<ParmVarDecl>(VD)) {
3512 // Assume variables referenced within a lambda's call operator that were
3513 // not declared within the call operator are captures and during checking
3514 // of a potential constant expression, assume they are unknown constant
3515 // expressions.
3516 assert(isLambdaCallOperator(Frame->Callee) &&
3517 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3518 "missing value for local variable");
3519 if (Info.checkingPotentialConstantExpression())
3520 return false;
3521 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3522 // still reachable at all?
3523 Info.FFDiag(E->getBeginLoc(),
3524 diag::note_unimplemented_constexpr_lambda_feature_ast)
3525 << "captures not currently allowed";
3526 return false;
3527 }
3528 }
3529
3530 // If we're currently evaluating the initializer of this declaration, use that
3531 // in-flight value.
3532 if (Info.EvaluatingDecl == Base) {
3533 Result = Info.EvaluatingDeclValue;
3534 return CheckUninitReference(/*IsLocalVariable=*/false);
3535 }
3536
3537 // P2280R4 struck the restriction that variable of reference type lifetime
3538 // should begin within the evaluation of E
3539 // Used to be C++20 [expr.const]p5.12.2:
3540 // ... its lifetime began within the evaluation of E;
3541 if (isa<ParmVarDecl>(VD)) {
3542 if (AllowConstexprUnknown) {
3543 Result = nullptr;
3544 return true;
3545 }
3546
3547 // Assume parameters of a potential constant expression are usable in
3548 // constant expressions.
3549 if (!Info.checkingPotentialConstantExpression() ||
3550 !Info.CurrentCall->Callee ||
3551 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3552 if (Info.getLangOpts().CPlusPlus11) {
3553 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3554 << VD;
3555 NoteLValueLocation(Info, Base);
3556 } else {
3557 Info.FFDiag(E);
3558 }
3559 }
3560 return false;
3561 }
3562
3563 if (E->isValueDependent())
3564 return false;
3565
3566 // Dig out the initializer, and use the declaration which it's attached to.
3567 // FIXME: We should eventually check whether the variable has a reachable
3568 // initializing declaration.
3569 const Expr *Init = VD->getAnyInitializer(VD);
3570 // P2280R4 struck the restriction that variable of reference type should have
3571 // a preceding initialization.
3572 // Used to be C++20 [expr.const]p5.12:
3573 // ... reference has a preceding initialization and either ...
3574 if (!Init && !AllowConstexprUnknown) {
3575 // Don't diagnose during potential constant expression checking; an
3576 // initializer might be added later.
3577 if (!Info.checkingPotentialConstantExpression()) {
3578 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3579 << VD;
3580 NoteLValueLocation(Info, Base);
3581 }
3582 return false;
3583 }
3584
3585 // P2280R4 struck the initialization requirement for variables of reference
3586 // type so we can no longer assume we have an Init.
3587 // Used to be C++20 [expr.const]p5.12:
3588 // ... reference has a preceding initialization and either ...
3589 if (Init && Init->isValueDependent()) {
3590 // The DeclRefExpr is not value-dependent, but the variable it refers to
3591 // has a value-dependent initializer. This should only happen in
3592 // constant-folding cases, where the variable is not actually of a suitable
3593 // type for use in a constant expression (otherwise the DeclRefExpr would
3594 // have been value-dependent too), so diagnose that.
3595 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3596 if (!Info.checkingPotentialConstantExpression()) {
3597 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3598 ? diag::note_constexpr_ltor_non_constexpr
3599 : diag::note_constexpr_ltor_non_integral, 1)
3600 << VD << VD->getType();
3601 NoteLValueLocation(Info, Base);
3602 }
3603 return false;
3604 }
3605
3606 // Check that we can fold the initializer. In C++, we will have already done
3607 // this in the cases where it matters for conformance.
3608 // P2280R4 struck the initialization requirement for variables of reference
3609 // type so we can no longer assume we have an Init.
3610 // Used to be C++20 [expr.const]p5.12:
3611 // ... reference has a preceding initialization and either ...
3612 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3613 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3614 NoteLValueLocation(Info, Base);
3615 return false;
3616 }
3617
3618 // Check that the variable is actually usable in constant expressions. For a
3619 // const integral variable or a reference, we might have a non-constant
3620 // initializer that we can nonetheless evaluate the initializer for. Such
3621 // variables are not usable in constant expressions. In C++98, the
3622 // initializer also syntactically needs to be an ICE.
3623 //
3624 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3625 // expressions here; doing so would regress diagnostics for things like
3626 // reading from a volatile constexpr variable.
3627 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3628 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3629 !AllowConstexprUnknown) ||
3630 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3631 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3632 if (Init) {
3633 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3634 NoteLValueLocation(Info, Base);
3635 } else {
3636 Info.CCEDiag(E);
3637 }
3638 }
3639
3640 // Never use the initializer of a weak variable, not even for constant
3641 // folding. We can't be sure that this is the definition that will be used.
3642 if (VD->isWeak()) {
3643 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3644 NoteLValueLocation(Info, Base);
3645 return false;
3646 }
3647
3648 Result = VD->getEvaluatedValue();
3649
3650 if (!Result && !AllowConstexprUnknown)
3651 return false;
3652
3653 return CheckUninitReference(/*IsLocalVariable=*/false);
3654}
3655
3656/// Get the base index of the given base class within an APValue representing
3657/// the given derived class.
3658static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3659 const CXXRecordDecl *Base) {
3660 Base = Base->getCanonicalDecl();
3661 unsigned Index = 0;
3663 E = Derived->bases_end(); I != E; ++I, ++Index) {
3664 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3665 return Index;
3666 }
3667
3668 llvm_unreachable("base class missing from derived class's bases list");
3669}
3670
3671/// Extract the value of a character from a string literal.
3672static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3673 uint64_t Index) {
3674 assert(!isa<SourceLocExpr>(Lit) &&
3675 "SourceLocExpr should have already been converted to a StringLiteral");
3676
3677 // FIXME: Support MakeStringConstant
3678 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3679 std::string Str;
3680 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3681 assert(Index <= Str.size() && "Index too large");
3682 return APSInt::getUnsigned(Str.c_str()[Index]);
3683 }
3684
3685 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3686 Lit = PE->getFunctionName();
3687 const StringLiteral *S = cast<StringLiteral>(Lit);
3688 const ConstantArrayType *CAT =
3689 Info.Ctx.getAsConstantArrayType(S->getType());
3690 assert(CAT && "string literal isn't an array");
3691 QualType CharType = CAT->getElementType();
3692 assert(CharType->isIntegerType() && "unexpected character type");
3693 APSInt Value(Info.Ctx.getTypeSize(CharType),
3694 CharType->isUnsignedIntegerType());
3695 if (Index < S->getLength())
3696 Value = S->getCodeUnit(Index);
3697 return Value;
3698}
3699
3700// Expand a string literal into an array of characters.
3701//
3702// FIXME: This is inefficient; we should probably introduce something similar
3703// to the LLVM ConstantDataArray to make this cheaper.
3704static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3705 APValue &Result,
3706 QualType AllocType = QualType()) {
3707 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3708 AllocType.isNull() ? S->getType() : AllocType);
3709 assert(CAT && "string literal isn't an array");
3710 QualType CharType = CAT->getElementType();
3711 assert(CharType->isIntegerType() && "unexpected character type");
3712
3713 unsigned Elts = CAT->getZExtSize();
3714 Result = APValue(APValue::UninitArray(),
3715 std::min(S->getLength(), Elts), Elts);
3716 APSInt Value(Info.Ctx.getTypeSize(CharType),
3717 CharType->isUnsignedIntegerType());
3718 if (Result.hasArrayFiller())
3719 Result.getArrayFiller() = APValue(Value);
3720 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3721 Value = S->getCodeUnit(I);
3722 Result.getArrayInitializedElt(I) = APValue(Value);
3723 }
3724}
3725
3726// Expand an array so that it has more than Index filled elements.
3727static void expandArray(APValue &Array, unsigned Index) {
3728 unsigned Size = Array.getArraySize();
3729 assert(Index < Size);
3730
3731 // Always at least double the number of elements for which we store a value.
3732 unsigned OldElts = Array.getArrayInitializedElts();
3733 unsigned NewElts = std::max(Index+1, OldElts * 2);
3734 NewElts = std::min(Size, std::max(NewElts, 8u));
3735
3736 // Copy the data across.
3737 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3738 for (unsigned I = 0; I != OldElts; ++I)
3739 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3740 for (unsigned I = OldElts; I != NewElts; ++I)
3741 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3742 if (NewValue.hasArrayFiller())
3743 NewValue.getArrayFiller() = Array.getArrayFiller();
3744 Array.swap(NewValue);
3745}
3746
3747/// Determine whether a type would actually be read by an lvalue-to-rvalue
3748/// conversion. If it's of class type, we may assume that the copy operation
3749/// is trivial. Note that this is never true for a union type with fields
3750/// (because the copy always "reads" the active member) and always true for
3751/// a non-class type.
3752static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3755 return !RD || isReadByLvalueToRvalueConversion(RD);
3756}
3758 // FIXME: A trivial copy of a union copies the object representation, even if
3759 // the union is empty.
3760 if (RD->isUnion())
3761 return !RD->field_empty();
3762 if (RD->isEmpty())
3763 return false;
3764
3765 for (auto *Field : RD->fields())
3766 if (!Field->isUnnamedBitField() &&
3767 isReadByLvalueToRvalueConversion(Field->getType()))
3768 return true;
3769
3770 for (auto &BaseSpec : RD->bases())
3771 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3772 return true;
3773
3774 return false;
3775}
3776
3777/// Diagnose an attempt to read from any unreadable field within the specified
3778/// type, which might be a class type.
3779static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3780 QualType T) {
3782 if (!RD)
3783 return false;
3784
3785 if (!RD->hasMutableFields())
3786 return false;
3787
3788 for (auto *Field : RD->fields()) {
3789 // If we're actually going to read this field in some way, then it can't
3790 // be mutable. If we're in a union, then assigning to a mutable field
3791 // (even an empty one) can change the active member, so that's not OK.
3792 // FIXME: Add core issue number for the union case.
3793 if (Field->isMutable() &&
3794 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3795 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3796 Info.Note(Field->getLocation(), diag::note_declared_at);
3797 return true;
3798 }
3799
3800 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3801 return true;
3802 }
3803
3804 for (auto &BaseSpec : RD->bases())
3805 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3806 return true;
3807
3808 // All mutable fields were empty, and thus not actually read.
3809 return false;
3810}
3811
3812static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3814 bool MutableSubobject = false) {
3815 // A temporary or transient heap allocation we created.
3816 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3817 return true;
3818
3819 switch (Info.IsEvaluatingDecl) {
3820 case EvalInfo::EvaluatingDeclKind::None:
3821 return false;
3822
3823 case EvalInfo::EvaluatingDeclKind::Ctor:
3824 // The variable whose initializer we're evaluating.
3825 if (Info.EvaluatingDecl == Base)
3826 return true;
3827
3828 // A temporary lifetime-extended by the variable whose initializer we're
3829 // evaluating.
3830 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3831 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3832 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3833 return false;
3834
3835 case EvalInfo::EvaluatingDeclKind::Dtor:
3836 // C++2a [expr.const]p6:
3837 // [during constant destruction] the lifetime of a and its non-mutable
3838 // subobjects (but not its mutable subobjects) [are] considered to start
3839 // within e.
3840 if (MutableSubobject || Base != Info.EvaluatingDecl)
3841 return false;
3842 // FIXME: We can meaningfully extend this to cover non-const objects, but
3843 // we will need special handling: we should be able to access only
3844 // subobjects of such objects that are themselves declared const.
3845 QualType T = getType(Base);
3846 return T.isConstQualified() || T->isReferenceType();
3847 }
3848
3849 llvm_unreachable("unknown evaluating decl kind");
3850}
3851
3852static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3853 SourceLocation CallLoc = {}) {
3854 return Info.CheckArraySize(
3855 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3856 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3857 /*Diag=*/true);
3858}
3859
3860namespace {
3861/// A handle to a complete object (an object that is not a subobject of
3862/// another object).
3863struct CompleteObject {
3864 /// The identity of the object.
3866 /// The value of the complete object.
3867 APValue *Value;
3868 /// The type of the complete object.
3869 QualType Type;
3870
3871 CompleteObject() : Value(nullptr) {}
3873 : Base(Base), Value(Value), Type(Type) {}
3874
3875 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3876 // If this isn't a "real" access (eg, if it's just accessing the type
3877 // info), allow it. We assume the type doesn't change dynamically for
3878 // subobjects of constexpr objects (even though we'd hit UB here if it
3879 // did). FIXME: Is this right?
3880 if (!isAnyAccess(AK))
3881 return true;
3882
3883 // In C++14 onwards, it is permitted to read a mutable member whose
3884 // lifetime began within the evaluation.
3885 // FIXME: Should we also allow this in C++11?
3886 if (!Info.getLangOpts().CPlusPlus14 &&
3887 AK != AccessKinds::AK_IsWithinLifetime)
3888 return false;
3889 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3890 }
3891
3892 explicit operator bool() const { return !Type.isNull(); }
3893};
3894} // end anonymous namespace
3895
3896static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3897 bool IsMutable = false) {
3898 // C++ [basic.type.qualifier]p1:
3899 // - A const object is an object of type const T or a non-mutable subobject
3900 // of a const object.
3901 if (ObjType.isConstQualified() && !IsMutable)
3902 SubobjType.addConst();
3903 // - A volatile object is an object of type const T or a subobject of a
3904 // volatile object.
3905 if (ObjType.isVolatileQualified())
3906 SubobjType.addVolatile();
3907 return SubobjType;
3908}
3909
3910/// Find the designated sub-object of an rvalue.
3911template <typename SubobjectHandler>
3912static typename SubobjectHandler::result_type
3913findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3914 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3915 if (Sub.Invalid)
3916 // A diagnostic will have already been produced.
3917 return handler.failed();
3918 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3919 if (Info.getLangOpts().CPlusPlus11)
3920 Info.FFDiag(E, Sub.isOnePastTheEnd()
3921 ? diag::note_constexpr_access_past_end
3922 : diag::note_constexpr_access_unsized_array)
3923 << handler.AccessKind;
3924 else
3925 Info.FFDiag(E);
3926 return handler.failed();
3927 }
3928
3929 APValue *O = Obj.Value;
3930 QualType ObjType = Obj.Type;
3931 const FieldDecl *LastField = nullptr;
3932 const FieldDecl *VolatileField = nullptr;
3933
3934 // Walk the designator's path to find the subobject.
3935 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3936 // Reading an indeterminate value is undefined, but assigning over one is OK.
3937 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3938 (O->isIndeterminate() &&
3939 !isValidIndeterminateAccess(handler.AccessKind))) {
3940 // Object has ended lifetime.
3941 // If I is non-zero, some subobject (member or array element) of a
3942 // complete object has ended its lifetime, so this is valid for
3943 // IsWithinLifetime, resulting in false.
3944 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3945 return false;
3946 if (!Info.checkingPotentialConstantExpression())
3947 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3948 << handler.AccessKind << O->isIndeterminate()
3949 << E->getSourceRange();
3950 return handler.failed();
3951 }
3952
3953 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3954 // const and volatile semantics are not applied on an object under
3955 // {con,de}struction.
3956 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3957 ObjType->isRecordType() &&
3958 Info.isEvaluatingCtorDtor(
3959 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3960 ConstructionPhase::None) {
3961 ObjType = Info.Ctx.getCanonicalType(ObjType);
3962 ObjType.removeLocalConst();
3963 ObjType.removeLocalVolatile();
3964 }
3965
3966 // If this is our last pass, check that the final object type is OK.
3967 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3968 // Accesses to volatile objects are prohibited.
3969 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3970 if (Info.getLangOpts().CPlusPlus) {
3971 int DiagKind;
3973 const NamedDecl *Decl = nullptr;
3974 if (VolatileField) {
3975 DiagKind = 2;
3976 Loc = VolatileField->getLocation();
3977 Decl = VolatileField;
3978 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3979 DiagKind = 1;
3980 Loc = VD->getLocation();
3981 Decl = VD;
3982 } else {
3983 DiagKind = 0;
3984 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3985 Loc = E->getExprLoc();
3986 }
3987 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3988 << handler.AccessKind << DiagKind << Decl;
3989 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3990 } else {
3991 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3992 }
3993 return handler.failed();
3994 }
3995
3996 // If we are reading an object of class type, there may still be more
3997 // things we need to check: if there are any mutable subobjects, we
3998 // cannot perform this read. (This only happens when performing a trivial
3999 // copy or assignment.)
4000 if (ObjType->isRecordType() &&
4001 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4002 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4003 return handler.failed();
4004 }
4005
4006 if (I == N) {
4007 if (!handler.found(*O, ObjType))
4008 return false;
4009
4010 // If we modified a bit-field, truncate it to the right width.
4011 if (isModification(handler.AccessKind) &&
4012 LastField && LastField->isBitField() &&
4013 !truncateBitfieldValue(Info, E, *O, LastField))
4014 return false;
4015
4016 return true;
4017 }
4018
4019 LastField = nullptr;
4020 if (ObjType->isArrayType()) {
4021 // Next subobject is an array element.
4022 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
4023 assert(CAT && "vla in literal type?");
4024 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4025 if (CAT->getSize().ule(Index)) {
4026 // Note, it should not be possible to form a pointer with a valid
4027 // designator which points more than one past the end of the array.
4028 if (Info.getLangOpts().CPlusPlus11)
4029 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4030 << handler.AccessKind;
4031 else
4032 Info.FFDiag(E);
4033 return handler.failed();
4034 }
4035
4036 ObjType = CAT->getElementType();
4037
4038 if (O->getArrayInitializedElts() > Index)
4039 O = &O->getArrayInitializedElt(Index);
4040 else if (!isRead(handler.AccessKind)) {
4041 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
4042 return handler.failed();
4043
4044 expandArray(*O, Index);
4045 O = &O->getArrayInitializedElt(Index);
4046 } else
4047 O = &O->getArrayFiller();
4048 } else if (ObjType->isAnyComplexType()) {
4049 // Next subobject is a complex number.
4050 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4051 if (Index > 1) {
4052 if (Info.getLangOpts().CPlusPlus11)
4053 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4054 << handler.AccessKind;
4055 else
4056 Info.FFDiag(E);
4057 return handler.failed();
4058 }
4059
4060 ObjType = getSubobjectType(
4061 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4062
4063 assert(I == N - 1 && "extracting subobject of scalar?");
4064 if (O->isComplexInt()) {
4065 return handler.found(Index ? O->getComplexIntImag()
4066 : O->getComplexIntReal(), ObjType);
4067 } else {
4068 assert(O->isComplexFloat());
4069 return handler.found(Index ? O->getComplexFloatImag()
4070 : O->getComplexFloatReal(), ObjType);
4071 }
4072 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4073 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4074 unsigned NumElements = VT->getNumElements();
4075 if (Index == NumElements) {
4076 if (Info.getLangOpts().CPlusPlus11)
4077 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4078 << handler.AccessKind;
4079 else
4080 Info.FFDiag(E);
4081 return handler.failed();
4082 }
4083
4084 if (Index > NumElements) {
4085 Info.CCEDiag(E, diag::note_constexpr_array_index)
4086 << Index << /*array*/ 0 << NumElements;
4087 return handler.failed();
4088 }
4089
4090 ObjType = VT->getElementType();
4091 assert(I == N - 1 && "extracting subobject of scalar?");
4092 return handler.found(O->getVectorElt(Index), ObjType);
4093 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4094 if (Field->isMutable() &&
4095 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4096 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4097 << handler.AccessKind << Field;
4098 Info.Note(Field->getLocation(), diag::note_declared_at);
4099 return handler.failed();
4100 }
4101
4102 // Next subobject is a class, struct or union field.
4103 RecordDecl *RD =
4104 ObjType->castAsCanonical<RecordType>()->getOriginalDecl();
4105 if (RD->isUnion()) {
4106 const FieldDecl *UnionField = O->getUnionField();
4107 if (!UnionField ||
4108 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4109 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4110 // Placement new onto an inactive union member makes it active.
4111 O->setUnion(Field, APValue());
4112 } else {
4113 // Pointer to/into inactive union member: Not within lifetime
4114 if (handler.AccessKind == AK_IsWithinLifetime)
4115 return false;
4116 // FIXME: If O->getUnionValue() is absent, report that there's no
4117 // active union member rather than reporting the prior active union
4118 // member. We'll need to fix nullptr_t to not use APValue() as its
4119 // representation first.
4120 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4121 << handler.AccessKind << Field << !UnionField << UnionField;
4122 return handler.failed();
4123 }
4124 }
4125 O = &O->getUnionValue();
4126 } else
4127 O = &O->getStructField(Field->getFieldIndex());
4128
4129 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4130 LastField = Field;
4131 if (Field->getType().isVolatileQualified())
4132 VolatileField = Field;
4133 } else {
4134 // Next subobject is a base class.
4135 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4136 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4137 O = &O->getStructBase(getBaseIndex(Derived, Base));
4138
4139 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4140 }
4141 }
4142}
4143
4144namespace {
4145struct ExtractSubobjectHandler {
4146 EvalInfo &Info;
4147 const Expr *E;
4148 APValue &Result;
4149 const AccessKinds AccessKind;
4150
4151 typedef bool result_type;
4152 bool failed() { return false; }
4153 bool found(APValue &Subobj, QualType SubobjType) {
4154 Result = Subobj;
4155 if (AccessKind == AK_ReadObjectRepresentation)
4156 return true;
4157 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4158 }
4159 bool found(APSInt &Value, QualType SubobjType) {
4160 Result = APValue(Value);
4161 return true;
4162 }
4163 bool found(APFloat &Value, QualType SubobjType) {
4164 Result = APValue(Value);
4165 return true;
4166 }
4167};
4168} // end anonymous namespace
4169
4170/// Extract the designated sub-object of an rvalue.
4171static bool extractSubobject(EvalInfo &Info, const Expr *E,
4172 const CompleteObject &Obj,
4173 const SubobjectDesignator &Sub, APValue &Result,
4174 AccessKinds AK = AK_Read) {
4175 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4176 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4177 return findSubobject(Info, E, Obj, Sub, Handler);
4178}
4179
4180namespace {
4181struct ModifySubobjectHandler {
4182 EvalInfo &Info;
4183 APValue &NewVal;
4184 const Expr *E;
4185
4186 typedef bool result_type;
4187 static const AccessKinds AccessKind = AK_Assign;
4188
4189 bool checkConst(QualType QT) {
4190 // Assigning to a const object has undefined behavior.
4191 if (QT.isConstQualified()) {
4192 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4193 return false;
4194 }
4195 return true;
4196 }
4197
4198 bool failed() { return false; }
4199 bool found(APValue &Subobj, QualType SubobjType) {
4200 if (!checkConst(SubobjType))
4201 return false;
4202 // We've been given ownership of NewVal, so just swap it in.
4203 Subobj.swap(NewVal);
4204 return true;
4205 }
4206 bool found(APSInt &Value, QualType SubobjType) {
4207 if (!checkConst(SubobjType))
4208 return false;
4209 if (!NewVal.isInt()) {
4210 // Maybe trying to write a cast pointer value into a complex?
4211 Info.FFDiag(E);
4212 return false;
4213 }
4214 Value = NewVal.getInt();
4215 return true;
4216 }
4217 bool found(APFloat &Value, QualType SubobjType) {
4218 if (!checkConst(SubobjType))
4219 return false;
4220 Value = NewVal.getFloat();
4221 return true;
4222 }
4223};
4224} // end anonymous namespace
4225
4226const AccessKinds ModifySubobjectHandler::AccessKind;
4227
4228/// Update the designated sub-object of an rvalue to the given value.
4229static bool modifySubobject(EvalInfo &Info, const Expr *E,
4230 const CompleteObject &Obj,
4231 const SubobjectDesignator &Sub,
4232 APValue &NewVal) {
4233 ModifySubobjectHandler Handler = { Info, NewVal, E };
4234 return findSubobject(Info, E, Obj, Sub, Handler);
4235}
4236
4237/// Find the position where two subobject designators diverge, or equivalently
4238/// the length of the common initial subsequence.
4239static unsigned FindDesignatorMismatch(QualType ObjType,
4240 const SubobjectDesignator &A,
4241 const SubobjectDesignator &B,
4242 bool &WasArrayIndex) {
4243 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4244 for (/**/; I != N; ++I) {
4245 if (!ObjType.isNull() &&
4246 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4247 // Next subobject is an array element.
4248 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4249 WasArrayIndex = true;
4250 return I;
4251 }
4252 if (ObjType->isAnyComplexType())
4253 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4254 else
4255 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4256 } else {
4257 if (A.Entries[I].getAsBaseOrMember() !=
4258 B.Entries[I].getAsBaseOrMember()) {
4259 WasArrayIndex = false;
4260 return I;
4261 }
4262 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4263 // Next subobject is a field.
4264 ObjType = FD->getType();
4265 else
4266 // Next subobject is a base class.
4267 ObjType = QualType();
4268 }
4269 }
4270 WasArrayIndex = false;
4271 return I;
4272}
4273
4274/// Determine whether the given subobject designators refer to elements of the
4275/// same array object.
4277 const SubobjectDesignator &A,
4278 const SubobjectDesignator &B) {
4279 if (A.Entries.size() != B.Entries.size())
4280 return false;
4281
4282 bool IsArray = A.MostDerivedIsArrayElement;
4283 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4284 // A is a subobject of the array element.
4285 return false;
4286
4287 // If A (and B) designates an array element, the last entry will be the array
4288 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4289 // of length 1' case, and the entire path must match.
4290 bool WasArrayIndex;
4291 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4292 return CommonLength >= A.Entries.size() - IsArray;
4293}
4294
4295/// Find the complete object to which an LValue refers.
4296static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4297 AccessKinds AK, const LValue &LVal,
4298 QualType LValType) {
4299 if (LVal.InvalidBase) {
4300 Info.FFDiag(E);
4301 return CompleteObject();
4302 }
4303
4304 if (!LVal.Base) {
4305 if (AK == AccessKinds::AK_Dereference)
4306 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4307 else
4308 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4309 return CompleteObject();
4310 }
4311
4312 CallStackFrame *Frame = nullptr;
4313 unsigned Depth = 0;
4314 if (LVal.getLValueCallIndex()) {
4315 std::tie(Frame, Depth) =
4316 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4317 if (!Frame) {
4318 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4319 << AK << LVal.Base.is<const ValueDecl*>();
4320 NoteLValueLocation(Info, LVal.Base);
4321 return CompleteObject();
4322 }
4323 }
4324
4325 bool IsAccess = isAnyAccess(AK);
4326
4327 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4328 // is not a constant expression (even if the object is non-volatile). We also
4329 // apply this rule to C++98, in order to conform to the expected 'volatile'
4330 // semantics.
4331 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4332 if (Info.getLangOpts().CPlusPlus)
4333 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4334 << AK << LValType;
4335 else
4336 Info.FFDiag(E);
4337 return CompleteObject();
4338 }
4339
4340 // Compute value storage location and type of base object.
4341 APValue *BaseVal = nullptr;
4342 QualType BaseType = getType(LVal.Base);
4343
4344 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4345 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4346 // This is the object whose initializer we're evaluating, so its lifetime
4347 // started in the current evaluation.
4348 BaseVal = Info.EvaluatingDeclValue;
4349 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4350 // Allow reading from a GUID declaration.
4351 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4352 if (isModification(AK)) {
4353 // All the remaining cases do not permit modification of the object.
4354 Info.FFDiag(E, diag::note_constexpr_modify_global);
4355 return CompleteObject();
4356 }
4357 APValue &V = GD->getAsAPValue();
4358 if (V.isAbsent()) {
4359 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4360 << GD->getType();
4361 return CompleteObject();
4362 }
4363 return CompleteObject(LVal.Base, &V, GD->getType());
4364 }
4365
4366 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4367 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4368 if (isModification(AK)) {
4369 Info.FFDiag(E, diag::note_constexpr_modify_global);
4370 return CompleteObject();
4371 }
4372 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4373 GCD->getType());
4374 }
4375
4376 // Allow reading from template parameter objects.
4377 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4378 if (isModification(AK)) {
4379 Info.FFDiag(E, diag::note_constexpr_modify_global);
4380 return CompleteObject();
4381 }
4382 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4383 TPO->getType());
4384 }
4385
4386 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4387 // In C++11, constexpr, non-volatile variables initialized with constant
4388 // expressions are constant expressions too. Inside constexpr functions,
4389 // parameters are constant expressions even if they're non-const.
4390 // In C++1y, objects local to a constant expression (those with a Frame) are
4391 // both readable and writable inside constant expressions.
4392 // In C, such things can also be folded, although they are not ICEs.
4393 const VarDecl *VD = dyn_cast<VarDecl>(D);
4394 if (VD) {
4395 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4396 VD = VDef;
4397 }
4398 if (!VD || VD->isInvalidDecl()) {
4399 Info.FFDiag(E);
4400 return CompleteObject();
4401 }
4402
4403 bool IsConstant = BaseType.isConstant(Info.Ctx);
4404 bool ConstexprVar = false;
4405 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4406 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4407 ConstexprVar = VD->isConstexpr();
4408
4409 // Unless we're looking at a local variable or argument in a constexpr call,
4410 // the variable we're reading must be const (unless we are binding to a
4411 // reference).
4412 if (AK != clang::AK_Dereference && !Frame) {
4413 if (IsAccess && isa<ParmVarDecl>(VD)) {
4414 // Access of a parameter that's not associated with a frame isn't going
4415 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4416 // suitable diagnostic.
4417 } else if (Info.getLangOpts().CPlusPlus14 &&
4418 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4419 // OK, we can read and modify an object if we're in the process of
4420 // evaluating its initializer, because its lifetime began in this
4421 // evaluation.
4422 } else if (isModification(AK)) {
4423 // All the remaining cases do not permit modification of the object.
4424 Info.FFDiag(E, diag::note_constexpr_modify_global);
4425 return CompleteObject();
4426 } else if (VD->isConstexpr()) {
4427 // OK, we can read this variable.
4428 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4429 Info.FFDiag(E);
4430 return CompleteObject();
4431 } else if (BaseType->isIntegralOrEnumerationType()) {
4432 if (!IsConstant) {
4433 if (!IsAccess)
4434 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4435 if (Info.getLangOpts().CPlusPlus) {
4436 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4437 Info.Note(VD->getLocation(), diag::note_declared_at);
4438 } else {
4439 Info.FFDiag(E);
4440 }
4441 return CompleteObject();
4442 }
4443 } else if (!IsAccess) {
4444 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4445 } else if ((IsConstant || BaseType->isReferenceType()) &&
4446 Info.checkingPotentialConstantExpression() &&
4447 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4448 // This variable might end up being constexpr. Don't diagnose it yet.
4449 } else if (IsConstant) {
4450 // Keep evaluating to see what we can do. In particular, we support
4451 // folding of const floating-point types, in order to make static const
4452 // data members of such types (supported as an extension) more useful.
4453 if (Info.getLangOpts().CPlusPlus) {
4454 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4455 ? diag::note_constexpr_ltor_non_constexpr
4456 : diag::note_constexpr_ltor_non_integral, 1)
4457 << VD << BaseType;
4458 Info.Note(VD->getLocation(), diag::note_declared_at);
4459 } else {
4460 Info.CCEDiag(E);
4461 }
4462 } else {
4463 // Never allow reading a non-const value.
4464 if (Info.getLangOpts().CPlusPlus) {
4465 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4466 ? diag::note_constexpr_ltor_non_constexpr
4467 : diag::note_constexpr_ltor_non_integral, 1)
4468 << VD << BaseType;
4469 Info.Note(VD->getLocation(), diag::note_declared_at);
4470 } else {
4471 Info.FFDiag(E);
4472 }
4473 return CompleteObject();
4474 }
4475 }
4476
4477 // When binding to a reference, the variable does not need to be constexpr
4478 // or have constant initalization.
4479 if (AK != clang::AK_Dereference &&
4480 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4481 BaseVal))
4482 return CompleteObject();
4483 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4484 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4485 // we can't access a constexpr-unknown object.
4486 if (AK != clang::AK_Dereference && !BaseVal) {
4487 if (!Info.checkingPotentialConstantExpression()) {
4488 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4489 << AK << VD;
4490 Info.Note(VD->getLocation(), diag::note_declared_at);
4491 }
4492 return CompleteObject();
4493 }
4494 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4495 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4496 if (!Alloc) {
4497 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4498 return CompleteObject();
4499 }
4500 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4501 LVal.Base.getDynamicAllocType());
4502 }
4503 // When binding to a reference, the variable does not need to be
4504 // within its lifetime.
4505 else if (AK != clang::AK_Dereference) {
4506 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4507
4508 if (!Frame) {
4509 if (const MaterializeTemporaryExpr *MTE =
4510 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4511 assert(MTE->getStorageDuration() == SD_Static &&
4512 "should have a frame for a non-global materialized temporary");
4513
4514 // C++20 [expr.const]p4: [DR2126]
4515 // An object or reference is usable in constant expressions if it is
4516 // - a temporary object of non-volatile const-qualified literal type
4517 // whose lifetime is extended to that of a variable that is usable
4518 // in constant expressions
4519 //
4520 // C++20 [expr.const]p5:
4521 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4522 // - a non-volatile glvalue that refers to an object that is usable
4523 // in constant expressions, or
4524 // - a non-volatile glvalue of literal type that refers to a
4525 // non-volatile object whose lifetime began within the evaluation
4526 // of E;
4527 //
4528 // C++11 misses the 'began within the evaluation of e' check and
4529 // instead allows all temporaries, including things like:
4530 // int &&r = 1;
4531 // int x = ++r;
4532 // constexpr int k = r;
4533 // Therefore we use the C++14-onwards rules in C++11 too.
4534 //
4535 // Note that temporaries whose lifetimes began while evaluating a
4536 // variable's constructor are not usable while evaluating the
4537 // corresponding destructor, not even if they're of const-qualified
4538 // types.
4539 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4540 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4541 if (!IsAccess)
4542 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4543 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4544 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4545 return CompleteObject();
4546 }
4547
4548 BaseVal = MTE->getOrCreateValue(false);
4549 assert(BaseVal && "got reference to unevaluated temporary");
4550 } else if (const CompoundLiteralExpr *CLE =
4551 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4552 // According to GCC info page:
4553 //
4554 // 6.28 Compound Literals
4555 //
4556 // As an optimization, G++ sometimes gives array compound literals
4557 // longer lifetimes: when the array either appears outside a function or
4558 // has a const-qualified type. If foo and its initializer had elements
4559 // of type char *const rather than char *, or if foo were a global
4560 // variable, the array would have static storage duration. But it is
4561 // probably safest just to avoid the use of array compound literals in
4562 // C++ code.
4563 //
4564 // Obey that rule by checking constness for converted array types.
4565 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4566 !LValType->isArrayType() &&
4567 !CLETy.isConstant(Info.Ctx)) {
4568 Info.FFDiag(E);
4569 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4570 return CompleteObject();
4571 }
4572
4573 BaseVal = &CLE->getStaticValue();
4574 } else {
4575 if (!IsAccess)
4576 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4577 APValue Val;
4578 LVal.moveInto(Val);
4579 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4580 << AK
4581 << Val.getAsString(Info.Ctx,
4582 Info.Ctx.getLValueReferenceType(LValType));
4583 NoteLValueLocation(Info, LVal.Base);
4584 return CompleteObject();
4585 }
4586 } else if (AK != clang::AK_Dereference) {
4587 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4588 assert(BaseVal && "missing value for temporary");
4589 }
4590 }
4591
4592 // In C++14, we can't safely access any mutable state when we might be
4593 // evaluating after an unmodeled side effect. Parameters are modeled as state
4594 // in the caller, but aren't visible once the call returns, so they can be
4595 // modified in a speculatively-evaluated call.
4596 //
4597 // FIXME: Not all local state is mutable. Allow local constant subobjects
4598 // to be read here (but take care with 'mutable' fields).
4599 unsigned VisibleDepth = Depth;
4600 if (llvm::isa_and_nonnull<ParmVarDecl>(
4601 LVal.Base.dyn_cast<const ValueDecl *>()))
4602 ++VisibleDepth;
4603 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4604 Info.EvalStatus.HasSideEffects) ||
4605 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4606 return CompleteObject();
4607
4608 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4609}
4610
4611/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4612/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4613/// glvalue referred to by an entity of reference type.
4614///
4615/// \param Info - Information about the ongoing evaluation.
4616/// \param Conv - The expression for which we are performing the conversion.
4617/// Used for diagnostics.
4618/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4619/// case of a non-class type).
4620/// \param LVal - The glvalue on which we are attempting to perform this action.
4621/// \param RVal - The produced value will be placed here.
4622/// \param WantObjectRepresentation - If true, we're looking for the object
4623/// representation rather than the value, and in particular,
4624/// there is no requirement that the result be fully initialized.
4625static bool
4627 const LValue &LVal, APValue &RVal,
4628 bool WantObjectRepresentation = false) {
4629 if (LVal.Designator.Invalid)
4630 return false;
4631
4632 // Check for special cases where there is no existing APValue to look at.
4633 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4634
4635 AccessKinds AK =
4636 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4637
4638 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4639 if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4640 // Special-case character extraction so we don't have to construct an
4641 // APValue for the whole string.
4642 assert(LVal.Designator.Entries.size() <= 1 &&
4643 "Can only read characters from string literals");
4644 if (LVal.Designator.Entries.empty()) {
4645 // Fail for now for LValue to RValue conversion of an array.
4646 // (This shouldn't show up in C/C++, but it could be triggered by a
4647 // weird EvaluateAsRValue call from a tool.)
4648 Info.FFDiag(Conv);
4649 return false;
4650 }
4651 if (LVal.Designator.isOnePastTheEnd()) {
4652 if (Info.getLangOpts().CPlusPlus11)
4653 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4654 else
4655 Info.FFDiag(Conv);
4656 return false;
4657 }
4658 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4659 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4660 return true;
4661 }
4662 }
4663
4664 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4665 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4666}
4667
4668/// Perform an assignment of Val to LVal. Takes ownership of Val.
4669static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4670 QualType LValType, APValue &Val) {
4671 if (LVal.Designator.Invalid)
4672 return false;
4673
4674 if (!Info.getLangOpts().CPlusPlus14) {
4675 Info.FFDiag(E);
4676 return false;
4677 }
4678
4679 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4680 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4681}
4682
4683namespace {
4684struct CompoundAssignSubobjectHandler {
4685 EvalInfo &Info;
4687 QualType PromotedLHSType;
4689 const APValue &RHS;
4690
4691 static const AccessKinds AccessKind = AK_Assign;
4692
4693 typedef bool result_type;
4694
4695 bool checkConst(QualType QT) {
4696 // Assigning to a const object has undefined behavior.
4697 if (QT.isConstQualified()) {
4698 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4699 return false;
4700 }
4701 return true;
4702 }
4703
4704 bool failed() { return false; }
4705 bool found(APValue &Subobj, QualType SubobjType) {
4706 switch (Subobj.getKind()) {
4707 case APValue::Int:
4708 return found(Subobj.getInt(), SubobjType);
4709 case APValue::Float:
4710 return found(Subobj.getFloat(), SubobjType);
4713 // FIXME: Implement complex compound assignment.
4714 Info.FFDiag(E);
4715 return false;
4716 case APValue::LValue:
4717 return foundPointer(Subobj, SubobjType);
4718 case APValue::Vector:
4719 return foundVector(Subobj, SubobjType);
4721 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4722 << /*read of=*/0 << /*uninitialized object=*/1
4723 << E->getLHS()->getSourceRange();
4724 return false;
4725 default:
4726 // FIXME: can this happen?
4727 Info.FFDiag(E);
4728 return false;
4729 }
4730 }
4731
4732 bool foundVector(APValue &Value, QualType SubobjType) {
4733 if (!checkConst(SubobjType))
4734 return false;
4735
4736 if (!SubobjType->isVectorType()) {
4737 Info.FFDiag(E);
4738 return false;
4739 }
4740 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4741 }
4742
4743 bool found(APSInt &Value, QualType SubobjType) {
4744 if (!checkConst(SubobjType))
4745 return false;
4746
4747 if (!SubobjType->isIntegerType()) {
4748 // We don't support compound assignment on integer-cast-to-pointer
4749 // values.
4750 Info.FFDiag(E);
4751 return false;
4752 }
4753
4754 if (RHS.isInt()) {
4755 APSInt LHS =
4756 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4757 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4758 return false;
4759 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4760 return true;
4761 } else if (RHS.isFloat()) {
4762 const FPOptions FPO = E->getFPFeaturesInEffect(
4763 Info.Ctx.getLangOpts());
4764 APFloat FValue(0.0);
4765 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4766 PromotedLHSType, FValue) &&
4767 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4768 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4769 Value);
4770 }
4771
4772 Info.FFDiag(E);
4773 return false;
4774 }
4775 bool found(APFloat &Value, QualType SubobjType) {
4776 return checkConst(SubobjType) &&
4777 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4778 Value) &&
4779 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4780 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4781 }
4782 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4783 if (!checkConst(SubobjType))
4784 return false;
4785
4786 QualType PointeeType;
4787 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4788 PointeeType = PT->getPointeeType();
4789
4790 if (PointeeType.isNull() || !RHS.isInt() ||
4791 (Opcode != BO_Add && Opcode != BO_Sub)) {
4792 Info.FFDiag(E);
4793 return false;
4794 }
4795
4796 APSInt Offset = RHS.getInt();
4797 if (Opcode == BO_Sub)
4798 negateAsSigned(Offset);
4799
4800 LValue LVal;
4801 LVal.setFrom(Info.Ctx, Subobj);
4802 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4803 return false;
4804 LVal.moveInto(Subobj);
4805 return true;
4806 }
4807};
4808} // end anonymous namespace
4809
4810const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4811
4812/// Perform a compound assignment of LVal <op>= RVal.
4813static bool handleCompoundAssignment(EvalInfo &Info,
4815 const LValue &LVal, QualType LValType,
4816 QualType PromotedLValType,
4817 BinaryOperatorKind Opcode,
4818 const APValue &RVal) {
4819 if (LVal.Designator.Invalid)
4820 return false;
4821
4822 if (!Info.getLangOpts().CPlusPlus14) {
4823 Info.FFDiag(E);
4824 return false;
4825 }
4826
4827 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4828 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4829 RVal };
4830 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4831}
4832
4833namespace {
4834struct IncDecSubobjectHandler {
4835 EvalInfo &Info;
4836 const UnaryOperator *E;
4837 AccessKinds AccessKind;
4838 APValue *Old;
4839
4840 typedef bool result_type;
4841
4842 bool checkConst(QualType QT) {
4843 // Assigning to a const object has undefined behavior.
4844 if (QT.isConstQualified()) {
4845 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4846 return false;
4847 }
4848 return true;
4849 }
4850
4851 bool failed() { return false; }
4852 bool found(APValue &Subobj, QualType SubobjType) {
4853 // Stash the old value. Also clear Old, so we don't clobber it later
4854 // if we're post-incrementing a complex.
4855 if (Old) {
4856 *Old = Subobj;
4857 Old = nullptr;
4858 }
4859
4860 switch (Subobj.getKind()) {
4861 case APValue::Int:
4862 return found(Subobj.getInt(), SubobjType);
4863 case APValue::Float:
4864 return found(Subobj.getFloat(), SubobjType);
4866 return found(Subobj.getComplexIntReal(),
4867 SubobjType->castAs<ComplexType>()->getElementType()
4868 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4870 return found(Subobj.getComplexFloatReal(),
4871 SubobjType->castAs<ComplexType>()->getElementType()
4872 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4873 case APValue::LValue:
4874 return foundPointer(Subobj, SubobjType);
4875 default:
4876 // FIXME: can this happen?
4877 Info.FFDiag(E);
4878 return false;
4879 }
4880 }
4881 bool found(APSInt &Value, QualType SubobjType) {
4882 if (!checkConst(SubobjType))
4883 return false;
4884
4885 if (!SubobjType->isIntegerType()) {
4886 // We don't support increment / decrement on integer-cast-to-pointer
4887 // values.
4888 Info.FFDiag(E);
4889 return false;
4890 }
4891
4892 if (Old) *Old = APValue(Value);
4893
4894 // bool arithmetic promotes to int, and the conversion back to bool
4895 // doesn't reduce mod 2^n, so special-case it.
4896 if (SubobjType->isBooleanType()) {
4897 if (AccessKind == AK_Increment)
4898 Value = 1;
4899 else
4900 Value = !Value;
4901 return true;
4902 }
4903
4904 bool WasNegative = Value.isNegative();
4905 if (AccessKind == AK_Increment) {
4906 ++Value;
4907
4908 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4909 APSInt ActualValue(Value, /*IsUnsigned*/true);
4910 return HandleOverflow(Info, E, ActualValue, SubobjType);
4911 }
4912 } else {
4913 --Value;
4914
4915 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4916 unsigned BitWidth = Value.getBitWidth();
4917 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4918 ActualValue.setBit(BitWidth);
4919 return HandleOverflow(Info, E, ActualValue, SubobjType);
4920 }
4921 }
4922 return true;
4923 }
4924 bool found(APFloat &Value, QualType SubobjType) {
4925 if (!checkConst(SubobjType))
4926 return false;
4927
4928 if (Old) *Old = APValue(Value);
4929
4930 APFloat One(Value.getSemantics(), 1);
4931 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4932 APFloat::opStatus St;
4933 if (AccessKind == AK_Increment)
4934 St = Value.add(One, RM);
4935 else
4936 St = Value.subtract(One, RM);
4937 return checkFloatingPointResult(Info, E, St);
4938 }
4939 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4940 if (!checkConst(SubobjType))
4941 return false;
4942
4943 QualType PointeeType;
4944 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4945 PointeeType = PT->getPointeeType();
4946 else {
4947 Info.FFDiag(E);
4948 return false;
4949 }
4950
4951 LValue LVal;
4952 LVal.setFrom(Info.Ctx, Subobj);
4953 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4954 AccessKind == AK_Increment ? 1 : -1))
4955 return false;
4956 LVal.moveInto(Subobj);
4957 return true;
4958 }
4959};
4960} // end anonymous namespace
4961
4962/// Perform an increment or decrement on LVal.
4963static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4964 QualType LValType, bool IsIncrement, APValue *Old) {
4965 if (LVal.Designator.Invalid)
4966 return false;
4967
4968 if (!Info.getLangOpts().CPlusPlus14) {
4969 Info.FFDiag(E);
4970 return false;
4971 }
4972
4973 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4974 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4975 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4976 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4977}
4978
4979/// Build an lvalue for the object argument of a member function call.
4980static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4981 LValue &This) {
4982 if (Object->getType()->isPointerType() && Object->isPRValue())
4983 return EvaluatePointer(Object, This, Info);
4984
4985 if (Object->isGLValue())
4986 return EvaluateLValue(Object, This, Info);
4987
4988 if (Object->getType()->isLiteralType(Info.Ctx))
4989 return EvaluateTemporary(Object, This, Info);
4990
4991 if (Object->getType()->isRecordType() && Object->isPRValue())
4992 return EvaluateTemporary(Object, This, Info);
4993
4994 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4995 return false;
4996}
4997
4998/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4999/// lvalue referring to the result.
5000///
5001/// \param Info - Information about the ongoing evaluation.
5002/// \param LV - An lvalue referring to the base of the member pointer.
5003/// \param RHS - The member pointer expression.
5004/// \param IncludeMember - Specifies whether the member itself is included in
5005/// the resulting LValue subobject designator. This is not possible when
5006/// creating a bound member function.
5007/// \return The field or method declaration to which the member pointer refers,
5008/// or 0 if evaluation fails.
5009static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5010 QualType LVType,
5011 LValue &LV,
5012 const Expr *RHS,
5013 bool IncludeMember = true) {
5014 MemberPtr MemPtr;
5015 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5016 return nullptr;
5017
5018 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5019 // member value, the behavior is undefined.
5020 if (!MemPtr.getDecl()) {
5021 // FIXME: Specific diagnostic.
5022 Info.FFDiag(RHS);
5023 return nullptr;
5024 }
5025
5026 if (MemPtr.isDerivedMember()) {
5027 // This is a member of some derived class. Truncate LV appropriately.
5028 // The end of the derived-to-base path for the base object must match the
5029 // derived-to-base path for the member pointer.
5030 // C++23 [expr.mptr.oper]p4:
5031 // If the result of E1 is an object [...] whose most derived object does
5032 // not contain the member to which E2 refers, the behavior is undefined.
5033 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5034 LV.Designator.Entries.size()) {
5035 Info.FFDiag(RHS);
5036 return nullptr;
5037 }
5038 unsigned PathLengthToMember =
5039 LV.Designator.Entries.size() - MemPtr.Path.size();
5040 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5041 const CXXRecordDecl *LVDecl = getAsBaseClass(
5042 LV.Designator.Entries[PathLengthToMember + I]);
5043 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5044 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5045 Info.FFDiag(RHS);
5046 return nullptr;
5047 }
5048 }
5049 // MemPtr.Path only contains the base classes of the class directly
5050 // containing the member E2. It is still necessary to check that the class
5051 // directly containing the member E2 lies on the derived-to-base path of E1
5052 // to avoid incorrectly permitting member pointer access into a sibling
5053 // class of the class containing the member E2. If this class would
5054 // correspond to the most-derived class of E1, it either isn't contained in
5055 // LV.Designator.Entries or the corresponding entry refers to an array
5056 // element instead. Therefore get the most derived class directly in this
5057 // case. Otherwise the previous entry should correpond to this class.
5058 const CXXRecordDecl *LastLVDecl =
5059 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5060 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5061 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5062 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5063 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5064 Info.FFDiag(RHS);
5065 return nullptr;
5066 }
5067
5068 // Truncate the lvalue to the appropriate derived class.
5069 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5070 PathLengthToMember))
5071 return nullptr;
5072 } else if (!MemPtr.Path.empty()) {
5073 // Extend the LValue path with the member pointer's path.
5074 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5075 MemPtr.Path.size() + IncludeMember);
5076
5077 // Walk down to the appropriate base class.
5078 if (const PointerType *PT = LVType->getAs<PointerType>())
5079 LVType = PT->getPointeeType();
5080 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5081 assert(RD && "member pointer access on non-class-type expression");
5082 // The first class in the path is that of the lvalue.
5083 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5084 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5085 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5086 return nullptr;
5087 RD = Base;
5088 }
5089 // Finally cast to the class containing the member.
5090 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5091 MemPtr.getContainingRecord()))
5092 return nullptr;
5093 }
5094
5095 // Add the member. Note that we cannot build bound member functions here.
5096 if (IncludeMember) {
5097 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5098 if (!HandleLValueMember(Info, RHS, LV, FD))
5099 return nullptr;
5100 } else if (const IndirectFieldDecl *IFD =
5101 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5102 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5103 return nullptr;
5104 } else {
5105 llvm_unreachable("can't construct reference to bound member function");
5106 }
5107 }
5108
5109 return MemPtr.getDecl();
5110}
5111
5112static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5113 const BinaryOperator *BO,
5114 LValue &LV,
5115 bool IncludeMember = true) {
5116 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5117
5118 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5119 if (Info.noteFailure()) {
5120 MemberPtr MemPtr;
5121 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5122 }
5123 return nullptr;
5124 }
5125
5126 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5127 BO->getRHS(), IncludeMember);
5128}
5129
5130/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5131/// the provided lvalue, which currently refers to the base object.
5132static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5133 LValue &Result) {
5134 SubobjectDesignator &D = Result.Designator;
5135 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5136 return false;
5137
5138 QualType TargetQT = E->getType();
5139 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5140 TargetQT = PT->getPointeeType();
5141
5142 // Check this cast lands within the final derived-to-base subobject path.
5143 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5144 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5145 << D.MostDerivedType << TargetQT;
5146 return false;
5147 }
5148
5149 // Check the type of the final cast. We don't need to check the path,
5150 // since a cast can only be formed if the path is unique.
5151 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5152 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5153 const CXXRecordDecl *FinalType;
5154 if (NewEntriesSize == D.MostDerivedPathLength)
5155 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5156 else
5157 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5158 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5159 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5160 << D.MostDerivedType << TargetQT;
5161 return false;
5162 }
5163
5164 // Truncate the lvalue to the appropriate derived class.
5165 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5166}
5167
5168/// Get the value to use for a default-initialized object of type T.
5169/// Return false if it encounters something invalid.
5171 bool Success = true;
5172
5173 // If there is already a value present don't overwrite it.
5174 if (!Result.isAbsent())
5175 return true;
5176
5177 if (auto *RD = T->getAsCXXRecordDecl()) {
5178 if (RD->isInvalidDecl()) {
5179 Result = APValue();
5180 return false;
5181 }
5182 if (RD->isUnion()) {
5183 Result = APValue((const FieldDecl *)nullptr);
5184 return true;
5185 }
5186 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5187 std::distance(RD->field_begin(), RD->field_end()));
5188
5189 unsigned Index = 0;
5190 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5191 End = RD->bases_end();
5192 I != End; ++I, ++Index)
5193 Success &=
5194 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5195
5196 for (const auto *I : RD->fields()) {
5197 if (I->isUnnamedBitField())
5198 continue;
5200 I->getType(), Result.getStructField(I->getFieldIndex()));
5201 }
5202 return Success;
5203 }
5204
5205 if (auto *AT =
5206 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5207 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5208 if (Result.hasArrayFiller())
5209 Success &=
5210 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5211
5212 return Success;
5213 }
5214
5215 Result = APValue::IndeterminateValue();
5216 return true;
5217}
5218
5219namespace {
5220enum EvalStmtResult {
5221 /// Evaluation failed.
5222 ESR_Failed,
5223 /// Hit a 'return' statement.
5224 ESR_Returned,
5225 /// Evaluation succeeded.
5226 ESR_Succeeded,
5227 /// Hit a 'continue' statement.
5228 ESR_Continue,
5229 /// Hit a 'break' statement.
5230 ESR_Break,
5231 /// Still scanning for 'case' or 'default' statement.
5232 ESR_CaseNotFound
5233};
5234}
5235/// Evaluates the initializer of a reference.
5236static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5237 const ValueDecl *D,
5238 const Expr *Init, LValue &Result,
5239 APValue &Val) {
5240 assert(Init->isGLValue() && D->getType()->isReferenceType());
5241 // A reference is an lvalue.
5242 if (!EvaluateLValue(Init, Result, Info))
5243 return false;
5244 // [C++26][decl.ref]
5245 // The object designated by such a glvalue can be outside its lifetime
5246 // Because a null pointer value or a pointer past the end of an object
5247 // does not point to an object, a reference in a well-defined program cannot
5248 // refer to such things;
5249 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5250 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5251 return false;
5252 }
5253
5254 // Save the result.
5255 Result.moveInto(Val);
5256 return true;
5257}
5258
5259static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5260 if (VD->isInvalidDecl())
5261 return false;
5262 // We don't need to evaluate the initializer for a static local.
5263 if (!VD->hasLocalStorage())
5264 return true;
5265
5266 LValue Result;
5267 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5268 ScopeKind::Block, Result);
5269
5270 const Expr *InitE = VD->getInit();
5271 if (!InitE) {
5272 if (VD->getType()->isDependentType())
5273 return Info.noteSideEffect();
5274 return handleDefaultInitValue(VD->getType(), Val);
5275 }
5276 if (InitE->isValueDependent())
5277 return false;
5278
5279 // For references to objects, check they do not designate a one-past-the-end
5280 // object.
5281 if (VD->getType()->isReferenceType()) {
5282 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5283 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5284 // Wipe out any partially-computed value, to allow tracking that this
5285 // evaluation failed.
5286 Val = APValue();
5287 return false;
5288 }
5289
5290 return true;
5291}
5292
5293static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5294 const DecompositionDecl *DD);
5295
5296static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5297 bool EvaluateConditionDecl = false) {
5298 bool OK = true;
5299 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5300 OK &= EvaluateVarDecl(Info, VD);
5301
5302 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5303 EvaluateConditionDecl && DD)
5304 OK &= EvaluateDecompositionDeclInit(Info, DD);
5305
5306 return OK;
5307}
5308
5309static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5310 const DecompositionDecl *DD) {
5311 bool OK = true;
5312 for (auto *BD : DD->flat_bindings())
5313 if (auto *VD = BD->getHoldingVar())
5314 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5315
5316 return OK;
5317}
5318
5319static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5320 const VarDecl *VD) {
5321 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5322 if (!EvaluateDecompositionDeclInit(Info, DD))
5323 return false;
5324 }
5325 return true;
5326}
5327
5328static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5329 assert(E->isValueDependent());
5330 if (Info.noteSideEffect())
5331 return true;
5332 assert(E->containsErrors() && "valid value-dependent expression should never "
5333 "reach invalid code path.");
5334 return false;
5335}
5336
5337/// Evaluate a condition (either a variable declaration or an expression).
5338static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5339 const Expr *Cond, bool &Result) {
5340 if (Cond->isValueDependent())
5341 return false;
5342 FullExpressionRAII Scope(Info);
5343 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5344 return false;
5345 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5346 return false;
5347 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5348 return false;
5349 return Scope.destroy();
5350}
5351
5352namespace {
5353/// A location where the result (returned value) of evaluating a
5354/// statement should be stored.
5355struct StmtResult {
5356 /// The APValue that should be filled in with the returned value.
5357 APValue &Value;
5358 /// The location containing the result, if any (used to support RVO).
5359 const LValue *Slot;
5360};
5361
5362struct TempVersionRAII {
5363 CallStackFrame &Frame;
5364
5365 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5366 Frame.pushTempVersion();
5367 }
5368
5369 ~TempVersionRAII() {
5370 Frame.popTempVersion();
5371 }
5372};
5373
5374}
5375
5376static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5377 const Stmt *S,
5378 const SwitchCase *SC = nullptr);
5379
5380/// Evaluate the body of a loop, and translate the result as appropriate.
5381static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5382 const Stmt *Body,
5383 const SwitchCase *Case = nullptr) {
5384 BlockScopeRAII Scope(Info);
5385
5386 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5387 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5388 ESR = ESR_Failed;
5389
5390 switch (ESR) {
5391 case ESR_Break:
5392 return ESR_Succeeded;
5393 case ESR_Succeeded:
5394 case ESR_Continue:
5395 return ESR_Continue;
5396 case ESR_Failed:
5397 case ESR_Returned:
5398 case ESR_CaseNotFound:
5399 return ESR;
5400 }
5401 llvm_unreachable("Invalid EvalStmtResult!");
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
5468 switch (ESR) {
5469 case ESR_Break:
5470 return ESR_Succeeded;
5471 case ESR_Succeeded:
5472 case ESR_Continue:
5473 case ESR_Failed:
5474 case ESR_Returned:
5475 return ESR;
5476 case ESR_CaseNotFound:
5477 // This can only happen if the switch case is nested within a statement
5478 // expression. We have no intention of supporting that.
5479 Info.FFDiag(Found->getBeginLoc(),
5480 diag::note_constexpr_stmt_expr_unsupported);
5481 return ESR_Failed;
5482 }
5483 llvm_unreachable("Invalid EvalStmtResult!");
5484}
5485
5486static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5487 // An expression E is a core constant expression unless the evaluation of E
5488 // would evaluate one of the following: [C++23] - a control flow that passes
5489 // through a declaration of a variable with static or thread storage duration
5490 // unless that variable is usable in constant expressions.
5491 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5492 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5493 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5494 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5495 return false;
5496 }
5497 return true;
5498}
5499
5500// Evaluate a statement.
5501static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5502 const Stmt *S, const SwitchCase *Case) {
5503 if (!Info.nextStep(S))
5504 return ESR_Failed;
5505
5506 // If we're hunting down a 'case' or 'default' label, recurse through
5507 // substatements until we hit the label.
5508 if (Case) {
5509 switch (S->getStmtClass()) {
5510 case Stmt::CompoundStmtClass:
5511 // FIXME: Precompute which substatement of a compound statement we
5512 // would jump to, and go straight there rather than performing a
5513 // linear scan each time.
5514 case Stmt::LabelStmtClass:
5515 case Stmt::AttributedStmtClass:
5516 case Stmt::DoStmtClass:
5517 break;
5518
5519 case Stmt::CaseStmtClass:
5520 case Stmt::DefaultStmtClass:
5521 if (Case == S)
5522 Case = nullptr;
5523 break;
5524
5525 case Stmt::IfStmtClass: {
5526 // FIXME: Precompute which side of an 'if' we would jump to, and go
5527 // straight there rather than scanning both sides.
5528 const IfStmt *IS = cast<IfStmt>(S);
5529
5530 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5531 // preceded by our switch label.
5532 BlockScopeRAII Scope(Info);
5533
5534 // Step into the init statement in case it brings an (uninitialized)
5535 // variable into scope.
5536 if (const Stmt *Init = IS->getInit()) {
5537 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5538 if (ESR != ESR_CaseNotFound) {
5539 assert(ESR != ESR_Succeeded);
5540 return ESR;
5541 }
5542 }
5543
5544 // Condition variable must be initialized if it exists.
5545 // FIXME: We can skip evaluating the body if there's a condition
5546 // variable, as there can't be any case labels within it.
5547 // (The same is true for 'for' statements.)
5548
5549 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5550 if (ESR == ESR_Failed)
5551 return ESR;
5552 if (ESR != ESR_CaseNotFound)
5553 return Scope.destroy() ? ESR : ESR_Failed;
5554 if (!IS->getElse())
5555 return ESR_CaseNotFound;
5556
5557 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5558 if (ESR == ESR_Failed)
5559 return ESR;
5560 if (ESR != ESR_CaseNotFound)
5561 return Scope.destroy() ? ESR : ESR_Failed;
5562 return ESR_CaseNotFound;
5563 }
5564
5565 case Stmt::WhileStmtClass: {
5566 EvalStmtResult ESR =
5567 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5568 if (ESR != ESR_Continue)
5569 return ESR;
5570 break;
5571 }
5572
5573 case Stmt::ForStmtClass: {
5574 const ForStmt *FS = cast<ForStmt>(S);
5575 BlockScopeRAII Scope(Info);
5576
5577 // Step into the init statement in case it brings an (uninitialized)
5578 // variable into scope.
5579 if (const Stmt *Init = FS->getInit()) {
5580 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5581 if (ESR != ESR_CaseNotFound) {
5582 assert(ESR != ESR_Succeeded);
5583 return ESR;
5584 }
5585 }
5586
5587 EvalStmtResult ESR =
5588 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5589 if (ESR != ESR_Continue)
5590 return ESR;
5591 if (const auto *Inc = FS->getInc()) {
5592 if (Inc->isValueDependent()) {
5593 if (!EvaluateDependentExpr(Inc, Info))
5594 return ESR_Failed;
5595 } else {
5596 FullExpressionRAII IncScope(Info);
5597 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5598 return ESR_Failed;
5599 }
5600 }
5601 break;
5602 }
5603
5604 case Stmt::DeclStmtClass: {
5605 // Start the lifetime of any uninitialized variables we encounter. They
5606 // might be used by the selected branch of the switch.
5607 const DeclStmt *DS = cast<DeclStmt>(S);
5608 for (const auto *D : DS->decls()) {
5609 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5610 if (!CheckLocalVariableDeclaration(Info, VD))
5611 return ESR_Failed;
5612 if (VD->hasLocalStorage() && !VD->getInit())
5613 if (!EvaluateVarDecl(Info, VD))
5614 return ESR_Failed;
5615 // FIXME: If the variable has initialization that can't be jumped
5616 // over, bail out of any immediately-surrounding compound-statement
5617 // too. There can't be any case labels here.
5618 }
5619 }
5620 return ESR_CaseNotFound;
5621 }
5622
5623 default:
5624 return ESR_CaseNotFound;
5625 }
5626 }
5627
5628 switch (S->getStmtClass()) {
5629 default:
5630 if (const Expr *E = dyn_cast<Expr>(S)) {
5631 if (E->isValueDependent()) {
5632 if (!EvaluateDependentExpr(E, Info))
5633 return ESR_Failed;
5634 } else {
5635 // Don't bother evaluating beyond an expression-statement which couldn't
5636 // be evaluated.
5637 // FIXME: Do we need the FullExpressionRAII object here?
5638 // VisitExprWithCleanups should create one when necessary.
5639 FullExpressionRAII Scope(Info);
5640 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5641 return ESR_Failed;
5642 }
5643 return ESR_Succeeded;
5644 }
5645
5646 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5647 return ESR_Failed;
5648
5649 case Stmt::NullStmtClass:
5650 return ESR_Succeeded;
5651
5652 case Stmt::DeclStmtClass: {
5653 const DeclStmt *DS = cast<DeclStmt>(S);
5654 for (const auto *D : DS->decls()) {
5655 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5656 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5657 return ESR_Failed;
5658 // Each declaration initialization is its own full-expression.
5659 FullExpressionRAII Scope(Info);
5660 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5661 !Info.noteFailure())
5662 return ESR_Failed;
5663 if (!Scope.destroy())
5664 return ESR_Failed;
5665 }
5666 return ESR_Succeeded;
5667 }
5668
5669 case Stmt::ReturnStmtClass: {
5670 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5671 FullExpressionRAII Scope(Info);
5672 if (RetExpr && RetExpr->isValueDependent()) {
5673 EvaluateDependentExpr(RetExpr, Info);
5674 // We know we returned, but we don't know what the value is.
5675 return ESR_Failed;
5676 }
5677 if (RetExpr &&
5678 !(Result.Slot
5679 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5680 : Evaluate(Result.Value, Info, RetExpr)))
5681 return ESR_Failed;
5682 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5683 }
5684
5685 case Stmt::CompoundStmtClass: {
5686 BlockScopeRAII Scope(Info);
5687
5688 const CompoundStmt *CS = cast<CompoundStmt>(S);
5689 for (const auto *BI : CS->body()) {
5690 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5691 if (ESR == ESR_Succeeded)
5692 Case = nullptr;
5693 else if (ESR != ESR_CaseNotFound) {
5694 if (ESR != ESR_Failed && !Scope.destroy())
5695 return ESR_Failed;
5696 return ESR;
5697 }
5698 }
5699 if (Case)
5700 return ESR_CaseNotFound;
5701 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5702 }
5703
5704 case Stmt::IfStmtClass: {
5705 const IfStmt *IS = cast<IfStmt>(S);
5706
5707 // Evaluate the condition, as either a var decl or as an expression.
5708 BlockScopeRAII Scope(Info);
5709 if (const Stmt *Init = IS->getInit()) {
5710 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5711 if (ESR != ESR_Succeeded) {
5712 if (ESR != ESR_Failed && !Scope.destroy())
5713 return ESR_Failed;
5714 return ESR;
5715 }
5716 }
5717 bool Cond;
5718 if (IS->isConsteval()) {
5719 Cond = IS->isNonNegatedConsteval();
5720 // If we are not in a constant context, if consteval should not evaluate
5721 // to true.
5722 if (!Info.InConstantContext)
5723 Cond = !Cond;
5724 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5725 Cond))
5726 return ESR_Failed;
5727
5728 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5729 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5730 if (ESR != ESR_Succeeded) {
5731 if (ESR != ESR_Failed && !Scope.destroy())
5732 return ESR_Failed;
5733 return ESR;
5734 }
5735 }
5736 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5737 }
5738
5739 case Stmt::WhileStmtClass: {
5740 const WhileStmt *WS = cast<WhileStmt>(S);
5741 while (true) {
5742 BlockScopeRAII Scope(Info);
5743 bool Continue;
5744 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5745 Continue))
5746 return ESR_Failed;
5747 if (!Continue)
5748 break;
5749
5750 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5751 if (ESR != ESR_Continue) {
5752 if (ESR != ESR_Failed && !Scope.destroy())
5753 return ESR_Failed;
5754 return ESR;
5755 }
5756 if (!Scope.destroy())
5757 return ESR_Failed;
5758 }
5759 return ESR_Succeeded;
5760 }
5761
5762 case Stmt::DoStmtClass: {
5763 const DoStmt *DS = cast<DoStmt>(S);
5764 bool Continue;
5765 do {
5766 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5767 if (ESR != ESR_Continue)
5768 return ESR;
5769 Case = nullptr;
5770
5771 if (DS->getCond()->isValueDependent()) {
5772 EvaluateDependentExpr(DS->getCond(), Info);
5773 // Bailout as we don't know whether to keep going or terminate the loop.
5774 return ESR_Failed;
5775 }
5776 FullExpressionRAII CondScope(Info);
5777 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5778 !CondScope.destroy())
5779 return ESR_Failed;
5780 } while (Continue);
5781 return ESR_Succeeded;
5782 }
5783
5784 case Stmt::ForStmtClass: {
5785 const ForStmt *FS = cast<ForStmt>(S);
5786 BlockScopeRAII ForScope(Info);
5787 if (FS->getInit()) {
5788 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5789 if (ESR != ESR_Succeeded) {
5790 if (ESR != ESR_Failed && !ForScope.destroy())
5791 return ESR_Failed;
5792 return ESR;
5793 }
5794 }
5795 while (true) {
5796 BlockScopeRAII IterScope(Info);
5797 bool Continue = true;
5798 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5799 FS->getCond(), Continue))
5800 return ESR_Failed;
5801
5802 if (!Continue) {
5803 if (!IterScope.destroy())
5804 return ESR_Failed;
5805 break;
5806 }
5807
5808 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5809 if (ESR != ESR_Continue) {
5810 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5811 return ESR_Failed;
5812 return ESR;
5813 }
5814
5815 if (const auto *Inc = FS->getInc()) {
5816 if (Inc->isValueDependent()) {
5817 if (!EvaluateDependentExpr(Inc, Info))
5818 return ESR_Failed;
5819 } else {
5820 FullExpressionRAII IncScope(Info);
5821 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5822 return ESR_Failed;
5823 }
5824 }
5825
5826 if (!IterScope.destroy())
5827 return ESR_Failed;
5828 }
5829 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5830 }
5831
5832 case Stmt::CXXForRangeStmtClass: {
5833 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5834 BlockScopeRAII Scope(Info);
5835
5836 // Evaluate the init-statement if present.
5837 if (FS->getInit()) {
5838 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5839 if (ESR != ESR_Succeeded) {
5840 if (ESR != ESR_Failed && !Scope.destroy())
5841 return ESR_Failed;
5842 return ESR;
5843 }
5844 }
5845
5846 // Initialize the __range variable.
5847 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5848 if (ESR != ESR_Succeeded) {
5849 if (ESR != ESR_Failed && !Scope.destroy())
5850 return ESR_Failed;
5851 return ESR;
5852 }
5853
5854 // In error-recovery cases it's possible to get here even if we failed to
5855 // synthesize the __begin and __end variables.
5856 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5857 return ESR_Failed;
5858
5859 // Create the __begin and __end iterators.
5860 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5861 if (ESR != ESR_Succeeded) {
5862 if (ESR != ESR_Failed && !Scope.destroy())
5863 return ESR_Failed;
5864 return ESR;
5865 }
5866 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5867 if (ESR != ESR_Succeeded) {
5868 if (ESR != ESR_Failed && !Scope.destroy())
5869 return ESR_Failed;
5870 return ESR;
5871 }
5872
5873 while (true) {
5874 // Condition: __begin != __end.
5875 {
5876 if (FS->getCond()->isValueDependent()) {
5877 EvaluateDependentExpr(FS->getCond(), Info);
5878 // We don't know whether to keep going or terminate the loop.
5879 return ESR_Failed;
5880 }
5881 bool Continue = true;
5882 FullExpressionRAII CondExpr(Info);
5883 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5884 return ESR_Failed;
5885 if (!Continue)
5886 break;
5887 }
5888
5889 // User's variable declaration, initialized by *__begin.
5890 BlockScopeRAII InnerScope(Info);
5891 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5892 if (ESR != ESR_Succeeded) {
5893 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5894 return ESR_Failed;
5895 return ESR;
5896 }
5897
5898 // Loop body.
5899 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5900 if (ESR != ESR_Continue) {
5901 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5902 return ESR_Failed;
5903 return ESR;
5904 }
5905 if (FS->getInc()->isValueDependent()) {
5906 if (!EvaluateDependentExpr(FS->getInc(), Info))
5907 return ESR_Failed;
5908 } else {
5909 // Increment: ++__begin
5910 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5911 return ESR_Failed;
5912 }
5913
5914 if (!InnerScope.destroy())
5915 return ESR_Failed;
5916 }
5917
5918 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5919 }
5920
5921 case Stmt::SwitchStmtClass:
5922 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5923
5924 case Stmt::ContinueStmtClass:
5925 return ESR_Continue;
5926
5927 case Stmt::BreakStmtClass:
5928 return ESR_Break;
5929
5930 case Stmt::LabelStmtClass:
5931 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5932
5933 case Stmt::AttributedStmtClass: {
5934 const auto *AS = cast<AttributedStmt>(S);
5935 const auto *SS = AS->getSubStmt();
5936 MSConstexprContextRAII ConstexprContext(
5937 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5938 isa<ReturnStmt>(SS));
5939
5940 auto LO = Info.getASTContext().getLangOpts();
5941 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5942 for (auto *Attr : AS->getAttrs()) {
5943 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5944 if (!AA)
5945 continue;
5946
5947 auto *Assumption = AA->getAssumption();
5948 if (Assumption->isValueDependent())
5949 return ESR_Failed;
5950
5951 if (Assumption->HasSideEffects(Info.getASTContext()))
5952 continue;
5953
5954 bool Value;
5955 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5956 return ESR_Failed;
5957 if (!Value) {
5958 Info.CCEDiag(Assumption->getExprLoc(),
5959 diag::note_constexpr_assumption_failed);
5960 return ESR_Failed;
5961 }
5962 }
5963 }
5964
5965 return EvaluateStmt(Result, Info, SS, Case);
5966 }
5967
5968 case Stmt::CaseStmtClass:
5969 case Stmt::DefaultStmtClass:
5970 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5971 case Stmt::CXXTryStmtClass:
5972 // Evaluate try blocks by evaluating all sub statements.
5973 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5974 }
5975}
5976
5977/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5978/// default constructor. If so, we'll fold it whether or not it's marked as
5979/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5980/// so we need special handling.
5982 const CXXConstructorDecl *CD,
5983 bool IsValueInitialization) {
5984 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5985 return false;
5986
5987 // Value-initialization does not call a trivial default constructor, so such a
5988 // call is a core constant expression whether or not the constructor is
5989 // constexpr.
5990 if (!CD->isConstexpr() && !IsValueInitialization) {
5991 if (Info.getLangOpts().CPlusPlus11) {
5992 // FIXME: If DiagDecl is an implicitly-declared special member function,
5993 // we should be much more explicit about why it's not constexpr.
5994 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5995 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5996 Info.Note(CD->getLocation(), diag::note_declared_at);
5997 } else {
5998 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5999 }
6000 }
6001 return true;
6002}
6003
6004/// CheckConstexprFunction - Check that a function can be called in a constant
6005/// expression.
6006static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6008 const FunctionDecl *Definition,
6009 const Stmt *Body) {
6010 // Potential constant expressions can contain calls to declared, but not yet
6011 // defined, constexpr functions.
6012 if (Info.checkingPotentialConstantExpression() && !Definition &&
6013 Declaration->isConstexpr())
6014 return false;
6015
6016 // Bail out if the function declaration itself is invalid. We will
6017 // have produced a relevant diagnostic while parsing it, so just
6018 // note the problematic sub-expression.
6019 if (Declaration->isInvalidDecl()) {
6020 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6021 return false;
6022 }
6023
6024 // DR1872: An instantiated virtual constexpr function can't be called in a
6025 // constant expression (prior to C++20). We can still constant-fold such a
6026 // call.
6027 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6028 cast<CXXMethodDecl>(Declaration)->isVirtual())
6029 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6030
6031 if (Definition && Definition->isInvalidDecl()) {
6032 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6033 return false;
6034 }
6035
6036 // Can we evaluate this function call?
6037 if (Definition && Body &&
6038 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6039 Definition->hasAttr<MSConstexprAttr>())))
6040 return true;
6041
6042 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6043 // Special note for the assert() macro, as the normal error message falsely
6044 // implies we cannot use an assertion during constant evaluation.
6045 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6046 // FIXME: Instead of checking for an implementation-defined function,
6047 // check and evaluate the assert() macro.
6048 StringRef Name = DiagDecl->getName();
6049 bool AssertFailed =
6050 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6051 if (AssertFailed) {
6052 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6053 return false;
6054 }
6055 }
6056
6057 if (Info.getLangOpts().CPlusPlus11) {
6058 // If this function is not constexpr because it is an inherited
6059 // non-constexpr constructor, diagnose that directly.
6060 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6061 if (CD && CD->isInheritingConstructor()) {
6062 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6063 if (!Inherited->isConstexpr())
6064 DiagDecl = CD = Inherited;
6065 }
6066
6067 // FIXME: If DiagDecl is an implicitly-declared special member function
6068 // or an inheriting constructor, we should be much more explicit about why
6069 // it's not constexpr.
6070 if (CD && CD->isInheritingConstructor())
6071 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6072 << CD->getInheritedConstructor().getConstructor()->getParent();
6073 else
6074 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6075 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6076 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6077 } else {
6078 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6079 }
6080 return false;
6081}
6082
6083namespace {
6084struct CheckDynamicTypeHandler {
6085 AccessKinds AccessKind;
6086 typedef bool result_type;
6087 bool failed() { return false; }
6088 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6089 bool found(APSInt &Value, QualType SubobjType) { return true; }
6090 bool found(APFloat &Value, QualType SubobjType) { return true; }
6091};
6092} // end anonymous namespace
6093
6094/// Check that we can access the notional vptr of an object / determine its
6095/// dynamic type.
6096static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6097 AccessKinds AK, bool Polymorphic) {
6098 if (This.Designator.Invalid)
6099 return false;
6100
6101 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6102
6103 if (!Obj)
6104 return false;
6105
6106 if (!Obj.Value) {
6107 // The object is not usable in constant expressions, so we can't inspect
6108 // its value to see if it's in-lifetime or what the active union members
6109 // are. We can still check for a one-past-the-end lvalue.
6110 if (This.Designator.isOnePastTheEnd() ||
6111 This.Designator.isMostDerivedAnUnsizedArray()) {
6112 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6113 ? diag::note_constexpr_access_past_end
6114 : diag::note_constexpr_access_unsized_array)
6115 << AK;
6116 return false;
6117 } else if (Polymorphic) {
6118 // Conservatively refuse to perform a polymorphic operation if we would
6119 // not be able to read a notional 'vptr' value.
6120 APValue Val;
6121 This.moveInto(Val);
6122 QualType StarThisType =
6123 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6124 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6125 << AK << Val.getAsString(Info.Ctx, StarThisType);
6126 return false;
6127 }
6128 return true;
6129 }
6130
6131 CheckDynamicTypeHandler Handler{AK};
6132 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6133}
6134
6135/// Check that the pointee of the 'this' pointer in a member function call is
6136/// either within its lifetime or in its period of construction or destruction.
6137static bool
6139 const LValue &This,
6140 const CXXMethodDecl *NamedMember) {
6141 return checkDynamicType(
6142 Info, E, This,
6143 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6144}
6145
6147 /// The dynamic class type of the object.
6149 /// The corresponding path length in the lvalue.
6150 unsigned PathLength;
6151};
6152
6153static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6154 unsigned PathLength) {
6155 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6156 Designator.Entries.size() && "invalid path length");
6157 return (PathLength == Designator.MostDerivedPathLength)
6158 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6159 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6160}
6161
6162/// Determine the dynamic type of an object.
6163static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6164 const Expr *E,
6165 LValue &This,
6166 AccessKinds AK) {
6167 // If we don't have an lvalue denoting an object of class type, there is no
6168 // meaningful dynamic type. (We consider objects of non-class type to have no
6169 // dynamic type.)
6170 if (!checkDynamicType(Info, E, This, AK,
6171 AK != AK_TypeId || This.AllowConstexprUnknown))
6172 return std::nullopt;
6173
6174 if (This.Designator.Invalid)
6175 return std::nullopt;
6176
6177 // Refuse to compute a dynamic type in the presence of virtual bases. This
6178 // shouldn't happen other than in constant-folding situations, since literal
6179 // types can't have virtual bases.
6180 //
6181 // Note that consumers of DynamicType assume that the type has no virtual
6182 // bases, and will need modifications if this restriction is relaxed.
6183 const CXXRecordDecl *Class =
6184 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6185 if (!Class || Class->getNumVBases()) {
6186 Info.FFDiag(E);
6187 return std::nullopt;
6188 }
6189
6190 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6191 // binary search here instead. But the overwhelmingly common case is that
6192 // we're not in the middle of a constructor, so it probably doesn't matter
6193 // in practice.
6194 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6195 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6196 PathLength <= Path.size(); ++PathLength) {
6197 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6198 Path.slice(0, PathLength))) {
6199 case ConstructionPhase::Bases:
6200 case ConstructionPhase::DestroyingBases:
6201 // We're constructing or destroying a base class. This is not the dynamic
6202 // type.
6203 break;
6204
6205 case ConstructionPhase::None:
6206 case ConstructionPhase::AfterBases:
6207 case ConstructionPhase::AfterFields:
6208 case ConstructionPhase::Destroying:
6209 // We've finished constructing the base classes and not yet started
6210 // destroying them again, so this is the dynamic type.
6211 return DynamicType{getBaseClassType(This.Designator, PathLength),
6212 PathLength};
6213 }
6214 }
6215
6216 // CWG issue 1517: we're constructing a base class of the object described by
6217 // 'This', so that object has not yet begun its period of construction and
6218 // any polymorphic operation on it results in undefined behavior.
6219 Info.FFDiag(E);
6220 return std::nullopt;
6221}
6222
6223/// Perform virtual dispatch.
6225 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6226 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6227 std::optional<DynamicType> DynType = ComputeDynamicType(
6228 Info, E, This,
6229 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6230 if (!DynType)
6231 return nullptr;
6232
6233 // Find the final overrider. It must be declared in one of the classes on the
6234 // path from the dynamic type to the static type.
6235 // FIXME: If we ever allow literal types to have virtual base classes, that
6236 // won't be true.
6237 const CXXMethodDecl *Callee = Found;
6238 unsigned PathLength = DynType->PathLength;
6239 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6240 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6241 const CXXMethodDecl *Overrider =
6242 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6243 if (Overrider) {
6244 Callee = Overrider;
6245 break;
6246 }
6247 }
6248
6249 // C++2a [class.abstract]p6:
6250 // the effect of making a virtual call to a pure virtual function [...] is
6251 // undefined
6252 if (Callee->isPureVirtual()) {
6253 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6254 Info.Note(Callee->getLocation(), diag::note_declared_at);
6255 return nullptr;
6256 }
6257
6258 // If necessary, walk the rest of the path to determine the sequence of
6259 // covariant adjustment steps to apply.
6260 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6261 Found->getReturnType())) {
6262 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6263 for (unsigned CovariantPathLength = PathLength + 1;
6264 CovariantPathLength != This.Designator.Entries.size();
6265 ++CovariantPathLength) {
6266 const CXXRecordDecl *NextClass =
6267 getBaseClassType(This.Designator, CovariantPathLength);
6268 const CXXMethodDecl *Next =
6269 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6270 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6271 Next->getReturnType(), CovariantAdjustmentPath.back()))
6272 CovariantAdjustmentPath.push_back(Next->getReturnType());
6273 }
6274 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6275 CovariantAdjustmentPath.back()))
6276 CovariantAdjustmentPath.push_back(Found->getReturnType());
6277 }
6278
6279 // Perform 'this' adjustment.
6280 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6281 return nullptr;
6282
6283 return Callee;
6284}
6285
6286/// Perform the adjustment from a value returned by a virtual function to
6287/// a value of the statically expected type, which may be a pointer or
6288/// reference to a base class of the returned type.
6289static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6290 APValue &Result,
6292 assert(Result.isLValue() &&
6293 "unexpected kind of APValue for covariant return");
6294 if (Result.isNullPointer())
6295 return true;
6296
6297 LValue LVal;
6298 LVal.setFrom(Info.Ctx, Result);
6299
6300 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6301 for (unsigned I = 1; I != Path.size(); ++I) {
6302 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6303 assert(OldClass && NewClass && "unexpected kind of covariant return");
6304 if (OldClass != NewClass &&
6305 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6306 return false;
6307 OldClass = NewClass;
6308 }
6309
6310 LVal.moveInto(Result);
6311 return true;
6312}
6313
6314/// Determine whether \p Base, which is known to be a direct base class of
6315/// \p Derived, is a public base class.
6316static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6317 const CXXRecordDecl *Base) {
6318 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6319 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6320 if (BaseClass && declaresSameEntity(BaseClass, Base))
6321 return BaseSpec.getAccessSpecifier() == AS_public;
6322 }
6323 llvm_unreachable("Base is not a direct base of Derived");
6324}
6325
6326/// Apply the given dynamic cast operation on the provided lvalue.
6327///
6328/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6329/// to find a suitable target subobject.
6330static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6331 LValue &Ptr) {
6332 // We can't do anything with a non-symbolic pointer value.
6333 SubobjectDesignator &D = Ptr.Designator;
6334 if (D.Invalid)
6335 return false;
6336
6337 // C++ [expr.dynamic.cast]p6:
6338 // If v is a null pointer value, the result is a null pointer value.
6339 if (Ptr.isNullPointer() && !E->isGLValue())
6340 return true;
6341
6342 // For all the other cases, we need the pointer to point to an object within
6343 // its lifetime / period of construction / destruction, and we need to know
6344 // its dynamic type.
6345 std::optional<DynamicType> DynType =
6346 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6347 if (!DynType)
6348 return false;
6349
6350 // C++ [expr.dynamic.cast]p7:
6351 // If T is "pointer to cv void", then the result is a pointer to the most
6352 // derived object
6353 if (E->getType()->isVoidPointerType())
6354 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6355
6356 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6357 assert(C && "dynamic_cast target is not void pointer nor class");
6358 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6359
6360 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6361 // C++ [expr.dynamic.cast]p9:
6362 if (!E->isGLValue()) {
6363 // The value of a failed cast to pointer type is the null pointer value
6364 // of the required result type.
6365 Ptr.setNull(Info.Ctx, E->getType());
6366 return true;
6367 }
6368
6369 // A failed cast to reference type throws [...] std::bad_cast.
6370 unsigned DiagKind;
6371 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6372 DynType->Type->isDerivedFrom(C)))
6373 DiagKind = 0;
6374 else if (!Paths || Paths->begin() == Paths->end())
6375 DiagKind = 1;
6376 else if (Paths->isAmbiguous(CQT))
6377 DiagKind = 2;
6378 else {
6379 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6380 DiagKind = 3;
6381 }
6382 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6383 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6384 << Info.Ctx.getCanonicalTagType(DynType->Type)
6386 return false;
6387 };
6388
6389 // Runtime check, phase 1:
6390 // Walk from the base subobject towards the derived object looking for the
6391 // target type.
6392 for (int PathLength = Ptr.Designator.Entries.size();
6393 PathLength >= (int)DynType->PathLength; --PathLength) {
6394 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6396 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6397 // We can only walk across public inheritance edges.
6398 if (PathLength > (int)DynType->PathLength &&
6399 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6400 Class))
6401 return RuntimeCheckFailed(nullptr);
6402 }
6403
6404 // Runtime check, phase 2:
6405 // Search the dynamic type for an unambiguous public base of type C.
6406 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6407 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6408 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6409 Paths.front().Access == AS_public) {
6410 // Downcast to the dynamic type...
6411 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6412 return false;
6413 // ... then upcast to the chosen base class subobject.
6414 for (CXXBasePathElement &Elem : Paths.front())
6415 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6416 return false;
6417 return true;
6418 }
6419
6420 // Otherwise, the runtime check fails.
6421 return RuntimeCheckFailed(&Paths);
6422}
6423
6424namespace {
6425struct StartLifetimeOfUnionMemberHandler {
6426 EvalInfo &Info;
6427 const Expr *LHSExpr;
6428 const FieldDecl *Field;
6429 bool DuringInit;
6430 bool Failed = false;
6431 static const AccessKinds AccessKind = AK_Assign;
6432
6433 typedef bool result_type;
6434 bool failed() { return Failed; }
6435 bool found(APValue &Subobj, QualType SubobjType) {
6436 // We are supposed to perform no initialization but begin the lifetime of
6437 // the object. We interpret that as meaning to do what default
6438 // initialization of the object would do if all constructors involved were
6439 // trivial:
6440 // * All base, non-variant member, and array element subobjects' lifetimes
6441 // begin
6442 // * No variant members' lifetimes begin
6443 // * All scalar subobjects whose lifetimes begin have indeterminate values
6444 assert(SubobjType->isUnionType());
6445 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6446 // This union member is already active. If it's also in-lifetime, there's
6447 // nothing to do.
6448 if (Subobj.getUnionValue().hasValue())
6449 return true;
6450 } else if (DuringInit) {
6451 // We're currently in the process of initializing a different union
6452 // member. If we carried on, that initialization would attempt to
6453 // store to an inactive union member, resulting in undefined behavior.
6454 Info.FFDiag(LHSExpr,
6455 diag::note_constexpr_union_member_change_during_init);
6456 return false;
6457 }
6458 APValue Result;
6459 Failed = !handleDefaultInitValue(Field->getType(), Result);
6460 Subobj.setUnion(Field, Result);
6461 return true;
6462 }
6463 bool found(APSInt &Value, QualType SubobjType) {
6464 llvm_unreachable("wrong value kind for union object");
6465 }
6466 bool found(APFloat &Value, QualType SubobjType) {
6467 llvm_unreachable("wrong value kind for union object");
6468 }
6469};
6470} // end anonymous namespace
6471
6472const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6473
6474/// Handle a builtin simple-assignment or a call to a trivial assignment
6475/// operator whose left-hand side might involve a union member access. If it
6476/// does, implicitly start the lifetime of any accessed union elements per
6477/// C++20 [class.union]5.
6478static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6479 const Expr *LHSExpr,
6480 const LValue &LHS) {
6481 if (LHS.InvalidBase || LHS.Designator.Invalid)
6482 return false;
6483
6485 // C++ [class.union]p5:
6486 // define the set S(E) of subexpressions of E as follows:
6487 unsigned PathLength = LHS.Designator.Entries.size();
6488 for (const Expr *E = LHSExpr; E != nullptr;) {
6489 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6490 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6491 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6492 // Note that we can't implicitly start the lifetime of a reference,
6493 // so we don't need to proceed any further if we reach one.
6494 if (!FD || FD->getType()->isReferenceType())
6495 break;
6496
6497 // ... and also contains A.B if B names a union member ...
6498 if (FD->getParent()->isUnion()) {
6499 // ... of a non-class, non-array type, or of a class type with a
6500 // trivial default constructor that is not deleted, or an array of
6501 // such types.
6502 auto *RD =
6503 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6504 if (!RD || RD->hasTrivialDefaultConstructor())
6505 UnionPathLengths.push_back({PathLength - 1, FD});
6506 }
6507
6508 E = ME->getBase();
6509 --PathLength;
6510 assert(declaresSameEntity(FD,
6511 LHS.Designator.Entries[PathLength]
6512 .getAsBaseOrMember().getPointer()));
6513
6514 // -- If E is of the form A[B] and is interpreted as a built-in array
6515 // subscripting operator, S(E) is [S(the array operand, if any)].
6516 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6517 // Step over an ArrayToPointerDecay implicit cast.
6518 auto *Base = ASE->getBase()->IgnoreImplicit();
6519 if (!Base->getType()->isArrayType())
6520 break;
6521
6522 E = Base;
6523 --PathLength;
6524
6525 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6526 // Step over a derived-to-base conversion.
6527 E = ICE->getSubExpr();
6528 if (ICE->getCastKind() == CK_NoOp)
6529 continue;
6530 if (ICE->getCastKind() != CK_DerivedToBase &&
6531 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6532 break;
6533 // Walk path backwards as we walk up from the base to the derived class.
6534 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6535 if (Elt->isVirtual()) {
6536 // A class with virtual base classes never has a trivial default
6537 // constructor, so S(E) is empty in this case.
6538 E = nullptr;
6539 break;
6540 }
6541
6542 --PathLength;
6543 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6544 LHS.Designator.Entries[PathLength]
6545 .getAsBaseOrMember().getPointer()));
6546 }
6547
6548 // -- Otherwise, S(E) is empty.
6549 } else {
6550 break;
6551 }
6552 }
6553
6554 // Common case: no unions' lifetimes are started.
6555 if (UnionPathLengths.empty())
6556 return true;
6557
6558 // if modification of X [would access an inactive union member], an object
6559 // of the type of X is implicitly created
6560 CompleteObject Obj =
6561 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6562 if (!Obj)
6563 return false;
6564 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6565 llvm::reverse(UnionPathLengths)) {
6566 // Form a designator for the union object.
6567 SubobjectDesignator D = LHS.Designator;
6568 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6569
6570 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6571 ConstructionPhase::AfterBases;
6572 StartLifetimeOfUnionMemberHandler StartLifetime{
6573 Info, LHSExpr, LengthAndField.second, DuringInit};
6574 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6575 return false;
6576 }
6577
6578 return true;
6579}
6580
6581static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6582 CallRef Call, EvalInfo &Info, bool NonNull = false,
6583 APValue **EvaluatedArg = nullptr) {
6584 LValue LV;
6585 // Create the parameter slot and register its destruction. For a vararg
6586 // argument, create a temporary.
6587 // FIXME: For calling conventions that destroy parameters in the callee,
6588 // should we consider performing destruction when the function returns
6589 // instead?
6590 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6591 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6592 ScopeKind::Call, LV);
6593 if (!EvaluateInPlace(V, Info, LV, Arg))
6594 return false;
6595
6596 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6597 // undefined behavior, so is non-constant.
6598 if (NonNull && V.isLValue() && V.isNullPointer()) {
6599 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6600 return false;
6601 }
6602
6603 if (EvaluatedArg)
6604 *EvaluatedArg = &V;
6605
6606 return true;
6607}
6608
6609/// Evaluate the arguments to a function call.
6610static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6611 EvalInfo &Info, const FunctionDecl *Callee,
6612 bool RightToLeft = false,
6613 LValue *ObjectArg = nullptr) {
6614 bool Success = true;
6615 llvm::SmallBitVector ForbiddenNullArgs;
6616 if (Callee->hasAttr<NonNullAttr>()) {
6617 ForbiddenNullArgs.resize(Args.size());
6618 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6619 if (!Attr->args_size()) {
6620 ForbiddenNullArgs.set();
6621 break;
6622 } else
6623 for (auto Idx : Attr->args()) {
6624 unsigned ASTIdx = Idx.getASTIndex();
6625 if (ASTIdx >= Args.size())
6626 continue;
6627 ForbiddenNullArgs[ASTIdx] = true;
6628 }
6629 }
6630 }
6631 for (unsigned I = 0; I < Args.size(); I++) {
6632 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6633 const ParmVarDecl *PVD =
6634 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6635 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6636 APValue *That = nullptr;
6637 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6638 // If we're checking for a potential constant expression, evaluate all
6639 // initializers even if some of them fail.
6640 if (!Info.noteFailure())
6641 return false;
6642 Success = false;
6643 }
6644 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6645 ObjectArg->setFrom(Info.Ctx, *That);
6646 }
6647 return Success;
6648}
6649
6650/// Perform a trivial copy from Param, which is the parameter of a copy or move
6651/// constructor or assignment operator.
6652static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6653 const Expr *E, APValue &Result,
6654 bool CopyObjectRepresentation) {
6655 // Find the reference argument.
6656 CallStackFrame *Frame = Info.CurrentCall;
6657 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6658 if (!RefValue) {
6659 Info.FFDiag(E);
6660 return false;
6661 }
6662
6663 // Copy out the contents of the RHS object.
6664 LValue RefLValue;
6665 RefLValue.setFrom(Info.Ctx, *RefValue);
6667 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6668 CopyObjectRepresentation);
6669}
6670
6671/// Evaluate a function call.
6673 const FunctionDecl *Callee,
6674 const LValue *ObjectArg, const Expr *E,
6675 ArrayRef<const Expr *> Args, CallRef Call,
6676 const Stmt *Body, EvalInfo &Info,
6677 APValue &Result, const LValue *ResultSlot) {
6678 if (!Info.CheckCallLimit(CallLoc))
6679 return false;
6680
6681 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
6682
6683 // For a trivial copy or move assignment, perform an APValue copy. This is
6684 // essential for unions, where the operations performed by the assignment
6685 // operator cannot be represented as statements.
6686 //
6687 // Skip this for non-union classes with no fields; in that case, the defaulted
6688 // copy/move does not actually read the object.
6689 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6690 if (MD && MD->isDefaulted() &&
6691 (MD->getParent()->isUnion() ||
6692 (MD->isTrivial() &&
6694 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
6695 assert(ObjectArg &&
6697 APValue RHSValue;
6698 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6699 MD->getParent()->isUnion()))
6700 return false;
6701
6702 LValue Obj;
6703 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
6705 RHSValue))
6706 return false;
6707 ObjectArg->moveInto(Result);
6708 return true;
6709 } else if (MD && isLambdaCallOperator(MD)) {
6710 // We're in a lambda; determine the lambda capture field maps unless we're
6711 // just constexpr checking a lambda's call operator. constexpr checking is
6712 // done before the captures have been added to the closure object (unless
6713 // we're inferring constexpr-ness), so we don't have access to them in this
6714 // case. But since we don't need the captures to constexpr check, we can
6715 // just ignore them.
6716 if (!Info.checkingPotentialConstantExpression())
6717 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6718 Frame.LambdaThisCaptureField);
6719 }
6720
6721 StmtResult Ret = {Result, ResultSlot};
6722 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6723 if (ESR == ESR_Succeeded) {
6724 if (Callee->getReturnType()->isVoidType())
6725 return true;
6726 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6727 }
6728 return ESR == ESR_Returned;
6729}
6730
6731/// Evaluate a constructor call.
6732static bool HandleConstructorCall(const Expr *E, const LValue &This,
6733 CallRef Call,
6735 EvalInfo &Info, APValue &Result) {
6736 SourceLocation CallLoc = E->getExprLoc();
6737 if (!Info.CheckCallLimit(CallLoc))
6738 return false;
6739
6740 const CXXRecordDecl *RD = Definition->getParent();
6741 if (RD->getNumVBases()) {
6742 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6743 return false;
6744 }
6745
6746 EvalInfo::EvaluatingConstructorRAII EvalObj(
6747 Info,
6748 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6749 RD->getNumBases());
6750 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6751
6752 // FIXME: Creating an APValue just to hold a nonexistent return value is
6753 // wasteful.
6754 APValue RetVal;
6755 StmtResult Ret = {RetVal, nullptr};
6756
6757 // If it's a delegating constructor, delegate.
6758 if (Definition->isDelegatingConstructor()) {
6760 if ((*I)->getInit()->isValueDependent()) {
6761 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6762 return false;
6763 } else {
6764 FullExpressionRAII InitScope(Info);
6765 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6766 !InitScope.destroy())
6767 return false;
6768 }
6769 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6770 }
6771
6772 // For a trivial copy or move constructor, perform an APValue copy. This is
6773 // essential for unions (or classes with anonymous union members), where the
6774 // operations performed by the constructor cannot be represented by
6775 // ctor-initializers.
6776 //
6777 // Skip this for empty non-union classes; we should not perform an
6778 // lvalue-to-rvalue conversion on them because their copy constructor does not
6779 // actually read them.
6780 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6781 (Definition->getParent()->isUnion() ||
6782 (Definition->isTrivial() &&
6784 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6785 Definition->getParent()->isUnion());
6786 }
6787
6788 // Reserve space for the struct members.
6789 if (!Result.hasValue()) {
6790 if (!RD->isUnion())
6791 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6792 std::distance(RD->field_begin(), RD->field_end()));
6793 else
6794 // A union starts with no active member.
6795 Result = APValue((const FieldDecl*)nullptr);
6796 }
6797
6798 if (RD->isInvalidDecl()) return false;
6799 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6800
6801 // A scope for temporaries lifetime-extended by reference members.
6802 BlockScopeRAII LifetimeExtendedScope(Info);
6803
6804 bool Success = true;
6805 unsigned BasesSeen = 0;
6806#ifndef NDEBUG
6808#endif
6810 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6811 // We might be initializing the same field again if this is an indirect
6812 // field initialization.
6813 if (FieldIt == RD->field_end() ||
6814 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6815 assert(Indirect && "fields out of order?");
6816 return;
6817 }
6818
6819 // Default-initialize any fields with no explicit initializer.
6820 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6821 assert(FieldIt != RD->field_end() && "missing field?");
6822 if (!FieldIt->isUnnamedBitField())
6824 FieldIt->getType(),
6825 Result.getStructField(FieldIt->getFieldIndex()));
6826 }
6827 ++FieldIt;
6828 };
6829 for (const auto *I : Definition->inits()) {
6830 LValue Subobject = This;
6831 LValue SubobjectParent = This;
6832 APValue *Value = &Result;
6833
6834 // Determine the subobject to initialize.
6835 FieldDecl *FD = nullptr;
6836 if (I->isBaseInitializer()) {
6837 QualType BaseType(I->getBaseClass(), 0);
6838#ifndef NDEBUG
6839 // Non-virtual base classes are initialized in the order in the class
6840 // definition. We have already checked for virtual base classes.
6841 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6842 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6843 "base class initializers not in expected order");
6844 ++BaseIt;
6845#endif
6846 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6847 BaseType->getAsCXXRecordDecl(), &Layout))
6848 return false;
6849 Value = &Result.getStructBase(BasesSeen++);
6850 } else if ((FD = I->getMember())) {
6851 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6852 return false;
6853 if (RD->isUnion()) {
6854 Result = APValue(FD);
6855 Value = &Result.getUnionValue();
6856 } else {
6857 SkipToField(FD, false);
6858 Value = &Result.getStructField(FD->getFieldIndex());
6859 }
6860 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6861 // Walk the indirect field decl's chain to find the object to initialize,
6862 // and make sure we've initialized every step along it.
6863 auto IndirectFieldChain = IFD->chain();
6864 for (auto *C : IndirectFieldChain) {
6865 FD = cast<FieldDecl>(C);
6866 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6867 // Switch the union field if it differs. This happens if we had
6868 // preceding zero-initialization, and we're now initializing a union
6869 // subobject other than the first.
6870 // FIXME: In this case, the values of the other subobjects are
6871 // specified, since zero-initialization sets all padding bits to zero.
6872 if (!Value->hasValue() ||
6873 (Value->isUnion() &&
6874 !declaresSameEntity(Value->getUnionField(), FD))) {
6875 if (CD->isUnion())
6876 *Value = APValue(FD);
6877 else
6878 // FIXME: This immediately starts the lifetime of all members of
6879 // an anonymous struct. It would be preferable to strictly start
6880 // member lifetime in initialization order.
6881 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
6882 *Value);
6883 }
6884 // Store Subobject as its parent before updating it for the last element
6885 // in the chain.
6886 if (C == IndirectFieldChain.back())
6887 SubobjectParent = Subobject;
6888 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6889 return false;
6890 if (CD->isUnion())
6891 Value = &Value->getUnionValue();
6892 else {
6893 if (C == IndirectFieldChain.front() && !RD->isUnion())
6894 SkipToField(FD, true);
6895 Value = &Value->getStructField(FD->getFieldIndex());
6896 }
6897 }
6898 } else {
6899 llvm_unreachable("unknown base initializer kind");
6900 }
6901
6902 // Need to override This for implicit field initializers as in this case
6903 // This refers to innermost anonymous struct/union containing initializer,
6904 // not to currently constructed class.
6905 const Expr *Init = I->getInit();
6906 if (Init->isValueDependent()) {
6907 if (!EvaluateDependentExpr(Init, Info))
6908 return false;
6909 } else {
6910 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6911 isa<CXXDefaultInitExpr>(Init));
6912 FullExpressionRAII InitScope(Info);
6913 if (FD && FD->getType()->isReferenceType() &&
6914 !FD->getType()->isFunctionReferenceType()) {
6915 LValue Result;
6916 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
6917 *Value)) {
6918 if (!Info.noteFailure())
6919 return false;
6920 Success = false;
6921 }
6922 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6923 (FD && FD->isBitField() &&
6924 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6925 // If we're checking for a potential constant expression, evaluate all
6926 // initializers even if some of them fail.
6927 if (!Info.noteFailure())
6928 return false;
6929 Success = false;
6930 }
6931 }
6932
6933 // This is the point at which the dynamic type of the object becomes this
6934 // class type.
6935 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6936 EvalObj.finishedConstructingBases();
6937 }
6938
6939 // Default-initialize any remaining fields.
6940 if (!RD->isUnion()) {
6941 for (; FieldIt != RD->field_end(); ++FieldIt) {
6942 if (!FieldIt->isUnnamedBitField())
6944 FieldIt->getType(),
6945 Result.getStructField(FieldIt->getFieldIndex()));
6946 }
6947 }
6948
6949 EvalObj.finishedConstructingFields();
6950
6951 return Success &&
6952 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6953 LifetimeExtendedScope.destroy();
6954}
6955
6956static bool HandleConstructorCall(const Expr *E, const LValue &This,
6959 EvalInfo &Info, APValue &Result) {
6960 CallScopeRAII CallScope(Info);
6961 CallRef Call = Info.CurrentCall->createCall(Definition);
6962 if (!EvaluateArgs(Args, Call, Info, Definition))
6963 return false;
6964
6965 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6966 CallScope.destroy();
6967}
6968
6969static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6970 const LValue &This, APValue &Value,
6971 QualType T) {
6972 // Objects can only be destroyed while they're within their lifetimes.
6973 // FIXME: We have no representation for whether an object of type nullptr_t
6974 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6975 // as indeterminate instead?
6976 if (Value.isAbsent() && !T->isNullPtrType()) {
6977 APValue Printable;
6978 This.moveInto(Printable);
6979 Info.FFDiag(CallRange.getBegin(),
6980 diag::note_constexpr_destroy_out_of_lifetime)
6981 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6982 return false;
6983 }
6984
6985 // Invent an expression for location purposes.
6986 // FIXME: We shouldn't need to do this.
6987 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6988
6989 // For arrays, destroy elements right-to-left.
6990 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6991 uint64_t Size = CAT->getZExtSize();
6992 QualType ElemT = CAT->getElementType();
6993
6994 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6995 return false;
6996
6997 LValue ElemLV = This;
6998 ElemLV.addArray(Info, &LocE, CAT);
6999 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7000 return false;
7001
7002 // Ensure that we have actual array elements available to destroy; the
7003 // destructors might mutate the value, so we can't run them on the array
7004 // filler.
7005 if (Size && Size > Value.getArrayInitializedElts())
7006 expandArray(Value, Value.getArraySize() - 1);
7007
7008 // The size of the array might have been reduced by
7009 // a placement new.
7010 for (Size = Value.getArraySize(); Size != 0; --Size) {
7011 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7012 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7013 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7014 return false;
7015 }
7016
7017 // End the lifetime of this array now.
7018 Value = APValue();
7019 return true;
7020 }
7021
7022 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7023 if (!RD) {
7024 if (T.isDestructedType()) {
7025 Info.FFDiag(CallRange.getBegin(),
7026 diag::note_constexpr_unsupported_destruction)
7027 << T;
7028 return false;
7029 }
7030
7031 Value = APValue();
7032 return true;
7033 }
7034
7035 if (RD->getNumVBases()) {
7036 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7037 return false;
7038 }
7039
7040 const CXXDestructorDecl *DD = RD->getDestructor();
7041 if (!DD && !RD->hasTrivialDestructor()) {
7042 Info.FFDiag(CallRange.getBegin());
7043 return false;
7044 }
7045
7046 if (!DD || DD->isTrivial() ||
7047 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7048 // A trivial destructor just ends the lifetime of the object. Check for
7049 // this case before checking for a body, because we might not bother
7050 // building a body for a trivial destructor. Note that it doesn't matter
7051 // whether the destructor is constexpr in this case; all trivial
7052 // destructors are constexpr.
7053 //
7054 // If an anonymous union would be destroyed, some enclosing destructor must
7055 // have been explicitly defined, and the anonymous union destruction should
7056 // have no effect.
7057 Value = APValue();
7058 return true;
7059 }
7060
7061 if (!Info.CheckCallLimit(CallRange.getBegin()))
7062 return false;
7063
7064 const FunctionDecl *Definition = nullptr;
7065 const Stmt *Body = DD->getBody(Definition);
7066
7067 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7068 return false;
7069
7070 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7071 CallRef());
7072
7073 // We're now in the period of destruction of this object.
7074 unsigned BasesLeft = RD->getNumBases();
7075 EvalInfo::EvaluatingDestructorRAII EvalObj(
7076 Info,
7077 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7078 if (!EvalObj.DidInsert) {
7079 // C++2a [class.dtor]p19:
7080 // the behavior is undefined if the destructor is invoked for an object
7081 // whose lifetime has ended
7082 // (Note that formally the lifetime ends when the period of destruction
7083 // begins, even though certain uses of the object remain valid until the
7084 // period of destruction ends.)
7085 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7086 return false;
7087 }
7088
7089 // FIXME: Creating an APValue just to hold a nonexistent return value is
7090 // wasteful.
7091 APValue RetVal;
7092 StmtResult Ret = {RetVal, nullptr};
7093 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7094 return false;
7095
7096 // A union destructor does not implicitly destroy its members.
7097 if (RD->isUnion())
7098 return true;
7099
7100 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7101
7102 // We don't have a good way to iterate fields in reverse, so collect all the
7103 // fields first and then walk them backwards.
7104 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7105 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7106 if (FD->isUnnamedBitField())
7107 continue;
7108
7109 LValue Subobject = This;
7110 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7111 return false;
7112
7113 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7114 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7115 FD->getType()))
7116 return false;
7117 }
7118
7119 if (BasesLeft != 0)
7120 EvalObj.startedDestroyingBases();
7121
7122 // Destroy base classes in reverse order.
7123 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7124 --BasesLeft;
7125
7126 QualType BaseType = Base.getType();
7127 LValue Subobject = This;
7128 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7129 BaseType->getAsCXXRecordDecl(), &Layout))
7130 return false;
7131
7132 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7133 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7134 BaseType))
7135 return false;
7136 }
7137 assert(BasesLeft == 0 && "NumBases was wrong?");
7138
7139 // The period of destruction ends now. The object is gone.
7140 Value = APValue();
7141 return true;
7142}
7143
7144namespace {
7145struct DestroyObjectHandler {
7146 EvalInfo &Info;
7147 const Expr *E;
7148 const LValue &This;
7149 const AccessKinds AccessKind;
7150
7151 typedef bool result_type;
7152 bool failed() { return false; }
7153 bool found(APValue &Subobj, QualType SubobjType) {
7154 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7155 SubobjType);
7156 }
7157 bool found(APSInt &Value, QualType SubobjType) {
7158 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7159 return false;
7160 }
7161 bool found(APFloat &Value, QualType SubobjType) {
7162 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7163 return false;
7164 }
7165};
7166}
7167
7168/// Perform a destructor or pseudo-destructor call on the given object, which
7169/// might in general not be a complete object.
7170static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7171 const LValue &This, QualType ThisType) {
7172 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7173 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7174 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7175}
7176
7177/// Destroy and end the lifetime of the given complete object.
7178static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7180 QualType T) {
7181 // If we've had an unmodeled side-effect, we can't rely on mutable state
7182 // (such as the object we're about to destroy) being correct.
7183 if (Info.EvalStatus.HasSideEffects)
7184 return false;
7185
7186 LValue LV;
7187 LV.set({LVBase});
7188 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7189}
7190
7191/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7192static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7193 LValue &Result) {
7194 if (Info.checkingPotentialConstantExpression() ||
7195 Info.SpeculativeEvaluationDepth)
7196 return false;
7197
7198 // This is permitted only within a call to std::allocator<T>::allocate.
7199 auto Caller = Info.getStdAllocatorCaller("allocate");
7200 if (!Caller) {
7201 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7202 ? diag::note_constexpr_new_untyped
7203 : diag::note_constexpr_new);
7204 return false;
7205 }
7206
7207 QualType ElemType = Caller.ElemType;
7208 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7209 Info.FFDiag(E->getExprLoc(),
7210 diag::note_constexpr_new_not_complete_object_type)
7211 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7212 return false;
7213 }
7214
7215 APSInt ByteSize;
7216 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7217 return false;
7218 bool IsNothrow = false;
7219 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7220 EvaluateIgnoredValue(Info, E->getArg(I));
7221 IsNothrow |= E->getType()->isNothrowT();
7222 }
7223
7224 CharUnits ElemSize;
7225 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7226 return false;
7227 APInt Size, Remainder;
7228 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7229 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7230 if (Remainder != 0) {
7231 // This likely indicates a bug in the implementation of 'std::allocator'.
7232 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7233 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7234 return false;
7235 }
7236
7237 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7238 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7239 if (IsNothrow) {
7240 Result.setNull(Info.Ctx, E->getType());
7241 return true;
7242 }
7243 return false;
7244 }
7245
7246 QualType AllocType = Info.Ctx.getConstantArrayType(
7247 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7248 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7249 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7250 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7251 return true;
7252}
7253
7255 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7256 if (CXXDestructorDecl *DD = RD->getDestructor())
7257 return DD->isVirtual();
7258 return false;
7259}
7260
7262 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7263 if (CXXDestructorDecl *DD = RD->getDestructor())
7264 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7265 return nullptr;
7266}
7267
7268/// Check that the given object is a suitable pointer to a heap allocation that
7269/// still exists and is of the right kind for the purpose of a deletion.
7270///
7271/// On success, returns the heap allocation to deallocate. On failure, produces
7272/// a diagnostic and returns std::nullopt.
7273static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7274 const LValue &Pointer,
7275 DynAlloc::Kind DeallocKind) {
7276 auto PointerAsString = [&] {
7277 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7278 };
7279
7280 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7281 if (!DA) {
7282 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7283 << PointerAsString();
7284 if (Pointer.Base)
7285 NoteLValueLocation(Info, Pointer.Base);
7286 return std::nullopt;
7287 }
7288
7289 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7290 if (!Alloc) {
7291 Info.FFDiag(E, diag::note_constexpr_double_delete);
7292 return std::nullopt;
7293 }
7294
7295 if (DeallocKind != (*Alloc)->getKind()) {
7296 QualType AllocType = Pointer.Base.getDynamicAllocType();
7297 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7298 << DeallocKind << (*Alloc)->getKind() << AllocType;
7299 NoteLValueLocation(Info, Pointer.Base);
7300 return std::nullopt;
7301 }
7302
7303 bool Subobject = false;
7304 if (DeallocKind == DynAlloc::New) {
7305 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7306 Pointer.Designator.isOnePastTheEnd();
7307 } else {
7308 Subobject = Pointer.Designator.Entries.size() != 1 ||
7309 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7310 }
7311 if (Subobject) {
7312 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7313 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7314 return std::nullopt;
7315 }
7316
7317 return Alloc;
7318}
7319
7320// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7321static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7322 if (Info.checkingPotentialConstantExpression() ||
7323 Info.SpeculativeEvaluationDepth)
7324 return false;
7325
7326 // This is permitted only within a call to std::allocator<T>::deallocate.
7327 if (!Info.getStdAllocatorCaller("deallocate")) {
7328 Info.FFDiag(E->getExprLoc());
7329 return true;
7330 }
7331
7332 LValue Pointer;
7333 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7334 return false;
7335 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7336 EvaluateIgnoredValue(Info, E->getArg(I));
7337
7338 if (Pointer.Designator.Invalid)
7339 return false;
7340
7341 // Deleting a null pointer would have no effect, but it's not permitted by
7342 // std::allocator<T>::deallocate's contract.
7343 if (Pointer.isNullPointer()) {
7344 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7345 return true;
7346 }
7347
7348 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7349 return false;
7350
7351 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7352 return true;
7353}
7354
7355//===----------------------------------------------------------------------===//
7356// Generic Evaluation
7357//===----------------------------------------------------------------------===//
7358namespace {
7359
7360class BitCastBuffer {
7361 // FIXME: We're going to need bit-level granularity when we support
7362 // bit-fields.
7363 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7364 // we don't support a host or target where that is the case. Still, we should
7365 // use a more generic type in case we ever do.
7367
7368 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7369 "Need at least 8 bit unsigned char");
7370
7371 bool TargetIsLittleEndian;
7372
7373public:
7374 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7375 : Bytes(Width.getQuantity()),
7376 TargetIsLittleEndian(TargetIsLittleEndian) {}
7377
7378 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7379 SmallVectorImpl<unsigned char> &Output) const {
7380 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7381 // If a byte of an integer is uninitialized, then the whole integer is
7382 // uninitialized.
7383 if (!Bytes[I.getQuantity()])
7384 return false;
7385 Output.push_back(*Bytes[I.getQuantity()]);
7386 }
7387 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7388 std::reverse(Output.begin(), Output.end());
7389 return true;
7390 }
7391
7392 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7393 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7394 std::reverse(Input.begin(), Input.end());
7395
7396 size_t Index = 0;
7397 for (unsigned char Byte : Input) {
7398 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7399 Bytes[Offset.getQuantity() + Index] = Byte;
7400 ++Index;
7401 }
7402 }
7403
7404 size_t size() { return Bytes.size(); }
7405};
7406
7407/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7408/// target would represent the value at runtime.
7409class APValueToBufferConverter {
7410 EvalInfo &Info;
7411 BitCastBuffer Buffer;
7412 const CastExpr *BCE;
7413
7414 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7415 const CastExpr *BCE)
7416 : Info(Info),
7417 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7418 BCE(BCE) {}
7419
7420 bool visit(const APValue &Val, QualType Ty) {
7421 return visit(Val, Ty, CharUnits::fromQuantity(0));
7422 }
7423
7424 // Write out Val with type Ty into Buffer starting at Offset.
7425 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7426 assert((size_t)Offset.getQuantity() <= Buffer.size());
7427
7428 // As a special case, nullptr_t has an indeterminate value.
7429 if (Ty->isNullPtrType())
7430 return true;
7431
7432 // Dig through Src to find the byte at SrcOffset.
7433 switch (Val.getKind()) {
7435 case APValue::None:
7436 return true;
7437
7438 case APValue::Int:
7439 return visitInt(Val.getInt(), Ty, Offset);
7440 case APValue::Float:
7441 return visitFloat(Val.getFloat(), Ty, Offset);
7442 case APValue::Array:
7443 return visitArray(Val, Ty, Offset);
7444 case APValue::Struct:
7445 return visitRecord(Val, Ty, Offset);
7446 case APValue::Vector:
7447 return visitVector(Val, Ty, Offset);
7448
7451 return visitComplex(Val, Ty, Offset);
7453 // FIXME: We should support these.
7454
7455 case APValue::Union:
7458 Info.FFDiag(BCE->getBeginLoc(),
7459 diag::note_constexpr_bit_cast_unsupported_type)
7460 << Ty;
7461 return false;
7462 }
7463
7464 case APValue::LValue:
7465 llvm_unreachable("LValue subobject in bit_cast?");
7466 }
7467 llvm_unreachable("Unhandled APValue::ValueKind");
7468 }
7469
7470 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7471 const RecordDecl *RD = Ty->getAsRecordDecl();
7472 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7473
7474 // Visit the base classes.
7475 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7476 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7477 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7478 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7479 const APValue &Base = Val.getStructBase(I);
7480
7481 // Can happen in error cases.
7482 if (!Base.isStruct())
7483 return false;
7484
7485 if (!visitRecord(Base, BS.getType(),
7486 Layout.getBaseClassOffset(BaseDecl) + Offset))
7487 return false;
7488 }
7489 }
7490
7491 // Visit the fields.
7492 unsigned FieldIdx = 0;
7493 for (FieldDecl *FD : RD->fields()) {
7494 if (FD->isBitField()) {
7495 Info.FFDiag(BCE->getBeginLoc(),
7496 diag::note_constexpr_bit_cast_unsupported_bitfield);
7497 return false;
7498 }
7499
7500 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7501
7502 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7503 "only bit-fields can have sub-char alignment");
7504 CharUnits FieldOffset =
7505 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7506 QualType FieldTy = FD->getType();
7507 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7508 return false;
7509 ++FieldIdx;
7510 }
7511
7512 return true;
7513 }
7514
7515 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7516 const auto *CAT =
7517 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7518 if (!CAT)
7519 return false;
7520
7521 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7522 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7523 unsigned ArraySize = Val.getArraySize();
7524 // First, initialize the initialized elements.
7525 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7526 const APValue &SubObj = Val.getArrayInitializedElt(I);
7527 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7528 return false;
7529 }
7530
7531 // Next, initialize the rest of the array using the filler.
7532 if (Val.hasArrayFiller()) {
7533 const APValue &Filler = Val.getArrayFiller();
7534 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7535 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7536 return false;
7537 }
7538 }
7539
7540 return true;
7541 }
7542
7543 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7544 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7545 QualType EltTy = ComplexTy->getElementType();
7546 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7547 bool IsInt = Val.isComplexInt();
7548
7549 if (IsInt) {
7550 if (!visitInt(Val.getComplexIntReal(), EltTy,
7551 Offset + (0 * EltSizeChars)))
7552 return false;
7553 if (!visitInt(Val.getComplexIntImag(), EltTy,
7554 Offset + (1 * EltSizeChars)))
7555 return false;
7556 } else {
7557 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7558 Offset + (0 * EltSizeChars)))
7559 return false;
7560 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7561 Offset + (1 * EltSizeChars)))
7562 return false;
7563 }
7564
7565 return true;
7566 }
7567
7568 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7569 const VectorType *VTy = Ty->castAs<VectorType>();
7570 QualType EltTy = VTy->getElementType();
7571 unsigned NElts = VTy->getNumElements();
7572
7573 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7574 // Special handling for OpenCL bool vectors:
7575 // Since these vectors are stored as packed bits, but we can't write
7576 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7577 // together into an appropriately sized APInt and write them all out at
7578 // once. Because we don't accept vectors where NElts * EltSize isn't a
7579 // multiple of the char size, there will be no padding space, so we don't
7580 // have to worry about writing data which should have been left
7581 // uninitialized.
7582 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7583
7584 llvm::APInt Res = llvm::APInt::getZero(NElts);
7585 for (unsigned I = 0; I < NElts; ++I) {
7586 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7587 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7588 "bool vector element must be 1-bit unsigned integer!");
7589
7590 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7591 }
7592
7593 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7594 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7595 Buffer.writeObject(Offset, Bytes);
7596 } else {
7597 // Iterate over each of the elements and write them out to the buffer at
7598 // the appropriate offset.
7599 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7600 for (unsigned I = 0; I < NElts; ++I) {
7601 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7602 return false;
7603 }
7604 }
7605
7606 return true;
7607 }
7608
7609 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7610 APSInt AdjustedVal = Val;
7611 unsigned Width = AdjustedVal.getBitWidth();
7612 if (Ty->isBooleanType()) {
7613 Width = Info.Ctx.getTypeSize(Ty);
7614 AdjustedVal = AdjustedVal.extend(Width);
7615 }
7616
7617 SmallVector<uint8_t, 8> Bytes(Width / 8);
7618 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7619 Buffer.writeObject(Offset, Bytes);
7620 return true;
7621 }
7622
7623 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7624 APSInt AsInt(Val.bitcastToAPInt());
7625 return visitInt(AsInt, Ty, Offset);
7626 }
7627
7628public:
7629 static std::optional<BitCastBuffer>
7630 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7631 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7632 APValueToBufferConverter Converter(Info, DstSize, BCE);
7633 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7634 return std::nullopt;
7635 return Converter.Buffer;
7636 }
7637};
7638
7639/// Write an BitCastBuffer into an APValue.
7640class BufferToAPValueConverter {
7641 EvalInfo &Info;
7642 const BitCastBuffer &Buffer;
7643 const CastExpr *BCE;
7644
7645 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7646 const CastExpr *BCE)
7647 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7648
7649 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7650 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7651 // Ideally this will be unreachable.
7652 std::nullopt_t unsupportedType(QualType Ty) {
7653 Info.FFDiag(BCE->getBeginLoc(),
7654 diag::note_constexpr_bit_cast_unsupported_type)
7655 << Ty;
7656 return std::nullopt;
7657 }
7658
7659 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7660 Info.FFDiag(BCE->getBeginLoc(),
7661 diag::note_constexpr_bit_cast_unrepresentable_value)
7662 << Ty << toString(Val, /*Radix=*/10);
7663 return std::nullopt;
7664 }
7665
7666 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7667 const EnumType *EnumSugar = nullptr) {
7668 if (T->isNullPtrType()) {
7669 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7670 return APValue((Expr *)nullptr,
7671 /*Offset=*/CharUnits::fromQuantity(NullValue),
7672 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7673 }
7674
7675 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7676
7677 // Work around floating point types that contain unused padding bytes. This
7678 // is really just `long double` on x86, which is the only fundamental type
7679 // with padding bytes.
7680 if (T->isRealFloatingType()) {
7681 const llvm::fltSemantics &Semantics =
7682 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7683 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7684 assert(NumBits % 8 == 0);
7685 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7686 if (NumBytes != SizeOf)
7687 SizeOf = NumBytes;
7688 }
7689
7691 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7692 // If this is std::byte or unsigned char, then its okay to store an
7693 // indeterminate value.
7694 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7695 bool IsUChar =
7696 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7697 T->isSpecificBuiltinType(BuiltinType::Char_U));
7698 if (!IsStdByte && !IsUChar) {
7699 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7700 Info.FFDiag(BCE->getExprLoc(),
7701 diag::note_constexpr_bit_cast_indet_dest)
7702 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7703 return std::nullopt;
7704 }
7705
7707 }
7708
7709 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7710 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7711
7713 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7714
7715 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7716 if (IntWidth != Val.getBitWidth()) {
7717 APSInt Truncated = Val.trunc(IntWidth);
7718 if (Truncated.extend(Val.getBitWidth()) != Val)
7719 return unrepresentableValue(QualType(T, 0), Val);
7720 Val = Truncated;
7721 }
7722
7723 return APValue(Val);
7724 }
7725
7726 if (T->isRealFloatingType()) {
7727 const llvm::fltSemantics &Semantics =
7728 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7729 return APValue(APFloat(Semantics, Val));
7730 }
7731
7732 return unsupportedType(QualType(T, 0));
7733 }
7734
7735 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7736 const RecordDecl *RD = RTy->getAsRecordDecl();
7737 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7738
7739 unsigned NumBases = 0;
7740 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7741 NumBases = CXXRD->getNumBases();
7742
7743 APValue ResultVal(APValue::UninitStruct(), NumBases,
7744 std::distance(RD->field_begin(), RD->field_end()));
7745
7746 // Visit the base classes.
7747 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7748 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7749 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7751
7752 std::optional<APValue> SubObj = visitType(
7753 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7754 if (!SubObj)
7755 return std::nullopt;
7756 ResultVal.getStructBase(I) = *SubObj;
7757 }
7758 }
7759
7760 // Visit the fields.
7761 unsigned FieldIdx = 0;
7762 for (FieldDecl *FD : RD->fields()) {
7763 // FIXME: We don't currently support bit-fields. A lot of the logic for
7764 // this is in CodeGen, so we need to factor it around.
7765 if (FD->isBitField()) {
7766 Info.FFDiag(BCE->getBeginLoc(),
7767 diag::note_constexpr_bit_cast_unsupported_bitfield);
7768 return std::nullopt;
7769 }
7770
7771 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7772 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7773
7774 CharUnits FieldOffset =
7775 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7776 Offset;
7777 QualType FieldTy = FD->getType();
7778 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7779 if (!SubObj)
7780 return std::nullopt;
7781 ResultVal.getStructField(FieldIdx) = *SubObj;
7782 ++FieldIdx;
7783 }
7784
7785 return ResultVal;
7786 }
7787
7788 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7789 QualType RepresentationType =
7791 assert(!RepresentationType.isNull() &&
7792 "enum forward decl should be caught by Sema");
7793 const auto *AsBuiltin =
7794 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7795 // Recurse into the underlying type. Treat std::byte transparently as
7796 // unsigned char.
7797 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7798 }
7799
7800 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7801 size_t Size = Ty->getLimitedSize();
7802 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7803
7804 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7805 for (size_t I = 0; I != Size; ++I) {
7806 std::optional<APValue> ElementValue =
7807 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7808 if (!ElementValue)
7809 return std::nullopt;
7810 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7811 }
7812
7813 return ArrayValue;
7814 }
7815
7816 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7817 QualType ElementType = Ty->getElementType();
7818 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7819 bool IsInt = ElementType->isIntegerType();
7820
7821 std::optional<APValue> Values[2];
7822 for (unsigned I = 0; I != 2; ++I) {
7823 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7824 if (!Values[I])
7825 return std::nullopt;
7826 }
7827
7828 if (IsInt)
7829 return APValue(Values[0]->getInt(), Values[1]->getInt());
7830 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7831 }
7832
7833 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7834 QualType EltTy = VTy->getElementType();
7835 unsigned NElts = VTy->getNumElements();
7836 unsigned EltSize =
7837 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
7838
7840 Elts.reserve(NElts);
7841 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7842 // Special handling for OpenCL bool vectors:
7843 // Since these vectors are stored as packed bits, but we can't read
7844 // individual bits from the BitCastBuffer, we'll buffer all of the
7845 // elements together into an appropriately sized APInt and write them all
7846 // out at once. Because we don't accept vectors where NElts * EltSize
7847 // isn't a multiple of the char size, there will be no padding space, so
7848 // we don't have to worry about reading any padding data which didn't
7849 // actually need to be accessed.
7850 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7851
7853 Bytes.reserve(NElts / 8);
7854 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7855 return std::nullopt;
7856
7857 APSInt SValInt(NElts, true);
7858 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7859
7860 for (unsigned I = 0; I < NElts; ++I) {
7861 llvm::APInt Elt =
7862 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7863 Elts.emplace_back(
7864 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7865 }
7866 } else {
7867 // Iterate over each of the elements and read them from the buffer at
7868 // the appropriate offset.
7869 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7870 for (unsigned I = 0; I < NElts; ++I) {
7871 std::optional<APValue> EltValue =
7872 visitType(EltTy, Offset + I * EltSizeChars);
7873 if (!EltValue)
7874 return std::nullopt;
7875 Elts.push_back(std::move(*EltValue));
7876 }
7877 }
7878
7879 return APValue(Elts.data(), Elts.size());
7880 }
7881
7882 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7883 return unsupportedType(QualType(Ty, 0));
7884 }
7885
7886 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7887 QualType Can = Ty.getCanonicalType();
7888
7889 switch (Can->getTypeClass()) {
7890#define TYPE(Class, Base) \
7891 case Type::Class: \
7892 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7893#define ABSTRACT_TYPE(Class, Base)
7894#define NON_CANONICAL_TYPE(Class, Base) \
7895 case Type::Class: \
7896 llvm_unreachable("non-canonical type should be impossible!");
7897#define DEPENDENT_TYPE(Class, Base) \
7898 case Type::Class: \
7899 llvm_unreachable( \
7900 "dependent types aren't supported in the constant evaluator!");
7901#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7902 case Type::Class: \
7903 llvm_unreachable("either dependent or not canonical!");
7904#include "clang/AST/TypeNodes.inc"
7905 }
7906 llvm_unreachable("Unhandled Type::TypeClass");
7907 }
7908
7909public:
7910 // Pull out a full value of type DstType.
7911 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7912 const CastExpr *BCE) {
7913 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7914 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7915 }
7916};
7917
7918static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7919 QualType Ty, EvalInfo *Info,
7920 const ASTContext &Ctx,
7921 bool CheckingDest) {
7922 Ty = Ty.getCanonicalType();
7923
7924 auto diag = [&](int Reason) {
7925 if (Info)
7926 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7927 << CheckingDest << (Reason == 4) << Reason;
7928 return false;
7929 };
7930 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7931 if (Info)
7932 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7933 << NoteTy << Construct << Ty;
7934 return false;
7935 };
7936
7937 if (Ty->isUnionType())
7938 return diag(0);
7939 if (Ty->isPointerType())
7940 return diag(1);
7941 if (Ty->isMemberPointerType())
7942 return diag(2);
7943 if (Ty.isVolatileQualified())
7944 return diag(3);
7945
7946 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7947 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7948 for (CXXBaseSpecifier &BS : CXXRD->bases())
7949 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7950 CheckingDest))
7951 return note(1, BS.getType(), BS.getBeginLoc());
7952 }
7953 for (FieldDecl *FD : Record->fields()) {
7954 if (FD->getType()->isReferenceType())
7955 return diag(4);
7956 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7957 CheckingDest))
7958 return note(0, FD->getType(), FD->getBeginLoc());
7959 }
7960 }
7961
7962 if (Ty->isArrayType() &&
7963 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7964 Info, Ctx, CheckingDest))
7965 return false;
7966
7967 if (const auto *VTy = Ty->getAs<VectorType>()) {
7968 QualType EltTy = VTy->getElementType();
7969 unsigned NElts = VTy->getNumElements();
7970 unsigned EltSize =
7971 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
7972
7973 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7974 // The vector's size in bits is not a multiple of the target's byte size,
7975 // so its layout is unspecified. For now, we'll simply treat these cases
7976 // as unsupported (this should only be possible with OpenCL bool vectors
7977 // whose element count isn't a multiple of the byte size).
7978 if (Info)
7979 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7980 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7981 return false;
7982 }
7983
7984 if (EltTy->isRealFloatingType() &&
7985 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7986 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7987 // by both clang and LLVM, so for now we won't allow bit_casts involving
7988 // it in a constexpr context.
7989 if (Info)
7990 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7991 << EltTy;
7992 return false;
7993 }
7994 }
7995
7996 return true;
7997}
7998
7999static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8000 const ASTContext &Ctx,
8001 const CastExpr *BCE) {
8002 bool DestOK = checkBitCastConstexprEligibilityType(
8003 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8004 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8005 BCE->getBeginLoc(),
8006 BCE->getSubExpr()->getType(), Info, Ctx, false);
8007 return SourceOK;
8008}
8009
8010static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8011 const APValue &SourceRValue,
8012 const CastExpr *BCE) {
8013 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8014 "no host or target supports non 8-bit chars");
8015
8016 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8017 return false;
8018
8019 // Read out SourceValue into a char buffer.
8020 std::optional<BitCastBuffer> Buffer =
8021 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8022 if (!Buffer)
8023 return false;
8024
8025 // Write out the buffer into a new APValue.
8026 std::optional<APValue> MaybeDestValue =
8027 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8028 if (!MaybeDestValue)
8029 return false;
8030
8031 DestValue = std::move(*MaybeDestValue);
8032 return true;
8033}
8034
8035static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8036 APValue &SourceValue,
8037 const CastExpr *BCE) {
8038 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8039 "no host or target supports non 8-bit chars");
8040 assert(SourceValue.isLValue() &&
8041 "LValueToRValueBitcast requires an lvalue operand!");
8042
8043 LValue SourceLValue;
8044 APValue SourceRValue;
8045 SourceLValue.setFrom(Info.Ctx, SourceValue);
8047 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8048 SourceRValue, /*WantObjectRepresentation=*/true))
8049 return false;
8050
8051 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8052}
8053
8054template <class Derived>
8055class ExprEvaluatorBase
8056 : public ConstStmtVisitor<Derived, bool> {
8057private:
8058 Derived &getDerived() { return static_cast<Derived&>(*this); }
8059 bool DerivedSuccess(const APValue &V, const Expr *E) {
8060 return getDerived().Success(V, E);
8061 }
8062 bool DerivedZeroInitialization(const Expr *E) {
8063 return getDerived().ZeroInitialization(E);
8064 }
8065
8066 // Check whether a conditional operator with a non-constant condition is a
8067 // potential constant expression. If neither arm is a potential constant
8068 // expression, then the conditional operator is not either.
8069 template<typename ConditionalOperator>
8070 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8071 assert(Info.checkingPotentialConstantExpression());
8072
8073 // Speculatively evaluate both arms.
8075 {
8076 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8077 StmtVisitorTy::Visit(E->getFalseExpr());
8078 if (Diag.empty())
8079 return;
8080 }
8081
8082 {
8083 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8084 Diag.clear();
8085 StmtVisitorTy::Visit(E->getTrueExpr());
8086 if (Diag.empty())
8087 return;
8088 }
8089
8090 Error(E, diag::note_constexpr_conditional_never_const);
8091 }
8092
8093
8094 template<typename ConditionalOperator>
8095 bool HandleConditionalOperator(const ConditionalOperator *E) {
8096 bool BoolResult;
8097 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8098 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8099 CheckPotentialConstantConditional(E);
8100 return false;
8101 }
8102 if (Info.noteFailure()) {
8103 StmtVisitorTy::Visit(E->getTrueExpr());
8104 StmtVisitorTy::Visit(E->getFalseExpr());
8105 }
8106 return false;
8107 }
8108
8109 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8110 return StmtVisitorTy::Visit(EvalExpr);
8111 }
8112
8113protected:
8114 EvalInfo &Info;
8115 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8116 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8117
8118 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8119 return Info.CCEDiag(E, D);
8120 }
8121
8122 bool ZeroInitialization(const Expr *E) { return Error(E); }
8123
8124 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8125 unsigned BuiltinOp = E->getBuiltinCallee();
8126 return BuiltinOp != 0 &&
8127 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8128 }
8129
8130public:
8131 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8132
8133 EvalInfo &getEvalInfo() { return Info; }
8134
8135 /// Report an evaluation error. This should only be called when an error is
8136 /// first discovered. When propagating an error, just return false.
8137 bool Error(const Expr *E, diag::kind D) {
8138 Info.FFDiag(E, D) << E->getSourceRange();
8139 return false;
8140 }
8141 bool Error(const Expr *E) {
8142 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8143 }
8144
8145 bool VisitStmt(const Stmt *) {
8146 llvm_unreachable("Expression evaluator should not be called on stmts");
8147 }
8148 bool VisitExpr(const Expr *E) {
8149 return Error(E);
8150 }
8151
8152 bool VisitEmbedExpr(const EmbedExpr *E) {
8153 const auto It = E->begin();
8154 return StmtVisitorTy::Visit(*It);
8155 }
8156
8157 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8158 return StmtVisitorTy::Visit(E->getFunctionName());
8159 }
8160 bool VisitConstantExpr(const ConstantExpr *E) {
8161 if (E->hasAPValueResult())
8162 return DerivedSuccess(E->getAPValueResult(), E);
8163
8164 return StmtVisitorTy::Visit(E->getSubExpr());
8165 }
8166
8167 bool VisitParenExpr(const ParenExpr *E)
8168 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8169 bool VisitUnaryExtension(const UnaryOperator *E)
8170 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8171 bool VisitUnaryPlus(const UnaryOperator *E)
8172 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8173 bool VisitChooseExpr(const ChooseExpr *E)
8174 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8175 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8176 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8177 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8178 { return StmtVisitorTy::Visit(E->getReplacement()); }
8179 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8180 TempVersionRAII RAII(*Info.CurrentCall);
8181 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8182 return StmtVisitorTy::Visit(E->getExpr());
8183 }
8184 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8185 TempVersionRAII RAII(*Info.CurrentCall);
8186 // The initializer may not have been parsed yet, or might be erroneous.
8187 if (!E->getExpr())
8188 return Error(E);
8189 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8190 return StmtVisitorTy::Visit(E->getExpr());
8191 }
8192
8193 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8194 FullExpressionRAII Scope(Info);
8195 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8196 }
8197
8198 // Temporaries are registered when created, so we don't care about
8199 // CXXBindTemporaryExpr.
8200 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8201 return StmtVisitorTy::Visit(E->getSubExpr());
8202 }
8203
8204 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8205 CCEDiag(E, diag::note_constexpr_invalid_cast)
8206 << diag::ConstexprInvalidCastKind::Reinterpret;
8207 return static_cast<Derived*>(this)->VisitCastExpr(E);
8208 }
8209 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8210 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8211 CCEDiag(E, diag::note_constexpr_invalid_cast)
8212 << diag::ConstexprInvalidCastKind::Dynamic;
8213 return static_cast<Derived*>(this)->VisitCastExpr(E);
8214 }
8215 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8216 return static_cast<Derived*>(this)->VisitCastExpr(E);
8217 }
8218
8219 bool VisitBinaryOperator(const BinaryOperator *E) {
8220 switch (E->getOpcode()) {
8221 default:
8222 return Error(E);
8223
8224 case BO_Comma:
8225 VisitIgnoredValue(E->getLHS());
8226 return StmtVisitorTy::Visit(E->getRHS());
8227
8228 case BO_PtrMemD:
8229 case BO_PtrMemI: {
8230 LValue Obj;
8231 if (!HandleMemberPointerAccess(Info, E, Obj))
8232 return false;
8233 APValue Result;
8234 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8235 return false;
8236 return DerivedSuccess(Result, E);
8237 }
8238 }
8239 }
8240
8241 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8242 return StmtVisitorTy::Visit(E->getSemanticForm());
8243 }
8244
8245 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8246 // Evaluate and cache the common expression. We treat it as a temporary,
8247 // even though it's not quite the same thing.
8248 LValue CommonLV;
8249 if (!Evaluate(Info.CurrentCall->createTemporary(
8250 E->getOpaqueValue(),
8251 getStorageType(Info.Ctx, E->getOpaqueValue()),
8252 ScopeKind::FullExpression, CommonLV),
8253 Info, E->getCommon()))
8254 return false;
8255
8256 return HandleConditionalOperator(E);
8257 }
8258
8259 bool VisitConditionalOperator(const ConditionalOperator *E) {
8260 bool IsBcpCall = false;
8261 // If the condition (ignoring parens) is a __builtin_constant_p call,
8262 // the result is a constant expression if it can be folded without
8263 // side-effects. This is an important GNU extension. See GCC PR38377
8264 // for discussion.
8265 if (const CallExpr *CallCE =
8266 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8267 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8268 IsBcpCall = true;
8269
8270 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8271 // constant expression; we can't check whether it's potentially foldable.
8272 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8273 // it would return 'false' in this mode.
8274 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8275 return false;
8276
8277 FoldConstant Fold(Info, IsBcpCall);
8278 if (!HandleConditionalOperator(E)) {
8279 Fold.keepDiagnostics();
8280 return false;
8281 }
8282
8283 return true;
8284 }
8285
8286 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8287 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8288 Value && !Value->isAbsent())
8289 return DerivedSuccess(*Value, E);
8290
8291 const Expr *Source = E->getSourceExpr();
8292 if (!Source)
8293 return Error(E);
8294 if (Source == E) {
8295 assert(0 && "OpaqueValueExpr recursively refers to itself");
8296 return Error(E);
8297 }
8298 return StmtVisitorTy::Visit(Source);
8299 }
8300
8301 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8302 for (const Expr *SemE : E->semantics()) {
8303 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8304 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8305 // result expression: there could be two different LValues that would
8306 // refer to the same object in that case, and we can't model that.
8307 if (SemE == E->getResultExpr())
8308 return Error(E);
8309
8310 // Unique OVEs get evaluated if and when we encounter them when
8311 // emitting the rest of the semantic form, rather than eagerly.
8312 if (OVE->isUnique())
8313 continue;
8314
8315 LValue LV;
8316 if (!Evaluate(Info.CurrentCall->createTemporary(
8317 OVE, getStorageType(Info.Ctx, OVE),
8318 ScopeKind::FullExpression, LV),
8319 Info, OVE->getSourceExpr()))
8320 return false;
8321 } else if (SemE == E->getResultExpr()) {
8322 if (!StmtVisitorTy::Visit(SemE))
8323 return false;
8324 } else {
8325 if (!EvaluateIgnoredValue(Info, SemE))
8326 return false;
8327 }
8328 }
8329 return true;
8330 }
8331
8332 bool VisitCallExpr(const CallExpr *E) {
8333 APValue Result;
8334 if (!handleCallExpr(E, Result, nullptr))
8335 return false;
8336 return DerivedSuccess(Result, E);
8337 }
8338
8339 bool handleCallExpr(const CallExpr *E, APValue &Result,
8340 const LValue *ResultSlot) {
8341 CallScopeRAII CallScope(Info);
8342
8343 const Expr *Callee = E->getCallee()->IgnoreParens();
8344 QualType CalleeType = Callee->getType();
8345
8346 const FunctionDecl *FD = nullptr;
8347 LValue *This = nullptr, ObjectArg;
8348 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8349 bool HasQualifier = false;
8350
8351 CallRef Call;
8352
8353 // Extract function decl and 'this' pointer from the callee.
8354 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8355 const CXXMethodDecl *Member = nullptr;
8356 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8357 // Explicit bound member calls, such as x.f() or p->g();
8358 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8359 return false;
8360 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8361 if (!Member)
8362 return Error(Callee);
8363 This = &ObjectArg;
8364 HasQualifier = ME->hasQualifier();
8365 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8366 // Indirect bound member calls ('.*' or '->*').
8367 const ValueDecl *D =
8368 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8369 if (!D)
8370 return false;
8371 Member = dyn_cast<CXXMethodDecl>(D);
8372 if (!Member)
8373 return Error(Callee);
8374 This = &ObjectArg;
8375 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8376 if (!Info.getLangOpts().CPlusPlus20)
8377 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8378 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8379 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8380 } else
8381 return Error(Callee);
8382 FD = Member;
8383 } else if (CalleeType->isFunctionPointerType()) {
8384 LValue CalleeLV;
8385 if (!EvaluatePointer(Callee, CalleeLV, Info))
8386 return false;
8387
8388 if (!CalleeLV.getLValueOffset().isZero())
8389 return Error(Callee);
8390 if (CalleeLV.isNullPointer()) {
8391 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8392 << const_cast<Expr *>(Callee);
8393 return false;
8394 }
8395 FD = dyn_cast_or_null<FunctionDecl>(
8396 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8397 if (!FD)
8398 return Error(Callee);
8399 // Don't call function pointers which have been cast to some other type.
8400 // Per DR (no number yet), the caller and callee can differ in noexcept.
8401 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8402 CalleeType->getPointeeType(), FD->getType())) {
8403 return Error(E);
8404 }
8405
8406 // For an (overloaded) assignment expression, evaluate the RHS before the
8407 // LHS.
8408 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8409 if (OCE && OCE->isAssignmentOp()) {
8410 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8411 Call = Info.CurrentCall->createCall(FD);
8412 bool HasThis = false;
8413 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8414 HasThis = MD->isImplicitObjectMemberFunction();
8415 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8416 /*RightToLeft=*/true, &ObjectArg))
8417 return false;
8418 }
8419
8420 // Overloaded operator calls to member functions are represented as normal
8421 // calls with '*this' as the first argument.
8422 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8423 if (MD &&
8424 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8425 // FIXME: When selecting an implicit conversion for an overloaded
8426 // operator delete, we sometimes try to evaluate calls to conversion
8427 // operators without a 'this' parameter!
8428 if (Args.empty())
8429 return Error(E);
8430
8431 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8432 return false;
8433
8434 // If we are calling a static operator, the 'this' argument needs to be
8435 // ignored after being evaluated.
8436 if (MD->isInstance())
8437 This = &ObjectArg;
8438
8439 // If this is syntactically a simple assignment using a trivial
8440 // assignment operator, start the lifetimes of union members as needed,
8441 // per C++20 [class.union]5.
8442 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8443 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8444 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8445 return false;
8446
8447 Args = Args.slice(1);
8448 } else if (MD && MD->isLambdaStaticInvoker()) {
8449 // Map the static invoker for the lambda back to the call operator.
8450 // Conveniently, we don't have to slice out the 'this' argument (as is
8451 // being done for the non-static case), since a static member function
8452 // doesn't have an implicit argument passed in.
8453 const CXXRecordDecl *ClosureClass = MD->getParent();
8454 assert(
8455 ClosureClass->captures().empty() &&
8456 "Number of captures must be zero for conversion to function-ptr");
8457
8458 const CXXMethodDecl *LambdaCallOp =
8459 ClosureClass->getLambdaCallOperator();
8460
8461 // Set 'FD', the function that will be called below, to the call
8462 // operator. If the closure object represents a generic lambda, find
8463 // the corresponding specialization of the call operator.
8464
8465 if (ClosureClass->isGenericLambda()) {
8466 assert(MD->isFunctionTemplateSpecialization() &&
8467 "A generic lambda's static-invoker function must be a "
8468 "template specialization");
8470 FunctionTemplateDecl *CallOpTemplate =
8471 LambdaCallOp->getDescribedFunctionTemplate();
8472 void *InsertPos = nullptr;
8473 FunctionDecl *CorrespondingCallOpSpecialization =
8474 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8475 assert(CorrespondingCallOpSpecialization &&
8476 "We must always have a function call operator specialization "
8477 "that corresponds to our static invoker specialization");
8478 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8479 FD = CorrespondingCallOpSpecialization;
8480 } else
8481 FD = LambdaCallOp;
8483 if (FD->getDeclName().isAnyOperatorNew()) {
8484 LValue Ptr;
8485 if (!HandleOperatorNewCall(Info, E, Ptr))
8486 return false;
8487 Ptr.moveInto(Result);
8488 return CallScope.destroy();
8489 } else {
8490 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8491 }
8492 }
8493 } else
8494 return Error(E);
8495
8496 // Evaluate the arguments now if we've not already done so.
8497 if (!Call) {
8498 Call = Info.CurrentCall->createCall(FD);
8499 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8500 &ObjectArg))
8501 return false;
8502 }
8503
8504 SmallVector<QualType, 4> CovariantAdjustmentPath;
8505 if (This) {
8506 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8507 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8508 // Perform virtual dispatch, if necessary.
8509 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8510 CovariantAdjustmentPath);
8511 if (!FD)
8512 return false;
8513 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8514 // Check that the 'this' pointer points to an object of the right type.
8515 // FIXME: If this is an assignment operator call, we may need to change
8516 // the active union member before we check this.
8517 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8518 return false;
8519 }
8520 }
8521
8522 // Destructor calls are different enough that they have their own codepath.
8523 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8524 assert(This && "no 'this' pointer for destructor call");
8525 return HandleDestruction(Info, E, *This,
8526 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8527 CallScope.destroy();
8528 }
8529
8530 const FunctionDecl *Definition = nullptr;
8531 Stmt *Body = FD->getBody(Definition);
8533
8534 // Treat the object argument as `this` when evaluating defaulted
8535 // special menmber functions
8537 This = &ObjectArg;
8538
8539 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8540 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8541 Result, ResultSlot))
8542 return false;
8543
8544 if (!CovariantAdjustmentPath.empty() &&
8545 !HandleCovariantReturnAdjustment(Info, E, Result,
8546 CovariantAdjustmentPath))
8547 return false;
8548
8549 return CallScope.destroy();
8550 }
8551
8552 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8553 return StmtVisitorTy::Visit(E->getInitializer());
8554 }
8555 bool VisitInitListExpr(const InitListExpr *E) {
8556 if (E->getNumInits() == 0)
8557 return DerivedZeroInitialization(E);
8558 if (E->getNumInits() == 1)
8559 return StmtVisitorTy::Visit(E->getInit(0));
8560 return Error(E);
8561 }
8562 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8563 return DerivedZeroInitialization(E);
8564 }
8565 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8566 return DerivedZeroInitialization(E);
8567 }
8568 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8569 return DerivedZeroInitialization(E);
8570 }
8571
8572 /// A member expression where the object is a prvalue is itself a prvalue.
8573 bool VisitMemberExpr(const MemberExpr *E) {
8574 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8575 "missing temporary materialization conversion");
8576 assert(!E->isArrow() && "missing call to bound member function?");
8577
8578 APValue Val;
8579 if (!Evaluate(Val, Info, E->getBase()))
8580 return false;
8581
8582 QualType BaseTy = E->getBase()->getType();
8583
8584 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8585 if (!FD) return Error(E);
8586 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8587 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8588 FD->getParent()->getCanonicalDecl() &&
8589 "record / field mismatch");
8590
8591 // Note: there is no lvalue base here. But this case should only ever
8592 // happen in C or in C++98, where we cannot be evaluating a constexpr
8593 // constructor, which is the only case the base matters.
8594 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8595 SubobjectDesignator Designator(BaseTy);
8596 Designator.addDeclUnchecked(FD);
8597
8598 APValue Result;
8599 return extractSubobject(Info, E, Obj, Designator, Result) &&
8600 DerivedSuccess(Result, E);
8601 }
8602
8603 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8604 APValue Val;
8605 if (!Evaluate(Val, Info, E->getBase()))
8606 return false;
8607
8608 if (Val.isVector()) {
8610 E->getEncodedElementAccess(Indices);
8611 if (Indices.size() == 1) {
8612 // Return scalar.
8613 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8614 } else {
8615 // Construct new APValue vector.
8617 for (unsigned I = 0; I < Indices.size(); ++I) {
8618 Elts.push_back(Val.getVectorElt(Indices[I]));
8619 }
8620 APValue VecResult(Elts.data(), Indices.size());
8621 return DerivedSuccess(VecResult, E);
8622 }
8623 }
8624
8625 return false;
8626 }
8627
8628 bool VisitCastExpr(const CastExpr *E) {
8629 switch (E->getCastKind()) {
8630 default:
8631 break;
8632
8633 case CK_AtomicToNonAtomic: {
8634 APValue AtomicVal;
8635 // This does not need to be done in place even for class/array types:
8636 // atomic-to-non-atomic conversion implies copying the object
8637 // representation.
8638 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8639 return false;
8640 return DerivedSuccess(AtomicVal, E);
8641 }
8642
8643 case CK_NoOp:
8644 case CK_UserDefinedConversion:
8645 return StmtVisitorTy::Visit(E->getSubExpr());
8646
8647 case CK_LValueToRValue: {
8648 LValue LVal;
8649 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8650 return false;
8651 APValue RVal;
8652 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8653 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8654 LVal, RVal))
8655 return false;
8656 return DerivedSuccess(RVal, E);
8657 }
8658 case CK_LValueToRValueBitCast: {
8659 APValue DestValue, SourceValue;
8660 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8661 return false;
8662 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8663 return false;
8664 return DerivedSuccess(DestValue, E);
8665 }
8666
8667 case CK_AddressSpaceConversion: {
8668 APValue Value;
8669 if (!Evaluate(Value, Info, E->getSubExpr()))
8670 return false;
8671 return DerivedSuccess(Value, E);
8672 }
8673 }
8674
8675 return Error(E);
8676 }
8677
8678 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8679 return VisitUnaryPostIncDec(UO);
8680 }
8681 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8682 return VisitUnaryPostIncDec(UO);
8683 }
8684 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8685 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8686 return Error(UO);
8687
8688 LValue LVal;
8689 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8690 return false;
8691 APValue RVal;
8692 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8693 UO->isIncrementOp(), &RVal))
8694 return false;
8695 return DerivedSuccess(RVal, UO);
8696 }
8697
8698 bool VisitStmtExpr(const StmtExpr *E) {
8699 // We will have checked the full-expressions inside the statement expression
8700 // when they were completed, and don't need to check them again now.
8701 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8702 false);
8703
8704 const CompoundStmt *CS = E->getSubStmt();
8705 if (CS->body_empty())
8706 return true;
8707
8708 BlockScopeRAII Scope(Info);
8710 BE = CS->body_end();
8711 /**/; ++BI) {
8712 if (BI + 1 == BE) {
8713 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8714 if (!FinalExpr) {
8715 Info.FFDiag((*BI)->getBeginLoc(),
8716 diag::note_constexpr_stmt_expr_unsupported);
8717 return false;
8718 }
8719 return this->Visit(FinalExpr) && Scope.destroy();
8720 }
8721
8723 StmtResult Result = { ReturnValue, nullptr };
8724 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8725 if (ESR != ESR_Succeeded) {
8726 // FIXME: If the statement-expression terminated due to 'return',
8727 // 'break', or 'continue', it would be nice to propagate that to
8728 // the outer statement evaluation rather than bailing out.
8729 if (ESR != ESR_Failed)
8730 Info.FFDiag((*BI)->getBeginLoc(),
8731 diag::note_constexpr_stmt_expr_unsupported);
8732 return false;
8733 }
8734 }
8735
8736 llvm_unreachable("Return from function from the loop above.");
8737 }
8738
8739 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8740 return StmtVisitorTy::Visit(E->getSelectedExpr());
8741 }
8742
8743 /// Visit a value which is evaluated, but whose value is ignored.
8744 void VisitIgnoredValue(const Expr *E) {
8745 EvaluateIgnoredValue(Info, E);
8746 }
8747
8748 /// Potentially visit a MemberExpr's base expression.
8749 void VisitIgnoredBaseExpression(const Expr *E) {
8750 // While MSVC doesn't evaluate the base expression, it does diagnose the
8751 // presence of side-effecting behavior.
8752 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8753 return;
8754 VisitIgnoredValue(E);
8755 }
8756};
8757
8758} // namespace
8759
8760//===----------------------------------------------------------------------===//
8761// Common base class for lvalue and temporary evaluation.
8762//===----------------------------------------------------------------------===//
8763namespace {
8764template<class Derived>
8765class LValueExprEvaluatorBase
8766 : public ExprEvaluatorBase<Derived> {
8767protected:
8768 LValue &Result;
8769 bool InvalidBaseOK;
8770 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8771 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8772
8774 Result.set(B);
8775 return true;
8776 }
8777
8778 bool evaluatePointer(const Expr *E, LValue &Result) {
8779 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8780 }
8781
8782public:
8783 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8784 : ExprEvaluatorBaseTy(Info), Result(Result),
8785 InvalidBaseOK(InvalidBaseOK) {}
8786
8787 bool Success(const APValue &V, const Expr *E) {
8788 Result.setFrom(this->Info.Ctx, V);
8789 return true;
8790 }
8791
8792 bool VisitMemberExpr(const MemberExpr *E) {
8793 // Handle non-static data members.
8794 QualType BaseTy;
8795 bool EvalOK;
8796 if (E->isArrow()) {
8797 EvalOK = evaluatePointer(E->getBase(), Result);
8798 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8799 } else if (E->getBase()->isPRValue()) {
8800 assert(E->getBase()->getType()->isRecordType());
8801 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8802 BaseTy = E->getBase()->getType();
8803 } else {
8804 EvalOK = this->Visit(E->getBase());
8805 BaseTy = E->getBase()->getType();
8806 }
8807 if (!EvalOK) {
8808 if (!InvalidBaseOK)
8809 return false;
8810 Result.setInvalid(E);
8811 return true;
8812 }
8813
8814 const ValueDecl *MD = E->getMemberDecl();
8815 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8816 assert(BaseTy->castAsCanonical<RecordType>()->getOriginalDecl() ==
8817 FD->getParent()->getCanonicalDecl() &&
8818 "record / field mismatch");
8819 (void)BaseTy;
8820 if (!HandleLValueMember(this->Info, E, Result, FD))
8821 return false;
8822 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8823 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8824 return false;
8825 } else
8826 return this->Error(E);
8827
8828 if (MD->getType()->isReferenceType()) {
8829 APValue RefValue;
8830 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8831 RefValue))
8832 return false;
8833 return Success(RefValue, E);
8834 }
8835 return true;
8836 }
8837
8838 bool VisitBinaryOperator(const BinaryOperator *E) {
8839 switch (E->getOpcode()) {
8840 default:
8841 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8842
8843 case BO_PtrMemD:
8844 case BO_PtrMemI:
8845 return HandleMemberPointerAccess(this->Info, E, Result);
8846 }
8847 }
8848
8849 bool VisitCastExpr(const CastExpr *E) {
8850 switch (E->getCastKind()) {
8851 default:
8852 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8853
8854 case CK_DerivedToBase:
8855 case CK_UncheckedDerivedToBase:
8856 if (!this->Visit(E->getSubExpr()))
8857 return false;
8858
8859 // Now figure out the necessary offset to add to the base LV to get from
8860 // the derived class to the base class.
8861 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8862 Result);
8863 }
8864 }
8865};
8866}
8867
8868//===----------------------------------------------------------------------===//
8869// LValue Evaluation
8870//
8871// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8872// function designators (in C), decl references to void objects (in C), and
8873// temporaries (if building with -Wno-address-of-temporary).
8874//
8875// LValue evaluation produces values comprising a base expression of one of the
8876// following types:
8877// - Declarations
8878// * VarDecl
8879// * FunctionDecl
8880// - Literals
8881// * CompoundLiteralExpr in C (and in global scope in C++)
8882// * StringLiteral
8883// * PredefinedExpr
8884// * ObjCStringLiteralExpr
8885// * ObjCEncodeExpr
8886// * AddrLabelExpr
8887// * BlockExpr
8888// * CallExpr for a MakeStringConstant builtin
8889// - typeid(T) expressions, as TypeInfoLValues
8890// - Locals and temporaries
8891// * MaterializeTemporaryExpr
8892// * Any Expr, with a CallIndex indicating the function in which the temporary
8893// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8894// from the AST (FIXME).
8895// * A MaterializeTemporaryExpr that has static storage duration, with no
8896// CallIndex, for a lifetime-extended temporary.
8897// * The ConstantExpr that is currently being evaluated during evaluation of an
8898// immediate invocation.
8899// plus an offset in bytes.
8900//===----------------------------------------------------------------------===//
8901namespace {
8902class LValueExprEvaluator
8903 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8904public:
8905 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8906 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8907
8908 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8909 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8910
8911 bool VisitCallExpr(const CallExpr *E);
8912 bool VisitDeclRefExpr(const DeclRefExpr *E);
8913 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8914 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8915 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8916 bool VisitMemberExpr(const MemberExpr *E);
8917 bool VisitStringLiteral(const StringLiteral *E) {
8919 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8920 }
8921 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8922 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8923 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8924 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8925 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8926 bool VisitUnaryDeref(const UnaryOperator *E);
8927 bool VisitUnaryReal(const UnaryOperator *E);
8928 bool VisitUnaryImag(const UnaryOperator *E);
8929 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8930 return VisitUnaryPreIncDec(UO);
8931 }
8932 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8933 return VisitUnaryPreIncDec(UO);
8934 }
8935 bool VisitBinAssign(const BinaryOperator *BO);
8936 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8937
8938 bool VisitCastExpr(const CastExpr *E) {
8939 switch (E->getCastKind()) {
8940 default:
8941 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8942
8943 case CK_LValueBitCast:
8944 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8945 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
8946 << Info.Ctx.getLangOpts().CPlusPlus;
8947 if (!Visit(E->getSubExpr()))
8948 return false;
8949 Result.Designator.setInvalid();
8950 return true;
8951
8952 case CK_BaseToDerived:
8953 if (!Visit(E->getSubExpr()))
8954 return false;
8955 return HandleBaseToDerivedCast(Info, E, Result);
8956
8957 case CK_Dynamic:
8958 if (!Visit(E->getSubExpr()))
8959 return false;
8960 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8961 }
8962 }
8963};
8964} // end anonymous namespace
8965
8966/// Get an lvalue to a field of a lambda's closure type.
8967static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8968 const CXXMethodDecl *MD, const FieldDecl *FD,
8969 bool LValueToRValueConversion) {
8970 // Static lambda function call operators can't have captures. We already
8971 // diagnosed this, so bail out here.
8972 if (MD->isStatic()) {
8973 assert(Info.CurrentCall->This == nullptr &&
8974 "This should not be set for a static call operator");
8975 return false;
8976 }
8977
8978 // Start with 'Result' referring to the complete closure object...
8980 // Self may be passed by reference or by value.
8981 const ParmVarDecl *Self = MD->getParamDecl(0);
8982 if (Self->getType()->isReferenceType()) {
8983 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8984 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
8985 Result.setFrom(Info.Ctx, *RefValue);
8986 } else {
8987 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8988 CallStackFrame *Frame =
8989 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8990 .first;
8991 unsigned Version = Info.CurrentCall->Arguments.Version;
8992 Result.set({VD, Frame->Index, Version});
8993 }
8994 } else
8995 Result = *Info.CurrentCall->This;
8996
8997 // ... then update it to refer to the field of the closure object
8998 // that represents the capture.
8999 if (!HandleLValueMember(Info, E, Result, FD))
9000 return false;
9001
9002 // And if the field is of reference type (or if we captured '*this' by
9003 // reference), update 'Result' to refer to what
9004 // the field refers to.
9005 if (LValueToRValueConversion) {
9006 APValue RVal;
9007 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9008 return false;
9009 Result.setFrom(Info.Ctx, RVal);
9010 }
9011 return true;
9012}
9013
9014/// Evaluate an expression as an lvalue. This can be legitimately called on
9015/// expressions which are not glvalues, in three cases:
9016/// * function designators in C, and
9017/// * "extern void" objects
9018/// * @selector() expressions in Objective-C
9019static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9020 bool InvalidBaseOK) {
9021 assert(!E->isValueDependent());
9022 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9023 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
9024 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9025}
9026
9027bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9028 const ValueDecl *D = E->getDecl();
9029
9030 // If we are within a lambda's call operator, check whether the 'VD' referred
9031 // to within 'E' actually represents a lambda-capture that maps to a
9032 // data-member/field within the closure object, and if so, evaluate to the
9033 // field or what the field refers to.
9034 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9035 E->refersToEnclosingVariableOrCapture()) {
9036 // We don't always have a complete capture-map when checking or inferring if
9037 // the function call operator meets the requirements of a constexpr function
9038 // - but we don't need to evaluate the captures to determine constexprness
9039 // (dcl.constexpr C++17).
9040 if (Info.checkingPotentialConstantExpression())
9041 return false;
9042
9043 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9044 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9045 return HandleLambdaCapture(Info, E, Result, MD, FD,
9046 FD->getType()->isReferenceType());
9047 }
9048 }
9049
9052 return Success(cast<ValueDecl>(D));
9053 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9054 return VisitVarDecl(E, VD);
9055 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9056 return Visit(BD->getBinding());
9057 return Error(E);
9058}
9059
9060bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9061 CallStackFrame *Frame = nullptr;
9062 unsigned Version = 0;
9063 if (VD->hasLocalStorage()) {
9064 // Only if a local variable was declared in the function currently being
9065 // evaluated, do we expect to be able to find its value in the current
9066 // frame. (Otherwise it was likely declared in an enclosing context and
9067 // could either have a valid evaluatable value (for e.g. a constexpr
9068 // variable) or be ill-formed (and trigger an appropriate evaluation
9069 // diagnostic)).
9070 CallStackFrame *CurrFrame = Info.CurrentCall;
9071 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9072 // Function parameters are stored in some caller's frame. (Usually the
9073 // immediate caller, but for an inherited constructor they may be more
9074 // distant.)
9075 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9076 if (CurrFrame->Arguments) {
9077 VD = CurrFrame->Arguments.getOrigParam(PVD);
9078 Frame =
9079 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9080 Version = CurrFrame->Arguments.Version;
9081 }
9082 } else {
9083 Frame = CurrFrame;
9084 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9085 }
9086 }
9087 }
9088
9089 if (!VD->getType()->isReferenceType()) {
9090 if (Frame) {
9091 Result.set({VD, Frame->Index, Version});
9092 return true;
9093 }
9094 return Success(VD);
9095 }
9096
9097 if (!Info.getLangOpts().CPlusPlus11) {
9098 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9099 << VD << VD->getType();
9100 Info.Note(VD->getLocation(), diag::note_declared_at);
9101 }
9102
9103 APValue *V;
9104 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9105 return false;
9106
9107 if (!V) {
9108 Result.set(VD);
9109 Result.AllowConstexprUnknown = true;
9110 return true;
9111 }
9112
9113 return Success(*V, E);
9114}
9115
9116bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9117 if (!IsConstantEvaluatedBuiltinCall(E))
9118 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9119
9120 switch (E->getBuiltinCallee()) {
9121 default:
9122 return false;
9123 case Builtin::BIas_const:
9124 case Builtin::BIforward:
9125 case Builtin::BIforward_like:
9126 case Builtin::BImove:
9127 case Builtin::BImove_if_noexcept:
9128 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9129 return Visit(E->getArg(0));
9130 break;
9131 }
9132
9133 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9134}
9135
9136bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9137 const MaterializeTemporaryExpr *E) {
9138 // Walk through the expression to find the materialized temporary itself.
9141 const Expr *Inner =
9142 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9143
9144 // If we passed any comma operators, evaluate their LHSs.
9145 for (const Expr *E : CommaLHSs)
9146 if (!EvaluateIgnoredValue(Info, E))
9147 return false;
9148
9149 // A materialized temporary with static storage duration can appear within the
9150 // result of a constant expression evaluation, so we need to preserve its
9151 // value for use outside this evaluation.
9152 APValue *Value;
9153 if (E->getStorageDuration() == SD_Static) {
9154 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
9155 return false;
9156 // FIXME: What about SD_Thread?
9157 Value = E->getOrCreateValue(true);
9158 *Value = APValue();
9159 Result.set(E);
9160 } else {
9161 Value = &Info.CurrentCall->createTemporary(
9162 E, Inner->getType(),
9163 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9164 : ScopeKind::Block,
9165 Result);
9166 }
9167
9168 QualType Type = Inner->getType();
9169
9170 // Materialize the temporary itself.
9171 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9172 *Value = APValue();
9173 return false;
9174 }
9175
9176 // Adjust our lvalue to refer to the desired subobject.
9177 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9178 --I;
9179 switch (Adjustments[I].Kind) {
9181 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9182 Type, Result))
9183 return false;
9184 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9185 break;
9186
9188 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9189 return false;
9190 Type = Adjustments[I].Field->getType();
9191 break;
9192
9194 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9195 Adjustments[I].Ptr.RHS))
9196 return false;
9197 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9198 break;
9199 }
9200 }
9201
9202 return true;
9203}
9204
9205bool
9206LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9207 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9208 "lvalue compound literal in c++?");
9209 APValue *Lit;
9210 // If CompountLiteral has static storage, its value can be used outside
9211 // this expression. So evaluate it once and store it in ASTContext.
9212 if (E->hasStaticStorage()) {
9213 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9214 Result.set(E);
9215 // Reset any previously evaluated state, otherwise evaluation below might
9216 // fail.
9217 // FIXME: Should we just re-use the previously evaluated value instead?
9218 *Lit = APValue();
9219 } else {
9220 assert(!Info.getLangOpts().CPlusPlus);
9221 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9222 ScopeKind::Block, Result);
9223 }
9224 // FIXME: Evaluating in place isn't always right. We should figure out how to
9225 // use appropriate evaluation context here, see
9226 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9227 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9228 *Lit = APValue();
9229 return false;
9230 }
9231 return true;
9232}
9233
9234bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9236
9237 if (!E->isPotentiallyEvaluated()) {
9238 if (E->isTypeOperand())
9239 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9240 else
9241 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9242 } else {
9243 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9244 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9245 << E->getExprOperand()->getType()
9246 << E->getExprOperand()->getSourceRange();
9247 }
9248
9249 if (!Visit(E->getExprOperand()))
9250 return false;
9251
9252 std::optional<DynamicType> DynType =
9253 ComputeDynamicType(Info, E, Result, AK_TypeId);
9254 if (!DynType)
9255 return false;
9256
9258 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9259 }
9260
9262}
9263
9264bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9265 return Success(E->getGuidDecl());
9266}
9267
9268bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9269 // Handle static data members.
9270 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9271 VisitIgnoredBaseExpression(E->getBase());
9272 return VisitVarDecl(E, VD);
9273 }
9274
9275 // Handle static member functions.
9276 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9277 if (MD->isStatic()) {
9278 VisitIgnoredBaseExpression(E->getBase());
9279 return Success(MD);
9280 }
9281 }
9282
9283 // Handle non-static data members.
9284 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9285}
9286
9287bool LValueExprEvaluator::VisitExtVectorElementExpr(
9288 const ExtVectorElementExpr *E) {
9289 bool Success = true;
9290
9291 APValue Val;
9292 if (!Evaluate(Val, Info, E->getBase())) {
9293 if (!Info.noteFailure())
9294 return false;
9295 Success = false;
9296 }
9297
9299 E->getEncodedElementAccess(Indices);
9300 // FIXME: support accessing more than one element
9301 if (Indices.size() > 1)
9302 return false;
9303
9304 if (Success) {
9305 Result.setFrom(Info.Ctx, Val);
9306 QualType BaseType = E->getBase()->getType();
9307 if (E->isArrow())
9308 BaseType = BaseType->getPointeeType();
9309 const auto *VT = BaseType->castAs<VectorType>();
9310 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9311 VT->getNumElements(), Indices[0]);
9312 }
9313
9314 return Success;
9315}
9316
9317bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9318 if (E->getBase()->getType()->isSveVLSBuiltinType())
9319 return Error(E);
9320
9321 APSInt Index;
9322 bool Success = true;
9323
9324 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9325 APValue Val;
9326 if (!Evaluate(Val, Info, E->getBase())) {
9327 if (!Info.noteFailure())
9328 return false;
9329 Success = false;
9330 }
9331
9332 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9333 if (!Info.noteFailure())
9334 return false;
9335 Success = false;
9336 }
9337
9338 if (Success) {
9339 Result.setFrom(Info.Ctx, Val);
9340 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9341 VT->getNumElements(), Index.getExtValue());
9342 }
9343
9344 return Success;
9345 }
9346
9347 // C++17's rules require us to evaluate the LHS first, regardless of which
9348 // side is the base.
9349 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9350 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9351 : !EvaluateInteger(SubExpr, Index, Info)) {
9352 if (!Info.noteFailure())
9353 return false;
9354 Success = false;
9355 }
9356 }
9357
9358 return Success &&
9359 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9360}
9361
9362bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9363 bool Success = evaluatePointer(E->getSubExpr(), Result);
9364 // [C++26][expr.unary.op]
9365 // If the operand points to an object or function, the result
9366 // denotes that object or function; otherwise, the behavior is undefined.
9367 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9368 // immediately.
9370 return Success;
9371 return bool(findCompleteObject(Info, E, AK_Dereference, Result,
9372 E->getType())) ||
9373 Info.noteUndefinedBehavior();
9374}
9375
9376bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9377 if (!Visit(E->getSubExpr()))
9378 return false;
9379 // __real is a no-op on scalar lvalues.
9380 if (E->getSubExpr()->getType()->isAnyComplexType())
9381 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9382 return true;
9383}
9384
9385bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9386 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9387 "lvalue __imag__ on scalar?");
9388 if (!Visit(E->getSubExpr()))
9389 return false;
9390 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9391 return true;
9392}
9393
9394bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9395 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9396 return Error(UO);
9397
9398 if (!this->Visit(UO->getSubExpr()))
9399 return false;
9400
9401 return handleIncDec(
9402 this->Info, UO, Result, UO->getSubExpr()->getType(),
9403 UO->isIncrementOp(), nullptr);
9404}
9405
9406bool LValueExprEvaluator::VisitCompoundAssignOperator(
9407 const CompoundAssignOperator *CAO) {
9408 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9409 return Error(CAO);
9410
9411 bool Success = true;
9412
9413 // C++17 onwards require that we evaluate the RHS first.
9414 APValue RHS;
9415 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9416 if (!Info.noteFailure())
9417 return false;
9418 Success = false;
9419 }
9420
9421 // The overall lvalue result is the result of evaluating the LHS.
9422 if (!this->Visit(CAO->getLHS()) || !Success)
9423 return false;
9424
9426 this->Info, CAO,
9427 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9428 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9429}
9430
9431bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9432 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9433 return Error(E);
9434
9435 bool Success = true;
9436
9437 // C++17 onwards require that we evaluate the RHS first.
9438 APValue NewVal;
9439 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9440 if (!Info.noteFailure())
9441 return false;
9442 Success = false;
9443 }
9444
9445 if (!this->Visit(E->getLHS()) || !Success)
9446 return false;
9447
9448 if (Info.getLangOpts().CPlusPlus20 &&
9449 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9450 return false;
9451
9452 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9453 NewVal);
9454}
9455
9456//===----------------------------------------------------------------------===//
9457// Pointer Evaluation
9458//===----------------------------------------------------------------------===//
9459
9460/// Convenience function. LVal's base must be a call to an alloc_size
9461/// function.
9463 const LValue &LVal,
9464 llvm::APInt &Result) {
9465 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9466 "Can't get the size of a non alloc_size function");
9467 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9468 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9469 std::optional<llvm::APInt> Size =
9470 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9471 if (!Size)
9472 return false;
9473
9474 Result = std::move(*Size);
9475 return true;
9476}
9477
9478/// Attempts to evaluate the given LValueBase as the result of a call to
9479/// a function with the alloc_size attribute. If it was possible to do so, this
9480/// function will return true, make Result's Base point to said function call,
9481/// and mark Result's Base as invalid.
9483 LValue &Result) {
9484 if (Base.isNull())
9485 return false;
9486
9487 // Because we do no form of static analysis, we only support const variables.
9488 //
9489 // Additionally, we can't support parameters, nor can we support static
9490 // variables (in the latter case, use-before-assign isn't UB; in the former,
9491 // we have no clue what they'll be assigned to).
9492 const auto *VD =
9493 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9494 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9495 return false;
9496
9497 const Expr *Init = VD->getAnyInitializer();
9498 if (!Init || Init->getType().isNull())
9499 return false;
9500
9501 const Expr *E = Init->IgnoreParens();
9502 if (!tryUnwrapAllocSizeCall(E))
9503 return false;
9504
9505 // Store E instead of E unwrapped so that the type of the LValue's base is
9506 // what the user wanted.
9507 Result.setInvalid(E);
9508
9509 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9510 Result.addUnsizedArray(Info, E, Pointee);
9511 return true;
9512}
9513
9514namespace {
9515class PointerExprEvaluator
9516 : public ExprEvaluatorBase<PointerExprEvaluator> {
9517 LValue &Result;
9518 bool InvalidBaseOK;
9519
9520 bool Success(const Expr *E) {
9521 Result.set(E);
9522 return true;
9523 }
9524
9525 bool evaluateLValue(const Expr *E, LValue &Result) {
9526 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9527 }
9528
9529 bool evaluatePointer(const Expr *E, LValue &Result) {
9530 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9531 }
9532
9533 bool visitNonBuiltinCallExpr(const CallExpr *E);
9534public:
9535
9536 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9537 : ExprEvaluatorBaseTy(info), Result(Result),
9538 InvalidBaseOK(InvalidBaseOK) {}
9539
9540 bool Success(const APValue &V, const Expr *E) {
9541 Result.setFrom(Info.Ctx, V);
9542 return true;
9543 }
9544 bool ZeroInitialization(const Expr *E) {
9545 Result.setNull(Info.Ctx, E->getType());
9546 return true;
9547 }
9548
9549 bool VisitBinaryOperator(const BinaryOperator *E);
9550 bool VisitCastExpr(const CastExpr* E);
9551 bool VisitUnaryAddrOf(const UnaryOperator *E);
9552 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9553 { return Success(E); }
9554 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9555 if (E->isExpressibleAsConstantInitializer())
9556 return Success(E);
9557 if (Info.noteFailure())
9558 EvaluateIgnoredValue(Info, E->getSubExpr());
9559 return Error(E);
9560 }
9561 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9562 { return Success(E); }
9563 bool VisitCallExpr(const CallExpr *E);
9564 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9565 bool VisitBlockExpr(const BlockExpr *E) {
9566 if (!E->getBlockDecl()->hasCaptures())
9567 return Success(E);
9568 return Error(E);
9569 }
9570 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9571 auto DiagnoseInvalidUseOfThis = [&] {
9572 if (Info.getLangOpts().CPlusPlus11)
9573 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9574 else
9575 Info.FFDiag(E);
9576 };
9577
9578 // Can't look at 'this' when checking a potential constant expression.
9579 if (Info.checkingPotentialConstantExpression())
9580 return false;
9581
9582 bool IsExplicitLambda =
9583 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9584 if (!IsExplicitLambda) {
9585 if (!Info.CurrentCall->This) {
9586 DiagnoseInvalidUseOfThis();
9587 return false;
9588 }
9589
9590 Result = *Info.CurrentCall->This;
9591 }
9592
9593 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9594 // Ensure we actually have captured 'this'. If something was wrong with
9595 // 'this' capture, the error would have been previously reported.
9596 // Otherwise we can be inside of a default initialization of an object
9597 // declared by lambda's body, so no need to return false.
9598 if (!Info.CurrentCall->LambdaThisCaptureField) {
9599 if (IsExplicitLambda && !Info.CurrentCall->This) {
9600 DiagnoseInvalidUseOfThis();
9601 return false;
9602 }
9603
9604 return true;
9605 }
9606
9607 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9608 return HandleLambdaCapture(
9609 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9610 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9611 }
9612 return true;
9613 }
9614
9615 bool VisitCXXNewExpr(const CXXNewExpr *E);
9616
9617 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9618 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9619 APValue LValResult = E->EvaluateInContext(
9620 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9621 Result.setFrom(Info.Ctx, LValResult);
9622 return true;
9623 }
9624
9625 bool VisitEmbedExpr(const EmbedExpr *E) {
9626 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9627 return true;
9628 }
9629
9630 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9631 std::string ResultStr = E->ComputeName(Info.Ctx);
9632
9633 QualType CharTy = Info.Ctx.CharTy.withConst();
9634 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9635 ResultStr.size() + 1);
9636 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9637 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9638
9639 StringLiteral *SL =
9640 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9641 /*Pascal*/ false, ArrayTy, E->getLocation());
9642
9643 evaluateLValue(SL, Result);
9644 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9645 return true;
9646 }
9647
9648 // FIXME: Missing: @protocol, @selector
9649};
9650} // end anonymous namespace
9651
9652static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9653 bool InvalidBaseOK) {
9654 assert(!E->isValueDependent());
9655 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9656 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9657}
9658
9659bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9660 if (E->getOpcode() != BO_Add &&
9661 E->getOpcode() != BO_Sub)
9662 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9663
9664 const Expr *PExp = E->getLHS();
9665 const Expr *IExp = E->getRHS();
9666 if (IExp->getType()->isPointerType())
9667 std::swap(PExp, IExp);
9668
9669 bool EvalPtrOK = evaluatePointer(PExp, Result);
9670 if (!EvalPtrOK && !Info.noteFailure())
9671 return false;
9672
9673 llvm::APSInt Offset;
9674 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9675 return false;
9676
9677 if (E->getOpcode() == BO_Sub)
9678 negateAsSigned(Offset);
9679
9680 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9681 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9682}
9683
9684bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9685 return evaluateLValue(E->getSubExpr(), Result);
9686}
9687
9688// Is the provided decl 'std::source_location::current'?
9690 if (!FD)
9691 return false;
9692 const IdentifierInfo *FnII = FD->getIdentifier();
9693 if (!FnII || !FnII->isStr("current"))
9694 return false;
9695
9696 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9697 if (!RD)
9698 return false;
9699
9700 const IdentifierInfo *ClassII = RD->getIdentifier();
9701 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9702}
9703
9704bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9705 const Expr *SubExpr = E->getSubExpr();
9706
9707 switch (E->getCastKind()) {
9708 default:
9709 break;
9710 case CK_BitCast:
9711 case CK_CPointerToObjCPointerCast:
9712 case CK_BlockPointerToObjCPointerCast:
9713 case CK_AnyPointerToBlockPointerCast:
9714 case CK_AddressSpaceConversion:
9715 if (!Visit(SubExpr))
9716 return false;
9717 if (E->getType()->isFunctionPointerType() ||
9718 SubExpr->getType()->isFunctionPointerType()) {
9719 // Casting between two function pointer types, or between a function
9720 // pointer and an object pointer, is always a reinterpret_cast.
9721 CCEDiag(E, diag::note_constexpr_invalid_cast)
9722 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9723 << Info.Ctx.getLangOpts().CPlusPlus;
9724 Result.Designator.setInvalid();
9725 } else if (!E->getType()->isVoidPointerType()) {
9726 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9727 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9728 // also static_casts, but we disallow them as a resolution to DR1312.
9729 //
9730 // In some circumstances, we permit casting from void* to cv1 T*, when the
9731 // actual pointee object is actually a cv2 T.
9732 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9733 !Result.IsNullPtr;
9734 bool VoidPtrCastMaybeOK =
9735 Result.IsNullPtr ||
9736 (HasValidResult &&
9737 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9738 E->getType()->getPointeeType()));
9739 // 1. We'll allow it in std::allocator::allocate, and anything which that
9740 // calls.
9741 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9742 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9743 // We'll allow it in the body of std::source_location::current. GCC's
9744 // implementation had a parameter of type `void*`, and casts from
9745 // that back to `const __impl*` in its body.
9746 if (VoidPtrCastMaybeOK &&
9747 (Info.getStdAllocatorCaller("allocate") ||
9748 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9749 Info.getLangOpts().CPlusPlus26)) {
9750 // Permitted.
9751 } else {
9752 if (SubExpr->getType()->isVoidPointerType() &&
9753 Info.getLangOpts().CPlusPlus) {
9754 if (HasValidResult)
9755 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9756 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9757 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9758 << E->getType()->getPointeeType();
9759 else
9760 CCEDiag(E, diag::note_constexpr_invalid_cast)
9761 << diag::ConstexprInvalidCastKind::CastFrom
9762 << SubExpr->getType();
9763 } else
9764 CCEDiag(E, diag::note_constexpr_invalid_cast)
9765 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9766 << Info.Ctx.getLangOpts().CPlusPlus;
9767 Result.Designator.setInvalid();
9768 }
9769 }
9770 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9771 ZeroInitialization(E);
9772 return true;
9773
9774 case CK_DerivedToBase:
9775 case CK_UncheckedDerivedToBase:
9776 if (!evaluatePointer(E->getSubExpr(), Result))
9777 return false;
9778 if (!Result.Base && Result.Offset.isZero())
9779 return true;
9780
9781 // Now figure out the necessary offset to add to the base LV to get from
9782 // the derived class to the base class.
9783 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9784 castAs<PointerType>()->getPointeeType(),
9785 Result);
9786
9787 case CK_BaseToDerived:
9788 if (!Visit(E->getSubExpr()))
9789 return false;
9790 if (!Result.Base && Result.Offset.isZero())
9791 return true;
9792 return HandleBaseToDerivedCast(Info, E, Result);
9793
9794 case CK_Dynamic:
9795 if (!Visit(E->getSubExpr()))
9796 return false;
9797 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9798
9799 case CK_NullToPointer:
9800 VisitIgnoredValue(E->getSubExpr());
9801 return ZeroInitialization(E);
9802
9803 case CK_IntegralToPointer: {
9804 CCEDiag(E, diag::note_constexpr_invalid_cast)
9805 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9806 << Info.Ctx.getLangOpts().CPlusPlus;
9807
9808 APValue Value;
9809 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9810 break;
9811
9812 if (Value.isInt()) {
9813 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9814 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9815 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
9816 Result.setNull(Info.Ctx, E->getType());
9817 } else {
9818 Result.Base = (Expr *)nullptr;
9819 Result.InvalidBase = false;
9820 Result.Offset = CharUnits::fromQuantity(N);
9821 Result.Designator.setInvalid();
9822 Result.IsNullPtr = false;
9823 }
9824 return true;
9825 } else {
9826 // In rare instances, the value isn't an lvalue.
9827 // For example, when the value is the difference between the addresses of
9828 // two labels. We reject that as a constant expression because we can't
9829 // compute a valid offset to convert into a pointer.
9830 if (!Value.isLValue())
9831 return false;
9832
9833 // Cast is of an lvalue, no need to change value.
9834 Result.setFrom(Info.Ctx, Value);
9835 return true;
9836 }
9837 }
9838
9839 case CK_ArrayToPointerDecay: {
9840 if (SubExpr->isGLValue()) {
9841 if (!evaluateLValue(SubExpr, Result))
9842 return false;
9843 } else {
9844 APValue &Value = Info.CurrentCall->createTemporary(
9845 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9846 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9847 return false;
9848 }
9849 // The result is a pointer to the first element of the array.
9850 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9851 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9852 Result.addArray(Info, E, CAT);
9853 else
9854 Result.addUnsizedArray(Info, E, AT->getElementType());
9855 return true;
9856 }
9857
9858 case CK_FunctionToPointerDecay:
9859 return evaluateLValue(SubExpr, Result);
9860
9861 case CK_LValueToRValue: {
9862 LValue LVal;
9863 if (!evaluateLValue(E->getSubExpr(), LVal))
9864 return false;
9865
9866 APValue RVal;
9867 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9868 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9869 LVal, RVal))
9870 return InvalidBaseOK &&
9871 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9872 return Success(RVal, E);
9873 }
9874 }
9875
9876 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9877}
9878
9880 UnaryExprOrTypeTrait ExprKind) {
9881 // C++ [expr.alignof]p3:
9882 // When alignof is applied to a reference type, the result is the
9883 // alignment of the referenced type.
9884 T = T.getNonReferenceType();
9885
9886 if (T.getQualifiers().hasUnaligned())
9887 return CharUnits::One();
9888
9889 const bool AlignOfReturnsPreferred =
9890 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9891
9892 // __alignof is defined to return the preferred alignment.
9893 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9894 // as well.
9895 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9896 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9897 // alignof and _Alignof are defined to return the ABI alignment.
9898 else if (ExprKind == UETT_AlignOf)
9899 return Ctx.getTypeAlignInChars(T.getTypePtr());
9900 else
9901 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9902}
9903
9905 UnaryExprOrTypeTrait ExprKind) {
9906 E = E->IgnoreParens();
9907
9908 // The kinds of expressions that we have special-case logic here for
9909 // should be kept up to date with the special checks for those
9910 // expressions in Sema.
9911
9912 // alignof decl is always accepted, even if it doesn't make sense: we default
9913 // to 1 in those cases.
9914 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9915 return Ctx.getDeclAlign(DRE->getDecl(),
9916 /*RefAsPointee*/ true);
9917
9918 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9919 return Ctx.getDeclAlign(ME->getMemberDecl(),
9920 /*RefAsPointee*/ true);
9921
9922 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9923}
9924
9925static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9926 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9927 return Info.Ctx.getDeclAlign(VD);
9928 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9929 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9930 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9931}
9932
9933/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9934/// __builtin_is_aligned and __builtin_assume_aligned.
9935static bool getAlignmentArgument(const Expr *E, QualType ForType,
9936 EvalInfo &Info, APSInt &Alignment) {
9937 if (!EvaluateInteger(E, Alignment, Info))
9938 return false;
9939 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9940 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9941 return false;
9942 }
9943 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9944 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9945 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9946 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9947 << MaxValue << ForType << Alignment;
9948 return false;
9949 }
9950 // Ensure both alignment and source value have the same bit width so that we
9951 // don't assert when computing the resulting value.
9952 APSInt ExtAlignment =
9953 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9954 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9955 "Alignment should not be changed by ext/trunc");
9956 Alignment = ExtAlignment;
9957 assert(Alignment.getBitWidth() == SrcWidth);
9958 return true;
9959}
9960
9961// To be clear: this happily visits unsupported builtins. Better name welcomed.
9962bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9963 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9964 return true;
9965
9966 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
9967 return false;
9968
9969 Result.setInvalid(E);
9970 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9971 Result.addUnsizedArray(Info, E, PointeeTy);
9972 return true;
9973}
9974
9975bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9976 if (!IsConstantEvaluatedBuiltinCall(E))
9977 return visitNonBuiltinCallExpr(E);
9978 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9979}
9980
9981// Determine if T is a character type for which we guarantee that
9982// sizeof(T) == 1.
9984 return T->isCharType() || T->isChar8Type();
9985}
9986
9987bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9988 unsigned BuiltinOp) {
9990 return Success(E);
9991
9992 switch (BuiltinOp) {
9993 case Builtin::BIaddressof:
9994 case Builtin::BI__addressof:
9995 case Builtin::BI__builtin_addressof:
9996 return evaluateLValue(E->getArg(0), Result);
9997 case Builtin::BI__builtin_assume_aligned: {
9998 // We need to be very careful here because: if the pointer does not have the
9999 // asserted alignment, then the behavior is undefined, and undefined
10000 // behavior is non-constant.
10001 if (!evaluatePointer(E->getArg(0), Result))
10002 return false;
10003
10004 LValue OffsetResult(Result);
10005 APSInt Alignment;
10006 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10007 Alignment))
10008 return false;
10009 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10010
10011 if (E->getNumArgs() > 2) {
10012 APSInt Offset;
10013 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10014 return false;
10015
10016 int64_t AdditionalOffset = -Offset.getZExtValue();
10017 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10018 }
10019
10020 // If there is a base object, then it must have the correct alignment.
10021 if (OffsetResult.Base) {
10022 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10023
10024 if (BaseAlignment < Align) {
10025 Result.Designator.setInvalid();
10026 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10027 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10028 return false;
10029 }
10030 }
10031
10032 // The offset must also have the correct alignment.
10033 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10034 Result.Designator.setInvalid();
10035
10036 (OffsetResult.Base
10037 ? CCEDiag(E->getArg(0),
10038 diag::note_constexpr_baa_insufficient_alignment)
10039 << 1
10040 : CCEDiag(E->getArg(0),
10041 diag::note_constexpr_baa_value_insufficient_alignment))
10042 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10043 return false;
10044 }
10045
10046 return true;
10047 }
10048 case Builtin::BI__builtin_align_up:
10049 case Builtin::BI__builtin_align_down: {
10050 if (!evaluatePointer(E->getArg(0), Result))
10051 return false;
10052 APSInt Alignment;
10053 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10054 Alignment))
10055 return false;
10056 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10057 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10058 // For align_up/align_down, we can return the same value if the alignment
10059 // is known to be greater or equal to the requested value.
10060 if (PtrAlign.getQuantity() >= Alignment)
10061 return true;
10062
10063 // The alignment could be greater than the minimum at run-time, so we cannot
10064 // infer much about the resulting pointer value. One case is possible:
10065 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10066 // can infer the correct index if the requested alignment is smaller than
10067 // the base alignment so we can perform the computation on the offset.
10068 if (BaseAlignment.getQuantity() >= Alignment) {
10069 assert(Alignment.getBitWidth() <= 64 &&
10070 "Cannot handle > 64-bit address-space");
10071 uint64_t Alignment64 = Alignment.getZExtValue();
10073 BuiltinOp == Builtin::BI__builtin_align_down
10074 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10075 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10076 Result.adjustOffset(NewOffset - Result.Offset);
10077 // TODO: diagnose out-of-bounds values/only allow for arrays?
10078 return true;
10079 }
10080 // Otherwise, we cannot constant-evaluate the result.
10081 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10082 << Alignment;
10083 return false;
10084 }
10085 case Builtin::BI__builtin_operator_new:
10086 return HandleOperatorNewCall(Info, E, Result);
10087 case Builtin::BI__builtin_launder:
10088 return evaluatePointer(E->getArg(0), Result);
10089 case Builtin::BIstrchr:
10090 case Builtin::BIwcschr:
10091 case Builtin::BImemchr:
10092 case Builtin::BIwmemchr:
10093 if (Info.getLangOpts().CPlusPlus11)
10094 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10095 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10096 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10097 else
10098 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10099 [[fallthrough]];
10100 case Builtin::BI__builtin_strchr:
10101 case Builtin::BI__builtin_wcschr:
10102 case Builtin::BI__builtin_memchr:
10103 case Builtin::BI__builtin_char_memchr:
10104 case Builtin::BI__builtin_wmemchr: {
10105 if (!Visit(E->getArg(0)))
10106 return false;
10107 APSInt Desired;
10108 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10109 return false;
10110 uint64_t MaxLength = uint64_t(-1);
10111 if (BuiltinOp != Builtin::BIstrchr &&
10112 BuiltinOp != Builtin::BIwcschr &&
10113 BuiltinOp != Builtin::BI__builtin_strchr &&
10114 BuiltinOp != Builtin::BI__builtin_wcschr) {
10115 APSInt N;
10116 if (!EvaluateInteger(E->getArg(2), N, Info))
10117 return false;
10118 MaxLength = N.getZExtValue();
10119 }
10120 // We cannot find the value if there are no candidates to match against.
10121 if (MaxLength == 0u)
10122 return ZeroInitialization(E);
10123 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10124 Result.Designator.Invalid)
10125 return false;
10126 QualType CharTy = Result.Designator.getType(Info.Ctx);
10127 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10128 BuiltinOp == Builtin::BI__builtin_memchr;
10129 assert(IsRawByte ||
10130 Info.Ctx.hasSameUnqualifiedType(
10131 CharTy, E->getArg(0)->getType()->getPointeeType()));
10132 // Pointers to const void may point to objects of incomplete type.
10133 if (IsRawByte && CharTy->isIncompleteType()) {
10134 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10135 return false;
10136 }
10137 // Give up on byte-oriented matching against multibyte elements.
10138 // FIXME: We can compare the bytes in the correct order.
10139 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10140 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10141 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10142 return false;
10143 }
10144 // Figure out what value we're actually looking for (after converting to
10145 // the corresponding unsigned type if necessary).
10146 uint64_t DesiredVal;
10147 bool StopAtNull = false;
10148 switch (BuiltinOp) {
10149 case Builtin::BIstrchr:
10150 case Builtin::BI__builtin_strchr:
10151 // strchr compares directly to the passed integer, and therefore
10152 // always fails if given an int that is not a char.
10153 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10154 E->getArg(1)->getType(),
10155 Desired),
10156 Desired))
10157 return ZeroInitialization(E);
10158 StopAtNull = true;
10159 [[fallthrough]];
10160 case Builtin::BImemchr:
10161 case Builtin::BI__builtin_memchr:
10162 case Builtin::BI__builtin_char_memchr:
10163 // memchr compares by converting both sides to unsigned char. That's also
10164 // correct for strchr if we get this far (to cope with plain char being
10165 // unsigned in the strchr case).
10166 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10167 break;
10168
10169 case Builtin::BIwcschr:
10170 case Builtin::BI__builtin_wcschr:
10171 StopAtNull = true;
10172 [[fallthrough]];
10173 case Builtin::BIwmemchr:
10174 case Builtin::BI__builtin_wmemchr:
10175 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10176 DesiredVal = Desired.getZExtValue();
10177 break;
10178 }
10179
10180 for (; MaxLength; --MaxLength) {
10181 APValue Char;
10182 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10183 !Char.isInt())
10184 return false;
10185 if (Char.getInt().getZExtValue() == DesiredVal)
10186 return true;
10187 if (StopAtNull && !Char.getInt())
10188 break;
10189 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10190 return false;
10191 }
10192 // Not found: return nullptr.
10193 return ZeroInitialization(E);
10194 }
10195
10196 case Builtin::BImemcpy:
10197 case Builtin::BImemmove:
10198 case Builtin::BIwmemcpy:
10199 case Builtin::BIwmemmove:
10200 if (Info.getLangOpts().CPlusPlus11)
10201 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10202 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10203 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10204 else
10205 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10206 [[fallthrough]];
10207 case Builtin::BI__builtin_memcpy:
10208 case Builtin::BI__builtin_memmove:
10209 case Builtin::BI__builtin_wmemcpy:
10210 case Builtin::BI__builtin_wmemmove: {
10211 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10212 BuiltinOp == Builtin::BIwmemmove ||
10213 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10214 BuiltinOp == Builtin::BI__builtin_wmemmove;
10215 bool Move = BuiltinOp == Builtin::BImemmove ||
10216 BuiltinOp == Builtin::BIwmemmove ||
10217 BuiltinOp == Builtin::BI__builtin_memmove ||
10218 BuiltinOp == Builtin::BI__builtin_wmemmove;
10219
10220 // The result of mem* is the first argument.
10221 if (!Visit(E->getArg(0)))
10222 return false;
10223 LValue Dest = Result;
10224
10225 LValue Src;
10226 if (!EvaluatePointer(E->getArg(1), Src, Info))
10227 return false;
10228
10229 APSInt N;
10230 if (!EvaluateInteger(E->getArg(2), N, Info))
10231 return false;
10232 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10233
10234 // If the size is zero, we treat this as always being a valid no-op.
10235 // (Even if one of the src and dest pointers is null.)
10236 if (!N)
10237 return true;
10238
10239 // Otherwise, if either of the operands is null, we can't proceed. Don't
10240 // try to determine the type of the copied objects, because there aren't
10241 // any.
10242 if (!Src.Base || !Dest.Base) {
10243 APValue Val;
10244 (!Src.Base ? Src : Dest).moveInto(Val);
10245 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10246 << Move << WChar << !!Src.Base
10247 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10248 return false;
10249 }
10250 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10251 return false;
10252
10253 // We require that Src and Dest are both pointers to arrays of
10254 // trivially-copyable type. (For the wide version, the designator will be
10255 // invalid if the designated object is not a wchar_t.)
10256 QualType T = Dest.Designator.getType(Info.Ctx);
10257 QualType SrcT = Src.Designator.getType(Info.Ctx);
10258 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10259 // FIXME: Consider using our bit_cast implementation to support this.
10260 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10261 return false;
10262 }
10263 if (T->isIncompleteType()) {
10264 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10265 return false;
10266 }
10267 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10268 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10269 return false;
10270 }
10271
10272 // Figure out how many T's we're copying.
10273 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10274 if (TSize == 0)
10275 return false;
10276 if (!WChar) {
10277 uint64_t Remainder;
10278 llvm::APInt OrigN = N;
10279 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10280 if (Remainder) {
10281 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10282 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10283 << (unsigned)TSize;
10284 return false;
10285 }
10286 }
10287
10288 // Check that the copying will remain within the arrays, just so that we
10289 // can give a more meaningful diagnostic. This implicitly also checks that
10290 // N fits into 64 bits.
10291 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10292 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10293 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10294 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10295 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10296 << toString(N, 10, /*Signed*/false);
10297 return false;
10298 }
10299 uint64_t NElems = N.getZExtValue();
10300 uint64_t NBytes = NElems * TSize;
10301
10302 // Check for overlap.
10303 int Direction = 1;
10304 if (HasSameBase(Src, Dest)) {
10305 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10306 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10307 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10308 // Dest is inside the source region.
10309 if (!Move) {
10310 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10311 return false;
10312 }
10313 // For memmove and friends, copy backwards.
10314 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10315 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10316 return false;
10317 Direction = -1;
10318 } else if (!Move && SrcOffset >= DestOffset &&
10319 SrcOffset - DestOffset < NBytes) {
10320 // Src is inside the destination region for memcpy: invalid.
10321 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10322 return false;
10323 }
10324 }
10325
10326 while (true) {
10327 APValue Val;
10328 // FIXME: Set WantObjectRepresentation to true if we're copying a
10329 // char-like type?
10330 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10331 !handleAssignment(Info, E, Dest, T, Val))
10332 return false;
10333 // Do not iterate past the last element; if we're copying backwards, that
10334 // might take us off the start of the array.
10335 if (--NElems == 0)
10336 return true;
10337 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10338 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10339 return false;
10340 }
10341 }
10342
10343 default:
10344 return false;
10345 }
10346}
10347
10348static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10349 APValue &Result, const InitListExpr *ILE,
10350 QualType AllocType);
10351static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10352 APValue &Result,
10353 const CXXConstructExpr *CCE,
10354 QualType AllocType);
10355
10356bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10357 if (!Info.getLangOpts().CPlusPlus20)
10358 Info.CCEDiag(E, diag::note_constexpr_new);
10359
10360 // We cannot speculatively evaluate a delete expression.
10361 if (Info.SpeculativeEvaluationDepth)
10362 return false;
10363
10364 FunctionDecl *OperatorNew = E->getOperatorNew();
10365 QualType AllocType = E->getAllocatedType();
10366 QualType TargetType = AllocType;
10367
10368 bool IsNothrow = false;
10369 bool IsPlacement = false;
10370
10371 if (E->getNumPlacementArgs() == 1 &&
10372 E->getPlacementArg(0)->getType()->isNothrowT()) {
10373 // The only new-placement list we support is of the form (std::nothrow).
10374 //
10375 // FIXME: There is no restriction on this, but it's not clear that any
10376 // other form makes any sense. We get here for cases such as:
10377 //
10378 // new (std::align_val_t{N}) X(int)
10379 //
10380 // (which should presumably be valid only if N is a multiple of
10381 // alignof(int), and in any case can't be deallocated unless N is
10382 // alignof(X) and X has new-extended alignment).
10383 LValue Nothrow;
10384 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10385 return false;
10386 IsNothrow = true;
10387 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10388 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10389 (Info.CurrentCall->CanEvalMSConstexpr &&
10390 OperatorNew->hasAttr<MSConstexprAttr>())) {
10391 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10392 return false;
10393 if (Result.Designator.Invalid)
10394 return false;
10395 TargetType = E->getPlacementArg(0)->getType();
10396 IsPlacement = true;
10397 } else {
10398 Info.FFDiag(E, diag::note_constexpr_new_placement)
10399 << /*C++26 feature*/ 1 << E->getSourceRange();
10400 return false;
10401 }
10402 } else if (E->getNumPlacementArgs()) {
10403 Info.FFDiag(E, diag::note_constexpr_new_placement)
10404 << /*Unsupported*/ 0 << E->getSourceRange();
10405 return false;
10406 } else if (!OperatorNew
10407 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10408 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10409 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10410 return false;
10411 }
10412
10413 const Expr *Init = E->getInitializer();
10414 const InitListExpr *ResizedArrayILE = nullptr;
10415 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10416 bool ValueInit = false;
10417
10418 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10419 const Expr *Stripped = *ArraySize;
10420 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10421 Stripped = ICE->getSubExpr())
10422 if (ICE->getCastKind() != CK_NoOp &&
10423 ICE->getCastKind() != CK_IntegralCast)
10424 break;
10425
10426 llvm::APSInt ArrayBound;
10427 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10428 return false;
10429
10430 // C++ [expr.new]p9:
10431 // The expression is erroneous if:
10432 // -- [...] its value before converting to size_t [or] applying the
10433 // second standard conversion sequence is less than zero
10434 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10435 if (IsNothrow)
10436 return ZeroInitialization(E);
10437
10438 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10439 << ArrayBound << (*ArraySize)->getSourceRange();
10440 return false;
10441 }
10442
10443 // -- its value is such that the size of the allocated object would
10444 // exceed the implementation-defined limit
10445 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10447 Info.Ctx, AllocType, ArrayBound),
10448 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10449 if (IsNothrow)
10450 return ZeroInitialization(E);
10451 return false;
10452 }
10453
10454 // -- the new-initializer is a braced-init-list and the number of
10455 // array elements for which initializers are provided [...]
10456 // exceeds the number of elements to initialize
10457 if (!Init) {
10458 // No initialization is performed.
10459 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10460 isa<ImplicitValueInitExpr>(Init)) {
10461 ValueInit = true;
10462 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10463 ResizedArrayCCE = CCE;
10464 } else {
10465 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10466 assert(CAT && "unexpected type for array initializer");
10467
10468 unsigned Bits =
10469 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10470 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10471 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10472 if (InitBound.ugt(AllocBound)) {
10473 if (IsNothrow)
10474 return ZeroInitialization(E);
10475
10476 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10477 << toString(AllocBound, 10, /*Signed=*/false)
10478 << toString(InitBound, 10, /*Signed=*/false)
10479 << (*ArraySize)->getSourceRange();
10480 return false;
10481 }
10482
10483 // If the sizes differ, we must have an initializer list, and we need
10484 // special handling for this case when we initialize.
10485 if (InitBound != AllocBound)
10486 ResizedArrayILE = cast<InitListExpr>(Init);
10487 }
10488
10489 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10490 ArraySizeModifier::Normal, 0);
10491 } else {
10492 assert(!AllocType->isArrayType() &&
10493 "array allocation with non-array new");
10494 }
10495
10496 APValue *Val;
10497 if (IsPlacement) {
10499 struct FindObjectHandler {
10500 EvalInfo &Info;
10501 const Expr *E;
10502 QualType AllocType;
10503 const AccessKinds AccessKind;
10504 APValue *Value;
10505
10506 typedef bool result_type;
10507 bool failed() { return false; }
10508 bool checkConst(QualType QT) {
10509 if (QT.isConstQualified()) {
10510 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10511 return false;
10512 }
10513 return true;
10514 }
10515 bool found(APValue &Subobj, QualType SubobjType) {
10516 if (!checkConst(SubobjType))
10517 return false;
10518 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10519 // old name of the object to be used to name the new object.
10520 unsigned SubobjectSize = 1;
10521 unsigned AllocSize = 1;
10522 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10523 AllocSize = CAT->getZExtSize();
10524 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10525 SubobjectSize = CAT->getZExtSize();
10526 if (SubobjectSize < AllocSize ||
10527 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10528 Info.Ctx.getBaseElementType(AllocType))) {
10529 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10530 << SubobjType << AllocType;
10531 return false;
10532 }
10533 Value = &Subobj;
10534 return true;
10535 }
10536 bool found(APSInt &Value, QualType SubobjType) {
10537 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10538 return false;
10539 }
10540 bool found(APFloat &Value, QualType SubobjType) {
10541 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10542 return false;
10543 }
10544 } Handler = {Info, E, AllocType, AK, nullptr};
10545
10546 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10547 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10548 return false;
10549
10550 Val = Handler.Value;
10551
10552 // [basic.life]p1:
10553 // The lifetime of an object o of type T ends when [...] the storage
10554 // which the object occupies is [...] reused by an object that is not
10555 // nested within o (6.6.2).
10556 *Val = APValue();
10557 } else {
10558 // Perform the allocation and obtain a pointer to the resulting object.
10559 Val = Info.createHeapAlloc(E, AllocType, Result);
10560 if (!Val)
10561 return false;
10562 }
10563
10564 if (ValueInit) {
10565 ImplicitValueInitExpr VIE(AllocType);
10566 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10567 return false;
10568 } else if (ResizedArrayILE) {
10569 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10570 AllocType))
10571 return false;
10572 } else if (ResizedArrayCCE) {
10573 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10574 AllocType))
10575 return false;
10576 } else if (Init) {
10577 if (!EvaluateInPlace(*Val, Info, Result, Init))
10578 return false;
10579 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10580 return false;
10581 }
10582
10583 // Array new returns a pointer to the first element, not a pointer to the
10584 // array.
10585 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10586 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10587
10588 return true;
10589}
10590//===----------------------------------------------------------------------===//
10591// Member Pointer Evaluation
10592//===----------------------------------------------------------------------===//
10593
10594namespace {
10595class MemberPointerExprEvaluator
10596 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10597 MemberPtr &Result;
10598
10599 bool Success(const ValueDecl *D) {
10600 Result = MemberPtr(D);
10601 return true;
10602 }
10603public:
10604
10605 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10606 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10607
10608 bool Success(const APValue &V, const Expr *E) {
10609 Result.setFrom(V);
10610 return true;
10611 }
10612 bool ZeroInitialization(const Expr *E) {
10613 return Success((const ValueDecl*)nullptr);
10614 }
10615
10616 bool VisitCastExpr(const CastExpr *E);
10617 bool VisitUnaryAddrOf(const UnaryOperator *E);
10618};
10619} // end anonymous namespace
10620
10621static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10622 EvalInfo &Info) {
10623 assert(!E->isValueDependent());
10624 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10625 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10626}
10627
10628bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10629 switch (E->getCastKind()) {
10630 default:
10631 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10632
10633 case CK_NullToMemberPointer:
10634 VisitIgnoredValue(E->getSubExpr());
10635 return ZeroInitialization(E);
10636
10637 case CK_BaseToDerivedMemberPointer: {
10638 if (!Visit(E->getSubExpr()))
10639 return false;
10640 if (E->path_empty())
10641 return true;
10642 // Base-to-derived member pointer casts store the path in derived-to-base
10643 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10644 // the wrong end of the derived->base arc, so stagger the path by one class.
10645 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10646 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10647 PathI != PathE; ++PathI) {
10648 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10649 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10650 if (!Result.castToDerived(Derived))
10651 return Error(E);
10652 }
10653 if (!Result.castToDerived(E->getType()
10656 return Error(E);
10657 return true;
10658 }
10659
10660 case CK_DerivedToBaseMemberPointer:
10661 if (!Visit(E->getSubExpr()))
10662 return false;
10663 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10664 PathE = E->path_end(); PathI != PathE; ++PathI) {
10665 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10666 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10667 if (!Result.castToBase(Base))
10668 return Error(E);
10669 }
10670 return true;
10671 }
10672}
10673
10674bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10675 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10676 // member can be formed.
10677 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10678}
10679
10680//===----------------------------------------------------------------------===//
10681// Record Evaluation
10682//===----------------------------------------------------------------------===//
10683
10684namespace {
10685 class RecordExprEvaluator
10686 : public ExprEvaluatorBase<RecordExprEvaluator> {
10687 const LValue &This;
10688 APValue &Result;
10689 public:
10690
10691 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10692 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10693
10694 bool Success(const APValue &V, const Expr *E) {
10695 Result = V;
10696 return true;
10697 }
10698 bool ZeroInitialization(const Expr *E) {
10699 return ZeroInitialization(E, E->getType());
10700 }
10701 bool ZeroInitialization(const Expr *E, QualType T);
10702
10703 bool VisitCallExpr(const CallExpr *E) {
10704 return handleCallExpr(E, Result, &This);
10705 }
10706 bool VisitCastExpr(const CastExpr *E);
10707 bool VisitInitListExpr(const InitListExpr *E);
10708 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10709 return VisitCXXConstructExpr(E, E->getType());
10710 }
10711 bool VisitLambdaExpr(const LambdaExpr *E);
10712 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10713 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10714 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10715 bool VisitBinCmp(const BinaryOperator *E);
10716 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10717 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10718 ArrayRef<Expr *> Args);
10719 };
10720}
10721
10722/// Perform zero-initialization on an object of non-union class type.
10723/// C++11 [dcl.init]p5:
10724/// To zero-initialize an object or reference of type T means:
10725/// [...]
10726/// -- if T is a (possibly cv-qualified) non-union class type,
10727/// each non-static data member and each base-class subobject is
10728/// zero-initialized
10729static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10730 const RecordDecl *RD,
10731 const LValue &This, APValue &Result) {
10732 assert(!RD->isUnion() && "Expected non-union class type");
10733 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10734 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10735 std::distance(RD->field_begin(), RD->field_end()));
10736
10737 if (RD->isInvalidDecl()) return false;
10738 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10739
10740 if (CD) {
10741 unsigned Index = 0;
10743 End = CD->bases_end(); I != End; ++I, ++Index) {
10744 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10745 LValue Subobject = This;
10746 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10747 return false;
10748 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10749 Result.getStructBase(Index)))
10750 return false;
10751 }
10752 }
10753
10754 for (const auto *I : RD->fields()) {
10755 // -- if T is a reference type, no initialization is performed.
10756 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10757 continue;
10758
10759 LValue Subobject = This;
10760 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10761 return false;
10762
10763 ImplicitValueInitExpr VIE(I->getType());
10764 if (!EvaluateInPlace(
10765 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10766 return false;
10767 }
10768
10769 return true;
10770}
10771
10772bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10773 const auto *RD = T->castAsRecordDecl();
10774 if (RD->isInvalidDecl()) return false;
10775 if (RD->isUnion()) {
10776 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10777 // object's first non-static named data member is zero-initialized
10779 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10780 ++I;
10781 if (I == RD->field_end()) {
10782 Result = APValue((const FieldDecl*)nullptr);
10783 return true;
10784 }
10785
10786 LValue Subobject = This;
10787 if (!HandleLValueMember(Info, E, Subobject, *I))
10788 return false;
10789 Result = APValue(*I);
10790 ImplicitValueInitExpr VIE(I->getType());
10791 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10792 }
10793
10794 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10795 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10796 return false;
10797 }
10798
10799 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10800}
10801
10802bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10803 switch (E->getCastKind()) {
10804 default:
10805 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10806
10807 case CK_ConstructorConversion:
10808 return Visit(E->getSubExpr());
10809
10810 case CK_DerivedToBase:
10811 case CK_UncheckedDerivedToBase: {
10812 APValue DerivedObject;
10813 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10814 return false;
10815 if (!DerivedObject.isStruct())
10816 return Error(E->getSubExpr());
10817
10818 // Derived-to-base rvalue conversion: just slice off the derived part.
10819 APValue *Value = &DerivedObject;
10820 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10821 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10822 PathE = E->path_end(); PathI != PathE; ++PathI) {
10823 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10824 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10825 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10826 RD = Base;
10827 }
10828 Result = *Value;
10829 return true;
10830 }
10831 }
10832}
10833
10834bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10835 if (E->isTransparent())
10836 return Visit(E->getInit(0));
10837 return VisitCXXParenListOrInitListExpr(E, E->inits());
10838}
10839
10840bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10841 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10842 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
10843 if (RD->isInvalidDecl()) return false;
10844 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10845 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10846
10847 EvalInfo::EvaluatingConstructorRAII EvalObj(
10848 Info,
10849 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10850 CXXRD && CXXRD->getNumBases());
10851
10852 if (RD->isUnion()) {
10853 const FieldDecl *Field;
10854 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10855 Field = ILE->getInitializedFieldInUnion();
10856 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10857 Field = PLIE->getInitializedFieldInUnion();
10858 } else {
10859 llvm_unreachable(
10860 "Expression is neither an init list nor a C++ paren list");
10861 }
10862
10863 Result = APValue(Field);
10864 if (!Field)
10865 return true;
10866
10867 // If the initializer list for a union does not contain any elements, the
10868 // first element of the union is value-initialized.
10869 // FIXME: The element should be initialized from an initializer list.
10870 // Is this difference ever observable for initializer lists which
10871 // we don't build?
10872 ImplicitValueInitExpr VIE(Field->getType());
10873 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10874
10875 LValue Subobject = This;
10876 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10877 return false;
10878
10879 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10880 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10881 isa<CXXDefaultInitExpr>(InitExpr));
10882
10883 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10884 if (Field->isBitField())
10885 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10886 Field);
10887 return true;
10888 }
10889
10890 return false;
10891 }
10892
10893 if (!Result.hasValue())
10894 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10895 std::distance(RD->field_begin(), RD->field_end()));
10896 unsigned ElementNo = 0;
10897 bool Success = true;
10898
10899 // Initialize base classes.
10900 if (CXXRD && CXXRD->getNumBases()) {
10901 for (const auto &Base : CXXRD->bases()) {
10902 assert(ElementNo < Args.size() && "missing init for base class");
10903 const Expr *Init = Args[ElementNo];
10904
10905 LValue Subobject = This;
10906 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10907 return false;
10908
10909 APValue &FieldVal = Result.getStructBase(ElementNo);
10910 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10911 if (!Info.noteFailure())
10912 return false;
10913 Success = false;
10914 }
10915 ++ElementNo;
10916 }
10917
10918 EvalObj.finishedConstructingBases();
10919 }
10920
10921 // Initialize members.
10922 for (const auto *Field : RD->fields()) {
10923 // Anonymous bit-fields are not considered members of the class for
10924 // purposes of aggregate initialization.
10925 if (Field->isUnnamedBitField())
10926 continue;
10927
10928 LValue Subobject = This;
10929
10930 bool HaveInit = ElementNo < Args.size();
10931
10932 // FIXME: Diagnostics here should point to the end of the initializer
10933 // list, not the start.
10934 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10935 Subobject, Field, &Layout))
10936 return false;
10937
10938 // Perform an implicit value-initialization for members beyond the end of
10939 // the initializer list.
10940 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10941 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10942
10943 if (Field->getType()->isIncompleteArrayType()) {
10944 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10945 if (!CAT->isZeroSize()) {
10946 // Bail out for now. This might sort of "work", but the rest of the
10947 // code isn't really prepared to handle it.
10948 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10949 return false;
10950 }
10951 }
10952 }
10953
10954 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10955 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10956 isa<CXXDefaultInitExpr>(Init));
10957
10958 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10959 if (Field->getType()->isReferenceType()) {
10960 LValue Result;
10961 if (!EvaluateInitForDeclOfReferenceType(Info, Field, Init, Result,
10962 FieldVal)) {
10963 if (!Info.noteFailure())
10964 return false;
10965 Success = false;
10966 }
10967 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10968 (Field->isBitField() &&
10969 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
10970 if (!Info.noteFailure())
10971 return false;
10972 Success = false;
10973 }
10974 }
10975
10976 EvalObj.finishedConstructingFields();
10977
10978 return Success;
10979}
10980
10981bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10982 QualType T) {
10983 // Note that E's type is not necessarily the type of our class here; we might
10984 // be initializing an array element instead.
10985 const CXXConstructorDecl *FD = E->getConstructor();
10986 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10987
10988 bool ZeroInit = E->requiresZeroInitialization();
10989 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10990 if (ZeroInit)
10991 return ZeroInitialization(E, T);
10992
10993 return handleDefaultInitValue(T, Result);
10994 }
10995
10996 const FunctionDecl *Definition = nullptr;
10997 auto Body = FD->getBody(Definition);
10998
10999 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11000 return false;
11001
11002 // Avoid materializing a temporary for an elidable copy/move constructor.
11003 if (E->isElidable() && !ZeroInit) {
11004 // FIXME: This only handles the simplest case, where the source object
11005 // is passed directly as the first argument to the constructor.
11006 // This should also handle stepping though implicit casts and
11007 // and conversion sequences which involve two steps, with a
11008 // conversion operator followed by a converting constructor.
11009 const Expr *SrcObj = E->getArg(0);
11010 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11011 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11012 if (const MaterializeTemporaryExpr *ME =
11013 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11014 return Visit(ME->getSubExpr());
11015 }
11016
11017 if (ZeroInit && !ZeroInitialization(E, T))
11018 return false;
11019
11020 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11021 return HandleConstructorCall(E, This, Args,
11022 cast<CXXConstructorDecl>(Definition), Info,
11023 Result);
11024}
11025
11026bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11027 const CXXInheritedCtorInitExpr *E) {
11028 if (!Info.CurrentCall) {
11029 assert(Info.checkingPotentialConstantExpression());
11030 return false;
11031 }
11032
11033 const CXXConstructorDecl *FD = E->getConstructor();
11034 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11035 return false;
11036
11037 const FunctionDecl *Definition = nullptr;
11038 auto Body = FD->getBody(Definition);
11039
11040 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11041 return false;
11042
11043 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11044 cast<CXXConstructorDecl>(Definition), Info,
11045 Result);
11046}
11047
11048bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11051 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11052
11053 LValue Array;
11054 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11055 return false;
11056
11057 assert(ArrayType && "unexpected type for array initializer");
11058
11059 // Get a pointer to the first element of the array.
11060 Array.addArray(Info, E, ArrayType);
11061
11062 // FIXME: What if the initializer_list type has base classes, etc?
11063 Result = APValue(APValue::UninitStruct(), 0, 2);
11064 Array.moveInto(Result.getStructField(0));
11065
11066 auto *Record = E->getType()->castAsRecordDecl();
11067 RecordDecl::field_iterator Field = Record->field_begin();
11068 assert(Field != Record->field_end() &&
11069 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11071 "Expected std::initializer_list first field to be const E *");
11072 ++Field;
11073 assert(Field != Record->field_end() &&
11074 "Expected std::initializer_list to have two fields");
11075
11076 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11077 // Length.
11078 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11079 } else {
11080 // End pointer.
11081 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11083 "Expected std::initializer_list second field to be const E *");
11084 if (!HandleLValueArrayAdjustment(Info, E, Array,
11086 ArrayType->getZExtSize()))
11087 return false;
11088 Array.moveInto(Result.getStructField(1));
11089 }
11090
11091 assert(++Field == Record->field_end() &&
11092 "Expected std::initializer_list to only have two fields");
11093
11094 return true;
11095}
11096
11097bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11098 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11099 if (ClosureClass->isInvalidDecl())
11100 return false;
11101
11102 const size_t NumFields =
11103 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11104
11105 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11106 E->capture_init_end()) &&
11107 "The number of lambda capture initializers should equal the number of "
11108 "fields within the closure type");
11109
11110 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11111 // Iterate through all the lambda's closure object's fields and initialize
11112 // them.
11113 auto *CaptureInitIt = E->capture_init_begin();
11114 bool Success = true;
11115 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11116 for (const auto *Field : ClosureClass->fields()) {
11117 assert(CaptureInitIt != E->capture_init_end());
11118 // Get the initializer for this field
11119 Expr *const CurFieldInit = *CaptureInitIt++;
11120
11121 // If there is no initializer, either this is a VLA or an error has
11122 // occurred.
11123 if (!CurFieldInit || CurFieldInit->containsErrors())
11124 return Error(E);
11125
11126 LValue Subobject = This;
11127
11128 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11129 return false;
11130
11131 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11132 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11133 if (!Info.keepEvaluatingAfterFailure())
11134 return false;
11135 Success = false;
11136 }
11137 }
11138 return Success;
11139}
11140
11141static bool EvaluateRecord(const Expr *E, const LValue &This,
11142 APValue &Result, EvalInfo &Info) {
11143 assert(!E->isValueDependent());
11144 assert(E->isPRValue() && E->getType()->isRecordType() &&
11145 "can't evaluate expression as a record rvalue");
11146 return RecordExprEvaluator(Info, This, Result).Visit(E);
11147}
11148
11149//===----------------------------------------------------------------------===//
11150// Temporary Evaluation
11151//
11152// Temporaries are represented in the AST as rvalues, but generally behave like
11153// lvalues. The full-object of which the temporary is a subobject is implicitly
11154// materialized so that a reference can bind to it.
11155//===----------------------------------------------------------------------===//
11156namespace {
11157class TemporaryExprEvaluator
11158 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11159public:
11160 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11161 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11162
11163 /// Visit an expression which constructs the value of this temporary.
11164 bool VisitConstructExpr(const Expr *E) {
11165 APValue &Value = Info.CurrentCall->createTemporary(
11166 E, E->getType(), ScopeKind::FullExpression, Result);
11167 return EvaluateInPlace(Value, Info, Result, E);
11168 }
11169
11170 bool VisitCastExpr(const CastExpr *E) {
11171 switch (E->getCastKind()) {
11172 default:
11173 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11174
11175 case CK_ConstructorConversion:
11176 return VisitConstructExpr(E->getSubExpr());
11177 }
11178 }
11179 bool VisitInitListExpr(const InitListExpr *E) {
11180 return VisitConstructExpr(E);
11181 }
11182 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11183 return VisitConstructExpr(E);
11184 }
11185 bool VisitCallExpr(const CallExpr *E) {
11186 return VisitConstructExpr(E);
11187 }
11188 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11189 return VisitConstructExpr(E);
11190 }
11191 bool VisitLambdaExpr(const LambdaExpr *E) {
11192 return VisitConstructExpr(E);
11193 }
11194};
11195} // end anonymous namespace
11196
11197/// Evaluate an expression of record type as a temporary.
11198static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11199 assert(!E->isValueDependent());
11200 assert(E->isPRValue() && E->getType()->isRecordType());
11201 return TemporaryExprEvaluator(Info, Result).Visit(E);
11202}
11203
11204//===----------------------------------------------------------------------===//
11205// Vector Evaluation
11206//===----------------------------------------------------------------------===//
11207
11208namespace {
11209 class VectorExprEvaluator
11210 : public ExprEvaluatorBase<VectorExprEvaluator> {
11211 APValue &Result;
11212 public:
11213
11214 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11215 : ExprEvaluatorBaseTy(info), Result(Result) {}
11216
11217 bool Success(ArrayRef<APValue> V, const Expr *E) {
11218 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11219 // FIXME: remove this APValue copy.
11220 Result = APValue(V.data(), V.size());
11221 return true;
11222 }
11223 bool Success(const APValue &V, const Expr *E) {
11224 assert(V.isVector());
11225 Result = V;
11226 return true;
11227 }
11228 bool ZeroInitialization(const Expr *E);
11229
11230 bool VisitUnaryReal(const UnaryOperator *E)
11231 { return Visit(E->getSubExpr()); }
11232 bool VisitCastExpr(const CastExpr* E);
11233 bool VisitInitListExpr(const InitListExpr *E);
11234 bool VisitUnaryImag(const UnaryOperator *E);
11235 bool VisitBinaryOperator(const BinaryOperator *E);
11236 bool VisitUnaryOperator(const UnaryOperator *E);
11237 bool VisitCallExpr(const CallExpr *E);
11238 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11239 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11240
11241 // FIXME: Missing: conditional operator (for GNU
11242 // conditional select), ExtVectorElementExpr
11243 };
11244} // end anonymous namespace
11245
11246static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11247 assert(E->isPRValue() && E->getType()->isVectorType() &&
11248 "not a vector prvalue");
11249 return VectorExprEvaluator(Info, Result).Visit(E);
11250}
11251
11252static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11253 assert(Val.isVector() && "expected vector APValue");
11254 unsigned NumElts = Val.getVectorLength();
11255
11256 // Each element is one bit, so create an integer with NumElts bits.
11257 llvm::APInt Result(NumElts, 0);
11258
11259 for (unsigned I = 0; I < NumElts; ++I) {
11260 const APValue &Elt = Val.getVectorElt(I);
11261 assert(Elt.isInt() && "expected integer element in bool vector");
11262
11263 if (Elt.getInt().getBoolValue())
11264 Result.setBit(I);
11265 }
11266
11267 return Result;
11268}
11269
11270bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11271 const VectorType *VTy = E->getType()->castAs<VectorType>();
11272 unsigned NElts = VTy->getNumElements();
11273
11274 const Expr *SE = E->getSubExpr();
11275 QualType SETy = SE->getType();
11276
11277 switch (E->getCastKind()) {
11278 case CK_VectorSplat: {
11279 APValue Val = APValue();
11280 if (SETy->isIntegerType()) {
11281 APSInt IntResult;
11282 if (!EvaluateInteger(SE, IntResult, Info))
11283 return false;
11284 Val = APValue(std::move(IntResult));
11285 } else if (SETy->isRealFloatingType()) {
11286 APFloat FloatResult(0.0);
11287 if (!EvaluateFloat(SE, FloatResult, Info))
11288 return false;
11289 Val = APValue(std::move(FloatResult));
11290 } else {
11291 return Error(E);
11292 }
11293
11294 // Splat and create vector APValue.
11295 SmallVector<APValue, 4> Elts(NElts, Val);
11296 return Success(Elts, E);
11297 }
11298 case CK_BitCast: {
11299 APValue SVal;
11300 if (!Evaluate(SVal, Info, SE))
11301 return false;
11302
11303 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11304 // Give up if the input isn't an int, float, or vector. For example, we
11305 // reject "(v4i16)(intptr_t)&a".
11306 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11307 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11308 << Info.Ctx.getLangOpts().CPlusPlus;
11309 return false;
11310 }
11311
11312 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11313 return false;
11314
11315 return true;
11316 }
11317 case CK_HLSLVectorTruncation: {
11318 APValue Val;
11319 SmallVector<APValue, 4> Elements;
11320 if (!EvaluateVector(SE, Val, Info))
11321 return Error(E);
11322 for (unsigned I = 0; I < NElts; I++)
11323 Elements.push_back(Val.getVectorElt(I));
11324 return Success(Elements, E);
11325 }
11326 default:
11327 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11328 }
11329}
11330
11331bool
11332VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11333 const VectorType *VT = E->getType()->castAs<VectorType>();
11334 unsigned NumInits = E->getNumInits();
11335 unsigned NumElements = VT->getNumElements();
11336
11337 QualType EltTy = VT->getElementType();
11338 SmallVector<APValue, 4> Elements;
11339
11340 // MFloat8 type doesn't have constants and thus constant folding
11341 // is impossible.
11342 if (EltTy->isMFloat8Type())
11343 return false;
11344
11345 // The number of initializers can be less than the number of
11346 // vector elements. For OpenCL, this can be due to nested vector
11347 // initialization. For GCC compatibility, missing trailing elements
11348 // should be initialized with zeroes.
11349 unsigned CountInits = 0, CountElts = 0;
11350 while (CountElts < NumElements) {
11351 // Handle nested vector initialization.
11352 if (CountInits < NumInits
11353 && E->getInit(CountInits)->getType()->isVectorType()) {
11354 APValue v;
11355 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11356 return Error(E);
11357 unsigned vlen = v.getVectorLength();
11358 for (unsigned j = 0; j < vlen; j++)
11359 Elements.push_back(v.getVectorElt(j));
11360 CountElts += vlen;
11361 } else if (EltTy->isIntegerType()) {
11362 llvm::APSInt sInt(32);
11363 if (CountInits < NumInits) {
11364 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11365 return false;
11366 } else // trailing integer zero.
11367 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11368 Elements.push_back(APValue(sInt));
11369 CountElts++;
11370 } else {
11371 llvm::APFloat f(0.0);
11372 if (CountInits < NumInits) {
11373 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11374 return false;
11375 } else // trailing float zero.
11376 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11377 Elements.push_back(APValue(f));
11378 CountElts++;
11379 }
11380 CountInits++;
11381 }
11382 return Success(Elements, E);
11383}
11384
11385bool
11386VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11387 const auto *VT = E->getType()->castAs<VectorType>();
11388 QualType EltTy = VT->getElementType();
11389 APValue ZeroElement;
11390 if (EltTy->isIntegerType())
11391 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11392 else
11393 ZeroElement =
11394 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11395
11396 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11397 return Success(Elements, E);
11398}
11399
11400bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11401 VisitIgnoredValue(E->getSubExpr());
11402 return ZeroInitialization(E);
11403}
11404
11405bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11406 BinaryOperatorKind Op = E->getOpcode();
11407 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11408 "Operation not supported on vector types");
11409
11410 if (Op == BO_Comma)
11411 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11412
11413 Expr *LHS = E->getLHS();
11414 Expr *RHS = E->getRHS();
11415
11416 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11417 "Must both be vector types");
11418 // Checking JUST the types are the same would be fine, except shifts don't
11419 // need to have their types be the same (since you always shift by an int).
11420 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11422 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11424 "All operands must be the same size.");
11425
11426 APValue LHSValue;
11427 APValue RHSValue;
11428 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11429 if (!LHSOK && !Info.noteFailure())
11430 return false;
11431 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11432 return false;
11433
11434 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11435 return false;
11436
11437 return Success(LHSValue, E);
11438}
11439
11440static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11441 QualType ResultTy,
11443 APValue Elt) {
11444 switch (Op) {
11445 case UO_Plus:
11446 // Nothing to do here.
11447 return Elt;
11448 case UO_Minus:
11449 if (Elt.getKind() == APValue::Int) {
11450 Elt.getInt().negate();
11451 } else {
11452 assert(Elt.getKind() == APValue::Float &&
11453 "Vector can only be int or float type");
11454 Elt.getFloat().changeSign();
11455 }
11456 return Elt;
11457 case UO_Not:
11458 // This is only valid for integral types anyway, so we don't have to handle
11459 // float here.
11460 assert(Elt.getKind() == APValue::Int &&
11461 "Vector operator ~ can only be int");
11462 Elt.getInt().flipAllBits();
11463 return Elt;
11464 case UO_LNot: {
11465 if (Elt.getKind() == APValue::Int) {
11466 Elt.getInt() = !Elt.getInt();
11467 // operator ! on vectors returns -1 for 'truth', so negate it.
11468 Elt.getInt().negate();
11469 return Elt;
11470 }
11471 assert(Elt.getKind() == APValue::Float &&
11472 "Vector can only be int or float type");
11473 // Float types result in an int of the same size, but -1 for true, or 0 for
11474 // false.
11475 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11476 ResultTy->isUnsignedIntegerType()};
11477 if (Elt.getFloat().isZero())
11478 EltResult.setAllBits();
11479 else
11480 EltResult.clearAllBits();
11481
11482 return APValue{EltResult};
11483 }
11484 default:
11485 // FIXME: Implement the rest of the unary operators.
11486 return std::nullopt;
11487 }
11488}
11489
11490bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11491 Expr *SubExpr = E->getSubExpr();
11492 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11493 // This result element type differs in the case of negating a floating point
11494 // vector, since the result type is the a vector of the equivilant sized
11495 // integer.
11496 const QualType ResultEltTy = VD->getElementType();
11497 UnaryOperatorKind Op = E->getOpcode();
11498
11499 APValue SubExprValue;
11500 if (!Evaluate(SubExprValue, Info, SubExpr))
11501 return false;
11502
11503 // FIXME: This vector evaluator someday needs to be changed to be LValue
11504 // aware/keep LValue information around, rather than dealing with just vector
11505 // types directly. Until then, we cannot handle cases where the operand to
11506 // these unary operators is an LValue. The only case I've been able to see
11507 // cause this is operator++ assigning to a member expression (only valid in
11508 // altivec compilations) in C mode, so this shouldn't limit us too much.
11509 if (SubExprValue.isLValue())
11510 return false;
11511
11512 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11513 "Vector length doesn't match type?");
11514
11515 SmallVector<APValue, 4> ResultElements;
11516 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11517 std::optional<APValue> Elt = handleVectorUnaryOperator(
11518 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11519 if (!Elt)
11520 return false;
11521 ResultElements.push_back(*Elt);
11522 }
11523 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11524}
11525
11526static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11527 const Expr *E, QualType SourceTy,
11528 QualType DestTy, APValue const &Original,
11529 APValue &Result) {
11530 if (SourceTy->isIntegerType()) {
11531 if (DestTy->isRealFloatingType()) {
11532 Result = APValue(APFloat(0.0));
11533 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11534 DestTy, Result.getFloat());
11535 }
11536 if (DestTy->isIntegerType()) {
11537 Result = APValue(
11538 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11539 return true;
11540 }
11541 } else if (SourceTy->isRealFloatingType()) {
11542 if (DestTy->isRealFloatingType()) {
11543 Result = Original;
11544 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11545 Result.getFloat());
11546 }
11547 if (DestTy->isIntegerType()) {
11548 Result = APValue(APSInt());
11549 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11550 DestTy, Result.getInt());
11551 }
11552 }
11553
11554 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11555 << SourceTy << DestTy;
11556 return false;
11557}
11558
11559bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11560 if (!IsConstantEvaluatedBuiltinCall(E))
11561 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11562
11563 switch (E->getBuiltinCallee()) {
11564 default:
11565 return false;
11566 case Builtin::BI__builtin_elementwise_popcount:
11567 case Builtin::BI__builtin_elementwise_bitreverse: {
11568 APValue Source;
11569 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11570 return false;
11571
11572 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11573 unsigned SourceLen = Source.getVectorLength();
11574 SmallVector<APValue, 4> ResultElements;
11575 ResultElements.reserve(SourceLen);
11576
11577 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11578 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11579 switch (E->getBuiltinCallee()) {
11580 case Builtin::BI__builtin_elementwise_popcount:
11581 ResultElements.push_back(APValue(
11582 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11583 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11584 break;
11585 case Builtin::BI__builtin_elementwise_bitreverse:
11586 ResultElements.push_back(
11587 APValue(APSInt(Elt.reverseBits(),
11588 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11589 break;
11590 }
11591 }
11592
11593 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11594 }
11595 case Builtin::BI__builtin_elementwise_abs: {
11596 APValue Source;
11597 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11598 return false;
11599
11600 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11601 unsigned SourceLen = Source.getVectorLength();
11602 SmallVector<APValue, 4> ResultElements;
11603 ResultElements.reserve(SourceLen);
11604
11605 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11606 APValue CurrentEle = Source.getVectorElt(EltNum);
11607 APValue Val = DestEltTy->isFloatingType()
11608 ? APValue(llvm::abs(CurrentEle.getFloat()))
11609 : APValue(APSInt(
11610 CurrentEle.getInt().abs(),
11611 DestEltTy->isUnsignedIntegerOrEnumerationType()));
11612 ResultElements.push_back(Val);
11613 }
11614
11615 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11616 }
11617
11618 case Builtin::BI__builtin_elementwise_add_sat:
11619 case Builtin::BI__builtin_elementwise_sub_sat:
11620 case clang::X86::BI__builtin_ia32_pmulhuw128:
11621 case clang::X86::BI__builtin_ia32_pmulhuw256:
11622 case clang::X86::BI__builtin_ia32_pmulhuw512:
11623 case clang::X86::BI__builtin_ia32_pmulhw128:
11624 case clang::X86::BI__builtin_ia32_pmulhw256:
11625 case clang::X86::BI__builtin_ia32_pmulhw512:
11626 case clang::X86::BI__builtin_ia32_psllv2di:
11627 case clang::X86::BI__builtin_ia32_psllv4di:
11628 case clang::X86::BI__builtin_ia32_psllv4si:
11629 case clang::X86::BI__builtin_ia32_psllv8si:
11630 case clang::X86::BI__builtin_ia32_psrav4si:
11631 case clang::X86::BI__builtin_ia32_psrav8si:
11632 case clang::X86::BI__builtin_ia32_psrlv2di:
11633 case clang::X86::BI__builtin_ia32_psrlv4di:
11634 case clang::X86::BI__builtin_ia32_psrlv4si:
11635 case clang::X86::BI__builtin_ia32_psrlv8si:
11636
11637 case clang::X86::BI__builtin_ia32_psllwi128:
11638 case clang::X86::BI__builtin_ia32_pslldi128:
11639 case clang::X86::BI__builtin_ia32_psllqi128:
11640 case clang::X86::BI__builtin_ia32_psllwi256:
11641 case clang::X86::BI__builtin_ia32_pslldi256:
11642 case clang::X86::BI__builtin_ia32_psllqi256:
11643 case clang::X86::BI__builtin_ia32_psllwi512:
11644 case clang::X86::BI__builtin_ia32_pslldi512:
11645 case clang::X86::BI__builtin_ia32_psllqi512:
11646
11647 case clang::X86::BI__builtin_ia32_psrlwi128:
11648 case clang::X86::BI__builtin_ia32_psrldi128:
11649 case clang::X86::BI__builtin_ia32_psrlqi128:
11650 case clang::X86::BI__builtin_ia32_psrlwi256:
11651 case clang::X86::BI__builtin_ia32_psrldi256:
11652 case clang::X86::BI__builtin_ia32_psrlqi256:
11653 case clang::X86::BI__builtin_ia32_psrlwi512:
11654 case clang::X86::BI__builtin_ia32_psrldi512:
11655 case clang::X86::BI__builtin_ia32_psrlqi512:
11656
11657 case clang::X86::BI__builtin_ia32_psrawi128:
11658 case clang::X86::BI__builtin_ia32_psradi128:
11659 case clang::X86::BI__builtin_ia32_psraqi128:
11660 case clang::X86::BI__builtin_ia32_psrawi256:
11661 case clang::X86::BI__builtin_ia32_psradi256:
11662 case clang::X86::BI__builtin_ia32_psraqi256:
11663 case clang::X86::BI__builtin_ia32_psrawi512:
11664 case clang::X86::BI__builtin_ia32_psradi512:
11665 case clang::X86::BI__builtin_ia32_psraqi512: {
11666
11667 APValue SourceLHS, SourceRHS;
11668 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11669 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11670 return false;
11671
11672 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11673 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
11674 unsigned SourceLen = SourceLHS.getVectorLength();
11675 SmallVector<APValue, 4> ResultElements;
11676 ResultElements.reserve(SourceLen);
11677
11678 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11679 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11680
11681 if (SourceRHS.isInt()) {
11682 const unsigned LaneBitWidth = LHS.getBitWidth();
11683 const unsigned ShiftAmount = SourceRHS.getInt().getZExtValue();
11684
11685 switch (E->getBuiltinCallee()) {
11686 case clang::X86::BI__builtin_ia32_psllwi128:
11687 case clang::X86::BI__builtin_ia32_psllwi256:
11688 case clang::X86::BI__builtin_ia32_psllwi512:
11689 case clang::X86::BI__builtin_ia32_pslldi128:
11690 case clang::X86::BI__builtin_ia32_pslldi256:
11691 case clang::X86::BI__builtin_ia32_pslldi512:
11692 case clang::X86::BI__builtin_ia32_psllqi128:
11693 case clang::X86::BI__builtin_ia32_psllqi256:
11694 case clang::X86::BI__builtin_ia32_psllqi512:
11695 if (ShiftAmount >= LaneBitWidth) {
11696 ResultElements.push_back(
11697 APValue(APSInt(APInt::getZero(LaneBitWidth), DestUnsigned)));
11698 } else {
11699 ResultElements.push_back(
11700 APValue(APSInt(LHS.shl(ShiftAmount), DestUnsigned)));
11701 }
11702 break;
11703 case clang::X86::BI__builtin_ia32_psrlwi128:
11704 case clang::X86::BI__builtin_ia32_psrlwi256:
11705 case clang::X86::BI__builtin_ia32_psrlwi512:
11706 case clang::X86::BI__builtin_ia32_psrldi128:
11707 case clang::X86::BI__builtin_ia32_psrldi256:
11708 case clang::X86::BI__builtin_ia32_psrldi512:
11709 case clang::X86::BI__builtin_ia32_psrlqi128:
11710 case clang::X86::BI__builtin_ia32_psrlqi256:
11711 case clang::X86::BI__builtin_ia32_psrlqi512:
11712 if (ShiftAmount >= LaneBitWidth) {
11713 ResultElements.push_back(
11714 APValue(APSInt(APInt::getZero(LaneBitWidth), DestUnsigned)));
11715 } else {
11716 ResultElements.push_back(
11717 APValue(APSInt(LHS.lshr(ShiftAmount), DestUnsigned)));
11718 }
11719 break;
11720 case clang::X86::BI__builtin_ia32_psrawi128:
11721 case clang::X86::BI__builtin_ia32_psrawi256:
11722 case clang::X86::BI__builtin_ia32_psrawi512:
11723 case clang::X86::BI__builtin_ia32_psradi128:
11724 case clang::X86::BI__builtin_ia32_psradi256:
11725 case clang::X86::BI__builtin_ia32_psradi512:
11726 case clang::X86::BI__builtin_ia32_psraqi128:
11727 case clang::X86::BI__builtin_ia32_psraqi256:
11728 case clang::X86::BI__builtin_ia32_psraqi512:
11729 ResultElements.push_back(
11730 APValue(APSInt(LHS.ashr(std::min(ShiftAmount, LaneBitWidth - 1)),
11731 DestUnsigned)));
11732 break;
11733 default:
11734 llvm_unreachable("Unexpected builtin callee");
11735 }
11736 continue;
11737 }
11738 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11739 switch (E->getBuiltinCallee()) {
11740 case Builtin::BI__builtin_elementwise_add_sat:
11741 ResultElements.push_back(APValue(
11742 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS),
11743 DestUnsigned)));
11744 break;
11745 case Builtin::BI__builtin_elementwise_sub_sat:
11746 ResultElements.push_back(APValue(
11747 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS),
11748 DestUnsigned)));
11749 break;
11750 case clang::X86::BI__builtin_ia32_pmulhuw128:
11751 case clang::X86::BI__builtin_ia32_pmulhuw256:
11752 case clang::X86::BI__builtin_ia32_pmulhuw512:
11753 ResultElements.push_back(APValue(APSInt(llvm::APIntOps::mulhu(LHS, RHS),
11754 /*isUnsigned=*/true)));
11755 break;
11756 case clang::X86::BI__builtin_ia32_pmulhw128:
11757 case clang::X86::BI__builtin_ia32_pmulhw256:
11758 case clang::X86::BI__builtin_ia32_pmulhw512:
11759 ResultElements.push_back(APValue(APSInt(llvm::APIntOps::mulhs(LHS, RHS),
11760 /*isUnsigned=*/false)));
11761 break;
11762 case clang::X86::BI__builtin_ia32_psllv2di:
11763 case clang::X86::BI__builtin_ia32_psllv4di:
11764 case clang::X86::BI__builtin_ia32_psllv4si:
11765 case clang::X86::BI__builtin_ia32_psllv8si:
11766 if (RHS.uge(RHS.getBitWidth())) {
11767 ResultElements.push_back(
11768 APValue(APSInt(APInt::getZero(RHS.getBitWidth()), DestUnsigned)));
11769 break;
11770 }
11771 ResultElements.push_back(
11772 APValue(APSInt(LHS.shl(RHS.getZExtValue()), DestUnsigned)));
11773 break;
11774 case clang::X86::BI__builtin_ia32_psrav4si:
11775 case clang::X86::BI__builtin_ia32_psrav8si:
11776 if (RHS.uge(RHS.getBitWidth())) {
11777 ResultElements.push_back(
11778 APValue(APSInt(LHS.ashr(RHS.getBitWidth() - 1), DestUnsigned)));
11779 break;
11780 }
11781 ResultElements.push_back(
11782 APValue(APSInt(LHS.ashr(RHS.getZExtValue()), DestUnsigned)));
11783 break;
11784 case clang::X86::BI__builtin_ia32_psrlv2di:
11785 case clang::X86::BI__builtin_ia32_psrlv4di:
11786 case clang::X86::BI__builtin_ia32_psrlv4si:
11787 case clang::X86::BI__builtin_ia32_psrlv8si:
11788 if (RHS.uge(RHS.getBitWidth())) {
11789 ResultElements.push_back(
11790 APValue(APSInt(APInt::getZero(RHS.getBitWidth()), DestUnsigned)));
11791 break;
11792 }
11793 ResultElements.push_back(
11794 APValue(APSInt(LHS.lshr(RHS.getZExtValue()), DestUnsigned)));
11795 break;
11796 }
11797 }
11798
11799 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11800 }
11801 case clang::X86::BI__builtin_ia32_pmuldq128:
11802 case clang::X86::BI__builtin_ia32_pmuldq256:
11803 case clang::X86::BI__builtin_ia32_pmuldq512:
11804 case clang::X86::BI__builtin_ia32_pmuludq128:
11805 case clang::X86::BI__builtin_ia32_pmuludq256:
11806 case clang::X86::BI__builtin_ia32_pmuludq512: {
11807 APValue SourceLHS, SourceRHS;
11808 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11809 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11810 return false;
11811
11812 unsigned SourceLen = SourceLHS.getVectorLength();
11813 SmallVector<APValue, 4> ResultElements;
11814 ResultElements.reserve(SourceLen / 2);
11815
11816 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
11817 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11818 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11819
11820 switch (E->getBuiltinCallee()) {
11821 case clang::X86::BI__builtin_ia32_pmuludq128:
11822 case clang::X86::BI__builtin_ia32_pmuludq256:
11823 case clang::X86::BI__builtin_ia32_pmuludq512:
11824 ResultElements.push_back(
11825 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
11826 break;
11827 case clang::X86::BI__builtin_ia32_pmuldq128:
11828 case clang::X86::BI__builtin_ia32_pmuldq256:
11829 case clang::X86::BI__builtin_ia32_pmuldq512:
11830 ResultElements.push_back(
11831 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
11832 break;
11833 }
11834 }
11835
11836 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11837 }
11838 case Builtin::BI__builtin_elementwise_max:
11839 case Builtin::BI__builtin_elementwise_min: {
11840 APValue SourceLHS, SourceRHS;
11841 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11842 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11843 return false;
11844
11845 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11846
11847 if (!DestEltTy->isIntegerType())
11848 return false;
11849
11850 unsigned SourceLen = SourceLHS.getVectorLength();
11851 SmallVector<APValue, 4> ResultElements;
11852 ResultElements.reserve(SourceLen);
11853
11854 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11855 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11856 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11857 switch (E->getBuiltinCallee()) {
11858 case Builtin::BI__builtin_elementwise_max:
11859 ResultElements.push_back(
11860 APValue(APSInt(std::max(LHS, RHS),
11861 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11862 break;
11863 case Builtin::BI__builtin_elementwise_min:
11864 ResultElements.push_back(
11865 APValue(APSInt(std::min(LHS, RHS),
11866 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11867 break;
11868 }
11869 }
11870
11871 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11872 }
11873 case X86::BI__builtin_ia32_selectb_128:
11874 case X86::BI__builtin_ia32_selectb_256:
11875 case X86::BI__builtin_ia32_selectb_512:
11876 case X86::BI__builtin_ia32_selectw_128:
11877 case X86::BI__builtin_ia32_selectw_256:
11878 case X86::BI__builtin_ia32_selectw_512:
11879 case X86::BI__builtin_ia32_selectd_128:
11880 case X86::BI__builtin_ia32_selectd_256:
11881 case X86::BI__builtin_ia32_selectd_512:
11882 case X86::BI__builtin_ia32_selectq_128:
11883 case X86::BI__builtin_ia32_selectq_256:
11884 case X86::BI__builtin_ia32_selectq_512:
11885 case X86::BI__builtin_ia32_selectph_128:
11886 case X86::BI__builtin_ia32_selectph_256:
11887 case X86::BI__builtin_ia32_selectph_512:
11888 case X86::BI__builtin_ia32_selectpbf_128:
11889 case X86::BI__builtin_ia32_selectpbf_256:
11890 case X86::BI__builtin_ia32_selectpbf_512:
11891 case X86::BI__builtin_ia32_selectps_128:
11892 case X86::BI__builtin_ia32_selectps_256:
11893 case X86::BI__builtin_ia32_selectps_512:
11894 case X86::BI__builtin_ia32_selectpd_128:
11895 case X86::BI__builtin_ia32_selectpd_256:
11896 case X86::BI__builtin_ia32_selectpd_512: {
11897 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
11898 APValue SourceMask, SourceLHS, SourceRHS;
11899 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
11900 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
11901 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
11902 return false;
11903
11904 APSInt Mask = SourceMask.getInt();
11905 unsigned SourceLen = SourceLHS.getVectorLength();
11906 SmallVector<APValue, 4> ResultElements;
11907 ResultElements.reserve(SourceLen);
11908
11909 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11910 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
11911 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
11912 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
11913 }
11914
11915 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11916 }
11917 case Builtin::BI__builtin_elementwise_ctlz:
11918 case Builtin::BI__builtin_elementwise_cttz: {
11919 APValue SourceLHS;
11920 std::optional<APValue> Fallback;
11921 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
11922 return false;
11923 if (E->getNumArgs() > 1) {
11924 APValue FallbackTmp;
11925 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
11926 return false;
11927 Fallback = FallbackTmp;
11928 }
11929
11930 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11931 unsigned SourceLen = SourceLHS.getVectorLength();
11932 SmallVector<APValue, 4> ResultElements;
11933 ResultElements.reserve(SourceLen);
11934
11935 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11936 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11937 if (!LHS) {
11938 // Without a fallback, a zero element is undefined
11939 if (!Fallback) {
11940 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
11941 << /*IsTrailing=*/(E->getBuiltinCallee() ==
11942 Builtin::BI__builtin_elementwise_cttz);
11943 return false;
11944 }
11945 ResultElements.push_back(Fallback->getVectorElt(EltNum));
11946 continue;
11947 }
11948 switch (E->getBuiltinCallee()) {
11949 case Builtin::BI__builtin_elementwise_ctlz:
11950 ResultElements.push_back(APValue(
11951 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
11952 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11953 break;
11954 case Builtin::BI__builtin_elementwise_cttz:
11955 ResultElements.push_back(APValue(
11956 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
11957 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11958 break;
11959 }
11960 }
11961
11962 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11963 }
11964
11965 case Builtin::BI__builtin_elementwise_fma: {
11966 APValue SourceX, SourceY, SourceZ;
11967 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
11968 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
11969 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
11970 return false;
11971
11972 unsigned SourceLen = SourceX.getVectorLength();
11973 SmallVector<APValue> ResultElements;
11974 ResultElements.reserve(SourceLen);
11975 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
11976 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11977 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
11978 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
11979 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
11980 APFloat Result(X);
11981 (void)Result.fusedMultiplyAdd(Y, Z, RM);
11982 ResultElements.push_back(APValue(Result));
11983 }
11984 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11985 }
11986 }
11987}
11988
11989bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11990 APValue Source;
11991 QualType SourceVecType = E->getSrcExpr()->getType();
11992 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11993 return false;
11994
11995 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11996 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11997
11998 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11999
12000 auto SourceLen = Source.getVectorLength();
12001 SmallVector<APValue, 4> ResultElements;
12002 ResultElements.reserve(SourceLen);
12003 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12004 APValue Elt;
12005 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
12006 Source.getVectorElt(EltNum), Elt))
12007 return false;
12008 ResultElements.push_back(std::move(Elt));
12009 }
12010
12011 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12012}
12013
12014static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
12015 QualType ElemType, APValue const &VecVal1,
12016 APValue const &VecVal2, unsigned EltNum,
12017 APValue &Result) {
12018 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
12019 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
12020
12021 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
12022 int64_t index = IndexVal.getExtValue();
12023 // The spec says that -1 should be treated as undef for optimizations,
12024 // but in constexpr we'd have to produce an APValue::Indeterminate,
12025 // which is prohibited from being a top-level constant value. Emit a
12026 // diagnostic instead.
12027 if (index == -1) {
12028 Info.FFDiag(
12029 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
12030 << EltNum;
12031 return false;
12032 }
12033
12034 if (index < 0 ||
12035 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
12036 llvm_unreachable("Out of bounds shuffle index");
12037
12038 if (index >= TotalElementsInInputVector1)
12039 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
12040 else
12041 Result = VecVal1.getVectorElt(index);
12042 return true;
12043}
12044
12045bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
12046 APValue VecVal1;
12047 const Expr *Vec1 = E->getExpr(0);
12048 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
12049 return false;
12050 APValue VecVal2;
12051 const Expr *Vec2 = E->getExpr(1);
12052 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
12053 return false;
12054
12055 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
12056 QualType DestElTy = DestVecTy->getElementType();
12057
12058 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
12059
12060 SmallVector<APValue, 4> ResultElements;
12061 ResultElements.reserve(TotalElementsInOutputVector);
12062 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
12063 APValue Elt;
12064 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
12065 return false;
12066 ResultElements.push_back(std::move(Elt));
12067 }
12068
12069 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12070}
12071
12072//===----------------------------------------------------------------------===//
12073// Array Evaluation
12074//===----------------------------------------------------------------------===//
12075
12076namespace {
12077 class ArrayExprEvaluator
12078 : public ExprEvaluatorBase<ArrayExprEvaluator> {
12079 const LValue &This;
12080 APValue &Result;
12081 public:
12082
12083 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
12084 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12085
12086 bool Success(const APValue &V, const Expr *E) {
12087 assert(V.isArray() && "expected array");
12088 Result = V;
12089 return true;
12090 }
12091
12092 bool ZeroInitialization(const Expr *E) {
12093 const ConstantArrayType *CAT =
12094 Info.Ctx.getAsConstantArrayType(E->getType());
12095 if (!CAT) {
12096 if (E->getType()->isIncompleteArrayType()) {
12097 // We can be asked to zero-initialize a flexible array member; this
12098 // is represented as an ImplicitValueInitExpr of incomplete array
12099 // type. In this case, the array has zero elements.
12100 Result = APValue(APValue::UninitArray(), 0, 0);
12101 return true;
12102 }
12103 // FIXME: We could handle VLAs here.
12104 return Error(E);
12105 }
12106
12107 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
12108 if (!Result.hasArrayFiller())
12109 return true;
12110
12111 // Zero-initialize all elements.
12112 LValue Subobject = This;
12113 Subobject.addArray(Info, E, CAT);
12115 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
12116 }
12117
12118 bool VisitCallExpr(const CallExpr *E) {
12119 return handleCallExpr(E, Result, &This);
12120 }
12121 bool VisitInitListExpr(const InitListExpr *E,
12122 QualType AllocType = QualType());
12123 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
12124 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
12125 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
12126 const LValue &Subobject,
12128 bool VisitStringLiteral(const StringLiteral *E,
12129 QualType AllocType = QualType()) {
12130 expandStringLiteral(Info, E, Result, AllocType);
12131 return true;
12132 }
12133 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
12134 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
12135 ArrayRef<Expr *> Args,
12136 const Expr *ArrayFiller,
12137 QualType AllocType = QualType());
12138 };
12139} // end anonymous namespace
12140
12141static bool EvaluateArray(const Expr *E, const LValue &This,
12142 APValue &Result, EvalInfo &Info) {
12143 assert(!E->isValueDependent());
12144 assert(E->isPRValue() && E->getType()->isArrayType() &&
12145 "not an array prvalue");
12146 return ArrayExprEvaluator(Info, This, Result).Visit(E);
12147}
12148
12149static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
12150 APValue &Result, const InitListExpr *ILE,
12151 QualType AllocType) {
12152 assert(!ILE->isValueDependent());
12153 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
12154 "not an array prvalue");
12155 return ArrayExprEvaluator(Info, This, Result)
12156 .VisitInitListExpr(ILE, AllocType);
12157}
12158
12159static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
12160 APValue &Result,
12161 const CXXConstructExpr *CCE,
12162 QualType AllocType) {
12163 assert(!CCE->isValueDependent());
12164 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
12165 "not an array prvalue");
12166 return ArrayExprEvaluator(Info, This, Result)
12167 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
12168}
12169
12170// Return true iff the given array filler may depend on the element index.
12171static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
12172 // For now, just allow non-class value-initialization and initialization
12173 // lists comprised of them.
12174 if (isa<ImplicitValueInitExpr>(FillerExpr))
12175 return false;
12176 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
12177 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
12178 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
12179 return true;
12180 }
12181
12182 if (ILE->hasArrayFiller() &&
12183 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
12184 return true;
12185
12186 return false;
12187 }
12188 return true;
12189}
12190
12191bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
12192 QualType AllocType) {
12193 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12194 AllocType.isNull() ? E->getType() : AllocType);
12195 if (!CAT)
12196 return Error(E);
12197
12198 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
12199 // an appropriately-typed string literal enclosed in braces.
12200 if (E->isStringLiteralInit()) {
12201 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
12202 // FIXME: Support ObjCEncodeExpr here once we support it in
12203 // ArrayExprEvaluator generally.
12204 if (!SL)
12205 return Error(E);
12206 return VisitStringLiteral(SL, AllocType);
12207 }
12208 // Any other transparent list init will need proper handling of the
12209 // AllocType; we can't just recurse to the inner initializer.
12210 assert(!E->isTransparent() &&
12211 "transparent array list initialization is not string literal init?");
12212
12213 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
12214 AllocType);
12215}
12216
12217bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
12218 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
12219 QualType AllocType) {
12220 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
12221 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
12222
12223 bool Success = true;
12224
12225 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
12226 "zero-initialized array shouldn't have any initialized elts");
12227 APValue Filler;
12228 if (Result.isArray() && Result.hasArrayFiller())
12229 Filler = Result.getArrayFiller();
12230
12231 unsigned NumEltsToInit = Args.size();
12232 unsigned NumElts = CAT->getZExtSize();
12233
12234 // If the initializer might depend on the array index, run it for each
12235 // array element.
12236 if (NumEltsToInit != NumElts &&
12237 MaybeElementDependentArrayFiller(ArrayFiller)) {
12238 NumEltsToInit = NumElts;
12239 } else {
12240 for (auto *Init : Args) {
12241 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
12242 NumEltsToInit += EmbedS->getDataElementCount() - 1;
12243 }
12244 if (NumEltsToInit > NumElts)
12245 NumEltsToInit = NumElts;
12246 }
12247
12248 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
12249 << NumEltsToInit << ".\n");
12250
12251 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
12252
12253 // If the array was previously zero-initialized, preserve the
12254 // zero-initialized values.
12255 if (Filler.hasValue()) {
12256 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
12257 Result.getArrayInitializedElt(I) = Filler;
12258 if (Result.hasArrayFiller())
12259 Result.getArrayFiller() = Filler;
12260 }
12261
12262 LValue Subobject = This;
12263 Subobject.addArray(Info, ExprToVisit, CAT);
12264 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
12265 if (Init->isValueDependent())
12266 return EvaluateDependentExpr(Init, Info);
12267
12268 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
12269 Subobject, Init) ||
12270 !HandleLValueArrayAdjustment(Info, Init, Subobject,
12271 CAT->getElementType(), 1)) {
12272 if (!Info.noteFailure())
12273 return false;
12274 Success = false;
12275 }
12276 return true;
12277 };
12278 unsigned ArrayIndex = 0;
12279 QualType DestTy = CAT->getElementType();
12280 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
12281 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
12282 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
12283 if (ArrayIndex >= NumEltsToInit)
12284 break;
12285 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
12286 StringLiteral *SL = EmbedS->getDataStringLiteral();
12287 for (unsigned I = EmbedS->getStartingElementPos(),
12288 N = EmbedS->getDataElementCount();
12289 I != EmbedS->getStartingElementPos() + N; ++I) {
12290 Value = SL->getCodeUnit(I);
12291 if (DestTy->isIntegerType()) {
12292 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
12293 } else {
12294 assert(DestTy->isFloatingType() && "unexpected type");
12295 const FPOptions FPO =
12296 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12297 APFloat FValue(0.0);
12298 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
12299 DestTy, FValue))
12300 return false;
12301 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
12302 }
12303 ArrayIndex++;
12304 }
12305 } else {
12306 if (!Eval(Init, ArrayIndex))
12307 return false;
12308 ++ArrayIndex;
12309 }
12310 }
12311
12312 if (!Result.hasArrayFiller())
12313 return Success;
12314
12315 // If we get here, we have a trivial filler, which we can just evaluate
12316 // once and splat over the rest of the array elements.
12317 assert(ArrayFiller && "no array filler for incomplete init list");
12318 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
12319 ArrayFiller) &&
12320 Success;
12321}
12322
12323bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
12324 LValue CommonLV;
12325 if (E->getCommonExpr() &&
12326 !Evaluate(Info.CurrentCall->createTemporary(
12327 E->getCommonExpr(),
12328 getStorageType(Info.Ctx, E->getCommonExpr()),
12329 ScopeKind::FullExpression, CommonLV),
12330 Info, E->getCommonExpr()->getSourceExpr()))
12331 return false;
12332
12333 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
12334
12335 uint64_t Elements = CAT->getZExtSize();
12336 Result = APValue(APValue::UninitArray(), Elements, Elements);
12337
12338 LValue Subobject = This;
12339 Subobject.addArray(Info, E, CAT);
12340
12341 bool Success = true;
12342 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
12343 // C++ [class.temporary]/5
12344 // There are four contexts in which temporaries are destroyed at a different
12345 // point than the end of the full-expression. [...] The second context is
12346 // when a copy constructor is called to copy an element of an array while
12347 // the entire array is copied [...]. In either case, if the constructor has
12348 // one or more default arguments, the destruction of every temporary created
12349 // in a default argument is sequenced before the construction of the next
12350 // array element, if any.
12351 FullExpressionRAII Scope(Info);
12352
12353 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
12354 Info, Subobject, E->getSubExpr()) ||
12355 !HandleLValueArrayAdjustment(Info, E, Subobject,
12356 CAT->getElementType(), 1)) {
12357 if (!Info.noteFailure())
12358 return false;
12359 Success = false;
12360 }
12361
12362 // Make sure we run the destructors too.
12363 Scope.destroy();
12364 }
12365
12366 return Success;
12367}
12368
12369bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
12370 return VisitCXXConstructExpr(E, This, &Result, E->getType());
12371}
12372
12373bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
12374 const LValue &Subobject,
12375 APValue *Value,
12376 QualType Type) {
12377 bool HadZeroInit = Value->hasValue();
12378
12379 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
12380 unsigned FinalSize = CAT->getZExtSize();
12381
12382 // Preserve the array filler if we had prior zero-initialization.
12383 APValue Filler =
12384 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
12385 : APValue();
12386
12387 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
12388 if (FinalSize == 0)
12389 return true;
12390
12391 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
12392 Info, E->getExprLoc(), E->getConstructor(),
12393 E->requiresZeroInitialization());
12394 LValue ArrayElt = Subobject;
12395 ArrayElt.addArray(Info, E, CAT);
12396 // We do the whole initialization in two passes, first for just one element,
12397 // then for the whole array. It's possible we may find out we can't do const
12398 // init in the first pass, in which case we avoid allocating a potentially
12399 // large array. We don't do more passes because expanding array requires
12400 // copying the data, which is wasteful.
12401 for (const unsigned N : {1u, FinalSize}) {
12402 unsigned OldElts = Value->getArrayInitializedElts();
12403 if (OldElts == N)
12404 break;
12405
12406 // Expand the array to appropriate size.
12407 APValue NewValue(APValue::UninitArray(), N, FinalSize);
12408 for (unsigned I = 0; I < OldElts; ++I)
12409 NewValue.getArrayInitializedElt(I).swap(
12410 Value->getArrayInitializedElt(I));
12411 Value->swap(NewValue);
12412
12413 if (HadZeroInit)
12414 for (unsigned I = OldElts; I < N; ++I)
12415 Value->getArrayInitializedElt(I) = Filler;
12416
12417 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
12418 // If we have a trivial constructor, only evaluate it once and copy
12419 // the result into all the array elements.
12420 APValue &FirstResult = Value->getArrayInitializedElt(0);
12421 for (unsigned I = OldElts; I < FinalSize; ++I)
12422 Value->getArrayInitializedElt(I) = FirstResult;
12423 } else {
12424 for (unsigned I = OldElts; I < N; ++I) {
12425 if (!VisitCXXConstructExpr(E, ArrayElt,
12426 &Value->getArrayInitializedElt(I),
12427 CAT->getElementType()) ||
12428 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
12429 CAT->getElementType(), 1))
12430 return false;
12431 // When checking for const initilization any diagnostic is considered
12432 // an error.
12433 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
12434 !Info.keepEvaluatingAfterFailure())
12435 return false;
12436 }
12437 }
12438 }
12439
12440 return true;
12441 }
12442
12443 if (!Type->isRecordType())
12444 return Error(E);
12445
12446 return RecordExprEvaluator(Info, Subobject, *Value)
12447 .VisitCXXConstructExpr(E, Type);
12448}
12449
12450bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
12451 const CXXParenListInitExpr *E) {
12452 assert(E->getType()->isConstantArrayType() &&
12453 "Expression result is not a constant array type");
12454
12455 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
12456 E->getArrayFiller());
12457}
12458
12459//===----------------------------------------------------------------------===//
12460// Integer Evaluation
12461//
12462// As a GNU extension, we support casting pointers to sufficiently-wide integer
12463// types and back in constant folding. Integer values are thus represented
12464// either as an integer-valued APValue, or as an lvalue-valued APValue.
12465//===----------------------------------------------------------------------===//
12466
12467namespace {
12468class IntExprEvaluator
12469 : public ExprEvaluatorBase<IntExprEvaluator> {
12470 APValue &Result;
12471public:
12472 IntExprEvaluator(EvalInfo &info, APValue &result)
12473 : ExprEvaluatorBaseTy(info), Result(result) {}
12474
12475 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
12476 assert(E->getType()->isIntegralOrEnumerationType() &&
12477 "Invalid evaluation result.");
12478 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
12479 "Invalid evaluation result.");
12480 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12481 "Invalid evaluation result.");
12482 Result = APValue(SI);
12483 return true;
12484 }
12485 bool Success(const llvm::APSInt &SI, const Expr *E) {
12486 return Success(SI, E, Result);
12487 }
12488
12489 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
12490 assert(E->getType()->isIntegralOrEnumerationType() &&
12491 "Invalid evaluation result.");
12492 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12493 "Invalid evaluation result.");
12494 Result = APValue(APSInt(I));
12495 Result.getInt().setIsUnsigned(
12497 return true;
12498 }
12499 bool Success(const llvm::APInt &I, const Expr *E) {
12500 return Success(I, E, Result);
12501 }
12502
12503 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12504 assert(E->getType()->isIntegralOrEnumerationType() &&
12505 "Invalid evaluation result.");
12506 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
12507 return true;
12508 }
12509 bool Success(uint64_t Value, const Expr *E) {
12510 return Success(Value, E, Result);
12511 }
12512
12513 bool Success(CharUnits Size, const Expr *E) {
12514 return Success(Size.getQuantity(), E);
12515 }
12516
12517 bool Success(const APValue &V, const Expr *E) {
12518 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
12519 // pointer allow further evaluation of the value.
12520 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
12521 V.allowConstexprUnknown()) {
12522 Result = V;
12523 return true;
12524 }
12525 return Success(V.getInt(), E);
12526 }
12527
12528 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
12529
12530 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12531 const CallExpr *);
12532
12533 //===--------------------------------------------------------------------===//
12534 // Visitor Methods
12535 //===--------------------------------------------------------------------===//
12536
12537 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12538 return Success(E->getValue(), E);
12539 }
12540 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12541 return Success(E->getValue(), E);
12542 }
12543
12544 bool CheckReferencedDecl(const Expr *E, const Decl *D);
12545 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12546 if (CheckReferencedDecl(E, E->getDecl()))
12547 return true;
12548
12549 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12550 }
12551 bool VisitMemberExpr(const MemberExpr *E) {
12552 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12553 VisitIgnoredBaseExpression(E->getBase());
12554 return true;
12555 }
12556
12557 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12558 }
12559
12560 bool VisitCallExpr(const CallExpr *E);
12561 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12562 bool VisitBinaryOperator(const BinaryOperator *E);
12563 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12564 bool VisitUnaryOperator(const UnaryOperator *E);
12565
12566 bool VisitCastExpr(const CastExpr* E);
12567 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12568
12569 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12570 return Success(E->getValue(), E);
12571 }
12572
12573 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12574 return Success(E->getValue(), E);
12575 }
12576
12577 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12578 if (Info.ArrayInitIndex == uint64_t(-1)) {
12579 // We were asked to evaluate this subexpression independent of the
12580 // enclosing ArrayInitLoopExpr. We can't do that.
12581 Info.FFDiag(E);
12582 return false;
12583 }
12584 return Success(Info.ArrayInitIndex, E);
12585 }
12586
12587 // Note, GNU defines __null as an integer, not a pointer.
12588 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12589 return ZeroInitialization(E);
12590 }
12591
12592 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12593 if (E->isStoredAsBoolean())
12594 return Success(E->getBoolValue(), E);
12595 if (E->getAPValue().isAbsent())
12596 return false;
12597 assert(E->getAPValue().isInt() && "APValue type not supported");
12598 return Success(E->getAPValue().getInt(), E);
12599 }
12600
12601 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12602 return Success(E->getValue(), E);
12603 }
12604
12605 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12606 return Success(E->getValue(), E);
12607 }
12608
12609 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12610 // This should not be evaluated during constant expr evaluation, as it
12611 // should always be in an unevaluated context (the args list of a 'gang' or
12612 // 'tile' clause).
12613 return Error(E);
12614 }
12615
12616 bool VisitUnaryReal(const UnaryOperator *E);
12617 bool VisitUnaryImag(const UnaryOperator *E);
12618
12619 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12620 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12621 bool VisitSourceLocExpr(const SourceLocExpr *E);
12622 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12623 bool VisitRequiresExpr(const RequiresExpr *E);
12624 // FIXME: Missing: array subscript of vector, member of vector
12625};
12626
12627class FixedPointExprEvaluator
12628 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12629 APValue &Result;
12630
12631 public:
12632 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12633 : ExprEvaluatorBaseTy(info), Result(result) {}
12634
12635 bool Success(const llvm::APInt &I, const Expr *E) {
12636 return Success(
12637 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12638 }
12639
12640 bool Success(uint64_t Value, const Expr *E) {
12641 return Success(
12642 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12643 }
12644
12645 bool Success(const APValue &V, const Expr *E) {
12646 return Success(V.getFixedPoint(), E);
12647 }
12648
12649 bool Success(const APFixedPoint &V, const Expr *E) {
12650 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12651 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12652 "Invalid evaluation result.");
12653 Result = APValue(V);
12654 return true;
12655 }
12656
12657 bool ZeroInitialization(const Expr *E) {
12658 return Success(0, E);
12659 }
12660
12661 //===--------------------------------------------------------------------===//
12662 // Visitor Methods
12663 //===--------------------------------------------------------------------===//
12664
12665 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12666 return Success(E->getValue(), E);
12667 }
12668
12669 bool VisitCastExpr(const CastExpr *E);
12670 bool VisitUnaryOperator(const UnaryOperator *E);
12671 bool VisitBinaryOperator(const BinaryOperator *E);
12672};
12673} // end anonymous namespace
12674
12675/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12676/// produce either the integer value or a pointer.
12677///
12678/// GCC has a heinous extension which folds casts between pointer types and
12679/// pointer-sized integral types. We support this by allowing the evaluation of
12680/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12681/// Some simple arithmetic on such values is supported (they are treated much
12682/// like char*).
12683static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12684 EvalInfo &Info) {
12685 assert(!E->isValueDependent());
12686 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12687 return IntExprEvaluator(Info, Result).Visit(E);
12688}
12689
12690static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12691 assert(!E->isValueDependent());
12692 APValue Val;
12693 if (!EvaluateIntegerOrLValue(E, Val, Info))
12694 return false;
12695 if (!Val.isInt()) {
12696 // FIXME: It would be better to produce the diagnostic for casting
12697 // a pointer to an integer.
12698 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12699 return false;
12700 }
12701 Result = Val.getInt();
12702 return true;
12703}
12704
12705bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12706 APValue Evaluated = E->EvaluateInContext(
12707 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12708 return Success(Evaluated, E);
12709}
12710
12711static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12712 EvalInfo &Info) {
12713 assert(!E->isValueDependent());
12714 if (E->getType()->isFixedPointType()) {
12715 APValue Val;
12716 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12717 return false;
12718 if (!Val.isFixedPoint())
12719 return false;
12720
12721 Result = Val.getFixedPoint();
12722 return true;
12723 }
12724 return false;
12725}
12726
12727static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12728 EvalInfo &Info) {
12729 assert(!E->isValueDependent());
12730 if (E->getType()->isIntegerType()) {
12731 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12732 APSInt Val;
12733 if (!EvaluateInteger(E, Val, Info))
12734 return false;
12735 Result = APFixedPoint(Val, FXSema);
12736 return true;
12737 } else if (E->getType()->isFixedPointType()) {
12738 return EvaluateFixedPoint(E, Result, Info);
12739 }
12740 return false;
12741}
12742
12743/// Check whether the given declaration can be directly converted to an integral
12744/// rvalue. If not, no diagnostic is produced; there are other things we can
12745/// try.
12746bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12747 // Enums are integer constant exprs.
12748 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12749 // Check for signedness/width mismatches between E type and ECD value.
12750 bool SameSign = (ECD->getInitVal().isSigned()
12752 bool SameWidth = (ECD->getInitVal().getBitWidth()
12753 == Info.Ctx.getIntWidth(E->getType()));
12754 if (SameSign && SameWidth)
12755 return Success(ECD->getInitVal(), E);
12756 else {
12757 // Get rid of mismatch (otherwise Success assertions will fail)
12758 // by computing a new value matching the type of E.
12759 llvm::APSInt Val = ECD->getInitVal();
12760 if (!SameSign)
12761 Val.setIsSigned(!ECD->getInitVal().isSigned());
12762 if (!SameWidth)
12763 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12764 return Success(Val, E);
12765 }
12766 }
12767 return false;
12768}
12769
12770/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12771/// as GCC.
12773 const LangOptions &LangOpts) {
12774 assert(!T->isDependentType() && "unexpected dependent type");
12775
12776 QualType CanTy = T.getCanonicalType();
12777
12778 switch (CanTy->getTypeClass()) {
12779#define TYPE(ID, BASE)
12780#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12781#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12782#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12783#include "clang/AST/TypeNodes.inc"
12784 case Type::Auto:
12785 case Type::DeducedTemplateSpecialization:
12786 llvm_unreachable("unexpected non-canonical or dependent type");
12787
12788 case Type::Builtin:
12789 switch (cast<BuiltinType>(CanTy)->getKind()) {
12790#define BUILTIN_TYPE(ID, SINGLETON_ID)
12791#define SIGNED_TYPE(ID, SINGLETON_ID) \
12792 case BuiltinType::ID: return GCCTypeClass::Integer;
12793#define FLOATING_TYPE(ID, SINGLETON_ID) \
12794 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12795#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12796 case BuiltinType::ID: break;
12797#include "clang/AST/BuiltinTypes.def"
12798 case BuiltinType::Void:
12799 return GCCTypeClass::Void;
12800
12801 case BuiltinType::Bool:
12802 return GCCTypeClass::Bool;
12803
12804 case BuiltinType::Char_U:
12805 case BuiltinType::UChar:
12806 case BuiltinType::WChar_U:
12807 case BuiltinType::Char8:
12808 case BuiltinType::Char16:
12809 case BuiltinType::Char32:
12810 case BuiltinType::UShort:
12811 case BuiltinType::UInt:
12812 case BuiltinType::ULong:
12813 case BuiltinType::ULongLong:
12814 case BuiltinType::UInt128:
12815 return GCCTypeClass::Integer;
12816
12817 case BuiltinType::UShortAccum:
12818 case BuiltinType::UAccum:
12819 case BuiltinType::ULongAccum:
12820 case BuiltinType::UShortFract:
12821 case BuiltinType::UFract:
12822 case BuiltinType::ULongFract:
12823 case BuiltinType::SatUShortAccum:
12824 case BuiltinType::SatUAccum:
12825 case BuiltinType::SatULongAccum:
12826 case BuiltinType::SatUShortFract:
12827 case BuiltinType::SatUFract:
12828 case BuiltinType::SatULongFract:
12829 return GCCTypeClass::None;
12830
12831 case BuiltinType::NullPtr:
12832
12833 case BuiltinType::ObjCId:
12834 case BuiltinType::ObjCClass:
12835 case BuiltinType::ObjCSel:
12836#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12837 case BuiltinType::Id:
12838#include "clang/Basic/OpenCLImageTypes.def"
12839#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12840 case BuiltinType::Id:
12841#include "clang/Basic/OpenCLExtensionTypes.def"
12842 case BuiltinType::OCLSampler:
12843 case BuiltinType::OCLEvent:
12844 case BuiltinType::OCLClkEvent:
12845 case BuiltinType::OCLQueue:
12846 case BuiltinType::OCLReserveID:
12847#define SVE_TYPE(Name, Id, SingletonId) \
12848 case BuiltinType::Id:
12849#include "clang/Basic/AArch64ACLETypes.def"
12850#define PPC_VECTOR_TYPE(Name, Id, Size) \
12851 case BuiltinType::Id:
12852#include "clang/Basic/PPCTypes.def"
12853#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12854#include "clang/Basic/RISCVVTypes.def"
12855#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12856#include "clang/Basic/WebAssemblyReferenceTypes.def"
12857#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12858#include "clang/Basic/AMDGPUTypes.def"
12859#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12860#include "clang/Basic/HLSLIntangibleTypes.def"
12861 return GCCTypeClass::None;
12862
12863 case BuiltinType::Dependent:
12864 llvm_unreachable("unexpected dependent type");
12865 };
12866 llvm_unreachable("unexpected placeholder type");
12867
12868 case Type::Enum:
12869 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12870
12871 case Type::Pointer:
12872 case Type::ConstantArray:
12873 case Type::VariableArray:
12874 case Type::IncompleteArray:
12875 case Type::FunctionNoProto:
12876 case Type::FunctionProto:
12877 case Type::ArrayParameter:
12878 return GCCTypeClass::Pointer;
12879
12880 case Type::MemberPointer:
12881 return CanTy->isMemberDataPointerType()
12882 ? GCCTypeClass::PointerToDataMember
12883 : GCCTypeClass::PointerToMemberFunction;
12884
12885 case Type::Complex:
12886 return GCCTypeClass::Complex;
12887
12888 case Type::Record:
12889 return CanTy->isUnionType() ? GCCTypeClass::Union
12890 : GCCTypeClass::ClassOrStruct;
12891
12892 case Type::Atomic:
12893 // GCC classifies _Atomic T the same as T.
12895 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12896
12897 case Type::Vector:
12898 case Type::ExtVector:
12899 return GCCTypeClass::Vector;
12900
12901 case Type::BlockPointer:
12902 case Type::ConstantMatrix:
12903 case Type::ObjCObject:
12904 case Type::ObjCInterface:
12905 case Type::ObjCObjectPointer:
12906 case Type::Pipe:
12907 case Type::HLSLAttributedResource:
12908 case Type::HLSLInlineSpirv:
12909 // Classify all other types that don't fit into the regular
12910 // classification the same way.
12911 return GCCTypeClass::None;
12912
12913 case Type::BitInt:
12914 return GCCTypeClass::BitInt;
12915
12916 case Type::LValueReference:
12917 case Type::RValueReference:
12918 llvm_unreachable("invalid type for expression");
12919 }
12920
12921 llvm_unreachable("unexpected type class");
12922}
12923
12924/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12925/// as GCC.
12926static GCCTypeClass
12928 // If no argument was supplied, default to None. This isn't
12929 // ideal, however it is what gcc does.
12930 if (E->getNumArgs() == 0)
12931 return GCCTypeClass::None;
12932
12933 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12934 // being an ICE, but still folds it to a constant using the type of the first
12935 // argument.
12936 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12937}
12938
12939/// EvaluateBuiltinConstantPForLValue - Determine the result of
12940/// __builtin_constant_p when applied to the given pointer.
12941///
12942/// A pointer is only "constant" if it is null (or a pointer cast to integer)
12943/// or it points to the first character of a string literal.
12946 if (Base.isNull()) {
12947 // A null base is acceptable.
12948 return true;
12949 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12950 if (!isa<StringLiteral>(E))
12951 return false;
12952 return LV.getLValueOffset().isZero();
12953 } else if (Base.is<TypeInfoLValue>()) {
12954 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12955 // evaluate to true.
12956 return true;
12957 } else {
12958 // Any other base is not constant enough for GCC.
12959 return false;
12960 }
12961}
12962
12963/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12964/// GCC as we can manage.
12965static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12966 // This evaluation is not permitted to have side-effects, so evaluate it in
12967 // a speculative evaluation context.
12968 SpeculativeEvaluationRAII SpeculativeEval(Info);
12969
12970 // Constant-folding is always enabled for the operand of __builtin_constant_p
12971 // (even when the enclosing evaluation context otherwise requires a strict
12972 // language-specific constant expression).
12973 FoldConstant Fold(Info, true);
12974
12975 QualType ArgType = Arg->getType();
12976
12977 // __builtin_constant_p always has one operand. The rules which gcc follows
12978 // are not precisely documented, but are as follows:
12979 //
12980 // - If the operand is of integral, floating, complex or enumeration type,
12981 // and can be folded to a known value of that type, it returns 1.
12982 // - If the operand can be folded to a pointer to the first character
12983 // of a string literal (or such a pointer cast to an integral type)
12984 // or to a null pointer or an integer cast to a pointer, it returns 1.
12985 //
12986 // Otherwise, it returns 0.
12987 //
12988 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12989 // its support for this did not work prior to GCC 9 and is not yet well
12990 // understood.
12991 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12992 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12993 ArgType->isNullPtrType()) {
12994 APValue V;
12995 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12996 Fold.keepDiagnostics();
12997 return false;
12998 }
12999
13000 // For a pointer (possibly cast to integer), there are special rules.
13001 if (V.getKind() == APValue::LValue)
13003
13004 // Otherwise, any constant value is good enough.
13005 return V.hasValue();
13006 }
13007
13008 // Anything else isn't considered to be sufficiently constant.
13009 return false;
13010}
13011
13012/// Retrieves the "underlying object type" of the given expression,
13013/// as used by __builtin_object_size.
13015 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
13016 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
13017 return VD->getType();
13018 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
13019 if (isa<CompoundLiteralExpr>(E))
13020 return E->getType();
13021 } else if (B.is<TypeInfoLValue>()) {
13022 return B.getTypeInfoType();
13023 } else if (B.is<DynamicAllocLValue>()) {
13024 return B.getDynamicAllocType();
13025 }
13026
13027 return QualType();
13028}
13029
13030/// A more selective version of E->IgnoreParenCasts for
13031/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
13032/// to change the type of E.
13033/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
13034///
13035/// Always returns an RValue with a pointer representation.
13037 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
13038
13039 const Expr *NoParens = E->IgnoreParens();
13040 const auto *Cast = dyn_cast<CastExpr>(NoParens);
13041 if (Cast == nullptr)
13042 return NoParens;
13043
13044 // We only conservatively allow a few kinds of casts, because this code is
13045 // inherently a simple solution that seeks to support the common case.
13046 auto CastKind = Cast->getCastKind();
13047 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
13048 CastKind != CK_AddressSpaceConversion)
13049 return NoParens;
13050
13051 const auto *SubExpr = Cast->getSubExpr();
13052 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
13053 return NoParens;
13054 return ignorePointerCastsAndParens(SubExpr);
13055}
13056
13057/// Checks to see if the given LValue's Designator is at the end of the LValue's
13058/// record layout. e.g.
13059/// struct { struct { int a, b; } fst, snd; } obj;
13060/// obj.fst // no
13061/// obj.snd // yes
13062/// obj.fst.a // no
13063/// obj.fst.b // no
13064/// obj.snd.a // no
13065/// obj.snd.b // yes
13066///
13067/// Please note: this function is specialized for how __builtin_object_size
13068/// views "objects".
13069///
13070/// If this encounters an invalid RecordDecl or otherwise cannot determine the
13071/// correct result, it will always return true.
13072static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
13073 assert(!LVal.Designator.Invalid);
13074
13075 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
13076 const RecordDecl *Parent = FD->getParent();
13077 if (Parent->isInvalidDecl() || Parent->isUnion())
13078 return true;
13079 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
13080 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
13081 };
13082
13083 auto &Base = LVal.getLValueBase();
13084 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
13085 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
13086 if (!IsLastOrInvalidFieldDecl(FD))
13087 return false;
13088 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
13089 for (auto *FD : IFD->chain()) {
13090 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
13091 return false;
13092 }
13093 }
13094 }
13095
13096 unsigned I = 0;
13097 QualType BaseType = getType(Base);
13098 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
13099 // If we don't know the array bound, conservatively assume we're looking at
13100 // the final array element.
13101 ++I;
13102 if (BaseType->isIncompleteArrayType())
13103 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
13104 else
13105 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
13106 }
13107
13108 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
13109 const auto &Entry = LVal.Designator.Entries[I];
13110 if (BaseType->isArrayType()) {
13111 // Because __builtin_object_size treats arrays as objects, we can ignore
13112 // the index iff this is the last array in the Designator.
13113 if (I + 1 == E)
13114 return true;
13115 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
13116 uint64_t Index = Entry.getAsArrayIndex();
13117 if (Index + 1 != CAT->getZExtSize())
13118 return false;
13119 BaseType = CAT->getElementType();
13120 } else if (BaseType->isAnyComplexType()) {
13121 const auto *CT = BaseType->castAs<ComplexType>();
13122 uint64_t Index = Entry.getAsArrayIndex();
13123 if (Index != 1)
13124 return false;
13125 BaseType = CT->getElementType();
13126 } else if (auto *FD = getAsField(Entry)) {
13127 if (!IsLastOrInvalidFieldDecl(FD))
13128 return false;
13129 BaseType = FD->getType();
13130 } else {
13131 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
13132 return false;
13133 }
13134 }
13135 return true;
13136}
13137
13138/// Tests to see if the LValue has a user-specified designator (that isn't
13139/// necessarily valid). Note that this always returns 'true' if the LValue has
13140/// an unsized array as its first designator entry, because there's currently no
13141/// way to tell if the user typed *foo or foo[0].
13142static bool refersToCompleteObject(const LValue &LVal) {
13143 if (LVal.Designator.Invalid)
13144 return false;
13145
13146 if (!LVal.Designator.Entries.empty())
13147 return LVal.Designator.isMostDerivedAnUnsizedArray();
13148
13149 if (!LVal.InvalidBase)
13150 return true;
13151
13152 // If `E` is a MemberExpr, then the first part of the designator is hiding in
13153 // the LValueBase.
13154 const auto *E = LVal.Base.dyn_cast<const Expr *>();
13155 return !E || !isa<MemberExpr>(E);
13156}
13157
13158/// Attempts to detect a user writing into a piece of memory that's impossible
13159/// to figure out the size of by just using types.
13160static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
13161 const SubobjectDesignator &Designator = LVal.Designator;
13162 // Notes:
13163 // - Users can only write off of the end when we have an invalid base. Invalid
13164 // bases imply we don't know where the memory came from.
13165 // - We used to be a bit more aggressive here; we'd only be conservative if
13166 // the array at the end was flexible, or if it had 0 or 1 elements. This
13167 // broke some common standard library extensions (PR30346), but was
13168 // otherwise seemingly fine. It may be useful to reintroduce this behavior
13169 // with some sort of list. OTOH, it seems that GCC is always
13170 // conservative with the last element in structs (if it's an array), so our
13171 // current behavior is more compatible than an explicit list approach would
13172 // be.
13173 auto isFlexibleArrayMember = [&] {
13175 FAMKind StrictFlexArraysLevel =
13176 Ctx.getLangOpts().getStrictFlexArraysLevel();
13177
13178 if (Designator.isMostDerivedAnUnsizedArray())
13179 return true;
13180
13181 if (StrictFlexArraysLevel == FAMKind::Default)
13182 return true;
13183
13184 if (Designator.getMostDerivedArraySize() == 0 &&
13185 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
13186 return true;
13187
13188 if (Designator.getMostDerivedArraySize() == 1 &&
13189 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
13190 return true;
13191
13192 return false;
13193 };
13194
13195 return LVal.InvalidBase &&
13196 Designator.Entries.size() == Designator.MostDerivedPathLength &&
13197 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
13198 isDesignatorAtObjectEnd(Ctx, LVal);
13199}
13200
13201/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
13202/// Fails if the conversion would cause loss of precision.
13203static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
13204 CharUnits &Result) {
13205 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
13206 if (Int.ugt(CharUnitsMax))
13207 return false;
13208 Result = CharUnits::fromQuantity(Int.getZExtValue());
13209 return true;
13210}
13211
13212/// If we're evaluating the object size of an instance of a struct that
13213/// contains a flexible array member, add the size of the initializer.
13214static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
13215 const LValue &LV, CharUnits &Size) {
13216 if (!T.isNull() && T->isStructureType() &&
13218 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
13219 if (const auto *VD = dyn_cast<VarDecl>(V))
13220 if (VD->hasInit())
13221 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
13222}
13223
13224/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
13225/// determine how many bytes exist from the beginning of the object to either
13226/// the end of the current subobject, or the end of the object itself, depending
13227/// on what the LValue looks like + the value of Type.
13228///
13229/// If this returns false, the value of Result is undefined.
13230static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
13231 unsigned Type, const LValue &LVal,
13232 CharUnits &EndOffset) {
13233 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
13234
13235 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
13236 if (Ty.isNull())
13237 return false;
13238
13239 Ty = Ty.getNonReferenceType();
13240
13241 if (Ty->isIncompleteType() || Ty->isFunctionType())
13242 return false;
13243
13244 return HandleSizeof(Info, ExprLoc, Ty, Result);
13245 };
13246
13247 // We want to evaluate the size of the entire object. This is a valid fallback
13248 // for when Type=1 and the designator is invalid, because we're asked for an
13249 // upper-bound.
13250 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
13251 // Type=3 wants a lower bound, so we can't fall back to this.
13252 if (Type == 3 && !DetermineForCompleteObject)
13253 return false;
13254
13255 llvm::APInt APEndOffset;
13256 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13257 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13258 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13259
13260 if (LVal.InvalidBase)
13261 return false;
13262
13263 QualType BaseTy = getObjectType(LVal.getLValueBase());
13264 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
13265 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
13266 return Ret;
13267 }
13268
13269 // We want to evaluate the size of a subobject.
13270 const SubobjectDesignator &Designator = LVal.Designator;
13271
13272 // The following is a moderately common idiom in C:
13273 //
13274 // struct Foo { int a; char c[1]; };
13275 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
13276 // strcpy(&F->c[0], Bar);
13277 //
13278 // In order to not break too much legacy code, we need to support it.
13279 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
13280 // If we can resolve this to an alloc_size call, we can hand that back,
13281 // because we know for certain how many bytes there are to write to.
13282 llvm::APInt APEndOffset;
13283 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
13284 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
13285 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
13286
13287 // If we cannot determine the size of the initial allocation, then we can't
13288 // given an accurate upper-bound. However, we are still able to give
13289 // conservative lower-bounds for Type=3.
13290 if (Type == 1)
13291 return false;
13292 }
13293
13294 CharUnits BytesPerElem;
13295 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
13296 return false;
13297
13298 // According to the GCC documentation, we want the size of the subobject
13299 // denoted by the pointer. But that's not quite right -- what we actually
13300 // want is the size of the immediately-enclosing array, if there is one.
13301 int64_t ElemsRemaining;
13302 if (Designator.MostDerivedIsArrayElement &&
13303 Designator.Entries.size() == Designator.MostDerivedPathLength) {
13304 uint64_t ArraySize = Designator.getMostDerivedArraySize();
13305 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
13306 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
13307 } else {
13308 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
13309 }
13310
13311 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
13312 return true;
13313}
13314
13315/// Tries to evaluate the __builtin_object_size for @p E. If successful,
13316/// returns true and stores the result in @p Size.
13317///
13318/// If @p WasError is non-null, this will report whether the failure to evaluate
13319/// is to be treated as an Error in IntExprEvaluator.
13320static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
13321 EvalInfo &Info, uint64_t &Size) {
13322 // Determine the denoted object.
13323 LValue LVal;
13324 {
13325 // The operand of __builtin_object_size is never evaluated for side-effects.
13326 // If there are any, but we can determine the pointed-to object anyway, then
13327 // ignore the side-effects.
13328 SpeculativeEvaluationRAII SpeculativeEval(Info);
13329 IgnoreSideEffectsRAII Fold(Info);
13330
13331 if (E->isGLValue()) {
13332 // It's possible for us to be given GLValues if we're called via
13333 // Expr::tryEvaluateObjectSize.
13334 APValue RVal;
13335 if (!EvaluateAsRValue(Info, E, RVal))
13336 return false;
13337 LVal.setFrom(Info.Ctx, RVal);
13338 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
13339 /*InvalidBaseOK=*/true))
13340 return false;
13341 }
13342
13343 // If we point to before the start of the object, there are no accessible
13344 // bytes.
13345 if (LVal.getLValueOffset().isNegative()) {
13346 Size = 0;
13347 return true;
13348 }
13349
13350 CharUnits EndOffset;
13351 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
13352 return false;
13353
13354 // If we've fallen outside of the end offset, just pretend there's nothing to
13355 // write to/read from.
13356 if (EndOffset <= LVal.getLValueOffset())
13357 Size = 0;
13358 else
13359 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
13360 return true;
13361}
13362
13363bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
13364 if (!IsConstantEvaluatedBuiltinCall(E))
13365 return ExprEvaluatorBaseTy::VisitCallExpr(E);
13366 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
13367}
13368
13369static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
13370 APValue &Val, APSInt &Alignment) {
13371 QualType SrcTy = E->getArg(0)->getType();
13372 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
13373 return false;
13374 // Even though we are evaluating integer expressions we could get a pointer
13375 // argument for the __builtin_is_aligned() case.
13376 if (SrcTy->isPointerType()) {
13377 LValue Ptr;
13378 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
13379 return false;
13380 Ptr.moveInto(Val);
13381 } else if (!SrcTy->isIntegralOrEnumerationType()) {
13382 Info.FFDiag(E->getArg(0));
13383 return false;
13384 } else {
13385 APSInt SrcInt;
13386 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
13387 return false;
13388 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
13389 "Bit widths must be the same");
13390 Val = APValue(SrcInt);
13391 }
13392 assert(Val.hasValue());
13393 return true;
13394}
13395
13396bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
13397 unsigned BuiltinOp) {
13398 switch (BuiltinOp) {
13399 default:
13400 return false;
13401
13402 case Builtin::BI__builtin_dynamic_object_size:
13403 case Builtin::BI__builtin_object_size: {
13404 // The type was checked when we built the expression.
13405 unsigned Type =
13406 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13407 assert(Type <= 3 && "unexpected type");
13408
13409 uint64_t Size;
13410 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
13411 return Success(Size, E);
13412
13413 if (E->getArg(0)->HasSideEffects(Info.Ctx))
13414 return Success((Type & 2) ? 0 : -1, E);
13415
13416 // Expression had no side effects, but we couldn't statically determine the
13417 // size of the referenced object.
13418 switch (Info.EvalMode) {
13419 case EvalInfo::EM_ConstantExpression:
13420 case EvalInfo::EM_ConstantFold:
13421 case EvalInfo::EM_IgnoreSideEffects:
13422 // Leave it to IR generation.
13423 return Error(E);
13424 case EvalInfo::EM_ConstantExpressionUnevaluated:
13425 // Reduce it to a constant now.
13426 return Success((Type & 2) ? 0 : -1, E);
13427 }
13428
13429 llvm_unreachable("unexpected EvalMode");
13430 }
13431
13432 case Builtin::BI__builtin_os_log_format_buffer_size: {
13435 return Success(Layout.size().getQuantity(), E);
13436 }
13437
13438 case Builtin::BI__builtin_is_aligned: {
13439 APValue Src;
13440 APSInt Alignment;
13441 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13442 return false;
13443 if (Src.isLValue()) {
13444 // If we evaluated a pointer, check the minimum known alignment.
13445 LValue Ptr;
13446 Ptr.setFrom(Info.Ctx, Src);
13447 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
13448 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
13449 // We can return true if the known alignment at the computed offset is
13450 // greater than the requested alignment.
13451 assert(PtrAlign.isPowerOfTwo());
13452 assert(Alignment.isPowerOf2());
13453 if (PtrAlign.getQuantity() >= Alignment)
13454 return Success(1, E);
13455 // If the alignment is not known to be sufficient, some cases could still
13456 // be aligned at run time. However, if the requested alignment is less or
13457 // equal to the base alignment and the offset is not aligned, we know that
13458 // the run-time value can never be aligned.
13459 if (BaseAlignment.getQuantity() >= Alignment &&
13460 PtrAlign.getQuantity() < Alignment)
13461 return Success(0, E);
13462 // Otherwise we can't infer whether the value is sufficiently aligned.
13463 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
13464 // in cases where we can't fully evaluate the pointer.
13465 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
13466 << Alignment;
13467 return false;
13468 }
13469 assert(Src.isInt());
13470 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
13471 }
13472 case Builtin::BI__builtin_align_up: {
13473 APValue Src;
13474 APSInt Alignment;
13475 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13476 return false;
13477 if (!Src.isInt())
13478 return Error(E);
13479 APSInt AlignedVal =
13480 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
13481 Src.getInt().isUnsigned());
13482 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13483 return Success(AlignedVal, E);
13484 }
13485 case Builtin::BI__builtin_align_down: {
13486 APValue Src;
13487 APSInt Alignment;
13488 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
13489 return false;
13490 if (!Src.isInt())
13491 return Error(E);
13492 APSInt AlignedVal =
13493 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
13494 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
13495 return Success(AlignedVal, E);
13496 }
13497
13498 case Builtin::BI__builtin_bitreverse8:
13499 case Builtin::BI__builtin_bitreverse16:
13500 case Builtin::BI__builtin_bitreverse32:
13501 case Builtin::BI__builtin_bitreverse64:
13502 case Builtin::BI__builtin_elementwise_bitreverse: {
13503 APSInt Val;
13504 if (!EvaluateInteger(E->getArg(0), Val, Info))
13505 return false;
13506
13507 return Success(Val.reverseBits(), E);
13508 }
13509
13510 case Builtin::BI__builtin_bswap16:
13511 case Builtin::BI__builtin_bswap32:
13512 case Builtin::BI__builtin_bswap64: {
13513 APSInt Val;
13514 if (!EvaluateInteger(E->getArg(0), Val, Info))
13515 return false;
13516
13517 return Success(Val.byteSwap(), E);
13518 }
13519
13520 case Builtin::BI__builtin_classify_type:
13521 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
13522
13523 case Builtin::BI__builtin_clrsb:
13524 case Builtin::BI__builtin_clrsbl:
13525 case Builtin::BI__builtin_clrsbll: {
13526 APSInt Val;
13527 if (!EvaluateInteger(E->getArg(0), Val, Info))
13528 return false;
13529
13530 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
13531 }
13532
13533 case Builtin::BI__builtin_clz:
13534 case Builtin::BI__builtin_clzl:
13535 case Builtin::BI__builtin_clzll:
13536 case Builtin::BI__builtin_clzs:
13537 case Builtin::BI__builtin_clzg:
13538 case Builtin::BI__builtin_elementwise_ctlz:
13539 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13540 case Builtin::BI__lzcnt:
13541 case Builtin::BI__lzcnt64: {
13542 APSInt Val;
13543 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13544 APValue Vec;
13545 if (!EvaluateVector(E->getArg(0), Vec, Info))
13546 return false;
13547 Val = ConvertBoolVectorToInt(Vec);
13548 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13549 return false;
13550 }
13551
13552 std::optional<APSInt> Fallback;
13553 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
13554 BuiltinOp == Builtin::BI__builtin_elementwise_ctlz) &&
13555 E->getNumArgs() > 1) {
13556 APSInt FallbackTemp;
13557 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13558 return false;
13559 Fallback = FallbackTemp;
13560 }
13561
13562 if (!Val) {
13563 if (Fallback)
13564 return Success(*Fallback, E);
13565
13566 // When the argument is 0, the result of GCC builtins is undefined,
13567 // whereas for Microsoft intrinsics, the result is the bit-width of the
13568 // argument.
13569 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13570 BuiltinOp != Builtin::BI__lzcnt &&
13571 BuiltinOp != Builtin::BI__lzcnt64;
13572
13573 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctlz) {
13574 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13575 << /*IsTrailing=*/false;
13576 }
13577
13578 if (ZeroIsUndefined)
13579 return Error(E);
13580 }
13581
13582 return Success(Val.countl_zero(), E);
13583 }
13584
13585 case Builtin::BI__builtin_constant_p: {
13586 const Expr *Arg = E->getArg(0);
13587 if (EvaluateBuiltinConstantP(Info, Arg))
13588 return Success(true, E);
13589 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13590 // Outside a constant context, eagerly evaluate to false in the presence
13591 // of side-effects in order to avoid -Wunsequenced false-positives in
13592 // a branch on __builtin_constant_p(expr).
13593 return Success(false, E);
13594 }
13595 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13596 return false;
13597 }
13598
13599 case Builtin::BI__noop:
13600 // __noop always evaluates successfully and returns 0.
13601 return Success(0, E);
13602
13603 case Builtin::BI__builtin_is_constant_evaluated: {
13604 const auto *Callee = Info.CurrentCall->getCallee();
13605 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13606 (Info.CallStackDepth == 1 ||
13607 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13608 Callee->getIdentifier() &&
13609 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13610 // FIXME: Find a better way to avoid duplicated diagnostics.
13611 if (Info.EvalStatus.Diag)
13612 Info.report((Info.CallStackDepth == 1)
13613 ? E->getExprLoc()
13614 : Info.CurrentCall->getCallRange().getBegin(),
13615 diag::warn_is_constant_evaluated_always_true_constexpr)
13616 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13617 : "std::is_constant_evaluated");
13618 }
13619
13620 return Success(Info.InConstantContext, E);
13621 }
13622
13623 case Builtin::BI__builtin_is_within_lifetime:
13624 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13625 return Success(*result, E);
13626 return false;
13627
13628 case Builtin::BI__builtin_ctz:
13629 case Builtin::BI__builtin_ctzl:
13630 case Builtin::BI__builtin_ctzll:
13631 case Builtin::BI__builtin_ctzs:
13632 case Builtin::BI__builtin_ctzg:
13633 case Builtin::BI__builtin_elementwise_cttz: {
13634 APSInt Val;
13635 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13636 APValue Vec;
13637 if (!EvaluateVector(E->getArg(0), Vec, Info))
13638 return false;
13639 Val = ConvertBoolVectorToInt(Vec);
13640 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13641 return false;
13642 }
13643
13644 std::optional<APSInt> Fallback;
13645 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
13646 BuiltinOp == Builtin::BI__builtin_elementwise_cttz) &&
13647 E->getNumArgs() > 1) {
13648 APSInt FallbackTemp;
13649 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13650 return false;
13651 Fallback = FallbackTemp;
13652 }
13653
13654 if (!Val) {
13655 if (Fallback)
13656 return Success(*Fallback, E);
13657
13658 if (BuiltinOp == Builtin::BI__builtin_elementwise_cttz) {
13659 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13660 << /*IsTrailing=*/true;
13661 }
13662 return Error(E);
13663 }
13664
13665 return Success(Val.countr_zero(), E);
13666 }
13667
13668 case Builtin::BI__builtin_eh_return_data_regno: {
13669 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13670 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13671 return Success(Operand, E);
13672 }
13673
13674 case Builtin::BI__builtin_elementwise_abs: {
13675 APSInt Val;
13676 if (!EvaluateInteger(E->getArg(0), Val, Info))
13677 return false;
13678
13679 return Success(Val.abs(), E);
13680 }
13681
13682 case Builtin::BI__builtin_expect:
13683 case Builtin::BI__builtin_expect_with_probability:
13684 return Visit(E->getArg(0));
13685
13686 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13687 const auto *Literal =
13688 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13689 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13690 return Success(Result, E);
13691 }
13692
13693 case Builtin::BI__builtin_ffs:
13694 case Builtin::BI__builtin_ffsl:
13695 case Builtin::BI__builtin_ffsll: {
13696 APSInt Val;
13697 if (!EvaluateInteger(E->getArg(0), Val, Info))
13698 return false;
13699
13700 unsigned N = Val.countr_zero();
13701 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13702 }
13703
13704 case Builtin::BI__builtin_fpclassify: {
13705 APFloat Val(0.0);
13706 if (!EvaluateFloat(E->getArg(5), Val, Info))
13707 return false;
13708 unsigned Arg;
13709 switch (Val.getCategory()) {
13710 case APFloat::fcNaN: Arg = 0; break;
13711 case APFloat::fcInfinity: Arg = 1; break;
13712 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13713 case APFloat::fcZero: Arg = 4; break;
13714 }
13715 return Visit(E->getArg(Arg));
13716 }
13717
13718 case Builtin::BI__builtin_isinf_sign: {
13719 APFloat Val(0.0);
13720 return EvaluateFloat(E->getArg(0), Val, Info) &&
13721 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13722 }
13723
13724 case Builtin::BI__builtin_isinf: {
13725 APFloat Val(0.0);
13726 return EvaluateFloat(E->getArg(0), Val, Info) &&
13727 Success(Val.isInfinity() ? 1 : 0, E);
13728 }
13729
13730 case Builtin::BI__builtin_isfinite: {
13731 APFloat Val(0.0);
13732 return EvaluateFloat(E->getArg(0), Val, Info) &&
13733 Success(Val.isFinite() ? 1 : 0, E);
13734 }
13735
13736 case Builtin::BI__builtin_isnan: {
13737 APFloat Val(0.0);
13738 return EvaluateFloat(E->getArg(0), Val, Info) &&
13739 Success(Val.isNaN() ? 1 : 0, E);
13740 }
13741
13742 case Builtin::BI__builtin_isnormal: {
13743 APFloat Val(0.0);
13744 return EvaluateFloat(E->getArg(0), Val, Info) &&
13745 Success(Val.isNormal() ? 1 : 0, E);
13746 }
13747
13748 case Builtin::BI__builtin_issubnormal: {
13749 APFloat Val(0.0);
13750 return EvaluateFloat(E->getArg(0), Val, Info) &&
13751 Success(Val.isDenormal() ? 1 : 0, E);
13752 }
13753
13754 case Builtin::BI__builtin_iszero: {
13755 APFloat Val(0.0);
13756 return EvaluateFloat(E->getArg(0), Val, Info) &&
13757 Success(Val.isZero() ? 1 : 0, E);
13758 }
13759
13760 case Builtin::BI__builtin_signbit:
13761 case Builtin::BI__builtin_signbitf:
13762 case Builtin::BI__builtin_signbitl: {
13763 APFloat Val(0.0);
13764 return EvaluateFloat(E->getArg(0), Val, Info) &&
13765 Success(Val.isNegative() ? 1 : 0, E);
13766 }
13767
13768 case Builtin::BI__builtin_isgreater:
13769 case Builtin::BI__builtin_isgreaterequal:
13770 case Builtin::BI__builtin_isless:
13771 case Builtin::BI__builtin_islessequal:
13772 case Builtin::BI__builtin_islessgreater:
13773 case Builtin::BI__builtin_isunordered: {
13774 APFloat LHS(0.0);
13775 APFloat RHS(0.0);
13776 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13777 !EvaluateFloat(E->getArg(1), RHS, Info))
13778 return false;
13779
13780 return Success(
13781 [&] {
13782 switch (BuiltinOp) {
13783 case Builtin::BI__builtin_isgreater:
13784 return LHS > RHS;
13785 case Builtin::BI__builtin_isgreaterequal:
13786 return LHS >= RHS;
13787 case Builtin::BI__builtin_isless:
13788 return LHS < RHS;
13789 case Builtin::BI__builtin_islessequal:
13790 return LHS <= RHS;
13791 case Builtin::BI__builtin_islessgreater: {
13792 APFloat::cmpResult cmp = LHS.compare(RHS);
13793 return cmp == APFloat::cmpResult::cmpLessThan ||
13794 cmp == APFloat::cmpResult::cmpGreaterThan;
13795 }
13796 case Builtin::BI__builtin_isunordered:
13797 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13798 default:
13799 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13800 "point comparison function");
13801 }
13802 }()
13803 ? 1
13804 : 0,
13805 E);
13806 }
13807
13808 case Builtin::BI__builtin_issignaling: {
13809 APFloat Val(0.0);
13810 return EvaluateFloat(E->getArg(0), Val, Info) &&
13811 Success(Val.isSignaling() ? 1 : 0, E);
13812 }
13813
13814 case Builtin::BI__builtin_isfpclass: {
13815 APSInt MaskVal;
13816 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13817 return false;
13818 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13819 APFloat Val(0.0);
13820 return EvaluateFloat(E->getArg(0), Val, Info) &&
13821 Success((Val.classify() & Test) ? 1 : 0, E);
13822 }
13823
13824 case Builtin::BI__builtin_parity:
13825 case Builtin::BI__builtin_parityl:
13826 case Builtin::BI__builtin_parityll: {
13827 APSInt Val;
13828 if (!EvaluateInteger(E->getArg(0), Val, Info))
13829 return false;
13830
13831 return Success(Val.popcount() % 2, E);
13832 }
13833
13834 case Builtin::BI__builtin_abs:
13835 case Builtin::BI__builtin_labs:
13836 case Builtin::BI__builtin_llabs: {
13837 APSInt Val;
13838 if (!EvaluateInteger(E->getArg(0), Val, Info))
13839 return false;
13840 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13841 /*IsUnsigned=*/false))
13842 return false;
13843 if (Val.isNegative())
13844 Val.negate();
13845 return Success(Val, E);
13846 }
13847
13848 case Builtin::BI__builtin_popcount:
13849 case Builtin::BI__builtin_popcountl:
13850 case Builtin::BI__builtin_popcountll:
13851 case Builtin::BI__builtin_popcountg:
13852 case Builtin::BI__builtin_elementwise_popcount:
13853 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13854 case Builtin::BI__popcnt:
13855 case Builtin::BI__popcnt64: {
13856 APSInt Val;
13857 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
13858 APValue Vec;
13859 if (!EvaluateVector(E->getArg(0), Vec, Info))
13860 return false;
13861 Val = ConvertBoolVectorToInt(Vec);
13862 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
13863 return false;
13864 }
13865
13866 return Success(Val.popcount(), E);
13867 }
13868
13869 case Builtin::BI__builtin_rotateleft8:
13870 case Builtin::BI__builtin_rotateleft16:
13871 case Builtin::BI__builtin_rotateleft32:
13872 case Builtin::BI__builtin_rotateleft64:
13873 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13874 case Builtin::BI_rotl16:
13875 case Builtin::BI_rotl:
13876 case Builtin::BI_lrotl:
13877 case Builtin::BI_rotl64: {
13878 APSInt Val, Amt;
13879 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13880 !EvaluateInteger(E->getArg(1), Amt, Info))
13881 return false;
13882
13883 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13884 }
13885
13886 case Builtin::BI__builtin_rotateright8:
13887 case Builtin::BI__builtin_rotateright16:
13888 case Builtin::BI__builtin_rotateright32:
13889 case Builtin::BI__builtin_rotateright64:
13890 case Builtin::BI_rotr8: // Microsoft variants of rotate right
13891 case Builtin::BI_rotr16:
13892 case Builtin::BI_rotr:
13893 case Builtin::BI_lrotr:
13894 case Builtin::BI_rotr64: {
13895 APSInt Val, Amt;
13896 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13897 !EvaluateInteger(E->getArg(1), Amt, Info))
13898 return false;
13899
13900 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13901 }
13902
13903 case Builtin::BI__builtin_elementwise_add_sat: {
13904 APSInt LHS, RHS;
13905 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13906 !EvaluateInteger(E->getArg(1), RHS, Info))
13907 return false;
13908
13909 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13910 return Success(APSInt(Result, !LHS.isSigned()), E);
13911 }
13912 case Builtin::BI__builtin_elementwise_sub_sat: {
13913 APSInt LHS, RHS;
13914 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13915 !EvaluateInteger(E->getArg(1), RHS, Info))
13916 return false;
13917
13918 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13919 return Success(APSInt(Result, !LHS.isSigned()), E);
13920 }
13921 case Builtin::BI__builtin_elementwise_max: {
13922 APSInt LHS, RHS;
13923 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13924 !EvaluateInteger(E->getArg(1), RHS, Info))
13925 return false;
13926
13927 APInt Result = std::max(LHS, RHS);
13928 return Success(APSInt(Result, !LHS.isSigned()), E);
13929 }
13930 case Builtin::BI__builtin_elementwise_min: {
13931 APSInt LHS, RHS;
13932 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13933 !EvaluateInteger(E->getArg(1), RHS, Info))
13934 return false;
13935
13936 APInt Result = std::min(LHS, RHS);
13937 return Success(APSInt(Result, !LHS.isSigned()), E);
13938 }
13939 case Builtin::BIstrlen:
13940 case Builtin::BIwcslen:
13941 // A call to strlen is not a constant expression.
13942 if (Info.getLangOpts().CPlusPlus11)
13943 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13944 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13945 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13946 else
13947 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13948 [[fallthrough]];
13949 case Builtin::BI__builtin_strlen:
13950 case Builtin::BI__builtin_wcslen: {
13951 // As an extension, we support __builtin_strlen() as a constant expression,
13952 // and support folding strlen() to a constant.
13953 uint64_t StrLen;
13954 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13955 return Success(StrLen, E);
13956 return false;
13957 }
13958
13959 case Builtin::BIstrcmp:
13960 case Builtin::BIwcscmp:
13961 case Builtin::BIstrncmp:
13962 case Builtin::BIwcsncmp:
13963 case Builtin::BImemcmp:
13964 case Builtin::BIbcmp:
13965 case Builtin::BIwmemcmp:
13966 // A call to strlen is not a constant expression.
13967 if (Info.getLangOpts().CPlusPlus11)
13968 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13969 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13970 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13971 else
13972 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13973 [[fallthrough]];
13974 case Builtin::BI__builtin_strcmp:
13975 case Builtin::BI__builtin_wcscmp:
13976 case Builtin::BI__builtin_strncmp:
13977 case Builtin::BI__builtin_wcsncmp:
13978 case Builtin::BI__builtin_memcmp:
13979 case Builtin::BI__builtin_bcmp:
13980 case Builtin::BI__builtin_wmemcmp: {
13981 LValue String1, String2;
13982 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13983 !EvaluatePointer(E->getArg(1), String2, Info))
13984 return false;
13985
13986 uint64_t MaxLength = uint64_t(-1);
13987 if (BuiltinOp != Builtin::BIstrcmp &&
13988 BuiltinOp != Builtin::BIwcscmp &&
13989 BuiltinOp != Builtin::BI__builtin_strcmp &&
13990 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13991 APSInt N;
13992 if (!EvaluateInteger(E->getArg(2), N, Info))
13993 return false;
13994 MaxLength = N.getZExtValue();
13995 }
13996
13997 // Empty substrings compare equal by definition.
13998 if (MaxLength == 0u)
13999 return Success(0, E);
14000
14001 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14002 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
14003 String1.Designator.Invalid || String2.Designator.Invalid)
14004 return false;
14005
14006 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
14007 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
14008
14009 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
14010 BuiltinOp == Builtin::BIbcmp ||
14011 BuiltinOp == Builtin::BI__builtin_memcmp ||
14012 BuiltinOp == Builtin::BI__builtin_bcmp;
14013
14014 assert(IsRawByte ||
14015 (Info.Ctx.hasSameUnqualifiedType(
14016 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
14017 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
14018
14019 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
14020 // 'char8_t', but no other types.
14021 if (IsRawByte &&
14022 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
14023 // FIXME: Consider using our bit_cast implementation to support this.
14024 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
14025 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
14026 << CharTy2;
14027 return false;
14028 }
14029
14030 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
14031 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
14032 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
14033 Char1.isInt() && Char2.isInt();
14034 };
14035 const auto &AdvanceElems = [&] {
14036 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
14037 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
14038 };
14039
14040 bool StopAtNull =
14041 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
14042 BuiltinOp != Builtin::BIwmemcmp &&
14043 BuiltinOp != Builtin::BI__builtin_memcmp &&
14044 BuiltinOp != Builtin::BI__builtin_bcmp &&
14045 BuiltinOp != Builtin::BI__builtin_wmemcmp);
14046 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
14047 BuiltinOp == Builtin::BIwcsncmp ||
14048 BuiltinOp == Builtin::BIwmemcmp ||
14049 BuiltinOp == Builtin::BI__builtin_wcscmp ||
14050 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
14051 BuiltinOp == Builtin::BI__builtin_wmemcmp;
14052
14053 for (; MaxLength; --MaxLength) {
14054 APValue Char1, Char2;
14055 if (!ReadCurElems(Char1, Char2))
14056 return false;
14057 if (Char1.getInt().ne(Char2.getInt())) {
14058 if (IsWide) // wmemcmp compares with wchar_t signedness.
14059 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
14060 // memcmp always compares unsigned chars.
14061 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
14062 }
14063 if (StopAtNull && !Char1.getInt())
14064 return Success(0, E);
14065 assert(!(StopAtNull && !Char2.getInt()));
14066 if (!AdvanceElems())
14067 return false;
14068 }
14069 // We hit the strncmp / memcmp limit.
14070 return Success(0, E);
14071 }
14072
14073 case Builtin::BI__atomic_always_lock_free:
14074 case Builtin::BI__atomic_is_lock_free:
14075 case Builtin::BI__c11_atomic_is_lock_free: {
14076 APSInt SizeVal;
14077 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
14078 return false;
14079
14080 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
14081 // of two less than or equal to the maximum inline atomic width, we know it
14082 // is lock-free. If the size isn't a power of two, or greater than the
14083 // maximum alignment where we promote atomics, we know it is not lock-free
14084 // (at least not in the sense of atomic_is_lock_free). Otherwise,
14085 // the answer can only be determined at runtime; for example, 16-byte
14086 // atomics have lock-free implementations on some, but not all,
14087 // x86-64 processors.
14088
14089 // Check power-of-two.
14090 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
14091 if (Size.isPowerOfTwo()) {
14092 // Check against inlining width.
14093 unsigned InlineWidthBits =
14094 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
14095 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
14096 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
14097 Size == CharUnits::One())
14098 return Success(1, E);
14099
14100 // If the pointer argument can be evaluated to a compile-time constant
14101 // integer (or nullptr), check if that value is appropriately aligned.
14102 const Expr *PtrArg = E->getArg(1);
14104 APSInt IntResult;
14105 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
14106 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
14107 Info.Ctx) &&
14108 IntResult.isAligned(Size.getAsAlign()))
14109 return Success(1, E);
14110
14111 // Otherwise, check if the type's alignment against Size.
14112 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
14113 // Drop the potential implicit-cast to 'const volatile void*', getting
14114 // the underlying type.
14115 if (ICE->getCastKind() == CK_BitCast)
14116 PtrArg = ICE->getSubExpr();
14117 }
14118
14119 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
14120 QualType PointeeType = PtrTy->getPointeeType();
14121 if (!PointeeType->isIncompleteType() &&
14122 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
14123 // OK, we will inline operations on this object.
14124 return Success(1, E);
14125 }
14126 }
14127 }
14128 }
14129
14130 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
14131 Success(0, E) : Error(E);
14132 }
14133 case Builtin::BI__builtin_addcb:
14134 case Builtin::BI__builtin_addcs:
14135 case Builtin::BI__builtin_addc:
14136 case Builtin::BI__builtin_addcl:
14137 case Builtin::BI__builtin_addcll:
14138 case Builtin::BI__builtin_subcb:
14139 case Builtin::BI__builtin_subcs:
14140 case Builtin::BI__builtin_subc:
14141 case Builtin::BI__builtin_subcl:
14142 case Builtin::BI__builtin_subcll: {
14143 LValue CarryOutLValue;
14144 APSInt LHS, RHS, CarryIn, CarryOut, Result;
14145 QualType ResultType = E->getArg(0)->getType();
14146 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14147 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14148 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
14149 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
14150 return false;
14151 // Copy the number of bits and sign.
14152 Result = LHS;
14153 CarryOut = LHS;
14154
14155 bool FirstOverflowed = false;
14156 bool SecondOverflowed = false;
14157 switch (BuiltinOp) {
14158 default:
14159 llvm_unreachable("Invalid value for BuiltinOp");
14160 case Builtin::BI__builtin_addcb:
14161 case Builtin::BI__builtin_addcs:
14162 case Builtin::BI__builtin_addc:
14163 case Builtin::BI__builtin_addcl:
14164 case Builtin::BI__builtin_addcll:
14165 Result =
14166 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
14167 break;
14168 case Builtin::BI__builtin_subcb:
14169 case Builtin::BI__builtin_subcs:
14170 case Builtin::BI__builtin_subc:
14171 case Builtin::BI__builtin_subcl:
14172 case Builtin::BI__builtin_subcll:
14173 Result =
14174 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
14175 break;
14176 }
14177
14178 // It is possible for both overflows to happen but CGBuiltin uses an OR so
14179 // this is consistent.
14180 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
14181 APValue APV{CarryOut};
14182 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
14183 return false;
14184 return Success(Result, E);
14185 }
14186 case Builtin::BI__builtin_add_overflow:
14187 case Builtin::BI__builtin_sub_overflow:
14188 case Builtin::BI__builtin_mul_overflow:
14189 case Builtin::BI__builtin_sadd_overflow:
14190 case Builtin::BI__builtin_uadd_overflow:
14191 case Builtin::BI__builtin_uaddl_overflow:
14192 case Builtin::BI__builtin_uaddll_overflow:
14193 case Builtin::BI__builtin_usub_overflow:
14194 case Builtin::BI__builtin_usubl_overflow:
14195 case Builtin::BI__builtin_usubll_overflow:
14196 case Builtin::BI__builtin_umul_overflow:
14197 case Builtin::BI__builtin_umull_overflow:
14198 case Builtin::BI__builtin_umulll_overflow:
14199 case Builtin::BI__builtin_saddl_overflow:
14200 case Builtin::BI__builtin_saddll_overflow:
14201 case Builtin::BI__builtin_ssub_overflow:
14202 case Builtin::BI__builtin_ssubl_overflow:
14203 case Builtin::BI__builtin_ssubll_overflow:
14204 case Builtin::BI__builtin_smul_overflow:
14205 case Builtin::BI__builtin_smull_overflow:
14206 case Builtin::BI__builtin_smulll_overflow: {
14207 LValue ResultLValue;
14208 APSInt LHS, RHS;
14209
14210 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
14211 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
14212 !EvaluateInteger(E->getArg(1), RHS, Info) ||
14213 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
14214 return false;
14215
14216 APSInt Result;
14217 bool DidOverflow = false;
14218
14219 // If the types don't have to match, enlarge all 3 to the largest of them.
14220 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14221 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14222 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14223 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
14225 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
14227 uint64_t LHSSize = LHS.getBitWidth();
14228 uint64_t RHSSize = RHS.getBitWidth();
14229 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
14230 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
14231
14232 // Add an additional bit if the signedness isn't uniformly agreed to. We
14233 // could do this ONLY if there is a signed and an unsigned that both have
14234 // MaxBits, but the code to check that is pretty nasty. The issue will be
14235 // caught in the shrink-to-result later anyway.
14236 if (IsSigned && !AllSigned)
14237 ++MaxBits;
14238
14239 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
14240 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
14241 Result = APSInt(MaxBits, !IsSigned);
14242 }
14243
14244 // Find largest int.
14245 switch (BuiltinOp) {
14246 default:
14247 llvm_unreachable("Invalid value for BuiltinOp");
14248 case Builtin::BI__builtin_add_overflow:
14249 case Builtin::BI__builtin_sadd_overflow:
14250 case Builtin::BI__builtin_saddl_overflow:
14251 case Builtin::BI__builtin_saddll_overflow:
14252 case Builtin::BI__builtin_uadd_overflow:
14253 case Builtin::BI__builtin_uaddl_overflow:
14254 case Builtin::BI__builtin_uaddll_overflow:
14255 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
14256 : LHS.uadd_ov(RHS, DidOverflow);
14257 break;
14258 case Builtin::BI__builtin_sub_overflow:
14259 case Builtin::BI__builtin_ssub_overflow:
14260 case Builtin::BI__builtin_ssubl_overflow:
14261 case Builtin::BI__builtin_ssubll_overflow:
14262 case Builtin::BI__builtin_usub_overflow:
14263 case Builtin::BI__builtin_usubl_overflow:
14264 case Builtin::BI__builtin_usubll_overflow:
14265 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
14266 : LHS.usub_ov(RHS, DidOverflow);
14267 break;
14268 case Builtin::BI__builtin_mul_overflow:
14269 case Builtin::BI__builtin_smul_overflow:
14270 case Builtin::BI__builtin_smull_overflow:
14271 case Builtin::BI__builtin_smulll_overflow:
14272 case Builtin::BI__builtin_umul_overflow:
14273 case Builtin::BI__builtin_umull_overflow:
14274 case Builtin::BI__builtin_umulll_overflow:
14275 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
14276 : LHS.umul_ov(RHS, DidOverflow);
14277 break;
14278 }
14279
14280 // In the case where multiple sizes are allowed, truncate and see if
14281 // the values are the same.
14282 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
14283 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
14284 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
14285 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
14286 // since it will give us the behavior of a TruncOrSelf in the case where
14287 // its parameter <= its size. We previously set Result to be at least the
14288 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
14289 // will work exactly like TruncOrSelf.
14290 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
14291 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
14292
14293 if (!APSInt::isSameValue(Temp, Result))
14294 DidOverflow = true;
14295 Result = Temp;
14296 }
14297
14298 APValue APV{Result};
14299 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14300 return false;
14301 return Success(DidOverflow, E);
14302 }
14303
14304 case Builtin::BI__builtin_reduce_add:
14305 case Builtin::BI__builtin_reduce_mul:
14306 case Builtin::BI__builtin_reduce_and:
14307 case Builtin::BI__builtin_reduce_or:
14308 case Builtin::BI__builtin_reduce_xor:
14309 case Builtin::BI__builtin_reduce_min:
14310 case Builtin::BI__builtin_reduce_max: {
14311 APValue Source;
14312 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
14313 return false;
14314
14315 unsigned SourceLen = Source.getVectorLength();
14316 APSInt Reduced = Source.getVectorElt(0).getInt();
14317 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
14318 switch (BuiltinOp) {
14319 default:
14320 return false;
14321 case Builtin::BI__builtin_reduce_add: {
14323 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14324 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
14325 return false;
14326 break;
14327 }
14328 case Builtin::BI__builtin_reduce_mul: {
14330 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
14331 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
14332 return false;
14333 break;
14334 }
14335 case Builtin::BI__builtin_reduce_and: {
14336 Reduced &= Source.getVectorElt(EltNum).getInt();
14337 break;
14338 }
14339 case Builtin::BI__builtin_reduce_or: {
14340 Reduced |= Source.getVectorElt(EltNum).getInt();
14341 break;
14342 }
14343 case Builtin::BI__builtin_reduce_xor: {
14344 Reduced ^= Source.getVectorElt(EltNum).getInt();
14345 break;
14346 }
14347 case Builtin::BI__builtin_reduce_min: {
14348 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
14349 break;
14350 }
14351 case Builtin::BI__builtin_reduce_max: {
14352 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
14353 break;
14354 }
14355 }
14356 }
14357
14358 return Success(Reduced, E);
14359 }
14360
14361 case clang::X86::BI__builtin_ia32_addcarryx_u32:
14362 case clang::X86::BI__builtin_ia32_addcarryx_u64:
14363 case clang::X86::BI__builtin_ia32_subborrow_u32:
14364 case clang::X86::BI__builtin_ia32_subborrow_u64: {
14365 LValue ResultLValue;
14366 APSInt CarryIn, LHS, RHS;
14367 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
14368 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
14369 !EvaluateInteger(E->getArg(1), LHS, Info) ||
14370 !EvaluateInteger(E->getArg(2), RHS, Info) ||
14371 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
14372 return false;
14373
14374 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
14375 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
14376
14377 unsigned BitWidth = LHS.getBitWidth();
14378 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
14379 APInt ExResult =
14380 IsAdd
14381 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
14382 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
14383
14384 APInt Result = ExResult.extractBits(BitWidth, 0);
14385 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
14386
14387 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
14388 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
14389 return false;
14390 return Success(CarryOut, E);
14391 }
14392
14393 case clang::X86::BI__builtin_ia32_bextr_u32:
14394 case clang::X86::BI__builtin_ia32_bextr_u64:
14395 case clang::X86::BI__builtin_ia32_bextri_u32:
14396 case clang::X86::BI__builtin_ia32_bextri_u64: {
14397 APSInt Val, Idx;
14398 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14399 !EvaluateInteger(E->getArg(1), Idx, Info))
14400 return false;
14401
14402 unsigned BitWidth = Val.getBitWidth();
14403 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
14404 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
14405 Length = Length > BitWidth ? BitWidth : Length;
14406
14407 // Handle out of bounds cases.
14408 if (Length == 0 || Shift >= BitWidth)
14409 return Success(0, E);
14410
14411 uint64_t Result = Val.getZExtValue() >> Shift;
14412 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
14413 return Success(Result, E);
14414 }
14415
14416 case clang::X86::BI__builtin_ia32_bzhi_si:
14417 case clang::X86::BI__builtin_ia32_bzhi_di: {
14418 APSInt Val, Idx;
14419 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14420 !EvaluateInteger(E->getArg(1), Idx, Info))
14421 return false;
14422
14423 unsigned BitWidth = Val.getBitWidth();
14424 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
14425 if (Index < BitWidth)
14426 Val.clearHighBits(BitWidth - Index);
14427 return Success(Val, E);
14428 }
14429
14430 case clang::X86::BI__builtin_ia32_lzcnt_u16:
14431 case clang::X86::BI__builtin_ia32_lzcnt_u32:
14432 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
14433 APSInt Val;
14434 if (!EvaluateInteger(E->getArg(0), Val, Info))
14435 return false;
14436 return Success(Val.countLeadingZeros(), E);
14437 }
14438
14439 case clang::X86::BI__builtin_ia32_tzcnt_u16:
14440 case clang::X86::BI__builtin_ia32_tzcnt_u32:
14441 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
14442 APSInt Val;
14443 if (!EvaluateInteger(E->getArg(0), Val, Info))
14444 return false;
14445 return Success(Val.countTrailingZeros(), E);
14446 }
14447
14448 case clang::X86::BI__builtin_ia32_pdep_si:
14449 case clang::X86::BI__builtin_ia32_pdep_di: {
14450 APSInt Val, Msk;
14451 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14452 !EvaluateInteger(E->getArg(1), Msk, Info))
14453 return false;
14454
14455 unsigned BitWidth = Val.getBitWidth();
14456 APInt Result = APInt::getZero(BitWidth);
14457 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14458 if (Msk[I])
14459 Result.setBitVal(I, Val[P++]);
14460 return Success(Result, E);
14461 }
14462
14463 case clang::X86::BI__builtin_ia32_pext_si:
14464 case clang::X86::BI__builtin_ia32_pext_di: {
14465 APSInt Val, Msk;
14466 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
14467 !EvaluateInteger(E->getArg(1), Msk, Info))
14468 return false;
14469
14470 unsigned BitWidth = Val.getBitWidth();
14471 APInt Result = APInt::getZero(BitWidth);
14472 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
14473 if (Msk[I])
14474 Result.setBitVal(P++, Val[I]);
14475 return Success(Result, E);
14476 }
14477 }
14478}
14479
14480/// Determine whether this is a pointer past the end of the complete
14481/// object referred to by the lvalue.
14483 const LValue &LV) {
14484 // A null pointer can be viewed as being "past the end" but we don't
14485 // choose to look at it that way here.
14486 if (!LV.getLValueBase())
14487 return false;
14488
14489 // If the designator is valid and refers to a subobject, we're not pointing
14490 // past the end.
14491 if (!LV.getLValueDesignator().Invalid &&
14492 !LV.getLValueDesignator().isOnePastTheEnd())
14493 return false;
14494
14495 // A pointer to an incomplete type might be past-the-end if the type's size is
14496 // zero. We cannot tell because the type is incomplete.
14497 QualType Ty = getType(LV.getLValueBase());
14498 if (Ty->isIncompleteType())
14499 return true;
14500
14501 // Can't be past the end of an invalid object.
14502 if (LV.getLValueDesignator().Invalid)
14503 return false;
14504
14505 // We're a past-the-end pointer if we point to the byte after the object,
14506 // no matter what our type or path is.
14507 auto Size = Ctx.getTypeSizeInChars(Ty);
14508 return LV.getLValueOffset() == Size;
14509}
14510
14511namespace {
14512
14513/// Data recursive integer evaluator of certain binary operators.
14514///
14515/// We use a data recursive algorithm for binary operators so that we are able
14516/// to handle extreme cases of chained binary operators without causing stack
14517/// overflow.
14518class DataRecursiveIntBinOpEvaluator {
14519 struct EvalResult {
14520 APValue Val;
14521 bool Failed = false;
14522
14523 EvalResult() = default;
14524
14525 void swap(EvalResult &RHS) {
14526 Val.swap(RHS.Val);
14527 Failed = RHS.Failed;
14528 RHS.Failed = false;
14529 }
14530 };
14531
14532 struct Job {
14533 const Expr *E;
14534 EvalResult LHSResult; // meaningful only for binary operator expression.
14535 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
14536
14537 Job() = default;
14538 Job(Job &&) = default;
14539
14540 void startSpeculativeEval(EvalInfo &Info) {
14541 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
14542 }
14543
14544 private:
14545 SpeculativeEvaluationRAII SpecEvalRAII;
14546 };
14547
14549
14550 IntExprEvaluator &IntEval;
14551 EvalInfo &Info;
14552 APValue &FinalResult;
14553
14554public:
14555 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
14556 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
14557
14558 /// True if \param E is a binary operator that we are going to handle
14559 /// data recursively.
14560 /// We handle binary operators that are comma, logical, or that have operands
14561 /// with integral or enumeration type.
14562 static bool shouldEnqueue(const BinaryOperator *E) {
14563 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
14565 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14566 E->getRHS()->getType()->isIntegralOrEnumerationType());
14567 }
14568
14569 bool Traverse(const BinaryOperator *E) {
14570 enqueue(E);
14571 EvalResult PrevResult;
14572 while (!Queue.empty())
14573 process(PrevResult);
14574
14575 if (PrevResult.Failed) return false;
14576
14577 FinalResult.swap(PrevResult.Val);
14578 return true;
14579 }
14580
14581private:
14582 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14583 return IntEval.Success(Value, E, Result);
14584 }
14585 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
14586 return IntEval.Success(Value, E, Result);
14587 }
14588 bool Error(const Expr *E) {
14589 return IntEval.Error(E);
14590 }
14591 bool Error(const Expr *E, diag::kind D) {
14592 return IntEval.Error(E, D);
14593 }
14594
14595 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14596 return Info.CCEDiag(E, D);
14597 }
14598
14599 // Returns true if visiting the RHS is necessary, false otherwise.
14600 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14601 bool &SuppressRHSDiags);
14602
14603 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14604 const BinaryOperator *E, APValue &Result);
14605
14606 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14607 Result.Failed = !Evaluate(Result.Val, Info, E);
14608 if (Result.Failed)
14609 Result.Val = APValue();
14610 }
14611
14612 void process(EvalResult &Result);
14613
14614 void enqueue(const Expr *E) {
14615 E = E->IgnoreParens();
14616 Queue.resize(Queue.size()+1);
14617 Queue.back().E = E;
14618 Queue.back().Kind = Job::AnyExprKind;
14619 }
14620};
14621
14622}
14623
14624bool DataRecursiveIntBinOpEvaluator::
14625 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14626 bool &SuppressRHSDiags) {
14627 if (E->getOpcode() == BO_Comma) {
14628 // Ignore LHS but note if we could not evaluate it.
14629 if (LHSResult.Failed)
14630 return Info.noteSideEffect();
14631 return true;
14632 }
14633
14634 if (E->isLogicalOp()) {
14635 bool LHSAsBool;
14636 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14637 // We were able to evaluate the LHS, see if we can get away with not
14638 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14639 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14640 Success(LHSAsBool, E, LHSResult.Val);
14641 return false; // Ignore RHS
14642 }
14643 } else {
14644 LHSResult.Failed = true;
14645
14646 // Since we weren't able to evaluate the left hand side, it
14647 // might have had side effects.
14648 if (!Info.noteSideEffect())
14649 return false;
14650
14651 // We can't evaluate the LHS; however, sometimes the result
14652 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14653 // Don't ignore RHS and suppress diagnostics from this arm.
14654 SuppressRHSDiags = true;
14655 }
14656
14657 return true;
14658 }
14659
14660 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14661 E->getRHS()->getType()->isIntegralOrEnumerationType());
14662
14663 if (LHSResult.Failed && !Info.noteFailure())
14664 return false; // Ignore RHS;
14665
14666 return true;
14667}
14668
14669static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14670 bool IsSub) {
14671 // Compute the new offset in the appropriate width, wrapping at 64 bits.
14672 // FIXME: When compiling for a 32-bit target, we should use 32-bit
14673 // offsets.
14674 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14675 CharUnits &Offset = LVal.getLValueOffset();
14676 uint64_t Offset64 = Offset.getQuantity();
14677 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14678 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14679 : Offset64 + Index64);
14680}
14681
14682bool DataRecursiveIntBinOpEvaluator::
14683 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14684 const BinaryOperator *E, APValue &Result) {
14685 if (E->getOpcode() == BO_Comma) {
14686 if (RHSResult.Failed)
14687 return false;
14688 Result = RHSResult.Val;
14689 return true;
14690 }
14691
14692 if (E->isLogicalOp()) {
14693 bool lhsResult, rhsResult;
14694 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14695 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14696
14697 if (LHSIsOK) {
14698 if (RHSIsOK) {
14699 if (E->getOpcode() == BO_LOr)
14700 return Success(lhsResult || rhsResult, E, Result);
14701 else
14702 return Success(lhsResult && rhsResult, E, Result);
14703 }
14704 } else {
14705 if (RHSIsOK) {
14706 // We can't evaluate the LHS; however, sometimes the result
14707 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14708 if (rhsResult == (E->getOpcode() == BO_LOr))
14709 return Success(rhsResult, E, Result);
14710 }
14711 }
14712
14713 return false;
14714 }
14715
14716 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14717 E->getRHS()->getType()->isIntegralOrEnumerationType());
14718
14719 if (LHSResult.Failed || RHSResult.Failed)
14720 return false;
14721
14722 const APValue &LHSVal = LHSResult.Val;
14723 const APValue &RHSVal = RHSResult.Val;
14724
14725 // Handle cases like (unsigned long)&a + 4.
14726 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14727 Result = LHSVal;
14728 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14729 return true;
14730 }
14731
14732 // Handle cases like 4 + (unsigned long)&a
14733 if (E->getOpcode() == BO_Add &&
14734 RHSVal.isLValue() && LHSVal.isInt()) {
14735 Result = RHSVal;
14736 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14737 return true;
14738 }
14739
14740 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14741 // Handle (intptr_t)&&A - (intptr_t)&&B.
14742 if (!LHSVal.getLValueOffset().isZero() ||
14743 !RHSVal.getLValueOffset().isZero())
14744 return false;
14745 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14746 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14747 if (!LHSExpr || !RHSExpr)
14748 return false;
14749 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14750 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14751 if (!LHSAddrExpr || !RHSAddrExpr)
14752 return false;
14753 // Make sure both labels come from the same function.
14754 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14755 RHSAddrExpr->getLabel()->getDeclContext())
14756 return false;
14757 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14758 return true;
14759 }
14760
14761 // All the remaining cases expect both operands to be an integer
14762 if (!LHSVal.isInt() || !RHSVal.isInt())
14763 return Error(E);
14764
14765 // Set up the width and signedness manually, in case it can't be deduced
14766 // from the operation we're performing.
14767 // FIXME: Don't do this in the cases where we can deduce it.
14768 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14770 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14771 RHSVal.getInt(), Value))
14772 return false;
14773 return Success(Value, E, Result);
14774}
14775
14776void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14777 Job &job = Queue.back();
14778
14779 switch (job.Kind) {
14780 case Job::AnyExprKind: {
14781 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14782 if (shouldEnqueue(Bop)) {
14783 job.Kind = Job::BinOpKind;
14784 enqueue(Bop->getLHS());
14785 return;
14786 }
14787 }
14788
14789 EvaluateExpr(job.E, Result);
14790 Queue.pop_back();
14791 return;
14792 }
14793
14794 case Job::BinOpKind: {
14795 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14796 bool SuppressRHSDiags = false;
14797 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14798 Queue.pop_back();
14799 return;
14800 }
14801 if (SuppressRHSDiags)
14802 job.startSpeculativeEval(Info);
14803 job.LHSResult.swap(Result);
14804 job.Kind = Job::BinOpVisitedLHSKind;
14805 enqueue(Bop->getRHS());
14806 return;
14807 }
14808
14809 case Job::BinOpVisitedLHSKind: {
14810 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14811 EvalResult RHS;
14812 RHS.swap(Result);
14813 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14814 Queue.pop_back();
14815 return;
14816 }
14817 }
14818
14819 llvm_unreachable("Invalid Job::Kind!");
14820}
14821
14822namespace {
14823enum class CmpResult {
14824 Unequal,
14825 Less,
14826 Equal,
14827 Greater,
14828 Unordered,
14829};
14830}
14831
14832template <class SuccessCB, class AfterCB>
14833static bool
14835 SuccessCB &&Success, AfterCB &&DoAfter) {
14836 assert(!E->isValueDependent());
14837 assert(E->isComparisonOp() && "expected comparison operator");
14838 assert((E->getOpcode() == BO_Cmp ||
14840 "unsupported binary expression evaluation");
14841 auto Error = [&](const Expr *E) {
14842 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14843 return false;
14844 };
14845
14846 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14847 bool IsEquality = E->isEqualityOp();
14848
14849 QualType LHSTy = E->getLHS()->getType();
14850 QualType RHSTy = E->getRHS()->getType();
14851
14852 if (LHSTy->isIntegralOrEnumerationType() &&
14853 RHSTy->isIntegralOrEnumerationType()) {
14854 APSInt LHS, RHS;
14855 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14856 if (!LHSOK && !Info.noteFailure())
14857 return false;
14858 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14859 return false;
14860 if (LHS < RHS)
14861 return Success(CmpResult::Less, E);
14862 if (LHS > RHS)
14863 return Success(CmpResult::Greater, E);
14864 return Success(CmpResult::Equal, E);
14865 }
14866
14867 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14868 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14869 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14870
14871 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14872 if (!LHSOK && !Info.noteFailure())
14873 return false;
14874 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14875 return false;
14876 if (LHSFX < RHSFX)
14877 return Success(CmpResult::Less, E);
14878 if (LHSFX > RHSFX)
14879 return Success(CmpResult::Greater, E);
14880 return Success(CmpResult::Equal, E);
14881 }
14882
14883 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14884 ComplexValue LHS, RHS;
14885 bool LHSOK;
14886 if (E->isAssignmentOp()) {
14887 LValue LV;
14888 EvaluateLValue(E->getLHS(), LV, Info);
14889 LHSOK = false;
14890 } else if (LHSTy->isRealFloatingType()) {
14891 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14892 if (LHSOK) {
14893 LHS.makeComplexFloat();
14894 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14895 }
14896 } else {
14897 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14898 }
14899 if (!LHSOK && !Info.noteFailure())
14900 return false;
14901
14902 if (E->getRHS()->getType()->isRealFloatingType()) {
14903 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14904 return false;
14905 RHS.makeComplexFloat();
14906 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14907 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14908 return false;
14909
14910 if (LHS.isComplexFloat()) {
14911 APFloat::cmpResult CR_r =
14912 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14913 APFloat::cmpResult CR_i =
14914 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14915 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14916 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14917 } else {
14918 assert(IsEquality && "invalid complex comparison");
14919 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14920 LHS.getComplexIntImag() == RHS.getComplexIntImag();
14921 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14922 }
14923 }
14924
14925 if (LHSTy->isRealFloatingType() &&
14926 RHSTy->isRealFloatingType()) {
14927 APFloat RHS(0.0), LHS(0.0);
14928
14929 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14930 if (!LHSOK && !Info.noteFailure())
14931 return false;
14932
14933 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14934 return false;
14935
14936 assert(E->isComparisonOp() && "Invalid binary operator!");
14937 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14938 if (!Info.InConstantContext &&
14939 APFloatCmpResult == APFloat::cmpUnordered &&
14940 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14941 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14942 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14943 return false;
14944 }
14945 auto GetCmpRes = [&]() {
14946 switch (APFloatCmpResult) {
14947 case APFloat::cmpEqual:
14948 return CmpResult::Equal;
14949 case APFloat::cmpLessThan:
14950 return CmpResult::Less;
14951 case APFloat::cmpGreaterThan:
14952 return CmpResult::Greater;
14953 case APFloat::cmpUnordered:
14954 return CmpResult::Unordered;
14955 }
14956 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14957 };
14958 return Success(GetCmpRes(), E);
14959 }
14960
14961 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14962 LValue LHSValue, RHSValue;
14963
14964 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14965 if (!LHSOK && !Info.noteFailure())
14966 return false;
14967
14968 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14969 return false;
14970
14971 // Reject differing bases from the normal codepath; we special-case
14972 // comparisons to null.
14973 if (!HasSameBase(LHSValue, RHSValue)) {
14974 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14975 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14976 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14977 Info.FFDiag(E, DiagID)
14978 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14979 return false;
14980 };
14981 // Inequalities and subtractions between unrelated pointers have
14982 // unspecified or undefined behavior.
14983 if (!IsEquality)
14984 return DiagComparison(
14985 diag::note_constexpr_pointer_comparison_unspecified);
14986 // A constant address may compare equal to the address of a symbol.
14987 // The one exception is that address of an object cannot compare equal
14988 // to a null pointer constant.
14989 // TODO: Should we restrict this to actual null pointers, and exclude the
14990 // case of zero cast to pointer type?
14991 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14992 (!RHSValue.Base && !RHSValue.Offset.isZero()))
14993 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14994 !RHSValue.Base);
14995 // C++2c [intro.object]/10:
14996 // Two objects [...] may have the same address if [...] they are both
14997 // potentially non-unique objects.
14998 // C++2c [intro.object]/9:
14999 // An object is potentially non-unique if it is a string literal object,
15000 // the backing array of an initializer list, or a subobject thereof.
15001 //
15002 // This makes the comparison result unspecified, so it's not a constant
15003 // expression.
15004 //
15005 // TODO: Do we need to handle the initializer list case here?
15006 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15007 return DiagComparison(diag::note_constexpr_literal_comparison);
15008 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
15009 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
15010 !IsOpaqueConstantCall(LHSValue));
15011 // We can't tell whether weak symbols will end up pointing to the same
15012 // object.
15013 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
15014 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
15015 !IsWeakLValue(LHSValue));
15016 // We can't compare the address of the start of one object with the
15017 // past-the-end address of another object, per C++ DR1652.
15018 if (LHSValue.Base && LHSValue.Offset.isZero() &&
15019 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
15020 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15021 true);
15022 if (RHSValue.Base && RHSValue.Offset.isZero() &&
15023 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
15024 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
15025 false);
15026 // We can't tell whether an object is at the same address as another
15027 // zero sized object.
15028 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
15029 (LHSValue.Base && isZeroSized(RHSValue)))
15030 return DiagComparison(
15031 diag::note_constexpr_pointer_comparison_zero_sized);
15032 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
15033 return DiagComparison(
15034 diag::note_constexpr_pointer_comparison_unspecified);
15035 // FIXME: Verify both variables are live.
15036 return Success(CmpResult::Unequal, E);
15037 }
15038
15039 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15040 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15041
15042 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15043 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15044
15045 // C++11 [expr.rel]p2:
15046 // - If two pointers point to non-static data members of the same object,
15047 // or to subobjects or array elements fo such members, recursively, the
15048 // pointer to the later declared member compares greater provided the
15049 // two members have the same access control and provided their class is
15050 // not a union.
15051 // [...]
15052 // - Otherwise pointer comparisons are unspecified.
15053 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
15054 bool WasArrayIndex;
15055 unsigned Mismatch = FindDesignatorMismatch(
15056 LHSValue.Base.isNull() ? QualType()
15057 : getType(LHSValue.Base).getNonReferenceType(),
15058 LHSDesignator, RHSDesignator, WasArrayIndex);
15059 // At the point where the designators diverge, the comparison has a
15060 // specified value if:
15061 // - we are comparing array indices
15062 // - we are comparing fields of a union, or fields with the same access
15063 // Otherwise, the result is unspecified and thus the comparison is not a
15064 // constant expression.
15065 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
15066 Mismatch < RHSDesignator.Entries.size()) {
15067 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
15068 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
15069 if (!LF && !RF)
15070 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
15071 else if (!LF)
15072 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15073 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
15074 << RF->getParent() << RF;
15075 else if (!RF)
15076 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
15077 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
15078 << LF->getParent() << LF;
15079 else if (!LF->getParent()->isUnion() &&
15080 LF->getAccess() != RF->getAccess())
15081 Info.CCEDiag(E,
15082 diag::note_constexpr_pointer_comparison_differing_access)
15083 << LF << LF->getAccess() << RF << RF->getAccess()
15084 << LF->getParent();
15085 }
15086 }
15087
15088 // The comparison here must be unsigned, and performed with the same
15089 // width as the pointer.
15090 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
15091 uint64_t CompareLHS = LHSOffset.getQuantity();
15092 uint64_t CompareRHS = RHSOffset.getQuantity();
15093 assert(PtrSize <= 64 && "Unexpected pointer width");
15094 uint64_t Mask = ~0ULL >> (64 - PtrSize);
15095 CompareLHS &= Mask;
15096 CompareRHS &= Mask;
15097
15098 // If there is a base and this is a relational operator, we can only
15099 // compare pointers within the object in question; otherwise, the result
15100 // depends on where the object is located in memory.
15101 if (!LHSValue.Base.isNull() && IsRelational) {
15102 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
15103 if (BaseTy->isIncompleteType())
15104 return Error(E);
15105 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
15106 uint64_t OffsetLimit = Size.getQuantity();
15107 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
15108 return Error(E);
15109 }
15110
15111 if (CompareLHS < CompareRHS)
15112 return Success(CmpResult::Less, E);
15113 if (CompareLHS > CompareRHS)
15114 return Success(CmpResult::Greater, E);
15115 return Success(CmpResult::Equal, E);
15116 }
15117
15118 if (LHSTy->isMemberPointerType()) {
15119 assert(IsEquality && "unexpected member pointer operation");
15120 assert(RHSTy->isMemberPointerType() && "invalid comparison");
15121
15122 MemberPtr LHSValue, RHSValue;
15123
15124 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
15125 if (!LHSOK && !Info.noteFailure())
15126 return false;
15127
15128 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15129 return false;
15130
15131 // If either operand is a pointer to a weak function, the comparison is not
15132 // constant.
15133 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
15134 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15135 << LHSValue.getDecl();
15136 return false;
15137 }
15138 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
15139 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
15140 << RHSValue.getDecl();
15141 return false;
15142 }
15143
15144 // C++11 [expr.eq]p2:
15145 // If both operands are null, they compare equal. Otherwise if only one is
15146 // null, they compare unequal.
15147 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
15148 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
15149 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15150 }
15151
15152 // Otherwise if either is a pointer to a virtual member function, the
15153 // result is unspecified.
15154 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
15155 if (MD->isVirtual())
15156 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15157 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
15158 if (MD->isVirtual())
15159 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
15160
15161 // Otherwise they compare equal if and only if they would refer to the
15162 // same member of the same most derived object or the same subobject if
15163 // they were dereferenced with a hypothetical object of the associated
15164 // class type.
15165 bool Equal = LHSValue == RHSValue;
15166 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
15167 }
15168
15169 if (LHSTy->isNullPtrType()) {
15170 assert(E->isComparisonOp() && "unexpected nullptr operation");
15171 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
15172 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
15173 // are compared, the result is true of the operator is <=, >= or ==, and
15174 // false otherwise.
15175 LValue Res;
15176 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
15177 !EvaluatePointer(E->getRHS(), Res, Info))
15178 return false;
15179 return Success(CmpResult::Equal, E);
15180 }
15181
15182 return DoAfter();
15183}
15184
15185bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
15186 if (!CheckLiteralType(Info, E))
15187 return false;
15188
15189 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15191 switch (CR) {
15192 case CmpResult::Unequal:
15193 llvm_unreachable("should never produce Unequal for three-way comparison");
15194 case CmpResult::Less:
15195 CCR = ComparisonCategoryResult::Less;
15196 break;
15197 case CmpResult::Equal:
15198 CCR = ComparisonCategoryResult::Equal;
15199 break;
15200 case CmpResult::Greater:
15201 CCR = ComparisonCategoryResult::Greater;
15202 break;
15203 case CmpResult::Unordered:
15204 CCR = ComparisonCategoryResult::Unordered;
15205 break;
15206 }
15207 // Evaluation succeeded. Lookup the information for the comparison category
15208 // type and fetch the VarDecl for the result.
15209 const ComparisonCategoryInfo &CmpInfo =
15211 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
15212 // Check and evaluate the result as a constant expression.
15213 LValue LV;
15214 LV.set(VD);
15215 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15216 return false;
15217 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15218 ConstantExprKind::Normal);
15219 };
15220 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15221 return ExprEvaluatorBaseTy::VisitBinCmp(E);
15222 });
15223}
15224
15225bool RecordExprEvaluator::VisitCXXParenListInitExpr(
15226 const CXXParenListInitExpr *E) {
15227 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
15228}
15229
15230bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15231 // We don't support assignment in C. C++ assignments don't get here because
15232 // assignment is an lvalue in C++.
15233 if (E->isAssignmentOp()) {
15234 Error(E);
15235 if (!Info.noteFailure())
15236 return false;
15237 }
15238
15239 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
15240 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
15241
15242 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
15243 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
15244 "DataRecursiveIntBinOpEvaluator should have handled integral types");
15245
15246 if (E->isComparisonOp()) {
15247 // Evaluate builtin binary comparisons by evaluating them as three-way
15248 // comparisons and then translating the result.
15249 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
15250 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
15251 "should only produce Unequal for equality comparisons");
15252 bool IsEqual = CR == CmpResult::Equal,
15253 IsLess = CR == CmpResult::Less,
15254 IsGreater = CR == CmpResult::Greater;
15255 auto Op = E->getOpcode();
15256 switch (Op) {
15257 default:
15258 llvm_unreachable("unsupported binary operator");
15259 case BO_EQ:
15260 case BO_NE:
15261 return Success(IsEqual == (Op == BO_EQ), E);
15262 case BO_LT:
15263 return Success(IsLess, E);
15264 case BO_GT:
15265 return Success(IsGreater, E);
15266 case BO_LE:
15267 return Success(IsEqual || IsLess, E);
15268 case BO_GE:
15269 return Success(IsEqual || IsGreater, E);
15270 }
15271 };
15272 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
15273 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15274 });
15275 }
15276
15277 QualType LHSTy = E->getLHS()->getType();
15278 QualType RHSTy = E->getRHS()->getType();
15279
15280 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
15281 E->getOpcode() == BO_Sub) {
15282 LValue LHSValue, RHSValue;
15283
15284 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
15285 if (!LHSOK && !Info.noteFailure())
15286 return false;
15287
15288 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
15289 return false;
15290
15291 // Reject differing bases from the normal codepath; we special-case
15292 // comparisons to null.
15293 if (!HasSameBase(LHSValue, RHSValue)) {
15294 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
15295 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
15296
15297 auto DiagArith = [&](unsigned DiagID) {
15298 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
15299 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
15300 Info.FFDiag(E, DiagID) << LHS << RHS;
15301 if (LHSExpr && LHSExpr == RHSExpr)
15302 Info.Note(LHSExpr->getExprLoc(),
15303 diag::note_constexpr_repeated_literal_eval)
15304 << LHSExpr->getSourceRange();
15305 return false;
15306 };
15307
15308 if (!LHSExpr || !RHSExpr)
15309 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
15310
15311 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
15312 return DiagArith(diag::note_constexpr_literal_arith);
15313
15314 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
15315 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
15316 if (!LHSAddrExpr || !RHSAddrExpr)
15317 return Error(E);
15318 // Make sure both labels come from the same function.
15319 if (LHSAddrExpr->getLabel()->getDeclContext() !=
15320 RHSAddrExpr->getLabel()->getDeclContext())
15321 return Error(E);
15322 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
15323 }
15324 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
15325 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
15326
15327 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
15328 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
15329
15330 // C++11 [expr.add]p6:
15331 // Unless both pointers point to elements of the same array object, or
15332 // one past the last element of the array object, the behavior is
15333 // undefined.
15334 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
15335 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
15336 RHSDesignator))
15337 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
15338
15339 QualType Type = E->getLHS()->getType();
15340 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
15341
15342 CharUnits ElementSize;
15343 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
15344 return false;
15345
15346 // As an extension, a type may have zero size (empty struct or union in
15347 // C, array of zero length). Pointer subtraction in such cases has
15348 // undefined behavior, so is not constant.
15349 if (ElementSize.isZero()) {
15350 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
15351 << ElementType;
15352 return false;
15353 }
15354
15355 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
15356 // and produce incorrect results when it overflows. Such behavior
15357 // appears to be non-conforming, but is common, so perhaps we should
15358 // assume the standard intended for such cases to be undefined behavior
15359 // and check for them.
15360
15361 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
15362 // overflow in the final conversion to ptrdiff_t.
15363 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
15364 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
15365 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
15366 false);
15367 APSInt TrueResult = (LHS - RHS) / ElemSize;
15368 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
15369
15370 if (Result.extend(65) != TrueResult &&
15371 !HandleOverflow(Info, E, TrueResult, E->getType()))
15372 return false;
15373 return Success(Result, E);
15374 }
15375
15376 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15377}
15378
15379/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
15380/// a result as the expression's type.
15381bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
15382 const UnaryExprOrTypeTraitExpr *E) {
15383 switch(E->getKind()) {
15384 case UETT_PreferredAlignOf:
15385 case UETT_AlignOf: {
15386 if (E->isArgumentType())
15387 return Success(
15388 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
15389 else
15390 return Success(
15391 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
15392 }
15393
15394 case UETT_PtrAuthTypeDiscriminator: {
15395 if (E->getArgumentType()->isDependentType())
15396 return false;
15397 return Success(
15398 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
15399 }
15400 case UETT_VecStep: {
15401 QualType Ty = E->getTypeOfArgument();
15402
15403 if (Ty->isVectorType()) {
15404 unsigned n = Ty->castAs<VectorType>()->getNumElements();
15405
15406 // The vec_step built-in functions that take a 3-component
15407 // vector return 4. (OpenCL 1.1 spec 6.11.12)
15408 if (n == 3)
15409 n = 4;
15410
15411 return Success(n, E);
15412 } else
15413 return Success(1, E);
15414 }
15415
15416 case UETT_DataSizeOf:
15417 case UETT_SizeOf: {
15418 QualType SrcTy = E->getTypeOfArgument();
15419 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
15420 // the result is the size of the referenced type."
15421 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
15422 SrcTy = Ref->getPointeeType();
15423
15424 CharUnits Sizeof;
15425 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
15426 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
15427 : SizeOfType::SizeOf)) {
15428 return false;
15429 }
15430 return Success(Sizeof, E);
15431 }
15432 case UETT_OpenMPRequiredSimdAlign:
15433 assert(E->isArgumentType());
15434 return Success(
15435 Info.Ctx.toCharUnitsFromBits(
15436 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
15437 .getQuantity(),
15438 E);
15439 case UETT_VectorElements: {
15440 QualType Ty = E->getTypeOfArgument();
15441 // If the vector has a fixed size, we can determine the number of elements
15442 // at compile time.
15443 if (const auto *VT = Ty->getAs<VectorType>())
15444 return Success(VT->getNumElements(), E);
15445
15446 assert(Ty->isSizelessVectorType());
15447 if (Info.InConstantContext)
15448 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
15449 << E->getSourceRange();
15450
15451 return false;
15452 }
15453 case UETT_CountOf: {
15454 QualType Ty = E->getTypeOfArgument();
15455 assert(Ty->isArrayType());
15456
15457 // We don't need to worry about array element qualifiers, so getting the
15458 // unsafe array type is fine.
15459 if (const auto *CAT =
15460 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
15461 return Success(CAT->getSize(), E);
15462 }
15463
15464 assert(!Ty->isConstantSizeType());
15465
15466 // If it's a variable-length array type, we need to check whether it is a
15467 // multidimensional array. If so, we need to check the size expression of
15468 // the VLA to see if it's a constant size. If so, we can return that value.
15469 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
15470 assert(VAT);
15471 if (VAT->getElementType()->isArrayType()) {
15472 // Variable array size expression could be missing (e.g. int a[*][10]) In
15473 // that case, it can't be a constant expression.
15474 if (!VAT->getSizeExpr()) {
15475 Info.FFDiag(E->getBeginLoc());
15476 return false;
15477 }
15478
15479 std::optional<APSInt> Res =
15480 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
15481 if (Res) {
15482 // The resulting value always has type size_t, so we need to make the
15483 // returned APInt have the correct sign and bit-width.
15484 APInt Val{
15485 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
15486 Res->getZExtValue()};
15487 return Success(Val, E);
15488 }
15489 }
15490
15491 // Definitely a variable-length type, which is not an ICE.
15492 // FIXME: Better diagnostic.
15493 Info.FFDiag(E->getBeginLoc());
15494 return false;
15495 }
15496 }
15497
15498 llvm_unreachable("unknown expr/type trait");
15499}
15500
15501bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
15502 CharUnits Result;
15503 unsigned n = OOE->getNumComponents();
15504 if (n == 0)
15505 return Error(OOE);
15506 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
15507 for (unsigned i = 0; i != n; ++i) {
15508 OffsetOfNode ON = OOE->getComponent(i);
15509 switch (ON.getKind()) {
15510 case OffsetOfNode::Array: {
15511 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
15512 APSInt IdxResult;
15513 if (!EvaluateInteger(Idx, IdxResult, Info))
15514 return false;
15515 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
15516 if (!AT)
15517 return Error(OOE);
15518 CurrentType = AT->getElementType();
15519 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
15520 Result += IdxResult.getSExtValue() * ElementSize;
15521 break;
15522 }
15523
15524 case OffsetOfNode::Field: {
15525 FieldDecl *MemberDecl = ON.getField();
15526 const auto *RD = CurrentType->getAsRecordDecl();
15527 if (!RD)
15528 return Error(OOE);
15529 if (RD->isInvalidDecl()) return false;
15530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15531 unsigned i = MemberDecl->getFieldIndex();
15532 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
15533 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
15534 CurrentType = MemberDecl->getType().getNonReferenceType();
15535 break;
15536 }
15537
15539 llvm_unreachable("dependent __builtin_offsetof");
15540
15541 case OffsetOfNode::Base: {
15542 CXXBaseSpecifier *BaseSpec = ON.getBase();
15543 if (BaseSpec->isVirtual())
15544 return Error(OOE);
15545
15546 // Find the layout of the class whose base we are looking into.
15547 const auto *RD = CurrentType->getAsCXXRecordDecl();
15548 if (!RD)
15549 return Error(OOE);
15550 if (RD->isInvalidDecl()) return false;
15551 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
15552
15553 // Find the base class itself.
15554 CurrentType = BaseSpec->getType();
15555 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
15556 if (!BaseRD)
15557 return Error(OOE);
15558
15559 // Add the offset to the base.
15560 Result += RL.getBaseClassOffset(BaseRD);
15561 break;
15562 }
15563 }
15564 }
15565 return Success(Result, OOE);
15566}
15567
15568bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15569 switch (E->getOpcode()) {
15570 default:
15571 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
15572 // See C99 6.6p3.
15573 return Error(E);
15574 case UO_Extension:
15575 // FIXME: Should extension allow i-c-e extension expressions in its scope?
15576 // If so, we could clear the diagnostic ID.
15577 return Visit(E->getSubExpr());
15578 case UO_Plus:
15579 // The result is just the value.
15580 return Visit(E->getSubExpr());
15581 case UO_Minus: {
15582 if (!Visit(E->getSubExpr()))
15583 return false;
15584 if (!Result.isInt()) return Error(E);
15585 const APSInt &Value = Result.getInt();
15586 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
15587 if (Info.checkingForUndefinedBehavior())
15588 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15589 diag::warn_integer_constant_overflow)
15590 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
15591 /*UpperCase=*/true, /*InsertSeparators=*/true)
15592 << E->getType() << E->getSourceRange();
15593
15594 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
15595 E->getType()))
15596 return false;
15597 }
15598 return Success(-Value, E);
15599 }
15600 case UO_Not: {
15601 if (!Visit(E->getSubExpr()))
15602 return false;
15603 if (!Result.isInt()) return Error(E);
15604 return Success(~Result.getInt(), E);
15605 }
15606 case UO_LNot: {
15607 bool bres;
15608 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15609 return false;
15610 return Success(!bres, E);
15611 }
15612 }
15613}
15614
15615/// HandleCast - This is used to evaluate implicit or explicit casts where the
15616/// result type is integer.
15617bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
15618 const Expr *SubExpr = E->getSubExpr();
15619 QualType DestType = E->getType();
15620 QualType SrcType = SubExpr->getType();
15621
15622 switch (E->getCastKind()) {
15623 case CK_BaseToDerived:
15624 case CK_DerivedToBase:
15625 case CK_UncheckedDerivedToBase:
15626 case CK_Dynamic:
15627 case CK_ToUnion:
15628 case CK_ArrayToPointerDecay:
15629 case CK_FunctionToPointerDecay:
15630 case CK_NullToPointer:
15631 case CK_NullToMemberPointer:
15632 case CK_BaseToDerivedMemberPointer:
15633 case CK_DerivedToBaseMemberPointer:
15634 case CK_ReinterpretMemberPointer:
15635 case CK_ConstructorConversion:
15636 case CK_IntegralToPointer:
15637 case CK_ToVoid:
15638 case CK_VectorSplat:
15639 case CK_IntegralToFloating:
15640 case CK_FloatingCast:
15641 case CK_CPointerToObjCPointerCast:
15642 case CK_BlockPointerToObjCPointerCast:
15643 case CK_AnyPointerToBlockPointerCast:
15644 case CK_ObjCObjectLValueCast:
15645 case CK_FloatingRealToComplex:
15646 case CK_FloatingComplexToReal:
15647 case CK_FloatingComplexCast:
15648 case CK_FloatingComplexToIntegralComplex:
15649 case CK_IntegralRealToComplex:
15650 case CK_IntegralComplexCast:
15651 case CK_IntegralComplexToFloatingComplex:
15652 case CK_BuiltinFnToFnPtr:
15653 case CK_ZeroToOCLOpaqueType:
15654 case CK_NonAtomicToAtomic:
15655 case CK_AddressSpaceConversion:
15656 case CK_IntToOCLSampler:
15657 case CK_FloatingToFixedPoint:
15658 case CK_FixedPointToFloating:
15659 case CK_FixedPointCast:
15660 case CK_IntegralToFixedPoint:
15661 case CK_MatrixCast:
15662 case CK_HLSLAggregateSplatCast:
15663 llvm_unreachable("invalid cast kind for integral value");
15664
15665 case CK_BitCast:
15666 case CK_Dependent:
15667 case CK_LValueBitCast:
15668 case CK_ARCProduceObject:
15669 case CK_ARCConsumeObject:
15670 case CK_ARCReclaimReturnedObject:
15671 case CK_ARCExtendBlockObject:
15672 case CK_CopyAndAutoreleaseBlockObject:
15673 return Error(E);
15674
15675 case CK_UserDefinedConversion:
15676 case CK_LValueToRValue:
15677 case CK_AtomicToNonAtomic:
15678 case CK_NoOp:
15679 case CK_LValueToRValueBitCast:
15680 case CK_HLSLArrayRValue:
15681 case CK_HLSLElementwiseCast:
15682 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15683
15684 case CK_MemberPointerToBoolean:
15685 case CK_PointerToBoolean:
15686 case CK_IntegralToBoolean:
15687 case CK_FloatingToBoolean:
15688 case CK_BooleanToSignedIntegral:
15689 case CK_FloatingComplexToBoolean:
15690 case CK_IntegralComplexToBoolean: {
15691 bool BoolResult;
15692 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15693 return false;
15694 uint64_t IntResult = BoolResult;
15695 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15696 IntResult = (uint64_t)-1;
15697 return Success(IntResult, E);
15698 }
15699
15700 case CK_FixedPointToIntegral: {
15701 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15702 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15703 return false;
15704 bool Overflowed;
15705 llvm::APSInt Result = Src.convertToInt(
15706 Info.Ctx.getIntWidth(DestType),
15707 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15708 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15709 return false;
15710 return Success(Result, E);
15711 }
15712
15713 case CK_FixedPointToBoolean: {
15714 // Unsigned padding does not affect this.
15715 APValue Val;
15716 if (!Evaluate(Val, Info, SubExpr))
15717 return false;
15718 return Success(Val.getFixedPoint().getBoolValue(), E);
15719 }
15720
15721 case CK_IntegralCast: {
15722 if (!Visit(SubExpr))
15723 return false;
15724
15725 if (!Result.isInt()) {
15726 // Allow casts of address-of-label differences if they are no-ops
15727 // or narrowing. (The narrowing case isn't actually guaranteed to
15728 // be constant-evaluatable except in some narrow cases which are hard
15729 // to detect here. We let it through on the assumption the user knows
15730 // what they are doing.)
15731 if (Result.isAddrLabelDiff())
15732 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15733 // Only allow casts of lvalues if they are lossless.
15734 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15735 }
15736
15737 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
15738 const auto *ED = DestType->getAsEnumDecl();
15739 // Check that the value is within the range of the enumeration values.
15740 //
15741 // This corressponds to [expr.static.cast]p10 which says:
15742 // A value of integral or enumeration type can be explicitly converted
15743 // to a complete enumeration type ... If the enumeration type does not
15744 // have a fixed underlying type, the value is unchanged if the original
15745 // value is within the range of the enumeration values ([dcl.enum]), and
15746 // otherwise, the behavior is undefined.
15747 //
15748 // This was resolved as part of DR2338 which has CD5 status.
15749 if (!ED->isFixed()) {
15750 llvm::APInt Min;
15751 llvm::APInt Max;
15752
15753 ED->getValueRange(Max, Min);
15754 --Max;
15755
15756 if (ED->getNumNegativeBits() &&
15757 (Max.slt(Result.getInt().getSExtValue()) ||
15758 Min.sgt(Result.getInt().getSExtValue())))
15759 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15760 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15761 << Max.getSExtValue() << ED;
15762 else if (!ED->getNumNegativeBits() &&
15763 Max.ult(Result.getInt().getZExtValue()))
15764 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15765 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15766 << Max.getZExtValue() << ED;
15767 }
15768 }
15769
15770 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15771 Result.getInt()), E);
15772 }
15773
15774 case CK_PointerToIntegral: {
15775 CCEDiag(E, diag::note_constexpr_invalid_cast)
15776 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
15777 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15778
15779 LValue LV;
15780 if (!EvaluatePointer(SubExpr, LV, Info))
15781 return false;
15782
15783 if (LV.getLValueBase()) {
15784 // Only allow based lvalue casts if they are lossless.
15785 // FIXME: Allow a larger integer size than the pointer size, and allow
15786 // narrowing back down to pointer width in subsequent integral casts.
15787 // FIXME: Check integer type's active bits, not its type size.
15788 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15789 return Error(E);
15790
15791 LV.Designator.setInvalid();
15792 LV.moveInto(Result);
15793 return true;
15794 }
15795
15796 APSInt AsInt;
15797 APValue V;
15798 LV.moveInto(V);
15799 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15800 llvm_unreachable("Can't cast this!");
15801
15802 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15803 }
15804
15805 case CK_IntegralComplexToReal: {
15806 ComplexValue C;
15807 if (!EvaluateComplex(SubExpr, C, Info))
15808 return false;
15809 return Success(C.getComplexIntReal(), E);
15810 }
15811
15812 case CK_FloatingToIntegral: {
15813 APFloat F(0.0);
15814 if (!EvaluateFloat(SubExpr, F, Info))
15815 return false;
15816
15817 APSInt Value;
15818 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15819 return false;
15820 return Success(Value, E);
15821 }
15822 case CK_HLSLVectorTruncation: {
15823 APValue Val;
15824 if (!EvaluateVector(SubExpr, Val, Info))
15825 return Error(E);
15826 return Success(Val.getVectorElt(0), E);
15827 }
15828 }
15829
15830 llvm_unreachable("unknown cast resulting in integral value");
15831}
15832
15833bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15834 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15835 ComplexValue LV;
15836 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15837 return false;
15838 if (!LV.isComplexInt())
15839 return Error(E);
15840 return Success(LV.getComplexIntReal(), E);
15841 }
15842
15843 return Visit(E->getSubExpr());
15844}
15845
15846bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15847 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15848 ComplexValue LV;
15849 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15850 return false;
15851 if (!LV.isComplexInt())
15852 return Error(E);
15853 return Success(LV.getComplexIntImag(), E);
15854 }
15855
15856 VisitIgnoredValue(E->getSubExpr());
15857 return Success(0, E);
15858}
15859
15860bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15861 return Success(E->getPackLength(), E);
15862}
15863
15864bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15865 return Success(E->getValue(), E);
15866}
15867
15868bool IntExprEvaluator::VisitConceptSpecializationExpr(
15870 return Success(E->isSatisfied(), E);
15871}
15872
15873bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15874 return Success(E->isSatisfied(), E);
15875}
15876
15877bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15878 switch (E->getOpcode()) {
15879 default:
15880 // Invalid unary operators
15881 return Error(E);
15882 case UO_Plus:
15883 // The result is just the value.
15884 return Visit(E->getSubExpr());
15885 case UO_Minus: {
15886 if (!Visit(E->getSubExpr())) return false;
15887 if (!Result.isFixedPoint())
15888 return Error(E);
15889 bool Overflowed;
15890 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15891 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15892 return false;
15893 return Success(Negated, E);
15894 }
15895 case UO_LNot: {
15896 bool bres;
15897 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15898 return false;
15899 return Success(!bres, E);
15900 }
15901 }
15902}
15903
15904bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15905 const Expr *SubExpr = E->getSubExpr();
15906 QualType DestType = E->getType();
15907 assert(DestType->isFixedPointType() &&
15908 "Expected destination type to be a fixed point type");
15909 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15910
15911 switch (E->getCastKind()) {
15912 case CK_FixedPointCast: {
15913 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15914 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15915 return false;
15916 bool Overflowed;
15917 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15918 if (Overflowed) {
15919 if (Info.checkingForUndefinedBehavior())
15920 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15921 diag::warn_fixedpoint_constant_overflow)
15922 << Result.toString() << E->getType();
15923 if (!HandleOverflow(Info, E, Result, E->getType()))
15924 return false;
15925 }
15926 return Success(Result, E);
15927 }
15928 case CK_IntegralToFixedPoint: {
15929 APSInt Src;
15930 if (!EvaluateInteger(SubExpr, Src, Info))
15931 return false;
15932
15933 bool Overflowed;
15934 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15935 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15936
15937 if (Overflowed) {
15938 if (Info.checkingForUndefinedBehavior())
15939 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15940 diag::warn_fixedpoint_constant_overflow)
15941 << IntResult.toString() << E->getType();
15942 if (!HandleOverflow(Info, E, IntResult, E->getType()))
15943 return false;
15944 }
15945
15946 return Success(IntResult, E);
15947 }
15948 case CK_FloatingToFixedPoint: {
15949 APFloat Src(0.0);
15950 if (!EvaluateFloat(SubExpr, Src, Info))
15951 return false;
15952
15953 bool Overflowed;
15954 APFixedPoint Result = APFixedPoint::getFromFloatValue(
15955 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15956
15957 if (Overflowed) {
15958 if (Info.checkingForUndefinedBehavior())
15959 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15960 diag::warn_fixedpoint_constant_overflow)
15961 << Result.toString() << E->getType();
15962 if (!HandleOverflow(Info, E, Result, E->getType()))
15963 return false;
15964 }
15965
15966 return Success(Result, E);
15967 }
15968 case CK_NoOp:
15969 case CK_LValueToRValue:
15970 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15971 default:
15972 return Error(E);
15973 }
15974}
15975
15976bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15977 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15978 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15979
15980 const Expr *LHS = E->getLHS();
15981 const Expr *RHS = E->getRHS();
15982 FixedPointSemantics ResultFXSema =
15983 Info.Ctx.getFixedPointSemantics(E->getType());
15984
15985 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15986 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15987 return false;
15988 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15989 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15990 return false;
15991
15992 bool OpOverflow = false, ConversionOverflow = false;
15993 APFixedPoint Result(LHSFX.getSemantics());
15994 switch (E->getOpcode()) {
15995 case BO_Add: {
15996 Result = LHSFX.add(RHSFX, &OpOverflow)
15997 .convert(ResultFXSema, &ConversionOverflow);
15998 break;
15999 }
16000 case BO_Sub: {
16001 Result = LHSFX.sub(RHSFX, &OpOverflow)
16002 .convert(ResultFXSema, &ConversionOverflow);
16003 break;
16004 }
16005 case BO_Mul: {
16006 Result = LHSFX.mul(RHSFX, &OpOverflow)
16007 .convert(ResultFXSema, &ConversionOverflow);
16008 break;
16009 }
16010 case BO_Div: {
16011 if (RHSFX.getValue() == 0) {
16012 Info.FFDiag(E, diag::note_expr_divide_by_zero);
16013 return false;
16014 }
16015 Result = LHSFX.div(RHSFX, &OpOverflow)
16016 .convert(ResultFXSema, &ConversionOverflow);
16017 break;
16018 }
16019 case BO_Shl:
16020 case BO_Shr: {
16021 FixedPointSemantics LHSSema = LHSFX.getSemantics();
16022 llvm::APSInt RHSVal = RHSFX.getValue();
16023
16024 unsigned ShiftBW =
16025 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
16026 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
16027 // Embedded-C 4.1.6.2.2:
16028 // The right operand must be nonnegative and less than the total number
16029 // of (nonpadding) bits of the fixed-point operand ...
16030 if (RHSVal.isNegative())
16031 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
16032 else if (Amt != RHSVal)
16033 Info.CCEDiag(E, diag::note_constexpr_large_shift)
16034 << RHSVal << E->getType() << ShiftBW;
16035
16036 if (E->getOpcode() == BO_Shl)
16037 Result = LHSFX.shl(Amt, &OpOverflow);
16038 else
16039 Result = LHSFX.shr(Amt, &OpOverflow);
16040 break;
16041 }
16042 default:
16043 return false;
16044 }
16045 if (OpOverflow || ConversionOverflow) {
16046 if (Info.checkingForUndefinedBehavior())
16047 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
16048 diag::warn_fixedpoint_constant_overflow)
16049 << Result.toString() << E->getType();
16050 if (!HandleOverflow(Info, E, Result, E->getType()))
16051 return false;
16052 }
16053 return Success(Result, E);
16054}
16055
16056//===----------------------------------------------------------------------===//
16057// Float Evaluation
16058//===----------------------------------------------------------------------===//
16059
16060namespace {
16061class FloatExprEvaluator
16062 : public ExprEvaluatorBase<FloatExprEvaluator> {
16063 APFloat &Result;
16064public:
16065 FloatExprEvaluator(EvalInfo &info, APFloat &result)
16066 : ExprEvaluatorBaseTy(info), Result(result) {}
16067
16068 bool Success(const APValue &V, const Expr *e) {
16069 Result = V.getFloat();
16070 return true;
16071 }
16072
16073 bool ZeroInitialization(const Expr *E) {
16074 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
16075 return true;
16076 }
16077
16078 bool VisitCallExpr(const CallExpr *E);
16079
16080 bool VisitUnaryOperator(const UnaryOperator *E);
16081 bool VisitBinaryOperator(const BinaryOperator *E);
16082 bool VisitFloatingLiteral(const FloatingLiteral *E);
16083 bool VisitCastExpr(const CastExpr *E);
16084
16085 bool VisitUnaryReal(const UnaryOperator *E);
16086 bool VisitUnaryImag(const UnaryOperator *E);
16087
16088 // FIXME: Missing: array subscript of vector, member of vector
16089};
16090} // end anonymous namespace
16091
16092static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
16093 assert(!E->isValueDependent());
16094 assert(E->isPRValue() && E->getType()->isRealFloatingType());
16095 return FloatExprEvaluator(Info, Result).Visit(E);
16096}
16097
16098static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
16099 QualType ResultTy,
16100 const Expr *Arg,
16101 bool SNaN,
16102 llvm::APFloat &Result) {
16103 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
16104 if (!S) return false;
16105
16106 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
16107
16108 llvm::APInt fill;
16109
16110 // Treat empty strings as if they were zero.
16111 if (S->getString().empty())
16112 fill = llvm::APInt(32, 0);
16113 else if (S->getString().getAsInteger(0, fill))
16114 return false;
16115
16116 if (Context.getTargetInfo().isNan2008()) {
16117 if (SNaN)
16118 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16119 else
16120 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16121 } else {
16122 // Prior to IEEE 754-2008, architectures were allowed to choose whether
16123 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
16124 // a different encoding to what became a standard in 2008, and for pre-
16125 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
16126 // sNaN. This is now known as "legacy NaN" encoding.
16127 if (SNaN)
16128 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
16129 else
16130 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
16131 }
16132
16133 return true;
16134}
16135
16136bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
16137 if (!IsConstantEvaluatedBuiltinCall(E))
16138 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16139
16140 switch (E->getBuiltinCallee()) {
16141 default:
16142 return false;
16143
16144 case Builtin::BI__builtin_huge_val:
16145 case Builtin::BI__builtin_huge_valf:
16146 case Builtin::BI__builtin_huge_vall:
16147 case Builtin::BI__builtin_huge_valf16:
16148 case Builtin::BI__builtin_huge_valf128:
16149 case Builtin::BI__builtin_inf:
16150 case Builtin::BI__builtin_inff:
16151 case Builtin::BI__builtin_infl:
16152 case Builtin::BI__builtin_inff16:
16153 case Builtin::BI__builtin_inff128: {
16154 const llvm::fltSemantics &Sem =
16155 Info.Ctx.getFloatTypeSemantics(E->getType());
16156 Result = llvm::APFloat::getInf(Sem);
16157 return true;
16158 }
16159
16160 case Builtin::BI__builtin_nans:
16161 case Builtin::BI__builtin_nansf:
16162 case Builtin::BI__builtin_nansl:
16163 case Builtin::BI__builtin_nansf16:
16164 case Builtin::BI__builtin_nansf128:
16165 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16166 true, Result))
16167 return Error(E);
16168 return true;
16169
16170 case Builtin::BI__builtin_nan:
16171 case Builtin::BI__builtin_nanf:
16172 case Builtin::BI__builtin_nanl:
16173 case Builtin::BI__builtin_nanf16:
16174 case Builtin::BI__builtin_nanf128:
16175 // If this is __builtin_nan() turn this into a nan, otherwise we
16176 // can't constant fold it.
16177 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
16178 false, Result))
16179 return Error(E);
16180 return true;
16181
16182 case Builtin::BI__builtin_elementwise_abs:
16183 case Builtin::BI__builtin_fabs:
16184 case Builtin::BI__builtin_fabsf:
16185 case Builtin::BI__builtin_fabsl:
16186 case Builtin::BI__builtin_fabsf128:
16187 // The C standard says "fabs raises no floating-point exceptions,
16188 // even if x is a signaling NaN. The returned value is independent of
16189 // the current rounding direction mode." Therefore constant folding can
16190 // proceed without regard to the floating point settings.
16191 // Reference, WG14 N2478 F.10.4.3
16192 if (!EvaluateFloat(E->getArg(0), Result, Info))
16193 return false;
16194
16195 if (Result.isNegative())
16196 Result.changeSign();
16197 return true;
16198
16199 case Builtin::BI__arithmetic_fence:
16200 return EvaluateFloat(E->getArg(0), Result, Info);
16201
16202 // FIXME: Builtin::BI__builtin_powi
16203 // FIXME: Builtin::BI__builtin_powif
16204 // FIXME: Builtin::BI__builtin_powil
16205
16206 case Builtin::BI__builtin_copysign:
16207 case Builtin::BI__builtin_copysignf:
16208 case Builtin::BI__builtin_copysignl:
16209 case Builtin::BI__builtin_copysignf128: {
16210 APFloat RHS(0.);
16211 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16212 !EvaluateFloat(E->getArg(1), RHS, Info))
16213 return false;
16214 Result.copySign(RHS);
16215 return true;
16216 }
16217
16218 case Builtin::BI__builtin_fmax:
16219 case Builtin::BI__builtin_fmaxf:
16220 case Builtin::BI__builtin_fmaxl:
16221 case Builtin::BI__builtin_fmaxf16:
16222 case Builtin::BI__builtin_fmaxf128: {
16223 APFloat RHS(0.);
16224 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16225 !EvaluateFloat(E->getArg(1), RHS, Info))
16226 return false;
16227 Result = maxnum(Result, RHS);
16228 return true;
16229 }
16230
16231 case Builtin::BI__builtin_fmin:
16232 case Builtin::BI__builtin_fminf:
16233 case Builtin::BI__builtin_fminl:
16234 case Builtin::BI__builtin_fminf16:
16235 case Builtin::BI__builtin_fminf128: {
16236 APFloat RHS(0.);
16237 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16238 !EvaluateFloat(E->getArg(1), RHS, Info))
16239 return false;
16240 Result = minnum(Result, RHS);
16241 return true;
16242 }
16243
16244 case Builtin::BI__builtin_fmaximum_num:
16245 case Builtin::BI__builtin_fmaximum_numf:
16246 case Builtin::BI__builtin_fmaximum_numl:
16247 case Builtin::BI__builtin_fmaximum_numf16:
16248 case Builtin::BI__builtin_fmaximum_numf128: {
16249 APFloat RHS(0.);
16250 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16251 !EvaluateFloat(E->getArg(1), RHS, Info))
16252 return false;
16253 Result = maximumnum(Result, RHS);
16254 return true;
16255 }
16256
16257 case Builtin::BI__builtin_fminimum_num:
16258 case Builtin::BI__builtin_fminimum_numf:
16259 case Builtin::BI__builtin_fminimum_numl:
16260 case Builtin::BI__builtin_fminimum_numf16:
16261 case Builtin::BI__builtin_fminimum_numf128: {
16262 APFloat RHS(0.);
16263 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16264 !EvaluateFloat(E->getArg(1), RHS, Info))
16265 return false;
16266 Result = minimumnum(Result, RHS);
16267 return true;
16268 }
16269
16270 case Builtin::BI__builtin_elementwise_fma: {
16271 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
16272 !E->getArg(2)->isPRValue()) {
16273 return false;
16274 }
16275 APFloat SourceY(0.), SourceZ(0.);
16276 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
16277 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
16278 !EvaluateFloat(E->getArg(2), SourceZ, Info))
16279 return false;
16280 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
16281 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
16282 return true;
16283 }
16284 }
16285}
16286
16287bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
16288 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16289 ComplexValue CV;
16290 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16291 return false;
16292 Result = CV.FloatReal;
16293 return true;
16294 }
16295
16296 return Visit(E->getSubExpr());
16297}
16298
16299bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
16300 if (E->getSubExpr()->getType()->isAnyComplexType()) {
16301 ComplexValue CV;
16302 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
16303 return false;
16304 Result = CV.FloatImag;
16305 return true;
16306 }
16307
16308 VisitIgnoredValue(E->getSubExpr());
16309 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
16310 Result = llvm::APFloat::getZero(Sem);
16311 return true;
16312}
16313
16314bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16315 switch (E->getOpcode()) {
16316 default: return Error(E);
16317 case UO_Plus:
16318 return EvaluateFloat(E->getSubExpr(), Result, Info);
16319 case UO_Minus:
16320 // In C standard, WG14 N2478 F.3 p4
16321 // "the unary - raises no floating point exceptions,
16322 // even if the operand is signalling."
16323 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
16324 return false;
16325 Result.changeSign();
16326 return true;
16327 }
16328}
16329
16330bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16331 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16332 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16333
16334 APFloat RHS(0.0);
16335 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
16336 if (!LHSOK && !Info.noteFailure())
16337 return false;
16338 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
16339 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
16340}
16341
16342bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
16343 Result = E->getValue();
16344 return true;
16345}
16346
16347bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
16348 const Expr* SubExpr = E->getSubExpr();
16349
16350 switch (E->getCastKind()) {
16351 default:
16352 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16353
16354 case CK_IntegralToFloating: {
16355 APSInt IntResult;
16356 const FPOptions FPO = E->getFPFeaturesInEffect(
16357 Info.Ctx.getLangOpts());
16358 return EvaluateInteger(SubExpr, IntResult, Info) &&
16359 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
16360 IntResult, E->getType(), Result);
16361 }
16362
16363 case CK_FixedPointToFloating: {
16364 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
16365 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
16366 return false;
16367 Result =
16368 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
16369 return true;
16370 }
16371
16372 case CK_FloatingCast: {
16373 if (!Visit(SubExpr))
16374 return false;
16375 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
16376 Result);
16377 }
16378
16379 case CK_FloatingComplexToReal: {
16380 ComplexValue V;
16381 if (!EvaluateComplex(SubExpr, V, Info))
16382 return false;
16383 Result = V.getComplexFloatReal();
16384 return true;
16385 }
16386 case CK_HLSLVectorTruncation: {
16387 APValue Val;
16388 if (!EvaluateVector(SubExpr, Val, Info))
16389 return Error(E);
16390 return Success(Val.getVectorElt(0), E);
16391 }
16392 }
16393}
16394
16395//===----------------------------------------------------------------------===//
16396// Complex Evaluation (for float and integer)
16397//===----------------------------------------------------------------------===//
16398
16399namespace {
16400class ComplexExprEvaluator
16401 : public ExprEvaluatorBase<ComplexExprEvaluator> {
16402 ComplexValue &Result;
16403
16404public:
16405 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
16406 : ExprEvaluatorBaseTy(info), Result(Result) {}
16407
16408 bool Success(const APValue &V, const Expr *e) {
16409 Result.setFrom(V);
16410 return true;
16411 }
16412
16413 bool ZeroInitialization(const Expr *E);
16414
16415 //===--------------------------------------------------------------------===//
16416 // Visitor Methods
16417 //===--------------------------------------------------------------------===//
16418
16419 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
16420 bool VisitCastExpr(const CastExpr *E);
16421 bool VisitBinaryOperator(const BinaryOperator *E);
16422 bool VisitUnaryOperator(const UnaryOperator *E);
16423 bool VisitInitListExpr(const InitListExpr *E);
16424 bool VisitCallExpr(const CallExpr *E);
16425};
16426} // end anonymous namespace
16427
16428static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
16429 EvalInfo &Info) {
16430 assert(!E->isValueDependent());
16431 assert(E->isPRValue() && E->getType()->isAnyComplexType());
16432 return ComplexExprEvaluator(Info, Result).Visit(E);
16433}
16434
16435bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
16436 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
16437 if (ElemTy->isRealFloatingType()) {
16438 Result.makeComplexFloat();
16439 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
16440 Result.FloatReal = Zero;
16441 Result.FloatImag = Zero;
16442 } else {
16443 Result.makeComplexInt();
16444 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
16445 Result.IntReal = Zero;
16446 Result.IntImag = Zero;
16447 }
16448 return true;
16449}
16450
16451bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
16452 const Expr* SubExpr = E->getSubExpr();
16453
16454 if (SubExpr->getType()->isRealFloatingType()) {
16455 Result.makeComplexFloat();
16456 APFloat &Imag = Result.FloatImag;
16457 if (!EvaluateFloat(SubExpr, Imag, Info))
16458 return false;
16459
16460 Result.FloatReal = APFloat(Imag.getSemantics());
16461 return true;
16462 } else {
16463 assert(SubExpr->getType()->isIntegerType() &&
16464 "Unexpected imaginary literal.");
16465
16466 Result.makeComplexInt();
16467 APSInt &Imag = Result.IntImag;
16468 if (!EvaluateInteger(SubExpr, Imag, Info))
16469 return false;
16470
16471 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
16472 return true;
16473 }
16474}
16475
16476bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
16477
16478 switch (E->getCastKind()) {
16479 case CK_BitCast:
16480 case CK_BaseToDerived:
16481 case CK_DerivedToBase:
16482 case CK_UncheckedDerivedToBase:
16483 case CK_Dynamic:
16484 case CK_ToUnion:
16485 case CK_ArrayToPointerDecay:
16486 case CK_FunctionToPointerDecay:
16487 case CK_NullToPointer:
16488 case CK_NullToMemberPointer:
16489 case CK_BaseToDerivedMemberPointer:
16490 case CK_DerivedToBaseMemberPointer:
16491 case CK_MemberPointerToBoolean:
16492 case CK_ReinterpretMemberPointer:
16493 case CK_ConstructorConversion:
16494 case CK_IntegralToPointer:
16495 case CK_PointerToIntegral:
16496 case CK_PointerToBoolean:
16497 case CK_ToVoid:
16498 case CK_VectorSplat:
16499 case CK_IntegralCast:
16500 case CK_BooleanToSignedIntegral:
16501 case CK_IntegralToBoolean:
16502 case CK_IntegralToFloating:
16503 case CK_FloatingToIntegral:
16504 case CK_FloatingToBoolean:
16505 case CK_FloatingCast:
16506 case CK_CPointerToObjCPointerCast:
16507 case CK_BlockPointerToObjCPointerCast:
16508 case CK_AnyPointerToBlockPointerCast:
16509 case CK_ObjCObjectLValueCast:
16510 case CK_FloatingComplexToReal:
16511 case CK_FloatingComplexToBoolean:
16512 case CK_IntegralComplexToReal:
16513 case CK_IntegralComplexToBoolean:
16514 case CK_ARCProduceObject:
16515 case CK_ARCConsumeObject:
16516 case CK_ARCReclaimReturnedObject:
16517 case CK_ARCExtendBlockObject:
16518 case CK_CopyAndAutoreleaseBlockObject:
16519 case CK_BuiltinFnToFnPtr:
16520 case CK_ZeroToOCLOpaqueType:
16521 case CK_NonAtomicToAtomic:
16522 case CK_AddressSpaceConversion:
16523 case CK_IntToOCLSampler:
16524 case CK_FloatingToFixedPoint:
16525 case CK_FixedPointToFloating:
16526 case CK_FixedPointCast:
16527 case CK_FixedPointToBoolean:
16528 case CK_FixedPointToIntegral:
16529 case CK_IntegralToFixedPoint:
16530 case CK_MatrixCast:
16531 case CK_HLSLVectorTruncation:
16532 case CK_HLSLElementwiseCast:
16533 case CK_HLSLAggregateSplatCast:
16534 llvm_unreachable("invalid cast kind for complex value");
16535
16536 case CK_LValueToRValue:
16537 case CK_AtomicToNonAtomic:
16538 case CK_NoOp:
16539 case CK_LValueToRValueBitCast:
16540 case CK_HLSLArrayRValue:
16541 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16542
16543 case CK_Dependent:
16544 case CK_LValueBitCast:
16545 case CK_UserDefinedConversion:
16546 return Error(E);
16547
16548 case CK_FloatingRealToComplex: {
16549 APFloat &Real = Result.FloatReal;
16550 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
16551 return false;
16552
16553 Result.makeComplexFloat();
16554 Result.FloatImag = APFloat(Real.getSemantics());
16555 return true;
16556 }
16557
16558 case CK_FloatingComplexCast: {
16559 if (!Visit(E->getSubExpr()))
16560 return false;
16561
16562 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16563 QualType From
16564 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16565
16566 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
16567 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
16568 }
16569
16570 case CK_FloatingComplexToIntegralComplex: {
16571 if (!Visit(E->getSubExpr()))
16572 return false;
16573
16574 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16575 QualType From
16576 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16577 Result.makeComplexInt();
16578 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
16579 To, Result.IntReal) &&
16580 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
16581 To, Result.IntImag);
16582 }
16583
16584 case CK_IntegralRealToComplex: {
16585 APSInt &Real = Result.IntReal;
16586 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
16587 return false;
16588
16589 Result.makeComplexInt();
16590 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
16591 return true;
16592 }
16593
16594 case CK_IntegralComplexCast: {
16595 if (!Visit(E->getSubExpr()))
16596 return false;
16597
16598 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16599 QualType From
16600 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16601
16602 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
16603 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
16604 return true;
16605 }
16606
16607 case CK_IntegralComplexToFloatingComplex: {
16608 if (!Visit(E->getSubExpr()))
16609 return false;
16610
16611 const FPOptions FPO = E->getFPFeaturesInEffect(
16612 Info.Ctx.getLangOpts());
16613 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
16614 QualType From
16615 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
16616 Result.makeComplexFloat();
16617 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
16618 To, Result.FloatReal) &&
16619 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
16620 To, Result.FloatImag);
16621 }
16622 }
16623
16624 llvm_unreachable("unknown cast resulting in complex value");
16625}
16626
16627void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16628 APFloat &ResR, APFloat &ResI) {
16629 // This is an implementation of complex multiplication according to the
16630 // constraints laid out in C11 Annex G. The implementation uses the
16631 // following naming scheme:
16632 // (a + ib) * (c + id)
16633
16634 APFloat AC = A * C;
16635 APFloat BD = B * D;
16636 APFloat AD = A * D;
16637 APFloat BC = B * C;
16638 ResR = AC - BD;
16639 ResI = AD + BC;
16640 if (ResR.isNaN() && ResI.isNaN()) {
16641 bool Recalc = false;
16642 if (A.isInfinity() || B.isInfinity()) {
16643 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16644 A);
16645 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16646 B);
16647 if (C.isNaN())
16648 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16649 if (D.isNaN())
16650 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16651 Recalc = true;
16652 }
16653 if (C.isInfinity() || D.isInfinity()) {
16654 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16655 C);
16656 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16657 D);
16658 if (A.isNaN())
16659 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16660 if (B.isNaN())
16661 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16662 Recalc = true;
16663 }
16664 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16665 BC.isInfinity())) {
16666 if (A.isNaN())
16667 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16668 if (B.isNaN())
16669 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16670 if (C.isNaN())
16671 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16672 if (D.isNaN())
16673 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16674 Recalc = true;
16675 }
16676 if (Recalc) {
16677 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16678 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16679 }
16680 }
16681}
16682
16683void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16684 APFloat &ResR, APFloat &ResI) {
16685 // This is an implementation of complex division according to the
16686 // constraints laid out in C11 Annex G. The implementation uses the
16687 // following naming scheme:
16688 // (a + ib) / (c + id)
16689
16690 int DenomLogB = 0;
16691 APFloat MaxCD = maxnum(abs(C), abs(D));
16692 if (MaxCD.isFinite()) {
16693 DenomLogB = ilogb(MaxCD);
16694 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16695 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16696 }
16697 APFloat Denom = C * C + D * D;
16698 ResR =
16699 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16700 ResI =
16701 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16702 if (ResR.isNaN() && ResI.isNaN()) {
16703 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16704 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16705 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16706 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16707 D.isFinite()) {
16708 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16709 A);
16710 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16711 B);
16712 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16713 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16714 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16715 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16716 C);
16717 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16718 D);
16719 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16720 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16721 }
16722 }
16723}
16724
16725bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16726 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16727 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16728
16729 // Track whether the LHS or RHS is real at the type system level. When this is
16730 // the case we can simplify our evaluation strategy.
16731 bool LHSReal = false, RHSReal = false;
16732
16733 bool LHSOK;
16734 if (E->getLHS()->getType()->isRealFloatingType()) {
16735 LHSReal = true;
16736 APFloat &Real = Result.FloatReal;
16737 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16738 if (LHSOK) {
16739 Result.makeComplexFloat();
16740 Result.FloatImag = APFloat(Real.getSemantics());
16741 }
16742 } else {
16743 LHSOK = Visit(E->getLHS());
16744 }
16745 if (!LHSOK && !Info.noteFailure())
16746 return false;
16747
16748 ComplexValue RHS;
16749 if (E->getRHS()->getType()->isRealFloatingType()) {
16750 RHSReal = true;
16751 APFloat &Real = RHS.FloatReal;
16752 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16753 return false;
16754 RHS.makeComplexFloat();
16755 RHS.FloatImag = APFloat(Real.getSemantics());
16756 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16757 return false;
16758
16759 assert(!(LHSReal && RHSReal) &&
16760 "Cannot have both operands of a complex operation be real.");
16761 switch (E->getOpcode()) {
16762 default: return Error(E);
16763 case BO_Add:
16764 if (Result.isComplexFloat()) {
16765 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16766 APFloat::rmNearestTiesToEven);
16767 if (LHSReal)
16768 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16769 else if (!RHSReal)
16770 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16771 APFloat::rmNearestTiesToEven);
16772 } else {
16773 Result.getComplexIntReal() += RHS.getComplexIntReal();
16774 Result.getComplexIntImag() += RHS.getComplexIntImag();
16775 }
16776 break;
16777 case BO_Sub:
16778 if (Result.isComplexFloat()) {
16779 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16780 APFloat::rmNearestTiesToEven);
16781 if (LHSReal) {
16782 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16783 Result.getComplexFloatImag().changeSign();
16784 } else if (!RHSReal) {
16785 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16786 APFloat::rmNearestTiesToEven);
16787 }
16788 } else {
16789 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16790 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16791 }
16792 break;
16793 case BO_Mul:
16794 if (Result.isComplexFloat()) {
16795 // This is an implementation of complex multiplication according to the
16796 // constraints laid out in C11 Annex G. The implementation uses the
16797 // following naming scheme:
16798 // (a + ib) * (c + id)
16799 ComplexValue LHS = Result;
16800 APFloat &A = LHS.getComplexFloatReal();
16801 APFloat &B = LHS.getComplexFloatImag();
16802 APFloat &C = RHS.getComplexFloatReal();
16803 APFloat &D = RHS.getComplexFloatImag();
16804 APFloat &ResR = Result.getComplexFloatReal();
16805 APFloat &ResI = Result.getComplexFloatImag();
16806 if (LHSReal) {
16807 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16808 ResR = A;
16809 ResI = A;
16810 // ResR = A * C;
16811 // ResI = A * D;
16812 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16813 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16814 return false;
16815 } else if (RHSReal) {
16816 // ResR = C * A;
16817 // ResI = C * B;
16818 ResR = C;
16819 ResI = C;
16820 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16821 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16822 return false;
16823 } else {
16824 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16825 }
16826 } else {
16827 ComplexValue LHS = Result;
16828 Result.getComplexIntReal() =
16829 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16830 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16831 Result.getComplexIntImag() =
16832 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16833 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16834 }
16835 break;
16836 case BO_Div:
16837 if (Result.isComplexFloat()) {
16838 // This is an implementation of complex division according to the
16839 // constraints laid out in C11 Annex G. The implementation uses the
16840 // following naming scheme:
16841 // (a + ib) / (c + id)
16842 ComplexValue LHS = Result;
16843 APFloat &A = LHS.getComplexFloatReal();
16844 APFloat &B = LHS.getComplexFloatImag();
16845 APFloat &C = RHS.getComplexFloatReal();
16846 APFloat &D = RHS.getComplexFloatImag();
16847 APFloat &ResR = Result.getComplexFloatReal();
16848 APFloat &ResI = Result.getComplexFloatImag();
16849 if (RHSReal) {
16850 ResR = A;
16851 ResI = B;
16852 // ResR = A / C;
16853 // ResI = B / C;
16854 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16855 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16856 return false;
16857 } else {
16858 if (LHSReal) {
16859 // No real optimizations we can do here, stub out with zero.
16860 B = APFloat::getZero(A.getSemantics());
16861 }
16862 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16863 }
16864 } else {
16865 ComplexValue LHS = Result;
16866 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16867 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16868 if (Den.isZero())
16869 return Error(E, diag::note_expr_divide_by_zero);
16870
16871 Result.getComplexIntReal() =
16872 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16873 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16874 Result.getComplexIntImag() =
16875 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16876 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16877 }
16878 break;
16879 }
16880
16881 return true;
16882}
16883
16884bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16885 // Get the operand value into 'Result'.
16886 if (!Visit(E->getSubExpr()))
16887 return false;
16888
16889 switch (E->getOpcode()) {
16890 default:
16891 return Error(E);
16892 case UO_Extension:
16893 return true;
16894 case UO_Plus:
16895 // The result is always just the subexpr.
16896 return true;
16897 case UO_Minus:
16898 if (Result.isComplexFloat()) {
16899 Result.getComplexFloatReal().changeSign();
16900 Result.getComplexFloatImag().changeSign();
16901 }
16902 else {
16903 Result.getComplexIntReal() = -Result.getComplexIntReal();
16904 Result.getComplexIntImag() = -Result.getComplexIntImag();
16905 }
16906 return true;
16907 case UO_Not:
16908 if (Result.isComplexFloat())
16909 Result.getComplexFloatImag().changeSign();
16910 else
16911 Result.getComplexIntImag() = -Result.getComplexIntImag();
16912 return true;
16913 }
16914}
16915
16916bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16917 if (E->getNumInits() == 2) {
16918 if (E->getType()->isComplexType()) {
16919 Result.makeComplexFloat();
16920 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16921 return false;
16922 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16923 return false;
16924 } else {
16925 Result.makeComplexInt();
16926 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16927 return false;
16928 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16929 return false;
16930 }
16931 return true;
16932 }
16933 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16934}
16935
16936bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16937 if (!IsConstantEvaluatedBuiltinCall(E))
16938 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16939
16940 switch (E->getBuiltinCallee()) {
16941 case Builtin::BI__builtin_complex:
16942 Result.makeComplexFloat();
16943 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16944 return false;
16945 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16946 return false;
16947 return true;
16948
16949 default:
16950 return false;
16951 }
16952}
16953
16954//===----------------------------------------------------------------------===//
16955// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16956// implicit conversion.
16957//===----------------------------------------------------------------------===//
16958
16959namespace {
16960class AtomicExprEvaluator :
16961 public ExprEvaluatorBase<AtomicExprEvaluator> {
16962 const LValue *This;
16963 APValue &Result;
16964public:
16965 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16966 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16967
16968 bool Success(const APValue &V, const Expr *E) {
16969 Result = V;
16970 return true;
16971 }
16972
16973 bool ZeroInitialization(const Expr *E) {
16976 // For atomic-qualified class (and array) types in C++, initialize the
16977 // _Atomic-wrapped subobject directly, in-place.
16978 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16979 : Evaluate(Result, Info, &VIE);
16980 }
16981
16982 bool VisitCastExpr(const CastExpr *E) {
16983 switch (E->getCastKind()) {
16984 default:
16985 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16986 case CK_NullToPointer:
16987 VisitIgnoredValue(E->getSubExpr());
16988 return ZeroInitialization(E);
16989 case CK_NonAtomicToAtomic:
16990 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16991 : Evaluate(Result, Info, E->getSubExpr());
16992 }
16993 }
16994};
16995} // end anonymous namespace
16996
16997static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16998 EvalInfo &Info) {
16999 assert(!E->isValueDependent());
17000 assert(E->isPRValue() && E->getType()->isAtomicType());
17001 return AtomicExprEvaluator(Info, This, Result).Visit(E);
17002}
17003
17004//===----------------------------------------------------------------------===//
17005// Void expression evaluation, primarily for a cast to void on the LHS of a
17006// comma operator
17007//===----------------------------------------------------------------------===//
17008
17009namespace {
17010class VoidExprEvaluator
17011 : public ExprEvaluatorBase<VoidExprEvaluator> {
17012public:
17013 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
17014
17015 bool Success(const APValue &V, const Expr *e) { return true; }
17016
17017 bool ZeroInitialization(const Expr *E) { return true; }
17018
17019 bool VisitCastExpr(const CastExpr *E) {
17020 switch (E->getCastKind()) {
17021 default:
17022 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17023 case CK_ToVoid:
17024 VisitIgnoredValue(E->getSubExpr());
17025 return true;
17026 }
17027 }
17028
17029 bool VisitCallExpr(const CallExpr *E) {
17030 if (!IsConstantEvaluatedBuiltinCall(E))
17031 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17032
17033 switch (E->getBuiltinCallee()) {
17034 case Builtin::BI__assume:
17035 case Builtin::BI__builtin_assume:
17036 // The argument is not evaluated!
17037 return true;
17038
17039 case Builtin::BI__builtin_operator_delete:
17040 return HandleOperatorDeleteCall(Info, E);
17041
17042 default:
17043 return false;
17044 }
17045 }
17046
17047 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
17048};
17049} // end anonymous namespace
17050
17051bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
17052 // We cannot speculatively evaluate a delete expression.
17053 if (Info.SpeculativeEvaluationDepth)
17054 return false;
17055
17056 FunctionDecl *OperatorDelete = E->getOperatorDelete();
17057 if (!OperatorDelete
17058 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17059 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17060 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
17061 return false;
17062 }
17063
17064 const Expr *Arg = E->getArgument();
17065
17066 LValue Pointer;
17067 if (!EvaluatePointer(Arg, Pointer, Info))
17068 return false;
17069 if (Pointer.Designator.Invalid)
17070 return false;
17071
17072 // Deleting a null pointer has no effect.
17073 if (Pointer.isNullPointer()) {
17074 // This is the only case where we need to produce an extension warning:
17075 // the only other way we can succeed is if we find a dynamic allocation,
17076 // and we will have warned when we allocated it in that case.
17077 if (!Info.getLangOpts().CPlusPlus20)
17078 Info.CCEDiag(E, diag::note_constexpr_new);
17079 return true;
17080 }
17081
17082 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
17083 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
17084 if (!Alloc)
17085 return false;
17086 QualType AllocType = Pointer.Base.getDynamicAllocType();
17087
17088 // For the non-array case, the designator must be empty if the static type
17089 // does not have a virtual destructor.
17090 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
17092 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
17093 << Arg->getType()->getPointeeType() << AllocType;
17094 return false;
17095 }
17096
17097 // For a class type with a virtual destructor, the selected operator delete
17098 // is the one looked up when building the destructor.
17099 if (!E->isArrayForm() && !E->isGlobalDelete()) {
17100 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
17101 if (VirtualDelete &&
17102 !VirtualDelete
17103 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
17104 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
17105 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
17106 return false;
17107 }
17108 }
17109
17110 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
17111 (*Alloc)->Value, AllocType))
17112 return false;
17113
17114 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
17115 // The element was already erased. This means the destructor call also
17116 // deleted the object.
17117 // FIXME: This probably results in undefined behavior before we get this
17118 // far, and should be diagnosed elsewhere first.
17119 Info.FFDiag(E, diag::note_constexpr_double_delete);
17120 return false;
17121 }
17122
17123 return true;
17124}
17125
17126static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
17127 assert(!E->isValueDependent());
17128 assert(E->isPRValue() && E->getType()->isVoidType());
17129 return VoidExprEvaluator(Info).Visit(E);
17130}
17131
17132//===----------------------------------------------------------------------===//
17133// Top level Expr::EvaluateAsRValue method.
17134//===----------------------------------------------------------------------===//
17135
17136static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
17137 assert(!E->isValueDependent());
17138 // In C, function designators are not lvalues, but we evaluate them as if they
17139 // are.
17140 QualType T = E->getType();
17141 if (E->isGLValue() || T->isFunctionType()) {
17142 LValue LV;
17143 if (!EvaluateLValue(E, LV, Info))
17144 return false;
17145 LV.moveInto(Result);
17146 } else if (T->isVectorType()) {
17147 if (!EvaluateVector(E, Result, Info))
17148 return false;
17149 } else if (T->isIntegralOrEnumerationType()) {
17150 if (!IntExprEvaluator(Info, Result).Visit(E))
17151 return false;
17152 } else if (T->hasPointerRepresentation()) {
17153 LValue LV;
17154 if (!EvaluatePointer(E, LV, Info))
17155 return false;
17156 LV.moveInto(Result);
17157 } else if (T->isRealFloatingType()) {
17158 llvm::APFloat F(0.0);
17159 if (!EvaluateFloat(E, F, Info))
17160 return false;
17161 Result = APValue(F);
17162 } else if (T->isAnyComplexType()) {
17163 ComplexValue C;
17164 if (!EvaluateComplex(E, C, Info))
17165 return false;
17166 C.moveInto(Result);
17167 } else if (T->isFixedPointType()) {
17168 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
17169 } else if (T->isMemberPointerType()) {
17170 MemberPtr P;
17171 if (!EvaluateMemberPointer(E, P, Info))
17172 return false;
17173 P.moveInto(Result);
17174 return true;
17175 } else if (T->isArrayType()) {
17176 LValue LV;
17177 APValue &Value =
17178 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17179 if (!EvaluateArray(E, LV, Value, Info))
17180 return false;
17181 Result = Value;
17182 } else if (T->isRecordType()) {
17183 LValue LV;
17184 APValue &Value =
17185 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
17186 if (!EvaluateRecord(E, LV, Value, Info))
17187 return false;
17188 Result = Value;
17189 } else if (T->isVoidType()) {
17190 if (!Info.getLangOpts().CPlusPlus11)
17191 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
17192 << E->getType();
17193 if (!EvaluateVoid(E, Info))
17194 return false;
17195 } else if (T->isAtomicType()) {
17196 QualType Unqual = T.getAtomicUnqualifiedType();
17197 if (Unqual->isArrayType() || Unqual->isRecordType()) {
17198 LValue LV;
17199 APValue &Value = Info.CurrentCall->createTemporary(
17200 E, Unqual, ScopeKind::FullExpression, LV);
17201 if (!EvaluateAtomic(E, &LV, Value, Info))
17202 return false;
17203 Result = Value;
17204 } else {
17205 if (!EvaluateAtomic(E, nullptr, Result, Info))
17206 return false;
17207 }
17208 } else if (Info.getLangOpts().CPlusPlus11) {
17209 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
17210 return false;
17211 } else {
17212 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17213 return false;
17214 }
17215
17216 return true;
17217}
17218
17219/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
17220/// cases, the in-place evaluation is essential, since later initializers for
17221/// an object can indirectly refer to subobjects which were initialized earlier.
17222static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
17223 const Expr *E, bool AllowNonLiteralTypes) {
17224 assert(!E->isValueDependent());
17225
17226 // Normally expressions passed to EvaluateInPlace have a type, but not when
17227 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
17228 // replaced with a CXXConstructExpr. This can happen in LLDB.
17229 if (E->getType().isNull())
17230 return false;
17231
17232 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
17233 return false;
17234
17235 if (E->isPRValue()) {
17236 // Evaluate arrays and record types in-place, so that later initializers can
17237 // refer to earlier-initialized members of the object.
17238 QualType T = E->getType();
17239 if (T->isArrayType())
17240 return EvaluateArray(E, This, Result, Info);
17241 else if (T->isRecordType())
17242 return EvaluateRecord(E, This, Result, Info);
17243 else if (T->isAtomicType()) {
17244 QualType Unqual = T.getAtomicUnqualifiedType();
17245 if (Unqual->isArrayType() || Unqual->isRecordType())
17246 return EvaluateAtomic(E, &This, Result, Info);
17247 }
17248 }
17249
17250 // For any other type, in-place evaluation is unimportant.
17251 return Evaluate(Result, Info, E);
17252}
17253
17254/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
17255/// lvalue-to-rvalue cast if it is an lvalue.
17256static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
17257 assert(!E->isValueDependent());
17258
17259 if (E->getType().isNull())
17260 return false;
17261
17262 if (!CheckLiteralType(Info, E))
17263 return false;
17264
17265 if (Info.EnableNewConstInterp) {
17266 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
17267 return false;
17268 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17269 ConstantExprKind::Normal);
17270 }
17271
17272 if (!::Evaluate(Result, Info, E))
17273 return false;
17274
17275 // Implicit lvalue-to-rvalue cast.
17276 if (E->isGLValue()) {
17277 LValue LV;
17278 LV.setFrom(Info.Ctx, Result);
17279 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17280 return false;
17281 }
17282
17283 // Check this core constant expression is a constant expression.
17284 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17285 ConstantExprKind::Normal) &&
17286 CheckMemoryLeaks(Info);
17287}
17288
17289static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
17290 const ASTContext &Ctx, bool &IsConst) {
17291 // Fast-path evaluations of integer literals, since we sometimes see files
17292 // containing vast quantities of these.
17293 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
17294 Result =
17295 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
17296 IsConst = true;
17297 return true;
17298 }
17299
17300 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
17301 Result = APValue(APSInt(APInt(1, L->getValue())));
17302 IsConst = true;
17303 return true;
17304 }
17305
17306 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
17307 Result = APValue(FL->getValue());
17308 IsConst = true;
17309 return true;
17310 }
17311
17312 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
17313 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
17314 IsConst = true;
17315 return true;
17316 }
17317
17318 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
17319 if (CE->hasAPValueResult()) {
17320 APValue APV = CE->getAPValueResult();
17321 if (!APV.isLValue()) {
17322 Result = std::move(APV);
17323 IsConst = true;
17324 return true;
17325 }
17326 }
17327
17328 // The SubExpr is usually just an IntegerLiteral.
17329 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
17330 }
17331
17332 // This case should be rare, but we need to check it before we check on
17333 // the type below.
17334 if (Exp->getType().isNull()) {
17335 IsConst = false;
17336 return true;
17337 }
17338
17339 return false;
17340}
17341
17344 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
17345 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
17346}
17347
17348static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
17349 const ASTContext &Ctx, EvalInfo &Info) {
17350 assert(!E->isValueDependent());
17351 bool IsConst;
17352 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
17353 return IsConst;
17354
17355 return EvaluateAsRValue(Info, E, Result.Val);
17356}
17357
17359 const ASTContext &Ctx,
17360 Expr::SideEffectsKind AllowSideEffects,
17361 EvalInfo &Info) {
17362 assert(!E->isValueDependent());
17364 return false;
17365
17366 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
17367 !ExprResult.Val.isInt() ||
17368 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17369 return false;
17370
17371 return true;
17372}
17373
17375 const ASTContext &Ctx,
17376 Expr::SideEffectsKind AllowSideEffects,
17377 EvalInfo &Info) {
17378 assert(!E->isValueDependent());
17379 if (!E->getType()->isFixedPointType())
17380 return false;
17381
17382 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
17383 return false;
17384
17385 if (!ExprResult.Val.isFixedPoint() ||
17386 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17387 return false;
17388
17389 return true;
17390}
17391
17392/// EvaluateAsRValue - Return true if this is a constant which we can fold using
17393/// any crazy technique (that has nothing to do with language standards) that
17394/// we want to. If this function returns true, it returns the folded constant
17395/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
17396/// will be applied to the result.
17398 bool InConstantContext) const {
17399 assert(!isValueDependent() &&
17400 "Expression evaluator can't be called on a dependent expression.");
17401 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
17402 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17403 Info.InConstantContext = InConstantContext;
17404 return ::EvaluateAsRValue(this, Result, Ctx, Info);
17405}
17406
17407bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
17408 bool InConstantContext) const {
17409 assert(!isValueDependent() &&
17410 "Expression evaluator can't be called on a dependent expression.");
17411 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
17412 EvalResult Scratch;
17413 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
17414 HandleConversionToBool(Scratch.Val, Result);
17415}
17416
17418 SideEffectsKind AllowSideEffects,
17419 bool InConstantContext) const {
17420 assert(!isValueDependent() &&
17421 "Expression evaluator can't be called on a dependent expression.");
17422 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
17423 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17424 Info.InConstantContext = InConstantContext;
17425 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
17426}
17427
17429 SideEffectsKind AllowSideEffects,
17430 bool InConstantContext) const {
17431 assert(!isValueDependent() &&
17432 "Expression evaluator can't be called on a dependent expression.");
17433 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
17434 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
17435 Info.InConstantContext = InConstantContext;
17436 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
17437}
17438
17439bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
17440 SideEffectsKind AllowSideEffects,
17441 bool InConstantContext) const {
17442 assert(!isValueDependent() &&
17443 "Expression evaluator can't be called on a dependent expression.");
17444
17445 if (!getType()->isRealFloatingType())
17446 return false;
17447
17448 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
17450 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
17451 !ExprResult.Val.isFloat() ||
17452 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
17453 return false;
17454
17455 Result = ExprResult.Val.getFloat();
17456 return true;
17457}
17458
17460 bool InConstantContext) const {
17461 assert(!isValueDependent() &&
17462 "Expression evaluator can't be called on a dependent expression.");
17463
17464 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
17465 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
17466 Info.InConstantContext = InConstantContext;
17467 LValue LV;
17468 CheckedTemporaries CheckedTemps;
17469 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
17470 Result.HasSideEffects ||
17471 !CheckLValueConstantExpression(Info, getExprLoc(),
17472 Ctx.getLValueReferenceType(getType()), LV,
17473 ConstantExprKind::Normal, CheckedTemps))
17474 return false;
17475
17476 LV.moveInto(Result.Val);
17477 return true;
17478}
17479
17481 APValue DestroyedValue, QualType Type,
17483 bool IsConstantDestruction) {
17484 EvalInfo Info(Ctx, EStatus,
17485 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
17486 : EvalInfo::EM_ConstantFold);
17487 Info.setEvaluatingDecl(Base, DestroyedValue,
17488 EvalInfo::EvaluatingDeclKind::Dtor);
17489 Info.InConstantContext = IsConstantDestruction;
17490
17491 LValue LVal;
17492 LVal.set(Base);
17493
17494 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
17495 EStatus.HasSideEffects)
17496 return false;
17497
17498 if (!Info.discardCleanups())
17499 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17500
17501 return true;
17502}
17503
17505 ConstantExprKind Kind) const {
17506 assert(!isValueDependent() &&
17507 "Expression evaluator can't be called on a dependent expression.");
17508 bool IsConst;
17509 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
17510 Result.Val.hasValue())
17511 return true;
17512
17513 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
17514 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
17515 EvalInfo Info(Ctx, Result, EM);
17516 Info.InConstantContext = true;
17517
17518 if (Info.EnableNewConstInterp) {
17519 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
17520 return false;
17521 return CheckConstantExpression(Info, getExprLoc(),
17522 getStorageType(Ctx, this), Result.Val, Kind);
17523 }
17524
17525 // The type of the object we're initializing is 'const T' for a class NTTP.
17526 QualType T = getType();
17527 if (Kind == ConstantExprKind::ClassTemplateArgument)
17528 T.addConst();
17529
17530 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
17531 // represent the result of the evaluation. CheckConstantExpression ensures
17532 // this doesn't escape.
17533 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
17534 APValue::LValueBase Base(&BaseMTE);
17535 Info.setEvaluatingDecl(Base, Result.Val);
17536
17537 LValue LVal;
17538 LVal.set(Base);
17539 // C++23 [intro.execution]/p5
17540 // A full-expression is [...] a constant-expression
17541 // So we need to make sure temporary objects are destroyed after having
17542 // evaluating the expression (per C++23 [class.temporary]/p4).
17543 FullExpressionRAII Scope(Info);
17544 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
17545 Result.HasSideEffects || !Scope.destroy())
17546 return false;
17547
17548 if (!Info.discardCleanups())
17549 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17550
17551 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
17552 Result.Val, Kind))
17553 return false;
17554 if (!CheckMemoryLeaks(Info))
17555 return false;
17556
17557 // If this is a class template argument, it's required to have constant
17558 // destruction too.
17559 if (Kind == ConstantExprKind::ClassTemplateArgument &&
17560 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
17561 true) ||
17562 Result.HasSideEffects)) {
17563 // FIXME: Prefix a note to indicate that the problem is lack of constant
17564 // destruction.
17565 return false;
17566 }
17567
17568 return true;
17569}
17570
17572 const VarDecl *VD,
17574 bool IsConstantInitialization) const {
17575 assert(!isValueDependent() &&
17576 "Expression evaluator can't be called on a dependent expression.");
17577
17578 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
17579 std::string Name;
17580 llvm::raw_string_ostream OS(Name);
17581 VD->printQualifiedName(OS);
17582 return Name;
17583 });
17584
17585 Expr::EvalStatus EStatus;
17586 EStatus.Diag = &Notes;
17587
17588 EvalInfo Info(Ctx, EStatus,
17589 (IsConstantInitialization &&
17590 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
17591 ? EvalInfo::EM_ConstantExpression
17592 : EvalInfo::EM_ConstantFold);
17593 Info.setEvaluatingDecl(VD, Value);
17594 Info.InConstantContext = IsConstantInitialization;
17595
17596 SourceLocation DeclLoc = VD->getLocation();
17597 QualType DeclTy = VD->getType();
17598
17599 if (Info.EnableNewConstInterp) {
17600 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
17601 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
17602 return false;
17603
17604 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17605 ConstantExprKind::Normal);
17606 } else {
17607 LValue LVal;
17608 LVal.set(VD);
17609
17610 {
17611 // C++23 [intro.execution]/p5
17612 // A full-expression is ... an init-declarator ([dcl.decl]) or a
17613 // mem-initializer.
17614 // So we need to make sure temporary objects are destroyed after having
17615 // evaluated the expression (per C++23 [class.temporary]/p4).
17616 //
17617 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
17618 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
17619 // outermost FullExpr, such as ExprWithCleanups.
17620 FullExpressionRAII Scope(Info);
17621 if (!EvaluateInPlace(Value, Info, LVal, this,
17622 /*AllowNonLiteralTypes=*/true) ||
17623 EStatus.HasSideEffects)
17624 return false;
17625 }
17626
17627 // At this point, any lifetime-extended temporaries are completely
17628 // initialized.
17629 Info.performLifetimeExtension();
17630
17631 if (!Info.discardCleanups())
17632 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17633 }
17634
17635 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17636 ConstantExprKind::Normal) &&
17637 CheckMemoryLeaks(Info);
17638}
17639
17642 Expr::EvalStatus EStatus;
17643 EStatus.Diag = &Notes;
17644
17645 // Only treat the destruction as constant destruction if we formally have
17646 // constant initialization (or are usable in a constant expression).
17647 bool IsConstantDestruction = hasConstantInitialization();
17648
17649 // Make a copy of the value for the destructor to mutate, if we know it.
17650 // Otherwise, treat the value as default-initialized; if the destructor works
17651 // anyway, then the destruction is constant (and must be essentially empty).
17652 APValue DestroyedValue;
17653 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17654 DestroyedValue = *getEvaluatedValue();
17655 else if (!handleDefaultInitValue(getType(), DestroyedValue))
17656 return false;
17657
17658 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17659 getType(), getLocation(), EStatus,
17660 IsConstantDestruction) ||
17661 EStatus.HasSideEffects)
17662 return false;
17663
17664 ensureEvaluatedStmt()->HasConstantDestruction = true;
17665 return true;
17666}
17667
17668/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17669/// constant folded, but discard the result.
17671 assert(!isValueDependent() &&
17672 "Expression evaluator can't be called on a dependent expression.");
17673
17674 EvalResult Result;
17675 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17676 !hasUnacceptableSideEffect(Result, SEK);
17677}
17678
17681 assert(!isValueDependent() &&
17682 "Expression evaluator can't be called on a dependent expression.");
17683
17684 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17685 EvalResult EVResult;
17686 EVResult.Diag = Diag;
17687 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17688 Info.InConstantContext = true;
17689
17690 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17691 (void)Result;
17692 assert(Result && "Could not evaluate expression");
17693 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17694
17695 return EVResult.Val.getInt();
17696}
17697
17700 assert(!isValueDependent() &&
17701 "Expression evaluator can't be called on a dependent expression.");
17702
17703 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17704 EvalResult EVResult;
17705 EVResult.Diag = Diag;
17706 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17707 Info.InConstantContext = true;
17708 Info.CheckingForUndefinedBehavior = true;
17709
17710 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17711 (void)Result;
17712 assert(Result && "Could not evaluate expression");
17713 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17714
17715 return EVResult.Val.getInt();
17716}
17717
17719 assert(!isValueDependent() &&
17720 "Expression evaluator can't be called on a dependent expression.");
17721
17722 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17723 bool IsConst;
17724 EvalResult EVResult;
17725 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
17726 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17727 Info.CheckingForUndefinedBehavior = true;
17728 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17729 }
17730}
17731
17733 assert(Val.isLValue());
17734 return IsGlobalLValue(Val.getLValueBase());
17735}
17736
17737/// isIntegerConstantExpr - this recursive routine will test if an expression is
17738/// an integer constant expression.
17739
17740/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17741/// comma, etc
17742
17743// CheckICE - This function does the fundamental ICE checking: the returned
17744// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
17745//
17746// Note that to reduce code duplication, this helper does no evaluation
17747// itself; the caller checks whether the expression is evaluatable, and
17748// in the rare cases where CheckICE actually cares about the evaluated
17749// value, it calls into Evaluate.
17750
17751namespace {
17752
17753enum ICEKind {
17754 /// This expression is an ICE.
17755 IK_ICE,
17756 /// This expression is not an ICE, but if it isn't evaluated, it's
17757 /// a legal subexpression for an ICE. This return value is used to handle
17758 /// the comma operator in C99 mode, and non-constant subexpressions.
17759 IK_ICEIfUnevaluated,
17760 /// This expression is not an ICE, and is not a legal subexpression for one.
17761 IK_NotICE
17762};
17763
17764struct ICEDiag {
17765 ICEKind Kind;
17767
17768 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17769};
17770
17771}
17772
17773static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17774
17775static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17776
17777static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17778 Expr::EvalResult EVResult;
17779 Expr::EvalStatus Status;
17780 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17781
17782 Info.InConstantContext = true;
17783 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17784 !EVResult.Val.isInt())
17785 return ICEDiag(IK_NotICE, E->getBeginLoc());
17786
17787 return NoDiag();
17788}
17789
17790static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17791 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17793 return ICEDiag(IK_NotICE, E->getBeginLoc());
17794
17795 switch (E->getStmtClass()) {
17796#define ABSTRACT_STMT(Node)
17797#define STMT(Node, Base) case Expr::Node##Class:
17798#define EXPR(Node, Base)
17799#include "clang/AST/StmtNodes.inc"
17800 case Expr::PredefinedExprClass:
17801 case Expr::FloatingLiteralClass:
17802 case Expr::ImaginaryLiteralClass:
17803 case Expr::StringLiteralClass:
17804 case Expr::ArraySubscriptExprClass:
17805 case Expr::MatrixSubscriptExprClass:
17806 case Expr::ArraySectionExprClass:
17807 case Expr::OMPArrayShapingExprClass:
17808 case Expr::OMPIteratorExprClass:
17809 case Expr::MemberExprClass:
17810 case Expr::CompoundAssignOperatorClass:
17811 case Expr::CompoundLiteralExprClass:
17812 case Expr::ExtVectorElementExprClass:
17813 case Expr::DesignatedInitExprClass:
17814 case Expr::ArrayInitLoopExprClass:
17815 case Expr::ArrayInitIndexExprClass:
17816 case Expr::NoInitExprClass:
17817 case Expr::DesignatedInitUpdateExprClass:
17818 case Expr::ImplicitValueInitExprClass:
17819 case Expr::ParenListExprClass:
17820 case Expr::VAArgExprClass:
17821 case Expr::AddrLabelExprClass:
17822 case Expr::StmtExprClass:
17823 case Expr::CXXMemberCallExprClass:
17824 case Expr::CUDAKernelCallExprClass:
17825 case Expr::CXXAddrspaceCastExprClass:
17826 case Expr::CXXDynamicCastExprClass:
17827 case Expr::CXXTypeidExprClass:
17828 case Expr::CXXUuidofExprClass:
17829 case Expr::MSPropertyRefExprClass:
17830 case Expr::MSPropertySubscriptExprClass:
17831 case Expr::CXXNullPtrLiteralExprClass:
17832 case Expr::UserDefinedLiteralClass:
17833 case Expr::CXXThisExprClass:
17834 case Expr::CXXThrowExprClass:
17835 case Expr::CXXNewExprClass:
17836 case Expr::CXXDeleteExprClass:
17837 case Expr::CXXPseudoDestructorExprClass:
17838 case Expr::UnresolvedLookupExprClass:
17839 case Expr::RecoveryExprClass:
17840 case Expr::DependentScopeDeclRefExprClass:
17841 case Expr::CXXConstructExprClass:
17842 case Expr::CXXInheritedCtorInitExprClass:
17843 case Expr::CXXStdInitializerListExprClass:
17844 case Expr::CXXBindTemporaryExprClass:
17845 case Expr::ExprWithCleanupsClass:
17846 case Expr::CXXTemporaryObjectExprClass:
17847 case Expr::CXXUnresolvedConstructExprClass:
17848 case Expr::CXXDependentScopeMemberExprClass:
17849 case Expr::UnresolvedMemberExprClass:
17850 case Expr::ObjCStringLiteralClass:
17851 case Expr::ObjCBoxedExprClass:
17852 case Expr::ObjCArrayLiteralClass:
17853 case Expr::ObjCDictionaryLiteralClass:
17854 case Expr::ObjCEncodeExprClass:
17855 case Expr::ObjCMessageExprClass:
17856 case Expr::ObjCSelectorExprClass:
17857 case Expr::ObjCProtocolExprClass:
17858 case Expr::ObjCIvarRefExprClass:
17859 case Expr::ObjCPropertyRefExprClass:
17860 case Expr::ObjCSubscriptRefExprClass:
17861 case Expr::ObjCIsaExprClass:
17862 case Expr::ObjCAvailabilityCheckExprClass:
17863 case Expr::ShuffleVectorExprClass:
17864 case Expr::ConvertVectorExprClass:
17865 case Expr::BlockExprClass:
17866 case Expr::NoStmtClass:
17867 case Expr::OpaqueValueExprClass:
17868 case Expr::PackExpansionExprClass:
17869 case Expr::SubstNonTypeTemplateParmPackExprClass:
17870 case Expr::FunctionParmPackExprClass:
17871 case Expr::AsTypeExprClass:
17872 case Expr::ObjCIndirectCopyRestoreExprClass:
17873 case Expr::MaterializeTemporaryExprClass:
17874 case Expr::PseudoObjectExprClass:
17875 case Expr::AtomicExprClass:
17876 case Expr::LambdaExprClass:
17877 case Expr::CXXFoldExprClass:
17878 case Expr::CoawaitExprClass:
17879 case Expr::DependentCoawaitExprClass:
17880 case Expr::CoyieldExprClass:
17881 case Expr::SYCLUniqueStableNameExprClass:
17882 case Expr::CXXParenListInitExprClass:
17883 case Expr::HLSLOutArgExprClass:
17884 return ICEDiag(IK_NotICE, E->getBeginLoc());
17885
17886 case Expr::InitListExprClass: {
17887 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17888 // form "T x = { a };" is equivalent to "T x = a;".
17889 // Unless we're initializing a reference, T is a scalar as it is known to be
17890 // of integral or enumeration type.
17891 if (E->isPRValue())
17892 if (cast<InitListExpr>(E)->getNumInits() == 1)
17893 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17894 return ICEDiag(IK_NotICE, E->getBeginLoc());
17895 }
17896
17897 case Expr::SizeOfPackExprClass:
17898 case Expr::GNUNullExprClass:
17899 case Expr::SourceLocExprClass:
17900 case Expr::EmbedExprClass:
17901 case Expr::OpenACCAsteriskSizeExprClass:
17902 return NoDiag();
17903
17904 case Expr::PackIndexingExprClass:
17905 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17906
17907 case Expr::SubstNonTypeTemplateParmExprClass:
17908 return
17909 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17910
17911 case Expr::ConstantExprClass:
17912 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17913
17914 case Expr::ParenExprClass:
17915 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17916 case Expr::GenericSelectionExprClass:
17917 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17918 case Expr::IntegerLiteralClass:
17919 case Expr::FixedPointLiteralClass:
17920 case Expr::CharacterLiteralClass:
17921 case Expr::ObjCBoolLiteralExprClass:
17922 case Expr::CXXBoolLiteralExprClass:
17923 case Expr::CXXScalarValueInitExprClass:
17924 case Expr::TypeTraitExprClass:
17925 case Expr::ConceptSpecializationExprClass:
17926 case Expr::RequiresExprClass:
17927 case Expr::ArrayTypeTraitExprClass:
17928 case Expr::ExpressionTraitExprClass:
17929 case Expr::CXXNoexceptExprClass:
17930 return NoDiag();
17931 case Expr::CallExprClass:
17932 case Expr::CXXOperatorCallExprClass: {
17933 // C99 6.6/3 allows function calls within unevaluated subexpressions of
17934 // constant expressions, but they can never be ICEs because an ICE cannot
17935 // contain an operand of (pointer to) function type.
17936 const CallExpr *CE = cast<CallExpr>(E);
17937 if (CE->getBuiltinCallee())
17938 return CheckEvalInICE(E, Ctx);
17939 return ICEDiag(IK_NotICE, E->getBeginLoc());
17940 }
17941 case Expr::CXXRewrittenBinaryOperatorClass:
17942 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17943 Ctx);
17944 case Expr::DeclRefExprClass: {
17945 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17946 if (isa<EnumConstantDecl>(D))
17947 return NoDiag();
17948
17949 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17950 // integer variables in constant expressions:
17951 //
17952 // C++ 7.1.5.1p2
17953 // A variable of non-volatile const-qualified integral or enumeration
17954 // type initialized by an ICE can be used in ICEs.
17955 //
17956 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17957 // that mode, use of reference variables should not be allowed.
17958 const VarDecl *VD = dyn_cast<VarDecl>(D);
17959 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17960 !VD->getType()->isReferenceType())
17961 return NoDiag();
17962
17963 return ICEDiag(IK_NotICE, E->getBeginLoc());
17964 }
17965 case Expr::UnaryOperatorClass: {
17966 const UnaryOperator *Exp = cast<UnaryOperator>(E);
17967 switch (Exp->getOpcode()) {
17968 case UO_PostInc:
17969 case UO_PostDec:
17970 case UO_PreInc:
17971 case UO_PreDec:
17972 case UO_AddrOf:
17973 case UO_Deref:
17974 case UO_Coawait:
17975 // C99 6.6/3 allows increment and decrement within unevaluated
17976 // subexpressions of constant expressions, but they can never be ICEs
17977 // because an ICE cannot contain an lvalue operand.
17978 return ICEDiag(IK_NotICE, E->getBeginLoc());
17979 case UO_Extension:
17980 case UO_LNot:
17981 case UO_Plus:
17982 case UO_Minus:
17983 case UO_Not:
17984 case UO_Real:
17985 case UO_Imag:
17986 return CheckICE(Exp->getSubExpr(), Ctx);
17987 }
17988 llvm_unreachable("invalid unary operator class");
17989 }
17990 case Expr::OffsetOfExprClass: {
17991 // Note that per C99, offsetof must be an ICE. And AFAIK, using
17992 // EvaluateAsRValue matches the proposed gcc behavior for cases like
17993 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
17994 // compliance: we should warn earlier for offsetof expressions with
17995 // array subscripts that aren't ICEs, and if the array subscripts
17996 // are ICEs, the value of the offsetof must be an integer constant.
17997 return CheckEvalInICE(E, Ctx);
17998 }
17999 case Expr::UnaryExprOrTypeTraitExprClass: {
18000 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
18001 if ((Exp->getKind() == UETT_SizeOf) &&
18003 return ICEDiag(IK_NotICE, E->getBeginLoc());
18004 if (Exp->getKind() == UETT_CountOf) {
18005 QualType ArgTy = Exp->getTypeOfArgument();
18006 if (ArgTy->isVariableArrayType()) {
18007 // We need to look whether the array is multidimensional. If it is,
18008 // then we want to check the size expression manually to see whether
18009 // it is an ICE or not.
18010 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
18011 if (VAT->getElementType()->isArrayType())
18012 // Variable array size expression could be missing (e.g. int a[*][10])
18013 // In that case, it can't be a constant expression.
18014 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
18015 : ICEDiag(IK_NotICE, E->getBeginLoc());
18016
18017 // Otherwise, this is a regular VLA, which is definitely not an ICE.
18018 return ICEDiag(IK_NotICE, E->getBeginLoc());
18019 }
18020 }
18021 return NoDiag();
18022 }
18023 case Expr::BinaryOperatorClass: {
18024 const BinaryOperator *Exp = cast<BinaryOperator>(E);
18025 switch (Exp->getOpcode()) {
18026 case BO_PtrMemD:
18027 case BO_PtrMemI:
18028 case BO_Assign:
18029 case BO_MulAssign:
18030 case BO_DivAssign:
18031 case BO_RemAssign:
18032 case BO_AddAssign:
18033 case BO_SubAssign:
18034 case BO_ShlAssign:
18035 case BO_ShrAssign:
18036 case BO_AndAssign:
18037 case BO_XorAssign:
18038 case BO_OrAssign:
18039 // C99 6.6/3 allows assignments within unevaluated subexpressions of
18040 // constant expressions, but they can never be ICEs because an ICE cannot
18041 // contain an lvalue operand.
18042 return ICEDiag(IK_NotICE, E->getBeginLoc());
18043
18044 case BO_Mul:
18045 case BO_Div:
18046 case BO_Rem:
18047 case BO_Add:
18048 case BO_Sub:
18049 case BO_Shl:
18050 case BO_Shr:
18051 case BO_LT:
18052 case BO_GT:
18053 case BO_LE:
18054 case BO_GE:
18055 case BO_EQ:
18056 case BO_NE:
18057 case BO_And:
18058 case BO_Xor:
18059 case BO_Or:
18060 case BO_Comma:
18061 case BO_Cmp: {
18062 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18063 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18064 if (Exp->getOpcode() == BO_Div ||
18065 Exp->getOpcode() == BO_Rem) {
18066 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
18067 // we don't evaluate one.
18068 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
18069 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
18070 if (REval == 0)
18071 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18072 if (REval.isSigned() && REval.isAllOnes()) {
18073 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
18074 if (LEval.isMinSignedValue())
18075 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18076 }
18077 }
18078 }
18079 if (Exp->getOpcode() == BO_Comma) {
18080 if (Ctx.getLangOpts().C99) {
18081 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
18082 // if it isn't evaluated.
18083 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
18084 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
18085 } else {
18086 // In both C89 and C++, commas in ICEs are illegal.
18087 return ICEDiag(IK_NotICE, E->getBeginLoc());
18088 }
18089 }
18090 return Worst(LHSResult, RHSResult);
18091 }
18092 case BO_LAnd:
18093 case BO_LOr: {
18094 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
18095 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
18096 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
18097 // Rare case where the RHS has a comma "side-effect"; we need
18098 // to actually check the condition to see whether the side
18099 // with the comma is evaluated.
18100 if ((Exp->getOpcode() == BO_LAnd) !=
18101 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
18102 return RHSResult;
18103 return NoDiag();
18104 }
18105
18106 return Worst(LHSResult, RHSResult);
18107 }
18108 }
18109 llvm_unreachable("invalid binary operator kind");
18110 }
18111 case Expr::ImplicitCastExprClass:
18112 case Expr::CStyleCastExprClass:
18113 case Expr::CXXFunctionalCastExprClass:
18114 case Expr::CXXStaticCastExprClass:
18115 case Expr::CXXReinterpretCastExprClass:
18116 case Expr::CXXConstCastExprClass:
18117 case Expr::ObjCBridgedCastExprClass: {
18118 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
18119 if (isa<ExplicitCastExpr>(E)) {
18120 if (const FloatingLiteral *FL
18121 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
18122 unsigned DestWidth = Ctx.getIntWidth(E->getType());
18123 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
18124 APSInt IgnoredVal(DestWidth, !DestSigned);
18125 bool Ignored;
18126 // If the value does not fit in the destination type, the behavior is
18127 // undefined, so we are not required to treat it as a constant
18128 // expression.
18129 if (FL->getValue().convertToInteger(IgnoredVal,
18130 llvm::APFloat::rmTowardZero,
18131 &Ignored) & APFloat::opInvalidOp)
18132 return ICEDiag(IK_NotICE, E->getBeginLoc());
18133 return NoDiag();
18134 }
18135 }
18136 switch (cast<CastExpr>(E)->getCastKind()) {
18137 case CK_LValueToRValue:
18138 case CK_AtomicToNonAtomic:
18139 case CK_NonAtomicToAtomic:
18140 case CK_NoOp:
18141 case CK_IntegralToBoolean:
18142 case CK_IntegralCast:
18143 return CheckICE(SubExpr, Ctx);
18144 default:
18145 return ICEDiag(IK_NotICE, E->getBeginLoc());
18146 }
18147 }
18148 case Expr::BinaryConditionalOperatorClass: {
18149 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
18150 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
18151 if (CommonResult.Kind == IK_NotICE) return CommonResult;
18152 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18153 if (FalseResult.Kind == IK_NotICE) return FalseResult;
18154 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
18155 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
18156 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
18157 return FalseResult;
18158 }
18159 case Expr::ConditionalOperatorClass: {
18160 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
18161 // If the condition (ignoring parens) is a __builtin_constant_p call,
18162 // then only the true side is actually considered in an integer constant
18163 // expression, and it is fully evaluated. This is an important GNU
18164 // extension. See GCC PR38377 for discussion.
18165 if (const CallExpr *CallCE
18166 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
18167 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
18168 return CheckEvalInICE(E, Ctx);
18169 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
18170 if (CondResult.Kind == IK_NotICE)
18171 return CondResult;
18172
18173 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
18174 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
18175
18176 if (TrueResult.Kind == IK_NotICE)
18177 return TrueResult;
18178 if (FalseResult.Kind == IK_NotICE)
18179 return FalseResult;
18180 if (CondResult.Kind == IK_ICEIfUnevaluated)
18181 return CondResult;
18182 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
18183 return NoDiag();
18184 // Rare case where the diagnostics depend on which side is evaluated
18185 // Note that if we get here, CondResult is 0, and at least one of
18186 // TrueResult and FalseResult is non-zero.
18187 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
18188 return FalseResult;
18189 return TrueResult;
18190 }
18191 case Expr::CXXDefaultArgExprClass:
18192 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
18193 case Expr::CXXDefaultInitExprClass:
18194 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
18195 case Expr::ChooseExprClass: {
18196 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
18197 }
18198 case Expr::BuiltinBitCastExprClass: {
18199 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
18200 return ICEDiag(IK_NotICE, E->getBeginLoc());
18201 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
18202 }
18203 }
18204
18205 llvm_unreachable("Invalid StmtClass!");
18206}
18207
18208/// Evaluate an expression as a C++11 integral constant expression.
18210 const Expr *E,
18211 llvm::APSInt *Value) {
18213 return false;
18214
18215 APValue Result;
18216 if (!E->isCXX11ConstantExpr(Ctx, &Result))
18217 return false;
18218
18219 if (!Result.isInt())
18220 return false;
18221
18222 if (Value) *Value = Result.getInt();
18223 return true;
18224}
18225
18227 assert(!isValueDependent() &&
18228 "Expression evaluator can't be called on a dependent expression.");
18229
18230 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
18231
18232 if (Ctx.getLangOpts().CPlusPlus11)
18233 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
18234
18235 ICEDiag D = CheckICE(this, Ctx);
18236 if (D.Kind != IK_ICE)
18237 return false;
18238 return true;
18239}
18240
18241std::optional<llvm::APSInt>
18243 if (isValueDependent()) {
18244 // Expression evaluator can't succeed on a dependent expression.
18245 return std::nullopt;
18246 }
18247
18248 if (Ctx.getLangOpts().CPlusPlus11) {
18249 APSInt Value;
18251 return Value;
18252 return std::nullopt;
18253 }
18254
18255 if (!isIntegerConstantExpr(Ctx))
18256 return std::nullopt;
18257
18258 // The only possible side-effects here are due to UB discovered in the
18259 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
18260 // required to treat the expression as an ICE, so we produce the folded
18261 // value.
18263 Expr::EvalStatus Status;
18264 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
18265 Info.InConstantContext = true;
18266
18267 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
18268 llvm_unreachable("ICE cannot be evaluated!");
18269
18270 return ExprResult.Val.getInt();
18271}
18272
18274 assert(!isValueDependent() &&
18275 "Expression evaluator can't be called on a dependent expression.");
18276
18277 return CheckICE(this, Ctx).Kind == IK_ICE;
18278}
18279
18280bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result) const {
18281 assert(!isValueDependent() &&
18282 "Expression evaluator can't be called on a dependent expression.");
18283
18284 // We support this checking in C++98 mode in order to diagnose compatibility
18285 // issues.
18286 assert(Ctx.getLangOpts().CPlusPlus);
18287
18288 bool IsConst;
18289 APValue Scratch;
18290 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
18291 if (Result)
18292 *Result = Scratch;
18293 return true;
18294 }
18295
18296 // Build evaluation settings.
18297 Expr::EvalStatus Status;
18299 Status.Diag = &Diags;
18300 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
18301
18302 bool IsConstExpr =
18303 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
18304 // FIXME: We don't produce a diagnostic for this, but the callers that
18305 // call us on arbitrary full-expressions should generally not care.
18306 Info.discardCleanups() && !Status.HasSideEffects;
18307
18308 return IsConstExpr && Diags.empty();
18309}
18310
18312 const FunctionDecl *Callee,
18314 const Expr *This) const {
18315 assert(!isValueDependent() &&
18316 "Expression evaluator can't be called on a dependent expression.");
18317
18318 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
18319 std::string Name;
18320 llvm::raw_string_ostream OS(Name);
18321 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
18322 /*Qualified=*/true);
18323 return Name;
18324 });
18325
18326 Expr::EvalStatus Status;
18327 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
18328 Info.InConstantContext = true;
18329
18330 LValue ThisVal;
18331 const LValue *ThisPtr = nullptr;
18332 if (This) {
18333#ifndef NDEBUG
18334 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
18335 assert(MD && "Don't provide `this` for non-methods.");
18336 assert(MD->isImplicitObjectMemberFunction() &&
18337 "Don't provide `this` for methods without an implicit object.");
18338#endif
18339 if (!This->isValueDependent() &&
18340 EvaluateObjectArgument(Info, This, ThisVal) &&
18341 !Info.EvalStatus.HasSideEffects)
18342 ThisPtr = &ThisVal;
18343
18344 // Ignore any side-effects from a failed evaluation. This is safe because
18345 // they can't interfere with any other argument evaluation.
18346 Info.EvalStatus.HasSideEffects = false;
18347 }
18348
18349 CallRef Call = Info.CurrentCall->createCall(Callee);
18350 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
18351 I != E; ++I) {
18352 unsigned Idx = I - Args.begin();
18353 if (Idx >= Callee->getNumParams())
18354 break;
18355 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
18356 if ((*I)->isValueDependent() ||
18357 !EvaluateCallArg(PVD, *I, Call, Info) ||
18358 Info.EvalStatus.HasSideEffects) {
18359 // If evaluation fails, throw away the argument entirely.
18360 if (APValue *Slot = Info.getParamSlot(Call, PVD))
18361 *Slot = APValue();
18362 }
18363
18364 // Ignore any side-effects from a failed evaluation. This is safe because
18365 // they can't interfere with any other argument evaluation.
18366 Info.EvalStatus.HasSideEffects = false;
18367 }
18368
18369 // Parameter cleanups happen in the caller and are not part of this
18370 // evaluation.
18371 Info.discardCleanups();
18372 Info.EvalStatus.HasSideEffects = false;
18373
18374 // Build fake call to Callee.
18375 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
18376 Call);
18377 // FIXME: Missing ExprWithCleanups in enable_if conditions?
18378 FullExpressionRAII Scope(Info);
18379 return Evaluate(Value, Info, this) && Scope.destroy() &&
18380 !Info.EvalStatus.HasSideEffects;
18381}
18382
18385 PartialDiagnosticAt> &Diags) {
18386 // FIXME: It would be useful to check constexpr function templates, but at the
18387 // moment the constant expression evaluator cannot cope with the non-rigorous
18388 // ASTs which we build for dependent expressions.
18389 if (FD->isDependentContext())
18390 return true;
18391
18392 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
18393 std::string Name;
18394 llvm::raw_string_ostream OS(Name);
18396 /*Qualified=*/true);
18397 return Name;
18398 });
18399
18400 Expr::EvalStatus Status;
18401 Status.Diag = &Diags;
18402
18403 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
18404 Info.InConstantContext = true;
18405 Info.CheckingPotentialConstantExpression = true;
18406
18407 // The constexpr VM attempts to compile all methods to bytecode here.
18408 if (Info.EnableNewConstInterp) {
18409 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
18410 return Diags.empty();
18411 }
18412
18413 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
18414 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
18415
18416 // Fabricate an arbitrary expression on the stack and pretend that it
18417 // is a temporary being used as the 'this' pointer.
18418 LValue This;
18419 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
18420 : Info.Ctx.IntTy);
18421 This.set({&VIE, Info.CurrentCall->Index});
18422
18424
18425 APValue Scratch;
18426 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
18427 // Evaluate the call as a constant initializer, to allow the construction
18428 // of objects of non-literal types.
18429 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
18430 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
18431 } else {
18434 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
18435 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
18436 /*ResultSlot=*/nullptr);
18437 }
18438
18439 return Diags.empty();
18440}
18441
18443 const FunctionDecl *FD,
18445 PartialDiagnosticAt> &Diags) {
18446 assert(!E->isValueDependent() &&
18447 "Expression evaluator can't be called on a dependent expression.");
18448
18449 Expr::EvalStatus Status;
18450 Status.Diag = &Diags;
18451
18452 EvalInfo Info(FD->getASTContext(), Status,
18453 EvalInfo::EM_ConstantExpressionUnevaluated);
18454 Info.InConstantContext = true;
18455 Info.CheckingPotentialConstantExpression = true;
18456
18457 if (Info.EnableNewConstInterp) {
18458 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
18459 return Diags.empty();
18460 }
18461
18462 // Fabricate a call stack frame to give the arguments a plausible cover story.
18463 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
18464 /*CallExpr=*/nullptr, CallRef());
18465
18466 APValue ResultScratch;
18467 Evaluate(ResultScratch, Info, E);
18468 return Diags.empty();
18469}
18470
18471bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
18472 unsigned Type) const {
18473 if (!getType()->isPointerType())
18474 return false;
18475
18476 Expr::EvalStatus Status;
18477 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18478 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
18479}
18480
18481static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
18482 EvalInfo &Info, std::string *StringResult) {
18483 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
18484 return false;
18485
18486 LValue String;
18487
18488 if (!EvaluatePointer(E, String, Info))
18489 return false;
18490
18491 QualType CharTy = E->getType()->getPointeeType();
18492
18493 // Fast path: if it's a string literal, search the string value.
18494 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
18495 String.getLValueBase().dyn_cast<const Expr *>())) {
18496 StringRef Str = S->getBytes();
18497 int64_t Off = String.Offset.getQuantity();
18498 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
18499 S->getCharByteWidth() == 1 &&
18500 // FIXME: Add fast-path for wchar_t too.
18501 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
18502 Str = Str.substr(Off);
18503
18504 StringRef::size_type Pos = Str.find(0);
18505 if (Pos != StringRef::npos)
18506 Str = Str.substr(0, Pos);
18507
18508 Result = Str.size();
18509 if (StringResult)
18510 *StringResult = Str;
18511 return true;
18512 }
18513
18514 // Fall through to slow path.
18515 }
18516
18517 // Slow path: scan the bytes of the string looking for the terminating 0.
18518 for (uint64_t Strlen = 0; /**/; ++Strlen) {
18519 APValue Char;
18520 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
18521 !Char.isInt())
18522 return false;
18523 if (!Char.getInt()) {
18524 Result = Strlen;
18525 return true;
18526 } else if (StringResult)
18527 StringResult->push_back(Char.getInt().getExtValue());
18528 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
18529 return false;
18530 }
18531}
18532
18533std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
18534 Expr::EvalStatus Status;
18535 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18536 uint64_t Result;
18537 std::string StringResult;
18538
18539 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
18540 return StringResult;
18541 return {};
18542}
18543
18544template <typename T>
18545static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
18546 const Expr *SizeExpression,
18547 const Expr *PtrExpression,
18548 ASTContext &Ctx,
18549 Expr::EvalResult &Status) {
18550 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
18551 Info.InConstantContext = true;
18552
18553 if (Info.EnableNewConstInterp)
18554 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
18555 PtrExpression, Result);
18556
18557 LValue String;
18558 FullExpressionRAII Scope(Info);
18559 APSInt SizeValue;
18560 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
18561 return false;
18562
18563 uint64_t Size = SizeValue.getZExtValue();
18564
18565 // FIXME: better protect against invalid or excessive sizes
18566 if constexpr (std::is_same_v<APValue, T>)
18567 Result = APValue(APValue::UninitArray{}, Size, Size);
18568 else {
18569 if (Size < Result.max_size())
18570 Result.reserve(Size);
18571 }
18572 if (!::EvaluatePointer(PtrExpression, String, Info))
18573 return false;
18574
18575 QualType CharTy = PtrExpression->getType()->getPointeeType();
18576 for (uint64_t I = 0; I < Size; ++I) {
18577 APValue Char;
18578 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
18579 Char))
18580 return false;
18581
18582 if constexpr (std::is_same_v<APValue, T>) {
18583 Result.getArrayInitializedElt(I) = std::move(Char);
18584 } else {
18585 APSInt C = Char.getInt();
18586
18587 assert(C.getBitWidth() <= 8 &&
18588 "string element not representable in char");
18589
18590 Result.push_back(static_cast<char>(C.getExtValue()));
18591 }
18592
18593 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
18594 return false;
18595 }
18596
18597 return Scope.destroy() && CheckMemoryLeaks(Info);
18598}
18599
18600bool Expr::EvaluateCharRangeAsString(std::string &Result,
18601 const Expr *SizeExpression,
18602 const Expr *PtrExpression, ASTContext &Ctx,
18603 EvalResult &Status) const {
18604 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18605 PtrExpression, Ctx, Status);
18606}
18607
18609 const Expr *SizeExpression,
18610 const Expr *PtrExpression, ASTContext &Ctx,
18611 EvalResult &Status) const {
18612 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
18613 PtrExpression, Ctx, Status);
18614}
18615
18616bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
18617 Expr::EvalStatus Status;
18618 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
18619
18620 if (Info.EnableNewConstInterp)
18621 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
18622
18623 return EvaluateBuiltinStrLen(this, Result, Info);
18624}
18625
18626namespace {
18627struct IsWithinLifetimeHandler {
18628 EvalInfo &Info;
18629 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
18630 using result_type = std::optional<bool>;
18631 std::optional<bool> failed() { return std::nullopt; }
18632 template <typename T>
18633 std::optional<bool> found(T &Subobj, QualType SubobjType) {
18634 return true;
18635 }
18636};
18637
18638std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
18639 const CallExpr *E) {
18640 EvalInfo &Info = IEE.Info;
18641 // Sometimes this is called during some sorts of constant folding / early
18642 // evaluation. These are meant for non-constant expressions and are not
18643 // necessary since this consteval builtin will never be evaluated at runtime.
18644 // Just fail to evaluate when not in a constant context.
18645 if (!Info.InConstantContext)
18646 return std::nullopt;
18647 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
18648 const Expr *Arg = E->getArg(0);
18649 if (Arg->isValueDependent())
18650 return std::nullopt;
18651 LValue Val;
18652 if (!EvaluatePointer(Arg, Val, Info))
18653 return std::nullopt;
18654
18655 if (Val.allowConstexprUnknown())
18656 return true;
18657
18658 auto Error = [&](int Diag) {
18659 bool CalledFromStd = false;
18660 const auto *Callee = Info.CurrentCall->getCallee();
18661 if (Callee && Callee->isInStdNamespace()) {
18662 const IdentifierInfo *Identifier = Callee->getIdentifier();
18663 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
18664 }
18665 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
18666 : E->getExprLoc(),
18667 diag::err_invalid_is_within_lifetime)
18668 << (CalledFromStd ? "std::is_within_lifetime"
18669 : "__builtin_is_within_lifetime")
18670 << Diag;
18671 return std::nullopt;
18672 };
18673 // C++2c [meta.const.eval]p4:
18674 // During the evaluation of an expression E as a core constant expression, a
18675 // call to this function is ill-formed unless p points to an object that is
18676 // usable in constant expressions or whose complete object's lifetime began
18677 // within E.
18678
18679 // Make sure it points to an object
18680 // nullptr does not point to an object
18681 if (Val.isNullPointer() || Val.getLValueBase().isNull())
18682 return Error(0);
18683 QualType T = Val.getLValueBase().getType();
18684 assert(!T->isFunctionType() &&
18685 "Pointers to functions should have been typed as function pointers "
18686 "which would have been rejected earlier");
18687 assert(T->isObjectType());
18688 // Hypothetical array element is not an object
18689 if (Val.getLValueDesignator().isOnePastTheEnd())
18690 return Error(1);
18691 assert(Val.getLValueDesignator().isValidSubobject() &&
18692 "Unchecked case for valid subobject");
18693 // All other ill-formed values should have failed EvaluatePointer, so the
18694 // object should be a pointer to an object that is usable in a constant
18695 // expression or whose complete lifetime began within the expression
18696 CompleteObject CO =
18697 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18698 // The lifetime hasn't begun yet if we are still evaluating the
18699 // initializer ([basic.life]p(1.2))
18700 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18701 return Error(2);
18702
18703 if (!CO)
18704 return false;
18705 IsWithinLifetimeHandler handler{Info};
18706 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18707}
18708} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
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 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.
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.
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.
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.
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.
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.
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.
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
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)
StringRef Identifier
Definition: Format.cpp:3185
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
#define X(type, name)
Definition: Value.h:145
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.
@ None
SourceLocation Loc
Definition: SemaObjC.cpp:754
bool Indirect
Definition: SemaObjC.cpp:755
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)
__device__ int
a trap message and trap category.
QualType getType() const
Definition: APValue.cpp:63
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
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:801
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.
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,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2716
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
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<=>,...
Definition: ASTContext.h:2565
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:793
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.
Definition: ASTContext.h:2625
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.
Definition: ASTContext.h:3310
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:3059
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2629
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:197
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:201
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:250
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:260
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4486
LabelDecl * getLabel() const
Definition: Expr.h:4509
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5957
Represents a loop initializing the elements of an array.
Definition: Expr.h:5904
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2723
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2990
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
QualType getElementType() const
Definition: TypeBase.h:3750
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: TypeBase.h:8142
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:4389
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4443
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4424
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
Expr * getLHS() const
Definition: Expr.h:4024
bool isComparisonOp() const
Definition: Expr.h:4075
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4121
bool isLogicalOp() const
Definition: Expr.h:4108
Expr * getRHS() const
Definition: Expr.h:4026
Opcode getOpcode() const
Definition: Expr.h:4019
A binding in a decomposition declaration.
Definition: DeclCXX.h:4179
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6560
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5470
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
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
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1494
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:723
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1549
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
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1271
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1378
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2620
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2869
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:481
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1753
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
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2349
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4303
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:768
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:5135
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
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.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:526
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:286
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2198
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:800
Represents the this expression in C++.
Definition: ExprCXX.h:1155
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:848
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1069
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1588
CaseStmt - Represent a case statement.
Definition: Stmt.h:1931
Expr * getLHS()
Definition: Stmt.h:2014
Expr * getRHS()
Definition: Stmt.h:2026
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3612
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3679
Expr * getSubExpr()
Definition: Expr.h:3662
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
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4784
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:3293
QualType getElementType() const
Definition: TypeBase.h:3303
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4236
QualType getComputationLHSType() const
Definition: Expr.h:4270
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3541
bool isFileScope() const
Definition: Expr.h:3573
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1731
bool body_empty() const
Definition: Stmt.h:1775
Stmt *const * const_body_iterator
Definition: Stmt.h:1803
body_iterator body_end()
Definition: Stmt.h:1796
body_range body()
Definition: Stmt.h:1794
body_iterator body_begin()
Definition: Stmt.h:1795
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4327
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4350
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4354
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:196
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: TypeBase.h:3839
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:3865
bool isZeroSize() const
Return true if the size is zero.
Definition: TypeBase.h:3846
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: TypeBase.h:3872
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: TypeBase.h:3852
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1084
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4655
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2393
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 isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1622
decl_range decls()
Definition: Stmt.h:1670
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:427
static void add(Kind k)
Definition: DeclBase.cpp:226
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
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
bool isAnyOperatorNew() const
A decomposition declaration.
Definition: DeclCXX.h:4243
auto flat_bindings() const
Definition: DeclCXX.h:4286
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2835
Stmt * getBody()
Definition: Stmt.h:2860
Expr * getCond()
Definition: Stmt.h:2853
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:5062
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3416
EnumDecl * getDefinitionOrSelf() const
Definition: Decl.h:4107
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4164
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EnumDecl * getOriginalDecl() const
Definition: TypeBase.h:6529
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3864
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3655
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:3078
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
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...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3922
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3073
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:3069
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:3624
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:3207
ConstantExprKind
Definition: Expr.h:751
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
An expression trait intrinsic.
Definition: ExprCXX.h:3063
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6500
bool isFPConstrained() const
Definition: LangOptions.h:844
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:862
RoundingMode getRoundingMode() const
Definition: LangOptions.h:850
Represents a member of a struct/union/class.
Definition: Decl.h:3153
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3256
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4689
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3238
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3389
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3400
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
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2891
Represents a function declaration or definition.
Definition: Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2790
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:4142
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4130
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3802
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:4266
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2776
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
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4859
Represents a C11 generic selection.
Definition: Expr.h:6114
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:2262
Stmt * getThen()
Definition: Stmt.h:2351
Stmt * getInit()
Definition: Stmt.h:2412
bool isNonNegatedConsteval() const
Definition: Stmt.h:2447
Expr * getCond()
Definition: Stmt.h:2339
Stmt * getElse()
Definition: Stmt.h:2360
bool isConsteval() const
Definition: Stmt.h:2442
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:1026
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1733
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5993
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3460
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3481
Describes an C or C++ initializer list.
Definition: Expr.h:5235
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
A global _GUID constant.
Definition: DeclCXX.h:4392
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4914
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition: Type.cpp:5502
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
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:88
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:128
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:409
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:52
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2529
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2588
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2576
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2569
unsigned getNumComponents() const
Definition: Expr.h:2584
Helper class for OffsetOfExpr.
Definition: Expr.h:2423
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2481
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2487
@ Array
An index into an array.
Definition: Expr.h:2428
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2432
@ Field
A field.
Definition: Expr.h:2430
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2435
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2477
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2497
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition: Expr.h:2092
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
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:3346
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:2007
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6692
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
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:8343
bool isConstant(const ASTContext &Ctx) const
Definition: TypeBase.h:1097
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:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
void removeLocalVolatile()
Definition: TypeBase.h:8459
QualType withCVRQualifiers(unsigned CVR) const
Definition: TypeBase.h:1179
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: TypeBase.h:1164
void removeLocalConst()
Definition: TypeBase.h:8451
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
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:8389
Represents a struct/union/class.
Definition: Decl.h:4305
bool hasFlexibleArrayMember() const
Definition: Decl.h:4338
field_iterator field_end() const
Definition: Decl.h:4511
field_range fields() const
Definition: Decl.h:4508
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4357
bool field_empty() const
Definition: Decl.h:4516
field_iterator field_begin() const
Definition: Decl.cpp:5150
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:505
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:4579
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4435
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4953
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4531
Stmt - This represents one statement.
Definition: Stmt.h:85
StmtClass getStmtClass() const
Definition: Stmt.h:1483
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:1801
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition: Expr.cpp:1184
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1884
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4658
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1904
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2512
Expr * getCond()
Definition: Stmt.h:2575
Stmt * getBody()
Definition: Stmt.h:2587
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1144
Stmt * getInit()
Definition: Stmt.h:2592
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2643
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4836
bool isUnion() const
Definition: Decl.h:3915
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1283
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
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:8325
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2890
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isStructureType() const
Definition: Type.cpp:678
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isFunctionReferenceType() const
Definition: TypeBase.h:8654
bool isMFloat8Type() const
Definition: TypeBase.h:8961
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
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:2998
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
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:9235
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2277
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
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:8683
bool isNothrowT() const
Definition: Type.cpp:3175
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:2430
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isVariableArrayType() const
Definition: TypeBase.h:8691
bool isChar8Type() const
Definition: Type.cpp:2152
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2612
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:9054
bool isExtVectorBoolType() const
Definition: TypeBase.h:8727
bool isMemberDataPointerType() const
Definition: TypeBase.h:8672
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: TypeBase.h:8905
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
RecordDecl * castAsRecordDecl() const
Definition: Type.h:48
bool isAnyComplexType() const
Definition: TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isAtomicType() const
Definition: TypeBase.h:8762
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:9212
bool isObjectType() const
Determine whether this type is an object type.
Definition: TypeBase.h:2528
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:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isVectorType() const
Definition: TypeBase.h:8719
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
bool isFloatingType() const
Definition: Type.cpp:2308
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:2257
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
bool isUnionType() const
Definition: Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2574
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: TypeBase.h:9100
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2627
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2696
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2659
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
Expr * getSubExpr() const
Definition: Expr.h:2287
Opcode getOpcode() const
Definition: Expr.h:2282
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2328
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4449
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:5445
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
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:3996
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
unsigned getNumElements() const
Definition: TypeBase.h:4206
QualType getElementType() const
Definition: TypeBase.h:4205
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2700
Expr * getCond()
Definition: Stmt.h:2752
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1205
Stmt * getBody()
Definition: Stmt.h:2764
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:58
#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
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.
Definition: Format.cpp:4035
llvm::APFloat APFloat
Definition: Floating.h:27
llvm::APInt APInt
Definition: FixedPoint.h:19
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition: Interp.cpp:1551
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1260
llvm::FixedPointSemantics FixedPointSemantics
Definition: Interp.h:41
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:3464
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.
@ NonNull
Values of this type can never be null.
@ Success
Annotation was successful.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:204
@ AS_public
Definition: Specifiers.h:124
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:45
@ TSCS_unspecified
Definition: Specifiers.h:236
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
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
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:249
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ None
The alignment was not explicit in code.
@ ArrayBound
Array bound in array declarator or new-expression.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
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
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 HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:617
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