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"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind");
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind");
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 // The type of Base is a reference type if the base is a constexpr-unknown
200 // variable. In that case, look through the reference type.
201 Type = getType(Base).getNonReferenceType();
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getZExtSize();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const auto *VT = Type->getAs<VectorType>()) {
224 Type = VT->getElementType();
225 ArraySize = VT->getNumElements();
226 MostDerivedLength = I + 1;
227 IsArray = true;
228 } else if (const FieldDecl *FD = getAsField(Path[I])) {
229 Type = FD->getType();
230 ArraySize = 0;
231 MostDerivedLength = I + 1;
232 IsArray = false;
233 } else {
234 // Path[I] describes a base class.
235 ArraySize = 0;
236 IsArray = false;
237 }
238 }
239 return MostDerivedLength;
240 }
241
242 /// A path from a glvalue to a subobject of that glvalue.
243 struct SubobjectDesignator {
244 /// True if the subobject was named in a manner not supported by C++11. Such
245 /// lvalues can still be folded, but they are not core constant expressions
246 /// and we cannot perform lvalue-to-rvalue conversions on them.
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned Invalid : 1;
249
250 /// Is this a pointer one past the end of an object?
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned IsOnePastTheEnd : 1;
253
254 /// Indicator of whether the first entry is an unsized array.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned FirstEntryIsAnUnsizedArray : 1;
257
258 /// Indicator of whether the most-derived object is an array element.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned MostDerivedIsArrayElement : 1;
261
262 /// The length of the path to the most-derived object of which this is a
263 /// subobject.
264 unsigned MostDerivedPathLength : 28;
265
266 /// The size of the array of which the most-derived object is an element.
267 /// This will always be 0 if the most-derived object is not an array
268 /// element. 0 is not an indicator of whether or not the most-derived object
269 /// is an array, however, because 0-length arrays are allowed.
270 ///
271 /// If the current array is an unsized array, the value of this is
272 /// undefined.
273 uint64_t MostDerivedArraySize;
274 /// The type of the most derived object referred to by this address.
275 QualType MostDerivedType;
276
277 typedef APValue::LValuePathEntry PathEntry;
278
279 /// The entries on the path from the glvalue to the designated subobject.
281
282 SubobjectDesignator() : Invalid(true) {}
283
284 explicit SubobjectDesignator(QualType T)
285 : Invalid(false), IsOnePastTheEnd(false),
286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287 MostDerivedPathLength(0), MostDerivedArraySize(0),
288 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
289
290 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
291 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
292 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
293 MostDerivedPathLength(0), MostDerivedArraySize(0) {
294 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
295 if (!Invalid) {
296 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
297 llvm::append_range(Entries, V.getLValuePath());
298 if (V.getLValueBase()) {
299 bool IsArray = false;
300 bool FirstIsUnsizedArray = false;
301 MostDerivedPathLength = findMostDerivedSubobject(
302 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
303 MostDerivedType, IsArray, FirstIsUnsizedArray);
304 MostDerivedIsArrayElement = IsArray;
305 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
306 }
307 }
308 }
309
310 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
311 unsigned NewLength) {
312 if (Invalid)
313 return;
314
315 assert(Base && "cannot truncate path for null pointer");
316 assert(NewLength <= Entries.size() && "not a truncation");
317
318 if (NewLength == Entries.size())
319 return;
320 Entries.resize(NewLength);
321
322 bool IsArray = false;
323 bool FirstIsUnsizedArray = false;
324 MostDerivedPathLength = findMostDerivedSubobject(
325 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
326 FirstIsUnsizedArray);
327 MostDerivedIsArrayElement = IsArray;
328 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
329 }
330
331 void setInvalid() {
332 Invalid = true;
333 Entries.clear();
334 }
335
336 /// Determine whether the most derived subobject is an array without a
337 /// known bound.
338 bool isMostDerivedAnUnsizedArray() const {
339 assert(!Invalid && "Calling this makes no sense on invalid designators");
340 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
341 }
342
343 /// Determine what the most derived array's size is. Results in an assertion
344 /// failure if the most derived array lacks a size.
345 uint64_t getMostDerivedArraySize() const {
346 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
347 return MostDerivedArraySize;
348 }
349
350 /// Determine whether this is a one-past-the-end pointer.
351 bool isOnePastTheEnd() const {
352 assert(!Invalid);
353 if (IsOnePastTheEnd)
354 return true;
355 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
356 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
357 MostDerivedArraySize)
358 return true;
359 return false;
360 }
361
362 /// Get the range of valid index adjustments in the form
363 /// {maximum value that can be subtracted from this pointer,
364 /// maximum value that can be added to this pointer}
365 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
366 if (Invalid || isMostDerivedAnUnsizedArray())
367 return {0, 0};
368
369 // [expr.add]p4: For the purposes of these operators, a pointer to a
370 // nonarray object behaves the same as a pointer to the first element of
371 // an array of length one with the type of the object as its element type.
372 bool IsArray = MostDerivedPathLength == Entries.size() &&
373 MostDerivedIsArrayElement;
374 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
375 : (uint64_t)IsOnePastTheEnd;
376 uint64_t ArraySize =
377 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
378 return {ArrayIndex, ArraySize - ArrayIndex};
379 }
380
381 /// Check that this refers to a valid subobject.
382 bool isValidSubobject() const {
383 if (Invalid)
384 return false;
385 return !isOnePastTheEnd();
386 }
387 /// Check that this refers to a valid subobject, and if not, produce a
388 /// relevant diagnostic and set the designator as invalid.
389 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
390
391 /// Get the type of the designated object.
392 QualType getType(ASTContext &Ctx) const {
393 assert(!Invalid && "invalid designator has no subobject type");
394 return MostDerivedPathLength == Entries.size()
395 ? MostDerivedType
396 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
397 }
398
399 /// Update this designator to refer to the first element within this array.
400 void addArrayUnchecked(const ConstantArrayType *CAT) {
401 Entries.push_back(PathEntry::ArrayIndex(0));
402
403 // This is a most-derived object.
404 MostDerivedType = CAT->getElementType();
405 MostDerivedIsArrayElement = true;
406 MostDerivedArraySize = CAT->getZExtSize();
407 MostDerivedPathLength = Entries.size();
408 }
409 /// Update this designator to refer to the first element within the array of
410 /// elements of type T. This is an array of unknown size.
411 void addUnsizedArrayUnchecked(QualType ElemTy) {
412 Entries.push_back(PathEntry::ArrayIndex(0));
413
414 MostDerivedType = ElemTy;
415 MostDerivedIsArrayElement = true;
416 // The value in MostDerivedArraySize is undefined in this case. So, set it
417 // to an arbitrary value that's likely to loudly break things if it's
418 // used.
419 MostDerivedArraySize = AssumedSizeForUnsizedArray;
420 MostDerivedPathLength = Entries.size();
421 }
422 /// Update this designator to refer to the given base or member of this
423 /// object.
424 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
425 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
426
427 // If this isn't a base class, it's a new most-derived object.
428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
429 MostDerivedType = FD->getType();
430 MostDerivedIsArrayElement = false;
431 MostDerivedArraySize = 0;
432 MostDerivedPathLength = Entries.size();
433 }
434 }
435 /// Update this designator to refer to the given complex component.
436 void addComplexUnchecked(QualType EltTy, bool Imag) {
437 Entries.push_back(PathEntry::ArrayIndex(Imag));
438
439 // This is technically a most-derived object, though in practice this
440 // is unlikely to matter.
441 MostDerivedType = EltTy;
442 MostDerivedIsArrayElement = true;
443 MostDerivedArraySize = 2;
444 MostDerivedPathLength = Entries.size();
445 }
446
447 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
448 uint64_t Idx) {
449 Entries.push_back(PathEntry::ArrayIndex(Idx));
450 MostDerivedType = EltTy;
451 MostDerivedPathLength = Entries.size();
452 MostDerivedArraySize = 0;
453 MostDerivedIsArrayElement = false;
454 }
455
456 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
457 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
458 const APSInt &N);
459 /// Add N to the address of this subobject.
460 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
461 };
462
463 /// A scope at the end of which an object can need to be destroyed.
464 enum class ScopeKind {
465 Block,
466 FullExpression,
467 Call
468 };
469
470 /// A reference to a particular call and its arguments.
471 struct CallRef {
472 CallRef() : OrigCallee(), CallIndex(0), Version() {}
473 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
474 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
475
476 explicit operator bool() const { return OrigCallee; }
477
478 /// Get the parameter that the caller initialized, corresponding to the
479 /// given parameter in the callee.
480 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
481 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
482 : PVD;
483 }
484
485 /// The callee at the point where the arguments were evaluated. This might
486 /// be different from the actual callee (a different redeclaration, or a
487 /// virtual override), but this function's parameters are the ones that
488 /// appear in the parameter map.
489 const FunctionDecl *OrigCallee;
490 /// The call index of the frame that holds the argument values.
491 unsigned CallIndex;
492 /// The version of the parameters corresponding to this call.
493 unsigned Version;
494 };
495
496 /// A stack frame in the constexpr call stack.
497 class CallStackFrame : public interp::Frame {
498 public:
499 EvalInfo &Info;
500
501 /// Parent - The caller of this stack frame.
502 CallStackFrame *Caller;
503
504 /// Callee - The function which was called.
505 const FunctionDecl *Callee;
506
507 /// This - The binding for the this pointer in this call, if any.
508 const LValue *This;
509
510 /// CallExpr - The syntactical structure of member function calls
511 const Expr *CallExpr;
512
513 /// Information on how to find the arguments to this call. Our arguments
514 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
515 /// key and this value as the version.
516 CallRef Arguments;
517
518 /// Source location information about the default argument or default
519 /// initializer expression we're evaluating, if any.
520 CurrentSourceLocExprScope CurSourceLocExprScope;
521
522 // Note that we intentionally use std::map here so that references to
523 // values are stable.
524 typedef std::pair<const void *, unsigned> MapKeyTy;
525 typedef std::map<MapKeyTy, APValue> MapTy;
526 /// Temporaries - Temporary lvalues materialized within this stack frame.
527 MapTy Temporaries;
528
529 /// CallRange - The source range of the call expression for this call.
530 SourceRange CallRange;
531
532 /// Index - The call index of this call.
533 unsigned Index;
534
535 /// The stack of integers for tracking version numbers for temporaries.
536 SmallVector<unsigned, 2> TempVersionStack = {1};
537 unsigned CurTempVersion = TempVersionStack.back();
538
539 unsigned getTempVersion() const { return TempVersionStack.back(); }
540
541 void pushTempVersion() {
542 TempVersionStack.push_back(++CurTempVersion);
543 }
544
545 void popTempVersion() {
546 TempVersionStack.pop_back();
547 }
548
549 CallRef createCall(const FunctionDecl *Callee) {
550 return {Callee, Index, ++CurTempVersion};
551 }
552
553 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
554 // on the overall stack usage of deeply-recursing constexpr evaluations.
555 // (We should cache this map rather than recomputing it repeatedly.)
556 // But let's try this and see how it goes; we can look into caching the map
557 // as a later change.
558
559 /// LambdaCaptureFields - Mapping from captured variables/this to
560 /// corresponding data members in the closure class.
561 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
562 FieldDecl *LambdaThisCaptureField = nullptr;
563
564 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
565 const FunctionDecl *Callee, const LValue *This,
566 const Expr *CallExpr, CallRef Arguments);
567 ~CallStackFrame();
568
569 // Return the temporary for Key whose version number is Version.
570 APValue *getTemporary(const void *Key, unsigned Version) {
571 MapKeyTy KV(Key, Version);
572 auto LB = Temporaries.lower_bound(KV);
573 if (LB != Temporaries.end() && LB->first == KV)
574 return &LB->second;
575 return nullptr;
576 }
577
578 // Return the current temporary for Key in the map.
579 APValue *getCurrentTemporary(const void *Key) {
580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582 return &std::prev(UB)->second;
583 return nullptr;
584 }
585
586 // Return the version number of the current temporary for Key.
587 unsigned getCurrentTemporaryVersion(const void *Key) const {
588 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
589 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
590 return std::prev(UB)->first.second;
591 return 0;
592 }
593
594 /// Allocate storage for an object of type T in this stack frame.
595 /// Populates LV with a handle to the created object. Key identifies
596 /// the temporary within the stack frame, and must not be reused without
597 /// bumping the temporary version number.
598 template<typename KeyT>
599 APValue &createTemporary(const KeyT *Key, QualType T,
600 ScopeKind Scope, LValue &LV);
601
602 /// Allocate storage for a parameter of a function call made in this frame.
603 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
604
605 void describe(llvm::raw_ostream &OS) const override;
606
607 Frame *getCaller() const override { return Caller; }
608 SourceRange getCallRange() const override { return CallRange; }
609 const FunctionDecl *getCallee() const override { return Callee; }
610
611 bool isStdFunction() const {
612 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
613 if (DC->isStdNamespace())
614 return true;
615 return false;
616 }
617
618 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
619 /// permitted. See MSConstexprDocs for description of permitted contexts.
620 bool CanEvalMSConstexpr = false;
621
622 private:
623 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
624 ScopeKind Scope);
625 };
626
627 /// Temporarily override 'this'.
628 class ThisOverrideRAII {
629 public:
630 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
631 : Frame(Frame), OldThis(Frame.This) {
632 if (Enable)
633 Frame.This = NewThis;
634 }
635 ~ThisOverrideRAII() {
636 Frame.This = OldThis;
637 }
638 private:
639 CallStackFrame &Frame;
640 const LValue *OldThis;
641 };
642
643 // A shorthand time trace scope struct, prints source range, for example
644 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
645 class ExprTimeTraceScope {
646 public:
647 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
648 : TimeScope(Name, [E, &Ctx] {
650 }) {}
651
652 private:
653 llvm::TimeTraceScope TimeScope;
654 };
655
656 /// RAII object used to change the current ability of
657 /// [[msvc::constexpr]] evaulation.
658 struct MSConstexprContextRAII {
659 CallStackFrame &Frame;
660 bool OldValue;
661 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
662 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
663 Frame.CanEvalMSConstexpr = Value;
664 }
665
666 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
667 };
668}
669
670static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
674 QualType T);
675
676namespace {
677 /// A cleanup, and a flag indicating whether it is lifetime-extended.
678 class Cleanup {
679 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 APValue::LValueBase Base;
681 QualType T;
682
683 public:
684 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
685 ScopeKind Scope)
686 : Value(Val, Scope), Base(Base), T(T) {}
687
688 /// Determine whether this cleanup should be performed at the end of the
689 /// given kind of scope.
690 bool isDestroyedAtEndOf(ScopeKind K) const {
691 return (int)Value.getInt() >= (int)K;
692 }
693 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
694 if (RunDestructors) {
695 SourceLocation Loc;
696 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
697 Loc = VD->getLocation();
698 else if (const Expr *E = Base.dyn_cast<const Expr*>())
699 Loc = E->getExprLoc();
700 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
701 }
702 *Value.getPointer() = APValue();
703 return true;
704 }
705
706 bool hasSideEffect() {
707 return T.isDestructedType();
708 }
709 };
710
711 /// A reference to an object whose construction we are currently evaluating.
712 struct ObjectUnderConstruction {
713 APValue::LValueBase Base;
714 ArrayRef<APValue::LValuePathEntry> Path;
715 friend bool operator==(const ObjectUnderConstruction &LHS,
716 const ObjectUnderConstruction &RHS) {
717 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
718 }
719 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
720 return llvm::hash_combine(Obj.Base, Obj.Path);
721 }
722 };
723 enum class ConstructionPhase {
724 None,
725 Bases,
726 AfterBases,
727 AfterFields,
728 Destroying,
729 DestroyingBases
730 };
731}
732
733namespace llvm {
734template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748};
749}
750
751namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo : public interp::State {
798 public:
799 ASTContext &Ctx;
800
801 /// EvalStatus - Contains information about the evaluation.
802 Expr::EvalStatus &EvalStatus;
803
804 /// CurrentCall - The top of the constexpr call stack.
805 CallStackFrame *CurrentCall;
806
807 /// CallStackDepth - The number of calls in the call stack right now.
808 unsigned CallStackDepth;
809
810 /// NextCallIndex - The next call index to assign.
811 unsigned NextCallIndex;
812
813 /// StepsLeft - The remaining number of evaluation steps we're permitted
814 /// to perform. This is essentially a limit for the number of statements
815 /// we will evaluate.
816 unsigned StepsLeft;
817
818 /// Enable the experimental new constant interpreter. If an expression is
819 /// not supported by the interpreter, an error is triggered.
820 bool EnableNewConstInterp;
821
822 /// BottomFrame - The frame in which evaluation started. This must be
823 /// initialized after CurrentCall and CallStackDepth.
824 CallStackFrame BottomFrame;
825
826 /// A stack of values whose lifetimes end at the end of some surrounding
827 /// evaluation frame.
828 llvm::SmallVector<Cleanup, 16> CleanupStack;
829
830 /// EvaluatingDecl - This is the declaration whose initializer is being
831 /// evaluated, if any.
832 APValue::LValueBase EvaluatingDecl;
833
834 enum class EvaluatingDeclKind {
835 None,
836 /// We're evaluating the construction of EvaluatingDecl.
837 Ctor,
838 /// We're evaluating the destruction of EvaluatingDecl.
839 Dtor,
840 };
841 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
842
843 /// EvaluatingDeclValue - This is the value being constructed for the
844 /// declaration whose initializer is being evaluated, if any.
845 APValue *EvaluatingDeclValue;
846
847 /// Stack of loops and 'switch' statements which we're currently
848 /// breaking/continuing; null entries are used to mark unlabeled
849 /// break/continue.
850 SmallVector<const Stmt *> BreakContinueStack;
851
852 /// Set of objects that are currently being constructed.
853 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
854 ObjectsUnderConstruction;
855
856 /// Current heap allocations, along with the location where each was
857 /// allocated. We use std::map here because we need stable addresses
858 /// for the stored APValues.
859 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
860
861 /// The number of heap allocations performed so far in this evaluation.
862 unsigned NumHeapAllocs = 0;
863
864 struct EvaluatingConstructorRAII {
865 EvalInfo &EI;
866 ObjectUnderConstruction Object;
867 bool DidInsert;
868 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
869 bool HasBases)
870 : EI(EI), Object(Object) {
871 DidInsert =
872 EI.ObjectsUnderConstruction
873 .insert({Object, HasBases ? ConstructionPhase::Bases
874 : ConstructionPhase::AfterBases})
875 .second;
876 }
877 void finishedConstructingBases() {
878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
879 }
880 void finishedConstructingFields() {
881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
882 }
883 ~EvaluatingConstructorRAII() {
884 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
885 }
886 };
887
888 struct EvaluatingDestructorRAII {
889 EvalInfo &EI;
890 ObjectUnderConstruction Object;
891 bool DidInsert;
892 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
893 : EI(EI), Object(Object) {
894 DidInsert = EI.ObjectsUnderConstruction
895 .insert({Object, ConstructionPhase::Destroying})
896 .second;
897 }
898 void startedDestroyingBases() {
899 EI.ObjectsUnderConstruction[Object] =
900 ConstructionPhase::DestroyingBases;
901 }
902 ~EvaluatingDestructorRAII() {
903 if (DidInsert)
904 EI.ObjectsUnderConstruction.erase(Object);
905 }
906 };
907
908 ConstructionPhase
909 isEvaluatingCtorDtor(APValue::LValueBase Base,
910 ArrayRef<APValue::LValuePathEntry> Path) {
911 return ObjectsUnderConstruction.lookup({Base, Path});
912 }
913
914 /// If we're currently speculatively evaluating, the outermost call stack
915 /// depth at which we can mutate state, otherwise 0.
916 unsigned SpeculativeEvaluationDepth = 0;
917
918 /// The current array initialization index, if we're performing array
919 /// initialization.
920 uint64_t ArrayInitIndex = -1;
921
922 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
923 /// notes attached to it will also be stored, otherwise they will not be.
924 bool HasActiveDiagnostic;
925
926 /// Have we emitted a diagnostic explaining why we couldn't constant
927 /// fold (not just why it's not strictly a constant expression)?
928 bool HasFoldFailureDiagnostic;
929
930 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
931 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
932 CallStackDepth(0), NextCallIndex(1),
933 StepsLeft(C.getLangOpts().ConstexprStepLimit),
934 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
935 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
936 /*This=*/nullptr,
937 /*CallExpr=*/nullptr, CallRef()),
938 EvaluatingDecl((const ValueDecl *)nullptr),
939 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
940 HasFoldFailureDiagnostic(false) {
941 EvalMode = Mode;
942 }
943
944 ~EvalInfo() {
945 discardCleanups();
946 }
947
948 ASTContext &getASTContext() const override { return Ctx; }
949 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
950
951 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
952 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
953 EvaluatingDecl = Base;
954 IsEvaluatingDecl = EDK;
955 EvaluatingDeclValue = &Value;
956 }
957
958 bool CheckCallLimit(SourceLocation Loc) {
959 // Don't perform any constexpr calls (other than the call we're checking)
960 // when checking a potential constant expression.
961 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
962 return false;
963 if (NextCallIndex == 0) {
964 // NextCallIndex has wrapped around.
965 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
966 return false;
967 }
968 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
969 return true;
970 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
971 << getLangOpts().ConstexprCallDepth;
972 return false;
973 }
974
975 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
976 uint64_t ElemCount, bool Diag) {
977 // FIXME: GH63562
978 // APValue stores array extents as unsigned,
979 // so anything that is greater that unsigned would overflow when
980 // constructing the array, we catch this here.
981 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
982 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
983 if (Diag)
984 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
985 return false;
986 }
987
988 // FIXME: GH63562
989 // Arrays allocate an APValue per element.
990 // We use the number of constexpr steps as a proxy for the maximum size
991 // of arrays to avoid exhausting the system resources, as initialization
992 // of each element is likely to take some number of steps anyway.
993 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
994 if (Limit != 0 && ElemCount > Limit) {
995 if (Diag)
996 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
997 << ElemCount << Limit;
998 return false;
999 }
1000 return true;
1001 }
1002
1003 std::pair<CallStackFrame *, unsigned>
1004 getCallFrameAndDepth(unsigned CallIndex) {
1005 assert(CallIndex && "no call index in getCallFrameAndDepth");
1006 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1007 // be null in this loop.
1008 unsigned Depth = CallStackDepth;
1009 CallStackFrame *Frame = CurrentCall;
1010 while (Frame->Index > CallIndex) {
1011 Frame = Frame->Caller;
1012 --Depth;
1013 }
1014 if (Frame->Index == CallIndex)
1015 return {Frame, Depth};
1016 return {nullptr, 0};
1017 }
1018
1019 bool nextStep(const Stmt *S) {
1020 if (Ctx.getLangOpts().ConstexprStepLimit == 0)
1021 return true;
1022
1023 if (!StepsLeft) {
1024 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1025 return false;
1026 }
1027 --StepsLeft;
1028 return true;
1029 }
1030
1031 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1032
1033 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1034 std::optional<DynAlloc *> Result;
1035 auto It = HeapAllocs.find(DA);
1036 if (It != HeapAllocs.end())
1037 Result = &It->second;
1038 return Result;
1039 }
1040
1041 /// Get the allocated storage for the given parameter of the given call.
1042 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1043 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1044 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1045 : nullptr;
1046 }
1047
1048 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1049 struct StdAllocatorCaller {
1050 unsigned FrameIndex;
1051 QualType ElemType;
1052 const Expr *Call;
1053 explicit operator bool() const { return FrameIndex != 0; };
1054 };
1055
1056 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1057 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1058 Call = Call->Caller) {
1059 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1060 if (!MD)
1061 continue;
1062 const IdentifierInfo *FnII = MD->getIdentifier();
1063 if (!FnII || !FnII->isStr(FnName))
1064 continue;
1065
1066 const auto *CTSD =
1067 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1068 if (!CTSD)
1069 continue;
1070
1071 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1072 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1073 if (CTSD->isInStdNamespace() && ClassII &&
1074 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1075 TAL[0].getKind() == TemplateArgument::Type)
1076 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1077 }
1078
1079 return {};
1080 }
1081
1082 void performLifetimeExtension() {
1083 // Disable the cleanups for lifetime-extended temporaries.
1084 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1085 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1086 });
1087 }
1088
1089 /// Throw away any remaining cleanups at the end of evaluation. If any
1090 /// cleanups would have had a side-effect, note that as an unmodeled
1091 /// side-effect and return false. Otherwise, return true.
1092 bool discardCleanups() {
1093 for (Cleanup &C : CleanupStack) {
1094 if (C.hasSideEffect() && !noteSideEffect()) {
1095 CleanupStack.clear();
1096 return false;
1097 }
1098 }
1099 CleanupStack.clear();
1100 return true;
1101 }
1102
1103 private:
1104 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1105 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1106
1107 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1108 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1109
1110 void setFoldFailureDiagnostic(bool Flag) override {
1111 HasFoldFailureDiagnostic = Flag;
1112 }
1113
1114 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1115
1116 // If we have a prior diagnostic, it will be noting that the expression
1117 // isn't a constant expression. This diagnostic is more important,
1118 // unless we require this evaluation to produce a constant expression.
1119 //
1120 // FIXME: We might want to show both diagnostics to the user in
1121 // EvaluationMode::ConstantFold mode.
1122 bool hasPriorDiagnostic() override {
1123 if (!EvalStatus.Diag->empty()) {
1124 switch (EvalMode) {
1125 case EvaluationMode::ConstantFold:
1126 case EvaluationMode::IgnoreSideEffects:
1127 if (!HasFoldFailureDiagnostic)
1128 break;
1129 // We've already failed to fold something. Keep that diagnostic.
1130 [[fallthrough]];
1131 case EvaluationMode::ConstantExpression:
1132 case EvaluationMode::ConstantExpressionUnevaluated:
1133 setActiveDiagnostic(false);
1134 return true;
1135 }
1136 }
1137 return false;
1138 }
1139
1140 unsigned getCallStackDepth() override { return CallStackDepth; }
1141
1142 public:
1143 /// Should we continue evaluation after encountering a side-effect that we
1144 /// couldn't model?
1145 bool keepEvaluatingAfterSideEffect() const override {
1146 switch (EvalMode) {
1147 case EvaluationMode::IgnoreSideEffects:
1148 return true;
1149
1150 case EvaluationMode::ConstantExpression:
1151 case EvaluationMode::ConstantExpressionUnevaluated:
1152 case EvaluationMode::ConstantFold:
1153 // By default, assume any side effect might be valid in some other
1154 // evaluation of this expression from a different context.
1155 return checkingPotentialConstantExpression() ||
1156 checkingForUndefinedBehavior();
1157 }
1158 llvm_unreachable("Missed EvalMode case");
1159 }
1160
1161 /// Note that we have had a side-effect, and determine whether we should
1162 /// keep evaluating.
1163 bool noteSideEffect() override {
1164 EvalStatus.HasSideEffects = true;
1165 return keepEvaluatingAfterSideEffect();
1166 }
1167
1168 /// Should we continue evaluation after encountering undefined behavior?
1169 bool keepEvaluatingAfterUndefinedBehavior() {
1170 switch (EvalMode) {
1171 case EvaluationMode::IgnoreSideEffects:
1172 case EvaluationMode::ConstantFold:
1173 return true;
1174
1175 case EvaluationMode::ConstantExpression:
1176 case EvaluationMode::ConstantExpressionUnevaluated:
1177 return checkingForUndefinedBehavior();
1178 }
1179 llvm_unreachable("Missed EvalMode case");
1180 }
1181
1182 /// Note that we hit something that was technically undefined behavior, but
1183 /// that we can evaluate past it (such as signed overflow or floating-point
1184 /// division by zero.)
1185 bool noteUndefinedBehavior() override {
1186 EvalStatus.HasUndefinedBehavior = true;
1187 return keepEvaluatingAfterUndefinedBehavior();
1188 }
1189
1190 /// Should we continue evaluation as much as possible after encountering a
1191 /// construct which can't be reduced to a value?
1192 bool keepEvaluatingAfterFailure() const override {
1193 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1194 if (Limit != 0 && !StepsLeft)
1195 return false;
1196
1197 switch (EvalMode) {
1198 case EvaluationMode::ConstantExpression:
1199 case EvaluationMode::ConstantExpressionUnevaluated:
1200 case EvaluationMode::ConstantFold:
1201 case EvaluationMode::IgnoreSideEffects:
1202 return checkingPotentialConstantExpression() ||
1203 checkingForUndefinedBehavior();
1204 }
1205 llvm_unreachable("Missed EvalMode case");
1206 }
1207
1208 /// Notes that we failed to evaluate an expression that other expressions
1209 /// directly depend on, and determine if we should keep evaluating. This
1210 /// should only be called if we actually intend to keep evaluating.
1211 ///
1212 /// Call noteSideEffect() instead if we may be able to ignore the value that
1213 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1214 ///
1215 /// (Foo(), 1) // use noteSideEffect
1216 /// (Foo() || true) // use noteSideEffect
1217 /// Foo() + 1 // use noteFailure
1218 [[nodiscard]] bool noteFailure() {
1219 // Failure when evaluating some expression often means there is some
1220 // subexpression whose evaluation was skipped. Therefore, (because we
1221 // don't track whether we skipped an expression when unwinding after an
1222 // evaluation failure) every evaluation failure that bubbles up from a
1223 // subexpression implies that a side-effect has potentially happened. We
1224 // skip setting the HasSideEffects flag to true until we decide to
1225 // continue evaluating after that point, which happens here.
1226 bool KeepGoing = keepEvaluatingAfterFailure();
1227 EvalStatus.HasSideEffects |= KeepGoing;
1228 return KeepGoing;
1229 }
1230
1231 class ArrayInitLoopIndex {
1232 EvalInfo &Info;
1233 uint64_t OuterIndex;
1234
1235 public:
1236 ArrayInitLoopIndex(EvalInfo &Info)
1237 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1238 Info.ArrayInitIndex = 0;
1239 }
1240 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1241
1242 operator uint64_t&() { return Info.ArrayInitIndex; }
1243 };
1244 };
1245
1246 /// Object used to treat all foldable expressions as constant expressions.
1247 struct FoldConstant {
1248 EvalInfo &Info;
1249 bool Enabled;
1250 bool HadNoPriorDiags;
1251 EvaluationMode OldMode;
1252
1253 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1254 : Info(Info),
1255 Enabled(Enabled),
1256 HadNoPriorDiags(Info.EvalStatus.Diag &&
1257 Info.EvalStatus.Diag->empty() &&
1258 !Info.EvalStatus.HasSideEffects),
1259 OldMode(Info.EvalMode) {
1260 if (Enabled)
1261 Info.EvalMode = EvaluationMode::ConstantFold;
1262 }
1263 void keepDiagnostics() { Enabled = false; }
1264 ~FoldConstant() {
1265 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1266 !Info.EvalStatus.HasSideEffects)
1267 Info.EvalStatus.Diag->clear();
1268 Info.EvalMode = OldMode;
1269 }
1270 };
1271
1272 /// RAII object used to set the current evaluation mode to ignore
1273 /// side-effects.
1274 struct IgnoreSideEffectsRAII {
1275 EvalInfo &Info;
1276 EvaluationMode OldMode;
1277 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1278 : Info(Info), OldMode(Info.EvalMode) {
1279 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1280 }
1281
1282 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1283 };
1284
1285 /// RAII object used to optionally suppress diagnostics and side-effects from
1286 /// a speculative evaluation.
1287 class SpeculativeEvaluationRAII {
1288 EvalInfo *Info = nullptr;
1289 Expr::EvalStatus OldStatus;
1290 unsigned OldSpeculativeEvaluationDepth = 0;
1291
1292 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1293 Info = Other.Info;
1294 OldStatus = Other.OldStatus;
1295 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1296 Other.Info = nullptr;
1297 }
1298
1299 void maybeRestoreState() {
1300 if (!Info)
1301 return;
1302
1303 Info->EvalStatus = OldStatus;
1304 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1305 }
1306
1307 public:
1308 SpeculativeEvaluationRAII() = default;
1309
1310 SpeculativeEvaluationRAII(
1311 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1312 : Info(&Info), OldStatus(Info.EvalStatus),
1313 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1314 Info.EvalStatus.Diag = NewDiag;
1315 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1316 }
1317
1318 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1319 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1320 moveFromAndCancel(std::move(Other));
1321 }
1322
1323 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1324 maybeRestoreState();
1325 moveFromAndCancel(std::move(Other));
1326 return *this;
1327 }
1328
1329 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1330 };
1331
1332 /// RAII object wrapping a full-expression or block scope, and handling
1333 /// the ending of the lifetime of temporaries created within it.
1334 template<ScopeKind Kind>
1335 class ScopeRAII {
1336 EvalInfo &Info;
1337 unsigned OldStackSize;
1338 public:
1339 ScopeRAII(EvalInfo &Info)
1340 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1341 // Push a new temporary version. This is needed to distinguish between
1342 // temporaries created in different iterations of a loop.
1343 Info.CurrentCall->pushTempVersion();
1344 }
1345 bool destroy(bool RunDestructors = true) {
1346 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1347 OldStackSize = std::numeric_limits<unsigned>::max();
1348 return OK;
1349 }
1350 ~ScopeRAII() {
1351 if (OldStackSize != std::numeric_limits<unsigned>::max())
1352 destroy(false);
1353 // Body moved to a static method to encourage the compiler to inline away
1354 // instances of this class.
1355 Info.CurrentCall->popTempVersion();
1356 }
1357 private:
1358 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1359 unsigned OldStackSize) {
1360 assert(OldStackSize <= Info.CleanupStack.size() &&
1361 "running cleanups out of order?");
1362
1363 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1364 // for a full-expression scope.
1365 bool Success = true;
1366 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1367 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1368 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1369 Success = false;
1370 break;
1371 }
1372 }
1373 }
1374
1375 // Compact any retained cleanups.
1376 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1377 if (Kind != ScopeKind::Block)
1378 NewEnd =
1379 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1380 return C.isDestroyedAtEndOf(Kind);
1381 });
1382 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1383 return Success;
1384 }
1385 };
1386 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1387 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1388 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1389}
1390
1391bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1392 CheckSubobjectKind CSK) {
1393 if (Invalid)
1394 return false;
1395 if (isOnePastTheEnd()) {
1396 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1397 << CSK;
1398 setInvalid();
1399 return false;
1400 }
1401 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1402 // must actually be at least one array element; even a VLA cannot have a
1403 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1404 return true;
1405}
1406
1407void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1408 const Expr *E) {
1409 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1410 // Do not set the designator as invalid: we can represent this situation,
1411 // and correct handling of __builtin_object_size requires us to do so.
1412}
1413
1414void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1415 const Expr *E,
1416 const APSInt &N) {
1417 // If we're complaining, we must be able to statically determine the size of
1418 // the most derived array.
1419 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1420 Info.CCEDiag(E, diag::note_constexpr_array_index)
1421 << N << /*array*/ 0
1422 << static_cast<unsigned>(getMostDerivedArraySize());
1423 else
1424 Info.CCEDiag(E, diag::note_constexpr_array_index)
1425 << N << /*non-array*/ 1;
1426 setInvalid();
1427}
1428
1429CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1430 const FunctionDecl *Callee, const LValue *This,
1431 const Expr *CallExpr, CallRef Call)
1432 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1433 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1434 Index(Info.NextCallIndex++) {
1435 Info.CurrentCall = this;
1436 ++Info.CallStackDepth;
1437}
1438
1439CallStackFrame::~CallStackFrame() {
1440 assert(Info.CurrentCall == this && "calls retired out of order");
1441 --Info.CallStackDepth;
1442 Info.CurrentCall = Caller;
1443}
1444
1445static bool isRead(AccessKinds AK) {
1446 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1447 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1448}
1449
1451 switch (AK) {
1452 case AK_Read:
1454 case AK_MemberCall:
1455 case AK_DynamicCast:
1456 case AK_TypeId:
1458 case AK_Dereference:
1459 return false;
1460 case AK_Assign:
1461 case AK_Increment:
1462 case AK_Decrement:
1463 case AK_Construct:
1464 case AK_Destroy:
1465 return true;
1466 }
1467 llvm_unreachable("unknown access kind");
1468}
1469
1470static bool isAnyAccess(AccessKinds AK) {
1471 return isRead(AK) || isModification(AK);
1472}
1473
1474/// Is this an access per the C++ definition?
1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1477 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1478}
1479
1480/// Is this kind of access valid on an indeterminate object value?
1482 switch (AK) {
1483 case AK_Read:
1484 case AK_Increment:
1485 case AK_Decrement:
1486 case AK_Dereference:
1487 // These need the object's value.
1488 return false;
1489
1492 case AK_Assign:
1493 case AK_Construct:
1494 case AK_Destroy:
1495 // Construction and destruction don't need the value.
1496 return true;
1497
1498 case AK_MemberCall:
1499 case AK_DynamicCast:
1500 case AK_TypeId:
1501 // These aren't really meaningful on scalars.
1502 return true;
1503 }
1504 llvm_unreachable("unknown access kind");
1505}
1506
1507namespace {
1508 struct ComplexValue {
1509 private:
1510 bool IsInt;
1511
1512 public:
1513 APSInt IntReal, IntImag;
1514 APFloat FloatReal, FloatImag;
1515
1516 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517
1518 void makeComplexFloat() { IsInt = false; }
1519 bool isComplexFloat() const { return !IsInt; }
1520 APFloat &getComplexFloatReal() { return FloatReal; }
1521 APFloat &getComplexFloatImag() { return FloatImag; }
1522
1523 void makeComplexInt() { IsInt = true; }
1524 bool isComplexInt() const { return IsInt; }
1525 APSInt &getComplexIntReal() { return IntReal; }
1526 APSInt &getComplexIntImag() { return IntImag; }
1527
1528 void moveInto(APValue &v) const {
1529 if (isComplexFloat())
1530 v = APValue(FloatReal, FloatImag);
1531 else
1532 v = APValue(IntReal, IntImag);
1533 }
1534 void setFrom(const APValue &v) {
1535 assert(v.isComplexFloat() || v.isComplexInt());
1536 if (v.isComplexFloat()) {
1537 makeComplexFloat();
1538 FloatReal = v.getComplexFloatReal();
1539 FloatImag = v.getComplexFloatImag();
1540 } else {
1541 makeComplexInt();
1542 IntReal = v.getComplexIntReal();
1543 IntImag = v.getComplexIntImag();
1544 }
1545 }
1546 };
1547
1548 struct LValue {
1549 APValue::LValueBase Base;
1550 CharUnits Offset;
1551 SubobjectDesignator Designator;
1552 bool IsNullPtr : 1;
1553 bool InvalidBase : 1;
1554 // P2280R4 track if we have an unknown reference or pointer.
1555 bool AllowConstexprUnknown = false;
1556
1557 const APValue::LValueBase getLValueBase() const { return Base; }
1558 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1559 CharUnits &getLValueOffset() { return Offset; }
1560 const CharUnits &getLValueOffset() const { return Offset; }
1561 SubobjectDesignator &getLValueDesignator() { return Designator; }
1562 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1563 bool isNullPointer() const { return IsNullPtr;}
1564
1565 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1566 unsigned getLValueVersion() const { return Base.getVersion(); }
1567
1568 void moveInto(APValue &V) const {
1569 if (Designator.Invalid)
1570 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1571 else {
1572 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1573 V = APValue(Base, Offset, Designator.Entries,
1574 Designator.IsOnePastTheEnd, IsNullPtr);
1575 }
1576 if (AllowConstexprUnknown)
1577 V.setConstexprUnknown();
1578 }
1579 void setFrom(const ASTContext &Ctx, const APValue &V) {
1580 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1581 Base = V.getLValueBase();
1582 Offset = V.getLValueOffset();
1583 InvalidBase = false;
1584 Designator = SubobjectDesignator(Ctx, V);
1585 IsNullPtr = V.isNullPointer();
1586 AllowConstexprUnknown = V.allowConstexprUnknown();
1587 }
1588
1589 void set(APValue::LValueBase B, bool BInvalid = false) {
1590#ifndef NDEBUG
1591 // We only allow a few types of invalid bases. Enforce that here.
1592 if (BInvalid) {
1593 const auto *E = B.get<const Expr *>();
1594 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1595 "Unexpected type of invalid base");
1596 }
1597#endif
1598
1599 Base = B;
1600 Offset = CharUnits::fromQuantity(0);
1601 InvalidBase = BInvalid;
1602 Designator = SubobjectDesignator(getType(B));
1603 IsNullPtr = false;
1604 AllowConstexprUnknown = false;
1605 }
1606
1607 void setNull(ASTContext &Ctx, QualType PointerTy) {
1608 Base = (const ValueDecl *)nullptr;
1609 Offset =
1611 InvalidBase = false;
1612 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1613 IsNullPtr = true;
1614 AllowConstexprUnknown = false;
1615 }
1616
1617 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1618 set(B, true);
1619 }
1620
1621 std::string toString(ASTContext &Ctx, QualType T) const {
1622 APValue Printable;
1623 moveInto(Printable);
1624 return Printable.getAsString(Ctx, T);
1625 }
1626
1627 private:
1628 // Check that this LValue is not based on a null pointer. If it is, produce
1629 // a diagnostic and mark the designator as invalid.
1630 template <typename GenDiagType>
1631 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1632 if (Designator.Invalid)
1633 return false;
1634 if (IsNullPtr) {
1635 GenDiag();
1636 Designator.setInvalid();
1637 return false;
1638 }
1639 return true;
1640 }
1641
1642 public:
1643 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1644 CheckSubobjectKind CSK) {
1645 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1646 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1647 });
1648 }
1649
1650 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1651 AccessKinds AK) {
1652 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1653 if (AK == AccessKinds::AK_Dereference)
1654 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1655 else
1656 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1657 });
1658 }
1659
1660 // Check this LValue refers to an object. If not, set the designator to be
1661 // invalid and emit a diagnostic.
1662 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1663 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1664 Designator.checkSubobject(Info, E, CSK);
1665 }
1666
1667 void addDecl(EvalInfo &Info, const Expr *E,
1668 const Decl *D, bool Virtual = false) {
1669 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1670 Designator.addDeclUnchecked(D, Virtual);
1671 }
1672 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1673 if (!Designator.Entries.empty()) {
1674 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1675 Designator.setInvalid();
1676 return;
1677 }
1678 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1679 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1680 getType(Base).getNonReferenceType()->isArrayType());
1681 Designator.FirstEntryIsAnUnsizedArray = true;
1682 Designator.addUnsizedArrayUnchecked(ElemTy);
1683 }
1684 }
1685 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1686 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1687 Designator.addArrayUnchecked(CAT);
1688 }
1689 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1690 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1691 Designator.addComplexUnchecked(EltTy, Imag);
1692 }
1693 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1694 uint64_t Size, uint64_t Idx) {
1695 if (checkSubobject(Info, E, CSK_VectorElement))
1696 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1697 }
1698 void clearIsNullPointer() {
1699 IsNullPtr = false;
1700 }
1701 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1702 const APSInt &Index, CharUnits ElementSize) {
1703 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1704 // but we're not required to diagnose it and it's valid in C++.)
1705 if (!Index)
1706 return;
1707
1708 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1709 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1710 // offsets.
1711 uint64_t Offset64 = Offset.getQuantity();
1712 uint64_t ElemSize64 = ElementSize.getQuantity();
1713 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1714 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1715
1716 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1717 Designator.adjustIndex(Info, E, Index, *this);
1718 clearIsNullPointer();
1719 }
1720 void adjustOffset(CharUnits N) {
1721 Offset += N;
1722 if (N.getQuantity())
1723 clearIsNullPointer();
1724 }
1725 };
1726
1727 struct MemberPtr {
1728 MemberPtr() {}
1729 explicit MemberPtr(const ValueDecl *Decl)
1730 : DeclAndIsDerivedMember(Decl, false) {}
1731
1732 /// The member or (direct or indirect) field referred to by this member
1733 /// pointer, or 0 if this is a null member pointer.
1734 const ValueDecl *getDecl() const {
1735 return DeclAndIsDerivedMember.getPointer();
1736 }
1737 /// Is this actually a member of some type derived from the relevant class?
1738 bool isDerivedMember() const {
1739 return DeclAndIsDerivedMember.getInt();
1740 }
1741 /// Get the class which the declaration actually lives in.
1742 const CXXRecordDecl *getContainingRecord() const {
1743 return cast<CXXRecordDecl>(
1744 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1745 }
1746
1747 void moveInto(APValue &V) const {
1748 V = APValue(getDecl(), isDerivedMember(), Path);
1749 }
1750 void setFrom(const APValue &V) {
1751 assert(V.isMemberPointer());
1752 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1753 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1754 Path.clear();
1755 llvm::append_range(Path, V.getMemberPointerPath());
1756 }
1757
1758 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1759 /// whether the member is a member of some class derived from the class type
1760 /// of the member pointer.
1761 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1762 /// Path - The path of base/derived classes from the member declaration's
1763 /// class (exclusive) to the class type of the member pointer (inclusive).
1764 SmallVector<const CXXRecordDecl*, 4> Path;
1765
1766 /// Perform a cast towards the class of the Decl (either up or down the
1767 /// hierarchy).
1768 bool castBack(const CXXRecordDecl *Class) {
1769 assert(!Path.empty());
1770 const CXXRecordDecl *Expected;
1771 if (Path.size() >= 2)
1772 Expected = Path[Path.size() - 2];
1773 else
1774 Expected = getContainingRecord();
1775 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1776 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1777 // if B does not contain the original member and is not a base or
1778 // derived class of the class containing the original member, the result
1779 // of the cast is undefined.
1780 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1781 // (D::*). We consider that to be a language defect.
1782 return false;
1783 }
1784 Path.pop_back();
1785 return true;
1786 }
1787 /// Perform a base-to-derived member pointer cast.
1788 bool castToDerived(const CXXRecordDecl *Derived) {
1789 if (!getDecl())
1790 return true;
1791 if (!isDerivedMember()) {
1792 Path.push_back(Derived);
1793 return true;
1794 }
1795 if (!castBack(Derived))
1796 return false;
1797 if (Path.empty())
1798 DeclAndIsDerivedMember.setInt(false);
1799 return true;
1800 }
1801 /// Perform a derived-to-base member pointer cast.
1802 bool castToBase(const CXXRecordDecl *Base) {
1803 if (!getDecl())
1804 return true;
1805 if (Path.empty())
1806 DeclAndIsDerivedMember.setInt(true);
1807 if (isDerivedMember()) {
1808 Path.push_back(Base);
1809 return true;
1810 }
1811 return castBack(Base);
1812 }
1813 };
1814
1815 /// Compare two member pointers, which are assumed to be of the same type.
1816 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1817 if (!LHS.getDecl() || !RHS.getDecl())
1818 return !LHS.getDecl() && !RHS.getDecl();
1819 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1820 return false;
1821 return LHS.Path == RHS.Path;
1822 }
1823}
1824
1825void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1826 const LValue &LV) {
1827 if (Invalid || !N)
1828 return;
1829 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1830 if (isMostDerivedAnUnsizedArray()) {
1831 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1832 // Can't verify -- trust that the user is doing the right thing (or if
1833 // not, trust that the caller will catch the bad behavior).
1834 // FIXME: Should we reject if this overflows, at least?
1835 Entries.back() =
1836 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1837 return;
1838 }
1839
1840 // [expr.add]p4: For the purposes of these operators, a pointer to a
1841 // nonarray object behaves the same as a pointer to the first element of
1842 // an array of length one with the type of the object as its element type.
1843 bool IsArray =
1844 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1845 uint64_t ArrayIndex =
1846 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1847 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1848
1849 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1850 if (!Info.checkingPotentialConstantExpression() ||
1851 !LV.AllowConstexprUnknown) {
1852 // Calculate the actual index in a wide enough type, so we can include
1853 // it in the note.
1854 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1855 (llvm::APInt &)N += ArrayIndex;
1856 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1857 diagnosePointerArithmetic(Info, E, N);
1858 }
1859 setInvalid();
1860 return;
1861 }
1862
1863 ArrayIndex += TruncatedN;
1864 assert(ArrayIndex <= ArraySize &&
1865 "bounds check succeeded for out-of-bounds index");
1866
1867 if (IsArray)
1868 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1869 else
1870 IsOnePastTheEnd = (ArrayIndex != 0);
1871}
1872
1873static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1874static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1875 const LValue &This, const Expr *E,
1876 bool AllowNonLiteralTypes = false);
1877static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1878 bool InvalidBaseOK = false);
1879static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1880 bool InvalidBaseOK = false);
1881static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1882 EvalInfo &Info);
1883static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1884static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1885static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1886 EvalInfo &Info);
1887static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1888static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1889static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1890 EvalInfo &Info);
1891static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1892static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1893 EvalInfo &Info,
1894 std::string *StringResult = nullptr);
1895
1896/// Evaluate an integer or fixed point expression into an APResult.
1897static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1898 EvalInfo &Info);
1899
1900/// Evaluate only a fixed point expression into an APResult.
1901static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1902 EvalInfo &Info);
1903
1904//===----------------------------------------------------------------------===//
1905// Misc utilities
1906//===----------------------------------------------------------------------===//
1907
1908/// Negate an APSInt in place, converting it to a signed form if necessary, and
1909/// preserving its value (by extending by up to one bit as needed).
1910static void negateAsSigned(APSInt &Int) {
1911 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1912 Int = Int.extend(Int.getBitWidth() + 1);
1913 Int.setIsSigned(true);
1914 }
1915 Int = -Int;
1916}
1917
1918template<typename KeyT>
1919APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1920 ScopeKind Scope, LValue &LV) {
1921 unsigned Version = getTempVersion();
1922 APValue::LValueBase Base(Key, Index, Version);
1923 LV.set(Base);
1924 return createLocal(Base, Key, T, Scope);
1925}
1926
1927/// Allocate storage for a parameter of a function call made in this frame.
1928APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1929 LValue &LV) {
1930 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1931 APValue::LValueBase Base(PVD, Index, Args.Version);
1932 LV.set(Base);
1933 // We always destroy parameters at the end of the call, even if we'd allow
1934 // them to live to the end of the full-expression at runtime, in order to
1935 // give portable results and match other compilers.
1936 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1937}
1938
1939APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1940 QualType T, ScopeKind Scope) {
1941 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1942 unsigned Version = Base.getVersion();
1943 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1944 assert(Result.isAbsent() && "local created multiple times");
1945
1946 // If we're creating a local immediately in the operand of a speculative
1947 // evaluation, don't register a cleanup to be run outside the speculative
1948 // evaluation context, since we won't actually be able to initialize this
1949 // object.
1950 if (Index <= Info.SpeculativeEvaluationDepth) {
1951 if (T.isDestructedType())
1952 Info.noteSideEffect();
1953 } else {
1954 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1955 }
1956 return Result;
1957}
1958
1959APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1960 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1961 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1962 return nullptr;
1963 }
1964
1965 DynamicAllocLValue DA(NumHeapAllocs++);
1967 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1968 std::forward_as_tuple(DA), std::tuple<>());
1969 assert(Result.second && "reused a heap alloc index?");
1970 Result.first->second.AllocExpr = E;
1971 return &Result.first->second.Value;
1972}
1973
1974/// Produce a string describing the given constexpr call.
1975void CallStackFrame::describe(raw_ostream &Out) const {
1976 unsigned ArgIndex = 0;
1977 bool IsMemberCall =
1978 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1979 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1980
1981 if (!IsMemberCall)
1982 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1983 /*Qualified=*/false);
1984
1985 if (This && IsMemberCall) {
1986 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1987 const Expr *Object = MCE->getImplicitObjectArgument();
1988 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1989 /*Indentation=*/0);
1990 if (Object->getType()->isPointerType())
1991 Out << "->";
1992 else
1993 Out << ".";
1994 } else if (const auto *OCE =
1995 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1996 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1997 Info.Ctx.getPrintingPolicy(),
1998 /*Indentation=*/0);
1999 Out << ".";
2000 } else {
2001 APValue Val;
2002 This->moveInto(Val);
2003 Val.printPretty(
2004 Out, Info.Ctx,
2005 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2006 Out << ".";
2007 }
2008 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2009 /*Qualified=*/false);
2010 IsMemberCall = false;
2011 }
2012
2013 Out << '(';
2014
2015 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2016 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2017 if (ArgIndex > (unsigned)IsMemberCall)
2018 Out << ", ";
2019
2020 const ParmVarDecl *Param = *I;
2021 APValue *V = Info.getParamSlot(Arguments, Param);
2022 if (V)
2023 V->printPretty(Out, Info.Ctx, Param->getType());
2024 else
2025 Out << "<...>";
2026
2027 if (ArgIndex == 0 && IsMemberCall)
2028 Out << "->" << *Callee << '(';
2029 }
2030
2031 Out << ')';
2032}
2033
2034/// Evaluate an expression to see if it had side-effects, and discard its
2035/// result.
2036/// \return \c true if the caller should keep evaluating.
2037static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2038 assert(!E->isValueDependent());
2039 APValue Scratch;
2040 if (!Evaluate(Scratch, Info, E))
2041 // We don't need the value, but we might have skipped a side effect here.
2042 return Info.noteSideEffect();
2043 return true;
2044}
2045
2046/// Should this call expression be treated as forming an opaque constant?
2047static bool IsOpaqueConstantCall(const CallExpr *E) {
2048 unsigned Builtin = E->getBuiltinCallee();
2049 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2050 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2051 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2052 Builtin == Builtin::BI__builtin_function_start);
2053}
2054
2055static bool IsOpaqueConstantCall(const LValue &LVal) {
2056 const auto *BaseExpr =
2057 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2058 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2059}
2060
2062 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2063 // constant expression of pointer type that evaluates to...
2064
2065 // ... a null pointer value, or a prvalue core constant expression of type
2066 // std::nullptr_t.
2067 if (!B)
2068 return true;
2069
2070 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2071 // ... the address of an object with static storage duration,
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->hasGlobalStorage();
2075 return true;
2076 // ... the address of a function,
2077 // ... the address of a GUID [MS extension],
2078 // ... the address of an unnamed global constant
2080 }
2081
2082 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2083 return true;
2084
2085 const Expr *E = B.get<const Expr*>();
2086 switch (E->getStmtClass()) {
2087 default:
2088 return false;
2089 case Expr::CompoundLiteralExprClass: {
2091 return CLE->isFileScope() && CLE->isLValue();
2092 }
2093 case Expr::MaterializeTemporaryExprClass:
2094 // A materialized temporary might have been lifetime-extended to static
2095 // storage duration.
2096 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2097 // A string literal has static storage duration.
2098 case Expr::StringLiteralClass:
2099 case Expr::PredefinedExprClass:
2100 case Expr::ObjCStringLiteralClass:
2101 case Expr::ObjCEncodeExprClass:
2102 return true;
2103 case Expr::ObjCBoxedExprClass:
2104 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2105 case Expr::CallExprClass:
2107 // For GCC compatibility, &&label has static storage duration.
2108 case Expr::AddrLabelExprClass:
2109 return true;
2110 // A Block literal expression may be used as the initialization value for
2111 // Block variables at global or local static scope.
2112 case Expr::BlockExprClass:
2113 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2114 // The APValue generated from a __builtin_source_location will be emitted as a
2115 // literal.
2116 case Expr::SourceLocExprClass:
2117 return true;
2118 case Expr::ImplicitValueInitExprClass:
2119 // FIXME:
2120 // We can never form an lvalue with an implicit value initialization as its
2121 // base through expression evaluation, so these only appear in one case: the
2122 // implicit variable declaration we invent when checking whether a constexpr
2123 // constructor can produce a constant expression. We must assume that such
2124 // an expression might be a global lvalue.
2125 return true;
2126 }
2127}
2128
2129static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2130 return LVal.Base.dyn_cast<const ValueDecl*>();
2131}
2132
2133// Information about an LValueBase that is some kind of string.
2136 StringRef Bytes;
2138};
2139
2140// Gets the lvalue base of LVal as a string.
2141static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2142 LValueBaseString &AsString) {
2143 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2144 if (!BaseExpr)
2145 return false;
2146
2147 // For ObjCEncodeExpr, we need to compute and store the string.
2148 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2149 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2150 AsString.ObjCEncodeStorage);
2151 AsString.Bytes = AsString.ObjCEncodeStorage;
2152 AsString.CharWidth = 1;
2153 return true;
2154 }
2155
2156 // Otherwise, we have a StringLiteral.
2157 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2158 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2159 Lit = PE->getFunctionName();
2160
2161 if (!Lit)
2162 return false;
2163
2164 AsString.Bytes = Lit->getBytes();
2165 AsString.CharWidth = Lit->getCharByteWidth();
2166 return true;
2167}
2168
2169// Determine whether two string literals potentially overlap. This will be the
2170// case if they agree on the values of all the bytes on the overlapping region
2171// between them.
2172//
2173// The overlapping region is the portion of the two string literals that must
2174// overlap in memory if the pointers actually point to the same address at
2175// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2176// the overlapping region is "cdef\0", which in this case does agree, so the
2177// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2178// "bazbar" + 3, the overlapping region contains all of both strings, so they
2179// are not potentially overlapping, even though they agree from the given
2180// addresses onwards.
2181//
2182// See open core issue CWG2765 which is discussing the desired rule here.
2183static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2184 const LValue &LHS,
2185 const LValue &RHS) {
2186 LValueBaseString LHSString, RHSString;
2187 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2188 !GetLValueBaseAsString(Info, RHS, RHSString))
2189 return false;
2190
2191 // This is the byte offset to the location of the first character of LHS
2192 // within RHS. We don't need to look at the characters of one string that
2193 // would appear before the start of the other string if they were merged.
2194 CharUnits Offset = RHS.Offset - LHS.Offset;
2195 if (Offset.isNegative()) {
2196 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2197 return false;
2198 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2199 } else {
2200 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2201 return false;
2202 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2203 }
2204
2205 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2206 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2207 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2208 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2209
2210 // The null terminator isn't included in the string data, so check for it
2211 // manually. If the longer string doesn't have a null terminator where the
2212 // shorter string ends, they aren't potentially overlapping.
2213 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2214 if (Shorter.size() + NullByte >= Longer.size())
2215 break;
2216 if (Longer[Shorter.size() + NullByte])
2217 return false;
2218 }
2219
2220 // Otherwise, they're potentially overlapping if and only if the overlapping
2221 // region is the same.
2222 return Shorter == Longer.take_front(Shorter.size());
2223}
2224
2225static bool IsWeakLValue(const LValue &Value) {
2227 return Decl && Decl->isWeak();
2228}
2229
2230static bool isZeroSized(const LValue &Value) {
2232 if (isa_and_nonnull<VarDecl>(Decl)) {
2233 QualType Ty = Decl->getType();
2234 if (Ty->isArrayType())
2235 return Ty->isIncompleteType() ||
2236 Decl->getASTContext().getTypeSize(Ty) == 0;
2237 }
2238 return false;
2239}
2240
2241static bool HasSameBase(const LValue &A, const LValue &B) {
2242 if (!A.getLValueBase())
2243 return !B.getLValueBase();
2244 if (!B.getLValueBase())
2245 return false;
2246
2247 if (A.getLValueBase().getOpaqueValue() !=
2248 B.getLValueBase().getOpaqueValue())
2249 return false;
2250
2251 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2252 A.getLValueVersion() == B.getLValueVersion();
2253}
2254
2255static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2256 assert(Base && "no location for a null lvalue");
2257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2258
2259 // For a parameter, find the corresponding call stack frame (if it still
2260 // exists), and point at the parameter of the function definition we actually
2261 // invoked.
2262 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2263 unsigned Idx = PVD->getFunctionScopeIndex();
2264 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2265 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2266 F->Arguments.Version == Base.getVersion() && F->Callee &&
2267 Idx < F->Callee->getNumParams()) {
2268 VD = F->Callee->getParamDecl(Idx);
2269 break;
2270 }
2271 }
2272 }
2273
2274 if (VD)
2275 Info.Note(VD->getLocation(), diag::note_declared_at);
2276 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2277 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2278 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2279 // FIXME: Produce a note for dangling pointers too.
2280 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2281 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2282 diag::note_constexpr_dynamic_alloc_here);
2283 }
2284
2285 // We have no information to show for a typeid(T) object.
2286}
2287
2292
2293/// Materialized temporaries that we've already checked to determine if they're
2294/// initializsed by a constant expression.
2297
2299 EvalInfo &Info, SourceLocation DiagLoc,
2300 QualType Type, const APValue &Value,
2301 ConstantExprKind Kind,
2302 const FieldDecl *SubobjectDecl,
2303 CheckedTemporaries &CheckedTemps);
2304
2305/// Check that this reference or pointer core constant expression is a valid
2306/// value for an address or reference constant expression. Return true if we
2307/// can fold this expression, whether or not it's a constant expression.
2308static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2309 QualType Type, const LValue &LVal,
2310 ConstantExprKind Kind,
2311 CheckedTemporaries &CheckedTemps) {
2312 bool IsReferenceType = Type->isReferenceType();
2313
2314 APValue::LValueBase Base = LVal.getLValueBase();
2315 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2316
2317 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2318 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2319
2320 // Additional restrictions apply in a template argument. We only enforce the
2321 // C++20 restrictions here; additional syntactic and semantic restrictions
2322 // are applied elsewhere.
2323 if (isTemplateArgument(Kind)) {
2324 int InvalidBaseKind = -1;
2325 StringRef Ident;
2326 if (Base.is<TypeInfoLValue>())
2327 InvalidBaseKind = 0;
2328 else if (isa_and_nonnull<StringLiteral>(BaseE))
2329 InvalidBaseKind = 1;
2330 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2331 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2332 InvalidBaseKind = 2;
2333 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2334 InvalidBaseKind = 3;
2335 Ident = PE->getIdentKindName();
2336 }
2337
2338 if (InvalidBaseKind != -1) {
2339 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2340 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2341 << Ident;
2342 return false;
2343 }
2344 }
2345
2346 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2347 FD && FD->isImmediateFunction()) {
2348 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2349 << !Type->isAnyPointerType();
2350 Info.Note(FD->getLocation(), diag::note_declared_at);
2351 return false;
2352 }
2353
2354 // Check that the object is a global. Note that the fake 'this' object we
2355 // manufacture when checking potential constant expressions is conservatively
2356 // assumed to be global here.
2357 if (!IsGlobalLValue(Base)) {
2358 if (Info.getLangOpts().CPlusPlus11) {
2359 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2360 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2361 << BaseVD;
2362 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2363 if (VarD && VarD->isConstexpr()) {
2364 // Non-static local constexpr variables have unintuitive semantics:
2365 // constexpr int a = 1;
2366 // constexpr const int *p = &a;
2367 // ... is invalid because the address of 'a' is not constant. Suggest
2368 // adding a 'static' in this case.
2369 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2370 << VarD
2371 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2372 } else {
2373 NoteLValueLocation(Info, Base);
2374 }
2375 } else {
2376 Info.FFDiag(Loc);
2377 }
2378 // Don't allow references to temporaries to escape.
2379 return false;
2380 }
2381 assert((Info.checkingPotentialConstantExpression() ||
2382 LVal.getLValueCallIndex() == 0) &&
2383 "have call index for global lvalue");
2384
2385 if (LVal.allowConstexprUnknown()) {
2386 if (BaseVD) {
2387 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2388 NoteLValueLocation(Info, Base);
2389 } else {
2390 Info.FFDiag(Loc);
2391 }
2392 return false;
2393 }
2394
2395 if (Base.is<DynamicAllocLValue>()) {
2396 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2397 << IsReferenceType << !Designator.Entries.empty();
2398 NoteLValueLocation(Info, Base);
2399 return false;
2400 }
2401
2402 if (BaseVD) {
2403 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2404 // Check if this is a thread-local variable.
2405 if (Var->getTLSKind())
2406 // FIXME: Diagnostic!
2407 return false;
2408
2409 // A dllimport variable never acts like a constant, unless we're
2410 // evaluating a value for use only in name mangling.
2411 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2412 // FIXME: Diagnostic!
2413 return false;
2414
2415 // In CUDA/HIP device compilation, only device side variables have
2416 // constant addresses.
2417 if (Info.getASTContext().getLangOpts().CUDA &&
2418 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2419 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2420 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2421 !Var->hasAttr<CUDAConstantAttr>() &&
2422 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2423 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2424 Var->hasAttr<HIPManagedAttr>())
2425 return false;
2426 }
2427 }
2428 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2429 // __declspec(dllimport) must be handled very carefully:
2430 // We must never initialize an expression with the thunk in C++.
2431 // Doing otherwise would allow the same id-expression to yield
2432 // different addresses for the same function in different translation
2433 // units. However, this means that we must dynamically initialize the
2434 // expression with the contents of the import address table at runtime.
2435 //
2436 // The C language has no notion of ODR; furthermore, it has no notion of
2437 // dynamic initialization. This means that we are permitted to
2438 // perform initialization with the address of the thunk.
2439 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2440 FD->hasAttr<DLLImportAttr>())
2441 // FIXME: Diagnostic!
2442 return false;
2443 }
2444 } else if (const auto *MTE =
2445 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2446 if (CheckedTemps.insert(MTE).second) {
2447 QualType TempType = getType(Base);
2448 if (TempType.isDestructedType()) {
2449 Info.FFDiag(MTE->getExprLoc(),
2450 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2451 << TempType;
2452 return false;
2453 }
2454
2455 APValue *V = MTE->getOrCreateValue(false);
2456 assert(V && "evasluation result refers to uninitialised temporary");
2458 Info, MTE->getExprLoc(), TempType, *V, Kind,
2459 /*SubobjectDecl=*/nullptr, CheckedTemps))
2460 return false;
2461 }
2462 }
2463
2464 // Allow address constant expressions to be past-the-end pointers. This is
2465 // an extension: the standard requires them to point to an object.
2466 if (!IsReferenceType)
2467 return true;
2468
2469 // A reference constant expression must refer to an object.
2470 if (!Base) {
2471 // FIXME: diagnostic
2472 Info.CCEDiag(Loc);
2473 return true;
2474 }
2475
2476 // Does this refer one past the end of some object?
2477 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2478 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2479 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2480 NoteLValueLocation(Info, Base);
2481 }
2482
2483 return true;
2484}
2485
2486/// Member pointers are constant expressions unless they point to a
2487/// non-virtual dllimport member function.
2488static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2489 SourceLocation Loc,
2490 QualType Type,
2491 const APValue &Value,
2492 ConstantExprKind Kind) {
2493 const ValueDecl *Member = Value.getMemberPointerDecl();
2494 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2495 if (!FD)
2496 return true;
2497 if (FD->isImmediateFunction()) {
2498 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2499 Info.Note(FD->getLocation(), diag::note_declared_at);
2500 return false;
2501 }
2502 return isForManglingOnly(Kind) || FD->isVirtual() ||
2503 !FD->hasAttr<DLLImportAttr>();
2504}
2505
2506/// Check that this core constant expression is of literal type, and if not,
2507/// produce an appropriate diagnostic.
2508static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2509 const LValue *This = nullptr) {
2510 // The restriction to literal types does not exist in C++23 anymore.
2511 if (Info.getLangOpts().CPlusPlus23)
2512 return true;
2513
2514 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2515 return true;
2516
2517 // C++1y: A constant initializer for an object o [...] may also invoke
2518 // constexpr constructors for o and its subobjects even if those objects
2519 // are of non-literal class types.
2520 //
2521 // C++11 missed this detail for aggregates, so classes like this:
2522 // struct foo_t { union { int i; volatile int j; } u; };
2523 // are not (obviously) initializable like so:
2524 // __attribute__((__require_constant_initialization__))
2525 // static const foo_t x = {{0}};
2526 // because "i" is a subobject with non-literal initialization (due to the
2527 // volatile member of the union). See:
2528 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2529 // Therefore, we use the C++1y behavior.
2530 if (This && Info.EvaluatingDecl == This->getLValueBase())
2531 return true;
2532
2533 // Prvalue constant expressions must be of literal types.
2534 if (Info.getLangOpts().CPlusPlus11)
2535 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2536 << E->getType();
2537 else
2538 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2539 return false;
2540}
2541
2543 EvalInfo &Info, SourceLocation DiagLoc,
2544 QualType Type, const APValue &Value,
2545 ConstantExprKind Kind,
2546 const FieldDecl *SubobjectDecl,
2547 CheckedTemporaries &CheckedTemps) {
2548 if (!Value.hasValue()) {
2549 if (SubobjectDecl) {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*(name)*/ 1 << SubobjectDecl;
2552 Info.Note(SubobjectDecl->getLocation(),
2553 diag::note_constexpr_subobject_declared_here);
2554 } else {
2555 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556 << /*of type*/ 0 << Type;
2557 }
2558 return false;
2559 }
2560
2561 // We allow _Atomic(T) to be initialized from anything that T can be
2562 // initialized from.
2563 if (const AtomicType *AT = Type->getAs<AtomicType>())
2564 Type = AT->getValueType();
2565
2566 // Core issue 1454: For a literal constant expression of array or class type,
2567 // each subobject of its value shall have been initialized by a constant
2568 // expression.
2569 if (Value.isArray()) {
2571 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2572 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2573 Value.getArrayInitializedElt(I), Kind,
2574 SubobjectDecl, CheckedTemps))
2575 return false;
2576 }
2577 if (!Value.hasArrayFiller())
2578 return true;
2579 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2580 Value.getArrayFiller(), Kind, SubobjectDecl,
2581 CheckedTemps);
2582 }
2583 if (Value.isUnion() && Value.getUnionField()) {
2584 return CheckEvaluationResult(
2585 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2586 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2587 }
2588 if (Value.isStruct()) {
2589 auto *RD = Type->castAsRecordDecl();
2590 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2591 unsigned BaseIndex = 0;
2592 for (const CXXBaseSpecifier &BS : CD->bases()) {
2593 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2594 if (!BaseValue.hasValue()) {
2595 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2596 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2597 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2598 return false;
2599 }
2600 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2601 Kind, /*SubobjectDecl=*/nullptr,
2602 CheckedTemps))
2603 return false;
2604 ++BaseIndex;
2605 }
2606 }
2607 for (const auto *I : RD->fields()) {
2608 if (I->isUnnamedBitField())
2609 continue;
2610
2611 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2612 Value.getStructField(I->getFieldIndex()), Kind,
2613 I, CheckedTemps))
2614 return false;
2615 }
2616 }
2617
2618 if (Value.isLValue() &&
2620 LValue LVal;
2621 LVal.setFrom(Info.Ctx, Value);
2622 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2623 CheckedTemps);
2624 }
2625
2626 if (Value.isMemberPointer() &&
2628 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2629
2630 // Everything else is fine.
2631 return true;
2632}
2633
2634/// Check that this core constant expression value is a valid value for a
2635/// constant expression. If not, report an appropriate diagnostic. Does not
2636/// check that the expression is of literal type.
2637static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2638 QualType Type, const APValue &Value,
2639 ConstantExprKind Kind) {
2640 // Nothing to check for a constant expression of type 'cv void'.
2641 if (Type->isVoidType())
2642 return true;
2643
2644 CheckedTemporaries CheckedTemps;
2646 Info, DiagLoc, Type, Value, Kind,
2647 /*SubobjectDecl=*/nullptr, CheckedTemps);
2648}
2649
2650/// Check that this evaluated value is fully-initialized and can be loaded by
2651/// an lvalue-to-rvalue conversion.
2652static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2653 QualType Type, const APValue &Value) {
2654 CheckedTemporaries CheckedTemps;
2655 return CheckEvaluationResult(
2657 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2658}
2659
2660/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2661/// "the allocated storage is deallocated within the evaluation".
2662static bool CheckMemoryLeaks(EvalInfo &Info) {
2663 if (!Info.HeapAllocs.empty()) {
2664 // We can still fold to a constant despite a compile-time memory leak,
2665 // so long as the heap allocation isn't referenced in the result (we check
2666 // that in CheckConstantExpression).
2667 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2668 diag::note_constexpr_memory_leak)
2669 << unsigned(Info.HeapAllocs.size() - 1);
2670 }
2671 return true;
2672}
2673
2674static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2675 // A null base expression indicates a null pointer. These are always
2676 // evaluatable, and they are false unless the offset is zero.
2677 if (!Value.getLValueBase()) {
2678 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2679 Result = !Value.getLValueOffset().isZero();
2680 return true;
2681 }
2682
2683 // We have a non-null base. These are generally known to be true, but if it's
2684 // a weak declaration it can be null at runtime.
2685 Result = true;
2686 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2687 return !Decl || !Decl->isWeak();
2688}
2689
2690static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2691 // TODO: This function should produce notes if it fails.
2692 switch (Val.getKind()) {
2693 case APValue::None:
2695 return false;
2696 case APValue::Int:
2697 Result = Val.getInt().getBoolValue();
2698 return true;
2700 Result = Val.getFixedPoint().getBoolValue();
2701 return true;
2702 case APValue::Float:
2703 Result = !Val.getFloat().isZero();
2704 return true;
2706 Result = Val.getComplexIntReal().getBoolValue() ||
2707 Val.getComplexIntImag().getBoolValue();
2708 return true;
2710 Result = !Val.getComplexFloatReal().isZero() ||
2711 !Val.getComplexFloatImag().isZero();
2712 return true;
2713 case APValue::LValue:
2714 return EvalPointerValueAsBool(Val, Result);
2716 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2717 return false;
2718 }
2719 Result = Val.getMemberPointerDecl();
2720 return true;
2721 case APValue::Vector:
2722 case APValue::Array:
2723 case APValue::Struct:
2724 case APValue::Union:
2726 return false;
2727 }
2728
2729 llvm_unreachable("unknown APValue kind");
2730}
2731
2732static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2733 EvalInfo &Info) {
2734 assert(!E->isValueDependent());
2735 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2736 APValue Val;
2737 if (!Evaluate(Val, Info, E))
2738 return false;
2739 return HandleConversionToBool(Val, Result);
2740}
2741
2742template<typename T>
2743static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2744 const T &SrcValue, QualType DestType) {
2745 Info.CCEDiag(E, diag::note_constexpr_overflow)
2746 << SrcValue << DestType;
2747 return Info.noteUndefinedBehavior();
2748}
2749
2750static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2751 QualType SrcType, const APFloat &Value,
2752 QualType DestType, APSInt &Result) {
2753 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2754 // Determine whether we are converting to unsigned or signed.
2755 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2756
2757 Result = APSInt(DestWidth, !DestSigned);
2758 bool ignored;
2759 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2760 & APFloat::opInvalidOp)
2761 return HandleOverflow(Info, E, Value, DestType);
2762 return true;
2763}
2764
2765/// Get rounding mode to use in evaluation of the specified expression.
2766///
2767/// If rounding mode is unknown at compile time, still try to evaluate the
2768/// expression. If the result is exact, it does not depend on rounding mode.
2769/// So return "tonearest" mode instead of "dynamic".
2770static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2771 llvm::RoundingMode RM =
2773 if (RM == llvm::RoundingMode::Dynamic)
2774 RM = llvm::RoundingMode::NearestTiesToEven;
2775 return RM;
2776}
2777
2778/// Check if the given evaluation result is allowed for constant evaluation.
2779static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2780 APFloat::opStatus St) {
2781 // In a constant context, assume that any dynamic rounding mode or FP
2782 // exception state matches the default floating-point environment.
2783 if (Info.InConstantContext)
2784 return true;
2785
2786 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2787 if ((St & APFloat::opInexact) &&
2788 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2789 // Inexact result means that it depends on rounding mode. If the requested
2790 // mode is dynamic, the evaluation cannot be made in compile time.
2791 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2792 return false;
2793 }
2794
2795 if ((St != APFloat::opOK) &&
2796 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2798 FPO.getAllowFEnvAccess())) {
2799 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2800 return false;
2801 }
2802
2803 if ((St & APFloat::opStatus::opInvalidOp) &&
2805 // There is no usefully definable result.
2806 Info.FFDiag(E);
2807 return false;
2808 }
2809
2810 // FIXME: if:
2811 // - evaluation triggered other FP exception, and
2812 // - exception mode is not "ignore", and
2813 // - the expression being evaluated is not a part of global variable
2814 // initializer,
2815 // the evaluation probably need to be rejected.
2816 return true;
2817}
2818
2819static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2820 QualType SrcType, QualType DestType,
2821 APFloat &Result) {
2822 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2824 "HandleFloatToFloatCast has been checked with only CastExpr, "
2825 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2826 "the new expression or address the root cause of this usage.");
2827 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2828 APFloat::opStatus St;
2829 APFloat Value = Result;
2830 bool ignored;
2831 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2832 return checkFloatingPointResult(Info, E, St);
2833}
2834
2835static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2836 QualType DestType, QualType SrcType,
2837 const APSInt &Value) {
2838 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2839 // Figure out if this is a truncate, extend or noop cast.
2840 // If the input is signed, do a sign extend, noop, or truncate.
2841 APSInt Result = Value.extOrTrunc(DestWidth);
2842 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2843 if (DestType->isBooleanType())
2844 Result = Value.getBoolValue();
2845 return Result;
2846}
2847
2848static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2849 const FPOptions FPO,
2850 QualType SrcType, const APSInt &Value,
2851 QualType DestType, APFloat &Result) {
2852 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2853 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2854 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2855 return checkFloatingPointResult(Info, E, St);
2856}
2857
2858static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2859 APValue &Value, const FieldDecl *FD) {
2860 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2861
2862 if (!Value.isInt()) {
2863 // Trying to store a pointer-cast-to-integer into a bitfield.
2864 // FIXME: In this case, we should provide the diagnostic for casting
2865 // a pointer to an integer.
2866 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2867 Info.FFDiag(E);
2868 return false;
2869 }
2870
2871 APSInt &Int = Value.getInt();
2872 unsigned OldBitWidth = Int.getBitWidth();
2873 unsigned NewBitWidth = FD->getBitWidthValue();
2874 if (NewBitWidth < OldBitWidth)
2875 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2876 return true;
2877}
2878
2879/// Perform the given integer operation, which is known to need at most BitWidth
2880/// bits, and check for overflow in the original type (if that type was not an
2881/// unsigned type).
2882template<typename Operation>
2883static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2884 const APSInt &LHS, const APSInt &RHS,
2885 unsigned BitWidth, Operation Op,
2886 APSInt &Result) {
2887 if (LHS.isUnsigned()) {
2888 Result = Op(LHS, RHS);
2889 return true;
2890 }
2891
2892 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2893 Result = Value.trunc(LHS.getBitWidth());
2894 if (Result.extend(BitWidth) != Value) {
2895 if (Info.checkingForUndefinedBehavior())
2896 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2897 diag::warn_integer_constant_overflow)
2898 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2899 /*UpperCase=*/true, /*InsertSeparators=*/true)
2900 << E->getType() << E->getSourceRange();
2901 return HandleOverflow(Info, E, Value, E->getType());
2902 }
2903 return true;
2904}
2905
2906/// Perform the given binary integer operation.
2907static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2908 const APSInt &LHS, BinaryOperatorKind Opcode,
2909 APSInt RHS, APSInt &Result) {
2910 bool HandleOverflowResult = true;
2911 switch (Opcode) {
2912 default:
2913 Info.FFDiag(E);
2914 return false;
2915 case BO_Mul:
2916 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2917 std::multiplies<APSInt>(), Result);
2918 case BO_Add:
2919 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2920 std::plus<APSInt>(), Result);
2921 case BO_Sub:
2922 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2923 std::minus<APSInt>(), Result);
2924 case BO_And: Result = LHS & RHS; return true;
2925 case BO_Xor: Result = LHS ^ RHS; return true;
2926 case BO_Or: Result = LHS | RHS; return true;
2927 case BO_Div:
2928 case BO_Rem:
2929 if (RHS == 0) {
2930 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2931 << E->getRHS()->getSourceRange();
2932 return false;
2933 }
2934 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2935 // this operation and gives the two's complement result.
2936 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2937 LHS.isMinSignedValue())
2938 HandleOverflowResult = HandleOverflow(
2939 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2940 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2941 return HandleOverflowResult;
2942 case BO_Shl: {
2943 if (Info.getLangOpts().OpenCL)
2944 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2945 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2946 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2947 RHS.isUnsigned());
2948 else if (RHS.isSigned() && RHS.isNegative()) {
2949 // During constant-folding, a negative shift is an opposite shift. Such
2950 // a shift is not a constant expression.
2951 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2952 if (!Info.noteUndefinedBehavior())
2953 return false;
2954 RHS = -RHS;
2955 goto shift_right;
2956 }
2957 shift_left:
2958 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2959 // the shifted type.
2960 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2961 if (SA != RHS) {
2962 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2963 << RHS << E->getType() << LHS.getBitWidth();
2964 if (!Info.noteUndefinedBehavior())
2965 return false;
2966 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2967 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2968 // operand, and must not overflow the corresponding unsigned type.
2969 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2970 // E1 x 2^E2 module 2^N.
2971 if (LHS.isNegative()) {
2972 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2973 if (!Info.noteUndefinedBehavior())
2974 return false;
2975 } else if (LHS.countl_zero() < SA) {
2976 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2977 if (!Info.noteUndefinedBehavior())
2978 return false;
2979 }
2980 }
2981 Result = LHS << SA;
2982 return true;
2983 }
2984 case BO_Shr: {
2985 if (Info.getLangOpts().OpenCL)
2986 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2987 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2988 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2989 RHS.isUnsigned());
2990 else if (RHS.isSigned() && RHS.isNegative()) {
2991 // During constant-folding, a negative shift is an opposite shift. Such a
2992 // shift is not a constant expression.
2993 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2994 if (!Info.noteUndefinedBehavior())
2995 return false;
2996 RHS = -RHS;
2997 goto shift_left;
2998 }
2999 shift_right:
3000 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3001 // shifted type.
3002 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3003 if (SA != RHS) {
3004 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3005 << RHS << E->getType() << LHS.getBitWidth();
3006 if (!Info.noteUndefinedBehavior())
3007 return false;
3008 }
3009
3010 Result = LHS >> SA;
3011 return true;
3012 }
3013
3014 case BO_LT: Result = LHS < RHS; return true;
3015 case BO_GT: Result = LHS > RHS; return true;
3016 case BO_LE: Result = LHS <= RHS; return true;
3017 case BO_GE: Result = LHS >= RHS; return true;
3018 case BO_EQ: Result = LHS == RHS; return true;
3019 case BO_NE: Result = LHS != RHS; return true;
3020 case BO_Cmp:
3021 llvm_unreachable("BO_Cmp should be handled elsewhere");
3022 }
3023}
3024
3025/// Perform the given binary floating-point operation, in-place, on LHS.
3026static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3027 APFloat &LHS, BinaryOperatorKind Opcode,
3028 const APFloat &RHS) {
3029 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3030 APFloat::opStatus St;
3031 switch (Opcode) {
3032 default:
3033 Info.FFDiag(E);
3034 return false;
3035 case BO_Mul:
3036 St = LHS.multiply(RHS, RM);
3037 break;
3038 case BO_Add:
3039 St = LHS.add(RHS, RM);
3040 break;
3041 case BO_Sub:
3042 St = LHS.subtract(RHS, RM);
3043 break;
3044 case BO_Div:
3045 // [expr.mul]p4:
3046 // If the second operand of / or % is zero the behavior is undefined.
3047 if (RHS.isZero())
3048 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3049 St = LHS.divide(RHS, RM);
3050 break;
3051 }
3052
3053 // [expr.pre]p4:
3054 // If during the evaluation of an expression, the result is not
3055 // mathematically defined [...], the behavior is undefined.
3056 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3057 if (LHS.isNaN()) {
3058 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3059 return Info.noteUndefinedBehavior();
3060 }
3061
3062 return checkFloatingPointResult(Info, E, St);
3063}
3064
3065static bool handleLogicalOpForVector(const APInt &LHSValue,
3066 BinaryOperatorKind Opcode,
3067 const APInt &RHSValue, APInt &Result) {
3068 bool LHS = (LHSValue != 0);
3069 bool RHS = (RHSValue != 0);
3070
3071 if (Opcode == BO_LAnd)
3072 Result = LHS && RHS;
3073 else
3074 Result = LHS || RHS;
3075 return true;
3076}
3077static bool handleLogicalOpForVector(const APFloat &LHSValue,
3078 BinaryOperatorKind Opcode,
3079 const APFloat &RHSValue, APInt &Result) {
3080 bool LHS = !LHSValue.isZero();
3081 bool RHS = !RHSValue.isZero();
3082
3083 if (Opcode == BO_LAnd)
3084 Result = LHS && RHS;
3085 else
3086 Result = LHS || RHS;
3087 return true;
3088}
3089
3090static bool handleLogicalOpForVector(const APValue &LHSValue,
3091 BinaryOperatorKind Opcode,
3092 const APValue &RHSValue, APInt &Result) {
3093 // The result is always an int type, however operands match the first.
3094 if (LHSValue.getKind() == APValue::Int)
3095 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3096 RHSValue.getInt(), Result);
3097 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3098 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3099 RHSValue.getFloat(), Result);
3100}
3101
3102template <typename APTy>
3103static bool
3105 const APTy &RHSValue, APInt &Result) {
3106 switch (Opcode) {
3107 default:
3108 llvm_unreachable("unsupported binary operator");
3109 case BO_EQ:
3110 Result = (LHSValue == RHSValue);
3111 break;
3112 case BO_NE:
3113 Result = (LHSValue != RHSValue);
3114 break;
3115 case BO_LT:
3116 Result = (LHSValue < RHSValue);
3117 break;
3118 case BO_GT:
3119 Result = (LHSValue > RHSValue);
3120 break;
3121 case BO_LE:
3122 Result = (LHSValue <= RHSValue);
3123 break;
3124 case BO_GE:
3125 Result = (LHSValue >= RHSValue);
3126 break;
3127 }
3128
3129 // The boolean operations on these vector types use an instruction that
3130 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3131 // to -1 to make sure that we produce the correct value.
3132 Result.negate();
3133
3134 return true;
3135}
3136
3137static bool handleCompareOpForVector(const APValue &LHSValue,
3138 BinaryOperatorKind Opcode,
3139 const APValue &RHSValue, APInt &Result) {
3140 // The result is always an int type, however operands match the first.
3141 if (LHSValue.getKind() == APValue::Int)
3142 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3143 RHSValue.getInt(), Result);
3144 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3145 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3146 RHSValue.getFloat(), Result);
3147}
3148
3149// Perform binary operations for vector types, in place on the LHS.
3150static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3151 BinaryOperatorKind Opcode,
3152 APValue &LHSValue,
3153 const APValue &RHSValue) {
3154 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3155 "Operation not supported on vector types");
3156
3157 const auto *VT = E->getType()->castAs<VectorType>();
3158 unsigned NumElements = VT->getNumElements();
3159 QualType EltTy = VT->getElementType();
3160
3161 // In the cases (typically C as I've observed) where we aren't evaluating
3162 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3163 // just give up.
3164 if (!LHSValue.isVector()) {
3165 assert(LHSValue.isLValue() &&
3166 "A vector result that isn't a vector OR uncalculated LValue");
3167 Info.FFDiag(E);
3168 return false;
3169 }
3170
3171 assert(LHSValue.getVectorLength() == NumElements &&
3172 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3173
3174 SmallVector<APValue, 4> ResultElements;
3175
3176 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3177 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3178 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3179
3180 if (EltTy->isIntegerType()) {
3181 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3182 EltTy->isUnsignedIntegerType()};
3183 bool Success = true;
3184
3185 if (BinaryOperator::isLogicalOp(Opcode))
3186 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3187 else if (BinaryOperator::isComparisonOp(Opcode))
3188 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3189 else
3190 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3191 RHSElt.getInt(), EltResult);
3192
3193 if (!Success) {
3194 Info.FFDiag(E);
3195 return false;
3196 }
3197 ResultElements.emplace_back(EltResult);
3198
3199 } else if (EltTy->isFloatingType()) {
3200 assert(LHSElt.getKind() == APValue::Float &&
3201 RHSElt.getKind() == APValue::Float &&
3202 "Mismatched LHS/RHS/Result Type");
3203 APFloat LHSFloat = LHSElt.getFloat();
3204
3205 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3206 RHSElt.getFloat())) {
3207 Info.FFDiag(E);
3208 return false;
3209 }
3210
3211 ResultElements.emplace_back(LHSFloat);
3212 }
3213 }
3214
3215 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3216 return true;
3217}
3218
3219/// Cast an lvalue referring to a base subobject to a derived class, by
3220/// truncating the lvalue's path to the given length.
3221static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3222 const RecordDecl *TruncatedType,
3223 unsigned TruncatedElements) {
3224 SubobjectDesignator &D = Result.Designator;
3225
3226 // Check we actually point to a derived class object.
3227 if (TruncatedElements == D.Entries.size())
3228 return true;
3229 assert(TruncatedElements >= D.MostDerivedPathLength &&
3230 "not casting to a derived class");
3231 if (!Result.checkSubobject(Info, E, CSK_Derived))
3232 return false;
3233
3234 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3235 const RecordDecl *RD = TruncatedType;
3236 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3237 if (RD->isInvalidDecl()) return false;
3238 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3239 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3240 if (isVirtualBaseClass(D.Entries[I]))
3241 Result.Offset -= Layout.getVBaseClassOffset(Base);
3242 else
3243 Result.Offset -= Layout.getBaseClassOffset(Base);
3244 RD = Base;
3245 }
3246 D.Entries.resize(TruncatedElements);
3247 return true;
3248}
3249
3250static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3251 const CXXRecordDecl *Derived,
3252 const CXXRecordDecl *Base,
3253 const ASTRecordLayout *RL = nullptr) {
3254 if (!RL) {
3255 if (Derived->isInvalidDecl()) return false;
3256 RL = &Info.Ctx.getASTRecordLayout(Derived);
3257 }
3258
3259 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3260 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3261 return true;
3262}
3263
3264static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3265 const CXXRecordDecl *DerivedDecl,
3266 const CXXBaseSpecifier *Base) {
3267 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3268
3269 if (!Base->isVirtual())
3270 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3271
3272 SubobjectDesignator &D = Obj.Designator;
3273 if (D.Invalid)
3274 return false;
3275
3276 // Extract most-derived object and corresponding type.
3277 // FIXME: After implementing P2280R4 it became possible to get references
3278 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3279 // locations and if we see crashes in those locations in the future
3280 // it may make more sense to move this fix into Lvalue::set.
3281 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3282 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3283 return false;
3284
3285 // Find the virtual base class.
3286 if (DerivedDecl->isInvalidDecl()) return false;
3287 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3289 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3290 return true;
3291}
3292
3293static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3294 QualType Type, LValue &Result) {
3295 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3296 PathE = E->path_end();
3297 PathI != PathE; ++PathI) {
3298 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3299 *PathI))
3300 return false;
3301 Type = (*PathI)->getType();
3302 }
3303 return true;
3304}
3305
3306/// Cast an lvalue referring to a derived class to a known base subobject.
3307static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3308 const CXXRecordDecl *DerivedRD,
3309 const CXXRecordDecl *BaseRD) {
3310 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3311 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3312 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3313 llvm_unreachable("Class must be derived from the passed in base class!");
3314
3315 for (CXXBasePathElement &Elem : Paths.front())
3316 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3317 return false;
3318 return true;
3319}
3320
3321/// Update LVal to refer to the given field, which must be a member of the type
3322/// currently described by LVal.
3323static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3324 const FieldDecl *FD,
3325 const ASTRecordLayout *RL = nullptr) {
3326 if (!RL) {
3327 if (FD->getParent()->isInvalidDecl()) return false;
3328 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3329 }
3330
3331 unsigned I = FD->getFieldIndex();
3332 LVal.addDecl(Info, E, FD);
3333 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3334 return true;
3335}
3336
3337/// Update LVal to refer to the given indirect field.
3338static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3339 LValue &LVal,
3340 const IndirectFieldDecl *IFD) {
3341 for (const auto *C : IFD->chain())
3342 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3343 return false;
3344 return true;
3345}
3346
3351
3352/// Get the size of the given type in char units.
3353static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3356 // extension.
3357 if (Type->isVoidType() || Type->isFunctionType()) {
3358 Size = CharUnits::One();
3359 return true;
3360 }
3361
3362 if (Type->isDependentType()) {
3363 Info.FFDiag(Loc);
3364 return false;
3365 }
3366
3367 if (!Type->isConstantSizeType()) {
3368 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3369 // FIXME: Better diagnostic.
3370 Info.FFDiag(Loc);
3371 return false;
3372 }
3373
3374 if (SOT == SizeOfType::SizeOf)
3375 Size = Info.Ctx.getTypeSizeInChars(Type);
3376 else
3377 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3378 return true;
3379}
3380
3381/// Update a pointer value to model pointer arithmetic.
3382/// \param Info - Information about the ongoing evaluation.
3383/// \param E - The expression being evaluated, for diagnostic purposes.
3384/// \param LVal - The pointer value to be updated.
3385/// \param EltTy - The pointee type represented by LVal.
3386/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3387static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3388 LValue &LVal, QualType EltTy,
3389 APSInt Adjustment) {
3390 CharUnits SizeOfPointee;
3391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3392 return false;
3393
3394 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3395 return true;
3396}
3397
3398static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3399 LValue &LVal, QualType EltTy,
3400 int64_t Adjustment) {
3401 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3402 APSInt::get(Adjustment));
3403}
3404
3405/// Update an lvalue to refer to a component of a complex number.
3406/// \param Info - Information about the ongoing evaluation.
3407/// \param LVal - The lvalue to be updated.
3408/// \param EltTy - The complex number's component type.
3409/// \param Imag - False for the real component, true for the imaginary.
3410static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3411 LValue &LVal, QualType EltTy,
3412 bool Imag) {
3413 if (Imag) {
3414 CharUnits SizeOfComponent;
3415 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3416 return false;
3417 LVal.Offset += SizeOfComponent;
3418 }
3419 LVal.addComplex(Info, E, EltTy, Imag);
3420 return true;
3421}
3422
3423static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3424 LValue &LVal, QualType EltTy,
3425 uint64_t Size, uint64_t Idx) {
3426 if (Idx) {
3427 CharUnits SizeOfElement;
3428 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3429 return false;
3430 LVal.Offset += SizeOfElement * Idx;
3431 }
3432 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3433 return true;
3434}
3435
3436/// Try to evaluate the initializer for a variable declaration.
3437///
3438/// \param Info Information about the ongoing evaluation.
3439/// \param E An expression to be used when printing diagnostics.
3440/// \param VD The variable whose initializer should be obtained.
3441/// \param Version The version of the variable within the frame.
3442/// \param Frame The frame in which the variable was created. Must be null
3443/// if this variable is not local to the evaluation.
3444/// \param Result Filled in with a pointer to the value of the variable.
3445static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3446 const VarDecl *VD, CallStackFrame *Frame,
3447 unsigned Version, APValue *&Result) {
3448 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3449 // and pointers.
3450 bool AllowConstexprUnknown =
3451 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3452
3453 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3454
3455 auto CheckUninitReference = [&](bool IsLocalVariable) {
3456 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3457 // C++23 [expr.const]p8
3458 // ... For such an object that is not usable in constant expressions, the
3459 // dynamic type of the object is constexpr-unknown. For such a reference
3460 // that is not usable in constant expressions, the reference is treated
3461 // as binding to an unspecified object of the referenced type whose
3462 // lifetime and that of all subobjects includes the entire constant
3463 // evaluation and whose dynamic type is constexpr-unknown.
3464 //
3465 // Variables that are part of the current evaluation are not
3466 // constexpr-unknown.
3467 if (!AllowConstexprUnknown || IsLocalVariable) {
3468 if (!Info.checkingPotentialConstantExpression())
3469 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3470 return false;
3471 }
3472 Result = nullptr;
3473 }
3474 return true;
3475 };
3476
3477 // If this is a local variable, dig out its value.
3478 if (Frame) {
3479 Result = Frame->getTemporary(VD, Version);
3480 if (Result)
3481 return CheckUninitReference(/*IsLocalVariable=*/true);
3482
3483 if (!isa<ParmVarDecl>(VD)) {
3484 // Assume variables referenced within a lambda's call operator that were
3485 // not declared within the call operator are captures and during checking
3486 // of a potential constant expression, assume they are unknown constant
3487 // expressions.
3488 assert(isLambdaCallOperator(Frame->Callee) &&
3489 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3490 "missing value for local variable");
3491 if (Info.checkingPotentialConstantExpression())
3492 return false;
3493 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3494 // still reachable at all?
3495 Info.FFDiag(E->getBeginLoc(),
3496 diag::note_unimplemented_constexpr_lambda_feature_ast)
3497 << "captures not currently allowed";
3498 return false;
3499 }
3500 }
3501
3502 // If we're currently evaluating the initializer of this declaration, use that
3503 // in-flight value.
3504 if (Info.EvaluatingDecl == Base) {
3505 Result = Info.EvaluatingDeclValue;
3506 return CheckUninitReference(/*IsLocalVariable=*/false);
3507 }
3508
3509 // P2280R4 struck the restriction that variable of reference type lifetime
3510 // should begin within the evaluation of E
3511 // Used to be C++20 [expr.const]p5.12.2:
3512 // ... its lifetime began within the evaluation of E;
3513 if (isa<ParmVarDecl>(VD)) {
3514 if (AllowConstexprUnknown) {
3515 Result = nullptr;
3516 return true;
3517 }
3518
3519 // Assume parameters of a potential constant expression are usable in
3520 // constant expressions.
3521 if (!Info.checkingPotentialConstantExpression() ||
3522 !Info.CurrentCall->Callee ||
3523 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3524 if (Info.getLangOpts().CPlusPlus11) {
3525 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3526 << VD;
3527 NoteLValueLocation(Info, Base);
3528 } else {
3529 Info.FFDiag(E);
3530 }
3531 }
3532 return false;
3533 }
3534
3535 if (E->isValueDependent())
3536 return false;
3537
3538 // Dig out the initializer, and use the declaration which it's attached to.
3539 // FIXME: We should eventually check whether the variable has a reachable
3540 // initializing declaration.
3541 const Expr *Init = VD->getAnyInitializer(VD);
3542 // P2280R4 struck the restriction that variable of reference type should have
3543 // a preceding initialization.
3544 // Used to be C++20 [expr.const]p5.12:
3545 // ... reference has a preceding initialization and either ...
3546 if (!Init && !AllowConstexprUnknown) {
3547 // Don't diagnose during potential constant expression checking; an
3548 // initializer might be added later.
3549 if (!Info.checkingPotentialConstantExpression()) {
3550 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3551 << VD;
3552 NoteLValueLocation(Info, Base);
3553 }
3554 return false;
3555 }
3556
3557 // P2280R4 struck the initialization requirement for variables of reference
3558 // type so we can no longer assume we have an Init.
3559 // Used to be C++20 [expr.const]p5.12:
3560 // ... reference has a preceding initialization and either ...
3561 if (Init && Init->isValueDependent()) {
3562 // The DeclRefExpr is not value-dependent, but the variable it refers to
3563 // has a value-dependent initializer. This should only happen in
3564 // constant-folding cases, where the variable is not actually of a suitable
3565 // type for use in a constant expression (otherwise the DeclRefExpr would
3566 // have been value-dependent too), so diagnose that.
3567 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3568 if (!Info.checkingPotentialConstantExpression()) {
3569 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3570 ? diag::note_constexpr_ltor_non_constexpr
3571 : diag::note_constexpr_ltor_non_integral, 1)
3572 << VD << VD->getType();
3573 NoteLValueLocation(Info, Base);
3574 }
3575 return false;
3576 }
3577
3578 // Check that we can fold the initializer. In C++, we will have already done
3579 // this in the cases where it matters for conformance.
3580 // P2280R4 struck the initialization requirement for variables of reference
3581 // type so we can no longer assume we have an Init.
3582 // Used to be C++20 [expr.const]p5.12:
3583 // ... reference has a preceding initialization and either ...
3584 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3585 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3586 NoteLValueLocation(Info, Base);
3587 return false;
3588 }
3589
3590 // Check that the variable is actually usable in constant expressions. For a
3591 // const integral variable or a reference, we might have a non-constant
3592 // initializer that we can nonetheless evaluate the initializer for. Such
3593 // variables are not usable in constant expressions. In C++98, the
3594 // initializer also syntactically needs to be an ICE.
3595 //
3596 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3597 // expressions here; doing so would regress diagnostics for things like
3598 // reading from a volatile constexpr variable.
3599 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3600 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3601 !AllowConstexprUnknown) ||
3602 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3603 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3604 if (Init) {
3605 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3606 NoteLValueLocation(Info, Base);
3607 } else {
3608 Info.CCEDiag(E);
3609 }
3610 }
3611
3612 // Never use the initializer of a weak variable, not even for constant
3613 // folding. We can't be sure that this is the definition that will be used.
3614 if (VD->isWeak()) {
3615 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3616 NoteLValueLocation(Info, Base);
3617 return false;
3618 }
3619
3620 Result = VD->getEvaluatedValue();
3621
3622 if (!Result && !AllowConstexprUnknown)
3623 return false;
3624
3625 return CheckUninitReference(/*IsLocalVariable=*/false);
3626}
3627
3628/// Get the base index of the given base class within an APValue representing
3629/// the given derived class.
3630static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3631 const CXXRecordDecl *Base) {
3632 Base = Base->getCanonicalDecl();
3633 unsigned Index = 0;
3635 E = Derived->bases_end(); I != E; ++I, ++Index) {
3636 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3637 return Index;
3638 }
3639
3640 llvm_unreachable("base class missing from derived class's bases list");
3641}
3642
3643/// Extract the value of a character from a string literal.
3644static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3645 uint64_t Index) {
3646 assert(!isa<SourceLocExpr>(Lit) &&
3647 "SourceLocExpr should have already been converted to a StringLiteral");
3648
3649 // FIXME: Support MakeStringConstant
3650 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3651 std::string Str;
3652 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3653 assert(Index <= Str.size() && "Index too large");
3654 return APSInt::getUnsigned(Str.c_str()[Index]);
3655 }
3656
3657 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3658 Lit = PE->getFunctionName();
3659 const StringLiteral *S = cast<StringLiteral>(Lit);
3660 const ConstantArrayType *CAT =
3661 Info.Ctx.getAsConstantArrayType(S->getType());
3662 assert(CAT && "string literal isn't an array");
3663 QualType CharType = CAT->getElementType();
3664 assert(CharType->isIntegerType() && "unexpected character type");
3665 APSInt Value(Info.Ctx.getTypeSize(CharType),
3666 CharType->isUnsignedIntegerType());
3667 if (Index < S->getLength())
3668 Value = S->getCodeUnit(Index);
3669 return Value;
3670}
3671
3672// Expand a string literal into an array of characters.
3673//
3674// FIXME: This is inefficient; we should probably introduce something similar
3675// to the LLVM ConstantDataArray to make this cheaper.
3676static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3677 APValue &Result,
3678 QualType AllocType = QualType()) {
3679 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3680 AllocType.isNull() ? S->getType() : AllocType);
3681 assert(CAT && "string literal isn't an array");
3682 QualType CharType = CAT->getElementType();
3683 assert(CharType->isIntegerType() && "unexpected character type");
3684
3685 unsigned Elts = CAT->getZExtSize();
3686 Result = APValue(APValue::UninitArray(),
3687 std::min(S->getLength(), Elts), Elts);
3688 APSInt Value(Info.Ctx.getTypeSize(CharType),
3689 CharType->isUnsignedIntegerType());
3690 if (Result.hasArrayFiller())
3691 Result.getArrayFiller() = APValue(Value);
3692 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3693 Value = S->getCodeUnit(I);
3694 Result.getArrayInitializedElt(I) = APValue(Value);
3695 }
3696}
3697
3698// Expand an array so that it has more than Index filled elements.
3699static void expandArray(APValue &Array, unsigned Index) {
3700 unsigned Size = Array.getArraySize();
3701 assert(Index < Size);
3702
3703 // Always at least double the number of elements for which we store a value.
3704 unsigned OldElts = Array.getArrayInitializedElts();
3705 unsigned NewElts = std::max(Index+1, OldElts * 2);
3706 NewElts = std::min(Size, std::max(NewElts, 8u));
3707
3708 // Copy the data across.
3709 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3710 for (unsigned I = 0; I != OldElts; ++I)
3711 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3712 for (unsigned I = OldElts; I != NewElts; ++I)
3713 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3714 if (NewValue.hasArrayFiller())
3715 NewValue.getArrayFiller() = Array.getArrayFiller();
3716 Array.swap(NewValue);
3717}
3718
3719/// Determine whether a type would actually be read by an lvalue-to-rvalue
3720/// conversion. If it's of class type, we may assume that the copy operation
3721/// is trivial. Note that this is never true for a union type with fields
3722/// (because the copy always "reads" the active member) and always true for
3723/// a non-class type.
3724static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3726 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3727 return !RD || isReadByLvalueToRvalueConversion(RD);
3728}
3730 // FIXME: A trivial copy of a union copies the object representation, even if
3731 // the union is empty.
3732 if (RD->isUnion())
3733 return !RD->field_empty();
3734 if (RD->isEmpty())
3735 return false;
3736
3737 for (auto *Field : RD->fields())
3738 if (!Field->isUnnamedBitField() &&
3739 isReadByLvalueToRvalueConversion(Field->getType()))
3740 return true;
3741
3742 for (auto &BaseSpec : RD->bases())
3743 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3744 return true;
3745
3746 return false;
3747}
3748
3749/// Diagnose an attempt to read from any unreadable field within the specified
3750/// type, which might be a class type.
3751static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3752 QualType T) {
3753 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3754 if (!RD)
3755 return false;
3756
3757 if (!RD->hasMutableFields())
3758 return false;
3759
3760 for (auto *Field : RD->fields()) {
3761 // If we're actually going to read this field in some way, then it can't
3762 // be mutable. If we're in a union, then assigning to a mutable field
3763 // (even an empty one) can change the active member, so that's not OK.
3764 // FIXME: Add core issue number for the union case.
3765 if (Field->isMutable() &&
3766 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3767 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3768 Info.Note(Field->getLocation(), diag::note_declared_at);
3769 return true;
3770 }
3771
3772 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3773 return true;
3774 }
3775
3776 for (auto &BaseSpec : RD->bases())
3777 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3778 return true;
3779
3780 // All mutable fields were empty, and thus not actually read.
3781 return false;
3782}
3783
3784static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3786 bool MutableSubobject = false) {
3787 // A temporary or transient heap allocation we created.
3788 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3789 return true;
3790
3791 switch (Info.IsEvaluatingDecl) {
3792 case EvalInfo::EvaluatingDeclKind::None:
3793 return false;
3794
3795 case EvalInfo::EvaluatingDeclKind::Ctor:
3796 // The variable whose initializer we're evaluating.
3797 if (Info.EvaluatingDecl == Base)
3798 return true;
3799
3800 // A temporary lifetime-extended by the variable whose initializer we're
3801 // evaluating.
3802 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3803 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3804 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3805 return false;
3806
3807 case EvalInfo::EvaluatingDeclKind::Dtor:
3808 // C++2a [expr.const]p6:
3809 // [during constant destruction] the lifetime of a and its non-mutable
3810 // subobjects (but not its mutable subobjects) [are] considered to start
3811 // within e.
3812 if (MutableSubobject || Base != Info.EvaluatingDecl)
3813 return false;
3814 // FIXME: We can meaningfully extend this to cover non-const objects, but
3815 // we will need special handling: we should be able to access only
3816 // subobjects of such objects that are themselves declared const.
3818 return T.isConstQualified() || T->isReferenceType();
3819 }
3820
3821 llvm_unreachable("unknown evaluating decl kind");
3822}
3823
3824static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3825 SourceLocation CallLoc = {}) {
3826 return Info.CheckArraySize(
3827 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3828 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3829 /*Diag=*/true);
3830}
3831
3832static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3833 QualType SourceTy, QualType DestTy,
3834 APValue const &Original, APValue &Result) {
3835 // boolean must be checked before integer
3836 // since IsIntegerType() is true for bool
3837 if (SourceTy->isBooleanType()) {
3838 if (DestTy->isBooleanType()) {
3839 Result = Original;
3840 return true;
3841 }
3842 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3843 bool BoolResult;
3844 if (!HandleConversionToBool(Original, BoolResult))
3845 return false;
3846 uint64_t IntResult = BoolResult;
3847 QualType IntType = DestTy->isIntegerType()
3848 ? DestTy
3849 : Info.Ctx.getIntTypeForBitwidth(64, false);
3850 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3851 }
3852 if (DestTy->isRealFloatingType()) {
3853 APValue Result2 = APValue(APFloat(0.0));
3854 if (!HandleIntToFloatCast(Info, E, FPO,
3855 Info.Ctx.getIntTypeForBitwidth(64, false),
3856 Result.getInt(), DestTy, Result2.getFloat()))
3857 return false;
3858 Result = Result2;
3859 }
3860 return true;
3861 }
3862 if (SourceTy->isIntegerType()) {
3863 if (DestTy->isRealFloatingType()) {
3864 Result = APValue(APFloat(0.0));
3865 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3866 DestTy, Result.getFloat());
3867 }
3868 if (DestTy->isBooleanType()) {
3869 bool BoolResult;
3870 if (!HandleConversionToBool(Original, BoolResult))
3871 return false;
3872 uint64_t IntResult = BoolResult;
3873 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3874 return true;
3875 }
3876 if (DestTy->isIntegerType()) {
3877 Result = APValue(
3878 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3879 return true;
3880 }
3881 } else if (SourceTy->isRealFloatingType()) {
3882 if (DestTy->isRealFloatingType()) {
3883 Result = Original;
3884 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3885 Result.getFloat());
3886 }
3887 if (DestTy->isBooleanType()) {
3888 bool BoolResult;
3889 if (!HandleConversionToBool(Original, BoolResult))
3890 return false;
3891 uint64_t IntResult = BoolResult;
3892 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3893 return true;
3894 }
3895 if (DestTy->isIntegerType()) {
3896 Result = APValue(APSInt());
3897 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3898 DestTy, Result.getInt());
3899 }
3900 }
3901
3902 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3903 return false;
3904}
3905
3906// do the heavy lifting for casting to aggregate types
3907// because we have to deal with bitfields specially
3908static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3909 const Expr *E, APValue &Result,
3910 QualType ResultType,
3911 SmallVectorImpl<APValue> &Elements,
3912 SmallVectorImpl<QualType> &ElTypes) {
3913
3915 {&Result, ResultType, 0}};
3916
3917 unsigned ElI = 0;
3918 while (!WorkList.empty() && ElI < Elements.size()) {
3919 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3920
3921 if (Type->isRealFloatingType()) {
3922 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3923 *Res))
3924 return false;
3925 ElI++;
3926 continue;
3927 }
3928 if (Type->isIntegerType()) {
3929 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3930 *Res))
3931 return false;
3932 if (BitWidth > 0) {
3933 if (!Res->isInt())
3934 return false;
3935 APSInt &Int = Res->getInt();
3936 unsigned OldBitWidth = Int.getBitWidth();
3937 unsigned NewBitWidth = BitWidth;
3938 if (NewBitWidth < OldBitWidth)
3939 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3940 }
3941 ElI++;
3942 continue;
3943 }
3944 if (Type->isVectorType()) {
3945 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3946 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3947 SmallVector<APValue> Vals(NumEl);
3948 for (unsigned I = 0; I < NumEl; ++I) {
3949 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3950 Vals[I]))
3951 return false;
3952 ElI++;
3953 }
3954 *Res = APValue(Vals.data(), NumEl);
3955 continue;
3956 }
3957 if (Type->isConstantArrayType()) {
3959 ->getElementType();
3960 uint64_t Size =
3961 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3962 *Res = APValue(APValue::UninitArray(), Size, Size);
3963 for (int64_t I = Size - 1; I > -1; --I)
3964 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3965 continue;
3966 }
3967 if (Type->isRecordType()) {
3968 const RecordDecl *RD = Type->getAsRecordDecl();
3969
3970 unsigned NumBases = 0;
3971 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3972 NumBases = CXXRD->getNumBases();
3973
3974 *Res = APValue(APValue::UninitStruct(), NumBases,
3975 std::distance(RD->field_begin(), RD->field_end()));
3976
3978 // we need to traverse backwards
3979 // Visit the base classes.
3980 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3981 if (CXXRD->getNumBases() > 0) {
3982 assert(CXXRD->getNumBases() == 1);
3983 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3984 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3985 }
3986 }
3987
3988 // Visit the fields.
3989 for (FieldDecl *FD : RD->fields()) {
3990 unsigned FDBW = 0;
3991 if (FD->isUnnamedBitField())
3992 continue;
3993 if (FD->isBitField()) {
3994 FDBW = FD->getBitWidthValue();
3995 }
3996
3997 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3998 FD->getType(), FDBW);
3999 }
4000
4001 std::reverse(ReverseList.begin(), ReverseList.end());
4002 llvm::append_range(WorkList, ReverseList);
4003 continue;
4004 }
4005 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4006 return false;
4007 }
4008 return true;
4009}
4010
4011static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4012 const FPOptions FPO,
4013 SmallVectorImpl<APValue> &Elements,
4014 SmallVectorImpl<QualType> &SrcTypes,
4015 SmallVectorImpl<QualType> &DestTypes,
4016 SmallVectorImpl<APValue> &Results) {
4017
4018 assert((Elements.size() == SrcTypes.size()) &&
4019 (Elements.size() == DestTypes.size()));
4020
4021 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4022 APValue Original = Elements[I];
4023 QualType SourceTy = SrcTypes[I];
4024 QualType DestTy = DestTypes[I];
4025
4026 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4027 return false;
4028 }
4029 return true;
4030}
4031
4032static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4033
4034 SmallVector<QualType> WorkList = {BaseTy};
4035
4036 unsigned Size = 0;
4037 while (!WorkList.empty()) {
4038 QualType Type = WorkList.pop_back_val();
4040 Type->isBooleanType()) {
4041 ++Size;
4042 continue;
4043 }
4044 if (Type->isVectorType()) {
4045 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4046 Size += NumEl;
4047 continue;
4048 }
4049 if (Type->isConstantArrayType()) {
4051 ->getElementType();
4052 uint64_t ArrSize =
4053 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4054 for (uint64_t I = 0; I < ArrSize; ++I) {
4055 WorkList.push_back(ElTy);
4056 }
4057 continue;
4058 }
4059 if (Type->isRecordType()) {
4060 const RecordDecl *RD = Type->getAsRecordDecl();
4061
4062 // Visit the base classes.
4063 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4064 if (CXXRD->getNumBases() > 0) {
4065 assert(CXXRD->getNumBases() == 1);
4066 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4067 WorkList.push_back(BS.getType());
4068 }
4069 }
4070
4071 // visit the fields.
4072 for (FieldDecl *FD : RD->fields()) {
4073 if (FD->isUnnamedBitField())
4074 continue;
4075 WorkList.push_back(FD->getType());
4076 }
4077 continue;
4078 }
4079 }
4080 return Size;
4081}
4082
4083static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4084 QualType &SrcTy) {
4085 SrcTy = E->getType();
4086
4087 if (!Evaluate(SrcVal, Info, E))
4088 return false;
4089
4090 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4091 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4092 "Not a valid HLSLAggregateSplatCast.");
4093
4094 if (SrcVal.isVector()) {
4095 assert(SrcTy->isVectorType() && "Type mismatch.");
4096 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4097 SrcVal = SrcVal.getVectorElt(0);
4098 }
4099 return true;
4100}
4101
4102static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4103 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4104 SmallVectorImpl<QualType> &Types, unsigned Size) {
4105
4106 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4107 unsigned Populated = 0;
4108 while (!WorkList.empty() && Populated < Size) {
4109 auto [Work, Type] = WorkList.pop_back_val();
4110
4111 if (Work.isFloat() || Work.isInt()) {
4112 Elements.push_back(Work);
4113 Types.push_back(Type);
4114 Populated++;
4115 continue;
4116 }
4117 if (Work.isVector()) {
4118 assert(Type->isVectorType() && "Type mismatch.");
4119 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4120 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4121 I++) {
4122 Elements.push_back(Work.getVectorElt(I));
4123 Types.push_back(ElTy);
4124 Populated++;
4125 }
4126 continue;
4127 }
4128 if (Work.isArray()) {
4129 assert(Type->isConstantArrayType() && "Type mismatch.");
4131 ->getElementType();
4132 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4133 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4134 }
4135 continue;
4136 }
4137
4138 if (Work.isStruct()) {
4139 assert(Type->isRecordType() && "Type mismatch.");
4140
4141 const RecordDecl *RD = Type->getAsRecordDecl();
4142
4144 // Visit the fields.
4145 for (FieldDecl *FD : RD->fields()) {
4146 if (FD->isUnnamedBitField())
4147 continue;
4148 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4149 FD->getType());
4150 }
4151
4152 std::reverse(ReverseList.begin(), ReverseList.end());
4153 llvm::append_range(WorkList, ReverseList);
4154
4155 // Visit the base classes.
4156 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4157 if (CXXRD->getNumBases() > 0) {
4158 assert(CXXRD->getNumBases() == 1);
4159 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4160 const APValue &Base = Work.getStructBase(0);
4161
4162 // Can happen in error cases.
4163 if (!Base.isStruct())
4164 return false;
4165
4166 WorkList.emplace_back(Base, BS.getType());
4167 }
4168 }
4169 continue;
4170 }
4171 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4172 return false;
4173 }
4174 return true;
4175}
4176
4177namespace {
4178/// A handle to a complete object (an object that is not a subobject of
4179/// another object).
4180struct CompleteObject {
4181 /// The identity of the object.
4182 APValue::LValueBase Base;
4183 /// The value of the complete object.
4184 APValue *Value;
4185 /// The type of the complete object.
4186 QualType Type;
4187
4188 CompleteObject() : Value(nullptr) {}
4189 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4190 : Base(Base), Value(Value), Type(Type) {}
4191
4192 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4193 // If this isn't a "real" access (eg, if it's just accessing the type
4194 // info), allow it. We assume the type doesn't change dynamically for
4195 // subobjects of constexpr objects (even though we'd hit UB here if it
4196 // did). FIXME: Is this right?
4197 if (!isAnyAccess(AK))
4198 return true;
4199
4200 // In C++14 onwards, it is permitted to read a mutable member whose
4201 // lifetime began within the evaluation.
4202 // FIXME: Should we also allow this in C++11?
4203 if (!Info.getLangOpts().CPlusPlus14 &&
4204 AK != AccessKinds::AK_IsWithinLifetime)
4205 return false;
4206 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4207 }
4208
4209 explicit operator bool() const { return !Type.isNull(); }
4210};
4211} // end anonymous namespace
4212
4213static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4214 bool IsMutable = false) {
4215 // C++ [basic.type.qualifier]p1:
4216 // - A const object is an object of type const T or a non-mutable subobject
4217 // of a const object.
4218 if (ObjType.isConstQualified() && !IsMutable)
4219 SubobjType.addConst();
4220 // - A volatile object is an object of type const T or a subobject of a
4221 // volatile object.
4222 if (ObjType.isVolatileQualified())
4223 SubobjType.addVolatile();
4224 return SubobjType;
4225}
4226
4227/// Find the designated sub-object of an rvalue.
4228template <typename SubobjectHandler>
4229static typename SubobjectHandler::result_type
4230findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4231 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4232 if (Sub.Invalid)
4233 // A diagnostic will have already been produced.
4234 return handler.failed();
4235 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4236 if (Info.getLangOpts().CPlusPlus11)
4237 Info.FFDiag(E, Sub.isOnePastTheEnd()
4238 ? diag::note_constexpr_access_past_end
4239 : diag::note_constexpr_access_unsized_array)
4240 << handler.AccessKind;
4241 else
4242 Info.FFDiag(E);
4243 return handler.failed();
4244 }
4245
4246 APValue *O = Obj.Value;
4247 QualType ObjType = Obj.Type;
4248 const FieldDecl *LastField = nullptr;
4249 const FieldDecl *VolatileField = nullptr;
4250
4251 // Walk the designator's path to find the subobject.
4252 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4253 // Reading an indeterminate value is undefined, but assigning over one is OK.
4254 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4255 (O->isIndeterminate() &&
4256 !isValidIndeterminateAccess(handler.AccessKind))) {
4257 // Object has ended lifetime.
4258 // If I is non-zero, some subobject (member or array element) of a
4259 // complete object has ended its lifetime, so this is valid for
4260 // IsWithinLifetime, resulting in false.
4261 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4262 return false;
4263 if (!Info.checkingPotentialConstantExpression())
4264 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4265 << handler.AccessKind << O->isIndeterminate()
4266 << E->getSourceRange();
4267 return handler.failed();
4268 }
4269
4270 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4271 // const and volatile semantics are not applied on an object under
4272 // {con,de}struction.
4273 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4274 ObjType->isRecordType() &&
4275 Info.isEvaluatingCtorDtor(
4276 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4277 ConstructionPhase::None) {
4278 ObjType = Info.Ctx.getCanonicalType(ObjType);
4279 ObjType.removeLocalConst();
4280 ObjType.removeLocalVolatile();
4281 }
4282
4283 // If this is our last pass, check that the final object type is OK.
4284 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4285 // Accesses to volatile objects are prohibited.
4286 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4287 if (Info.getLangOpts().CPlusPlus) {
4288 int DiagKind;
4289 SourceLocation Loc;
4290 const NamedDecl *Decl = nullptr;
4291 if (VolatileField) {
4292 DiagKind = 2;
4293 Loc = VolatileField->getLocation();
4294 Decl = VolatileField;
4295 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4296 DiagKind = 1;
4297 Loc = VD->getLocation();
4298 Decl = VD;
4299 } else {
4300 DiagKind = 0;
4301 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4302 Loc = E->getExprLoc();
4303 }
4304 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4305 << handler.AccessKind << DiagKind << Decl;
4306 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4307 } else {
4308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4309 }
4310 return handler.failed();
4311 }
4312
4313 // If we are reading an object of class type, there may still be more
4314 // things we need to check: if there are any mutable subobjects, we
4315 // cannot perform this read. (This only happens when performing a trivial
4316 // copy or assignment.)
4317 if (ObjType->isRecordType() &&
4318 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4319 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4320 return handler.failed();
4321 }
4322
4323 if (I == N) {
4324 if (!handler.found(*O, ObjType))
4325 return false;
4326
4327 // If we modified a bit-field, truncate it to the right width.
4328 if (isModification(handler.AccessKind) &&
4329 LastField && LastField->isBitField() &&
4330 !truncateBitfieldValue(Info, E, *O, LastField))
4331 return false;
4332
4333 return true;
4334 }
4335
4336 LastField = nullptr;
4337 if (ObjType->isArrayType()) {
4338 // Next subobject is an array element.
4339 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4341 "vla in literal type?");
4342 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4343 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4344 CAT && CAT->getSize().ule(Index)) {
4345 // Note, it should not be possible to form a pointer with a valid
4346 // designator which points more than one past the end of the array.
4347 if (Info.getLangOpts().CPlusPlus11)
4348 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4349 << handler.AccessKind;
4350 else
4351 Info.FFDiag(E);
4352 return handler.failed();
4353 }
4354
4355 ObjType = AT->getElementType();
4356
4357 if (O->getArrayInitializedElts() > Index)
4358 O = &O->getArrayInitializedElt(Index);
4359 else if (!isRead(handler.AccessKind)) {
4360 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4361 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4362 return handler.failed();
4363
4364 expandArray(*O, Index);
4365 O = &O->getArrayInitializedElt(Index);
4366 } else
4367 O = &O->getArrayFiller();
4368 } else if (ObjType->isAnyComplexType()) {
4369 // Next subobject is a complex number.
4370 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4371 if (Index > 1) {
4372 if (Info.getLangOpts().CPlusPlus11)
4373 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4374 << handler.AccessKind;
4375 else
4376 Info.FFDiag(E);
4377 return handler.failed();
4378 }
4379
4380 ObjType = getSubobjectType(
4381 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4382
4383 assert(I == N - 1 && "extracting subobject of scalar?");
4384 if (O->isComplexInt()) {
4385 return handler.found(Index ? O->getComplexIntImag()
4386 : O->getComplexIntReal(), ObjType);
4387 } else {
4388 assert(O->isComplexFloat());
4389 return handler.found(Index ? O->getComplexFloatImag()
4390 : O->getComplexFloatReal(), ObjType);
4391 }
4392 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4393 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4394 unsigned NumElements = VT->getNumElements();
4395 if (Index == NumElements) {
4396 if (Info.getLangOpts().CPlusPlus11)
4397 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4398 << handler.AccessKind;
4399 else
4400 Info.FFDiag(E);
4401 return handler.failed();
4402 }
4403
4404 if (Index > NumElements) {
4405 Info.CCEDiag(E, diag::note_constexpr_array_index)
4406 << Index << /*array*/ 0 << NumElements;
4407 return handler.failed();
4408 }
4409
4410 ObjType = VT->getElementType();
4411 assert(I == N - 1 && "extracting subobject of scalar?");
4412 return handler.found(O->getVectorElt(Index), ObjType);
4413 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4414 if (Field->isMutable() &&
4415 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4416 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4417 << handler.AccessKind << Field;
4418 Info.Note(Field->getLocation(), diag::note_declared_at);
4419 return handler.failed();
4420 }
4421
4422 // Next subobject is a class, struct or union field.
4423 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4424 if (RD->isUnion()) {
4425 const FieldDecl *UnionField = O->getUnionField();
4426 if (!UnionField ||
4427 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4428 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4429 // Placement new onto an inactive union member makes it active.
4430 O->setUnion(Field, APValue());
4431 } else {
4432 // Pointer to/into inactive union member: Not within lifetime
4433 if (handler.AccessKind == AK_IsWithinLifetime)
4434 return false;
4435 // FIXME: If O->getUnionValue() is absent, report that there's no
4436 // active union member rather than reporting the prior active union
4437 // member. We'll need to fix nullptr_t to not use APValue() as its
4438 // representation first.
4439 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4440 << handler.AccessKind << Field << !UnionField << UnionField;
4441 return handler.failed();
4442 }
4443 }
4444 O = &O->getUnionValue();
4445 } else
4446 O = &O->getStructField(Field->getFieldIndex());
4447
4448 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4449 LastField = Field;
4450 if (Field->getType().isVolatileQualified())
4451 VolatileField = Field;
4452 } else {
4453 // Next subobject is a base class.
4454 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4455 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4456 O = &O->getStructBase(getBaseIndex(Derived, Base));
4457
4458 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4459 }
4460 }
4461}
4462
4463namespace {
4464struct ExtractSubobjectHandler {
4465 EvalInfo &Info;
4466 const Expr *E;
4467 APValue &Result;
4468 const AccessKinds AccessKind;
4469
4470 typedef bool result_type;
4471 bool failed() { return false; }
4472 bool found(APValue &Subobj, QualType SubobjType) {
4473 Result = Subobj;
4474 if (AccessKind == AK_ReadObjectRepresentation)
4475 return true;
4476 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4477 }
4478 bool found(APSInt &Value, QualType SubobjType) {
4479 Result = APValue(Value);
4480 return true;
4481 }
4482 bool found(APFloat &Value, QualType SubobjType) {
4483 Result = APValue(Value);
4484 return true;
4485 }
4486};
4487} // end anonymous namespace
4488
4489/// Extract the designated sub-object of an rvalue.
4490static bool extractSubobject(EvalInfo &Info, const Expr *E,
4491 const CompleteObject &Obj,
4492 const SubobjectDesignator &Sub, APValue &Result,
4493 AccessKinds AK = AK_Read) {
4494 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4495 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4496 return findSubobject(Info, E, Obj, Sub, Handler);
4497}
4498
4499namespace {
4500struct ModifySubobjectHandler {
4501 EvalInfo &Info;
4502 APValue &NewVal;
4503 const Expr *E;
4504
4505 typedef bool result_type;
4506 static const AccessKinds AccessKind = AK_Assign;
4507
4508 bool checkConst(QualType QT) {
4509 // Assigning to a const object has undefined behavior.
4510 if (QT.isConstQualified()) {
4511 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4512 return false;
4513 }
4514 return true;
4515 }
4516
4517 bool failed() { return false; }
4518 bool found(APValue &Subobj, QualType SubobjType) {
4519 if (!checkConst(SubobjType))
4520 return false;
4521 // We've been given ownership of NewVal, so just swap it in.
4522 Subobj.swap(NewVal);
4523 return true;
4524 }
4525 bool found(APSInt &Value, QualType SubobjType) {
4526 if (!checkConst(SubobjType))
4527 return false;
4528 if (!NewVal.isInt()) {
4529 // Maybe trying to write a cast pointer value into a complex?
4530 Info.FFDiag(E);
4531 return false;
4532 }
4533 Value = NewVal.getInt();
4534 return true;
4535 }
4536 bool found(APFloat &Value, QualType SubobjType) {
4537 if (!checkConst(SubobjType))
4538 return false;
4539 Value = NewVal.getFloat();
4540 return true;
4541 }
4542};
4543} // end anonymous namespace
4544
4545const AccessKinds ModifySubobjectHandler::AccessKind;
4546
4547/// Update the designated sub-object of an rvalue to the given value.
4548static bool modifySubobject(EvalInfo &Info, const Expr *E,
4549 const CompleteObject &Obj,
4550 const SubobjectDesignator &Sub,
4551 APValue &NewVal) {
4552 ModifySubobjectHandler Handler = { Info, NewVal, E };
4553 return findSubobject(Info, E, Obj, Sub, Handler);
4554}
4555
4556/// Find the position where two subobject designators diverge, or equivalently
4557/// the length of the common initial subsequence.
4558static unsigned FindDesignatorMismatch(QualType ObjType,
4559 const SubobjectDesignator &A,
4560 const SubobjectDesignator &B,
4561 bool &WasArrayIndex) {
4562 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4563 for (/**/; I != N; ++I) {
4564 if (!ObjType.isNull() &&
4565 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4566 // Next subobject is an array element.
4567 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4568 WasArrayIndex = true;
4569 return I;
4570 }
4571 if (ObjType->isAnyComplexType())
4572 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4573 else
4574 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4575 } else {
4576 if (A.Entries[I].getAsBaseOrMember() !=
4577 B.Entries[I].getAsBaseOrMember()) {
4578 WasArrayIndex = false;
4579 return I;
4580 }
4581 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4582 // Next subobject is a field.
4583 ObjType = FD->getType();
4584 else
4585 // Next subobject is a base class.
4586 ObjType = QualType();
4587 }
4588 }
4589 WasArrayIndex = false;
4590 return I;
4591}
4592
4593/// Determine whether the given subobject designators refer to elements of the
4594/// same array object.
4596 const SubobjectDesignator &A,
4597 const SubobjectDesignator &B) {
4598 if (A.Entries.size() != B.Entries.size())
4599 return false;
4600
4601 bool IsArray = A.MostDerivedIsArrayElement;
4602 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4603 // A is a subobject of the array element.
4604 return false;
4605
4606 // If A (and B) designates an array element, the last entry will be the array
4607 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4608 // of length 1' case, and the entire path must match.
4609 bool WasArrayIndex;
4610 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4611 return CommonLength >= A.Entries.size() - IsArray;
4612}
4613
4614/// Find the complete object to which an LValue refers.
4615static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4616 AccessKinds AK, const LValue &LVal,
4617 QualType LValType) {
4618 if (LVal.InvalidBase) {
4619 Info.FFDiag(E);
4620 return CompleteObject();
4621 }
4622
4623 if (!LVal.Base) {
4625 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4626 else
4627 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4628 return CompleteObject();
4629 }
4630
4631 CallStackFrame *Frame = nullptr;
4632 unsigned Depth = 0;
4633 if (LVal.getLValueCallIndex()) {
4634 std::tie(Frame, Depth) =
4635 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4636 if (!Frame) {
4637 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4638 << AK << LVal.Base.is<const ValueDecl*>();
4639 NoteLValueLocation(Info, LVal.Base);
4640 return CompleteObject();
4641 }
4642 }
4643
4644 bool IsAccess = isAnyAccess(AK);
4645
4646 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4647 // is not a constant expression (even if the object is non-volatile). We also
4648 // apply this rule to C++98, in order to conform to the expected 'volatile'
4649 // semantics.
4650 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4651 if (Info.getLangOpts().CPlusPlus)
4652 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4653 << AK << LValType;
4654 else
4655 Info.FFDiag(E);
4656 return CompleteObject();
4657 }
4658
4659 // Compute value storage location and type of base object.
4660 APValue *BaseVal = nullptr;
4661 QualType BaseType = getType(LVal.Base);
4662
4663 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4664 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4665 // This is the object whose initializer we're evaluating, so its lifetime
4666 // started in the current evaluation.
4667 BaseVal = Info.EvaluatingDeclValue;
4668 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4669 // Allow reading from a GUID declaration.
4670 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4671 if (isModification(AK)) {
4672 // All the remaining cases do not permit modification of the object.
4673 Info.FFDiag(E, diag::note_constexpr_modify_global);
4674 return CompleteObject();
4675 }
4676 APValue &V = GD->getAsAPValue();
4677 if (V.isAbsent()) {
4678 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4679 << GD->getType();
4680 return CompleteObject();
4681 }
4682 return CompleteObject(LVal.Base, &V, GD->getType());
4683 }
4684
4685 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4686 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4687 if (isModification(AK)) {
4688 Info.FFDiag(E, diag::note_constexpr_modify_global);
4689 return CompleteObject();
4690 }
4691 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4692 GCD->getType());
4693 }
4694
4695 // Allow reading from template parameter objects.
4696 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4697 if (isModification(AK)) {
4698 Info.FFDiag(E, diag::note_constexpr_modify_global);
4699 return CompleteObject();
4700 }
4701 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4702 TPO->getType());
4703 }
4704
4705 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4706 // In C++11, constexpr, non-volatile variables initialized with constant
4707 // expressions are constant expressions too. Inside constexpr functions,
4708 // parameters are constant expressions even if they're non-const.
4709 // In C++1y, objects local to a constant expression (those with a Frame) are
4710 // both readable and writable inside constant expressions.
4711 // In C, such things can also be folded, although they are not ICEs.
4712 const VarDecl *VD = dyn_cast<VarDecl>(D);
4713 if (VD) {
4714 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4715 VD = VDef;
4716 }
4717 if (!VD || VD->isInvalidDecl()) {
4718 Info.FFDiag(E);
4719 return CompleteObject();
4720 }
4721
4722 bool IsConstant = BaseType.isConstant(Info.Ctx);
4723 bool ConstexprVar = false;
4724 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4725 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4726 ConstexprVar = VD->isConstexpr();
4727
4728 // Unless we're looking at a local variable or argument in a constexpr call,
4729 // the variable we're reading must be const (unless we are binding to a
4730 // reference).
4731 if (AK != clang::AK_Dereference && !Frame) {
4732 if (IsAccess && isa<ParmVarDecl>(VD)) {
4733 // Access of a parameter that's not associated with a frame isn't going
4734 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4735 // suitable diagnostic.
4736 } else if (Info.getLangOpts().CPlusPlus14 &&
4737 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4738 // OK, we can read and modify an object if we're in the process of
4739 // evaluating its initializer, because its lifetime began in this
4740 // evaluation.
4741 } else if (isModification(AK)) {
4742 // All the remaining cases do not permit modification of the object.
4743 Info.FFDiag(E, diag::note_constexpr_modify_global);
4744 return CompleteObject();
4745 } else if (VD->isConstexpr()) {
4746 // OK, we can read this variable.
4747 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4748 Info.FFDiag(E);
4749 return CompleteObject();
4750 } else if (BaseType->isIntegralOrEnumerationType()) {
4751 if (!IsConstant) {
4752 if (!IsAccess)
4753 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4754 if (Info.getLangOpts().CPlusPlus) {
4755 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4756 Info.Note(VD->getLocation(), diag::note_declared_at);
4757 } else {
4758 Info.FFDiag(E);
4759 }
4760 return CompleteObject();
4761 }
4762 } else if (!IsAccess) {
4763 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4764 } else if ((IsConstant || BaseType->isReferenceType()) &&
4765 Info.checkingPotentialConstantExpression() &&
4766 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4767 // This variable might end up being constexpr. Don't diagnose it yet.
4768 } else if (IsConstant) {
4769 // Keep evaluating to see what we can do. In particular, we support
4770 // folding of const floating-point types, in order to make static const
4771 // data members of such types (supported as an extension) more useful.
4772 if (Info.getLangOpts().CPlusPlus) {
4773 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4774 ? diag::note_constexpr_ltor_non_constexpr
4775 : diag::note_constexpr_ltor_non_integral, 1)
4776 << VD << BaseType;
4777 Info.Note(VD->getLocation(), diag::note_declared_at);
4778 } else {
4779 Info.CCEDiag(E);
4780 }
4781 } else {
4782 // Never allow reading a non-const value.
4783 if (Info.getLangOpts().CPlusPlus) {
4784 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4785 ? diag::note_constexpr_ltor_non_constexpr
4786 : diag::note_constexpr_ltor_non_integral, 1)
4787 << VD << BaseType;
4788 Info.Note(VD->getLocation(), diag::note_declared_at);
4789 } else {
4790 Info.FFDiag(E);
4791 }
4792 return CompleteObject();
4793 }
4794 }
4795
4796 // When binding to a reference, the variable does not need to be constexpr
4797 // or have constant initalization.
4798 if (AK != clang::AK_Dereference &&
4799 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4800 BaseVal))
4801 return CompleteObject();
4802 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4803 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4804 // we can't access a constexpr-unknown object.
4805 if (AK != clang::AK_Dereference && !BaseVal) {
4806 if (!Info.checkingPotentialConstantExpression()) {
4807 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4808 << AK << VD;
4809 Info.Note(VD->getLocation(), diag::note_declared_at);
4810 }
4811 return CompleteObject();
4812 }
4813 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4814 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4815 if (!Alloc) {
4816 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4817 return CompleteObject();
4818 }
4819 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4820 LVal.Base.getDynamicAllocType());
4821 }
4822 // When binding to a reference, the variable does not need to be
4823 // within its lifetime.
4824 else if (AK != clang::AK_Dereference) {
4825 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4826
4827 if (!Frame) {
4828 if (const MaterializeTemporaryExpr *MTE =
4829 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4830 assert(MTE->getStorageDuration() == SD_Static &&
4831 "should have a frame for a non-global materialized temporary");
4832
4833 // C++20 [expr.const]p4: [DR2126]
4834 // An object or reference is usable in constant expressions if it is
4835 // - a temporary object of non-volatile const-qualified literal type
4836 // whose lifetime is extended to that of a variable that is usable
4837 // in constant expressions
4838 //
4839 // C++20 [expr.const]p5:
4840 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4841 // - a non-volatile glvalue that refers to an object that is usable
4842 // in constant expressions, or
4843 // - a non-volatile glvalue of literal type that refers to a
4844 // non-volatile object whose lifetime began within the evaluation
4845 // of E;
4846 //
4847 // C++11 misses the 'began within the evaluation of e' check and
4848 // instead allows all temporaries, including things like:
4849 // int &&r = 1;
4850 // int x = ++r;
4851 // constexpr int k = r;
4852 // Therefore we use the C++14-onwards rules in C++11 too.
4853 //
4854 // Note that temporaries whose lifetimes began while evaluating a
4855 // variable's constructor are not usable while evaluating the
4856 // corresponding destructor, not even if they're of const-qualified
4857 // types.
4858 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4859 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4860 if (!IsAccess)
4861 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4862 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4863 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4864 return CompleteObject();
4865 }
4866
4867 BaseVal = MTE->getOrCreateValue(false);
4868 assert(BaseVal && "got reference to unevaluated temporary");
4869 } else if (const CompoundLiteralExpr *CLE =
4870 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4871 // According to GCC info page:
4872 //
4873 // 6.28 Compound Literals
4874 //
4875 // As an optimization, G++ sometimes gives array compound literals
4876 // longer lifetimes: when the array either appears outside a function or
4877 // has a const-qualified type. If foo and its initializer had elements
4878 // of type char *const rather than char *, or if foo were a global
4879 // variable, the array would have static storage duration. But it is
4880 // probably safest just to avoid the use of array compound literals in
4881 // C++ code.
4882 //
4883 // Obey that rule by checking constness for converted array types.
4884 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4885 !LValType->isArrayType() &&
4886 !CLETy.isConstant(Info.Ctx)) {
4887 Info.FFDiag(E);
4888 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4889 return CompleteObject();
4890 }
4891
4892 BaseVal = &CLE->getStaticValue();
4893 } else {
4894 if (!IsAccess)
4895 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4896 APValue Val;
4897 LVal.moveInto(Val);
4898 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4899 << AK
4900 << Val.getAsString(Info.Ctx,
4901 Info.Ctx.getLValueReferenceType(LValType));
4902 NoteLValueLocation(Info, LVal.Base);
4903 return CompleteObject();
4904 }
4905 } else if (AK != clang::AK_Dereference) {
4906 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4907 assert(BaseVal && "missing value for temporary");
4908 }
4909 }
4910
4911 // In C++14, we can't safely access any mutable state when we might be
4912 // evaluating after an unmodeled side effect. Parameters are modeled as state
4913 // in the caller, but aren't visible once the call returns, so they can be
4914 // modified in a speculatively-evaluated call.
4915 //
4916 // FIXME: Not all local state is mutable. Allow local constant subobjects
4917 // to be read here (but take care with 'mutable' fields).
4918 unsigned VisibleDepth = Depth;
4919 if (llvm::isa_and_nonnull<ParmVarDecl>(
4920 LVal.Base.dyn_cast<const ValueDecl *>()))
4921 ++VisibleDepth;
4922 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4923 Info.EvalStatus.HasSideEffects) ||
4924 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4925 return CompleteObject();
4926
4927 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4928}
4929
4930/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4931/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4932/// glvalue referred to by an entity of reference type.
4933///
4934/// \param Info - Information about the ongoing evaluation.
4935/// \param Conv - The expression for which we are performing the conversion.
4936/// Used for diagnostics.
4937/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4938/// case of a non-class type).
4939/// \param LVal - The glvalue on which we are attempting to perform this action.
4940/// \param RVal - The produced value will be placed here.
4941/// \param WantObjectRepresentation - If true, we're looking for the object
4942/// representation rather than the value, and in particular,
4943/// there is no requirement that the result be fully initialized.
4944static bool
4946 const LValue &LVal, APValue &RVal,
4947 bool WantObjectRepresentation = false) {
4948 if (LVal.Designator.Invalid)
4949 return false;
4950
4951 // Check for special cases where there is no existing APValue to look at.
4952 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4953
4954 AccessKinds AK =
4955 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4956
4957 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4959 // Special-case character extraction so we don't have to construct an
4960 // APValue for the whole string.
4961 assert(LVal.Designator.Entries.size() <= 1 &&
4962 "Can only read characters from string literals");
4963 if (LVal.Designator.Entries.empty()) {
4964 // Fail for now for LValue to RValue conversion of an array.
4965 // (This shouldn't show up in C/C++, but it could be triggered by a
4966 // weird EvaluateAsRValue call from a tool.)
4967 Info.FFDiag(Conv);
4968 return false;
4969 }
4970 if (LVal.Designator.isOnePastTheEnd()) {
4971 if (Info.getLangOpts().CPlusPlus11)
4972 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4973 else
4974 Info.FFDiag(Conv);
4975 return false;
4976 }
4977 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4978 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4979 return true;
4980 }
4981 }
4982
4983 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4984 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4985}
4986
4987static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4988 QualType DestTy,
4989 SmallVectorImpl<APValue> &SrcVals,
4990 SmallVectorImpl<QualType> &SrcTypes) {
4991 APValue Val;
4992 if (!Evaluate(Val, Info, E))
4993 return false;
4994
4995 // must be dealing with a record
4996 if (Val.isLValue()) {
4997 LValue LVal;
4998 LVal.setFrom(Info.Ctx, Val);
4999 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5000 return false;
5001 }
5002
5003 unsigned NEls = elementwiseSize(Info, DestTy);
5004 // flatten the source
5005 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5006 return false;
5007
5008 return true;
5009}
5010
5011/// Perform an assignment of Val to LVal. Takes ownership of Val.
5012static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5013 QualType LValType, APValue &Val) {
5014 if (LVal.Designator.Invalid)
5015 return false;
5016
5017 if (!Info.getLangOpts().CPlusPlus14) {
5018 Info.FFDiag(E);
5019 return false;
5020 }
5021
5022 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5023 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5024}
5025
5026namespace {
5027struct CompoundAssignSubobjectHandler {
5028 EvalInfo &Info;
5029 const CompoundAssignOperator *E;
5030 QualType PromotedLHSType;
5032 const APValue &RHS;
5033
5034 static const AccessKinds AccessKind = AK_Assign;
5035
5036 typedef bool result_type;
5037
5038 bool checkConst(QualType QT) {
5039 // Assigning to a const object has undefined behavior.
5040 if (QT.isConstQualified()) {
5041 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5042 return false;
5043 }
5044 return true;
5045 }
5046
5047 bool failed() { return false; }
5048 bool found(APValue &Subobj, QualType SubobjType) {
5049 switch (Subobj.getKind()) {
5050 case APValue::Int:
5051 return found(Subobj.getInt(), SubobjType);
5052 case APValue::Float:
5053 return found(Subobj.getFloat(), SubobjType);
5056 // FIXME: Implement complex compound assignment.
5057 Info.FFDiag(E);
5058 return false;
5059 case APValue::LValue:
5060 return foundPointer(Subobj, SubobjType);
5061 case APValue::Vector:
5062 return foundVector(Subobj, SubobjType);
5064 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5065 << /*read of=*/0 << /*uninitialized object=*/1
5066 << E->getLHS()->getSourceRange();
5067 return false;
5068 default:
5069 // FIXME: can this happen?
5070 Info.FFDiag(E);
5071 return false;
5072 }
5073 }
5074
5075 bool foundVector(APValue &Value, QualType SubobjType) {
5076 if (!checkConst(SubobjType))
5077 return false;
5078
5079 if (!SubobjType->isVectorType()) {
5080 Info.FFDiag(E);
5081 return false;
5082 }
5083 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5084 }
5085
5086 bool found(APSInt &Value, QualType SubobjType) {
5087 if (!checkConst(SubobjType))
5088 return false;
5089
5090 if (!SubobjType->isIntegerType()) {
5091 // We don't support compound assignment on integer-cast-to-pointer
5092 // values.
5093 Info.FFDiag(E);
5094 return false;
5095 }
5096
5097 if (RHS.isInt()) {
5098 APSInt LHS =
5099 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5100 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5101 return false;
5102 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5103 return true;
5104 } else if (RHS.isFloat()) {
5105 const FPOptions FPO = E->getFPFeaturesInEffect(
5106 Info.Ctx.getLangOpts());
5107 APFloat FValue(0.0);
5108 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5109 PromotedLHSType, FValue) &&
5110 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5111 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5112 Value);
5113 }
5114
5115 Info.FFDiag(E);
5116 return false;
5117 }
5118 bool found(APFloat &Value, QualType SubobjType) {
5119 return checkConst(SubobjType) &&
5120 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5121 Value) &&
5122 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5123 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5124 }
5125 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5126 if (!checkConst(SubobjType))
5127 return false;
5128
5129 QualType PointeeType;
5130 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5131 PointeeType = PT->getPointeeType();
5132
5133 if (PointeeType.isNull() || !RHS.isInt() ||
5134 (Opcode != BO_Add && Opcode != BO_Sub)) {
5135 Info.FFDiag(E);
5136 return false;
5137 }
5138
5139 APSInt Offset = RHS.getInt();
5140 if (Opcode == BO_Sub)
5141 negateAsSigned(Offset);
5142
5143 LValue LVal;
5144 LVal.setFrom(Info.Ctx, Subobj);
5145 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5146 return false;
5147 LVal.moveInto(Subobj);
5148 return true;
5149 }
5150};
5151} // end anonymous namespace
5152
5153const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5154
5155/// Perform a compound assignment of LVal <op>= RVal.
5156static bool handleCompoundAssignment(EvalInfo &Info,
5157 const CompoundAssignOperator *E,
5158 const LValue &LVal, QualType LValType,
5159 QualType PromotedLValType,
5160 BinaryOperatorKind Opcode,
5161 const APValue &RVal) {
5162 if (LVal.Designator.Invalid)
5163 return false;
5164
5165 if (!Info.getLangOpts().CPlusPlus14) {
5166 Info.FFDiag(E);
5167 return false;
5168 }
5169
5170 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5171 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5172 RVal };
5173 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5174}
5175
5176namespace {
5177struct IncDecSubobjectHandler {
5178 EvalInfo &Info;
5179 const UnaryOperator *E;
5181 APValue *Old;
5182
5183 typedef bool result_type;
5184
5185 bool checkConst(QualType QT) {
5186 // Assigning to a const object has undefined behavior.
5187 if (QT.isConstQualified()) {
5188 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5189 return false;
5190 }
5191 return true;
5192 }
5193
5194 bool failed() { return false; }
5195 bool found(APValue &Subobj, QualType SubobjType) {
5196 // Stash the old value. Also clear Old, so we don't clobber it later
5197 // if we're post-incrementing a complex.
5198 if (Old) {
5199 *Old = Subobj;
5200 Old = nullptr;
5201 }
5202
5203 switch (Subobj.getKind()) {
5204 case APValue::Int:
5205 return found(Subobj.getInt(), SubobjType);
5206 case APValue::Float:
5207 return found(Subobj.getFloat(), SubobjType);
5209 return found(Subobj.getComplexIntReal(),
5210 SubobjType->castAs<ComplexType>()->getElementType()
5211 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5213 return found(Subobj.getComplexFloatReal(),
5214 SubobjType->castAs<ComplexType>()->getElementType()
5215 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5216 case APValue::LValue:
5217 return foundPointer(Subobj, SubobjType);
5218 default:
5219 // FIXME: can this happen?
5220 Info.FFDiag(E);
5221 return false;
5222 }
5223 }
5224 bool found(APSInt &Value, QualType SubobjType) {
5225 if (!checkConst(SubobjType))
5226 return false;
5227
5228 if (!SubobjType->isIntegerType()) {
5229 // We don't support increment / decrement on integer-cast-to-pointer
5230 // values.
5231 Info.FFDiag(E);
5232 return false;
5233 }
5234
5235 if (Old) *Old = APValue(Value);
5236
5237 // bool arithmetic promotes to int, and the conversion back to bool
5238 // doesn't reduce mod 2^n, so special-case it.
5239 if (SubobjType->isBooleanType()) {
5240 if (AccessKind == AK_Increment)
5241 Value = 1;
5242 else
5243 Value = !Value;
5244 return true;
5245 }
5246
5247 bool WasNegative = Value.isNegative();
5248 if (AccessKind == AK_Increment) {
5249 ++Value;
5250
5251 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
5252 APSInt ActualValue(Value, /*IsUnsigned*/true);
5253 return HandleOverflow(Info, E, ActualValue, SubobjType);
5254 }
5255 } else {
5256 --Value;
5257
5258 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
5259 unsigned BitWidth = Value.getBitWidth();
5260 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5261 ActualValue.setBit(BitWidth);
5262 return HandleOverflow(Info, E, ActualValue, SubobjType);
5263 }
5264 }
5265 return true;
5266 }
5267 bool found(APFloat &Value, QualType SubobjType) {
5268 if (!checkConst(SubobjType))
5269 return false;
5270
5271 if (Old) *Old = APValue(Value);
5272
5273 APFloat One(Value.getSemantics(), 1);
5274 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5275 APFloat::opStatus St;
5276 if (AccessKind == AK_Increment)
5277 St = Value.add(One, RM);
5278 else
5279 St = Value.subtract(One, RM);
5280 return checkFloatingPointResult(Info, E, St);
5281 }
5282 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5283 if (!checkConst(SubobjType))
5284 return false;
5285
5286 QualType PointeeType;
5287 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5288 PointeeType = PT->getPointeeType();
5289 else {
5290 Info.FFDiag(E);
5291 return false;
5292 }
5293
5294 LValue LVal;
5295 LVal.setFrom(Info.Ctx, Subobj);
5296 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5297 AccessKind == AK_Increment ? 1 : -1))
5298 return false;
5299 LVal.moveInto(Subobj);
5300 return true;
5301 }
5302};
5303} // end anonymous namespace
5304
5305/// Perform an increment or decrement on LVal.
5306static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5307 QualType LValType, bool IsIncrement, APValue *Old) {
5308 if (LVal.Designator.Invalid)
5309 return false;
5310
5311 if (!Info.getLangOpts().CPlusPlus14) {
5312 Info.FFDiag(E);
5313 return false;
5314 }
5315
5316 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5317 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5318 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5319 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5320}
5321
5322/// Build an lvalue for the object argument of a member function call.
5323static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5324 LValue &This) {
5325 if (Object->getType()->isPointerType() && Object->isPRValue())
5326 return EvaluatePointer(Object, This, Info);
5327
5328 if (Object->isGLValue())
5329 return EvaluateLValue(Object, This, Info);
5330
5331 if (Object->getType()->isLiteralType(Info.Ctx))
5332 return EvaluateTemporary(Object, This, Info);
5333
5334 if (Object->getType()->isRecordType() && Object->isPRValue())
5335 return EvaluateTemporary(Object, This, Info);
5336
5337 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5338 return false;
5339}
5340
5341/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5342/// lvalue referring to the result.
5343///
5344/// \param Info - Information about the ongoing evaluation.
5345/// \param LV - An lvalue referring to the base of the member pointer.
5346/// \param RHS - The member pointer expression.
5347/// \param IncludeMember - Specifies whether the member itself is included in
5348/// the resulting LValue subobject designator. This is not possible when
5349/// creating a bound member function.
5350/// \return The field or method declaration to which the member pointer refers,
5351/// or 0 if evaluation fails.
5352static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5353 QualType LVType,
5354 LValue &LV,
5355 const Expr *RHS,
5356 bool IncludeMember = true) {
5357 MemberPtr MemPtr;
5358 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5359 return nullptr;
5360
5361 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5362 // member value, the behavior is undefined.
5363 if (!MemPtr.getDecl()) {
5364 // FIXME: Specific diagnostic.
5365 Info.FFDiag(RHS);
5366 return nullptr;
5367 }
5368
5369 if (MemPtr.isDerivedMember()) {
5370 // This is a member of some derived class. Truncate LV appropriately.
5371 // The end of the derived-to-base path for the base object must match the
5372 // derived-to-base path for the member pointer.
5373 // C++23 [expr.mptr.oper]p4:
5374 // If the result of E1 is an object [...] whose most derived object does
5375 // not contain the member to which E2 refers, the behavior is undefined.
5376 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5377 LV.Designator.Entries.size()) {
5378 Info.FFDiag(RHS);
5379 return nullptr;
5380 }
5381 unsigned PathLengthToMember =
5382 LV.Designator.Entries.size() - MemPtr.Path.size();
5383 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5384 const CXXRecordDecl *LVDecl = getAsBaseClass(
5385 LV.Designator.Entries[PathLengthToMember + I]);
5386 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5387 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5388 Info.FFDiag(RHS);
5389 return nullptr;
5390 }
5391 }
5392 // MemPtr.Path only contains the base classes of the class directly
5393 // containing the member E2. It is still necessary to check that the class
5394 // directly containing the member E2 lies on the derived-to-base path of E1
5395 // to avoid incorrectly permitting member pointer access into a sibling
5396 // class of the class containing the member E2. If this class would
5397 // correspond to the most-derived class of E1, it either isn't contained in
5398 // LV.Designator.Entries or the corresponding entry refers to an array
5399 // element instead. Therefore get the most derived class directly in this
5400 // case. Otherwise the previous entry should correpond to this class.
5401 const CXXRecordDecl *LastLVDecl =
5402 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5403 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5404 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5405 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5406 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5407 Info.FFDiag(RHS);
5408 return nullptr;
5409 }
5410
5411 // Truncate the lvalue to the appropriate derived class.
5412 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5413 PathLengthToMember))
5414 return nullptr;
5415 } else if (!MemPtr.Path.empty()) {
5416 // Extend the LValue path with the member pointer's path.
5417 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5418 MemPtr.Path.size() + IncludeMember);
5419
5420 // Walk down to the appropriate base class.
5421 if (const PointerType *PT = LVType->getAs<PointerType>())
5422 LVType = PT->getPointeeType();
5423 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5424 assert(RD && "member pointer access on non-class-type expression");
5425 // The first class in the path is that of the lvalue.
5426 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5427 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5428 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5429 return nullptr;
5430 RD = Base;
5431 }
5432 // Finally cast to the class containing the member.
5433 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5434 MemPtr.getContainingRecord()))
5435 return nullptr;
5436 }
5437
5438 // Add the member. Note that we cannot build bound member functions here.
5439 if (IncludeMember) {
5440 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5441 if (!HandleLValueMember(Info, RHS, LV, FD))
5442 return nullptr;
5443 } else if (const IndirectFieldDecl *IFD =
5444 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5445 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5446 return nullptr;
5447 } else {
5448 llvm_unreachable("can't construct reference to bound member function");
5449 }
5450 }
5451
5452 return MemPtr.getDecl();
5453}
5454
5455static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5456 const BinaryOperator *BO,
5457 LValue &LV,
5458 bool IncludeMember = true) {
5459 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5460
5461 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5462 if (Info.noteFailure()) {
5463 MemberPtr MemPtr;
5464 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5465 }
5466 return nullptr;
5467 }
5468
5469 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5470 BO->getRHS(), IncludeMember);
5471}
5472
5473/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5474/// the provided lvalue, which currently refers to the base object.
5475static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5476 LValue &Result) {
5477 SubobjectDesignator &D = Result.Designator;
5478 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5479 return false;
5480
5481 QualType TargetQT = E->getType();
5482 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5483 TargetQT = PT->getPointeeType();
5484
5485 auto InvalidCast = [&]() {
5486 if (!Info.checkingPotentialConstantExpression() ||
5487 !Result.AllowConstexprUnknown) {
5488 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5489 << D.MostDerivedType << TargetQT;
5490 }
5491 return false;
5492 };
5493
5494 // Check this cast lands within the final derived-to-base subobject path.
5495 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5496 return InvalidCast();
5497
5498 // Check the type of the final cast. We don't need to check the path,
5499 // since a cast can only be formed if the path is unique.
5500 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5501 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5502 const CXXRecordDecl *FinalType;
5503 if (NewEntriesSize == D.MostDerivedPathLength)
5504 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5505 else
5506 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5507 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5508 return InvalidCast();
5509
5510 // Truncate the lvalue to the appropriate derived class.
5511 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5512}
5513
5514/// Get the value to use for a default-initialized object of type T.
5515/// Return false if it encounters something invalid.
5517 bool Success = true;
5518
5519 // If there is already a value present don't overwrite it.
5520 if (!Result.isAbsent())
5521 return true;
5522
5523 if (auto *RD = T->getAsCXXRecordDecl()) {
5524 if (RD->isInvalidDecl()) {
5525 Result = APValue();
5526 return false;
5527 }
5528 if (RD->isUnion()) {
5529 Result = APValue((const FieldDecl *)nullptr);
5530 return true;
5531 }
5532 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5533 std::distance(RD->field_begin(), RD->field_end()));
5534
5535 unsigned Index = 0;
5536 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5537 End = RD->bases_end();
5538 I != End; ++I, ++Index)
5539 Success &=
5540 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5541
5542 for (const auto *I : RD->fields()) {
5543 if (I->isUnnamedBitField())
5544 continue;
5546 I->getType(), Result.getStructField(I->getFieldIndex()));
5547 }
5548 return Success;
5549 }
5550
5551 if (auto *AT =
5552 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5553 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5554 if (Result.hasArrayFiller())
5555 Success &=
5556 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5557
5558 return Success;
5559 }
5560
5561 Result = APValue::IndeterminateValue();
5562 return true;
5563}
5564
5565namespace {
5566enum EvalStmtResult {
5567 /// Evaluation failed.
5568 ESR_Failed,
5569 /// Hit a 'return' statement.
5570 ESR_Returned,
5571 /// Evaluation succeeded.
5572 ESR_Succeeded,
5573 /// Hit a 'continue' statement.
5574 ESR_Continue,
5575 /// Hit a 'break' statement.
5576 ESR_Break,
5577 /// Still scanning for 'case' or 'default' statement.
5578 ESR_CaseNotFound
5579};
5580}
5581/// Evaluates the initializer of a reference.
5582static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5583 const ValueDecl *D,
5584 const Expr *Init, LValue &Result,
5585 APValue &Val) {
5586 assert(Init->isGLValue() && D->getType()->isReferenceType());
5587 // A reference is an lvalue.
5588 if (!EvaluateLValue(Init, Result, Info))
5589 return false;
5590 // [C++26][decl.ref]
5591 // The object designated by such a glvalue can be outside its lifetime
5592 // Because a null pointer value or a pointer past the end of an object
5593 // does not point to an object, a reference in a well-defined program cannot
5594 // refer to such things;
5595 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5596 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5597 return false;
5598 }
5599
5600 // Save the result.
5601 Result.moveInto(Val);
5602 return true;
5603}
5604
5605static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5606 if (VD->isInvalidDecl())
5607 return false;
5608 // We don't need to evaluate the initializer for a static local.
5609 if (!VD->hasLocalStorage())
5610 return true;
5611
5612 LValue Result;
5613 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5614 ScopeKind::Block, Result);
5615
5616 const Expr *InitE = VD->getInit();
5617 if (!InitE) {
5618 if (VD->getType()->isDependentType())
5619 return Info.noteSideEffect();
5620 return handleDefaultInitValue(VD->getType(), Val);
5621 }
5622 if (InitE->isValueDependent())
5623 return false;
5624
5625 // For references to objects, check they do not designate a one-past-the-end
5626 // object.
5627 if (VD->getType()->isReferenceType()) {
5628 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5629 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5630 // Wipe out any partially-computed value, to allow tracking that this
5631 // evaluation failed.
5632 Val = APValue();
5633 return false;
5634 }
5635
5636 return true;
5637}
5638
5639static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5640 const DecompositionDecl *DD);
5641
5642static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5643 bool EvaluateConditionDecl = false) {
5644 bool OK = true;
5645 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5646 OK &= EvaluateVarDecl(Info, VD);
5647
5648 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5649 EvaluateConditionDecl && DD)
5650 OK &= EvaluateDecompositionDeclInit(Info, DD);
5651
5652 return OK;
5653}
5654
5655static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5656 const DecompositionDecl *DD) {
5657 bool OK = true;
5658 for (auto *BD : DD->flat_bindings())
5659 if (auto *VD = BD->getHoldingVar())
5660 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5661
5662 return OK;
5663}
5664
5665static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5666 const VarDecl *VD) {
5667 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5668 if (!EvaluateDecompositionDeclInit(Info, DD))
5669 return false;
5670 }
5671 return true;
5672}
5673
5674static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5675 assert(E->isValueDependent());
5676 if (Info.noteSideEffect())
5677 return true;
5678 assert(E->containsErrors() && "valid value-dependent expression should never "
5679 "reach invalid code path.");
5680 return false;
5681}
5682
5683/// Evaluate a condition (either a variable declaration or an expression).
5684static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5685 const Expr *Cond, bool &Result) {
5686 if (Cond->isValueDependent())
5687 return false;
5688 FullExpressionRAII Scope(Info);
5689 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5690 return false;
5691 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5692 return false;
5693 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5694 return false;
5695 return Scope.destroy();
5696}
5697
5698namespace {
5699/// A location where the result (returned value) of evaluating a
5700/// statement should be stored.
5701struct StmtResult {
5702 /// The APValue that should be filled in with the returned value.
5703 APValue &Value;
5704 /// The location containing the result, if any (used to support RVO).
5705 const LValue *Slot;
5706};
5707
5708struct TempVersionRAII {
5709 CallStackFrame &Frame;
5710
5711 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5712 Frame.pushTempVersion();
5713 }
5714
5715 ~TempVersionRAII() {
5716 Frame.popTempVersion();
5717 }
5718};
5719
5720}
5721
5722static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5723 const Stmt *S,
5724 const SwitchCase *SC = nullptr);
5725
5726/// Helper to implement named break/continue. Returns 'true' if the evaluation
5727/// result should be propagated up. Otherwise, it sets the evaluation result
5728/// to either Continue to continue the current loop, or Succeeded to break it.
5729static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5730 const Stmt *LoopOrSwitch,
5732 EvalStmtResult &ESR) {
5733 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5734
5735 // For loops, map Succeeded to Continue so we don't have to check for both.
5736 if (!IsSwitch && ESR == ESR_Succeeded) {
5737 ESR = ESR_Continue;
5738 return false;
5739 }
5740
5741 if (ESR != ESR_Break && ESR != ESR_Continue)
5742 return false;
5743
5744 // Are we breaking out of or continuing this statement?
5745 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5746 const Stmt *StackTop = Info.BreakContinueStack.back();
5747 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5748 Info.BreakContinueStack.pop_back();
5749 if (ESR == ESR_Break)
5750 ESR = ESR_Succeeded;
5751 return false;
5752 }
5753
5754 // We're not. Propagate the result up.
5755 for (BlockScopeRAII *S : Scopes) {
5756 if (!S->destroy()) {
5757 ESR = ESR_Failed;
5758 break;
5759 }
5760 }
5761 return true;
5762}
5763
5764/// Evaluate the body of a loop, and translate the result as appropriate.
5765static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5766 const Stmt *Body,
5767 const SwitchCase *Case = nullptr) {
5768 BlockScopeRAII Scope(Info);
5769
5770 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5771 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5772 ESR = ESR_Failed;
5773
5774 return ESR;
5775}
5776
5777/// Evaluate a switch statement.
5778static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5779 const SwitchStmt *SS) {
5780 BlockScopeRAII Scope(Info);
5781
5782 // Evaluate the switch condition.
5783 APSInt Value;
5784 {
5785 if (const Stmt *Init = SS->getInit()) {
5786 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5787 if (ESR != ESR_Succeeded) {
5788 if (ESR != ESR_Failed && !Scope.destroy())
5789 ESR = ESR_Failed;
5790 return ESR;
5791 }
5792 }
5793
5794 FullExpressionRAII CondScope(Info);
5795 if (SS->getConditionVariable() &&
5796 !EvaluateDecl(Info, SS->getConditionVariable()))
5797 return ESR_Failed;
5798 if (SS->getCond()->isValueDependent()) {
5799 // We don't know what the value is, and which branch should jump to.
5800 EvaluateDependentExpr(SS->getCond(), Info);
5801 return ESR_Failed;
5802 }
5803 if (!EvaluateInteger(SS->getCond(), Value, Info))
5804 return ESR_Failed;
5805
5807 return ESR_Failed;
5808
5809 if (!CondScope.destroy())
5810 return ESR_Failed;
5811 }
5812
5813 // Find the switch case corresponding to the value of the condition.
5814 // FIXME: Cache this lookup.
5815 const SwitchCase *Found = nullptr;
5816 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5817 SC = SC->getNextSwitchCase()) {
5818 if (isa<DefaultStmt>(SC)) {
5819 Found = SC;
5820 continue;
5821 }
5822
5823 const CaseStmt *CS = cast<CaseStmt>(SC);
5824 const Expr *LHS = CS->getLHS();
5825 const Expr *RHS = CS->getRHS();
5826 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5827 return ESR_Failed;
5828 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5829 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5830 if (LHSValue <= Value && Value <= RHSValue) {
5831 Found = SC;
5832 break;
5833 }
5834 }
5835
5836 if (!Found)
5837 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5838
5839 // Search the switch body for the switch case and evaluate it from there.
5840 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5841 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5842 return ESR_Failed;
5843 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5844 return ESR;
5845
5846 switch (ESR) {
5847 case ESR_Break:
5848 llvm_unreachable("Should have been converted to Succeeded");
5849 case ESR_Succeeded:
5850 case ESR_Continue:
5851 case ESR_Failed:
5852 case ESR_Returned:
5853 return ESR;
5854 case ESR_CaseNotFound:
5855 // This can only happen if the switch case is nested within a statement
5856 // expression. We have no intention of supporting that.
5857 Info.FFDiag(Found->getBeginLoc(),
5858 diag::note_constexpr_stmt_expr_unsupported);
5859 return ESR_Failed;
5860 }
5861 llvm_unreachable("Invalid EvalStmtResult!");
5862}
5863
5864static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5865 // An expression E is a core constant expression unless the evaluation of E
5866 // would evaluate one of the following: [C++23] - a control flow that passes
5867 // through a declaration of a variable with static or thread storage duration
5868 // unless that variable is usable in constant expressions.
5869 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5870 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5871 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5872 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5873 return false;
5874 }
5875 return true;
5876}
5877
5878// Evaluate a statement.
5879static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5880 const Stmt *S, const SwitchCase *Case) {
5881 if (!Info.nextStep(S))
5882 return ESR_Failed;
5883
5884 // If we're hunting down a 'case' or 'default' label, recurse through
5885 // substatements until we hit the label.
5886 if (Case) {
5887 switch (S->getStmtClass()) {
5888 case Stmt::CompoundStmtClass:
5889 // FIXME: Precompute which substatement of a compound statement we
5890 // would jump to, and go straight there rather than performing a
5891 // linear scan each time.
5892 case Stmt::LabelStmtClass:
5893 case Stmt::AttributedStmtClass:
5894 case Stmt::DoStmtClass:
5895 break;
5896
5897 case Stmt::CaseStmtClass:
5898 case Stmt::DefaultStmtClass:
5899 if (Case == S)
5900 Case = nullptr;
5901 break;
5902
5903 case Stmt::IfStmtClass: {
5904 // FIXME: Precompute which side of an 'if' we would jump to, and go
5905 // straight there rather than scanning both sides.
5906 const IfStmt *IS = cast<IfStmt>(S);
5907
5908 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5909 // preceded by our switch label.
5910 BlockScopeRAII Scope(Info);
5911
5912 // Step into the init statement in case it brings an (uninitialized)
5913 // variable into scope.
5914 if (const Stmt *Init = IS->getInit()) {
5915 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5916 if (ESR != ESR_CaseNotFound) {
5917 assert(ESR != ESR_Succeeded);
5918 return ESR;
5919 }
5920 }
5921
5922 // Condition variable must be initialized if it exists.
5923 // FIXME: We can skip evaluating the body if there's a condition
5924 // variable, as there can't be any case labels within it.
5925 // (The same is true for 'for' statements.)
5926
5927 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5928 if (ESR == ESR_Failed)
5929 return ESR;
5930 if (ESR != ESR_CaseNotFound)
5931 return Scope.destroy() ? ESR : ESR_Failed;
5932 if (!IS->getElse())
5933 return ESR_CaseNotFound;
5934
5935 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5936 if (ESR == ESR_Failed)
5937 return ESR;
5938 if (ESR != ESR_CaseNotFound)
5939 return Scope.destroy() ? ESR : ESR_Failed;
5940 return ESR_CaseNotFound;
5941 }
5942
5943 case Stmt::WhileStmtClass: {
5944 EvalStmtResult ESR =
5945 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5946 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5947 return ESR;
5948 if (ESR != ESR_Continue)
5949 return ESR;
5950 break;
5951 }
5952
5953 case Stmt::ForStmtClass: {
5954 const ForStmt *FS = cast<ForStmt>(S);
5955 BlockScopeRAII Scope(Info);
5956
5957 // Step into the init statement in case it brings an (uninitialized)
5958 // variable into scope.
5959 if (const Stmt *Init = FS->getInit()) {
5960 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5961 if (ESR != ESR_CaseNotFound) {
5962 assert(ESR != ESR_Succeeded);
5963 return ESR;
5964 }
5965 }
5966
5967 EvalStmtResult ESR =
5968 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5969 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5970 return ESR;
5971 if (ESR != ESR_Continue)
5972 return ESR;
5973 if (const auto *Inc = FS->getInc()) {
5974 if (Inc->isValueDependent()) {
5975 if (!EvaluateDependentExpr(Inc, Info))
5976 return ESR_Failed;
5977 } else {
5978 FullExpressionRAII IncScope(Info);
5979 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5980 return ESR_Failed;
5981 }
5982 }
5983 break;
5984 }
5985
5986 case Stmt::DeclStmtClass: {
5987 // Start the lifetime of any uninitialized variables we encounter. They
5988 // might be used by the selected branch of the switch.
5989 const DeclStmt *DS = cast<DeclStmt>(S);
5990 for (const auto *D : DS->decls()) {
5991 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5992 if (!CheckLocalVariableDeclaration(Info, VD))
5993 return ESR_Failed;
5994 if (VD->hasLocalStorage() && !VD->getInit())
5995 if (!EvaluateVarDecl(Info, VD))
5996 return ESR_Failed;
5997 // FIXME: If the variable has initialization that can't be jumped
5998 // over, bail out of any immediately-surrounding compound-statement
5999 // too. There can't be any case labels here.
6000 }
6001 }
6002 return ESR_CaseNotFound;
6003 }
6004
6005 default:
6006 return ESR_CaseNotFound;
6007 }
6008 }
6009
6010 switch (S->getStmtClass()) {
6011 default:
6012 if (const Expr *E = dyn_cast<Expr>(S)) {
6013 if (E->isValueDependent()) {
6014 if (!EvaluateDependentExpr(E, Info))
6015 return ESR_Failed;
6016 } else {
6017 // Don't bother evaluating beyond an expression-statement which couldn't
6018 // be evaluated.
6019 // FIXME: Do we need the FullExpressionRAII object here?
6020 // VisitExprWithCleanups should create one when necessary.
6021 FullExpressionRAII Scope(Info);
6022 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6023 return ESR_Failed;
6024 }
6025 return ESR_Succeeded;
6026 }
6027
6028 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6029 return ESR_Failed;
6030
6031 case Stmt::NullStmtClass:
6032 return ESR_Succeeded;
6033
6034 case Stmt::DeclStmtClass: {
6035 const DeclStmt *DS = cast<DeclStmt>(S);
6036 for (const auto *D : DS->decls()) {
6037 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6038 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6039 return ESR_Failed;
6040 // Each declaration initialization is its own full-expression.
6041 FullExpressionRAII Scope(Info);
6042 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6043 !Info.noteFailure())
6044 return ESR_Failed;
6045 if (!Scope.destroy())
6046 return ESR_Failed;
6047 }
6048 return ESR_Succeeded;
6049 }
6050
6051 case Stmt::ReturnStmtClass: {
6052 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6053 FullExpressionRAII Scope(Info);
6054 if (RetExpr && RetExpr->isValueDependent()) {
6055 EvaluateDependentExpr(RetExpr, Info);
6056 // We know we returned, but we don't know what the value is.
6057 return ESR_Failed;
6058 }
6059 if (RetExpr &&
6060 !(Result.Slot
6061 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6062 : Evaluate(Result.Value, Info, RetExpr)))
6063 return ESR_Failed;
6064 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6065 }
6066
6067 case Stmt::CompoundStmtClass: {
6068 BlockScopeRAII Scope(Info);
6069
6070 const CompoundStmt *CS = cast<CompoundStmt>(S);
6071 for (const auto *BI : CS->body()) {
6072 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6073 if (ESR == ESR_Succeeded)
6074 Case = nullptr;
6075 else if (ESR != ESR_CaseNotFound) {
6076 if (ESR != ESR_Failed && !Scope.destroy())
6077 return ESR_Failed;
6078 return ESR;
6079 }
6080 }
6081 if (Case)
6082 return ESR_CaseNotFound;
6083 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6084 }
6085
6086 case Stmt::IfStmtClass: {
6087 const IfStmt *IS = cast<IfStmt>(S);
6088
6089 // Evaluate the condition, as either a var decl or as an expression.
6090 BlockScopeRAII Scope(Info);
6091 if (const Stmt *Init = IS->getInit()) {
6092 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6093 if (ESR != ESR_Succeeded) {
6094 if (ESR != ESR_Failed && !Scope.destroy())
6095 return ESR_Failed;
6096 return ESR;
6097 }
6098 }
6099 bool Cond;
6100 if (IS->isConsteval()) {
6102 // If we are not in a constant context, if consteval should not evaluate
6103 // to true.
6104 if (!Info.InConstantContext)
6105 Cond = !Cond;
6106 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6107 Cond))
6108 return ESR_Failed;
6109
6110 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6111 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6112 if (ESR != ESR_Succeeded) {
6113 if (ESR != ESR_Failed && !Scope.destroy())
6114 return ESR_Failed;
6115 return ESR;
6116 }
6117 }
6118 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6119 }
6120
6121 case Stmt::WhileStmtClass: {
6122 const WhileStmt *WS = cast<WhileStmt>(S);
6123 while (true) {
6124 BlockScopeRAII Scope(Info);
6125 bool Continue;
6126 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6127 Continue))
6128 return ESR_Failed;
6129 if (!Continue)
6130 break;
6131
6132 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6133 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6134 return ESR;
6135
6136 if (ESR != ESR_Continue) {
6137 if (ESR != ESR_Failed && !Scope.destroy())
6138 return ESR_Failed;
6139 return ESR;
6140 }
6141 if (!Scope.destroy())
6142 return ESR_Failed;
6143 }
6144 return ESR_Succeeded;
6145 }
6146
6147 case Stmt::DoStmtClass: {
6148 const DoStmt *DS = cast<DoStmt>(S);
6149 bool Continue;
6150 do {
6151 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6152 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6153 return ESR;
6154 if (ESR != ESR_Continue)
6155 return ESR;
6156 Case = nullptr;
6157
6158 if (DS->getCond()->isValueDependent()) {
6159 EvaluateDependentExpr(DS->getCond(), Info);
6160 // Bailout as we don't know whether to keep going or terminate the loop.
6161 return ESR_Failed;
6162 }
6163 FullExpressionRAII CondScope(Info);
6164 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6165 !CondScope.destroy())
6166 return ESR_Failed;
6167 } while (Continue);
6168 return ESR_Succeeded;
6169 }
6170
6171 case Stmt::ForStmtClass: {
6172 const ForStmt *FS = cast<ForStmt>(S);
6173 BlockScopeRAII ForScope(Info);
6174 if (FS->getInit()) {
6175 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6176 if (ESR != ESR_Succeeded) {
6177 if (ESR != ESR_Failed && !ForScope.destroy())
6178 return ESR_Failed;
6179 return ESR;
6180 }
6181 }
6182 while (true) {
6183 BlockScopeRAII IterScope(Info);
6184 bool Continue = true;
6185 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6186 FS->getCond(), Continue))
6187 return ESR_Failed;
6188
6189 if (!Continue) {
6190 if (!IterScope.destroy())
6191 return ESR_Failed;
6192 break;
6193 }
6194
6195 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6196 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6197 return ESR;
6198 if (ESR != ESR_Continue) {
6199 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6200 return ESR_Failed;
6201 return ESR;
6202 }
6203
6204 if (const auto *Inc = FS->getInc()) {
6205 if (Inc->isValueDependent()) {
6206 if (!EvaluateDependentExpr(Inc, Info))
6207 return ESR_Failed;
6208 } else {
6209 FullExpressionRAII IncScope(Info);
6210 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6211 return ESR_Failed;
6212 }
6213 }
6214
6215 if (!IterScope.destroy())
6216 return ESR_Failed;
6217 }
6218 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6219 }
6220
6221 case Stmt::CXXForRangeStmtClass: {
6223 BlockScopeRAII Scope(Info);
6224
6225 // Evaluate the init-statement if present.
6226 if (FS->getInit()) {
6227 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6228 if (ESR != ESR_Succeeded) {
6229 if (ESR != ESR_Failed && !Scope.destroy())
6230 return ESR_Failed;
6231 return ESR;
6232 }
6233 }
6234
6235 // Initialize the __range variable.
6236 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6237 if (ESR != ESR_Succeeded) {
6238 if (ESR != ESR_Failed && !Scope.destroy())
6239 return ESR_Failed;
6240 return ESR;
6241 }
6242
6243 // In error-recovery cases it's possible to get here even if we failed to
6244 // synthesize the __begin and __end variables.
6245 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6246 return ESR_Failed;
6247
6248 // Create the __begin and __end iterators.
6249 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6250 if (ESR != ESR_Succeeded) {
6251 if (ESR != ESR_Failed && !Scope.destroy())
6252 return ESR_Failed;
6253 return ESR;
6254 }
6255 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6256 if (ESR != ESR_Succeeded) {
6257 if (ESR != ESR_Failed && !Scope.destroy())
6258 return ESR_Failed;
6259 return ESR;
6260 }
6261
6262 while (true) {
6263 // Condition: __begin != __end.
6264 {
6265 if (FS->getCond()->isValueDependent()) {
6266 EvaluateDependentExpr(FS->getCond(), Info);
6267 // We don't know whether to keep going or terminate the loop.
6268 return ESR_Failed;
6269 }
6270 bool Continue = true;
6271 FullExpressionRAII CondExpr(Info);
6272 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6273 return ESR_Failed;
6274 if (!Continue)
6275 break;
6276 }
6277
6278 // User's variable declaration, initialized by *__begin.
6279 BlockScopeRAII InnerScope(Info);
6280 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6281 if (ESR != ESR_Succeeded) {
6282 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6283 return ESR_Failed;
6284 return ESR;
6285 }
6286
6287 // Loop body.
6288 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6289 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6290 return ESR;
6291 if (ESR != ESR_Continue) {
6292 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6293 return ESR_Failed;
6294 return ESR;
6295 }
6296 if (FS->getInc()->isValueDependent()) {
6297 if (!EvaluateDependentExpr(FS->getInc(), Info))
6298 return ESR_Failed;
6299 } else {
6300 // Increment: ++__begin
6301 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6302 return ESR_Failed;
6303 }
6304
6305 if (!InnerScope.destroy())
6306 return ESR_Failed;
6307 }
6308
6309 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6310 }
6311
6312 case Stmt::SwitchStmtClass:
6313 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6314
6315 case Stmt::ContinueStmtClass:
6316 case Stmt::BreakStmtClass: {
6317 auto *B = cast<LoopControlStmt>(S);
6318 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6319 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6320 }
6321
6322 case Stmt::LabelStmtClass:
6323 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6324
6325 case Stmt::AttributedStmtClass: {
6326 const auto *AS = cast<AttributedStmt>(S);
6327 const auto *SS = AS->getSubStmt();
6328 MSConstexprContextRAII ConstexprContext(
6329 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6330 isa<ReturnStmt>(SS));
6331
6332 auto LO = Info.getASTContext().getLangOpts();
6333 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6334 for (auto *Attr : AS->getAttrs()) {
6335 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6336 if (!AA)
6337 continue;
6338
6339 auto *Assumption = AA->getAssumption();
6340 if (Assumption->isValueDependent())
6341 return ESR_Failed;
6342
6343 if (Assumption->HasSideEffects(Info.getASTContext()))
6344 continue;
6345
6346 bool Value;
6347 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6348 return ESR_Failed;
6349 if (!Value) {
6350 Info.CCEDiag(Assumption->getExprLoc(),
6351 diag::note_constexpr_assumption_failed);
6352 return ESR_Failed;
6353 }
6354 }
6355 }
6356
6357 return EvaluateStmt(Result, Info, SS, Case);
6358 }
6359
6360 case Stmt::CaseStmtClass:
6361 case Stmt::DefaultStmtClass:
6362 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6363 case Stmt::CXXTryStmtClass:
6364 // Evaluate try blocks by evaluating all sub statements.
6365 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6366 }
6367}
6368
6369/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6370/// default constructor. If so, we'll fold it whether or not it's marked as
6371/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6372/// so we need special handling.
6373static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6374 const CXXConstructorDecl *CD,
6375 bool IsValueInitialization) {
6376 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6377 return false;
6378
6379 // Value-initialization does not call a trivial default constructor, so such a
6380 // call is a core constant expression whether or not the constructor is
6381 // constexpr.
6382 if (!CD->isConstexpr() && !IsValueInitialization) {
6383 if (Info.getLangOpts().CPlusPlus11) {
6384 // FIXME: If DiagDecl is an implicitly-declared special member function,
6385 // we should be much more explicit about why it's not constexpr.
6386 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6387 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6388 Info.Note(CD->getLocation(), diag::note_declared_at);
6389 } else {
6390 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6391 }
6392 }
6393 return true;
6394}
6395
6396/// CheckConstexprFunction - Check that a function can be called in a constant
6397/// expression.
6398static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6400 const FunctionDecl *Definition,
6401 const Stmt *Body) {
6402 // Potential constant expressions can contain calls to declared, but not yet
6403 // defined, constexpr functions.
6404 if (Info.checkingPotentialConstantExpression() && !Definition &&
6405 Declaration->isConstexpr())
6406 return false;
6407
6408 // Bail out if the function declaration itself is invalid. We will
6409 // have produced a relevant diagnostic while parsing it, so just
6410 // note the problematic sub-expression.
6411 if (Declaration->isInvalidDecl()) {
6412 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6413 return false;
6414 }
6415
6416 // DR1872: An instantiated virtual constexpr function can't be called in a
6417 // constant expression (prior to C++20). We can still constant-fold such a
6418 // call.
6419 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6420 cast<CXXMethodDecl>(Declaration)->isVirtual())
6421 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6422
6423 if (Definition && Definition->isInvalidDecl()) {
6424 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6425 return false;
6426 }
6427
6428 // Can we evaluate this function call?
6429 if (Definition && Body &&
6430 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6431 Definition->hasAttr<MSConstexprAttr>())))
6432 return true;
6433
6434 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6435 // Special note for the assert() macro, as the normal error message falsely
6436 // implies we cannot use an assertion during constant evaluation.
6437 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6438 // FIXME: Instead of checking for an implementation-defined function,
6439 // check and evaluate the assert() macro.
6440 StringRef Name = DiagDecl->getName();
6441 bool AssertFailed =
6442 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6443 if (AssertFailed) {
6444 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6445 return false;
6446 }
6447 }
6448
6449 if (Info.getLangOpts().CPlusPlus11) {
6450 // If this function is not constexpr because it is an inherited
6451 // non-constexpr constructor, diagnose that directly.
6452 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6453 if (CD && CD->isInheritingConstructor()) {
6454 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6455 if (!Inherited->isConstexpr())
6456 DiagDecl = CD = Inherited;
6457 }
6458
6459 // FIXME: If DiagDecl is an implicitly-declared special member function
6460 // or an inheriting constructor, we should be much more explicit about why
6461 // it's not constexpr.
6462 if (CD && CD->isInheritingConstructor())
6463 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6464 << CD->getInheritedConstructor().getConstructor()->getParent();
6465 else
6466 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6467 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6468 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6469 } else {
6470 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6471 }
6472 return false;
6473}
6474
6475namespace {
6476struct CheckDynamicTypeHandler {
6478 typedef bool result_type;
6479 bool failed() { return false; }
6480 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6481 bool found(APSInt &Value, QualType SubobjType) { return true; }
6482 bool found(APFloat &Value, QualType SubobjType) { return true; }
6483};
6484} // end anonymous namespace
6485
6486/// Check that we can access the notional vptr of an object / determine its
6487/// dynamic type.
6488static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6489 AccessKinds AK, bool Polymorphic) {
6490 if (This.Designator.Invalid)
6491 return false;
6492
6493 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6494
6495 if (!Obj)
6496 return false;
6497
6498 if (!Obj.Value) {
6499 // The object is not usable in constant expressions, so we can't inspect
6500 // its value to see if it's in-lifetime or what the active union members
6501 // are. We can still check for a one-past-the-end lvalue.
6502 if (This.Designator.isOnePastTheEnd() ||
6503 This.Designator.isMostDerivedAnUnsizedArray()) {
6504 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6505 ? diag::note_constexpr_access_past_end
6506 : diag::note_constexpr_access_unsized_array)
6507 << AK;
6508 return false;
6509 } else if (Polymorphic) {
6510 // Conservatively refuse to perform a polymorphic operation if we would
6511 // not be able to read a notional 'vptr' value.
6512 if (!Info.checkingPotentialConstantExpression() ||
6513 !This.AllowConstexprUnknown) {
6514 APValue Val;
6515 This.moveInto(Val);
6516 QualType StarThisType =
6517 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6518 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6519 << AK << Val.getAsString(Info.Ctx, StarThisType);
6520 }
6521 return false;
6522 }
6523 return true;
6524 }
6525
6526 CheckDynamicTypeHandler Handler{AK};
6527 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6528}
6529
6530/// Check that the pointee of the 'this' pointer in a member function call is
6531/// either within its lifetime or in its period of construction or destruction.
6532static bool
6534 const LValue &This,
6535 const CXXMethodDecl *NamedMember) {
6536 return checkDynamicType(
6537 Info, E, This,
6538 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6539}
6540
6542 /// The dynamic class type of the object.
6544 /// The corresponding path length in the lvalue.
6545 unsigned PathLength;
6546};
6547
6548static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6549 unsigned PathLength) {
6550 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6551 Designator.Entries.size() && "invalid path length");
6552 return (PathLength == Designator.MostDerivedPathLength)
6553 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6554 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6555}
6556
6557/// Determine the dynamic type of an object.
6558static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6559 const Expr *E,
6560 LValue &This,
6561 AccessKinds AK) {
6562 // If we don't have an lvalue denoting an object of class type, there is no
6563 // meaningful dynamic type. (We consider objects of non-class type to have no
6564 // dynamic type.)
6565 if (!checkDynamicType(Info, E, This, AK,
6566 AK != AK_TypeId || This.AllowConstexprUnknown))
6567 return std::nullopt;
6568
6569 if (This.Designator.Invalid)
6570 return std::nullopt;
6571
6572 // Refuse to compute a dynamic type in the presence of virtual bases. This
6573 // shouldn't happen other than in constant-folding situations, since literal
6574 // types can't have virtual bases.
6575 //
6576 // Note that consumers of DynamicType assume that the type has no virtual
6577 // bases, and will need modifications if this restriction is relaxed.
6578 const CXXRecordDecl *Class =
6579 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6580 if (!Class || Class->getNumVBases()) {
6581 Info.FFDiag(E);
6582 return std::nullopt;
6583 }
6584
6585 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6586 // binary search here instead. But the overwhelmingly common case is that
6587 // we're not in the middle of a constructor, so it probably doesn't matter
6588 // in practice.
6589 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6590 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6591 PathLength <= Path.size(); ++PathLength) {
6592 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6593 Path.slice(0, PathLength))) {
6594 case ConstructionPhase::Bases:
6595 case ConstructionPhase::DestroyingBases:
6596 // We're constructing or destroying a base class. This is not the dynamic
6597 // type.
6598 break;
6599
6600 case ConstructionPhase::None:
6601 case ConstructionPhase::AfterBases:
6602 case ConstructionPhase::AfterFields:
6603 case ConstructionPhase::Destroying:
6604 // We've finished constructing the base classes and not yet started
6605 // destroying them again, so this is the dynamic type.
6606 return DynamicType{getBaseClassType(This.Designator, PathLength),
6607 PathLength};
6608 }
6609 }
6610
6611 // CWG issue 1517: we're constructing a base class of the object described by
6612 // 'This', so that object has not yet begun its period of construction and
6613 // any polymorphic operation on it results in undefined behavior.
6614 Info.FFDiag(E);
6615 return std::nullopt;
6616}
6617
6618/// Perform virtual dispatch.
6620 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6621 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6622 std::optional<DynamicType> DynType = ComputeDynamicType(
6623 Info, E, This,
6625 if (!DynType)
6626 return nullptr;
6627
6628 // Find the final overrider. It must be declared in one of the classes on the
6629 // path from the dynamic type to the static type.
6630 // FIXME: If we ever allow literal types to have virtual base classes, that
6631 // won't be true.
6632 const CXXMethodDecl *Callee = Found;
6633 unsigned PathLength = DynType->PathLength;
6634 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6635 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6636 const CXXMethodDecl *Overrider =
6637 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6638 if (Overrider) {
6639 Callee = Overrider;
6640 break;
6641 }
6642 }
6643
6644 // C++2a [class.abstract]p6:
6645 // the effect of making a virtual call to a pure virtual function [...] is
6646 // undefined
6647 if (Callee->isPureVirtual()) {
6648 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6649 Info.Note(Callee->getLocation(), diag::note_declared_at);
6650 return nullptr;
6651 }
6652
6653 // If necessary, walk the rest of the path to determine the sequence of
6654 // covariant adjustment steps to apply.
6655 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6656 Found->getReturnType())) {
6657 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6658 for (unsigned CovariantPathLength = PathLength + 1;
6659 CovariantPathLength != This.Designator.Entries.size();
6660 ++CovariantPathLength) {
6661 const CXXRecordDecl *NextClass =
6662 getBaseClassType(This.Designator, CovariantPathLength);
6663 const CXXMethodDecl *Next =
6664 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6665 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6666 Next->getReturnType(), CovariantAdjustmentPath.back()))
6667 CovariantAdjustmentPath.push_back(Next->getReturnType());
6668 }
6669 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6670 CovariantAdjustmentPath.back()))
6671 CovariantAdjustmentPath.push_back(Found->getReturnType());
6672 }
6673
6674 // Perform 'this' adjustment.
6675 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6676 return nullptr;
6677
6678 return Callee;
6679}
6680
6681/// Perform the adjustment from a value returned by a virtual function to
6682/// a value of the statically expected type, which may be a pointer or
6683/// reference to a base class of the returned type.
6684static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6685 APValue &Result,
6686 ArrayRef<QualType> Path) {
6687 assert(Result.isLValue() &&
6688 "unexpected kind of APValue for covariant return");
6689 if (Result.isNullPointer())
6690 return true;
6691
6692 LValue LVal;
6693 LVal.setFrom(Info.Ctx, Result);
6694
6695 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6696 for (unsigned I = 1; I != Path.size(); ++I) {
6697 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6698 assert(OldClass && NewClass && "unexpected kind of covariant return");
6699 if (OldClass != NewClass &&
6700 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6701 return false;
6702 OldClass = NewClass;
6703 }
6704
6705 LVal.moveInto(Result);
6706 return true;
6707}
6708
6709/// Determine whether \p Base, which is known to be a direct base class of
6710/// \p Derived, is a public base class.
6711static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6712 const CXXRecordDecl *Base) {
6713 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6714 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6715 if (BaseClass && declaresSameEntity(BaseClass, Base))
6716 return BaseSpec.getAccessSpecifier() == AS_public;
6717 }
6718 llvm_unreachable("Base is not a direct base of Derived");
6719}
6720
6721/// Apply the given dynamic cast operation on the provided lvalue.
6722///
6723/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6724/// to find a suitable target subobject.
6725static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6726 LValue &Ptr) {
6727 // We can't do anything with a non-symbolic pointer value.
6728 SubobjectDesignator &D = Ptr.Designator;
6729 if (D.Invalid)
6730 return false;
6731
6732 // C++ [expr.dynamic.cast]p6:
6733 // If v is a null pointer value, the result is a null pointer value.
6734 if (Ptr.isNullPointer() && !E->isGLValue())
6735 return true;
6736
6737 // For all the other cases, we need the pointer to point to an object within
6738 // its lifetime / period of construction / destruction, and we need to know
6739 // its dynamic type.
6740 std::optional<DynamicType> DynType =
6741 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6742 if (!DynType)
6743 return false;
6744
6745 // C++ [expr.dynamic.cast]p7:
6746 // If T is "pointer to cv void", then the result is a pointer to the most
6747 // derived object
6748 if (E->getType()->isVoidPointerType())
6749 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6750
6752 assert(C && "dynamic_cast target is not void pointer nor class");
6753 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6754
6755 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6756 // C++ [expr.dynamic.cast]p9:
6757 if (!E->isGLValue()) {
6758 // The value of a failed cast to pointer type is the null pointer value
6759 // of the required result type.
6760 Ptr.setNull(Info.Ctx, E->getType());
6761 return true;
6762 }
6763
6764 // A failed cast to reference type throws [...] std::bad_cast.
6765 unsigned DiagKind;
6766 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6767 DynType->Type->isDerivedFrom(C)))
6768 DiagKind = 0;
6769 else if (!Paths || Paths->begin() == Paths->end())
6770 DiagKind = 1;
6771 else if (Paths->isAmbiguous(CQT))
6772 DiagKind = 2;
6773 else {
6774 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6775 DiagKind = 3;
6776 }
6777 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6778 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6779 << Info.Ctx.getCanonicalTagType(DynType->Type)
6780 << E->getType().getUnqualifiedType();
6781 return false;
6782 };
6783
6784 // Runtime check, phase 1:
6785 // Walk from the base subobject towards the derived object looking for the
6786 // target type.
6787 for (int PathLength = Ptr.Designator.Entries.size();
6788 PathLength >= (int)DynType->PathLength; --PathLength) {
6789 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6790 if (declaresSameEntity(Class, C))
6791 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6792 // We can only walk across public inheritance edges.
6793 if (PathLength > (int)DynType->PathLength &&
6794 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6795 Class))
6796 return RuntimeCheckFailed(nullptr);
6797 }
6798
6799 // Runtime check, phase 2:
6800 // Search the dynamic type for an unambiguous public base of type C.
6801 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6802 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6803 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6804 Paths.front().Access == AS_public) {
6805 // Downcast to the dynamic type...
6806 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6807 return false;
6808 // ... then upcast to the chosen base class subobject.
6809 for (CXXBasePathElement &Elem : Paths.front())
6810 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6811 return false;
6812 return true;
6813 }
6814
6815 // Otherwise, the runtime check fails.
6816 return RuntimeCheckFailed(&Paths);
6817}
6818
6819namespace {
6820struct StartLifetimeOfUnionMemberHandler {
6821 EvalInfo &Info;
6822 const Expr *LHSExpr;
6823 const FieldDecl *Field;
6824 bool DuringInit;
6825 bool Failed = false;
6826 static const AccessKinds AccessKind = AK_Assign;
6827
6828 typedef bool result_type;
6829 bool failed() { return Failed; }
6830 bool found(APValue &Subobj, QualType SubobjType) {
6831 // We are supposed to perform no initialization but begin the lifetime of
6832 // the object. We interpret that as meaning to do what default
6833 // initialization of the object would do if all constructors involved were
6834 // trivial:
6835 // * All base, non-variant member, and array element subobjects' lifetimes
6836 // begin
6837 // * No variant members' lifetimes begin
6838 // * All scalar subobjects whose lifetimes begin have indeterminate values
6839 assert(SubobjType->isUnionType());
6840 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6841 // This union member is already active. If it's also in-lifetime, there's
6842 // nothing to do.
6843 if (Subobj.getUnionValue().hasValue())
6844 return true;
6845 } else if (DuringInit) {
6846 // We're currently in the process of initializing a different union
6847 // member. If we carried on, that initialization would attempt to
6848 // store to an inactive union member, resulting in undefined behavior.
6849 Info.FFDiag(LHSExpr,
6850 diag::note_constexpr_union_member_change_during_init);
6851 return false;
6852 }
6854 Failed = !handleDefaultInitValue(Field->getType(), Result);
6855 Subobj.setUnion(Field, Result);
6856 return true;
6857 }
6858 bool found(APSInt &Value, QualType SubobjType) {
6859 llvm_unreachable("wrong value kind for union object");
6860 }
6861 bool found(APFloat &Value, QualType SubobjType) {
6862 llvm_unreachable("wrong value kind for union object");
6863 }
6864};
6865} // end anonymous namespace
6866
6867const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6868
6869/// Handle a builtin simple-assignment or a call to a trivial assignment
6870/// operator whose left-hand side might involve a union member access. If it
6871/// does, implicitly start the lifetime of any accessed union elements per
6872/// C++20 [class.union]5.
6873static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6874 const Expr *LHSExpr,
6875 const LValue &LHS) {
6876 if (LHS.InvalidBase || LHS.Designator.Invalid)
6877 return false;
6878
6880 // C++ [class.union]p5:
6881 // define the set S(E) of subexpressions of E as follows:
6882 unsigned PathLength = LHS.Designator.Entries.size();
6883 for (const Expr *E = LHSExpr; E != nullptr;) {
6884 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6885 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6886 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6887 // Note that we can't implicitly start the lifetime of a reference,
6888 // so we don't need to proceed any further if we reach one.
6889 if (!FD || FD->getType()->isReferenceType())
6890 break;
6891
6892 // ... and also contains A.B if B names a union member ...
6893 if (FD->getParent()->isUnion()) {
6894 // ... of a non-class, non-array type, or of a class type with a
6895 // trivial default constructor that is not deleted, or an array of
6896 // such types.
6897 auto *RD =
6898 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6899 if (!RD || RD->hasTrivialDefaultConstructor())
6900 UnionPathLengths.push_back({PathLength - 1, FD});
6901 }
6902
6903 E = ME->getBase();
6904 --PathLength;
6905 assert(declaresSameEntity(FD,
6906 LHS.Designator.Entries[PathLength]
6907 .getAsBaseOrMember().getPointer()));
6908
6909 // -- If E is of the form A[B] and is interpreted as a built-in array
6910 // subscripting operator, S(E) is [S(the array operand, if any)].
6911 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6912 // Step over an ArrayToPointerDecay implicit cast.
6913 auto *Base = ASE->getBase()->IgnoreImplicit();
6914 if (!Base->getType()->isArrayType())
6915 break;
6916
6917 E = Base;
6918 --PathLength;
6919
6920 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6921 // Step over a derived-to-base conversion.
6922 E = ICE->getSubExpr();
6923 if (ICE->getCastKind() == CK_NoOp)
6924 continue;
6925 if (ICE->getCastKind() != CK_DerivedToBase &&
6926 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6927 break;
6928 // Walk path backwards as we walk up from the base to the derived class.
6929 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6930 if (Elt->isVirtual()) {
6931 // A class with virtual base classes never has a trivial default
6932 // constructor, so S(E) is empty in this case.
6933 E = nullptr;
6934 break;
6935 }
6936
6937 --PathLength;
6938 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6939 LHS.Designator.Entries[PathLength]
6940 .getAsBaseOrMember().getPointer()));
6941 }
6942
6943 // -- Otherwise, S(E) is empty.
6944 } else {
6945 break;
6946 }
6947 }
6948
6949 // Common case: no unions' lifetimes are started.
6950 if (UnionPathLengths.empty())
6951 return true;
6952
6953 // if modification of X [would access an inactive union member], an object
6954 // of the type of X is implicitly created
6955 CompleteObject Obj =
6956 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6957 if (!Obj)
6958 return false;
6959 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6960 llvm::reverse(UnionPathLengths)) {
6961 // Form a designator for the union object.
6962 SubobjectDesignator D = LHS.Designator;
6963 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6964
6965 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6966 ConstructionPhase::AfterBases;
6967 StartLifetimeOfUnionMemberHandler StartLifetime{
6968 Info, LHSExpr, LengthAndField.second, DuringInit};
6969 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6970 return false;
6971 }
6972
6973 return true;
6974}
6975
6976static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6977 CallRef Call, EvalInfo &Info, bool NonNull = false,
6978 APValue **EvaluatedArg = nullptr) {
6979 LValue LV;
6980 // Create the parameter slot and register its destruction. For a vararg
6981 // argument, create a temporary.
6982 // FIXME: For calling conventions that destroy parameters in the callee,
6983 // should we consider performing destruction when the function returns
6984 // instead?
6985 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6986 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6987 ScopeKind::Call, LV);
6988 if (!EvaluateInPlace(V, Info, LV, Arg))
6989 return false;
6990
6991 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6992 // undefined behavior, so is non-constant.
6993 if (NonNull && V.isLValue() && V.isNullPointer()) {
6994 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6995 return false;
6996 }
6997
6998 if (EvaluatedArg)
6999 *EvaluatedArg = &V;
7000
7001 return true;
7002}
7003
7004/// Evaluate the arguments to a function call.
7005static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7006 EvalInfo &Info, const FunctionDecl *Callee,
7007 bool RightToLeft = false,
7008 LValue *ObjectArg = nullptr) {
7009 bool Success = true;
7010 llvm::SmallBitVector ForbiddenNullArgs;
7011 if (Callee->hasAttr<NonNullAttr>()) {
7012 ForbiddenNullArgs.resize(Args.size());
7013 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7014 if (!Attr->args_size()) {
7015 ForbiddenNullArgs.set();
7016 break;
7017 } else
7018 for (auto Idx : Attr->args()) {
7019 unsigned ASTIdx = Idx.getASTIndex();
7020 if (ASTIdx >= Args.size())
7021 continue;
7022 ForbiddenNullArgs[ASTIdx] = true;
7023 }
7024 }
7025 }
7026 for (unsigned I = 0; I < Args.size(); I++) {
7027 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7028 const ParmVarDecl *PVD =
7029 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7030 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7031 APValue *That = nullptr;
7032 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7033 // If we're checking for a potential constant expression, evaluate all
7034 // initializers even if some of them fail.
7035 if (!Info.noteFailure())
7036 return false;
7037 Success = false;
7038 }
7039 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7040 ObjectArg->setFrom(Info.Ctx, *That);
7041 }
7042 return Success;
7043}
7044
7045/// Perform a trivial copy from Param, which is the parameter of a copy or move
7046/// constructor or assignment operator.
7047static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7048 const Expr *E, APValue &Result,
7049 bool CopyObjectRepresentation) {
7050 // Find the reference argument.
7051 CallStackFrame *Frame = Info.CurrentCall;
7052 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7053 if (!RefValue) {
7054 Info.FFDiag(E);
7055 return false;
7056 }
7057
7058 // Copy out the contents of the RHS object.
7059 LValue RefLValue;
7060 RefLValue.setFrom(Info.Ctx, *RefValue);
7062 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7063 CopyObjectRepresentation);
7064}
7065
7066/// Evaluate a function call.
7068 const FunctionDecl *Callee,
7069 const LValue *ObjectArg, const Expr *E,
7070 ArrayRef<const Expr *> Args, CallRef Call,
7071 const Stmt *Body, EvalInfo &Info,
7072 APValue &Result, const LValue *ResultSlot) {
7073 if (!Info.CheckCallLimit(CallLoc))
7074 return false;
7075
7076 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7077
7078 // For a trivial copy or move assignment, perform an APValue copy. This is
7079 // essential for unions, where the operations performed by the assignment
7080 // operator cannot be represented as statements.
7081 //
7082 // Skip this for non-union classes with no fields; in that case, the defaulted
7083 // copy/move does not actually read the object.
7084 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7085 if (MD && MD->isDefaulted() &&
7086 (MD->getParent()->isUnion() ||
7087 (MD->isTrivial() &&
7089 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7090 assert(ObjectArg &&
7092 APValue RHSValue;
7093 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7094 MD->getParent()->isUnion()))
7095 return false;
7096
7097 LValue Obj;
7098 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7100 RHSValue))
7101 return false;
7102 ObjectArg->moveInto(Result);
7103 return true;
7104 } else if (MD && isLambdaCallOperator(MD)) {
7105 // We're in a lambda; determine the lambda capture field maps unless we're
7106 // just constexpr checking a lambda's call operator. constexpr checking is
7107 // done before the captures have been added to the closure object (unless
7108 // we're inferring constexpr-ness), so we don't have access to them in this
7109 // case. But since we don't need the captures to constexpr check, we can
7110 // just ignore them.
7111 if (!Info.checkingPotentialConstantExpression())
7112 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7113 Frame.LambdaThisCaptureField);
7114 }
7115
7116 StmtResult Ret = {Result, ResultSlot};
7117 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7118 if (ESR == ESR_Succeeded) {
7119 if (Callee->getReturnType()->isVoidType())
7120 return true;
7121 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7122 }
7123 return ESR == ESR_Returned;
7124}
7125
7126/// Evaluate a constructor call.
7127static bool HandleConstructorCall(const Expr *E, const LValue &This,
7128 CallRef Call,
7130 EvalInfo &Info, APValue &Result) {
7131 SourceLocation CallLoc = E->getExprLoc();
7132 if (!Info.CheckCallLimit(CallLoc))
7133 return false;
7134
7135 const CXXRecordDecl *RD = Definition->getParent();
7136 if (RD->getNumVBases()) {
7137 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7138 return false;
7139 }
7140
7141 EvalInfo::EvaluatingConstructorRAII EvalObj(
7142 Info,
7143 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7144 RD->getNumBases());
7145 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7146
7147 // FIXME: Creating an APValue just to hold a nonexistent return value is
7148 // wasteful.
7149 APValue RetVal;
7150 StmtResult Ret = {RetVal, nullptr};
7151
7152 // If it's a delegating constructor, delegate.
7153 if (Definition->isDelegatingConstructor()) {
7155 if ((*I)->getInit()->isValueDependent()) {
7156 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7157 return false;
7158 } else {
7159 FullExpressionRAII InitScope(Info);
7160 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7161 !InitScope.destroy())
7162 return false;
7163 }
7164 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7165 }
7166
7167 // For a trivial copy or move constructor, perform an APValue copy. This is
7168 // essential for unions (or classes with anonymous union members), where the
7169 // operations performed by the constructor cannot be represented by
7170 // ctor-initializers.
7171 //
7172 // Skip this for empty non-union classes; we should not perform an
7173 // lvalue-to-rvalue conversion on them because their copy constructor does not
7174 // actually read them.
7175 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7176 (Definition->getParent()->isUnion() ||
7177 (Definition->isTrivial() &&
7179 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7180 Definition->getParent()->isUnion());
7181 }
7182
7183 // Reserve space for the struct members.
7184 if (!Result.hasValue()) {
7185 if (!RD->isUnion())
7186 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7187 std::distance(RD->field_begin(), RD->field_end()));
7188 else
7189 // A union starts with no active member.
7190 Result = APValue((const FieldDecl*)nullptr);
7191 }
7192
7193 if (RD->isInvalidDecl()) return false;
7194 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7195
7196 // A scope for temporaries lifetime-extended by reference members.
7197 BlockScopeRAII LifetimeExtendedScope(Info);
7198
7199 bool Success = true;
7200 unsigned BasesSeen = 0;
7201#ifndef NDEBUG
7203#endif
7205 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7206 // We might be initializing the same field again if this is an indirect
7207 // field initialization.
7208 if (FieldIt == RD->field_end() ||
7209 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7210 assert(Indirect && "fields out of order?");
7211 return;
7212 }
7213
7214 // Default-initialize any fields with no explicit initializer.
7215 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7216 assert(FieldIt != RD->field_end() && "missing field?");
7217 if (!FieldIt->isUnnamedBitField())
7219 FieldIt->getType(),
7220 Result.getStructField(FieldIt->getFieldIndex()));
7221 }
7222 ++FieldIt;
7223 };
7224 for (const auto *I : Definition->inits()) {
7225 LValue Subobject = This;
7226 LValue SubobjectParent = This;
7227 APValue *Value = &Result;
7228
7229 // Determine the subobject to initialize.
7230 FieldDecl *FD = nullptr;
7231 if (I->isBaseInitializer()) {
7232 QualType BaseType(I->getBaseClass(), 0);
7233#ifndef NDEBUG
7234 // Non-virtual base classes are initialized in the order in the class
7235 // definition. We have already checked for virtual base classes.
7236 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7237 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7238 "base class initializers not in expected order");
7239 ++BaseIt;
7240#endif
7241 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7242 BaseType->getAsCXXRecordDecl(), &Layout))
7243 return false;
7244 Value = &Result.getStructBase(BasesSeen++);
7245 } else if ((FD = I->getMember())) {
7246 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7247 return false;
7248 if (RD->isUnion()) {
7249 Result = APValue(FD);
7250 Value = &Result.getUnionValue();
7251 } else {
7252 SkipToField(FD, false);
7253 Value = &Result.getStructField(FD->getFieldIndex());
7254 }
7255 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7256 // Walk the indirect field decl's chain to find the object to initialize,
7257 // and make sure we've initialized every step along it.
7258 auto IndirectFieldChain = IFD->chain();
7259 for (auto *C : IndirectFieldChain) {
7260 FD = cast<FieldDecl>(C);
7262 // Switch the union field if it differs. This happens if we had
7263 // preceding zero-initialization, and we're now initializing a union
7264 // subobject other than the first.
7265 // FIXME: In this case, the values of the other subobjects are
7266 // specified, since zero-initialization sets all padding bits to zero.
7267 if (!Value->hasValue() ||
7268 (Value->isUnion() &&
7269 !declaresSameEntity(Value->getUnionField(), FD))) {
7270 if (CD->isUnion())
7271 *Value = APValue(FD);
7272 else
7273 // FIXME: This immediately starts the lifetime of all members of
7274 // an anonymous struct. It would be preferable to strictly start
7275 // member lifetime in initialization order.
7277 *Value);
7278 }
7279 // Store Subobject as its parent before updating it for the last element
7280 // in the chain.
7281 if (C == IndirectFieldChain.back())
7282 SubobjectParent = Subobject;
7283 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7284 return false;
7285 if (CD->isUnion())
7286 Value = &Value->getUnionValue();
7287 else {
7288 if (C == IndirectFieldChain.front() && !RD->isUnion())
7289 SkipToField(FD, true);
7290 Value = &Value->getStructField(FD->getFieldIndex());
7291 }
7292 }
7293 } else {
7294 llvm_unreachable("unknown base initializer kind");
7295 }
7296
7297 // Need to override This for implicit field initializers as in this case
7298 // This refers to innermost anonymous struct/union containing initializer,
7299 // not to currently constructed class.
7300 const Expr *Init = I->getInit();
7301 if (Init->isValueDependent()) {
7302 if (!EvaluateDependentExpr(Init, Info))
7303 return false;
7304 } else {
7305 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7307 FullExpressionRAII InitScope(Info);
7308 if (FD && FD->getType()->isReferenceType() &&
7309 !FD->getType()->isFunctionReferenceType()) {
7310 LValue Result;
7311 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7312 *Value)) {
7313 if (!Info.noteFailure())
7314 return false;
7315 Success = false;
7316 }
7317 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7318 (FD && FD->isBitField() &&
7319 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7320 // If we're checking for a potential constant expression, evaluate all
7321 // initializers even if some of them fail.
7322 if (!Info.noteFailure())
7323 return false;
7324 Success = false;
7325 }
7326 }
7327
7328 // This is the point at which the dynamic type of the object becomes this
7329 // class type.
7330 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7331 EvalObj.finishedConstructingBases();
7332 }
7333
7334 // Default-initialize any remaining fields.
7335 if (!RD->isUnion()) {
7336 for (; FieldIt != RD->field_end(); ++FieldIt) {
7337 if (!FieldIt->isUnnamedBitField())
7339 FieldIt->getType(),
7340 Result.getStructField(FieldIt->getFieldIndex()));
7341 }
7342 }
7343
7344 EvalObj.finishedConstructingFields();
7345
7346 return Success &&
7347 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7348 LifetimeExtendedScope.destroy();
7349}
7350
7351static bool HandleConstructorCall(const Expr *E, const LValue &This,
7354 EvalInfo &Info, APValue &Result) {
7355 CallScopeRAII CallScope(Info);
7356 CallRef Call = Info.CurrentCall->createCall(Definition);
7357 if (!EvaluateArgs(Args, Call, Info, Definition))
7358 return false;
7359
7360 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7361 CallScope.destroy();
7362}
7363
7364static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7365 const LValue &This, APValue &Value,
7366 QualType T) {
7367 // Objects can only be destroyed while they're within their lifetimes.
7368 // FIXME: We have no representation for whether an object of type nullptr_t
7369 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7370 // as indeterminate instead?
7371 if (Value.isAbsent() && !T->isNullPtrType()) {
7372 APValue Printable;
7373 This.moveInto(Printable);
7374 Info.FFDiag(CallRange.getBegin(),
7375 diag::note_constexpr_destroy_out_of_lifetime)
7376 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7377 return false;
7378 }
7379
7380 // Invent an expression for location purposes.
7381 // FIXME: We shouldn't need to do this.
7382 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7383
7384 // For arrays, destroy elements right-to-left.
7385 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7386 uint64_t Size = CAT->getZExtSize();
7387 QualType ElemT = CAT->getElementType();
7388
7389 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7390 return false;
7391
7392 LValue ElemLV = This;
7393 ElemLV.addArray(Info, &LocE, CAT);
7394 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7395 return false;
7396
7397 // Ensure that we have actual array elements available to destroy; the
7398 // destructors might mutate the value, so we can't run them on the array
7399 // filler.
7400 if (Size && Size > Value.getArrayInitializedElts())
7401 expandArray(Value, Value.getArraySize() - 1);
7402
7403 // The size of the array might have been reduced by
7404 // a placement new.
7405 for (Size = Value.getArraySize(); Size != 0; --Size) {
7406 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7407 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7408 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7409 return false;
7410 }
7411
7412 // End the lifetime of this array now.
7413 Value = APValue();
7414 return true;
7415 }
7416
7417 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7418 if (!RD) {
7419 if (T.isDestructedType()) {
7420 Info.FFDiag(CallRange.getBegin(),
7421 diag::note_constexpr_unsupported_destruction)
7422 << T;
7423 return false;
7424 }
7425
7426 Value = APValue();
7427 return true;
7428 }
7429
7430 if (RD->getNumVBases()) {
7431 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7432 return false;
7433 }
7434
7435 const CXXDestructorDecl *DD = RD->getDestructor();
7436 if (!DD && !RD->hasTrivialDestructor()) {
7437 Info.FFDiag(CallRange.getBegin());
7438 return false;
7439 }
7440
7441 if (!DD || DD->isTrivial() ||
7442 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7443 // A trivial destructor just ends the lifetime of the object. Check for
7444 // this case before checking for a body, because we might not bother
7445 // building a body for a trivial destructor. Note that it doesn't matter
7446 // whether the destructor is constexpr in this case; all trivial
7447 // destructors are constexpr.
7448 //
7449 // If an anonymous union would be destroyed, some enclosing destructor must
7450 // have been explicitly defined, and the anonymous union destruction should
7451 // have no effect.
7452 Value = APValue();
7453 return true;
7454 }
7455
7456 if (!Info.CheckCallLimit(CallRange.getBegin()))
7457 return false;
7458
7459 const FunctionDecl *Definition = nullptr;
7460 const Stmt *Body = DD->getBody(Definition);
7461
7462 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7463 return false;
7464
7465 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7466 CallRef());
7467
7468 // We're now in the period of destruction of this object.
7469 unsigned BasesLeft = RD->getNumBases();
7470 EvalInfo::EvaluatingDestructorRAII EvalObj(
7471 Info,
7472 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7473 if (!EvalObj.DidInsert) {
7474 // C++2a [class.dtor]p19:
7475 // the behavior is undefined if the destructor is invoked for an object
7476 // whose lifetime has ended
7477 // (Note that formally the lifetime ends when the period of destruction
7478 // begins, even though certain uses of the object remain valid until the
7479 // period of destruction ends.)
7480 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7481 return false;
7482 }
7483
7484 // FIXME: Creating an APValue just to hold a nonexistent return value is
7485 // wasteful.
7486 APValue RetVal;
7487 StmtResult Ret = {RetVal, nullptr};
7488 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7489 return false;
7490
7491 // A union destructor does not implicitly destroy its members.
7492 if (RD->isUnion())
7493 return true;
7494
7495 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7496
7497 // We don't have a good way to iterate fields in reverse, so collect all the
7498 // fields first and then walk them backwards.
7499 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7500 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7501 if (FD->isUnnamedBitField())
7502 continue;
7503
7504 LValue Subobject = This;
7505 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7506 return false;
7507
7508 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7509 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7510 FD->getType()))
7511 return false;
7512 }
7513
7514 if (BasesLeft != 0)
7515 EvalObj.startedDestroyingBases();
7516
7517 // Destroy base classes in reverse order.
7518 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7519 --BasesLeft;
7520
7521 QualType BaseType = Base.getType();
7522 LValue Subobject = This;
7523 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7524 BaseType->getAsCXXRecordDecl(), &Layout))
7525 return false;
7526
7527 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7528 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7529 BaseType))
7530 return false;
7531 }
7532 assert(BasesLeft == 0 && "NumBases was wrong?");
7533
7534 // The period of destruction ends now. The object is gone.
7535 Value = APValue();
7536 return true;
7537}
7538
7539namespace {
7540struct DestroyObjectHandler {
7541 EvalInfo &Info;
7542 const Expr *E;
7543 const LValue &This;
7544 const AccessKinds AccessKind;
7545
7546 typedef bool result_type;
7547 bool failed() { return false; }
7548 bool found(APValue &Subobj, QualType SubobjType) {
7549 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7550 SubobjType);
7551 }
7552 bool found(APSInt &Value, QualType SubobjType) {
7553 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7554 return false;
7555 }
7556 bool found(APFloat &Value, QualType SubobjType) {
7557 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7558 return false;
7559 }
7560};
7561}
7562
7563/// Perform a destructor or pseudo-destructor call on the given object, which
7564/// might in general not be a complete object.
7565static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7566 const LValue &This, QualType ThisType) {
7567 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7568 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7569 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7570}
7571
7572/// Destroy and end the lifetime of the given complete object.
7573static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7575 QualType T) {
7576 // If we've had an unmodeled side-effect, we can't rely on mutable state
7577 // (such as the object we're about to destroy) being correct.
7578 if (Info.EvalStatus.HasSideEffects)
7579 return false;
7580
7581 LValue LV;
7582 LV.set({LVBase});
7583 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7584}
7585
7586/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7587static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7588 LValue &Result) {
7589 if (Info.checkingPotentialConstantExpression() ||
7590 Info.SpeculativeEvaluationDepth)
7591 return false;
7592
7593 // This is permitted only within a call to std::allocator<T>::allocate.
7594 auto Caller = Info.getStdAllocatorCaller("allocate");
7595 if (!Caller) {
7596 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7597 ? diag::note_constexpr_new_untyped
7598 : diag::note_constexpr_new);
7599 return false;
7600 }
7601
7602 QualType ElemType = Caller.ElemType;
7603 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7604 Info.FFDiag(E->getExprLoc(),
7605 diag::note_constexpr_new_not_complete_object_type)
7606 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7607 return false;
7608 }
7609
7610 APSInt ByteSize;
7611 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7612 return false;
7613 bool IsNothrow = false;
7614 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7615 EvaluateIgnoredValue(Info, E->getArg(I));
7616 IsNothrow |= E->getType()->isNothrowT();
7617 }
7618
7619 CharUnits ElemSize;
7620 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7621 return false;
7622 APInt Size, Remainder;
7623 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7624 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7625 if (Remainder != 0) {
7626 // This likely indicates a bug in the implementation of 'std::allocator'.
7627 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7628 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7629 return false;
7630 }
7631
7632 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7633 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7634 if (IsNothrow) {
7635 Result.setNull(Info.Ctx, E->getType());
7636 return true;
7637 }
7638 return false;
7639 }
7640
7641 QualType AllocType = Info.Ctx.getConstantArrayType(
7642 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7643 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7644 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7645 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7646 return true;
7647}
7648
7650 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7651 if (CXXDestructorDecl *DD = RD->getDestructor())
7652 return DD->isVirtual();
7653 return false;
7654}
7655
7657 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7658 if (CXXDestructorDecl *DD = RD->getDestructor())
7659 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7660 return nullptr;
7661}
7662
7663/// Check that the given object is a suitable pointer to a heap allocation that
7664/// still exists and is of the right kind for the purpose of a deletion.
7665///
7666/// On success, returns the heap allocation to deallocate. On failure, produces
7667/// a diagnostic and returns std::nullopt.
7668static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7669 const LValue &Pointer,
7670 DynAlloc::Kind DeallocKind) {
7671 auto PointerAsString = [&] {
7672 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7673 };
7674
7675 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7676 if (!DA) {
7677 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7678 << PointerAsString();
7679 if (Pointer.Base)
7680 NoteLValueLocation(Info, Pointer.Base);
7681 return std::nullopt;
7682 }
7683
7684 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7685 if (!Alloc) {
7686 Info.FFDiag(E, diag::note_constexpr_double_delete);
7687 return std::nullopt;
7688 }
7689
7690 if (DeallocKind != (*Alloc)->getKind()) {
7691 QualType AllocType = Pointer.Base.getDynamicAllocType();
7692 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7693 << DeallocKind << (*Alloc)->getKind() << AllocType;
7694 NoteLValueLocation(Info, Pointer.Base);
7695 return std::nullopt;
7696 }
7697
7698 bool Subobject = false;
7699 if (DeallocKind == DynAlloc::New) {
7700 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7701 Pointer.Designator.isOnePastTheEnd();
7702 } else {
7703 Subobject = Pointer.Designator.Entries.size() != 1 ||
7704 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7705 }
7706 if (Subobject) {
7707 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7708 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7709 return std::nullopt;
7710 }
7711
7712 return Alloc;
7713}
7714
7715// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7716static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7717 if (Info.checkingPotentialConstantExpression() ||
7718 Info.SpeculativeEvaluationDepth)
7719 return false;
7720
7721 // This is permitted only within a call to std::allocator<T>::deallocate.
7722 if (!Info.getStdAllocatorCaller("deallocate")) {
7723 Info.FFDiag(E->getExprLoc());
7724 return true;
7725 }
7726
7727 LValue Pointer;
7728 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7729 return false;
7730 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7731 EvaluateIgnoredValue(Info, E->getArg(I));
7732
7733 if (Pointer.Designator.Invalid)
7734 return false;
7735
7736 // Deleting a null pointer would have no effect, but it's not permitted by
7737 // std::allocator<T>::deallocate's contract.
7738 if (Pointer.isNullPointer()) {
7739 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7740 return true;
7741 }
7742
7743 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7744 return false;
7745
7746 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7747 return true;
7748}
7749
7750//===----------------------------------------------------------------------===//
7751// Generic Evaluation
7752//===----------------------------------------------------------------------===//
7753namespace {
7754
7755class BitCastBuffer {
7756 // FIXME: We're going to need bit-level granularity when we support
7757 // bit-fields.
7758 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7759 // we don't support a host or target where that is the case. Still, we should
7760 // use a more generic type in case we ever do.
7761 SmallVector<std::optional<unsigned char>, 32> Bytes;
7762
7763 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7764 "Need at least 8 bit unsigned char");
7765
7766 bool TargetIsLittleEndian;
7767
7768public:
7769 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7770 : Bytes(Width.getQuantity()),
7771 TargetIsLittleEndian(TargetIsLittleEndian) {}
7772
7773 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7774 SmallVectorImpl<unsigned char> &Output) const {
7775 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7776 // If a byte of an integer is uninitialized, then the whole integer is
7777 // uninitialized.
7778 if (!Bytes[I.getQuantity()])
7779 return false;
7780 Output.push_back(*Bytes[I.getQuantity()]);
7781 }
7782 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7783 std::reverse(Output.begin(), Output.end());
7784 return true;
7785 }
7786
7787 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7788 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7789 std::reverse(Input.begin(), Input.end());
7790
7791 size_t Index = 0;
7792 for (unsigned char Byte : Input) {
7793 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7794 Bytes[Offset.getQuantity() + Index] = Byte;
7795 ++Index;
7796 }
7797 }
7798
7799 size_t size() { return Bytes.size(); }
7800};
7801
7802/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7803/// target would represent the value at runtime.
7804class APValueToBufferConverter {
7805 EvalInfo &Info;
7806 BitCastBuffer Buffer;
7807 const CastExpr *BCE;
7808
7809 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7810 const CastExpr *BCE)
7811 : Info(Info),
7812 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7813 BCE(BCE) {}
7814
7815 bool visit(const APValue &Val, QualType Ty) {
7816 return visit(Val, Ty, CharUnits::fromQuantity(0));
7817 }
7818
7819 // Write out Val with type Ty into Buffer starting at Offset.
7820 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7821 assert((size_t)Offset.getQuantity() <= Buffer.size());
7822
7823 // As a special case, nullptr_t has an indeterminate value.
7824 if (Ty->isNullPtrType())
7825 return true;
7826
7827 // Dig through Src to find the byte at SrcOffset.
7828 switch (Val.getKind()) {
7830 case APValue::None:
7831 return true;
7832
7833 case APValue::Int:
7834 return visitInt(Val.getInt(), Ty, Offset);
7835 case APValue::Float:
7836 return visitFloat(Val.getFloat(), Ty, Offset);
7837 case APValue::Array:
7838 return visitArray(Val, Ty, Offset);
7839 case APValue::Struct:
7840 return visitRecord(Val, Ty, Offset);
7841 case APValue::Vector:
7842 return visitVector(Val, Ty, Offset);
7843
7846 return visitComplex(Val, Ty, Offset);
7848 // FIXME: We should support these.
7849
7850 case APValue::Union:
7853 Info.FFDiag(BCE->getBeginLoc(),
7854 diag::note_constexpr_bit_cast_unsupported_type)
7855 << Ty;
7856 return false;
7857 }
7858
7859 case APValue::LValue:
7860 llvm_unreachable("LValue subobject in bit_cast?");
7861 }
7862 llvm_unreachable("Unhandled APValue::ValueKind");
7863 }
7864
7865 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7866 const RecordDecl *RD = Ty->getAsRecordDecl();
7867 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7868
7869 // Visit the base classes.
7870 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7871 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7872 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7873 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7874 const APValue &Base = Val.getStructBase(I);
7875
7876 // Can happen in error cases.
7877 if (!Base.isStruct())
7878 return false;
7879
7880 if (!visitRecord(Base, BS.getType(),
7881 Layout.getBaseClassOffset(BaseDecl) + Offset))
7882 return false;
7883 }
7884 }
7885
7886 // Visit the fields.
7887 unsigned FieldIdx = 0;
7888 for (FieldDecl *FD : RD->fields()) {
7889 if (FD->isBitField()) {
7890 Info.FFDiag(BCE->getBeginLoc(),
7891 diag::note_constexpr_bit_cast_unsupported_bitfield);
7892 return false;
7893 }
7894
7895 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7896
7897 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7898 "only bit-fields can have sub-char alignment");
7899 CharUnits FieldOffset =
7900 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7901 QualType FieldTy = FD->getType();
7902 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7903 return false;
7904 ++FieldIdx;
7905 }
7906
7907 return true;
7908 }
7909
7910 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7911 const auto *CAT =
7912 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7913 if (!CAT)
7914 return false;
7915
7916 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7917 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7918 unsigned ArraySize = Val.getArraySize();
7919 // First, initialize the initialized elements.
7920 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7921 const APValue &SubObj = Val.getArrayInitializedElt(I);
7922 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7923 return false;
7924 }
7925
7926 // Next, initialize the rest of the array using the filler.
7927 if (Val.hasArrayFiller()) {
7928 const APValue &Filler = Val.getArrayFiller();
7929 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7930 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7931 return false;
7932 }
7933 }
7934
7935 return true;
7936 }
7937
7938 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7939 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7940 QualType EltTy = ComplexTy->getElementType();
7941 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7942 bool IsInt = Val.isComplexInt();
7943
7944 if (IsInt) {
7945 if (!visitInt(Val.getComplexIntReal(), EltTy,
7946 Offset + (0 * EltSizeChars)))
7947 return false;
7948 if (!visitInt(Val.getComplexIntImag(), EltTy,
7949 Offset + (1 * EltSizeChars)))
7950 return false;
7951 } else {
7952 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7953 Offset + (0 * EltSizeChars)))
7954 return false;
7955 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7956 Offset + (1 * EltSizeChars)))
7957 return false;
7958 }
7959
7960 return true;
7961 }
7962
7963 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7964 const VectorType *VTy = Ty->castAs<VectorType>();
7965 QualType EltTy = VTy->getElementType();
7966 unsigned NElts = VTy->getNumElements();
7967
7968 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7969 // Special handling for OpenCL bool vectors:
7970 // Since these vectors are stored as packed bits, but we can't write
7971 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7972 // together into an appropriately sized APInt and write them all out at
7973 // once. Because we don't accept vectors where NElts * EltSize isn't a
7974 // multiple of the char size, there will be no padding space, so we don't
7975 // have to worry about writing data which should have been left
7976 // uninitialized.
7977 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7978
7979 llvm::APInt Res = llvm::APInt::getZero(NElts);
7980 for (unsigned I = 0; I < NElts; ++I) {
7981 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7982 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7983 "bool vector element must be 1-bit unsigned integer!");
7984
7985 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7986 }
7987
7988 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7989 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7990 Buffer.writeObject(Offset, Bytes);
7991 } else {
7992 // Iterate over each of the elements and write them out to the buffer at
7993 // the appropriate offset.
7994 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7995 for (unsigned I = 0; I < NElts; ++I) {
7996 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7997 return false;
7998 }
7999 }
8000
8001 return true;
8002 }
8003
8004 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8005 APSInt AdjustedVal = Val;
8006 unsigned Width = AdjustedVal.getBitWidth();
8007 if (Ty->isBooleanType()) {
8008 Width = Info.Ctx.getTypeSize(Ty);
8009 AdjustedVal = AdjustedVal.extend(Width);
8010 }
8011
8012 SmallVector<uint8_t, 8> Bytes(Width / 8);
8013 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8014 Buffer.writeObject(Offset, Bytes);
8015 return true;
8016 }
8017
8018 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8019 APSInt AsInt(Val.bitcastToAPInt());
8020 return visitInt(AsInt, Ty, Offset);
8021 }
8022
8023public:
8024 static std::optional<BitCastBuffer>
8025 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8026 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8027 APValueToBufferConverter Converter(Info, DstSize, BCE);
8028 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8029 return std::nullopt;
8030 return Converter.Buffer;
8031 }
8032};
8033
8034/// Write an BitCastBuffer into an APValue.
8035class BufferToAPValueConverter {
8036 EvalInfo &Info;
8037 const BitCastBuffer &Buffer;
8038 const CastExpr *BCE;
8039
8040 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8041 const CastExpr *BCE)
8042 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8043
8044 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8045 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8046 // Ideally this will be unreachable.
8047 std::nullopt_t unsupportedType(QualType Ty) {
8048 Info.FFDiag(BCE->getBeginLoc(),
8049 diag::note_constexpr_bit_cast_unsupported_type)
8050 << Ty;
8051 return std::nullopt;
8052 }
8053
8054 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8055 Info.FFDiag(BCE->getBeginLoc(),
8056 diag::note_constexpr_bit_cast_unrepresentable_value)
8057 << Ty << toString(Val, /*Radix=*/10);
8058 return std::nullopt;
8059 }
8060
8061 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8062 const EnumType *EnumSugar = nullptr) {
8063 if (T->isNullPtrType()) {
8064 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8065 return APValue((Expr *)nullptr,
8066 /*Offset=*/CharUnits::fromQuantity(NullValue),
8067 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8068 }
8069
8070 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8071
8072 // Work around floating point types that contain unused padding bytes. This
8073 // is really just `long double` on x86, which is the only fundamental type
8074 // with padding bytes.
8075 if (T->isRealFloatingType()) {
8076 const llvm::fltSemantics &Semantics =
8077 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8078 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8079 assert(NumBits % 8 == 0);
8080 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8081 if (NumBytes != SizeOf)
8082 SizeOf = NumBytes;
8083 }
8084
8085 SmallVector<uint8_t, 8> Bytes;
8086 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8087 // If this is std::byte or unsigned char, then its okay to store an
8088 // indeterminate value.
8089 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8090 bool IsUChar =
8091 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8092 T->isSpecificBuiltinType(BuiltinType::Char_U));
8093 if (!IsStdByte && !IsUChar) {
8094 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8095 Info.FFDiag(BCE->getExprLoc(),
8096 diag::note_constexpr_bit_cast_indet_dest)
8097 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8098 return std::nullopt;
8099 }
8100
8102 }
8103
8104 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8105 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8106
8108 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8109
8110 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8111 if (IntWidth != Val.getBitWidth()) {
8112 APSInt Truncated = Val.trunc(IntWidth);
8113 if (Truncated.extend(Val.getBitWidth()) != Val)
8114 return unrepresentableValue(QualType(T, 0), Val);
8115 Val = Truncated;
8116 }
8117
8118 return APValue(Val);
8119 }
8120
8121 if (T->isRealFloatingType()) {
8122 const llvm::fltSemantics &Semantics =
8123 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8124 return APValue(APFloat(Semantics, Val));
8125 }
8126
8127 return unsupportedType(QualType(T, 0));
8128 }
8129
8130 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8131 const RecordDecl *RD = RTy->getAsRecordDecl();
8132 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8133
8134 unsigned NumBases = 0;
8135 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8136 NumBases = CXXRD->getNumBases();
8137
8138 APValue ResultVal(APValue::UninitStruct(), NumBases,
8139 std::distance(RD->field_begin(), RD->field_end()));
8140
8141 // Visit the base classes.
8142 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8143 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8144 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8145 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8146
8147 std::optional<APValue> SubObj = visitType(
8148 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8149 if (!SubObj)
8150 return std::nullopt;
8151 ResultVal.getStructBase(I) = *SubObj;
8152 }
8153 }
8154
8155 // Visit the fields.
8156 unsigned FieldIdx = 0;
8157 for (FieldDecl *FD : RD->fields()) {
8158 // FIXME: We don't currently support bit-fields. A lot of the logic for
8159 // this is in CodeGen, so we need to factor it around.
8160 if (FD->isBitField()) {
8161 Info.FFDiag(BCE->getBeginLoc(),
8162 diag::note_constexpr_bit_cast_unsupported_bitfield);
8163 return std::nullopt;
8164 }
8165
8166 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8167 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8168
8169 CharUnits FieldOffset =
8170 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8171 Offset;
8172 QualType FieldTy = FD->getType();
8173 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8174 if (!SubObj)
8175 return std::nullopt;
8176 ResultVal.getStructField(FieldIdx) = *SubObj;
8177 ++FieldIdx;
8178 }
8179
8180 return ResultVal;
8181 }
8182
8183 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8184 QualType RepresentationType =
8185 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8186 assert(!RepresentationType.isNull() &&
8187 "enum forward decl should be caught by Sema");
8188 const auto *AsBuiltin =
8189 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8190 // Recurse into the underlying type. Treat std::byte transparently as
8191 // unsigned char.
8192 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8193 }
8194
8195 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8196 size_t Size = Ty->getLimitedSize();
8197 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8198
8199 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8200 for (size_t I = 0; I != Size; ++I) {
8201 std::optional<APValue> ElementValue =
8202 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8203 if (!ElementValue)
8204 return std::nullopt;
8205 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8206 }
8207
8208 return ArrayValue;
8209 }
8210
8211 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8212 QualType ElementType = Ty->getElementType();
8213 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8214 bool IsInt = ElementType->isIntegerType();
8215
8216 std::optional<APValue> Values[2];
8217 for (unsigned I = 0; I != 2; ++I) {
8218 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8219 if (!Values[I])
8220 return std::nullopt;
8221 }
8222
8223 if (IsInt)
8224 return APValue(Values[0]->getInt(), Values[1]->getInt());
8225 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8226 }
8227
8228 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8229 QualType EltTy = VTy->getElementType();
8230 unsigned NElts = VTy->getNumElements();
8231 unsigned EltSize =
8232 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8233
8234 SmallVector<APValue, 4> Elts;
8235 Elts.reserve(NElts);
8236 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8237 // Special handling for OpenCL bool vectors:
8238 // Since these vectors are stored as packed bits, but we can't read
8239 // individual bits from the BitCastBuffer, we'll buffer all of the
8240 // elements together into an appropriately sized APInt and write them all
8241 // out at once. Because we don't accept vectors where NElts * EltSize
8242 // isn't a multiple of the char size, there will be no padding space, so
8243 // we don't have to worry about reading any padding data which didn't
8244 // actually need to be accessed.
8245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8246
8247 SmallVector<uint8_t, 8> Bytes;
8248 Bytes.reserve(NElts / 8);
8249 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8250 return std::nullopt;
8251
8252 APSInt SValInt(NElts, true);
8253 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8254
8255 for (unsigned I = 0; I < NElts; ++I) {
8256 llvm::APInt Elt =
8257 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8258 Elts.emplace_back(
8259 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8260 }
8261 } else {
8262 // Iterate over each of the elements and read them from the buffer at
8263 // the appropriate offset.
8264 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8265 for (unsigned I = 0; I < NElts; ++I) {
8266 std::optional<APValue> EltValue =
8267 visitType(EltTy, Offset + I * EltSizeChars);
8268 if (!EltValue)
8269 return std::nullopt;
8270 Elts.push_back(std::move(*EltValue));
8271 }
8272 }
8273
8274 return APValue(Elts.data(), Elts.size());
8275 }
8276
8277 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8278 return unsupportedType(QualType(Ty, 0));
8279 }
8280
8281 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8282 QualType Can = Ty.getCanonicalType();
8283
8284 switch (Can->getTypeClass()) {
8285#define TYPE(Class, Base) \
8286 case Type::Class: \
8287 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8288#define ABSTRACT_TYPE(Class, Base)
8289#define NON_CANONICAL_TYPE(Class, Base) \
8290 case Type::Class: \
8291 llvm_unreachable("non-canonical type should be impossible!");
8292#define DEPENDENT_TYPE(Class, Base) \
8293 case Type::Class: \
8294 llvm_unreachable( \
8295 "dependent types aren't supported in the constant evaluator!");
8296#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8297 case Type::Class: \
8298 llvm_unreachable("either dependent or not canonical!");
8299#include "clang/AST/TypeNodes.inc"
8300 }
8301 llvm_unreachable("Unhandled Type::TypeClass");
8302 }
8303
8304public:
8305 // Pull out a full value of type DstType.
8306 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8307 const CastExpr *BCE) {
8308 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8309 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8310 }
8311};
8312
8313static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8314 QualType Ty, EvalInfo *Info,
8315 const ASTContext &Ctx,
8316 bool CheckingDest) {
8317 Ty = Ty.getCanonicalType();
8318
8319 auto diag = [&](int Reason) {
8320 if (Info)
8321 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8322 << CheckingDest << (Reason == 4) << Reason;
8323 return false;
8324 };
8325 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8326 if (Info)
8327 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8328 << NoteTy << Construct << Ty;
8329 return false;
8330 };
8331
8332 if (Ty->isUnionType())
8333 return diag(0);
8334 if (Ty->isPointerType())
8335 return diag(1);
8336 if (Ty->isMemberPointerType())
8337 return diag(2);
8338 if (Ty.isVolatileQualified())
8339 return diag(3);
8340
8341 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8342 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8343 for (CXXBaseSpecifier &BS : CXXRD->bases())
8344 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8345 CheckingDest))
8346 return note(1, BS.getType(), BS.getBeginLoc());
8347 }
8348 for (FieldDecl *FD : Record->fields()) {
8349 if (FD->getType()->isReferenceType())
8350 return diag(4);
8351 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8352 CheckingDest))
8353 return note(0, FD->getType(), FD->getBeginLoc());
8354 }
8355 }
8356
8357 if (Ty->isArrayType() &&
8358 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8359 Info, Ctx, CheckingDest))
8360 return false;
8361
8362 if (const auto *VTy = Ty->getAs<VectorType>()) {
8363 QualType EltTy = VTy->getElementType();
8364 unsigned NElts = VTy->getNumElements();
8365 unsigned EltSize =
8366 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8367
8368 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8369 // The vector's size in bits is not a multiple of the target's byte size,
8370 // so its layout is unspecified. For now, we'll simply treat these cases
8371 // as unsupported (this should only be possible with OpenCL bool vectors
8372 // whose element count isn't a multiple of the byte size).
8373 if (Info)
8374 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8375 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8376 return false;
8377 }
8378
8379 if (EltTy->isRealFloatingType() &&
8380 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8381 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8382 // by both clang and LLVM, so for now we won't allow bit_casts involving
8383 // it in a constexpr context.
8384 if (Info)
8385 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8386 << EltTy;
8387 return false;
8388 }
8389 }
8390
8391 return true;
8392}
8393
8394static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8395 const ASTContext &Ctx,
8396 const CastExpr *BCE) {
8397 bool DestOK = checkBitCastConstexprEligibilityType(
8398 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8399 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8400 BCE->getBeginLoc(),
8401 BCE->getSubExpr()->getType(), Info, Ctx, false);
8402 return SourceOK;
8403}
8404
8405static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8406 const APValue &SourceRValue,
8407 const CastExpr *BCE) {
8408 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8409 "no host or target supports non 8-bit chars");
8410
8411 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8412 return false;
8413
8414 // Read out SourceValue into a char buffer.
8415 std::optional<BitCastBuffer> Buffer =
8416 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8417 if (!Buffer)
8418 return false;
8419
8420 // Write out the buffer into a new APValue.
8421 std::optional<APValue> MaybeDestValue =
8422 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8423 if (!MaybeDestValue)
8424 return false;
8425
8426 DestValue = std::move(*MaybeDestValue);
8427 return true;
8428}
8429
8430static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8431 APValue &SourceValue,
8432 const CastExpr *BCE) {
8433 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8434 "no host or target supports non 8-bit chars");
8435 assert(SourceValue.isLValue() &&
8436 "LValueToRValueBitcast requires an lvalue operand!");
8437
8438 LValue SourceLValue;
8439 APValue SourceRValue;
8440 SourceLValue.setFrom(Info.Ctx, SourceValue);
8442 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8443 SourceRValue, /*WantObjectRepresentation=*/true))
8444 return false;
8445
8446 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8447}
8448
8449template <class Derived>
8450class ExprEvaluatorBase
8451 : public ConstStmtVisitor<Derived, bool> {
8452private:
8453 Derived &getDerived() { return static_cast<Derived&>(*this); }
8454 bool DerivedSuccess(const APValue &V, const Expr *E) {
8455 return getDerived().Success(V, E);
8456 }
8457 bool DerivedZeroInitialization(const Expr *E) {
8458 return getDerived().ZeroInitialization(E);
8459 }
8460
8461 // Check whether a conditional operator with a non-constant condition is a
8462 // potential constant expression. If neither arm is a potential constant
8463 // expression, then the conditional operator is not either.
8464 template<typename ConditionalOperator>
8465 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8466 assert(Info.checkingPotentialConstantExpression());
8467
8468 // Speculatively evaluate both arms.
8469 SmallVector<PartialDiagnosticAt, 8> Diag;
8470 {
8471 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8472 StmtVisitorTy::Visit(E->getFalseExpr());
8473 if (Diag.empty())
8474 return;
8475 }
8476
8477 {
8478 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8479 Diag.clear();
8480 StmtVisitorTy::Visit(E->getTrueExpr());
8481 if (Diag.empty())
8482 return;
8483 }
8484
8485 Error(E, diag::note_constexpr_conditional_never_const);
8486 }
8487
8488
8489 template<typename ConditionalOperator>
8490 bool HandleConditionalOperator(const ConditionalOperator *E) {
8491 bool BoolResult;
8492 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8493 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8494 CheckPotentialConstantConditional(E);
8495 return false;
8496 }
8497 if (Info.noteFailure()) {
8498 StmtVisitorTy::Visit(E->getTrueExpr());
8499 StmtVisitorTy::Visit(E->getFalseExpr());
8500 }
8501 return false;
8502 }
8503
8504 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8505 return StmtVisitorTy::Visit(EvalExpr);
8506 }
8507
8508protected:
8509 EvalInfo &Info;
8510 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8511 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8512
8513 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8514 return Info.CCEDiag(E, D);
8515 }
8516
8517 bool ZeroInitialization(const Expr *E) { return Error(E); }
8518
8519 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8520 unsigned BuiltinOp = E->getBuiltinCallee();
8521 return BuiltinOp != 0 &&
8522 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8523 }
8524
8525public:
8526 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8527
8528 EvalInfo &getEvalInfo() { return Info; }
8529
8530 /// Report an evaluation error. This should only be called when an error is
8531 /// first discovered. When propagating an error, just return false.
8532 bool Error(const Expr *E, diag::kind D) {
8533 Info.FFDiag(E, D) << E->getSourceRange();
8534 return false;
8535 }
8536 bool Error(const Expr *E) {
8537 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8538 }
8539
8540 bool VisitStmt(const Stmt *) {
8541 llvm_unreachable("Expression evaluator should not be called on stmts");
8542 }
8543 bool VisitExpr(const Expr *E) {
8544 return Error(E);
8545 }
8546
8547 bool VisitEmbedExpr(const EmbedExpr *E) {
8548 const auto It = E->begin();
8549 return StmtVisitorTy::Visit(*It);
8550 }
8551
8552 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8553 return StmtVisitorTy::Visit(E->getFunctionName());
8554 }
8555 bool VisitConstantExpr(const ConstantExpr *E) {
8556 if (E->hasAPValueResult())
8557 return DerivedSuccess(E->getAPValueResult(), E);
8558
8559 return StmtVisitorTy::Visit(E->getSubExpr());
8560 }
8561
8562 bool VisitParenExpr(const ParenExpr *E)
8563 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8564 bool VisitUnaryExtension(const UnaryOperator *E)
8565 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8566 bool VisitUnaryPlus(const UnaryOperator *E)
8567 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8568 bool VisitChooseExpr(const ChooseExpr *E)
8569 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8571 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8572 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8573 { return StmtVisitorTy::Visit(E->getReplacement()); }
8574 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8575 TempVersionRAII RAII(*Info.CurrentCall);
8576 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8577 return StmtVisitorTy::Visit(E->getExpr());
8578 }
8579 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8580 TempVersionRAII RAII(*Info.CurrentCall);
8581 // The initializer may not have been parsed yet, or might be erroneous.
8582 if (!E->getExpr())
8583 return Error(E);
8584 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8585 return StmtVisitorTy::Visit(E->getExpr());
8586 }
8587
8588 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8589 FullExpressionRAII Scope(Info);
8590 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8591 }
8592
8593 // Temporaries are registered when created, so we don't care about
8594 // CXXBindTemporaryExpr.
8595 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8596 return StmtVisitorTy::Visit(E->getSubExpr());
8597 }
8598
8599 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8600 CCEDiag(E, diag::note_constexpr_invalid_cast)
8601 << diag::ConstexprInvalidCastKind::Reinterpret;
8602 return static_cast<Derived*>(this)->VisitCastExpr(E);
8603 }
8604 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8605 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8606 CCEDiag(E, diag::note_constexpr_invalid_cast)
8607 << diag::ConstexprInvalidCastKind::Dynamic;
8608 return static_cast<Derived*>(this)->VisitCastExpr(E);
8609 }
8610 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8611 return static_cast<Derived*>(this)->VisitCastExpr(E);
8612 }
8613
8614 bool VisitBinaryOperator(const BinaryOperator *E) {
8615 switch (E->getOpcode()) {
8616 default:
8617 return Error(E);
8618
8619 case BO_Comma:
8620 VisitIgnoredValue(E->getLHS());
8621 return StmtVisitorTy::Visit(E->getRHS());
8622
8623 case BO_PtrMemD:
8624 case BO_PtrMemI: {
8625 LValue Obj;
8626 if (!HandleMemberPointerAccess(Info, E, Obj))
8627 return false;
8629 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8630 return false;
8631 return DerivedSuccess(Result, E);
8632 }
8633 }
8634 }
8635
8636 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8637 return StmtVisitorTy::Visit(E->getSemanticForm());
8638 }
8639
8640 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8641 // Evaluate and cache the common expression. We treat it as a temporary,
8642 // even though it's not quite the same thing.
8643 LValue CommonLV;
8644 if (!Evaluate(Info.CurrentCall->createTemporary(
8645 E->getOpaqueValue(),
8646 getStorageType(Info.Ctx, E->getOpaqueValue()),
8647 ScopeKind::FullExpression, CommonLV),
8648 Info, E->getCommon()))
8649 return false;
8650
8651 return HandleConditionalOperator(E);
8652 }
8653
8654 bool VisitConditionalOperator(const ConditionalOperator *E) {
8655 bool IsBcpCall = false;
8656 // If the condition (ignoring parens) is a __builtin_constant_p call,
8657 // the result is a constant expression if it can be folded without
8658 // side-effects. This is an important GNU extension. See GCC PR38377
8659 // for discussion.
8660 if (const CallExpr *CallCE =
8661 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8662 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8663 IsBcpCall = true;
8664
8665 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8666 // constant expression; we can't check whether it's potentially foldable.
8667 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8668 // it would return 'false' in this mode.
8669 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8670 return false;
8671
8672 FoldConstant Fold(Info, IsBcpCall);
8673 if (!HandleConditionalOperator(E)) {
8674 Fold.keepDiagnostics();
8675 return false;
8676 }
8677
8678 return true;
8679 }
8680
8681 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8682 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8683 Value && !Value->isAbsent())
8684 return DerivedSuccess(*Value, E);
8685
8686 const Expr *Source = E->getSourceExpr();
8687 if (!Source)
8688 return Error(E);
8689 if (Source == E) {
8690 assert(0 && "OpaqueValueExpr recursively refers to itself");
8691 return Error(E);
8692 }
8693 return StmtVisitorTy::Visit(Source);
8694 }
8695
8696 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8697 for (const Expr *SemE : E->semantics()) {
8698 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8699 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8700 // result expression: there could be two different LValues that would
8701 // refer to the same object in that case, and we can't model that.
8702 if (SemE == E->getResultExpr())
8703 return Error(E);
8704
8705 // Unique OVEs get evaluated if and when we encounter them when
8706 // emitting the rest of the semantic form, rather than eagerly.
8707 if (OVE->isUnique())
8708 continue;
8709
8710 LValue LV;
8711 if (!Evaluate(Info.CurrentCall->createTemporary(
8712 OVE, getStorageType(Info.Ctx, OVE),
8713 ScopeKind::FullExpression, LV),
8714 Info, OVE->getSourceExpr()))
8715 return false;
8716 } else if (SemE == E->getResultExpr()) {
8717 if (!StmtVisitorTy::Visit(SemE))
8718 return false;
8719 } else {
8720 if (!EvaluateIgnoredValue(Info, SemE))
8721 return false;
8722 }
8723 }
8724 return true;
8725 }
8726
8727 bool VisitCallExpr(const CallExpr *E) {
8729 if (!handleCallExpr(E, Result, nullptr))
8730 return false;
8731 return DerivedSuccess(Result, E);
8732 }
8733
8734 bool handleCallExpr(const CallExpr *E, APValue &Result,
8735 const LValue *ResultSlot) {
8736 CallScopeRAII CallScope(Info);
8737
8738 const Expr *Callee = E->getCallee()->IgnoreParens();
8739 QualType CalleeType = Callee->getType();
8740
8741 const FunctionDecl *FD = nullptr;
8742 LValue *This = nullptr, ObjectArg;
8743 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8744 bool HasQualifier = false;
8745
8746 CallRef Call;
8747
8748 // Extract function decl and 'this' pointer from the callee.
8749 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8750 const CXXMethodDecl *Member = nullptr;
8751 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8752 // Explicit bound member calls, such as x.f() or p->g();
8753 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8754 return false;
8755 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8756 if (!Member)
8757 return Error(Callee);
8758 This = &ObjectArg;
8759 HasQualifier = ME->hasQualifier();
8760 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8761 // Indirect bound member calls ('.*' or '->*').
8762 const ValueDecl *D =
8763 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8764 if (!D)
8765 return false;
8766 Member = dyn_cast<CXXMethodDecl>(D);
8767 if (!Member)
8768 return Error(Callee);
8769 This = &ObjectArg;
8770 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8771 if (!Info.getLangOpts().CPlusPlus20)
8772 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8773 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8774 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8775 } else
8776 return Error(Callee);
8777 FD = Member;
8778 } else if (CalleeType->isFunctionPointerType()) {
8779 LValue CalleeLV;
8780 if (!EvaluatePointer(Callee, CalleeLV, Info))
8781 return false;
8782
8783 if (!CalleeLV.getLValueOffset().isZero())
8784 return Error(Callee);
8785 if (CalleeLV.isNullPointer()) {
8786 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8787 << const_cast<Expr *>(Callee);
8788 return false;
8789 }
8790 FD = dyn_cast_or_null<FunctionDecl>(
8791 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8792 if (!FD)
8793 return Error(Callee);
8794 // Don't call function pointers which have been cast to some other type.
8795 // Per DR (no number yet), the caller and callee can differ in noexcept.
8797 CalleeType->getPointeeType(), FD->getType())) {
8798 return Error(E);
8799 }
8800
8801 // For an (overloaded) assignment expression, evaluate the RHS before the
8802 // LHS.
8803 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8804 if (OCE && OCE->isAssignmentOp()) {
8805 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8806 Call = Info.CurrentCall->createCall(FD);
8807 bool HasThis = false;
8808 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8809 HasThis = MD->isImplicitObjectMemberFunction();
8810 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8811 /*RightToLeft=*/true, &ObjectArg))
8812 return false;
8813 }
8814
8815 // Overloaded operator calls to member functions are represented as normal
8816 // calls with '*this' as the first argument.
8817 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8818 if (MD &&
8819 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8820 // FIXME: When selecting an implicit conversion for an overloaded
8821 // operator delete, we sometimes try to evaluate calls to conversion
8822 // operators without a 'this' parameter!
8823 if (Args.empty())
8824 return Error(E);
8825
8826 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8827 return false;
8828
8829 // If we are calling a static operator, the 'this' argument needs to be
8830 // ignored after being evaluated.
8831 if (MD->isInstance())
8832 This = &ObjectArg;
8833
8834 // If this is syntactically a simple assignment using a trivial
8835 // assignment operator, start the lifetimes of union members as needed,
8836 // per C++20 [class.union]5.
8837 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8838 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8839 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8840 return false;
8841
8842 Args = Args.slice(1);
8843 } else if (MD && MD->isLambdaStaticInvoker()) {
8844 // Map the static invoker for the lambda back to the call operator.
8845 // Conveniently, we don't have to slice out the 'this' argument (as is
8846 // being done for the non-static case), since a static member function
8847 // doesn't have an implicit argument passed in.
8848 const CXXRecordDecl *ClosureClass = MD->getParent();
8849 assert(
8850 ClosureClass->captures().empty() &&
8851 "Number of captures must be zero for conversion to function-ptr");
8852
8853 const CXXMethodDecl *LambdaCallOp =
8854 ClosureClass->getLambdaCallOperator();
8855
8856 // Set 'FD', the function that will be called below, to the call
8857 // operator. If the closure object represents a generic lambda, find
8858 // the corresponding specialization of the call operator.
8859
8860 if (ClosureClass->isGenericLambda()) {
8861 assert(MD->isFunctionTemplateSpecialization() &&
8862 "A generic lambda's static-invoker function must be a "
8863 "template specialization");
8864 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8865 FunctionTemplateDecl *CallOpTemplate =
8866 LambdaCallOp->getDescribedFunctionTemplate();
8867 void *InsertPos = nullptr;
8868 FunctionDecl *CorrespondingCallOpSpecialization =
8869 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8870 assert(CorrespondingCallOpSpecialization &&
8871 "We must always have a function call operator specialization "
8872 "that corresponds to our static invoker specialization");
8873 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8874 FD = CorrespondingCallOpSpecialization;
8875 } else
8876 FD = LambdaCallOp;
8878 if (FD->getDeclName().isAnyOperatorNew()) {
8879 LValue Ptr;
8880 if (!HandleOperatorNewCall(Info, E, Ptr))
8881 return false;
8882 Ptr.moveInto(Result);
8883 return CallScope.destroy();
8884 } else {
8885 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8886 }
8887 }
8888 } else
8889 return Error(E);
8890
8891 // Evaluate the arguments now if we've not already done so.
8892 if (!Call) {
8893 Call = Info.CurrentCall->createCall(FD);
8894 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8895 &ObjectArg))
8896 return false;
8897 }
8898
8899 SmallVector<QualType, 4> CovariantAdjustmentPath;
8900 if (This) {
8901 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8902 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8903 // Perform virtual dispatch, if necessary.
8904 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8905 CovariantAdjustmentPath);
8906 if (!FD)
8907 return false;
8908 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8909 // Check that the 'this' pointer points to an object of the right type.
8910 // FIXME: If this is an assignment operator call, we may need to change
8911 // the active union member before we check this.
8912 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8913 return false;
8914 }
8915 }
8916
8917 // Destructor calls are different enough that they have their own codepath.
8918 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8919 assert(This && "no 'this' pointer for destructor call");
8920 return HandleDestruction(Info, E, *This,
8921 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8922 CallScope.destroy();
8923 }
8924
8925 const FunctionDecl *Definition = nullptr;
8926 Stmt *Body = FD->getBody(Definition);
8927 SourceLocation Loc = E->getExprLoc();
8928
8929 // Treat the object argument as `this` when evaluating defaulted
8930 // special menmber functions
8932 This = &ObjectArg;
8933
8934 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8935 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8936 Result, ResultSlot))
8937 return false;
8938
8939 if (!CovariantAdjustmentPath.empty() &&
8941 CovariantAdjustmentPath))
8942 return false;
8943
8944 return CallScope.destroy();
8945 }
8946
8947 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8948 return StmtVisitorTy::Visit(E->getInitializer());
8949 }
8950 bool VisitInitListExpr(const InitListExpr *E) {
8951 if (E->getNumInits() == 0)
8952 return DerivedZeroInitialization(E);
8953 if (E->getNumInits() == 1)
8954 return StmtVisitorTy::Visit(E->getInit(0));
8955 return Error(E);
8956 }
8957 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8958 return DerivedZeroInitialization(E);
8959 }
8960 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8961 return DerivedZeroInitialization(E);
8962 }
8963 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8964 return DerivedZeroInitialization(E);
8965 }
8966
8967 /// A member expression where the object is a prvalue is itself a prvalue.
8968 bool VisitMemberExpr(const MemberExpr *E) {
8969 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8970 "missing temporary materialization conversion");
8971 assert(!E->isArrow() && "missing call to bound member function?");
8972
8973 APValue Val;
8974 if (!Evaluate(Val, Info, E->getBase()))
8975 return false;
8976
8977 QualType BaseTy = E->getBase()->getType();
8978
8979 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8980 if (!FD) return Error(E);
8981 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8982 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8983 FD->getParent()->getCanonicalDecl() &&
8984 "record / field mismatch");
8985
8986 // Note: there is no lvalue base here. But this case should only ever
8987 // happen in C or in C++98, where we cannot be evaluating a constexpr
8988 // constructor, which is the only case the base matters.
8989 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8990 SubobjectDesignator Designator(BaseTy);
8991 Designator.addDeclUnchecked(FD);
8992
8994 return extractSubobject(Info, E, Obj, Designator, Result) &&
8995 DerivedSuccess(Result, E);
8996 }
8997
8998 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8999 APValue Val;
9000 if (!Evaluate(Val, Info, E->getBase()))
9001 return false;
9002
9003 if (Val.isVector()) {
9004 SmallVector<uint32_t, 4> Indices;
9005 E->getEncodedElementAccess(Indices);
9006 if (Indices.size() == 1) {
9007 // Return scalar.
9008 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9009 } else {
9010 // Construct new APValue vector.
9011 SmallVector<APValue, 4> Elts;
9012 for (unsigned I = 0; I < Indices.size(); ++I) {
9013 Elts.push_back(Val.getVectorElt(Indices[I]));
9014 }
9015 APValue VecResult(Elts.data(), Indices.size());
9016 return DerivedSuccess(VecResult, E);
9017 }
9018 }
9019
9020 return false;
9021 }
9022
9023 bool VisitCastExpr(const CastExpr *E) {
9024 switch (E->getCastKind()) {
9025 default:
9026 break;
9027
9028 case CK_AtomicToNonAtomic: {
9029 APValue AtomicVal;
9030 // This does not need to be done in place even for class/array types:
9031 // atomic-to-non-atomic conversion implies copying the object
9032 // representation.
9033 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9034 return false;
9035 return DerivedSuccess(AtomicVal, E);
9036 }
9037
9038 case CK_NoOp:
9039 case CK_UserDefinedConversion:
9040 return StmtVisitorTy::Visit(E->getSubExpr());
9041
9042 case CK_HLSLArrayRValue: {
9043 const Expr *SubExpr = E->getSubExpr();
9044 if (!SubExpr->isGLValue()) {
9045 APValue Val;
9046 if (!Evaluate(Val, Info, SubExpr))
9047 return false;
9048 return DerivedSuccess(Val, E);
9049 }
9050
9051 LValue LVal;
9052 if (!EvaluateLValue(SubExpr, LVal, Info))
9053 return false;
9054 APValue RVal;
9055 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9056 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9057 RVal))
9058 return false;
9059 return DerivedSuccess(RVal, E);
9060 }
9061 case CK_LValueToRValue: {
9062 LValue LVal;
9063 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9064 return false;
9065 APValue RVal;
9066 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9068 LVal, RVal))
9069 return false;
9070 return DerivedSuccess(RVal, E);
9071 }
9072 case CK_LValueToRValueBitCast: {
9073 APValue DestValue, SourceValue;
9074 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9075 return false;
9076 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9077 return false;
9078 return DerivedSuccess(DestValue, E);
9079 }
9080
9081 case CK_AddressSpaceConversion: {
9082 APValue Value;
9083 if (!Evaluate(Value, Info, E->getSubExpr()))
9084 return false;
9085 return DerivedSuccess(Value, E);
9086 }
9087 }
9088
9089 return Error(E);
9090 }
9091
9092 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9093 return VisitUnaryPostIncDec(UO);
9094 }
9095 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9096 return VisitUnaryPostIncDec(UO);
9097 }
9098 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9099 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9100 return Error(UO);
9101
9102 LValue LVal;
9103 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9104 return false;
9105 APValue RVal;
9106 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9107 UO->isIncrementOp(), &RVal))
9108 return false;
9109 return DerivedSuccess(RVal, UO);
9110 }
9111
9112 bool VisitStmtExpr(const StmtExpr *E) {
9113 // We will have checked the full-expressions inside the statement expression
9114 // when they were completed, and don't need to check them again now.
9115 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9116 false);
9117
9118 const CompoundStmt *CS = E->getSubStmt();
9119 if (CS->body_empty())
9120 return true;
9121
9122 BlockScopeRAII Scope(Info);
9124 BE = CS->body_end();
9125 /**/; ++BI) {
9126 if (BI + 1 == BE) {
9127 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9128 if (!FinalExpr) {
9129 Info.FFDiag((*BI)->getBeginLoc(),
9130 diag::note_constexpr_stmt_expr_unsupported);
9131 return false;
9132 }
9133 return this->Visit(FinalExpr) && Scope.destroy();
9134 }
9135
9137 StmtResult Result = { ReturnValue, nullptr };
9138 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9139 if (ESR != ESR_Succeeded) {
9140 // FIXME: If the statement-expression terminated due to 'return',
9141 // 'break', or 'continue', it would be nice to propagate that to
9142 // the outer statement evaluation rather than bailing out.
9143 if (ESR != ESR_Failed)
9144 Info.FFDiag((*BI)->getBeginLoc(),
9145 diag::note_constexpr_stmt_expr_unsupported);
9146 return false;
9147 }
9148 }
9149
9150 llvm_unreachable("Return from function from the loop above.");
9151 }
9152
9153 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9154 return StmtVisitorTy::Visit(E->getSelectedExpr());
9155 }
9156
9157 /// Visit a value which is evaluated, but whose value is ignored.
9158 void VisitIgnoredValue(const Expr *E) {
9159 EvaluateIgnoredValue(Info, E);
9160 }
9161
9162 /// Potentially visit a MemberExpr's base expression.
9163 void VisitIgnoredBaseExpression(const Expr *E) {
9164 // While MSVC doesn't evaluate the base expression, it does diagnose the
9165 // presence of side-effecting behavior.
9166 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9167 return;
9168 VisitIgnoredValue(E);
9169 }
9170};
9171
9172} // namespace
9173
9174//===----------------------------------------------------------------------===//
9175// Common base class for lvalue and temporary evaluation.
9176//===----------------------------------------------------------------------===//
9177namespace {
9178template<class Derived>
9179class LValueExprEvaluatorBase
9180 : public ExprEvaluatorBase<Derived> {
9181protected:
9182 LValue &Result;
9183 bool InvalidBaseOK;
9184 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9185 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9186
9187 bool Success(APValue::LValueBase B) {
9188 Result.set(B);
9189 return true;
9190 }
9191
9192 bool evaluatePointer(const Expr *E, LValue &Result) {
9193 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9194 }
9195
9196public:
9197 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9198 : ExprEvaluatorBaseTy(Info), Result(Result),
9199 InvalidBaseOK(InvalidBaseOK) {}
9200
9201 bool Success(const APValue &V, const Expr *E) {
9202 Result.setFrom(this->Info.Ctx, V);
9203 return true;
9204 }
9205
9206 bool VisitMemberExpr(const MemberExpr *E) {
9207 // Handle non-static data members.
9208 QualType BaseTy;
9209 bool EvalOK;
9210 if (E->isArrow()) {
9211 EvalOK = evaluatePointer(E->getBase(), Result);
9212 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9213 } else if (E->getBase()->isPRValue()) {
9214 assert(E->getBase()->getType()->isRecordType());
9215 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9216 BaseTy = E->getBase()->getType();
9217 } else {
9218 EvalOK = this->Visit(E->getBase());
9219 BaseTy = E->getBase()->getType();
9220 }
9221 if (!EvalOK) {
9222 if (!InvalidBaseOK)
9223 return false;
9224 Result.setInvalid(E);
9225 return true;
9226 }
9227
9228 const ValueDecl *MD = E->getMemberDecl();
9229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9230 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9231 FD->getParent()->getCanonicalDecl() &&
9232 "record / field mismatch");
9233 (void)BaseTy;
9234 if (!HandleLValueMember(this->Info, E, Result, FD))
9235 return false;
9236 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9237 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9238 return false;
9239 } else
9240 return this->Error(E);
9241
9242 if (MD->getType()->isReferenceType()) {
9243 APValue RefValue;
9244 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9245 RefValue))
9246 return false;
9247 return Success(RefValue, E);
9248 }
9249 return true;
9250 }
9251
9252 bool VisitBinaryOperator(const BinaryOperator *E) {
9253 switch (E->getOpcode()) {
9254 default:
9255 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9256
9257 case BO_PtrMemD:
9258 case BO_PtrMemI:
9259 return HandleMemberPointerAccess(this->Info, E, Result);
9260 }
9261 }
9262
9263 bool VisitCastExpr(const CastExpr *E) {
9264 switch (E->getCastKind()) {
9265 default:
9266 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9267
9268 case CK_DerivedToBase:
9269 case CK_UncheckedDerivedToBase:
9270 if (!this->Visit(E->getSubExpr()))
9271 return false;
9272
9273 // Now figure out the necessary offset to add to the base LV to get from
9274 // the derived class to the base class.
9275 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9276 Result);
9277 }
9278 }
9279};
9280}
9281
9282//===----------------------------------------------------------------------===//
9283// LValue Evaluation
9284//
9285// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9286// function designators (in C), decl references to void objects (in C), and
9287// temporaries (if building with -Wno-address-of-temporary).
9288//
9289// LValue evaluation produces values comprising a base expression of one of the
9290// following types:
9291// - Declarations
9292// * VarDecl
9293// * FunctionDecl
9294// - Literals
9295// * CompoundLiteralExpr in C (and in global scope in C++)
9296// * StringLiteral
9297// * PredefinedExpr
9298// * ObjCStringLiteralExpr
9299// * ObjCEncodeExpr
9300// * AddrLabelExpr
9301// * BlockExpr
9302// * CallExpr for a MakeStringConstant builtin
9303// - typeid(T) expressions, as TypeInfoLValues
9304// - Locals and temporaries
9305// * MaterializeTemporaryExpr
9306// * Any Expr, with a CallIndex indicating the function in which the temporary
9307// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9308// from the AST (FIXME).
9309// * A MaterializeTemporaryExpr that has static storage duration, with no
9310// CallIndex, for a lifetime-extended temporary.
9311// * The ConstantExpr that is currently being evaluated during evaluation of an
9312// immediate invocation.
9313// plus an offset in bytes.
9314//===----------------------------------------------------------------------===//
9315namespace {
9316class LValueExprEvaluator
9317 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9318public:
9319 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9320 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9321
9322 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9323 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9324
9325 bool VisitCallExpr(const CallExpr *E);
9326 bool VisitDeclRefExpr(const DeclRefExpr *E);
9327 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9328 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9329 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9330 bool VisitMemberExpr(const MemberExpr *E);
9331 bool VisitStringLiteral(const StringLiteral *E) {
9332 return Success(APValue::LValueBase(
9333 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
9334 }
9335 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9336 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9337 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9338 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9339 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9340 bool VisitUnaryDeref(const UnaryOperator *E);
9341 bool VisitUnaryReal(const UnaryOperator *E);
9342 bool VisitUnaryImag(const UnaryOperator *E);
9343 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9344 return VisitUnaryPreIncDec(UO);
9345 }
9346 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9347 return VisitUnaryPreIncDec(UO);
9348 }
9349 bool VisitBinAssign(const BinaryOperator *BO);
9350 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9351
9352 bool VisitCastExpr(const CastExpr *E) {
9353 switch (E->getCastKind()) {
9354 default:
9355 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9356
9357 case CK_LValueBitCast:
9358 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9359 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9360 << Info.Ctx.getLangOpts().CPlusPlus;
9361 if (!Visit(E->getSubExpr()))
9362 return false;
9363 Result.Designator.setInvalid();
9364 return true;
9365
9366 case CK_BaseToDerived:
9367 if (!Visit(E->getSubExpr()))
9368 return false;
9369 return HandleBaseToDerivedCast(Info, E, Result);
9370
9371 case CK_Dynamic:
9372 if (!Visit(E->getSubExpr()))
9373 return false;
9375 }
9376 }
9377};
9378} // end anonymous namespace
9379
9380/// Get an lvalue to a field of a lambda's closure type.
9381static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9382 const CXXMethodDecl *MD, const FieldDecl *FD,
9383 bool LValueToRValueConversion) {
9384 // Static lambda function call operators can't have captures. We already
9385 // diagnosed this, so bail out here.
9386 if (MD->isStatic()) {
9387 assert(Info.CurrentCall->This == nullptr &&
9388 "This should not be set for a static call operator");
9389 return false;
9390 }
9391
9392 // Start with 'Result' referring to the complete closure object...
9394 // Self may be passed by reference or by value.
9395 const ParmVarDecl *Self = MD->getParamDecl(0);
9396 if (Self->getType()->isReferenceType()) {
9397 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9398 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9399 Result.setFrom(Info.Ctx, *RefValue);
9400 } else {
9401 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9402 CallStackFrame *Frame =
9403 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9404 .first;
9405 unsigned Version = Info.CurrentCall->Arguments.Version;
9406 Result.set({VD, Frame->Index, Version});
9407 }
9408 } else
9409 Result = *Info.CurrentCall->This;
9410
9411 // ... then update it to refer to the field of the closure object
9412 // that represents the capture.
9413 if (!HandleLValueMember(Info, E, Result, FD))
9414 return false;
9415
9416 // And if the field is of reference type (or if we captured '*this' by
9417 // reference), update 'Result' to refer to what
9418 // the field refers to.
9419 if (LValueToRValueConversion) {
9420 APValue RVal;
9421 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9422 return false;
9423 Result.setFrom(Info.Ctx, RVal);
9424 }
9425 return true;
9426}
9427
9428/// Evaluate an expression as an lvalue. This can be legitimately called on
9429/// expressions which are not glvalues, in three cases:
9430/// * function designators in C, and
9431/// * "extern void" objects
9432/// * @selector() expressions in Objective-C
9433static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9434 bool InvalidBaseOK) {
9435 assert(!E->isValueDependent());
9436 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9438 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9439}
9440
9441bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9442 const ValueDecl *D = E->getDecl();
9443
9444 // If we are within a lambda's call operator, check whether the 'VD' referred
9445 // to within 'E' actually represents a lambda-capture that maps to a
9446 // data-member/field within the closure object, and if so, evaluate to the
9447 // field or what the field refers to.
9448 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9450 // We don't always have a complete capture-map when checking or inferring if
9451 // the function call operator meets the requirements of a constexpr function
9452 // - but we don't need to evaluate the captures to determine constexprness
9453 // (dcl.constexpr C++17).
9454 if (Info.checkingPotentialConstantExpression())
9455 return false;
9456
9457 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9458 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9459 return HandleLambdaCapture(Info, E, Result, MD, FD,
9460 FD->getType()->isReferenceType());
9461 }
9462 }
9463
9464 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9465 UnnamedGlobalConstantDecl>(D))
9466 return Success(cast<ValueDecl>(D));
9467 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9468 return VisitVarDecl(E, VD);
9469 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9470 return Visit(BD->getBinding());
9471 return Error(E);
9472}
9473
9474bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9475 CallStackFrame *Frame = nullptr;
9476 unsigned Version = 0;
9477 if (VD->hasLocalStorage()) {
9478 // Only if a local variable was declared in the function currently being
9479 // evaluated, do we expect to be able to find its value in the current
9480 // frame. (Otherwise it was likely declared in an enclosing context and
9481 // could either have a valid evaluatable value (for e.g. a constexpr
9482 // variable) or be ill-formed (and trigger an appropriate evaluation
9483 // diagnostic)).
9484 CallStackFrame *CurrFrame = Info.CurrentCall;
9485 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9486 // Function parameters are stored in some caller's frame. (Usually the
9487 // immediate caller, but for an inherited constructor they may be more
9488 // distant.)
9489 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9490 if (CurrFrame->Arguments) {
9491 VD = CurrFrame->Arguments.getOrigParam(PVD);
9492 Frame =
9493 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9494 Version = CurrFrame->Arguments.Version;
9495 }
9496 } else {
9497 Frame = CurrFrame;
9498 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9499 }
9500 }
9501 }
9502
9503 if (!VD->getType()->isReferenceType()) {
9504 if (Frame) {
9505 Result.set({VD, Frame->Index, Version});
9506 return true;
9507 }
9508 return Success(VD);
9509 }
9510
9511 if (!Info.getLangOpts().CPlusPlus11) {
9512 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9513 << VD << VD->getType();
9514 Info.Note(VD->getLocation(), diag::note_declared_at);
9515 }
9516
9517 APValue *V;
9518 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9519 return false;
9520
9521 if (!V) {
9522 Result.set(VD);
9523 Result.AllowConstexprUnknown = true;
9524 return true;
9525 }
9526
9527 return Success(*V, E);
9528}
9529
9530bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9531 if (!IsConstantEvaluatedBuiltinCall(E))
9532 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9533
9534 switch (E->getBuiltinCallee()) {
9535 default:
9536 return false;
9537 case Builtin::BIas_const:
9538 case Builtin::BIforward:
9539 case Builtin::BIforward_like:
9540 case Builtin::BImove:
9541 case Builtin::BImove_if_noexcept:
9542 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9543 return Visit(E->getArg(0));
9544 break;
9545 }
9546
9547 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9548}
9549
9550bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9551 const MaterializeTemporaryExpr *E) {
9552 // Walk through the expression to find the materialized temporary itself.
9555 const Expr *Inner =
9556 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9557
9558 // If we passed any comma operators, evaluate their LHSs.
9559 for (const Expr *E : CommaLHSs)
9560 if (!EvaluateIgnoredValue(Info, E))
9561 return false;
9562
9563 // A materialized temporary with static storage duration can appear within the
9564 // result of a constant expression evaluation, so we need to preserve its
9565 // value for use outside this evaluation.
9566 APValue *Value;
9567 if (E->getStorageDuration() == SD_Static) {
9568 if (Info.EvalMode == EvaluationMode::ConstantFold)
9569 return false;
9570 // FIXME: What about SD_Thread?
9571 Value = E->getOrCreateValue(true);
9572 *Value = APValue();
9573 Result.set(E);
9574 } else {
9575 Value = &Info.CurrentCall->createTemporary(
9576 E, Inner->getType(),
9577 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9578 : ScopeKind::Block,
9579 Result);
9580 }
9581
9582 QualType Type = Inner->getType();
9583
9584 // Materialize the temporary itself.
9585 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9586 *Value = APValue();
9587 return false;
9588 }
9589
9590 // Adjust our lvalue to refer to the desired subobject.
9591 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9592 --I;
9593 switch (Adjustments[I].Kind) {
9595 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9596 Type, Result))
9597 return false;
9598 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9599 break;
9600
9602 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9603 return false;
9604 Type = Adjustments[I].Field->getType();
9605 break;
9606
9608 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9609 Adjustments[I].Ptr.RHS))
9610 return false;
9611 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9612 break;
9613 }
9614 }
9615
9616 return true;
9617}
9618
9619bool
9620LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9621 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9622 "lvalue compound literal in c++?");
9623 APValue *Lit;
9624 // If CompountLiteral has static storage, its value can be used outside
9625 // this expression. So evaluate it once and store it in ASTContext.
9626 if (E->hasStaticStorage()) {
9627 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9628 Result.set(E);
9629 // Reset any previously evaluated state, otherwise evaluation below might
9630 // fail.
9631 // FIXME: Should we just re-use the previously evaluated value instead?
9632 *Lit = APValue();
9633 } else {
9634 assert(!Info.getLangOpts().CPlusPlus);
9635 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9636 ScopeKind::Block, Result);
9637 }
9638 // FIXME: Evaluating in place isn't always right. We should figure out how to
9639 // use appropriate evaluation context here, see
9640 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9641 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9642 *Lit = APValue();
9643 return false;
9644 }
9645 return true;
9646}
9647
9648bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9649 TypeInfoLValue TypeInfo;
9650
9651 if (!E->isPotentiallyEvaluated()) {
9652 if (E->isTypeOperand())
9653 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9654 else
9655 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9656 } else {
9657 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9658 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9659 << E->getExprOperand()->getType()
9660 << E->getExprOperand()->getSourceRange();
9661 }
9662
9663 if (!Visit(E->getExprOperand()))
9664 return false;
9665
9666 std::optional<DynamicType> DynType =
9668 if (!DynType)
9669 return false;
9670
9671 TypeInfo = TypeInfoLValue(
9672 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9673 }
9674
9675 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9676}
9677
9678bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9679 return Success(E->getGuidDecl());
9680}
9681
9682bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9683 // Handle static data members.
9684 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9685 VisitIgnoredBaseExpression(E->getBase());
9686 return VisitVarDecl(E, VD);
9687 }
9688
9689 // Handle static member functions.
9690 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9691 if (MD->isStatic()) {
9692 VisitIgnoredBaseExpression(E->getBase());
9693 return Success(MD);
9694 }
9695 }
9696
9697 // Handle non-static data members.
9698 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9699}
9700
9701bool LValueExprEvaluator::VisitExtVectorElementExpr(
9702 const ExtVectorElementExpr *E) {
9703 bool Success = true;
9704
9705 APValue Val;
9706 if (!Evaluate(Val, Info, E->getBase())) {
9707 if (!Info.noteFailure())
9708 return false;
9709 Success = false;
9710 }
9711
9713 E->getEncodedElementAccess(Indices);
9714 // FIXME: support accessing more than one element
9715 if (Indices.size() > 1)
9716 return false;
9717
9718 if (Success) {
9719 Result.setFrom(Info.Ctx, Val);
9720 QualType BaseType = E->getBase()->getType();
9721 if (E->isArrow())
9722 BaseType = BaseType->getPointeeType();
9723 const auto *VT = BaseType->castAs<VectorType>();
9724 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9725 VT->getNumElements(), Indices[0]);
9726 }
9727
9728 return Success;
9729}
9730
9731bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9732 if (E->getBase()->getType()->isSveVLSBuiltinType())
9733 return Error(E);
9734
9735 APSInt Index;
9736 bool Success = true;
9737
9738 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9739 APValue Val;
9740 if (!Evaluate(Val, Info, E->getBase())) {
9741 if (!Info.noteFailure())
9742 return false;
9743 Success = false;
9744 }
9745
9746 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9747 if (!Info.noteFailure())
9748 return false;
9749 Success = false;
9750 }
9751
9752 if (Success) {
9753 Result.setFrom(Info.Ctx, Val);
9754 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9755 VT->getNumElements(), Index.getExtValue());
9756 }
9757
9758 return Success;
9759 }
9760
9761 // C++17's rules require us to evaluate the LHS first, regardless of which
9762 // side is the base.
9763 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9764 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9765 : !EvaluateInteger(SubExpr, Index, Info)) {
9766 if (!Info.noteFailure())
9767 return false;
9768 Success = false;
9769 }
9770 }
9771
9772 return Success &&
9773 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9774}
9775
9776bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9777 bool Success = evaluatePointer(E->getSubExpr(), Result);
9778 // [C++26][expr.unary.op]
9779 // If the operand points to an object or function, the result
9780 // denotes that object or function; otherwise, the behavior is undefined.
9781 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9782 // immediately.
9784 return Success;
9786 E->getType())) ||
9787 Info.noteUndefinedBehavior();
9788}
9789
9790bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9791 if (!Visit(E->getSubExpr()))
9792 return false;
9793 // __real is a no-op on scalar lvalues.
9794 if (E->getSubExpr()->getType()->isAnyComplexType())
9795 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9796 return true;
9797}
9798
9799bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9800 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9801 "lvalue __imag__ on scalar?");
9802 if (!Visit(E->getSubExpr()))
9803 return false;
9804 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9805 return true;
9806}
9807
9808bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9809 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9810 return Error(UO);
9811
9812 if (!this->Visit(UO->getSubExpr()))
9813 return false;
9814
9815 return handleIncDec(
9816 this->Info, UO, Result, UO->getSubExpr()->getType(),
9817 UO->isIncrementOp(), nullptr);
9818}
9819
9820bool LValueExprEvaluator::VisitCompoundAssignOperator(
9821 const CompoundAssignOperator *CAO) {
9822 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9823 return Error(CAO);
9824
9825 bool Success = true;
9826
9827 // C++17 onwards require that we evaluate the RHS first.
9828 APValue RHS;
9829 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9830 if (!Info.noteFailure())
9831 return false;
9832 Success = false;
9833 }
9834
9835 // The overall lvalue result is the result of evaluating the LHS.
9836 if (!this->Visit(CAO->getLHS()) || !Success)
9837 return false;
9838
9840 this->Info, CAO,
9841 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9842 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9843}
9844
9845bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9846 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9847 return Error(E);
9848
9849 bool Success = true;
9850
9851 // C++17 onwards require that we evaluate the RHS first.
9852 APValue NewVal;
9853 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9854 if (!Info.noteFailure())
9855 return false;
9856 Success = false;
9857 }
9858
9859 if (!this->Visit(E->getLHS()) || !Success)
9860 return false;
9861
9862 if (Info.getLangOpts().CPlusPlus20 &&
9864 return false;
9865
9866 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9867 NewVal);
9868}
9869
9870//===----------------------------------------------------------------------===//
9871// Pointer Evaluation
9872//===----------------------------------------------------------------------===//
9873
9874/// Convenience function. LVal's base must be a call to an alloc_size
9875/// function.
9877 const LValue &LVal,
9878 llvm::APInt &Result) {
9879 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9880 "Can't get the size of a non alloc_size function");
9881 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9882 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9883 std::optional<llvm::APInt> Size =
9884 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9885 if (!Size)
9886 return false;
9887
9888 Result = std::move(*Size);
9889 return true;
9890}
9891
9892/// Attempts to evaluate the given LValueBase as the result of a call to
9893/// a function with the alloc_size attribute. If it was possible to do so, this
9894/// function will return true, make Result's Base point to said function call,
9895/// and mark Result's Base as invalid.
9897 LValue &Result) {
9898 if (Base.isNull())
9899 return false;
9900
9901 // Because we do no form of static analysis, we only support const variables.
9902 //
9903 // Additionally, we can't support parameters, nor can we support static
9904 // variables (in the latter case, use-before-assign isn't UB; in the former,
9905 // we have no clue what they'll be assigned to).
9906 const auto *VD =
9907 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9908 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9909 return false;
9910
9911 const Expr *Init = VD->getAnyInitializer();
9912 if (!Init || Init->getType().isNull())
9913 return false;
9914
9915 const Expr *E = Init->IgnoreParens();
9916 if (!tryUnwrapAllocSizeCall(E))
9917 return false;
9918
9919 // Store E instead of E unwrapped so that the type of the LValue's base is
9920 // what the user wanted.
9921 Result.setInvalid(E);
9922
9923 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9924 Result.addUnsizedArray(Info, E, Pointee);
9925 return true;
9926}
9927
9928namespace {
9929class PointerExprEvaluator
9930 : public ExprEvaluatorBase<PointerExprEvaluator> {
9931 LValue &Result;
9932 bool InvalidBaseOK;
9933
9934 bool Success(const Expr *E) {
9935 Result.set(E);
9936 return true;
9937 }
9938
9939 bool evaluateLValue(const Expr *E, LValue &Result) {
9940 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9941 }
9942
9943 bool evaluatePointer(const Expr *E, LValue &Result) {
9944 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9945 }
9946
9947 bool visitNonBuiltinCallExpr(const CallExpr *E);
9948public:
9949
9950 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9951 : ExprEvaluatorBaseTy(info), Result(Result),
9952 InvalidBaseOK(InvalidBaseOK) {}
9953
9954 bool Success(const APValue &V, const Expr *E) {
9955 Result.setFrom(Info.Ctx, V);
9956 return true;
9957 }
9958 bool ZeroInitialization(const Expr *E) {
9959 Result.setNull(Info.Ctx, E->getType());
9960 return true;
9961 }
9962
9963 bool VisitBinaryOperator(const BinaryOperator *E);
9964 bool VisitCastExpr(const CastExpr* E);
9965 bool VisitUnaryAddrOf(const UnaryOperator *E);
9966 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9967 { return Success(E); }
9968 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9970 return Success(E);
9971 if (Info.noteFailure())
9972 EvaluateIgnoredValue(Info, E->getSubExpr());
9973 return Error(E);
9974 }
9975 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9976 { return Success(E); }
9977 bool VisitCallExpr(const CallExpr *E);
9978 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9979 bool VisitBlockExpr(const BlockExpr *E) {
9980 if (!E->getBlockDecl()->hasCaptures())
9981 return Success(E);
9982 return Error(E);
9983 }
9984 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9985 auto DiagnoseInvalidUseOfThis = [&] {
9986 if (Info.getLangOpts().CPlusPlus11)
9987 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9988 else
9989 Info.FFDiag(E);
9990 };
9991
9992 // Can't look at 'this' when checking a potential constant expression.
9993 if (Info.checkingPotentialConstantExpression())
9994 return false;
9995
9996 bool IsExplicitLambda =
9997 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9998 if (!IsExplicitLambda) {
9999 if (!Info.CurrentCall->This) {
10000 DiagnoseInvalidUseOfThis();
10001 return false;
10002 }
10003
10004 Result = *Info.CurrentCall->This;
10005 }
10006
10007 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10008 // Ensure we actually have captured 'this'. If something was wrong with
10009 // 'this' capture, the error would have been previously reported.
10010 // Otherwise we can be inside of a default initialization of an object
10011 // declared by lambda's body, so no need to return false.
10012 if (!Info.CurrentCall->LambdaThisCaptureField) {
10013 if (IsExplicitLambda && !Info.CurrentCall->This) {
10014 DiagnoseInvalidUseOfThis();
10015 return false;
10016 }
10017
10018 return true;
10019 }
10020
10021 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10022 return HandleLambdaCapture(
10023 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10024 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10025 }
10026 return true;
10027 }
10028
10029 bool VisitCXXNewExpr(const CXXNewExpr *E);
10030
10031 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10032 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10033 APValue LValResult = E->EvaluateInContext(
10034 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10035 Result.setFrom(Info.Ctx, LValResult);
10036 return true;
10037 }
10038
10039 bool VisitEmbedExpr(const EmbedExpr *E) {
10040 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10041 return true;
10042 }
10043
10044 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10045 std::string ResultStr = E->ComputeName(Info.Ctx);
10046
10047 QualType CharTy = Info.Ctx.CharTy.withConst();
10048 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10049 ResultStr.size() + 1);
10050 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10051 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10052
10053 StringLiteral *SL =
10054 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10055 /*Pascal*/ false, ArrayTy, E->getLocation());
10056
10057 evaluateLValue(SL, Result);
10058 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10059 return true;
10060 }
10061
10062 // FIXME: Missing: @protocol, @selector
10063};
10064} // end anonymous namespace
10065
10066static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10067 bool InvalidBaseOK) {
10068 assert(!E->isValueDependent());
10069 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10070 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10071}
10072
10073bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10074 if (E->getOpcode() != BO_Add &&
10075 E->getOpcode() != BO_Sub)
10076 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10077
10078 const Expr *PExp = E->getLHS();
10079 const Expr *IExp = E->getRHS();
10080 if (IExp->getType()->isPointerType())
10081 std::swap(PExp, IExp);
10082
10083 bool EvalPtrOK = evaluatePointer(PExp, Result);
10084 if (!EvalPtrOK && !Info.noteFailure())
10085 return false;
10086
10087 llvm::APSInt Offset;
10088 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10089 return false;
10090
10091 if (E->getOpcode() == BO_Sub)
10092 negateAsSigned(Offset);
10093
10094 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10095 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10096}
10097
10098bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10099 return evaluateLValue(E->getSubExpr(), Result);
10100}
10101
10102// Is the provided decl 'std::source_location::current'?
10104 if (!FD)
10105 return false;
10106 const IdentifierInfo *FnII = FD->getIdentifier();
10107 if (!FnII || !FnII->isStr("current"))
10108 return false;
10109
10110 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10111 if (!RD)
10112 return false;
10113
10114 const IdentifierInfo *ClassII = RD->getIdentifier();
10115 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10116}
10117
10118bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10119 const Expr *SubExpr = E->getSubExpr();
10120
10121 switch (E->getCastKind()) {
10122 default:
10123 break;
10124 case CK_BitCast:
10125 case CK_CPointerToObjCPointerCast:
10126 case CK_BlockPointerToObjCPointerCast:
10127 case CK_AnyPointerToBlockPointerCast:
10128 case CK_AddressSpaceConversion:
10129 if (!Visit(SubExpr))
10130 return false;
10131 if (E->getType()->isFunctionPointerType() ||
10132 SubExpr->getType()->isFunctionPointerType()) {
10133 // Casting between two function pointer types, or between a function
10134 // pointer and an object pointer, is always a reinterpret_cast.
10135 CCEDiag(E, diag::note_constexpr_invalid_cast)
10136 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10137 << Info.Ctx.getLangOpts().CPlusPlus;
10138 Result.Designator.setInvalid();
10139 } else if (!E->getType()->isVoidPointerType()) {
10140 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10141 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10142 // also static_casts, but we disallow them as a resolution to DR1312.
10143 //
10144 // In some circumstances, we permit casting from void* to cv1 T*, when the
10145 // actual pointee object is actually a cv2 T.
10146 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10147 !Result.IsNullPtr;
10148 bool VoidPtrCastMaybeOK =
10149 Result.IsNullPtr ||
10150 (HasValidResult &&
10151 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10152 E->getType()->getPointeeType()));
10153 // 1. We'll allow it in std::allocator::allocate, and anything which that
10154 // calls.
10155 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10156 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10157 // We'll allow it in the body of std::source_location::current. GCC's
10158 // implementation had a parameter of type `void*`, and casts from
10159 // that back to `const __impl*` in its body.
10160 if (VoidPtrCastMaybeOK &&
10161 (Info.getStdAllocatorCaller("allocate") ||
10162 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10163 Info.getLangOpts().CPlusPlus26)) {
10164 // Permitted.
10165 } else {
10166 if (SubExpr->getType()->isVoidPointerType() &&
10167 Info.getLangOpts().CPlusPlus) {
10168 if (HasValidResult)
10169 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10170 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10171 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10172 << E->getType()->getPointeeType();
10173 else
10174 CCEDiag(E, diag::note_constexpr_invalid_cast)
10175 << diag::ConstexprInvalidCastKind::CastFrom
10176 << SubExpr->getType();
10177 } else
10178 CCEDiag(E, diag::note_constexpr_invalid_cast)
10179 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10180 << Info.Ctx.getLangOpts().CPlusPlus;
10181 Result.Designator.setInvalid();
10182 }
10183 }
10184 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10185 ZeroInitialization(E);
10186 return true;
10187
10188 case CK_DerivedToBase:
10189 case CK_UncheckedDerivedToBase:
10190 if (!evaluatePointer(E->getSubExpr(), Result))
10191 return false;
10192 if (!Result.Base && Result.Offset.isZero())
10193 return true;
10194
10195 // Now figure out the necessary offset to add to the base LV to get from
10196 // the derived class to the base class.
10197 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10198 castAs<PointerType>()->getPointeeType(),
10199 Result);
10200
10201 case CK_BaseToDerived:
10202 if (!Visit(E->getSubExpr()))
10203 return false;
10204 if (!Result.Base && Result.Offset.isZero())
10205 return true;
10206 return HandleBaseToDerivedCast(Info, E, Result);
10207
10208 case CK_Dynamic:
10209 if (!Visit(E->getSubExpr()))
10210 return false;
10212
10213 case CK_NullToPointer:
10214 VisitIgnoredValue(E->getSubExpr());
10215 return ZeroInitialization(E);
10216
10217 case CK_IntegralToPointer: {
10218 CCEDiag(E, diag::note_constexpr_invalid_cast)
10219 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10220 << Info.Ctx.getLangOpts().CPlusPlus;
10221
10222 APValue Value;
10223 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10224 break;
10225
10226 if (Value.isInt()) {
10227 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10228 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10229 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10230 Result.setNull(Info.Ctx, E->getType());
10231 } else {
10232 Result.Base = (Expr *)nullptr;
10233 Result.InvalidBase = false;
10234 Result.Offset = CharUnits::fromQuantity(N);
10235 Result.Designator.setInvalid();
10236 Result.IsNullPtr = false;
10237 }
10238 return true;
10239 } else {
10240 // In rare instances, the value isn't an lvalue.
10241 // For example, when the value is the difference between the addresses of
10242 // two labels. We reject that as a constant expression because we can't
10243 // compute a valid offset to convert into a pointer.
10244 if (!Value.isLValue())
10245 return false;
10246
10247 // Cast is of an lvalue, no need to change value.
10248 Result.setFrom(Info.Ctx, Value);
10249 return true;
10250 }
10251 }
10252
10253 case CK_ArrayToPointerDecay: {
10254 if (SubExpr->isGLValue()) {
10255 if (!evaluateLValue(SubExpr, Result))
10256 return false;
10257 } else {
10258 APValue &Value = Info.CurrentCall->createTemporary(
10259 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10260 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10261 return false;
10262 }
10263 // The result is a pointer to the first element of the array.
10264 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10265 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10266 Result.addArray(Info, E, CAT);
10267 else
10268 Result.addUnsizedArray(Info, E, AT->getElementType());
10269 return true;
10270 }
10271
10272 case CK_FunctionToPointerDecay:
10273 return evaluateLValue(SubExpr, Result);
10274
10275 case CK_LValueToRValue: {
10276 LValue LVal;
10277 if (!evaluateLValue(E->getSubExpr(), LVal))
10278 return false;
10279
10280 APValue RVal;
10281 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10283 LVal, RVal))
10284 return InvalidBaseOK &&
10285 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10286 return Success(RVal, E);
10287 }
10288 }
10289
10290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10291}
10292
10294 UnaryExprOrTypeTrait ExprKind) {
10295 // C++ [expr.alignof]p3:
10296 // When alignof is applied to a reference type, the result is the
10297 // alignment of the referenced type.
10298 T = T.getNonReferenceType();
10299
10300 if (T.getQualifiers().hasUnaligned())
10301 return CharUnits::One();
10302
10303 const bool AlignOfReturnsPreferred =
10304 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10305
10306 // __alignof is defined to return the preferred alignment.
10307 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10308 // as well.
10309 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10310 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10311 // alignof and _Alignof are defined to return the ABI alignment.
10312 else if (ExprKind == UETT_AlignOf)
10313 return Ctx.getTypeAlignInChars(T.getTypePtr());
10314 else
10315 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10316}
10317
10319 UnaryExprOrTypeTrait ExprKind) {
10320 E = E->IgnoreParens();
10321
10322 // The kinds of expressions that we have special-case logic here for
10323 // should be kept up to date with the special checks for those
10324 // expressions in Sema.
10325
10326 // alignof decl is always accepted, even if it doesn't make sense: we default
10327 // to 1 in those cases.
10328 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10329 return Ctx.getDeclAlign(DRE->getDecl(),
10330 /*RefAsPointee*/ true);
10331
10332 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10333 return Ctx.getDeclAlign(ME->getMemberDecl(),
10334 /*RefAsPointee*/ true);
10335
10336 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10337}
10338
10339static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10340 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10341 return Info.Ctx.getDeclAlign(VD);
10342 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10343 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10344 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10345}
10346
10347/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10348/// __builtin_is_aligned and __builtin_assume_aligned.
10349static bool getAlignmentArgument(const Expr *E, QualType ForType,
10350 EvalInfo &Info, APSInt &Alignment) {
10351 if (!EvaluateInteger(E, Alignment, Info))
10352 return false;
10353 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10354 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10355 return false;
10356 }
10357 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10358 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10359 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10360 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10361 << MaxValue << ForType << Alignment;
10362 return false;
10363 }
10364 // Ensure both alignment and source value have the same bit width so that we
10365 // don't assert when computing the resulting value.
10366 APSInt ExtAlignment =
10367 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10368 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10369 "Alignment should not be changed by ext/trunc");
10370 Alignment = ExtAlignment;
10371 assert(Alignment.getBitWidth() == SrcWidth);
10372 return true;
10373}
10374
10375// To be clear: this happily visits unsupported builtins. Better name welcomed.
10376bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10377 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10378 return true;
10379
10380 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10381 return false;
10382
10383 Result.setInvalid(E);
10384 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10385 Result.addUnsizedArray(Info, E, PointeeTy);
10386 return true;
10387}
10388
10389bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10390 if (!IsConstantEvaluatedBuiltinCall(E))
10391 return visitNonBuiltinCallExpr(E);
10392 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10393}
10394
10395// Determine if T is a character type for which we guarantee that
10396// sizeof(T) == 1.
10398 return T->isCharType() || T->isChar8Type();
10399}
10400
10401bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10402 unsigned BuiltinOp) {
10403 if (IsOpaqueConstantCall(E))
10404 return Success(E);
10405
10406 switch (BuiltinOp) {
10407 case Builtin::BIaddressof:
10408 case Builtin::BI__addressof:
10409 case Builtin::BI__builtin_addressof:
10410 return evaluateLValue(E->getArg(0), Result);
10411 case Builtin::BI__builtin_assume_aligned: {
10412 // We need to be very careful here because: if the pointer does not have the
10413 // asserted alignment, then the behavior is undefined, and undefined
10414 // behavior is non-constant.
10415 if (!evaluatePointer(E->getArg(0), Result))
10416 return false;
10417
10418 LValue OffsetResult(Result);
10419 APSInt Alignment;
10420 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10421 Alignment))
10422 return false;
10423 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10424
10425 if (E->getNumArgs() > 2) {
10426 APSInt Offset;
10427 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10428 return false;
10429
10430 int64_t AdditionalOffset = -Offset.getZExtValue();
10431 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10432 }
10433
10434 // If there is a base object, then it must have the correct alignment.
10435 if (OffsetResult.Base) {
10436 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10437
10438 if (BaseAlignment < Align) {
10439 Result.Designator.setInvalid();
10440 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10441 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10442 return false;
10443 }
10444 }
10445
10446 // The offset must also have the correct alignment.
10447 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10448 Result.Designator.setInvalid();
10449
10450 (OffsetResult.Base
10451 ? CCEDiag(E->getArg(0),
10452 diag::note_constexpr_baa_insufficient_alignment)
10453 << 1
10454 : CCEDiag(E->getArg(0),
10455 diag::note_constexpr_baa_value_insufficient_alignment))
10456 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10457 return false;
10458 }
10459
10460 return true;
10461 }
10462 case Builtin::BI__builtin_align_up:
10463 case Builtin::BI__builtin_align_down: {
10464 if (!evaluatePointer(E->getArg(0), Result))
10465 return false;
10466 APSInt Alignment;
10467 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10468 Alignment))
10469 return false;
10470 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10471 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10472 // For align_up/align_down, we can return the same value if the alignment
10473 // is known to be greater or equal to the requested value.
10474 if (PtrAlign.getQuantity() >= Alignment)
10475 return true;
10476
10477 // The alignment could be greater than the minimum at run-time, so we cannot
10478 // infer much about the resulting pointer value. One case is possible:
10479 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10480 // can infer the correct index if the requested alignment is smaller than
10481 // the base alignment so we can perform the computation on the offset.
10482 if (BaseAlignment.getQuantity() >= Alignment) {
10483 assert(Alignment.getBitWidth() <= 64 &&
10484 "Cannot handle > 64-bit address-space");
10485 uint64_t Alignment64 = Alignment.getZExtValue();
10486 CharUnits NewOffset = CharUnits::fromQuantity(
10487 BuiltinOp == Builtin::BI__builtin_align_down
10488 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10489 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10490 Result.adjustOffset(NewOffset - Result.Offset);
10491 // TODO: diagnose out-of-bounds values/only allow for arrays?
10492 return true;
10493 }
10494 // Otherwise, we cannot constant-evaluate the result.
10495 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10496 << Alignment;
10497 return false;
10498 }
10499 case Builtin::BI__builtin_operator_new:
10500 return HandleOperatorNewCall(Info, E, Result);
10501 case Builtin::BI__builtin_launder:
10502 return evaluatePointer(E->getArg(0), Result);
10503 case Builtin::BIstrchr:
10504 case Builtin::BIwcschr:
10505 case Builtin::BImemchr:
10506 case Builtin::BIwmemchr:
10507 if (Info.getLangOpts().CPlusPlus11)
10508 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10509 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10510 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10511 else
10512 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10513 [[fallthrough]];
10514 case Builtin::BI__builtin_strchr:
10515 case Builtin::BI__builtin_wcschr:
10516 case Builtin::BI__builtin_memchr:
10517 case Builtin::BI__builtin_char_memchr:
10518 case Builtin::BI__builtin_wmemchr: {
10519 if (!Visit(E->getArg(0)))
10520 return false;
10521 APSInt Desired;
10522 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10523 return false;
10524 uint64_t MaxLength = uint64_t(-1);
10525 if (BuiltinOp != Builtin::BIstrchr &&
10526 BuiltinOp != Builtin::BIwcschr &&
10527 BuiltinOp != Builtin::BI__builtin_strchr &&
10528 BuiltinOp != Builtin::BI__builtin_wcschr) {
10529 APSInt N;
10530 if (!EvaluateInteger(E->getArg(2), N, Info))
10531 return false;
10532 MaxLength = N.getZExtValue();
10533 }
10534 // We cannot find the value if there are no candidates to match against.
10535 if (MaxLength == 0u)
10536 return ZeroInitialization(E);
10537 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10538 Result.Designator.Invalid)
10539 return false;
10540 QualType CharTy = Result.Designator.getType(Info.Ctx);
10541 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10542 BuiltinOp == Builtin::BI__builtin_memchr;
10543 assert(IsRawByte ||
10544 Info.Ctx.hasSameUnqualifiedType(
10545 CharTy, E->getArg(0)->getType()->getPointeeType()));
10546 // Pointers to const void may point to objects of incomplete type.
10547 if (IsRawByte && CharTy->isIncompleteType()) {
10548 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10549 return false;
10550 }
10551 // Give up on byte-oriented matching against multibyte elements.
10552 // FIXME: We can compare the bytes in the correct order.
10553 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10554 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10555 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10556 return false;
10557 }
10558 // Figure out what value we're actually looking for (after converting to
10559 // the corresponding unsigned type if necessary).
10560 uint64_t DesiredVal;
10561 bool StopAtNull = false;
10562 switch (BuiltinOp) {
10563 case Builtin::BIstrchr:
10564 case Builtin::BI__builtin_strchr:
10565 // strchr compares directly to the passed integer, and therefore
10566 // always fails if given an int that is not a char.
10567 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10568 E->getArg(1)->getType(),
10569 Desired),
10570 Desired))
10571 return ZeroInitialization(E);
10572 StopAtNull = true;
10573 [[fallthrough]];
10574 case Builtin::BImemchr:
10575 case Builtin::BI__builtin_memchr:
10576 case Builtin::BI__builtin_char_memchr:
10577 // memchr compares by converting both sides to unsigned char. That's also
10578 // correct for strchr if we get this far (to cope with plain char being
10579 // unsigned in the strchr case).
10580 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10581 break;
10582
10583 case Builtin::BIwcschr:
10584 case Builtin::BI__builtin_wcschr:
10585 StopAtNull = true;
10586 [[fallthrough]];
10587 case Builtin::BIwmemchr:
10588 case Builtin::BI__builtin_wmemchr:
10589 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10590 DesiredVal = Desired.getZExtValue();
10591 break;
10592 }
10593
10594 for (; MaxLength; --MaxLength) {
10595 APValue Char;
10596 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10597 !Char.isInt())
10598 return false;
10599 if (Char.getInt().getZExtValue() == DesiredVal)
10600 return true;
10601 if (StopAtNull && !Char.getInt())
10602 break;
10603 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10604 return false;
10605 }
10606 // Not found: return nullptr.
10607 return ZeroInitialization(E);
10608 }
10609
10610 case Builtin::BImemcpy:
10611 case Builtin::BImemmove:
10612 case Builtin::BIwmemcpy:
10613 case Builtin::BIwmemmove:
10614 if (Info.getLangOpts().CPlusPlus11)
10615 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10616 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10617 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10618 else
10619 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10620 [[fallthrough]];
10621 case Builtin::BI__builtin_memcpy:
10622 case Builtin::BI__builtin_memmove:
10623 case Builtin::BI__builtin_wmemcpy:
10624 case Builtin::BI__builtin_wmemmove: {
10625 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10626 BuiltinOp == Builtin::BIwmemmove ||
10627 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10628 BuiltinOp == Builtin::BI__builtin_wmemmove;
10629 bool Move = BuiltinOp == Builtin::BImemmove ||
10630 BuiltinOp == Builtin::BIwmemmove ||
10631 BuiltinOp == Builtin::BI__builtin_memmove ||
10632 BuiltinOp == Builtin::BI__builtin_wmemmove;
10633
10634 // The result of mem* is the first argument.
10635 if (!Visit(E->getArg(0)))
10636 return false;
10637 LValue Dest = Result;
10638
10639 LValue Src;
10640 if (!EvaluatePointer(E->getArg(1), Src, Info))
10641 return false;
10642
10643 APSInt N;
10644 if (!EvaluateInteger(E->getArg(2), N, Info))
10645 return false;
10646 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10647
10648 // If the size is zero, we treat this as always being a valid no-op.
10649 // (Even if one of the src and dest pointers is null.)
10650 if (!N)
10651 return true;
10652
10653 // Otherwise, if either of the operands is null, we can't proceed. Don't
10654 // try to determine the type of the copied objects, because there aren't
10655 // any.
10656 if (!Src.Base || !Dest.Base) {
10657 APValue Val;
10658 (!Src.Base ? Src : Dest).moveInto(Val);
10659 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10660 << Move << WChar << !!Src.Base
10661 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10662 return false;
10663 }
10664 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10665 return false;
10666
10667 // We require that Src and Dest are both pointers to arrays of
10668 // trivially-copyable type. (For the wide version, the designator will be
10669 // invalid if the designated object is not a wchar_t.)
10670 QualType T = Dest.Designator.getType(Info.Ctx);
10671 QualType SrcT = Src.Designator.getType(Info.Ctx);
10672 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10673 // FIXME: Consider using our bit_cast implementation to support this.
10674 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10675 return false;
10676 }
10677 if (T->isIncompleteType()) {
10678 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10679 return false;
10680 }
10681 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10682 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10683 return false;
10684 }
10685
10686 // Figure out how many T's we're copying.
10687 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10688 if (TSize == 0)
10689 return false;
10690 if (!WChar) {
10691 uint64_t Remainder;
10692 llvm::APInt OrigN = N;
10693 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10694 if (Remainder) {
10695 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10696 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10697 << (unsigned)TSize;
10698 return false;
10699 }
10700 }
10701
10702 // Check that the copying will remain within the arrays, just so that we
10703 // can give a more meaningful diagnostic. This implicitly also checks that
10704 // N fits into 64 bits.
10705 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10706 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10707 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10708 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10709 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10710 << toString(N, 10, /*Signed*/false);
10711 return false;
10712 }
10713 uint64_t NElems = N.getZExtValue();
10714 uint64_t NBytes = NElems * TSize;
10715
10716 // Check for overlap.
10717 int Direction = 1;
10718 if (HasSameBase(Src, Dest)) {
10719 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10720 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10721 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10722 // Dest is inside the source region.
10723 if (!Move) {
10724 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10725 return false;
10726 }
10727 // For memmove and friends, copy backwards.
10728 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10729 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10730 return false;
10731 Direction = -1;
10732 } else if (!Move && SrcOffset >= DestOffset &&
10733 SrcOffset - DestOffset < NBytes) {
10734 // Src is inside the destination region for memcpy: invalid.
10735 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10736 return false;
10737 }
10738 }
10739
10740 while (true) {
10741 APValue Val;
10742 // FIXME: Set WantObjectRepresentation to true if we're copying a
10743 // char-like type?
10744 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10745 !handleAssignment(Info, E, Dest, T, Val))
10746 return false;
10747 // Do not iterate past the last element; if we're copying backwards, that
10748 // might take us off the start of the array.
10749 if (--NElems == 0)
10750 return true;
10751 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10752 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10753 return false;
10754 }
10755 }
10756
10757 default:
10758 return false;
10759 }
10760}
10761
10762static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10763 APValue &Result, const InitListExpr *ILE,
10764 QualType AllocType);
10765static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10766 APValue &Result,
10767 const CXXConstructExpr *CCE,
10768 QualType AllocType);
10769
10770bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10771 if (!Info.getLangOpts().CPlusPlus20)
10772 Info.CCEDiag(E, diag::note_constexpr_new);
10773
10774 // We cannot speculatively evaluate a delete expression.
10775 if (Info.SpeculativeEvaluationDepth)
10776 return false;
10777
10778 FunctionDecl *OperatorNew = E->getOperatorNew();
10779 QualType AllocType = E->getAllocatedType();
10780 QualType TargetType = AllocType;
10781
10782 bool IsNothrow = false;
10783 bool IsPlacement = false;
10784
10785 if (E->getNumPlacementArgs() == 1 &&
10786 E->getPlacementArg(0)->getType()->isNothrowT()) {
10787 // The only new-placement list we support is of the form (std::nothrow).
10788 //
10789 // FIXME: There is no restriction on this, but it's not clear that any
10790 // other form makes any sense. We get here for cases such as:
10791 //
10792 // new (std::align_val_t{N}) X(int)
10793 //
10794 // (which should presumably be valid only if N is a multiple of
10795 // alignof(int), and in any case can't be deallocated unless N is
10796 // alignof(X) and X has new-extended alignment).
10797 LValue Nothrow;
10798 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10799 return false;
10800 IsNothrow = true;
10801 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10802 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10803 (Info.CurrentCall->CanEvalMSConstexpr &&
10804 OperatorNew->hasAttr<MSConstexprAttr>())) {
10805 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10806 return false;
10807 if (Result.Designator.Invalid)
10808 return false;
10809 TargetType = E->getPlacementArg(0)->getType();
10810 IsPlacement = true;
10811 } else {
10812 Info.FFDiag(E, diag::note_constexpr_new_placement)
10813 << /*C++26 feature*/ 1 << E->getSourceRange();
10814 return false;
10815 }
10816 } else if (E->getNumPlacementArgs()) {
10817 Info.FFDiag(E, diag::note_constexpr_new_placement)
10818 << /*Unsupported*/ 0 << E->getSourceRange();
10819 return false;
10820 } else if (!OperatorNew
10821 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10822 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10823 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10824 return false;
10825 }
10826
10827 const Expr *Init = E->getInitializer();
10828 const InitListExpr *ResizedArrayILE = nullptr;
10829 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10830 bool ValueInit = false;
10831
10832 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10833 const Expr *Stripped = *ArraySize;
10834 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10835 Stripped = ICE->getSubExpr())
10836 if (ICE->getCastKind() != CK_NoOp &&
10837 ICE->getCastKind() != CK_IntegralCast)
10838 break;
10839
10840 llvm::APSInt ArrayBound;
10841 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10842 return false;
10843
10844 // C++ [expr.new]p9:
10845 // The expression is erroneous if:
10846 // -- [...] its value before converting to size_t [or] applying the
10847 // second standard conversion sequence is less than zero
10848 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10849 if (IsNothrow)
10850 return ZeroInitialization(E);
10851
10852 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10853 << ArrayBound << (*ArraySize)->getSourceRange();
10854 return false;
10855 }
10856
10857 // -- its value is such that the size of the allocated object would
10858 // exceed the implementation-defined limit
10859 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10861 Info.Ctx, AllocType, ArrayBound),
10862 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10863 if (IsNothrow)
10864 return ZeroInitialization(E);
10865 return false;
10866 }
10867
10868 // -- the new-initializer is a braced-init-list and the number of
10869 // array elements for which initializers are provided [...]
10870 // exceeds the number of elements to initialize
10871 if (!Init) {
10872 // No initialization is performed.
10873 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10875 ValueInit = true;
10876 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10877 ResizedArrayCCE = CCE;
10878 } else {
10879 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10880 assert(CAT && "unexpected type for array initializer");
10881
10882 unsigned Bits =
10883 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10884 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10885 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10886 if (InitBound.ugt(AllocBound)) {
10887 if (IsNothrow)
10888 return ZeroInitialization(E);
10889
10890 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10891 << toString(AllocBound, 10, /*Signed=*/false)
10892 << toString(InitBound, 10, /*Signed=*/false)
10893 << (*ArraySize)->getSourceRange();
10894 return false;
10895 }
10896
10897 // If the sizes differ, we must have an initializer list, and we need
10898 // special handling for this case when we initialize.
10899 if (InitBound != AllocBound)
10900 ResizedArrayILE = cast<InitListExpr>(Init);
10901 }
10902
10903 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10904 ArraySizeModifier::Normal, 0);
10905 } else {
10906 assert(!AllocType->isArrayType() &&
10907 "array allocation with non-array new");
10908 }
10909
10910 APValue *Val;
10911 if (IsPlacement) {
10913 struct FindObjectHandler {
10914 EvalInfo &Info;
10915 const Expr *E;
10916 QualType AllocType;
10917 const AccessKinds AccessKind;
10918 APValue *Value;
10919
10920 typedef bool result_type;
10921 bool failed() { return false; }
10922 bool checkConst(QualType QT) {
10923 if (QT.isConstQualified()) {
10924 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10925 return false;
10926 }
10927 return true;
10928 }
10929 bool found(APValue &Subobj, QualType SubobjType) {
10930 if (!checkConst(SubobjType))
10931 return false;
10932 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10933 // old name of the object to be used to name the new object.
10934 unsigned SubobjectSize = 1;
10935 unsigned AllocSize = 1;
10936 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10937 AllocSize = CAT->getZExtSize();
10938 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10939 SubobjectSize = CAT->getZExtSize();
10940 if (SubobjectSize < AllocSize ||
10941 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10942 Info.Ctx.getBaseElementType(AllocType))) {
10943 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10944 << SubobjType << AllocType;
10945 return false;
10946 }
10947 Value = &Subobj;
10948 return true;
10949 }
10950 bool found(APSInt &Value, QualType SubobjType) {
10951 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10952 return false;
10953 }
10954 bool found(APFloat &Value, QualType SubobjType) {
10955 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10956 return false;
10957 }
10958 } Handler = {Info, E, AllocType, AK, nullptr};
10959
10960 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10961 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10962 return false;
10963
10964 Val = Handler.Value;
10965
10966 // [basic.life]p1:
10967 // The lifetime of an object o of type T ends when [...] the storage
10968 // which the object occupies is [...] reused by an object that is not
10969 // nested within o (6.6.2).
10970 *Val = APValue();
10971 } else {
10972 // Perform the allocation and obtain a pointer to the resulting object.
10973 Val = Info.createHeapAlloc(E, AllocType, Result);
10974 if (!Val)
10975 return false;
10976 }
10977
10978 if (ValueInit) {
10979 ImplicitValueInitExpr VIE(AllocType);
10980 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10981 return false;
10982 } else if (ResizedArrayILE) {
10983 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10984 AllocType))
10985 return false;
10986 } else if (ResizedArrayCCE) {
10987 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10988 AllocType))
10989 return false;
10990 } else if (Init) {
10991 if (!EvaluateInPlace(*Val, Info, Result, Init))
10992 return false;
10993 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10994 return false;
10995 }
10996
10997 // Array new returns a pointer to the first element, not a pointer to the
10998 // array.
10999 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11000 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11001
11002 return true;
11003}
11004//===----------------------------------------------------------------------===//
11005// Member Pointer Evaluation
11006//===----------------------------------------------------------------------===//
11007
11008namespace {
11009class MemberPointerExprEvaluator
11010 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11011 MemberPtr &Result;
11012
11013 bool Success(const ValueDecl *D) {
11014 Result = MemberPtr(D);
11015 return true;
11016 }
11017public:
11018
11019 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11020 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11021
11022 bool Success(const APValue &V, const Expr *E) {
11023 Result.setFrom(V);
11024 return true;
11025 }
11026 bool ZeroInitialization(const Expr *E) {
11027 return Success((const ValueDecl*)nullptr);
11028 }
11029
11030 bool VisitCastExpr(const CastExpr *E);
11031 bool VisitUnaryAddrOf(const UnaryOperator *E);
11032};
11033} // end anonymous namespace
11034
11035static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11036 EvalInfo &Info) {
11037 assert(!E->isValueDependent());
11038 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11039 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11040}
11041
11042bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11043 switch (E->getCastKind()) {
11044 default:
11045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11046
11047 case CK_NullToMemberPointer:
11048 VisitIgnoredValue(E->getSubExpr());
11049 return ZeroInitialization(E);
11050
11051 case CK_BaseToDerivedMemberPointer: {
11052 if (!Visit(E->getSubExpr()))
11053 return false;
11054 if (E->path_empty())
11055 return true;
11056 // Base-to-derived member pointer casts store the path in derived-to-base
11057 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11058 // the wrong end of the derived->base arc, so stagger the path by one class.
11059 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11060 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11061 PathI != PathE; ++PathI) {
11062 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11063 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11064 if (!Result.castToDerived(Derived))
11065 return Error(E);
11066 }
11067 if (!Result.castToDerived(E->getType()
11068 ->castAs<MemberPointerType>()
11069 ->getMostRecentCXXRecordDecl()))
11070 return Error(E);
11071 return true;
11072 }
11073
11074 case CK_DerivedToBaseMemberPointer:
11075 if (!Visit(E->getSubExpr()))
11076 return false;
11077 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11078 PathE = E->path_end(); PathI != PathE; ++PathI) {
11079 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11080 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11081 if (!Result.castToBase(Base))
11082 return Error(E);
11083 }
11084 return true;
11085 }
11086}
11087
11088bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11089 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11090 // member can be formed.
11091 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11092}
11093
11094//===----------------------------------------------------------------------===//
11095// Record Evaluation
11096//===----------------------------------------------------------------------===//
11097
11098namespace {
11099 class RecordExprEvaluator
11100 : public ExprEvaluatorBase<RecordExprEvaluator> {
11101 const LValue &This;
11102 APValue &Result;
11103 public:
11104
11105 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11106 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11107
11108 bool Success(const APValue &V, const Expr *E) {
11109 Result = V;
11110 return true;
11111 }
11112 bool ZeroInitialization(const Expr *E) {
11113 return ZeroInitialization(E, E->getType());
11114 }
11115 bool ZeroInitialization(const Expr *E, QualType T);
11116
11117 bool VisitCallExpr(const CallExpr *E) {
11118 return handleCallExpr(E, Result, &This);
11119 }
11120 bool VisitCastExpr(const CastExpr *E);
11121 bool VisitInitListExpr(const InitListExpr *E);
11122 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11123 return VisitCXXConstructExpr(E, E->getType());
11124 }
11125 bool VisitLambdaExpr(const LambdaExpr *E);
11126 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11127 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11128 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11129 bool VisitBinCmp(const BinaryOperator *E);
11130 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11131 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11132 ArrayRef<Expr *> Args);
11133 };
11134}
11135
11136/// Perform zero-initialization on an object of non-union class type.
11137/// C++11 [dcl.init]p5:
11138/// To zero-initialize an object or reference of type T means:
11139/// [...]
11140/// -- if T is a (possibly cv-qualified) non-union class type,
11141/// each non-static data member and each base-class subobject is
11142/// zero-initialized
11143static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11144 const RecordDecl *RD,
11145 const LValue &This, APValue &Result) {
11146 assert(!RD->isUnion() && "Expected non-union class type");
11147 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11148 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11149 std::distance(RD->field_begin(), RD->field_end()));
11150
11151 if (RD->isInvalidDecl()) return false;
11152 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11153
11154 if (CD) {
11155 unsigned Index = 0;
11157 End = CD->bases_end(); I != End; ++I, ++Index) {
11158 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11159 LValue Subobject = This;
11160 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11161 return false;
11162 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11163 Result.getStructBase(Index)))
11164 return false;
11165 }
11166 }
11167
11168 for (const auto *I : RD->fields()) {
11169 // -- if T is a reference type, no initialization is performed.
11170 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11171 continue;
11172
11173 LValue Subobject = This;
11174 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11175 return false;
11176
11177 ImplicitValueInitExpr VIE(I->getType());
11178 if (!EvaluateInPlace(
11179 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11180 return false;
11181 }
11182
11183 return true;
11184}
11185
11186bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11187 const auto *RD = T->castAsRecordDecl();
11188 if (RD->isInvalidDecl()) return false;
11189 if (RD->isUnion()) {
11190 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11191 // object's first non-static named data member is zero-initialized
11193 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11194 ++I;
11195 if (I == RD->field_end()) {
11196 Result = APValue((const FieldDecl*)nullptr);
11197 return true;
11198 }
11199
11200 LValue Subobject = This;
11201 if (!HandleLValueMember(Info, E, Subobject, *I))
11202 return false;
11203 Result = APValue(*I);
11204 ImplicitValueInitExpr VIE(I->getType());
11205 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11206 }
11207
11208 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11209 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11210 return false;
11211 }
11212
11213 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11214}
11215
11216bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11217 switch (E->getCastKind()) {
11218 default:
11219 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11220
11221 case CK_ConstructorConversion:
11222 return Visit(E->getSubExpr());
11223
11224 case CK_DerivedToBase:
11225 case CK_UncheckedDerivedToBase: {
11226 APValue DerivedObject;
11227 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11228 return false;
11229 if (!DerivedObject.isStruct())
11230 return Error(E->getSubExpr());
11231
11232 // Derived-to-base rvalue conversion: just slice off the derived part.
11233 APValue *Value = &DerivedObject;
11234 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11235 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11236 PathE = E->path_end(); PathI != PathE; ++PathI) {
11237 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11238 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11239 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11240 RD = Base;
11241 }
11242 Result = *Value;
11243 return true;
11244 }
11245 case CK_HLSLAggregateSplatCast: {
11246 APValue Val;
11247 QualType ValTy;
11248
11249 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11250 return false;
11251
11252 unsigned NEls = elementwiseSize(Info, E->getType());
11253 // splat our Val
11254 SmallVector<APValue> SplatEls(NEls, Val);
11255 SmallVector<QualType> SplatType(NEls, ValTy);
11256
11257 // cast the elements and construct our struct result
11258 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11259 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11260 SplatType))
11261 return false;
11262
11263 return true;
11264 }
11265 case CK_HLSLElementwiseCast: {
11266 SmallVector<APValue> SrcEls;
11267 SmallVector<QualType> SrcTypes;
11268
11269 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11270 SrcTypes))
11271 return false;
11272
11273 // cast the elements and construct our struct result
11274 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11275 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11276 SrcTypes))
11277 return false;
11278
11279 return true;
11280 }
11281 }
11282}
11283
11284bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11285 if (E->isTransparent())
11286 return Visit(E->getInit(0));
11287 return VisitCXXParenListOrInitListExpr(E, E->inits());
11288}
11289
11290bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11291 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11292 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11293 if (RD->isInvalidDecl()) return false;
11294 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11295 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11296
11297 EvalInfo::EvaluatingConstructorRAII EvalObj(
11298 Info,
11299 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11300 CXXRD && CXXRD->getNumBases());
11301
11302 if (RD->isUnion()) {
11303 const FieldDecl *Field;
11304 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11305 Field = ILE->getInitializedFieldInUnion();
11306 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11307 Field = PLIE->getInitializedFieldInUnion();
11308 } else {
11309 llvm_unreachable(
11310 "Expression is neither an init list nor a C++ paren list");
11311 }
11312
11313 Result = APValue(Field);
11314 if (!Field)
11315 return true;
11316
11317 // If the initializer list for a union does not contain any elements, the
11318 // first element of the union is value-initialized.
11319 // FIXME: The element should be initialized from an initializer list.
11320 // Is this difference ever observable for initializer lists which
11321 // we don't build?
11322 ImplicitValueInitExpr VIE(Field->getType());
11323 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11324
11325 LValue Subobject = This;
11326 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11327 return false;
11328
11329 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11330 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11331 isa<CXXDefaultInitExpr>(InitExpr));
11332
11333 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11334 if (Field->isBitField())
11335 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11336 Field);
11337 return true;
11338 }
11339
11340 return false;
11341 }
11342
11343 if (!Result.hasValue())
11344 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11345 std::distance(RD->field_begin(), RD->field_end()));
11346 unsigned ElementNo = 0;
11347 bool Success = true;
11348
11349 // Initialize base classes.
11350 if (CXXRD && CXXRD->getNumBases()) {
11351 for (const auto &Base : CXXRD->bases()) {
11352 assert(ElementNo < Args.size() && "missing init for base class");
11353 const Expr *Init = Args[ElementNo];
11354
11355 LValue Subobject = This;
11356 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11357 return false;
11358
11359 APValue &FieldVal = Result.getStructBase(ElementNo);
11360 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11361 if (!Info.noteFailure())
11362 return false;
11363 Success = false;
11364 }
11365 ++ElementNo;
11366 }
11367
11368 EvalObj.finishedConstructingBases();
11369 }
11370
11371 // Initialize members.
11372 for (const auto *Field : RD->fields()) {
11373 // Anonymous bit-fields are not considered members of the class for
11374 // purposes of aggregate initialization.
11375 if (Field->isUnnamedBitField())
11376 continue;
11377
11378 LValue Subobject = This;
11379
11380 bool HaveInit = ElementNo < Args.size();
11381
11382 // FIXME: Diagnostics here should point to the end of the initializer
11383 // list, not the start.
11384 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11385 Subobject, Field, &Layout))
11386 return false;
11387
11388 // Perform an implicit value-initialization for members beyond the end of
11389 // the initializer list.
11390 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11391 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11392
11393 if (Field->getType()->isIncompleteArrayType()) {
11394 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11395 if (!CAT->isZeroSize()) {
11396 // Bail out for now. This might sort of "work", but the rest of the
11397 // code isn't really prepared to handle it.
11398 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11399 return false;
11400 }
11401 }
11402 }
11403
11404 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11405 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11407
11408 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11409 if (Field->getType()->isReferenceType()) {
11410 LValue Result;
11412 FieldVal)) {
11413 if (!Info.noteFailure())
11414 return false;
11415 Success = false;
11416 }
11417 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11418 (Field->isBitField() &&
11419 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11420 if (!Info.noteFailure())
11421 return false;
11422 Success = false;
11423 }
11424 }
11425
11426 EvalObj.finishedConstructingFields();
11427
11428 return Success;
11429}
11430
11431bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11432 QualType T) {
11433 // Note that E's type is not necessarily the type of our class here; we might
11434 // be initializing an array element instead.
11435 const CXXConstructorDecl *FD = E->getConstructor();
11436 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11437
11438 bool ZeroInit = E->requiresZeroInitialization();
11439 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11440 if (ZeroInit)
11441 return ZeroInitialization(E, T);
11442
11444 }
11445
11446 const FunctionDecl *Definition = nullptr;
11447 auto Body = FD->getBody(Definition);
11448
11449 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11450 return false;
11451
11452 // Avoid materializing a temporary for an elidable copy/move constructor.
11453 if (E->isElidable() && !ZeroInit) {
11454 // FIXME: This only handles the simplest case, where the source object
11455 // is passed directly as the first argument to the constructor.
11456 // This should also handle stepping though implicit casts and
11457 // and conversion sequences which involve two steps, with a
11458 // conversion operator followed by a converting constructor.
11459 const Expr *SrcObj = E->getArg(0);
11460 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11461 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11462 if (const MaterializeTemporaryExpr *ME =
11463 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11464 return Visit(ME->getSubExpr());
11465 }
11466
11467 if (ZeroInit && !ZeroInitialization(E, T))
11468 return false;
11469
11470 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11471 return HandleConstructorCall(E, This, Args,
11473 Result);
11474}
11475
11476bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11477 const CXXInheritedCtorInitExpr *E) {
11478 if (!Info.CurrentCall) {
11479 assert(Info.checkingPotentialConstantExpression());
11480 return false;
11481 }
11482
11483 const CXXConstructorDecl *FD = E->getConstructor();
11484 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11485 return false;
11486
11487 const FunctionDecl *Definition = nullptr;
11488 auto Body = FD->getBody(Definition);
11489
11490 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11491 return false;
11492
11493 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11495 Result);
11496}
11497
11498bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11499 const CXXStdInitializerListExpr *E) {
11500 const ConstantArrayType *ArrayType =
11501 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11502
11503 LValue Array;
11504 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11505 return false;
11506
11507 assert(ArrayType && "unexpected type for array initializer");
11508
11509 // Get a pointer to the first element of the array.
11510 Array.addArray(Info, E, ArrayType);
11511
11512 // FIXME: What if the initializer_list type has base classes, etc?
11513 Result = APValue(APValue::UninitStruct(), 0, 2);
11514 Array.moveInto(Result.getStructField(0));
11515
11516 auto *Record = E->getType()->castAsRecordDecl();
11517 RecordDecl::field_iterator Field = Record->field_begin();
11518 assert(Field != Record->field_end() &&
11519 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11520 ArrayType->getElementType()) &&
11521 "Expected std::initializer_list first field to be const E *");
11522 ++Field;
11523 assert(Field != Record->field_end() &&
11524 "Expected std::initializer_list to have two fields");
11525
11526 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11527 // Length.
11528 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11529 } else {
11530 // End pointer.
11531 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11532 ArrayType->getElementType()) &&
11533 "Expected std::initializer_list second field to be const E *");
11534 if (!HandleLValueArrayAdjustment(Info, E, Array,
11535 ArrayType->getElementType(),
11536 ArrayType->getZExtSize()))
11537 return false;
11538 Array.moveInto(Result.getStructField(1));
11539 }
11540
11541 assert(++Field == Record->field_end() &&
11542 "Expected std::initializer_list to only have two fields");
11543
11544 return true;
11545}
11546
11547bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11548 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11549 if (ClosureClass->isInvalidDecl())
11550 return false;
11551
11552 const size_t NumFields =
11553 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
11554
11555 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11556 E->capture_init_end()) &&
11557 "The number of lambda capture initializers should equal the number of "
11558 "fields within the closure type");
11559
11560 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11561 // Iterate through all the lambda's closure object's fields and initialize
11562 // them.
11563 auto *CaptureInitIt = E->capture_init_begin();
11564 bool Success = true;
11565 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11566 for (const auto *Field : ClosureClass->fields()) {
11567 assert(CaptureInitIt != E->capture_init_end());
11568 // Get the initializer for this field
11569 Expr *const CurFieldInit = *CaptureInitIt++;
11570
11571 // If there is no initializer, either this is a VLA or an error has
11572 // occurred.
11573 if (!CurFieldInit || CurFieldInit->containsErrors())
11574 return Error(E);
11575
11576 LValue Subobject = This;
11577
11578 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11579 return false;
11580
11581 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11582 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11583 if (!Info.keepEvaluatingAfterFailure())
11584 return false;
11585 Success = false;
11586 }
11587 }
11588 return Success;
11589}
11590
11591static bool EvaluateRecord(const Expr *E, const LValue &This,
11592 APValue &Result, EvalInfo &Info) {
11593 assert(!E->isValueDependent());
11594 assert(E->isPRValue() && E->getType()->isRecordType() &&
11595 "can't evaluate expression as a record rvalue");
11596 return RecordExprEvaluator(Info, This, Result).Visit(E);
11597}
11598
11599//===----------------------------------------------------------------------===//
11600// Temporary Evaluation
11601//
11602// Temporaries are represented in the AST as rvalues, but generally behave like
11603// lvalues. The full-object of which the temporary is a subobject is implicitly
11604// materialized so that a reference can bind to it.
11605//===----------------------------------------------------------------------===//
11606namespace {
11607class TemporaryExprEvaluator
11608 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11609public:
11610 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11611 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11612
11613 /// Visit an expression which constructs the value of this temporary.
11614 bool VisitConstructExpr(const Expr *E) {
11615 APValue &Value = Info.CurrentCall->createTemporary(
11616 E, E->getType(), ScopeKind::FullExpression, Result);
11617 return EvaluateInPlace(Value, Info, Result, E);
11618 }
11619
11620 bool VisitCastExpr(const CastExpr *E) {
11621 switch (E->getCastKind()) {
11622 default:
11623 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11624
11625 case CK_ConstructorConversion:
11626 return VisitConstructExpr(E->getSubExpr());
11627 }
11628 }
11629 bool VisitInitListExpr(const InitListExpr *E) {
11630 return VisitConstructExpr(E);
11631 }
11632 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11633 return VisitConstructExpr(E);
11634 }
11635 bool VisitCallExpr(const CallExpr *E) {
11636 return VisitConstructExpr(E);
11637 }
11638 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11639 return VisitConstructExpr(E);
11640 }
11641 bool VisitLambdaExpr(const LambdaExpr *E) {
11642 return VisitConstructExpr(E);
11643 }
11644};
11645} // end anonymous namespace
11646
11647/// Evaluate an expression of record type as a temporary.
11648static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11649 assert(!E->isValueDependent());
11650 assert(E->isPRValue() && E->getType()->isRecordType());
11651 return TemporaryExprEvaluator(Info, Result).Visit(E);
11652}
11653
11654//===----------------------------------------------------------------------===//
11655// Vector Evaluation
11656//===----------------------------------------------------------------------===//
11657
11658namespace {
11659 class VectorExprEvaluator
11660 : public ExprEvaluatorBase<VectorExprEvaluator> {
11661 APValue &Result;
11662 public:
11663
11664 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11665 : ExprEvaluatorBaseTy(info), Result(Result) {}
11666
11667 bool Success(ArrayRef<APValue> V, const Expr *E) {
11668 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11669 // FIXME: remove this APValue copy.
11670 Result = APValue(V.data(), V.size());
11671 return true;
11672 }
11673 bool Success(const APValue &V, const Expr *E) {
11674 assert(V.isVector());
11675 Result = V;
11676 return true;
11677 }
11678 bool ZeroInitialization(const Expr *E);
11679
11680 bool VisitUnaryReal(const UnaryOperator *E)
11681 { return Visit(E->getSubExpr()); }
11682 bool VisitCastExpr(const CastExpr* E);
11683 bool VisitInitListExpr(const InitListExpr *E);
11684 bool VisitUnaryImag(const UnaryOperator *E);
11685 bool VisitBinaryOperator(const BinaryOperator *E);
11686 bool VisitUnaryOperator(const UnaryOperator *E);
11687 bool VisitCallExpr(const CallExpr *E);
11688 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11689 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11690
11691 // FIXME: Missing: conditional operator (for GNU
11692 // conditional select), ExtVectorElementExpr
11693 };
11694} // end anonymous namespace
11695
11696static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11697 assert(E->isPRValue() && E->getType()->isVectorType() &&
11698 "not a vector prvalue");
11699 return VectorExprEvaluator(Info, Result).Visit(E);
11700}
11701
11702static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11703 assert(Val.isVector() && "expected vector APValue");
11704 unsigned NumElts = Val.getVectorLength();
11705
11706 // Each element is one bit, so create an integer with NumElts bits.
11707 llvm::APInt Result(NumElts, 0);
11708
11709 for (unsigned I = 0; I < NumElts; ++I) {
11710 const APValue &Elt = Val.getVectorElt(I);
11711 assert(Elt.isInt() && "expected integer element in bool vector");
11712
11713 if (Elt.getInt().getBoolValue())
11714 Result.setBit(I);
11715 }
11716
11717 return Result;
11718}
11719
11720bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11721 const VectorType *VTy = E->getType()->castAs<VectorType>();
11722 unsigned NElts = VTy->getNumElements();
11723
11724 const Expr *SE = E->getSubExpr();
11725 QualType SETy = SE->getType();
11726
11727 switch (E->getCastKind()) {
11728 case CK_VectorSplat: {
11729 APValue Val = APValue();
11730 if (SETy->isIntegerType()) {
11731 APSInt IntResult;
11732 if (!EvaluateInteger(SE, IntResult, Info))
11733 return false;
11734 Val = APValue(std::move(IntResult));
11735 } else if (SETy->isRealFloatingType()) {
11736 APFloat FloatResult(0.0);
11737 if (!EvaluateFloat(SE, FloatResult, Info))
11738 return false;
11739 Val = APValue(std::move(FloatResult));
11740 } else {
11741 return Error(E);
11742 }
11743
11744 // Splat and create vector APValue.
11745 SmallVector<APValue, 4> Elts(NElts, Val);
11746 return Success(Elts, E);
11747 }
11748 case CK_BitCast: {
11749 APValue SVal;
11750 if (!Evaluate(SVal, Info, SE))
11751 return false;
11752
11753 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11754 // Give up if the input isn't an int, float, or vector. For example, we
11755 // reject "(v4i16)(intptr_t)&a".
11756 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11757 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11758 << Info.Ctx.getLangOpts().CPlusPlus;
11759 return false;
11760 }
11761
11762 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11763 return false;
11764
11765 return true;
11766 }
11767 case CK_HLSLVectorTruncation: {
11768 APValue Val;
11769 SmallVector<APValue, 4> Elements;
11770 if (!EvaluateVector(SE, Val, Info))
11771 return Error(E);
11772 for (unsigned I = 0; I < NElts; I++)
11773 Elements.push_back(Val.getVectorElt(I));
11774 return Success(Elements, E);
11775 }
11776 case CK_HLSLAggregateSplatCast: {
11777 APValue Val;
11778 QualType ValTy;
11779
11780 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11781 return false;
11782
11783 // cast our Val once.
11785 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11786 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11787 Result))
11788 return false;
11789
11790 SmallVector<APValue, 4> SplatEls(NElts, Result);
11791 return Success(SplatEls, E);
11792 }
11793 case CK_HLSLElementwiseCast: {
11794 SmallVector<APValue> SrcVals;
11795 SmallVector<QualType> SrcTypes;
11796
11797 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11798 return false;
11799
11800 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11801 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11802 SmallVector<APValue, 4> ResultEls(NElts);
11803 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11804 ResultEls))
11805 return false;
11806 return Success(ResultEls, E);
11807 }
11808 default:
11809 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11810 }
11811}
11812
11813bool
11814VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11815 const VectorType *VT = E->getType()->castAs<VectorType>();
11816 unsigned NumInits = E->getNumInits();
11817 unsigned NumElements = VT->getNumElements();
11818
11819 QualType EltTy = VT->getElementType();
11820 SmallVector<APValue, 4> Elements;
11821
11822 // MFloat8 type doesn't have constants and thus constant folding
11823 // is impossible.
11824 if (EltTy->isMFloat8Type())
11825 return false;
11826
11827 // The number of initializers can be less than the number of
11828 // vector elements. For OpenCL, this can be due to nested vector
11829 // initialization. For GCC compatibility, missing trailing elements
11830 // should be initialized with zeroes.
11831 unsigned CountInits = 0, CountElts = 0;
11832 while (CountElts < NumElements) {
11833 // Handle nested vector initialization.
11834 if (CountInits < NumInits
11835 && E->getInit(CountInits)->getType()->isVectorType()) {
11836 APValue v;
11837 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11838 return Error(E);
11839 unsigned vlen = v.getVectorLength();
11840 for (unsigned j = 0; j < vlen; j++)
11841 Elements.push_back(v.getVectorElt(j));
11842 CountElts += vlen;
11843 } else if (EltTy->isIntegerType()) {
11844 llvm::APSInt sInt(32);
11845 if (CountInits < NumInits) {
11846 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11847 return false;
11848 } else // trailing integer zero.
11849 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11850 Elements.push_back(APValue(sInt));
11851 CountElts++;
11852 } else {
11853 llvm::APFloat f(0.0);
11854 if (CountInits < NumInits) {
11855 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11856 return false;
11857 } else // trailing float zero.
11858 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11859 Elements.push_back(APValue(f));
11860 CountElts++;
11861 }
11862 CountInits++;
11863 }
11864 return Success(Elements, E);
11865}
11866
11867bool
11868VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11869 const auto *VT = E->getType()->castAs<VectorType>();
11870 QualType EltTy = VT->getElementType();
11871 APValue ZeroElement;
11872 if (EltTy->isIntegerType())
11873 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11874 else
11875 ZeroElement =
11876 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11877
11878 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11879 return Success(Elements, E);
11880}
11881
11882bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11883 VisitIgnoredValue(E->getSubExpr());
11884 return ZeroInitialization(E);
11885}
11886
11887bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11888 BinaryOperatorKind Op = E->getOpcode();
11889 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11890 "Operation not supported on vector types");
11891
11892 if (Op == BO_Comma)
11893 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11894
11895 Expr *LHS = E->getLHS();
11896 Expr *RHS = E->getRHS();
11897
11898 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11899 "Must both be vector types");
11900 // Checking JUST the types are the same would be fine, except shifts don't
11901 // need to have their types be the same (since you always shift by an int).
11902 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11903 E->getType()->castAs<VectorType>()->getNumElements() &&
11904 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11905 E->getType()->castAs<VectorType>()->getNumElements() &&
11906 "All operands must be the same size.");
11907
11908 APValue LHSValue;
11909 APValue RHSValue;
11910 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11911 if (!LHSOK && !Info.noteFailure())
11912 return false;
11913 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11914 return false;
11915
11916 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11917 return false;
11918
11919 return Success(LHSValue, E);
11920}
11921
11922static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11923 QualType ResultTy,
11925 APValue Elt) {
11926 switch (Op) {
11927 case UO_Plus:
11928 // Nothing to do here.
11929 return Elt;
11930 case UO_Minus:
11931 if (Elt.getKind() == APValue::Int) {
11932 Elt.getInt().negate();
11933 } else {
11934 assert(Elt.getKind() == APValue::Float &&
11935 "Vector can only be int or float type");
11936 Elt.getFloat().changeSign();
11937 }
11938 return Elt;
11939 case UO_Not:
11940 // This is only valid for integral types anyway, so we don't have to handle
11941 // float here.
11942 assert(Elt.getKind() == APValue::Int &&
11943 "Vector operator ~ can only be int");
11944 Elt.getInt().flipAllBits();
11945 return Elt;
11946 case UO_LNot: {
11947 if (Elt.getKind() == APValue::Int) {
11948 Elt.getInt() = !Elt.getInt();
11949 // operator ! on vectors returns -1 for 'truth', so negate it.
11950 Elt.getInt().negate();
11951 return Elt;
11952 }
11953 assert(Elt.getKind() == APValue::Float &&
11954 "Vector can only be int or float type");
11955 // Float types result in an int of the same size, but -1 for true, or 0 for
11956 // false.
11957 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11958 ResultTy->isUnsignedIntegerType()};
11959 if (Elt.getFloat().isZero())
11960 EltResult.setAllBits();
11961 else
11962 EltResult.clearAllBits();
11963
11964 return APValue{EltResult};
11965 }
11966 default:
11967 // FIXME: Implement the rest of the unary operators.
11968 return std::nullopt;
11969 }
11970}
11971
11972bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11973 Expr *SubExpr = E->getSubExpr();
11974 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11975 // This result element type differs in the case of negating a floating point
11976 // vector, since the result type is the a vector of the equivilant sized
11977 // integer.
11978 const QualType ResultEltTy = VD->getElementType();
11979 UnaryOperatorKind Op = E->getOpcode();
11980
11981 APValue SubExprValue;
11982 if (!Evaluate(SubExprValue, Info, SubExpr))
11983 return false;
11984
11985 // FIXME: This vector evaluator someday needs to be changed to be LValue
11986 // aware/keep LValue information around, rather than dealing with just vector
11987 // types directly. Until then, we cannot handle cases where the operand to
11988 // these unary operators is an LValue. The only case I've been able to see
11989 // cause this is operator++ assigning to a member expression (only valid in
11990 // altivec compilations) in C mode, so this shouldn't limit us too much.
11991 if (SubExprValue.isLValue())
11992 return false;
11993
11994 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11995 "Vector length doesn't match type?");
11996
11997 SmallVector<APValue, 4> ResultElements;
11998 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11999 std::optional<APValue> Elt = handleVectorUnaryOperator(
12000 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12001 if (!Elt)
12002 return false;
12003 ResultElements.push_back(*Elt);
12004 }
12005 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12006}
12007
12008static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12009 const Expr *E, QualType SourceTy,
12010 QualType DestTy, APValue const &Original,
12011 APValue &Result) {
12012 if (SourceTy->isIntegerType()) {
12013 if (DestTy->isRealFloatingType()) {
12014 Result = APValue(APFloat(0.0));
12015 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12016 DestTy, Result.getFloat());
12017 }
12018 if (DestTy->isIntegerType()) {
12019 Result = APValue(
12020 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12021 return true;
12022 }
12023 } else if (SourceTy->isRealFloatingType()) {
12024 if (DestTy->isRealFloatingType()) {
12025 Result = Original;
12026 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12027 Result.getFloat());
12028 }
12029 if (DestTy->isIntegerType()) {
12030 Result = APValue(APSInt());
12031 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12032 DestTy, Result.getInt());
12033 }
12034 }
12035
12036 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12037 << SourceTy << DestTy;
12038 return false;
12039}
12040
12041static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12042 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12043 APValue LHS, RHS;
12044 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12045 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12046 return false;
12047
12048 unsigned LHSVecLen = LHS.getVectorLength();
12049 unsigned RHSVecLen = RHS.getVectorLength();
12050
12051 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12052 "pack builtin LHSVecLen must equal to RHSVecLen");
12053
12054 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12055 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12056
12057 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12058 QualType DstElemTy = DstVT->getElementType();
12059 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12060
12061 const unsigned SrcPerLane = 128 / SrcBits;
12062 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12063
12065 Out.reserve(LHSVecLen + RHSVecLen);
12066
12067 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12068 unsigned base = Lane * SrcPerLane;
12069 for (unsigned I = 0; I != SrcPerLane; ++I)
12070 Out.emplace_back(APValue(
12071 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12072 for (unsigned I = 0; I != SrcPerLane; ++I)
12073 Out.emplace_back(APValue(
12074 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12075 }
12076
12077 Result = APValue(Out.data(), Out.size());
12078 return true;
12079}
12080
12082 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12083 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12084 GetSourceIndex) {
12085
12086 const auto *VT = Call->getType()->getAs<VectorType>();
12087 if (!VT)
12088 return false;
12089
12090 unsigned ShuffleMask = 0;
12091 APValue A, MaskVector, B;
12092 bool IsVectorMask = false;
12093 bool IsSingleOperand = (Call->getNumArgs() == 2);
12094
12095 if (IsSingleOperand) {
12096 QualType MaskType = Call->getArg(1)->getType();
12097 if (MaskType->isVectorType()) {
12098 IsVectorMask = true;
12099 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12100 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12101 return false;
12102 B = A;
12103 } else if (MaskType->isIntegerType()) {
12104 APSInt MaskImm;
12105 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12106 return false;
12107 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12108 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12109 return false;
12110 B = A;
12111 } else {
12112 return false;
12113 }
12114 } else {
12115 QualType Arg2Type = Call->getArg(2)->getType();
12116 if (Arg2Type->isVectorType()) {
12117 IsVectorMask = true;
12118 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12119 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12120 !EvaluateAsRValue(Info, Call->getArg(2), B))
12121 return false;
12122 } else if (Arg2Type->isIntegerType()) {
12123 APSInt MaskImm;
12124 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12125 return false;
12126 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12127 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12128 !EvaluateAsRValue(Info, Call->getArg(1), B))
12129 return false;
12130 } else {
12131 return false;
12132 }
12133 }
12134
12135 unsigned NumElts = VT->getNumElements();
12136 SmallVector<APValue, 64> ResultElements;
12137 ResultElements.reserve(NumElts);
12138
12139 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12140 if (IsVectorMask) {
12141 ShuffleMask = static_cast<unsigned>(
12142 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12143 }
12144 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12145
12146 if (SrcIdx < 0) {
12147 // Zero out this element
12148 QualType ElemTy = VT->getElementType();
12149 if (ElemTy->isRealFloatingType()) {
12150 ResultElements.push_back(
12151 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12152 } else if (ElemTy->isIntegerType()) {
12153 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12154 ResultElements.push_back(APValue(Zero));
12155 } else {
12156 // Other types of fallback logic
12157 ResultElements.push_back(APValue());
12158 }
12159 } else {
12160 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12161 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12162 }
12163 }
12164
12165 Out = APValue(ResultElements.data(), ResultElements.size());
12166 return true;
12167}
12168
12169bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12170 if (!IsConstantEvaluatedBuiltinCall(E))
12171 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12172
12173 auto EvaluateBinOpExpr =
12174 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12175 APValue SourceLHS, SourceRHS;
12176 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12177 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12178 return false;
12179
12180 auto *DestTy = E->getType()->castAs<VectorType>();
12181 QualType DestEltTy = DestTy->getElementType();
12182 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12183 unsigned SourceLen = SourceLHS.getVectorLength();
12184 SmallVector<APValue, 4> ResultElements;
12185 ResultElements.reserve(SourceLen);
12186
12187 if (SourceRHS.isInt()) {
12188 const APSInt &RHS = SourceRHS.getInt();
12189 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12190 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12191 ResultElements.push_back(
12192 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12193 }
12194 } else {
12195 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12196 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12197 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12198 ResultElements.push_back(
12199 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12200 }
12201 }
12202 return Success(APValue(ResultElements.data(), SourceLen), E);
12203 };
12204
12205 switch (E->getBuiltinCallee()) {
12206 default:
12207 return false;
12208 case Builtin::BI__builtin_elementwise_popcount:
12209 case Builtin::BI__builtin_elementwise_bitreverse: {
12210 APValue Source;
12211 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12212 return false;
12213
12214 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12215 unsigned SourceLen = Source.getVectorLength();
12216 SmallVector<APValue, 4> ResultElements;
12217 ResultElements.reserve(SourceLen);
12218
12219 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12220 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12221 switch (E->getBuiltinCallee()) {
12222 case Builtin::BI__builtin_elementwise_popcount:
12223 ResultElements.push_back(APValue(
12224 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12225 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12226 break;
12227 case Builtin::BI__builtin_elementwise_bitreverse:
12228 ResultElements.push_back(
12229 APValue(APSInt(Elt.reverseBits(),
12230 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12231 break;
12232 }
12233 }
12234
12235 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12236 }
12237 case Builtin::BI__builtin_elementwise_abs: {
12238 APValue Source;
12239 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12240 return false;
12241
12242 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12243 unsigned SourceLen = Source.getVectorLength();
12244 SmallVector<APValue, 4> ResultElements;
12245 ResultElements.reserve(SourceLen);
12246
12247 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12248 APValue CurrentEle = Source.getVectorElt(EltNum);
12249 APValue Val = DestEltTy->isFloatingType()
12250 ? APValue(llvm::abs(CurrentEle.getFloat()))
12251 : APValue(APSInt(
12252 CurrentEle.getInt().abs(),
12253 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12254 ResultElements.push_back(Val);
12255 }
12256
12257 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12258 }
12259
12260 case Builtin::BI__builtin_elementwise_add_sat:
12261 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12262 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12263 });
12264
12265 case Builtin::BI__builtin_elementwise_sub_sat:
12266 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12267 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12268 });
12269
12270 case X86::BI__builtin_ia32_extract128i256:
12271 case X86::BI__builtin_ia32_vextractf128_pd256:
12272 case X86::BI__builtin_ia32_vextractf128_ps256:
12273 case X86::BI__builtin_ia32_vextractf128_si256: {
12274 APValue SourceVec, SourceImm;
12275 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12276 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12277 return false;
12278
12279 if (!SourceVec.isVector())
12280 return false;
12281
12282 const auto *RetVT = E->getType()->castAs<VectorType>();
12283 unsigned RetLen = RetVT->getNumElements();
12284 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12285
12286 SmallVector<APValue, 32> ResultElements;
12287 ResultElements.reserve(RetLen);
12288
12289 for (unsigned I = 0; I < RetLen; I++)
12290 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12291
12292 return Success(APValue(ResultElements.data(), RetLen), E);
12293 }
12294
12295 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12296 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12297 case X86::BI__builtin_ia32_extracti32x4_mask:
12298 case X86::BI__builtin_ia32_extractf32x4_mask:
12299 case X86::BI__builtin_ia32_extracti32x8_mask:
12300 case X86::BI__builtin_ia32_extractf32x8_mask:
12301 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12302 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12303 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12304 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12305 case X86::BI__builtin_ia32_extracti64x4_mask:
12306 case X86::BI__builtin_ia32_extractf64x4_mask: {
12307 APValue SourceVec, MergeVec;
12308 APSInt Imm, MaskImm;
12309
12310 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12311 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12312 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12313 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12314 return false;
12315
12316 const auto *RetVT = E->getType()->castAs<VectorType>();
12317 unsigned RetLen = RetVT->getNumElements();
12318
12319 if (!SourceVec.isVector() || !MergeVec.isVector())
12320 return false;
12321 unsigned SrcLen = SourceVec.getVectorLength();
12322 unsigned Lanes = SrcLen / RetLen;
12323 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12324 unsigned Base = Lane * RetLen;
12325
12326 SmallVector<APValue, 32> ResultElements;
12327 ResultElements.reserve(RetLen);
12328 for (unsigned I = 0; I < RetLen; ++I) {
12329 if (MaskImm[I])
12330 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12331 else
12332 ResultElements.push_back(MergeVec.getVectorElt(I));
12333 }
12334 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12335 }
12336
12337 case clang::X86::BI__builtin_ia32_pavgb128:
12338 case clang::X86::BI__builtin_ia32_pavgw128:
12339 case clang::X86::BI__builtin_ia32_pavgb256:
12340 case clang::X86::BI__builtin_ia32_pavgw256:
12341 case clang::X86::BI__builtin_ia32_pavgb512:
12342 case clang::X86::BI__builtin_ia32_pavgw512:
12343 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12344
12345 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12346 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12347 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12348 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12349 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12350 .extractBits(16, 1);
12351 });
12352
12353 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12354 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12355 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12356 case clang::X86::BI__builtin_ia32_pmaddwd128:
12357 case clang::X86::BI__builtin_ia32_pmaddwd256:
12358 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12359 APValue SourceLHS, SourceRHS;
12360 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12361 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12362 return false;
12363
12364 auto *DestTy = E->getType()->castAs<VectorType>();
12365 QualType DestEltTy = DestTy->getElementType();
12366 unsigned SourceLen = SourceLHS.getVectorLength();
12367 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12368 SmallVector<APValue, 4> ResultElements;
12369 ResultElements.reserve(SourceLen / 2);
12370
12371 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12372 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12373 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12374 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12375 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12376 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12377
12378 switch (E->getBuiltinCallee()) {
12379 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12380 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12381 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12382 ResultElements.push_back(APValue(
12383 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12384 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12385 DestUnsigned)));
12386 break;
12387 case clang::X86::BI__builtin_ia32_pmaddwd128:
12388 case clang::X86::BI__builtin_ia32_pmaddwd256:
12389 case clang::X86::BI__builtin_ia32_pmaddwd512:
12390 ResultElements.push_back(
12391 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12392 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12393 DestUnsigned)));
12394 break;
12395 }
12396 }
12397
12398 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12399 }
12400
12401 case clang::X86::BI__builtin_ia32_pmulhuw128:
12402 case clang::X86::BI__builtin_ia32_pmulhuw256:
12403 case clang::X86::BI__builtin_ia32_pmulhuw512:
12404 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12405
12406 case clang::X86::BI__builtin_ia32_pmulhw128:
12407 case clang::X86::BI__builtin_ia32_pmulhw256:
12408 case clang::X86::BI__builtin_ia32_pmulhw512:
12409 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12410
12411 case clang::X86::BI__builtin_ia32_psllv2di:
12412 case clang::X86::BI__builtin_ia32_psllv4di:
12413 case clang::X86::BI__builtin_ia32_psllv4si:
12414 case clang::X86::BI__builtin_ia32_psllv8di:
12415 case clang::X86::BI__builtin_ia32_psllv8hi:
12416 case clang::X86::BI__builtin_ia32_psllv8si:
12417 case clang::X86::BI__builtin_ia32_psllv16hi:
12418 case clang::X86::BI__builtin_ia32_psllv16si:
12419 case clang::X86::BI__builtin_ia32_psllv32hi:
12420 case clang::X86::BI__builtin_ia32_psllwi128:
12421 case clang::X86::BI__builtin_ia32_pslldi128:
12422 case clang::X86::BI__builtin_ia32_psllqi128:
12423 case clang::X86::BI__builtin_ia32_psllwi256:
12424 case clang::X86::BI__builtin_ia32_pslldi256:
12425 case clang::X86::BI__builtin_ia32_psllqi256:
12426 case clang::X86::BI__builtin_ia32_psllwi512:
12427 case clang::X86::BI__builtin_ia32_pslldi512:
12428 case clang::X86::BI__builtin_ia32_psllqi512:
12429 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12430 if (RHS.uge(LHS.getBitWidth())) {
12431 return APInt::getZero(LHS.getBitWidth());
12432 }
12433 return LHS.shl(RHS.getZExtValue());
12434 });
12435
12436 case clang::X86::BI__builtin_ia32_psrav4si:
12437 case clang::X86::BI__builtin_ia32_psrav8di:
12438 case clang::X86::BI__builtin_ia32_psrav8hi:
12439 case clang::X86::BI__builtin_ia32_psrav8si:
12440 case clang::X86::BI__builtin_ia32_psrav16hi:
12441 case clang::X86::BI__builtin_ia32_psrav16si:
12442 case clang::X86::BI__builtin_ia32_psrav32hi:
12443 case clang::X86::BI__builtin_ia32_psravq128:
12444 case clang::X86::BI__builtin_ia32_psravq256:
12445 case clang::X86::BI__builtin_ia32_psrawi128:
12446 case clang::X86::BI__builtin_ia32_psradi128:
12447 case clang::X86::BI__builtin_ia32_psraqi128:
12448 case clang::X86::BI__builtin_ia32_psrawi256:
12449 case clang::X86::BI__builtin_ia32_psradi256:
12450 case clang::X86::BI__builtin_ia32_psraqi256:
12451 case clang::X86::BI__builtin_ia32_psrawi512:
12452 case clang::X86::BI__builtin_ia32_psradi512:
12453 case clang::X86::BI__builtin_ia32_psraqi512:
12454 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12455 if (RHS.uge(LHS.getBitWidth())) {
12456 return LHS.ashr(LHS.getBitWidth() - 1);
12457 }
12458 return LHS.ashr(RHS.getZExtValue());
12459 });
12460
12461 case clang::X86::BI__builtin_ia32_psrlv2di:
12462 case clang::X86::BI__builtin_ia32_psrlv4di:
12463 case clang::X86::BI__builtin_ia32_psrlv4si:
12464 case clang::X86::BI__builtin_ia32_psrlv8di:
12465 case clang::X86::BI__builtin_ia32_psrlv8hi:
12466 case clang::X86::BI__builtin_ia32_psrlv8si:
12467 case clang::X86::BI__builtin_ia32_psrlv16hi:
12468 case clang::X86::BI__builtin_ia32_psrlv16si:
12469 case clang::X86::BI__builtin_ia32_psrlv32hi:
12470 case clang::X86::BI__builtin_ia32_psrlwi128:
12471 case clang::X86::BI__builtin_ia32_psrldi128:
12472 case clang::X86::BI__builtin_ia32_psrlqi128:
12473 case clang::X86::BI__builtin_ia32_psrlwi256:
12474 case clang::X86::BI__builtin_ia32_psrldi256:
12475 case clang::X86::BI__builtin_ia32_psrlqi256:
12476 case clang::X86::BI__builtin_ia32_psrlwi512:
12477 case clang::X86::BI__builtin_ia32_psrldi512:
12478 case clang::X86::BI__builtin_ia32_psrlqi512:
12479 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12480 if (RHS.uge(LHS.getBitWidth())) {
12481 return APInt::getZero(LHS.getBitWidth());
12482 }
12483 return LHS.lshr(RHS.getZExtValue());
12484 });
12485 case X86::BI__builtin_ia32_packsswb128:
12486 case X86::BI__builtin_ia32_packsswb256:
12487 case X86::BI__builtin_ia32_packsswb512:
12488 case X86::BI__builtin_ia32_packssdw128:
12489 case X86::BI__builtin_ia32_packssdw256:
12490 case X86::BI__builtin_ia32_packssdw512:
12491 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12492 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12493 });
12494 case X86::BI__builtin_ia32_packusdw128:
12495 case X86::BI__builtin_ia32_packusdw256:
12496 case X86::BI__builtin_ia32_packusdw512:
12497 case X86::BI__builtin_ia32_packuswb128:
12498 case X86::BI__builtin_ia32_packuswb256:
12499 case X86::BI__builtin_ia32_packuswb512:
12500 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12501 unsigned DstBits = Src.getBitWidth() / 2;
12502 if (Src.isNegative())
12503 return APInt::getZero(DstBits);
12504 if (Src.isIntN(DstBits))
12505 return APInt((Src).trunc(DstBits));
12506 return APInt::getAllOnes(DstBits);
12507 });
12508 case clang::X86::BI__builtin_ia32_pmuldq128:
12509 case clang::X86::BI__builtin_ia32_pmuldq256:
12510 case clang::X86::BI__builtin_ia32_pmuldq512:
12511 case clang::X86::BI__builtin_ia32_pmuludq128:
12512 case clang::X86::BI__builtin_ia32_pmuludq256:
12513 case clang::X86::BI__builtin_ia32_pmuludq512: {
12514 APValue SourceLHS, SourceRHS;
12515 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12516 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12517 return false;
12518
12519 unsigned SourceLen = SourceLHS.getVectorLength();
12520 SmallVector<APValue, 4> ResultElements;
12521 ResultElements.reserve(SourceLen / 2);
12522
12523 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12524 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12525 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12526
12527 switch (E->getBuiltinCallee()) {
12528 case clang::X86::BI__builtin_ia32_pmuludq128:
12529 case clang::X86::BI__builtin_ia32_pmuludq256:
12530 case clang::X86::BI__builtin_ia32_pmuludq512:
12531 ResultElements.push_back(
12532 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12533 break;
12534 case clang::X86::BI__builtin_ia32_pmuldq128:
12535 case clang::X86::BI__builtin_ia32_pmuldq256:
12536 case clang::X86::BI__builtin_ia32_pmuldq512:
12537 ResultElements.push_back(
12538 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12539 break;
12540 }
12541 }
12542
12543 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12544 }
12545
12546 case X86::BI__builtin_ia32_vpmadd52luq128:
12547 case X86::BI__builtin_ia32_vpmadd52luq256:
12548 case X86::BI__builtin_ia32_vpmadd52luq512: {
12549 APValue A, B, C;
12550 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12551 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12552 !EvaluateAsRValue(Info, E->getArg(2), C))
12553 return false;
12554
12555 unsigned ALen = A.getVectorLength();
12556 SmallVector<APValue, 4> ResultElements;
12557 ResultElements.reserve(ALen);
12558
12559 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12560 APInt AElt = A.getVectorElt(EltNum).getInt();
12561 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12562 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12563 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12564 ResultElements.push_back(APValue(ResElt));
12565 }
12566
12567 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12568 }
12569 case X86::BI__builtin_ia32_vpmadd52huq128:
12570 case X86::BI__builtin_ia32_vpmadd52huq256:
12571 case X86::BI__builtin_ia32_vpmadd52huq512: {
12572 APValue A, B, C;
12573 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12574 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12575 !EvaluateAsRValue(Info, E->getArg(2), C))
12576 return false;
12577
12578 unsigned ALen = A.getVectorLength();
12579 SmallVector<APValue, 4> ResultElements;
12580 ResultElements.reserve(ALen);
12581
12582 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12583 APInt AElt = A.getVectorElt(EltNum).getInt();
12584 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12585 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12586 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12587 ResultElements.push_back(APValue(ResElt));
12588 }
12589
12590 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12591 }
12592
12593 case clang::X86::BI__builtin_ia32_vprotbi:
12594 case clang::X86::BI__builtin_ia32_vprotdi:
12595 case clang::X86::BI__builtin_ia32_vprotqi:
12596 case clang::X86::BI__builtin_ia32_vprotwi:
12597 case clang::X86::BI__builtin_ia32_prold128:
12598 case clang::X86::BI__builtin_ia32_prold256:
12599 case clang::X86::BI__builtin_ia32_prold512:
12600 case clang::X86::BI__builtin_ia32_prolq128:
12601 case clang::X86::BI__builtin_ia32_prolq256:
12602 case clang::X86::BI__builtin_ia32_prolq512:
12603 return EvaluateBinOpExpr(
12604 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12605
12606 case clang::X86::BI__builtin_ia32_prord128:
12607 case clang::X86::BI__builtin_ia32_prord256:
12608 case clang::X86::BI__builtin_ia32_prord512:
12609 case clang::X86::BI__builtin_ia32_prorq128:
12610 case clang::X86::BI__builtin_ia32_prorq256:
12611 case clang::X86::BI__builtin_ia32_prorq512:
12612 return EvaluateBinOpExpr(
12613 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12614
12615 case Builtin::BI__builtin_elementwise_max:
12616 case Builtin::BI__builtin_elementwise_min: {
12617 APValue SourceLHS, SourceRHS;
12618 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12619 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12620 return false;
12621
12622 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12623
12624 if (!DestEltTy->isIntegerType())
12625 return false;
12626
12627 unsigned SourceLen = SourceLHS.getVectorLength();
12628 SmallVector<APValue, 4> ResultElements;
12629 ResultElements.reserve(SourceLen);
12630
12631 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12632 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12633 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12634 switch (E->getBuiltinCallee()) {
12635 case Builtin::BI__builtin_elementwise_max:
12636 ResultElements.push_back(
12637 APValue(APSInt(std::max(LHS, RHS),
12638 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12639 break;
12640 case Builtin::BI__builtin_elementwise_min:
12641 ResultElements.push_back(
12642 APValue(APSInt(std::min(LHS, RHS),
12643 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12644 break;
12645 }
12646 }
12647
12648 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12649 }
12650 case X86::BI__builtin_ia32_vpshldd128:
12651 case X86::BI__builtin_ia32_vpshldd256:
12652 case X86::BI__builtin_ia32_vpshldd512:
12653 case X86::BI__builtin_ia32_vpshldq128:
12654 case X86::BI__builtin_ia32_vpshldq256:
12655 case X86::BI__builtin_ia32_vpshldq512:
12656 case X86::BI__builtin_ia32_vpshldw128:
12657 case X86::BI__builtin_ia32_vpshldw256:
12658 case X86::BI__builtin_ia32_vpshldw512: {
12659 APValue SourceHi, SourceLo, SourceAmt;
12660 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12661 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12662 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12663 return false;
12664
12665 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12666 unsigned SourceLen = SourceHi.getVectorLength();
12667 SmallVector<APValue, 32> ResultElements;
12668 ResultElements.reserve(SourceLen);
12669
12670 APInt Amt = SourceAmt.getInt();
12671 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12672 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12673 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12674 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12675 ResultElements.push_back(
12677 }
12678
12679 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12680 }
12681 case X86::BI__builtin_ia32_vpshrdd128:
12682 case X86::BI__builtin_ia32_vpshrdd256:
12683 case X86::BI__builtin_ia32_vpshrdd512:
12684 case X86::BI__builtin_ia32_vpshrdq128:
12685 case X86::BI__builtin_ia32_vpshrdq256:
12686 case X86::BI__builtin_ia32_vpshrdq512:
12687 case X86::BI__builtin_ia32_vpshrdw128:
12688 case X86::BI__builtin_ia32_vpshrdw256:
12689 case X86::BI__builtin_ia32_vpshrdw512: {
12690 // NOTE: Reversed Hi/Lo operands.
12691 APValue SourceHi, SourceLo, SourceAmt;
12692 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12693 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12694 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12695 return false;
12696
12697 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12698 unsigned SourceLen = SourceHi.getVectorLength();
12699 SmallVector<APValue, 32> ResultElements;
12700 ResultElements.reserve(SourceLen);
12701
12702 APInt Amt = SourceAmt.getInt();
12703 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12704 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12705 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12706 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12707 ResultElements.push_back(
12709 }
12710
12711 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12712 }
12713 case X86::BI__builtin_ia32_vpconflictsi_128:
12714 case X86::BI__builtin_ia32_vpconflictsi_256:
12715 case X86::BI__builtin_ia32_vpconflictsi_512:
12716 case X86::BI__builtin_ia32_vpconflictdi_128:
12717 case X86::BI__builtin_ia32_vpconflictdi_256:
12718 case X86::BI__builtin_ia32_vpconflictdi_512: {
12719 APValue Source;
12720
12721 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12722 return false;
12723
12724 unsigned SourceLen = Source.getVectorLength();
12725 SmallVector<APValue, 32> ResultElements;
12726 ResultElements.reserve(SourceLen);
12727
12728 const auto *VecT = E->getType()->castAs<VectorType>();
12729 bool DestUnsigned =
12730 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12731
12732 for (unsigned I = 0; I != SourceLen; ++I) {
12733 const APValue &EltI = Source.getVectorElt(I);
12734
12735 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12736 for (unsigned J = 0; J != I; ++J) {
12737 const APValue &EltJ = Source.getVectorElt(J);
12738 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12739 }
12740 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12741 }
12742 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12743 }
12744 case X86::BI__builtin_ia32_blendpd:
12745 case X86::BI__builtin_ia32_blendpd256:
12746 case X86::BI__builtin_ia32_blendps:
12747 case X86::BI__builtin_ia32_blendps256:
12748 case X86::BI__builtin_ia32_pblendw128:
12749 case X86::BI__builtin_ia32_pblendw256:
12750 case X86::BI__builtin_ia32_pblendd128:
12751 case X86::BI__builtin_ia32_pblendd256: {
12752 APValue SourceF, SourceT, SourceC;
12753 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12754 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12755 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12756 return false;
12757
12758 const APInt &C = SourceC.getInt();
12759 unsigned SourceLen = SourceF.getVectorLength();
12760 SmallVector<APValue, 32> ResultElements;
12761 ResultElements.reserve(SourceLen);
12762 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12763 const APValue &F = SourceF.getVectorElt(EltNum);
12764 const APValue &T = SourceT.getVectorElt(EltNum);
12765 ResultElements.push_back(C[EltNum % 8] ? T : F);
12766 }
12767
12768 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12769 }
12770
12771 case X86::BI__builtin_ia32_psignb128:
12772 case X86::BI__builtin_ia32_psignb256:
12773 case X86::BI__builtin_ia32_psignw128:
12774 case X86::BI__builtin_ia32_psignw256:
12775 case X86::BI__builtin_ia32_psignd128:
12776 case X86::BI__builtin_ia32_psignd256:
12777 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12778 if (BElem.isZero())
12779 return APInt::getZero(AElem.getBitWidth());
12780 if (BElem.isNegative())
12781 return -AElem;
12782 return AElem;
12783 });
12784
12785 case X86::BI__builtin_ia32_blendvpd:
12786 case X86::BI__builtin_ia32_blendvpd256:
12787 case X86::BI__builtin_ia32_blendvps:
12788 case X86::BI__builtin_ia32_blendvps256:
12789 case X86::BI__builtin_ia32_pblendvb128:
12790 case X86::BI__builtin_ia32_pblendvb256: {
12791 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12792 APValue SourceF, SourceT, SourceC;
12793 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12794 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12795 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12796 return false;
12797
12798 unsigned SourceLen = SourceF.getVectorLength();
12799 SmallVector<APValue, 32> ResultElements;
12800 ResultElements.reserve(SourceLen);
12801
12802 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12803 const APValue &F = SourceF.getVectorElt(EltNum);
12804 const APValue &T = SourceT.getVectorElt(EltNum);
12805 const APValue &C = SourceC.getVectorElt(EltNum);
12806 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12807 ResultElements.push_back(M.isNegative() ? T : F);
12808 }
12809
12810 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12811 }
12812 case X86::BI__builtin_ia32_selectb_128:
12813 case X86::BI__builtin_ia32_selectb_256:
12814 case X86::BI__builtin_ia32_selectb_512:
12815 case X86::BI__builtin_ia32_selectw_128:
12816 case X86::BI__builtin_ia32_selectw_256:
12817 case X86::BI__builtin_ia32_selectw_512:
12818 case X86::BI__builtin_ia32_selectd_128:
12819 case X86::BI__builtin_ia32_selectd_256:
12820 case X86::BI__builtin_ia32_selectd_512:
12821 case X86::BI__builtin_ia32_selectq_128:
12822 case X86::BI__builtin_ia32_selectq_256:
12823 case X86::BI__builtin_ia32_selectq_512:
12824 case X86::BI__builtin_ia32_selectph_128:
12825 case X86::BI__builtin_ia32_selectph_256:
12826 case X86::BI__builtin_ia32_selectph_512:
12827 case X86::BI__builtin_ia32_selectpbf_128:
12828 case X86::BI__builtin_ia32_selectpbf_256:
12829 case X86::BI__builtin_ia32_selectpbf_512:
12830 case X86::BI__builtin_ia32_selectps_128:
12831 case X86::BI__builtin_ia32_selectps_256:
12832 case X86::BI__builtin_ia32_selectps_512:
12833 case X86::BI__builtin_ia32_selectpd_128:
12834 case X86::BI__builtin_ia32_selectpd_256:
12835 case X86::BI__builtin_ia32_selectpd_512: {
12836 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12837 APValue SourceMask, SourceLHS, SourceRHS;
12838 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12839 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12840 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12841 return false;
12842
12843 APSInt Mask = SourceMask.getInt();
12844 unsigned SourceLen = SourceLHS.getVectorLength();
12845 SmallVector<APValue, 4> ResultElements;
12846 ResultElements.reserve(SourceLen);
12847
12848 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12849 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12850 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12851 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12852 }
12853
12854 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12855 }
12856 case X86::BI__builtin_ia32_shufps:
12857 case X86::BI__builtin_ia32_shufps256:
12858 case X86::BI__builtin_ia32_shufps512: {
12859 APValue R;
12860 if (!evalShuffleGeneric(
12861 Info, E, R,
12862 [](unsigned DstIdx,
12863 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12864 constexpr unsigned LaneBits = 128u;
12865 unsigned NumElemPerLane = LaneBits / 32;
12866 unsigned NumSelectableElems = NumElemPerLane / 2;
12867 unsigned BitsPerElem = 2;
12868 unsigned IndexMask = (1u << BitsPerElem) - 1;
12869 unsigned MaskBits = 8;
12870 unsigned Lane = DstIdx / NumElemPerLane;
12871 unsigned ElemInLane = DstIdx % NumElemPerLane;
12872 unsigned LaneOffset = Lane * NumElemPerLane;
12873 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12874 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12875 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12876 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
12877 }))
12878 return false;
12879 return Success(R, E);
12880 }
12881 case X86::BI__builtin_ia32_shufpd:
12882 case X86::BI__builtin_ia32_shufpd256:
12883 case X86::BI__builtin_ia32_shufpd512: {
12884 APValue R;
12885 if (!evalShuffleGeneric(
12886 Info, E, R,
12887 [](unsigned DstIdx,
12888 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12889 constexpr unsigned LaneBits = 128u;
12890 unsigned NumElemPerLane = LaneBits / 64;
12891 unsigned NumSelectableElems = NumElemPerLane / 2;
12892 unsigned BitsPerElem = 1;
12893 unsigned IndexMask = (1u << BitsPerElem) - 1;
12894 unsigned MaskBits = 8;
12895 unsigned Lane = DstIdx / NumElemPerLane;
12896 unsigned ElemInLane = DstIdx % NumElemPerLane;
12897 unsigned LaneOffset = Lane * NumElemPerLane;
12898 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
12899 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
12900 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
12901 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
12902 }))
12903 return false;
12904 return Success(R, E);
12905 }
12906 case X86::BI__builtin_ia32_insertps128: {
12907 APValue R;
12908 if (!evalShuffleGeneric(
12909 Info, E, R,
12910 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12911 // Bits [3:0]: zero mask - if bit is set, zero this element
12912 if ((Mask & (1 << DstIdx)) != 0) {
12913 return {0, -1};
12914 }
12915 // Bits [7:6]: select element from source vector Y (0-3)
12916 // Bits [5:4]: select destination position (0-3)
12917 unsigned SrcElem = (Mask >> 6) & 0x3;
12918 unsigned DstElem = (Mask >> 4) & 0x3;
12919 if (DstIdx == DstElem) {
12920 // Insert element from source vector (B) at this position
12921 return {1, static_cast<int>(SrcElem)};
12922 } else {
12923 // Copy from destination vector (A)
12924 return {0, static_cast<int>(DstIdx)};
12925 }
12926 }))
12927 return false;
12928 return Success(R, E);
12929 }
12930 case X86::BI__builtin_ia32_pshufb128:
12931 case X86::BI__builtin_ia32_pshufb256:
12932 case X86::BI__builtin_ia32_pshufb512: {
12933 APValue R;
12934 if (!evalShuffleGeneric(
12935 Info, E, R,
12936 [](unsigned DstIdx,
12937 unsigned ShuffleMask) -> std::pair<unsigned, int> {
12938 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
12939 if (Ctlb & 0x80)
12940 return std::make_pair(0, -1);
12941
12942 unsigned LaneBase = (DstIdx / 16) * 16;
12943 unsigned SrcOffset = Ctlb & 0x0F;
12944 unsigned SrcIdx = LaneBase + SrcOffset;
12945 return std::make_pair(0, static_cast<int>(SrcIdx));
12946 }))
12947 return false;
12948 return Success(R, E);
12949 }
12950
12951 case X86::BI__builtin_ia32_pshuflw:
12952 case X86::BI__builtin_ia32_pshuflw256:
12953 case X86::BI__builtin_ia32_pshuflw512: {
12954 APValue R;
12955 if (!evalShuffleGeneric(
12956 Info, E, R,
12957 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12958 constexpr unsigned LaneBits = 128u;
12959 constexpr unsigned ElemBits = 16u;
12960 constexpr unsigned LaneElts = LaneBits / ElemBits;
12961 constexpr unsigned HalfSize = 4;
12962 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
12963 unsigned LaneIdx = DstIdx % LaneElts;
12964 if (LaneIdx < HalfSize) {
12965 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
12966 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
12967 }
12968 return std::make_pair(0, static_cast<int>(DstIdx));
12969 }))
12970 return false;
12971 return Success(R, E);
12972 }
12973
12974 case X86::BI__builtin_ia32_pshufhw:
12975 case X86::BI__builtin_ia32_pshufhw256:
12976 case X86::BI__builtin_ia32_pshufhw512: {
12977 APValue R;
12978 if (!evalShuffleGeneric(
12979 Info, E, R,
12980 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
12981 constexpr unsigned LaneBits = 128u;
12982 constexpr unsigned ElemBits = 16u;
12983 constexpr unsigned LaneElts = LaneBits / ElemBits;
12984 constexpr unsigned HalfSize = 4;
12985 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
12986 unsigned LaneIdx = DstIdx % LaneElts;
12987 if (LaneIdx >= HalfSize) {
12988 unsigned Rel = LaneIdx - HalfSize;
12989 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
12990 return std::make_pair(
12991 0, static_cast<int>(LaneBase + HalfSize + Sel));
12992 }
12993 return std::make_pair(0, static_cast<int>(DstIdx));
12994 }))
12995 return false;
12996 return Success(R, E);
12997 }
12998
12999 case X86::BI__builtin_ia32_pshufd:
13000 case X86::BI__builtin_ia32_pshufd256:
13001 case X86::BI__builtin_ia32_pshufd512: {
13002 APValue R;
13003 if (!evalShuffleGeneric(
13004 Info, E, R,
13005 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13006 constexpr unsigned LaneBits = 128u;
13007 constexpr unsigned ElemBits = 32u;
13008 constexpr unsigned LaneElts = LaneBits / ElemBits;
13009 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13010 unsigned LaneIdx = DstIdx % LaneElts;
13011 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13012 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13013 }))
13014 return false;
13015 return Success(R, E);
13016 }
13017
13018 case X86::BI__builtin_ia32_phminposuw128: {
13019 APValue Source;
13020 if (!Evaluate(Source, Info, E->getArg(0)))
13021 return false;
13022 unsigned SourceLen = Source.getVectorLength();
13023 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13024 QualType ElemQT = VT->getElementType();
13025 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13026
13027 APInt MinIndex(ElemBitWidth, 0);
13028 APInt MinVal = Source.getVectorElt(0).getInt();
13029 for (unsigned I = 1; I != SourceLen; ++I) {
13030 APInt Val = Source.getVectorElt(I).getInt();
13031 if (MinVal.ugt(Val)) {
13032 MinVal = Val;
13033 MinIndex = I;
13034 }
13035 }
13036
13037 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13038 ->castAs<VectorType>()
13039 ->getElementType()
13040 ->isUnsignedIntegerOrEnumerationType();
13041
13043 Result.reserve(SourceLen);
13044 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13045 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13046 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13047 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13048 }
13049 return Success(APValue(Result.data(), Result.size()), E);
13050 }
13051
13052 case X86::BI__builtin_ia32_pternlogd128_mask:
13053 case X86::BI__builtin_ia32_pternlogd256_mask:
13054 case X86::BI__builtin_ia32_pternlogd512_mask:
13055 case X86::BI__builtin_ia32_pternlogq128_mask:
13056 case X86::BI__builtin_ia32_pternlogq256_mask:
13057 case X86::BI__builtin_ia32_pternlogq512_mask: {
13058 APValue AValue, BValue, CValue, ImmValue, UValue;
13059 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13060 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13061 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13062 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13063 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13064 return false;
13065
13066 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13067 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13068 APInt Imm = ImmValue.getInt();
13069 APInt U = UValue.getInt();
13070 unsigned ResultLen = AValue.getVectorLength();
13071 SmallVector<APValue, 16> ResultElements;
13072 ResultElements.reserve(ResultLen);
13073
13074 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13075 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13076 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13077 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13078
13079 if (U[EltNum]) {
13080 unsigned BitWidth = ALane.getBitWidth();
13081 APInt ResLane(BitWidth, 0);
13082
13083 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13084 unsigned ABit = ALane[Bit];
13085 unsigned BBit = BLane[Bit];
13086 unsigned CBit = CLane[Bit];
13087
13088 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13089 ResLane.setBitVal(Bit, Imm[Idx]);
13090 }
13091 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13092 } else {
13093 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13094 }
13095 }
13096 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13097 }
13098 case X86::BI__builtin_ia32_pternlogd128_maskz:
13099 case X86::BI__builtin_ia32_pternlogd256_maskz:
13100 case X86::BI__builtin_ia32_pternlogd512_maskz:
13101 case X86::BI__builtin_ia32_pternlogq128_maskz:
13102 case X86::BI__builtin_ia32_pternlogq256_maskz:
13103 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13104 APValue AValue, BValue, CValue, ImmValue, UValue;
13105 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13106 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13107 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13108 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13109 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13110 return false;
13111
13112 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13113 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13114 APInt Imm = ImmValue.getInt();
13115 APInt U = UValue.getInt();
13116 unsigned ResultLen = AValue.getVectorLength();
13117 SmallVector<APValue, 16> ResultElements;
13118 ResultElements.reserve(ResultLen);
13119
13120 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13121 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13122 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13123 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13124
13125 unsigned BitWidth = ALane.getBitWidth();
13126 APInt ResLane(BitWidth, 0);
13127
13128 if (U[EltNum]) {
13129 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13130 unsigned ABit = ALane[Bit];
13131 unsigned BBit = BLane[Bit];
13132 unsigned CBit = CLane[Bit];
13133
13134 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13135 ResLane.setBitVal(Bit, Imm[Idx]);
13136 }
13137 }
13138 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13139 }
13140 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13141 }
13142
13143 case Builtin::BI__builtin_elementwise_clzg:
13144 case Builtin::BI__builtin_elementwise_ctzg: {
13145 APValue SourceLHS;
13146 std::optional<APValue> Fallback;
13147 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13148 return false;
13149 if (E->getNumArgs() > 1) {
13150 APValue FallbackTmp;
13151 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13152 return false;
13153 Fallback = FallbackTmp;
13154 }
13155
13156 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13157 unsigned SourceLen = SourceLHS.getVectorLength();
13158 SmallVector<APValue, 4> ResultElements;
13159 ResultElements.reserve(SourceLen);
13160
13161 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13162 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13163 if (!LHS) {
13164 // Without a fallback, a zero element is undefined
13165 if (!Fallback) {
13166 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13167 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13168 Builtin::BI__builtin_elementwise_ctzg);
13169 return false;
13170 }
13171 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13172 continue;
13173 }
13174 switch (E->getBuiltinCallee()) {
13175 case Builtin::BI__builtin_elementwise_clzg:
13176 ResultElements.push_back(APValue(
13177 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13178 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13179 break;
13180 case Builtin::BI__builtin_elementwise_ctzg:
13181 ResultElements.push_back(APValue(
13182 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13183 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13184 break;
13185 }
13186 }
13187
13188 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13189 }
13190
13191 case Builtin::BI__builtin_elementwise_fma: {
13192 APValue SourceX, SourceY, SourceZ;
13193 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13194 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13195 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13196 return false;
13197
13198 unsigned SourceLen = SourceX.getVectorLength();
13199 SmallVector<APValue> ResultElements;
13200 ResultElements.reserve(SourceLen);
13201 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13202 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13203 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13204 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13205 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13206 APFloat Result(X);
13207 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13208 ResultElements.push_back(APValue(Result));
13209 }
13210 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13211 }
13212
13213 case clang::X86::BI__builtin_ia32_phaddw128:
13214 case clang::X86::BI__builtin_ia32_phaddw256:
13215 case clang::X86::BI__builtin_ia32_phaddd128:
13216 case clang::X86::BI__builtin_ia32_phaddd256:
13217 case clang::X86::BI__builtin_ia32_phaddsw128:
13218 case clang::X86::BI__builtin_ia32_phaddsw256:
13219
13220 case clang::X86::BI__builtin_ia32_phsubw128:
13221 case clang::X86::BI__builtin_ia32_phsubw256:
13222 case clang::X86::BI__builtin_ia32_phsubd128:
13223 case clang::X86::BI__builtin_ia32_phsubd256:
13224 case clang::X86::BI__builtin_ia32_phsubsw128:
13225 case clang::X86::BI__builtin_ia32_phsubsw256: {
13226 APValue SourceLHS, SourceRHS;
13227 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13228 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13229 return false;
13230 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13231 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13232
13233 unsigned NumElts = SourceLHS.getVectorLength();
13234 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13235 unsigned EltsPerLane = 128 / EltBits;
13236 SmallVector<APValue, 4> ResultElements;
13237 ResultElements.reserve(NumElts);
13238
13239 for (unsigned LaneStart = 0; LaneStart != NumElts;
13240 LaneStart += EltsPerLane) {
13241 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13242 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13243 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13244 switch (E->getBuiltinCallee()) {
13245 case clang::X86::BI__builtin_ia32_phaddw128:
13246 case clang::X86::BI__builtin_ia32_phaddw256:
13247 case clang::X86::BI__builtin_ia32_phaddd128:
13248 case clang::X86::BI__builtin_ia32_phaddd256: {
13249 APSInt Res(LHSA + LHSB, DestUnsigned);
13250 ResultElements.push_back(APValue(Res));
13251 break;
13252 }
13253 case clang::X86::BI__builtin_ia32_phaddsw128:
13254 case clang::X86::BI__builtin_ia32_phaddsw256: {
13255 APSInt Res(LHSA.sadd_sat(LHSB));
13256 ResultElements.push_back(APValue(Res));
13257 break;
13258 }
13259 case clang::X86::BI__builtin_ia32_phsubw128:
13260 case clang::X86::BI__builtin_ia32_phsubw256:
13261 case clang::X86::BI__builtin_ia32_phsubd128:
13262 case clang::X86::BI__builtin_ia32_phsubd256: {
13263 APSInt Res(LHSA - LHSB, DestUnsigned);
13264 ResultElements.push_back(APValue(Res));
13265 break;
13266 }
13267 case clang::X86::BI__builtin_ia32_phsubsw128:
13268 case clang::X86::BI__builtin_ia32_phsubsw256: {
13269 APSInt Res(LHSA.ssub_sat(LHSB));
13270 ResultElements.push_back(APValue(Res));
13271 break;
13272 }
13273 }
13274 }
13275 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13276 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13277 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13278 switch (E->getBuiltinCallee()) {
13279 case clang::X86::BI__builtin_ia32_phaddw128:
13280 case clang::X86::BI__builtin_ia32_phaddw256:
13281 case clang::X86::BI__builtin_ia32_phaddd128:
13282 case clang::X86::BI__builtin_ia32_phaddd256: {
13283 APSInt Res(RHSA + RHSB, DestUnsigned);
13284 ResultElements.push_back(APValue(Res));
13285 break;
13286 }
13287 case clang::X86::BI__builtin_ia32_phaddsw128:
13288 case clang::X86::BI__builtin_ia32_phaddsw256: {
13289 APSInt Res(RHSA.sadd_sat(RHSB));
13290 ResultElements.push_back(APValue(Res));
13291 break;
13292 }
13293 case clang::X86::BI__builtin_ia32_phsubw128:
13294 case clang::X86::BI__builtin_ia32_phsubw256:
13295 case clang::X86::BI__builtin_ia32_phsubd128:
13296 case clang::X86::BI__builtin_ia32_phsubd256: {
13297 APSInt Res(RHSA - RHSB, DestUnsigned);
13298 ResultElements.push_back(APValue(Res));
13299 break;
13300 }
13301 case clang::X86::BI__builtin_ia32_phsubsw128:
13302 case clang::X86::BI__builtin_ia32_phsubsw256: {
13303 APSInt Res(RHSA.ssub_sat(RHSB));
13304 ResultElements.push_back(APValue(Res));
13305 break;
13306 }
13307 }
13308 }
13309 }
13310 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13311 }
13312 case clang::X86::BI__builtin_ia32_haddpd:
13313 case clang::X86::BI__builtin_ia32_haddps:
13314 case clang::X86::BI__builtin_ia32_haddps256:
13315 case clang::X86::BI__builtin_ia32_haddpd256:
13316 case clang::X86::BI__builtin_ia32_hsubpd:
13317 case clang::X86::BI__builtin_ia32_hsubps:
13318 case clang::X86::BI__builtin_ia32_hsubps256:
13319 case clang::X86::BI__builtin_ia32_hsubpd256: {
13320 APValue SourceLHS, SourceRHS;
13321 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13322 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13323 return false;
13324 unsigned NumElts = SourceLHS.getVectorLength();
13325 SmallVector<APValue, 4> ResultElements;
13326 ResultElements.reserve(NumElts);
13327 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13328 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13329 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13330 unsigned NumLanes = NumElts * EltBits / 128;
13331 unsigned NumElemsPerLane = NumElts / NumLanes;
13332 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13333
13334 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13335 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13336 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13337 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13338 switch (E->getBuiltinCallee()) {
13339 case clang::X86::BI__builtin_ia32_haddpd:
13340 case clang::X86::BI__builtin_ia32_haddps:
13341 case clang::X86::BI__builtin_ia32_haddps256:
13342 case clang::X86::BI__builtin_ia32_haddpd256:
13343 LHSA.add(LHSB, RM);
13344 break;
13345 case clang::X86::BI__builtin_ia32_hsubpd:
13346 case clang::X86::BI__builtin_ia32_hsubps:
13347 case clang::X86::BI__builtin_ia32_hsubps256:
13348 case clang::X86::BI__builtin_ia32_hsubpd256:
13349 LHSA.subtract(LHSB, RM);
13350 break;
13351 }
13352 ResultElements.push_back(APValue(LHSA));
13353 }
13354 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13355 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13356 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13357 switch (E->getBuiltinCallee()) {
13358 case clang::X86::BI__builtin_ia32_haddpd:
13359 case clang::X86::BI__builtin_ia32_haddps:
13360 case clang::X86::BI__builtin_ia32_haddps256:
13361 case clang::X86::BI__builtin_ia32_haddpd256:
13362 RHSA.add(RHSB, RM);
13363 break;
13364 case clang::X86::BI__builtin_ia32_hsubpd:
13365 case clang::X86::BI__builtin_ia32_hsubps:
13366 case clang::X86::BI__builtin_ia32_hsubps256:
13367 case clang::X86::BI__builtin_ia32_hsubpd256:
13368 RHSA.subtract(RHSB, RM);
13369 break;
13370 }
13371 ResultElements.push_back(APValue(RHSA));
13372 }
13373 }
13374 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13375 }
13376 case clang::X86::BI__builtin_ia32_addsubpd:
13377 case clang::X86::BI__builtin_ia32_addsubps:
13378 case clang::X86::BI__builtin_ia32_addsubpd256:
13379 case clang::X86::BI__builtin_ia32_addsubps256: {
13380 // Addsub: alternates between subtraction and addition
13381 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13382 APValue SourceLHS, SourceRHS;
13383 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13384 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13385 return false;
13386 unsigned NumElems = SourceLHS.getVectorLength();
13387 SmallVector<APValue, 8> ResultElements;
13388 ResultElements.reserve(NumElems);
13389 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13390
13391 for (unsigned I = 0; I != NumElems; ++I) {
13392 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13393 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13394 if (I % 2 == 0) {
13395 // Even indices: subtract
13396 LHS.subtract(RHS, RM);
13397 } else {
13398 // Odd indices: add
13399 LHS.add(RHS, RM);
13400 }
13401 ResultElements.push_back(APValue(LHS));
13402 }
13403 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13404 }
13405 case Builtin::BI__builtin_elementwise_fshl:
13406 case Builtin::BI__builtin_elementwise_fshr: {
13407 APValue SourceHi, SourceLo, SourceShift;
13408 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13409 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13410 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13411 return false;
13412
13413 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13414 if (!DestEltTy->isIntegerType())
13415 return false;
13416
13417 unsigned SourceLen = SourceHi.getVectorLength();
13418 SmallVector<APValue> ResultElements;
13419 ResultElements.reserve(SourceLen);
13420 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13421 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
13422 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
13423 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
13424 switch (E->getBuiltinCallee()) {
13425 case Builtin::BI__builtin_elementwise_fshl:
13426 ResultElements.push_back(APValue(
13427 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
13428 break;
13429 case Builtin::BI__builtin_elementwise_fshr:
13430 ResultElements.push_back(APValue(
13431 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
13432 break;
13433 }
13434 }
13435
13436 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13437 }
13438
13439 case X86::BI__builtin_ia32_insertf32x4_256:
13440 case X86::BI__builtin_ia32_inserti32x4_256:
13441 case X86::BI__builtin_ia32_insertf64x2_256:
13442 case X86::BI__builtin_ia32_inserti64x2_256:
13443 case X86::BI__builtin_ia32_insertf32x4:
13444 case X86::BI__builtin_ia32_inserti32x4:
13445 case X86::BI__builtin_ia32_insertf64x2_512:
13446 case X86::BI__builtin_ia32_inserti64x2_512:
13447 case X86::BI__builtin_ia32_insertf32x8:
13448 case X86::BI__builtin_ia32_inserti32x8:
13449 case X86::BI__builtin_ia32_insertf64x4:
13450 case X86::BI__builtin_ia32_inserti64x4:
13451 case X86::BI__builtin_ia32_vinsertf128_ps256:
13452 case X86::BI__builtin_ia32_vinsertf128_pd256:
13453 case X86::BI__builtin_ia32_vinsertf128_si256:
13454 case X86::BI__builtin_ia32_insert128i256: {
13455 APValue SourceDst, SourceSub;
13456 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
13457 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
13458 return false;
13459
13460 APSInt Imm;
13461 if (!EvaluateInteger(E->getArg(2), Imm, Info))
13462 return false;
13463
13464 assert(SourceDst.isVector() && SourceSub.isVector());
13465 unsigned DstLen = SourceDst.getVectorLength();
13466 unsigned SubLen = SourceSub.getVectorLength();
13467 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
13468 unsigned NumLanes = DstLen / SubLen;
13469 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
13470
13471 SmallVector<APValue, 16> ResultElements;
13472 ResultElements.reserve(DstLen);
13473
13474 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
13475 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
13476 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
13477 else
13478 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
13479 }
13480
13481 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13482 }
13483
13484 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
13485 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
13486 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
13487 case clang::X86::BI__builtin_ia32_vec_set_v4si:
13488 case clang::X86::BI__builtin_ia32_vec_set_v2di:
13489 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
13490 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
13491 case clang::X86::BI__builtin_ia32_vec_set_v8si:
13492 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
13493 APValue VecVal;
13494 APSInt Scalar, IndexAPS;
13495 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
13496 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
13497 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
13498 return false;
13499
13500 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
13501 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
13502 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
13503 Scalar.setIsUnsigned(ElemUnsigned);
13504 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
13505 APValue ElemAV(ElemAPS);
13506
13507 unsigned NumElems = VecVal.getVectorLength();
13508 unsigned Index =
13509 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
13510
13512 Elems.reserve(NumElems);
13513 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
13514 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
13515
13516 return Success(APValue(Elems.data(), NumElems), E);
13517 }
13518
13519 case X86::BI__builtin_ia32_pslldqi128_byteshift:
13520 case X86::BI__builtin_ia32_pslldqi256_byteshift:
13521 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
13522 APValue R;
13523 if (!evalShuffleGeneric(
13524 Info, E, R,
13525 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
13526 unsigned LaneBase = (DstIdx / 16) * 16;
13527 unsigned LaneIdx = DstIdx % 16;
13528 if (LaneIdx < Shift)
13529 return std::make_pair(0, -1);
13530
13531 return std::make_pair(
13532 0, static_cast<int>(LaneBase + LaneIdx - Shift));
13533 }))
13534 return false;
13535 return Success(R, E);
13536 }
13537
13538 case X86::BI__builtin_ia32_psrldqi128_byteshift:
13539 case X86::BI__builtin_ia32_psrldqi256_byteshift:
13540 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
13541 APValue R;
13542 if (!evalShuffleGeneric(
13543 Info, E, R,
13544 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
13545 unsigned LaneBase = (DstIdx / 16) * 16;
13546 unsigned LaneIdx = DstIdx % 16;
13547 if (LaneIdx + Shift < 16)
13548 return std::make_pair(
13549 0, static_cast<int>(LaneBase + LaneIdx + Shift));
13550
13551 return std::make_pair(0, -1);
13552 }))
13553 return false;
13554 return Success(R, E);
13555 }
13556
13557 case X86::BI__builtin_ia32_palignr128:
13558 case X86::BI__builtin_ia32_palignr256:
13559 case X86::BI__builtin_ia32_palignr512: {
13560 APValue R;
13561 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
13562 // Default to -1 → zero-fill this destination element
13563 unsigned VecIdx = 1;
13564 int ElemIdx = -1;
13565
13566 int Lane = DstIdx / 16;
13567 int Offset = DstIdx % 16;
13568
13569 // Elements come from VecB first, then VecA after the shift boundary
13570 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
13571 if (ShiftedIdx < 16) { // from VecB
13572 ElemIdx = ShiftedIdx + (Lane * 16);
13573 } else if (ShiftedIdx < 32) { // from VecA
13574 VecIdx = 0;
13575 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
13576 }
13577
13578 return std::pair<unsigned, int>{VecIdx, ElemIdx};
13579 }))
13580 return false;
13581 return Success(R, E);
13582 }
13583 case X86::BI__builtin_ia32_permvarsi256:
13584 case X86::BI__builtin_ia32_permvarsf256:
13585 case X86::BI__builtin_ia32_permvardf512:
13586 case X86::BI__builtin_ia32_permvardi512:
13587 case X86::BI__builtin_ia32_permvarhi128: {
13588 APValue R;
13589 if (!evalShuffleGeneric(Info, E, R,
13590 [](unsigned DstIdx, unsigned ShuffleMask) {
13591 int Offset = ShuffleMask & 0x7;
13592 return std::pair<unsigned, int>{0, Offset};
13593 }))
13594 return false;
13595 return Success(R, E);
13596 }
13597 case X86::BI__builtin_ia32_permvarqi128:
13598 case X86::BI__builtin_ia32_permvarhi256:
13599 case X86::BI__builtin_ia32_permvarsi512:
13600 case X86::BI__builtin_ia32_permvarsf512: {
13601 APValue R;
13602 if (!evalShuffleGeneric(Info, E, R,
13603 [](unsigned DstIdx, unsigned ShuffleMask) {
13604 int Offset = ShuffleMask & 0xF;
13605 return std::pair<unsigned, int>{0, Offset};
13606 }))
13607 return false;
13608 return Success(R, E);
13609 }
13610 case X86::BI__builtin_ia32_permvardi256:
13611 case X86::BI__builtin_ia32_permvardf256: {
13612 APValue R;
13613 if (!evalShuffleGeneric(Info, E, R,
13614 [](unsigned DstIdx, unsigned ShuffleMask) {
13615 int Offset = ShuffleMask & 0x3;
13616 return std::pair<unsigned, int>{0, Offset};
13617 }))
13618 return false;
13619 return Success(R, E);
13620 }
13621 case X86::BI__builtin_ia32_permvarqi256:
13622 case X86::BI__builtin_ia32_permvarhi512: {
13623 APValue R;
13624 if (!evalShuffleGeneric(Info, E, R,
13625 [](unsigned DstIdx, unsigned ShuffleMask) {
13626 int Offset = ShuffleMask & 0x1F;
13627 return std::pair<unsigned, int>{0, Offset};
13628 }))
13629 return false;
13630 return Success(R, E);
13631 }
13632 case X86::BI__builtin_ia32_permvarqi512: {
13633 APValue R;
13634 if (!evalShuffleGeneric(Info, E, R,
13635 [](unsigned DstIdx, unsigned ShuffleMask) {
13636 int Offset = ShuffleMask & 0x3F;
13637 return std::pair<unsigned, int>{0, Offset};
13638 }))
13639 return false;
13640 return Success(R, E);
13641 }
13642 case X86::BI__builtin_ia32_vpermi2varq128:
13643 case X86::BI__builtin_ia32_vpermi2varpd128: {
13644 APValue R;
13645 if (!evalShuffleGeneric(Info, E, R,
13646 [](unsigned DstIdx, unsigned ShuffleMask) {
13647 int Offset = ShuffleMask & 0x1;
13648 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
13649 return std::pair<unsigned, int>{SrcIdx, Offset};
13650 }))
13651 return false;
13652 return Success(R, E);
13653 }
13654 case X86::BI__builtin_ia32_vpermi2vard128:
13655 case X86::BI__builtin_ia32_vpermi2varps128:
13656 case X86::BI__builtin_ia32_vpermi2varq256:
13657 case X86::BI__builtin_ia32_vpermi2varpd256: {
13658 APValue R;
13659 if (!evalShuffleGeneric(Info, E, R,
13660 [](unsigned DstIdx, unsigned ShuffleMask) {
13661 int Offset = ShuffleMask & 0x3;
13662 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
13663 return std::pair<unsigned, int>{SrcIdx, Offset};
13664 }))
13665 return false;
13666 return Success(R, E);
13667 }
13668 case X86::BI__builtin_ia32_vpermi2varhi128:
13669 case X86::BI__builtin_ia32_vpermi2vard256:
13670 case X86::BI__builtin_ia32_vpermi2varps256:
13671 case X86::BI__builtin_ia32_vpermi2varq512:
13672 case X86::BI__builtin_ia32_vpermi2varpd512: {
13673 APValue R;
13674 if (!evalShuffleGeneric(Info, E, R,
13675 [](unsigned DstIdx, unsigned ShuffleMask) {
13676 int Offset = ShuffleMask & 0x7;
13677 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
13678 return std::pair<unsigned, int>{SrcIdx, Offset};
13679 }))
13680 return false;
13681 return Success(R, E);
13682 }
13683 case X86::BI__builtin_ia32_vpermi2varqi128:
13684 case X86::BI__builtin_ia32_vpermi2varhi256:
13685 case X86::BI__builtin_ia32_vpermi2vard512:
13686 case X86::BI__builtin_ia32_vpermi2varps512: {
13687 APValue R;
13688 if (!evalShuffleGeneric(Info, E, R,
13689 [](unsigned DstIdx, unsigned ShuffleMask) {
13690 int Offset = ShuffleMask & 0xF;
13691 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
13692 return std::pair<unsigned, int>{SrcIdx, Offset};
13693 }))
13694 return false;
13695 return Success(R, E);
13696 }
13697 case X86::BI__builtin_ia32_vpermi2varqi256:
13698 case X86::BI__builtin_ia32_vpermi2varhi512: {
13699 APValue R;
13700 if (!evalShuffleGeneric(Info, E, R,
13701 [](unsigned DstIdx, unsigned ShuffleMask) {
13702 int Offset = ShuffleMask & 0x1F;
13703 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
13704 return std::pair<unsigned, int>{SrcIdx, Offset};
13705 }))
13706 return false;
13707 return Success(R, E);
13708 }
13709 case X86::BI__builtin_ia32_vpermi2varqi512: {
13710 APValue R;
13711 if (!evalShuffleGeneric(Info, E, R,
13712 [](unsigned DstIdx, unsigned ShuffleMask) {
13713 int Offset = ShuffleMask & 0x3F;
13714 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
13715 return std::pair<unsigned, int>{SrcIdx, Offset};
13716 }))
13717 return false;
13718 return Success(R, E);
13719 }
13720 }
13721}
13722
13723bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
13724 APValue Source;
13725 QualType SourceVecType = E->getSrcExpr()->getType();
13726 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
13727 return false;
13728
13729 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
13730 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
13731
13732 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13733
13734 auto SourceLen = Source.getVectorLength();
13735 SmallVector<APValue, 4> ResultElements;
13736 ResultElements.reserve(SourceLen);
13737 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13738 APValue Elt;
13739 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
13740 Source.getVectorElt(EltNum), Elt))
13741 return false;
13742 ResultElements.push_back(std::move(Elt));
13743 }
13744
13745 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13746}
13747
13748static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
13749 QualType ElemType, APValue const &VecVal1,
13750 APValue const &VecVal2, unsigned EltNum,
13751 APValue &Result) {
13752 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
13753 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
13754
13755 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
13756 int64_t index = IndexVal.getExtValue();
13757 // The spec says that -1 should be treated as undef for optimizations,
13758 // but in constexpr we'd have to produce an APValue::Indeterminate,
13759 // which is prohibited from being a top-level constant value. Emit a
13760 // diagnostic instead.
13761 if (index == -1) {
13762 Info.FFDiag(
13763 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
13764 << EltNum;
13765 return false;
13766 }
13767
13768 if (index < 0 ||
13769 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
13770 llvm_unreachable("Out of bounds shuffle index");
13771
13772 if (index >= TotalElementsInInputVector1)
13773 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
13774 else
13775 Result = VecVal1.getVectorElt(index);
13776 return true;
13777}
13778
13779bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
13780 // FIXME: Unary shuffle with mask not currently supported.
13781 if (E->getNumSubExprs() == 2)
13782 return Error(E);
13783 APValue VecVal1;
13784 const Expr *Vec1 = E->getExpr(0);
13785 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
13786 return false;
13787 APValue VecVal2;
13788 const Expr *Vec2 = E->getExpr(1);
13789 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
13790 return false;
13791
13792 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
13793 QualType DestElTy = DestVecTy->getElementType();
13794
13795 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
13796
13797 SmallVector<APValue, 4> ResultElements;
13798 ResultElements.reserve(TotalElementsInOutputVector);
13799 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
13800 APValue Elt;
13801 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
13802 return false;
13803 ResultElements.push_back(std::move(Elt));
13804 }
13805
13806 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13807}
13808
13809//===----------------------------------------------------------------------===//
13810// Array Evaluation
13811//===----------------------------------------------------------------------===//
13812
13813namespace {
13814 class ArrayExprEvaluator
13815 : public ExprEvaluatorBase<ArrayExprEvaluator> {
13816 const LValue &This;
13817 APValue &Result;
13818 public:
13819
13820 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
13821 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13822
13823 bool Success(const APValue &V, const Expr *E) {
13824 assert(V.isArray() && "expected array");
13825 Result = V;
13826 return true;
13827 }
13828
13829 bool ZeroInitialization(const Expr *E) {
13830 const ConstantArrayType *CAT =
13831 Info.Ctx.getAsConstantArrayType(E->getType());
13832 if (!CAT) {
13833 if (E->getType()->isIncompleteArrayType()) {
13834 // We can be asked to zero-initialize a flexible array member; this
13835 // is represented as an ImplicitValueInitExpr of incomplete array
13836 // type. In this case, the array has zero elements.
13837 Result = APValue(APValue::UninitArray(), 0, 0);
13838 return true;
13839 }
13840 // FIXME: We could handle VLAs here.
13841 return Error(E);
13842 }
13843
13844 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
13845 if (!Result.hasArrayFiller())
13846 return true;
13847
13848 // Zero-initialize all elements.
13849 LValue Subobject = This;
13850 Subobject.addArray(Info, E, CAT);
13851 ImplicitValueInitExpr VIE(CAT->getElementType());
13852 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
13853 }
13854
13855 bool VisitCallExpr(const CallExpr *E) {
13856 return handleCallExpr(E, Result, &This);
13857 }
13858 bool VisitCastExpr(const CastExpr *E);
13859 bool VisitInitListExpr(const InitListExpr *E,
13860 QualType AllocType = QualType());
13861 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
13862 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
13863 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
13864 const LValue &Subobject,
13865 APValue *Value, QualType Type);
13866 bool VisitStringLiteral(const StringLiteral *E,
13867 QualType AllocType = QualType()) {
13868 expandStringLiteral(Info, E, Result, AllocType);
13869 return true;
13870 }
13871 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
13872 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
13873 ArrayRef<Expr *> Args,
13874 const Expr *ArrayFiller,
13875 QualType AllocType = QualType());
13876 };
13877} // end anonymous namespace
13878
13879static bool EvaluateArray(const Expr *E, const LValue &This,
13880 APValue &Result, EvalInfo &Info) {
13881 assert(!E->isValueDependent());
13882 assert(E->isPRValue() && E->getType()->isArrayType() &&
13883 "not an array prvalue");
13884 return ArrayExprEvaluator(Info, This, Result).Visit(E);
13885}
13886
13887static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
13888 APValue &Result, const InitListExpr *ILE,
13889 QualType AllocType) {
13890 assert(!ILE->isValueDependent());
13891 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
13892 "not an array prvalue");
13893 return ArrayExprEvaluator(Info, This, Result)
13894 .VisitInitListExpr(ILE, AllocType);
13895}
13896
13897static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
13898 APValue &Result,
13899 const CXXConstructExpr *CCE,
13900 QualType AllocType) {
13901 assert(!CCE->isValueDependent());
13902 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
13903 "not an array prvalue");
13904 return ArrayExprEvaluator(Info, This, Result)
13905 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
13906}
13907
13908// Return true iff the given array filler may depend on the element index.
13909static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
13910 // For now, just allow non-class value-initialization and initialization
13911 // lists comprised of them.
13912 if (isa<ImplicitValueInitExpr>(FillerExpr))
13913 return false;
13914 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
13915 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
13916 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
13917 return true;
13918 }
13919
13920 if (ILE->hasArrayFiller() &&
13921 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
13922 return true;
13923
13924 return false;
13925 }
13926 return true;
13927}
13928
13929bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
13930 const Expr *SE = E->getSubExpr();
13931
13932 switch (E->getCastKind()) {
13933 default:
13934 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13935 case CK_HLSLAggregateSplatCast: {
13936 APValue Val;
13937 QualType ValTy;
13938
13939 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
13940 return false;
13941
13942 unsigned NEls = elementwiseSize(Info, E->getType());
13943
13944 SmallVector<APValue> SplatEls(NEls, Val);
13945 SmallVector<QualType> SplatType(NEls, ValTy);
13946
13947 // cast the elements
13948 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13949 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
13950 SplatType))
13951 return false;
13952
13953 return true;
13954 }
13955 case CK_HLSLElementwiseCast: {
13956 SmallVector<APValue> SrcEls;
13957 SmallVector<QualType> SrcTypes;
13958
13959 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
13960 return false;
13961
13962 // cast the elements
13963 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
13964 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
13965 SrcTypes))
13966 return false;
13967 return true;
13968 }
13969 }
13970}
13971
13972bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
13973 QualType AllocType) {
13974 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
13975 AllocType.isNull() ? E->getType() : AllocType);
13976 if (!CAT)
13977 return Error(E);
13978
13979 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
13980 // an appropriately-typed string literal enclosed in braces.
13981 if (E->isStringLiteralInit()) {
13982 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
13983 // FIXME: Support ObjCEncodeExpr here once we support it in
13984 // ArrayExprEvaluator generally.
13985 if (!SL)
13986 return Error(E);
13987 return VisitStringLiteral(SL, AllocType);
13988 }
13989 // Any other transparent list init will need proper handling of the
13990 // AllocType; we can't just recurse to the inner initializer.
13991 assert(!E->isTransparent() &&
13992 "transparent array list initialization is not string literal init?");
13993
13994 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
13995 AllocType);
13996}
13997
13998bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
13999 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
14000 QualType AllocType) {
14001 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14002 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
14003
14004 bool Success = true;
14005
14006 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
14007 "zero-initialized array shouldn't have any initialized elts");
14008 APValue Filler;
14009 if (Result.isArray() && Result.hasArrayFiller())
14010 Filler = Result.getArrayFiller();
14011
14012 unsigned NumEltsToInit = Args.size();
14013 unsigned NumElts = CAT->getZExtSize();
14014
14015 // If the initializer might depend on the array index, run it for each
14016 // array element.
14017 if (NumEltsToInit != NumElts &&
14018 MaybeElementDependentArrayFiller(ArrayFiller)) {
14019 NumEltsToInit = NumElts;
14020 } else {
14021 for (auto *Init : Args) {
14022 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
14023 NumEltsToInit += EmbedS->getDataElementCount() - 1;
14024 }
14025 if (NumEltsToInit > NumElts)
14026 NumEltsToInit = NumElts;
14027 }
14028
14029 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
14030 << NumEltsToInit << ".\n");
14031
14032 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
14033
14034 // If the array was previously zero-initialized, preserve the
14035 // zero-initialized values.
14036 if (Filler.hasValue()) {
14037 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
14038 Result.getArrayInitializedElt(I) = Filler;
14039 if (Result.hasArrayFiller())
14040 Result.getArrayFiller() = Filler;
14041 }
14042
14043 LValue Subobject = This;
14044 Subobject.addArray(Info, ExprToVisit, CAT);
14045 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
14046 if (Init->isValueDependent())
14047 return EvaluateDependentExpr(Init, Info);
14048
14049 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
14050 Subobject, Init) ||
14051 !HandleLValueArrayAdjustment(Info, Init, Subobject,
14052 CAT->getElementType(), 1)) {
14053 if (!Info.noteFailure())
14054 return false;
14055 Success = false;
14056 }
14057 return true;
14058 };
14059 unsigned ArrayIndex = 0;
14060 QualType DestTy = CAT->getElementType();
14061 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
14062 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
14063 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
14064 if (ArrayIndex >= NumEltsToInit)
14065 break;
14066 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
14067 StringLiteral *SL = EmbedS->getDataStringLiteral();
14068 for (unsigned I = EmbedS->getStartingElementPos(),
14069 N = EmbedS->getDataElementCount();
14070 I != EmbedS->getStartingElementPos() + N; ++I) {
14071 Value = SL->getCodeUnit(I);
14072 if (DestTy->isIntegerType()) {
14073 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
14074 } else {
14075 assert(DestTy->isFloatingType() && "unexpected type");
14076 const FPOptions FPO =
14077 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14078 APFloat FValue(0.0);
14079 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
14080 DestTy, FValue))
14081 return false;
14082 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
14083 }
14084 ArrayIndex++;
14085 }
14086 } else {
14087 if (!Eval(Init, ArrayIndex))
14088 return false;
14089 ++ArrayIndex;
14090 }
14091 }
14092
14093 if (!Result.hasArrayFiller())
14094 return Success;
14095
14096 // If we get here, we have a trivial filler, which we can just evaluate
14097 // once and splat over the rest of the array elements.
14098 assert(ArrayFiller && "no array filler for incomplete init list");
14099 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
14100 ArrayFiller) &&
14101 Success;
14102}
14103
14104bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
14105 LValue CommonLV;
14106 if (E->getCommonExpr() &&
14107 !Evaluate(Info.CurrentCall->createTemporary(
14108 E->getCommonExpr(),
14109 getStorageType(Info.Ctx, E->getCommonExpr()),
14110 ScopeKind::FullExpression, CommonLV),
14111 Info, E->getCommonExpr()->getSourceExpr()))
14112 return false;
14113
14115
14116 uint64_t Elements = CAT->getZExtSize();
14117 Result = APValue(APValue::UninitArray(), Elements, Elements);
14118
14119 LValue Subobject = This;
14120 Subobject.addArray(Info, E, CAT);
14121
14122 bool Success = true;
14123 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
14124 // C++ [class.temporary]/5
14125 // There are four contexts in which temporaries are destroyed at a different
14126 // point than the end of the full-expression. [...] The second context is
14127 // when a copy constructor is called to copy an element of an array while
14128 // the entire array is copied [...]. In either case, if the constructor has
14129 // one or more default arguments, the destruction of every temporary created
14130 // in a default argument is sequenced before the construction of the next
14131 // array element, if any.
14132 FullExpressionRAII Scope(Info);
14133
14134 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14135 Info, Subobject, E->getSubExpr()) ||
14136 !HandleLValueArrayAdjustment(Info, E, Subobject,
14137 CAT->getElementType(), 1)) {
14138 if (!Info.noteFailure())
14139 return false;
14140 Success = false;
14141 }
14142
14143 // Make sure we run the destructors too.
14144 Scope.destroy();
14145 }
14146
14147 return Success;
14148}
14149
14150bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
14151 return VisitCXXConstructExpr(E, This, &Result, E->getType());
14152}
14153
14154bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
14155 const LValue &Subobject,
14156 APValue *Value,
14157 QualType Type) {
14158 bool HadZeroInit = Value->hasValue();
14159
14160 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
14161 unsigned FinalSize = CAT->getZExtSize();
14162
14163 // Preserve the array filler if we had prior zero-initialization.
14164 APValue Filler =
14165 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
14166 : APValue();
14167
14168 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
14169 if (FinalSize == 0)
14170 return true;
14171
14172 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
14173 Info, E->getExprLoc(), E->getConstructor(),
14175 LValue ArrayElt = Subobject;
14176 ArrayElt.addArray(Info, E, CAT);
14177 // We do the whole initialization in two passes, first for just one element,
14178 // then for the whole array. It's possible we may find out we can't do const
14179 // init in the first pass, in which case we avoid allocating a potentially
14180 // large array. We don't do more passes because expanding array requires
14181 // copying the data, which is wasteful.
14182 for (const unsigned N : {1u, FinalSize}) {
14183 unsigned OldElts = Value->getArrayInitializedElts();
14184 if (OldElts == N)
14185 break;
14186
14187 // Expand the array to appropriate size.
14188 APValue NewValue(APValue::UninitArray(), N, FinalSize);
14189 for (unsigned I = 0; I < OldElts; ++I)
14190 NewValue.getArrayInitializedElt(I).swap(
14191 Value->getArrayInitializedElt(I));
14192 Value->swap(NewValue);
14193
14194 if (HadZeroInit)
14195 for (unsigned I = OldElts; I < N; ++I)
14196 Value->getArrayInitializedElt(I) = Filler;
14197
14198 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
14199 // If we have a trivial constructor, only evaluate it once and copy
14200 // the result into all the array elements.
14201 APValue &FirstResult = Value->getArrayInitializedElt(0);
14202 for (unsigned I = OldElts; I < FinalSize; ++I)
14203 Value->getArrayInitializedElt(I) = FirstResult;
14204 } else {
14205 for (unsigned I = OldElts; I < N; ++I) {
14206 if (!VisitCXXConstructExpr(E, ArrayElt,
14207 &Value->getArrayInitializedElt(I),
14208 CAT->getElementType()) ||
14209 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
14210 CAT->getElementType(), 1))
14211 return false;
14212 // When checking for const initilization any diagnostic is considered
14213 // an error.
14214 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
14215 !Info.keepEvaluatingAfterFailure())
14216 return false;
14217 }
14218 }
14219 }
14220
14221 return true;
14222 }
14223
14224 if (!Type->isRecordType())
14225 return Error(E);
14226
14227 return RecordExprEvaluator(Info, Subobject, *Value)
14228 .VisitCXXConstructExpr(E, Type);
14229}
14230
14231bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
14232 const CXXParenListInitExpr *E) {
14233 assert(E->getType()->isConstantArrayType() &&
14234 "Expression result is not a constant array type");
14235
14236 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
14237 E->getArrayFiller());
14238}
14239
14240//===----------------------------------------------------------------------===//
14241// Integer Evaluation
14242//
14243// As a GNU extension, we support casting pointers to sufficiently-wide integer
14244// types and back in constant folding. Integer values are thus represented
14245// either as an integer-valued APValue, or as an lvalue-valued APValue.
14246//===----------------------------------------------------------------------===//
14247
14248namespace {
14249class IntExprEvaluator
14250 : public ExprEvaluatorBase<IntExprEvaluator> {
14251 APValue &Result;
14252public:
14253 IntExprEvaluator(EvalInfo &info, APValue &result)
14254 : ExprEvaluatorBaseTy(info), Result(result) {}
14255
14256 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
14257 assert(E->getType()->isIntegralOrEnumerationType() &&
14258 "Invalid evaluation result.");
14259 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
14260 "Invalid evaluation result.");
14261 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14262 "Invalid evaluation result.");
14263 Result = APValue(SI);
14264 return true;
14265 }
14266 bool Success(const llvm::APSInt &SI, const Expr *E) {
14267 return Success(SI, E, Result);
14268 }
14269
14270 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
14271 assert(E->getType()->isIntegralOrEnumerationType() &&
14272 "Invalid evaluation result.");
14273 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14274 "Invalid evaluation result.");
14275 Result = APValue(APSInt(I));
14276 Result.getInt().setIsUnsigned(
14278 return true;
14279 }
14280 bool Success(const llvm::APInt &I, const Expr *E) {
14281 return Success(I, E, Result);
14282 }
14283
14284 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14285 assert(E->getType()->isIntegralOrEnumerationType() &&
14286 "Invalid evaluation result.");
14287 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
14288 return true;
14289 }
14290 bool Success(uint64_t Value, const Expr *E) {
14291 return Success(Value, E, Result);
14292 }
14293
14294 bool Success(CharUnits Size, const Expr *E) {
14295 return Success(Size.getQuantity(), E);
14296 }
14297
14298 bool Success(const APValue &V, const Expr *E) {
14299 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
14300 // pointer allow further evaluation of the value.
14301 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
14302 V.allowConstexprUnknown()) {
14303 Result = V;
14304 return true;
14305 }
14306 return Success(V.getInt(), E);
14307 }
14308
14309 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
14310
14311 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
14312 const CallExpr *);
14313
14314 //===--------------------------------------------------------------------===//
14315 // Visitor Methods
14316 //===--------------------------------------------------------------------===//
14317
14318 bool VisitIntegerLiteral(const IntegerLiteral *E) {
14319 return Success(E->getValue(), E);
14320 }
14321 bool VisitCharacterLiteral(const CharacterLiteral *E) {
14322 return Success(E->getValue(), E);
14323 }
14324
14325 bool CheckReferencedDecl(const Expr *E, const Decl *D);
14326 bool VisitDeclRefExpr(const DeclRefExpr *E) {
14327 if (CheckReferencedDecl(E, E->getDecl()))
14328 return true;
14329
14330 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
14331 }
14332 bool VisitMemberExpr(const MemberExpr *E) {
14333 if (CheckReferencedDecl(E, E->getMemberDecl())) {
14334 VisitIgnoredBaseExpression(E->getBase());
14335 return true;
14336 }
14337
14338 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
14339 }
14340
14341 bool VisitCallExpr(const CallExpr *E);
14342 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
14343 bool VisitBinaryOperator(const BinaryOperator *E);
14344 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
14345 bool VisitUnaryOperator(const UnaryOperator *E);
14346
14347 bool VisitCastExpr(const CastExpr* E);
14348 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
14349
14350 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
14351 return Success(E->getValue(), E);
14352 }
14353
14354 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
14355 return Success(E->getValue(), E);
14356 }
14357
14358 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
14359 if (Info.ArrayInitIndex == uint64_t(-1)) {
14360 // We were asked to evaluate this subexpression independent of the
14361 // enclosing ArrayInitLoopExpr. We can't do that.
14362 Info.FFDiag(E);
14363 return false;
14364 }
14365 return Success(Info.ArrayInitIndex, E);
14366 }
14367
14368 // Note, GNU defines __null as an integer, not a pointer.
14369 bool VisitGNUNullExpr(const GNUNullExpr *E) {
14370 return ZeroInitialization(E);
14371 }
14372
14373 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
14374 if (E->isStoredAsBoolean())
14375 return Success(E->getBoolValue(), E);
14376 if (E->getAPValue().isAbsent())
14377 return false;
14378 assert(E->getAPValue().isInt() && "APValue type not supported");
14379 return Success(E->getAPValue().getInt(), E);
14380 }
14381
14382 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
14383 return Success(E->getValue(), E);
14384 }
14385
14386 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
14387 return Success(E->getValue(), E);
14388 }
14389
14390 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
14391 // This should not be evaluated during constant expr evaluation, as it
14392 // should always be in an unevaluated context (the args list of a 'gang' or
14393 // 'tile' clause).
14394 return Error(E);
14395 }
14396
14397 bool VisitUnaryReal(const UnaryOperator *E);
14398 bool VisitUnaryImag(const UnaryOperator *E);
14399
14400 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
14401 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
14402 bool VisitSourceLocExpr(const SourceLocExpr *E);
14403 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
14404 bool VisitRequiresExpr(const RequiresExpr *E);
14405 // FIXME: Missing: array subscript of vector, member of vector
14406};
14407
14408class FixedPointExprEvaluator
14409 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
14410 APValue &Result;
14411
14412 public:
14413 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
14414 : ExprEvaluatorBaseTy(info), Result(result) {}
14415
14416 bool Success(const llvm::APInt &I, const Expr *E) {
14417 return Success(
14418 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
14419 }
14420
14421 bool Success(uint64_t Value, const Expr *E) {
14422 return Success(
14423 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
14424 }
14425
14426 bool Success(const APValue &V, const Expr *E) {
14427 return Success(V.getFixedPoint(), E);
14428 }
14429
14430 bool Success(const APFixedPoint &V, const Expr *E) {
14431 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
14432 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14433 "Invalid evaluation result.");
14434 Result = APValue(V);
14435 return true;
14436 }
14437
14438 bool ZeroInitialization(const Expr *E) {
14439 return Success(0, E);
14440 }
14441
14442 //===--------------------------------------------------------------------===//
14443 // Visitor Methods
14444 //===--------------------------------------------------------------------===//
14445
14446 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
14447 return Success(E->getValue(), E);
14448 }
14449
14450 bool VisitCastExpr(const CastExpr *E);
14451 bool VisitUnaryOperator(const UnaryOperator *E);
14452 bool VisitBinaryOperator(const BinaryOperator *E);
14453};
14454} // end anonymous namespace
14455
14456/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
14457/// produce either the integer value or a pointer.
14458///
14459/// GCC has a heinous extension which folds casts between pointer types and
14460/// pointer-sized integral types. We support this by allowing the evaluation of
14461/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
14462/// Some simple arithmetic on such values is supported (they are treated much
14463/// like char*).
14464static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
14465 EvalInfo &Info) {
14466 assert(!E->isValueDependent());
14467 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
14468 return IntExprEvaluator(Info, Result).Visit(E);
14469}
14470
14471static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
14472 assert(!E->isValueDependent());
14473 APValue Val;
14474 if (!EvaluateIntegerOrLValue(E, Val, Info))
14475 return false;
14476 if (!Val.isInt()) {
14477 // FIXME: It would be better to produce the diagnostic for casting
14478 // a pointer to an integer.
14479 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14480 return false;
14481 }
14482 Result = Val.getInt();
14483 return true;
14484}
14485
14486bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
14488 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
14489 return Success(Evaluated, E);
14490}
14491
14492static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
14493 EvalInfo &Info) {
14494 assert(!E->isValueDependent());
14495 if (E->getType()->isFixedPointType()) {
14496 APValue Val;
14497 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
14498 return false;
14499 if (!Val.isFixedPoint())
14500 return false;
14501
14502 Result = Val.getFixedPoint();
14503 return true;
14504 }
14505 return false;
14506}
14507
14508static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
14509 EvalInfo &Info) {
14510 assert(!E->isValueDependent());
14511 if (E->getType()->isIntegerType()) {
14512 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
14513 APSInt Val;
14514 if (!EvaluateInteger(E, Val, Info))
14515 return false;
14516 Result = APFixedPoint(Val, FXSema);
14517 return true;
14518 } else if (E->getType()->isFixedPointType()) {
14519 return EvaluateFixedPoint(E, Result, Info);
14520 }
14521 return false;
14522}
14523
14524/// Check whether the given declaration can be directly converted to an integral
14525/// rvalue. If not, no diagnostic is produced; there are other things we can
14526/// try.
14527bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
14528 // Enums are integer constant exprs.
14529 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
14530 // Check for signedness/width mismatches between E type and ECD value.
14531 bool SameSign = (ECD->getInitVal().isSigned()
14533 bool SameWidth = (ECD->getInitVal().getBitWidth()
14534 == Info.Ctx.getIntWidth(E->getType()));
14535 if (SameSign && SameWidth)
14536 return Success(ECD->getInitVal(), E);
14537 else {
14538 // Get rid of mismatch (otherwise Success assertions will fail)
14539 // by computing a new value matching the type of E.
14540 llvm::APSInt Val = ECD->getInitVal();
14541 if (!SameSign)
14542 Val.setIsSigned(!ECD->getInitVal().isSigned());
14543 if (!SameWidth)
14544 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
14545 return Success(Val, E);
14546 }
14547 }
14548 return false;
14549}
14550
14551/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
14552/// as GCC.
14554 const LangOptions &LangOpts) {
14555 assert(!T->isDependentType() && "unexpected dependent type");
14556
14557 QualType CanTy = T.getCanonicalType();
14558
14559 switch (CanTy->getTypeClass()) {
14560#define TYPE(ID, BASE)
14561#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
14562#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
14563#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
14564#include "clang/AST/TypeNodes.inc"
14565 case Type::Auto:
14566 case Type::DeducedTemplateSpecialization:
14567 llvm_unreachable("unexpected non-canonical or dependent type");
14568
14569 case Type::Builtin:
14570 switch (cast<BuiltinType>(CanTy)->getKind()) {
14571#define BUILTIN_TYPE(ID, SINGLETON_ID)
14572#define SIGNED_TYPE(ID, SINGLETON_ID) \
14573 case BuiltinType::ID: return GCCTypeClass::Integer;
14574#define FLOATING_TYPE(ID, SINGLETON_ID) \
14575 case BuiltinType::ID: return GCCTypeClass::RealFloat;
14576#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
14577 case BuiltinType::ID: break;
14578#include "clang/AST/BuiltinTypes.def"
14579 case BuiltinType::Void:
14580 return GCCTypeClass::Void;
14581
14582 case BuiltinType::Bool:
14583 return GCCTypeClass::Bool;
14584
14585 case BuiltinType::Char_U:
14586 case BuiltinType::UChar:
14587 case BuiltinType::WChar_U:
14588 case BuiltinType::Char8:
14589 case BuiltinType::Char16:
14590 case BuiltinType::Char32:
14591 case BuiltinType::UShort:
14592 case BuiltinType::UInt:
14593 case BuiltinType::ULong:
14594 case BuiltinType::ULongLong:
14595 case BuiltinType::UInt128:
14596 return GCCTypeClass::Integer;
14597
14598 case BuiltinType::UShortAccum:
14599 case BuiltinType::UAccum:
14600 case BuiltinType::ULongAccum:
14601 case BuiltinType::UShortFract:
14602 case BuiltinType::UFract:
14603 case BuiltinType::ULongFract:
14604 case BuiltinType::SatUShortAccum:
14605 case BuiltinType::SatUAccum:
14606 case BuiltinType::SatULongAccum:
14607 case BuiltinType::SatUShortFract:
14608 case BuiltinType::SatUFract:
14609 case BuiltinType::SatULongFract:
14610 return GCCTypeClass::None;
14611
14612 case BuiltinType::NullPtr:
14613
14614 case BuiltinType::ObjCId:
14615 case BuiltinType::ObjCClass:
14616 case BuiltinType::ObjCSel:
14617#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
14618 case BuiltinType::Id:
14619#include "clang/Basic/OpenCLImageTypes.def"
14620#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
14621 case BuiltinType::Id:
14622#include "clang/Basic/OpenCLExtensionTypes.def"
14623 case BuiltinType::OCLSampler:
14624 case BuiltinType::OCLEvent:
14625 case BuiltinType::OCLClkEvent:
14626 case BuiltinType::OCLQueue:
14627 case BuiltinType::OCLReserveID:
14628#define SVE_TYPE(Name, Id, SingletonId) \
14629 case BuiltinType::Id:
14630#include "clang/Basic/AArch64ACLETypes.def"
14631#define PPC_VECTOR_TYPE(Name, Id, Size) \
14632 case BuiltinType::Id:
14633#include "clang/Basic/PPCTypes.def"
14634#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14635#include "clang/Basic/RISCVVTypes.def"
14636#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14637#include "clang/Basic/WebAssemblyReferenceTypes.def"
14638#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
14639#include "clang/Basic/AMDGPUTypes.def"
14640#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
14641#include "clang/Basic/HLSLIntangibleTypes.def"
14642 return GCCTypeClass::None;
14643
14644 case BuiltinType::Dependent:
14645 llvm_unreachable("unexpected dependent type");
14646 };
14647 llvm_unreachable("unexpected placeholder type");
14648
14649 case Type::Enum:
14650 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
14651
14652 case Type::Pointer:
14653 case Type::ConstantArray:
14654 case Type::VariableArray:
14655 case Type::IncompleteArray:
14656 case Type::FunctionNoProto:
14657 case Type::FunctionProto:
14658 case Type::ArrayParameter:
14659 return GCCTypeClass::Pointer;
14660
14661 case Type::MemberPointer:
14662 return CanTy->isMemberDataPointerType()
14665
14666 case Type::Complex:
14667 return GCCTypeClass::Complex;
14668
14669 case Type::Record:
14670 return CanTy->isUnionType() ? GCCTypeClass::Union
14672
14673 case Type::Atomic:
14674 // GCC classifies _Atomic T the same as T.
14676 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
14677
14678 case Type::Vector:
14679 case Type::ExtVector:
14680 return GCCTypeClass::Vector;
14681
14682 case Type::BlockPointer:
14683 case Type::ConstantMatrix:
14684 case Type::ObjCObject:
14685 case Type::ObjCInterface:
14686 case Type::ObjCObjectPointer:
14687 case Type::Pipe:
14688 case Type::HLSLAttributedResource:
14689 case Type::HLSLInlineSpirv:
14690 // Classify all other types that don't fit into the regular
14691 // classification the same way.
14692 return GCCTypeClass::None;
14693
14694 case Type::BitInt:
14695 return GCCTypeClass::BitInt;
14696
14697 case Type::LValueReference:
14698 case Type::RValueReference:
14699 llvm_unreachable("invalid type for expression");
14700 }
14701
14702 llvm_unreachable("unexpected type class");
14703}
14704
14705/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
14706/// as GCC.
14707static GCCTypeClass
14709 // If no argument was supplied, default to None. This isn't
14710 // ideal, however it is what gcc does.
14711 if (E->getNumArgs() == 0)
14712 return GCCTypeClass::None;
14713
14714 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
14715 // being an ICE, but still folds it to a constant using the type of the first
14716 // argument.
14717 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
14718}
14719
14720/// EvaluateBuiltinConstantPForLValue - Determine the result of
14721/// __builtin_constant_p when applied to the given pointer.
14722///
14723/// A pointer is only "constant" if it is null (or a pointer cast to integer)
14724/// or it points to the first character of a string literal.
14727 if (Base.isNull()) {
14728 // A null base is acceptable.
14729 return true;
14730 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
14731 if (!isa<StringLiteral>(E))
14732 return false;
14733 return LV.getLValueOffset().isZero();
14734 } else if (Base.is<TypeInfoLValue>()) {
14735 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
14736 // evaluate to true.
14737 return true;
14738 } else {
14739 // Any other base is not constant enough for GCC.
14740 return false;
14741 }
14742}
14743
14744/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
14745/// GCC as we can manage.
14746static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
14747 // This evaluation is not permitted to have side-effects, so evaluate it in
14748 // a speculative evaluation context.
14749 SpeculativeEvaluationRAII SpeculativeEval(Info);
14750
14751 // Constant-folding is always enabled for the operand of __builtin_constant_p
14752 // (even when the enclosing evaluation context otherwise requires a strict
14753 // language-specific constant expression).
14754 FoldConstant Fold(Info, true);
14755
14756 QualType ArgType = Arg->getType();
14757
14758 // __builtin_constant_p always has one operand. The rules which gcc follows
14759 // are not precisely documented, but are as follows:
14760 //
14761 // - If the operand is of integral, floating, complex or enumeration type,
14762 // and can be folded to a known value of that type, it returns 1.
14763 // - If the operand can be folded to a pointer to the first character
14764 // of a string literal (or such a pointer cast to an integral type)
14765 // or to a null pointer or an integer cast to a pointer, it returns 1.
14766 //
14767 // Otherwise, it returns 0.
14768 //
14769 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
14770 // its support for this did not work prior to GCC 9 and is not yet well
14771 // understood.
14772 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
14773 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
14774 ArgType->isNullPtrType()) {
14775 APValue V;
14776 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
14777 Fold.keepDiagnostics();
14778 return false;
14779 }
14780
14781 // For a pointer (possibly cast to integer), there are special rules.
14782 if (V.getKind() == APValue::LValue)
14784
14785 // Otherwise, any constant value is good enough.
14786 return V.hasValue();
14787 }
14788
14789 // Anything else isn't considered to be sufficiently constant.
14790 return false;
14791}
14792
14793/// Retrieves the "underlying object type" of the given expression,
14794/// as used by __builtin_object_size.
14796 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
14797 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
14798 return VD->getType();
14799 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
14801 return E->getType();
14802 } else if (B.is<TypeInfoLValue>()) {
14803 return B.getTypeInfoType();
14804 } else if (B.is<DynamicAllocLValue>()) {
14805 return B.getDynamicAllocType();
14806 }
14807
14808 return QualType();
14809}
14810
14811/// A more selective version of E->IgnoreParenCasts for
14812/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
14813/// to change the type of E.
14814/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
14815///
14816/// Always returns an RValue with a pointer representation.
14817static const Expr *ignorePointerCastsAndParens(const Expr *E) {
14818 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
14819
14820 const Expr *NoParens = E->IgnoreParens();
14821 const auto *Cast = dyn_cast<CastExpr>(NoParens);
14822 if (Cast == nullptr)
14823 return NoParens;
14824
14825 // We only conservatively allow a few kinds of casts, because this code is
14826 // inherently a simple solution that seeks to support the common case.
14827 auto CastKind = Cast->getCastKind();
14828 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
14829 CastKind != CK_AddressSpaceConversion)
14830 return NoParens;
14831
14832 const auto *SubExpr = Cast->getSubExpr();
14833 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
14834 return NoParens;
14835 return ignorePointerCastsAndParens(SubExpr);
14836}
14837
14838/// Checks to see if the given LValue's Designator is at the end of the LValue's
14839/// record layout. e.g.
14840/// struct { struct { int a, b; } fst, snd; } obj;
14841/// obj.fst // no
14842/// obj.snd // yes
14843/// obj.fst.a // no
14844/// obj.fst.b // no
14845/// obj.snd.a // no
14846/// obj.snd.b // yes
14847///
14848/// Please note: this function is specialized for how __builtin_object_size
14849/// views "objects".
14850///
14851/// If this encounters an invalid RecordDecl or otherwise cannot determine the
14852/// correct result, it will always return true.
14853static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
14854 assert(!LVal.Designator.Invalid);
14855
14856 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
14857 const RecordDecl *Parent = FD->getParent();
14858 if (Parent->isInvalidDecl() || Parent->isUnion())
14859 return true;
14860 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
14861 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
14862 };
14863
14864 auto &Base = LVal.getLValueBase();
14865 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
14866 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
14867 if (!IsLastOrInvalidFieldDecl(FD))
14868 return false;
14869 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
14870 for (auto *FD : IFD->chain()) {
14871 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
14872 return false;
14873 }
14874 }
14875 }
14876
14877 unsigned I = 0;
14878 QualType BaseType = getType(Base);
14879 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
14880 // If we don't know the array bound, conservatively assume we're looking at
14881 // the final array element.
14882 ++I;
14883 if (BaseType->isIncompleteArrayType())
14884 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
14885 else
14886 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
14887 }
14888
14889 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
14890 const auto &Entry = LVal.Designator.Entries[I];
14891 if (BaseType->isArrayType()) {
14892 // Because __builtin_object_size treats arrays as objects, we can ignore
14893 // the index iff this is the last array in the Designator.
14894 if (I + 1 == E)
14895 return true;
14896 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
14897 uint64_t Index = Entry.getAsArrayIndex();
14898 if (Index + 1 != CAT->getZExtSize())
14899 return false;
14900 BaseType = CAT->getElementType();
14901 } else if (BaseType->isAnyComplexType()) {
14902 const auto *CT = BaseType->castAs<ComplexType>();
14903 uint64_t Index = Entry.getAsArrayIndex();
14904 if (Index != 1)
14905 return false;
14906 BaseType = CT->getElementType();
14907 } else if (auto *FD = getAsField(Entry)) {
14908 if (!IsLastOrInvalidFieldDecl(FD))
14909 return false;
14910 BaseType = FD->getType();
14911 } else {
14912 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
14913 return false;
14914 }
14915 }
14916 return true;
14917}
14918
14919/// Tests to see if the LValue has a user-specified designator (that isn't
14920/// necessarily valid). Note that this always returns 'true' if the LValue has
14921/// an unsized array as its first designator entry, because there's currently no
14922/// way to tell if the user typed *foo or foo[0].
14923static bool refersToCompleteObject(const LValue &LVal) {
14924 if (LVal.Designator.Invalid)
14925 return false;
14926
14927 if (!LVal.Designator.Entries.empty())
14928 return LVal.Designator.isMostDerivedAnUnsizedArray();
14929
14930 if (!LVal.InvalidBase)
14931 return true;
14932
14933 // If `E` is a MemberExpr, then the first part of the designator is hiding in
14934 // the LValueBase.
14935 const auto *E = LVal.Base.dyn_cast<const Expr *>();
14936 return !E || !isa<MemberExpr>(E);
14937}
14938
14939/// Attempts to detect a user writing into a piece of memory that's impossible
14940/// to figure out the size of by just using types.
14941static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
14942 const SubobjectDesignator &Designator = LVal.Designator;
14943 // Notes:
14944 // - Users can only write off of the end when we have an invalid base. Invalid
14945 // bases imply we don't know where the memory came from.
14946 // - We used to be a bit more aggressive here; we'd only be conservative if
14947 // the array at the end was flexible, or if it had 0 or 1 elements. This
14948 // broke some common standard library extensions (PR30346), but was
14949 // otherwise seemingly fine. It may be useful to reintroduce this behavior
14950 // with some sort of list. OTOH, it seems that GCC is always
14951 // conservative with the last element in structs (if it's an array), so our
14952 // current behavior is more compatible than an explicit list approach would
14953 // be.
14954 auto isFlexibleArrayMember = [&] {
14956 FAMKind StrictFlexArraysLevel =
14957 Ctx.getLangOpts().getStrictFlexArraysLevel();
14958
14959 if (Designator.isMostDerivedAnUnsizedArray())
14960 return true;
14961
14962 if (StrictFlexArraysLevel == FAMKind::Default)
14963 return true;
14964
14965 if (Designator.getMostDerivedArraySize() == 0 &&
14966 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
14967 return true;
14968
14969 if (Designator.getMostDerivedArraySize() == 1 &&
14970 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
14971 return true;
14972
14973 return false;
14974 };
14975
14976 return LVal.InvalidBase &&
14977 Designator.Entries.size() == Designator.MostDerivedPathLength &&
14978 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
14979 isDesignatorAtObjectEnd(Ctx, LVal);
14980}
14981
14982/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
14983/// Fails if the conversion would cause loss of precision.
14984static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
14985 CharUnits &Result) {
14986 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
14987 if (Int.ugt(CharUnitsMax))
14988 return false;
14989 Result = CharUnits::fromQuantity(Int.getZExtValue());
14990 return true;
14991}
14992
14993/// If we're evaluating the object size of an instance of a struct that
14994/// contains a flexible array member, add the size of the initializer.
14995static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
14996 const LValue &LV, CharUnits &Size) {
14997 if (!T.isNull() && T->isStructureType() &&
14998 T->castAsRecordDecl()->hasFlexibleArrayMember())
14999 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
15000 if (const auto *VD = dyn_cast<VarDecl>(V))
15001 if (VD->hasInit())
15002 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
15003}
15004
15005/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
15006/// determine how many bytes exist from the beginning of the object to either
15007/// the end of the current subobject, or the end of the object itself, depending
15008/// on what the LValue looks like + the value of Type.
15009///
15010/// If this returns false, the value of Result is undefined.
15011static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
15012 unsigned Type, const LValue &LVal,
15013 CharUnits &EndOffset) {
15014 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
15015
15016 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
15017 if (Ty.isNull())
15018 return false;
15019
15020 Ty = Ty.getNonReferenceType();
15021
15022 if (Ty->isIncompleteType() || Ty->isFunctionType())
15023 return false;
15024
15025 return HandleSizeof(Info, ExprLoc, Ty, Result);
15026 };
15027
15028 // We want to evaluate the size of the entire object. This is a valid fallback
15029 // for when Type=1 and the designator is invalid, because we're asked for an
15030 // upper-bound.
15031 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
15032 // Type=3 wants a lower bound, so we can't fall back to this.
15033 if (Type == 3 && !DetermineForCompleteObject)
15034 return false;
15035
15036 llvm::APInt APEndOffset;
15037 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15038 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15039 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15040
15041 if (LVal.InvalidBase)
15042 return false;
15043
15044 QualType BaseTy = getObjectType(LVal.getLValueBase());
15045 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
15046 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
15047 return Ret;
15048 }
15049
15050 // We want to evaluate the size of a subobject.
15051 const SubobjectDesignator &Designator = LVal.Designator;
15052
15053 // The following is a moderately common idiom in C:
15054 //
15055 // struct Foo { int a; char c[1]; };
15056 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
15057 // strcpy(&F->c[0], Bar);
15058 //
15059 // In order to not break too much legacy code, we need to support it.
15060 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
15061 // If we can resolve this to an alloc_size call, we can hand that back,
15062 // because we know for certain how many bytes there are to write to.
15063 llvm::APInt APEndOffset;
15064 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15065 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15066 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15067
15068 // If we cannot determine the size of the initial allocation, then we can't
15069 // given an accurate upper-bound. However, we are still able to give
15070 // conservative lower-bounds for Type=3.
15071 if (Type == 1)
15072 return false;
15073 }
15074
15075 CharUnits BytesPerElem;
15076 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
15077 return false;
15078
15079 // According to the GCC documentation, we want the size of the subobject
15080 // denoted by the pointer. But that's not quite right -- what we actually
15081 // want is the size of the immediately-enclosing array, if there is one.
15082 int64_t ElemsRemaining;
15083 if (Designator.MostDerivedIsArrayElement &&
15084 Designator.Entries.size() == Designator.MostDerivedPathLength) {
15085 uint64_t ArraySize = Designator.getMostDerivedArraySize();
15086 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
15087 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
15088 } else {
15089 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
15090 }
15091
15092 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
15093 return true;
15094}
15095
15096/// Tries to evaluate the __builtin_object_size for @p E. If successful,
15097/// returns true and stores the result in @p Size.
15098///
15099/// If @p WasError is non-null, this will report whether the failure to evaluate
15100/// is to be treated as an Error in IntExprEvaluator.
15101static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
15102 EvalInfo &Info, uint64_t &Size) {
15103 // Determine the denoted object.
15104 LValue LVal;
15105 {
15106 // The operand of __builtin_object_size is never evaluated for side-effects.
15107 // If there are any, but we can determine the pointed-to object anyway, then
15108 // ignore the side-effects.
15109 SpeculativeEvaluationRAII SpeculativeEval(Info);
15110 IgnoreSideEffectsRAII Fold(Info);
15111
15112 if (E->isGLValue()) {
15113 // It's possible for us to be given GLValues if we're called via
15114 // Expr::tryEvaluateObjectSize.
15115 APValue RVal;
15116 if (!EvaluateAsRValue(Info, E, RVal))
15117 return false;
15118 LVal.setFrom(Info.Ctx, RVal);
15119 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
15120 /*InvalidBaseOK=*/true))
15121 return false;
15122 }
15123
15124 // If we point to before the start of the object, there are no accessible
15125 // bytes.
15126 if (LVal.getLValueOffset().isNegative()) {
15127 Size = 0;
15128 return true;
15129 }
15130
15131 CharUnits EndOffset;
15132 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
15133 return false;
15134
15135 // If we've fallen outside of the end offset, just pretend there's nothing to
15136 // write to/read from.
15137 if (EndOffset <= LVal.getLValueOffset())
15138 Size = 0;
15139 else
15140 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
15141 return true;
15142}
15143
15144bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
15145 if (!IsConstantEvaluatedBuiltinCall(E))
15146 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15147 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
15148}
15149
15150static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
15151 APValue &Val, APSInt &Alignment) {
15152 QualType SrcTy = E->getArg(0)->getType();
15153 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
15154 return false;
15155 // Even though we are evaluating integer expressions we could get a pointer
15156 // argument for the __builtin_is_aligned() case.
15157 if (SrcTy->isPointerType()) {
15158 LValue Ptr;
15159 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
15160 return false;
15161 Ptr.moveInto(Val);
15162 } else if (!SrcTy->isIntegralOrEnumerationType()) {
15163 Info.FFDiag(E->getArg(0));
15164 return false;
15165 } else {
15166 APSInt SrcInt;
15167 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
15168 return false;
15169 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
15170 "Bit widths must be the same");
15171 Val = APValue(SrcInt);
15172 }
15173 assert(Val.hasValue());
15174 return true;
15175}
15176
15177bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
15178 unsigned BuiltinOp) {
15179 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
15180 Fn) {
15181 APValue SourceLHS, SourceRHS;
15182 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
15183 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
15184 return false;
15185
15186 unsigned SourceLen = SourceLHS.getVectorLength();
15187 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15188 QualType ElemQT = VT->getElementType();
15189 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
15190
15191 APInt AWide(LaneWidth * SourceLen, 0);
15192 APInt BWide(LaneWidth * SourceLen, 0);
15193
15194 for (unsigned I = 0; I != SourceLen; ++I) {
15195 APInt ALane;
15196 APInt BLane;
15197 if (ElemQT->isIntegerType()) { // Get value.
15198 ALane = SourceLHS.getVectorElt(I).getInt();
15199 BLane = SourceRHS.getVectorElt(I).getInt();
15200 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
15201 ALane =
15202 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15203 BLane =
15204 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15205 } else { // Must be integer or floating type.
15206 return false;
15207 }
15208 AWide.insertBits(ALane, I * LaneWidth);
15209 BWide.insertBits(BLane, I * LaneWidth);
15210 }
15211 return Success(Fn(AWide, BWide), E);
15212 };
15213
15214 auto HandleMaskBinOp =
15215 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
15216 -> bool {
15217 APValue LHS, RHS;
15218 if (!Evaluate(LHS, Info, E->getArg(0)) ||
15219 !Evaluate(RHS, Info, E->getArg(1)))
15220 return false;
15221
15222 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
15223
15224 return Success(APValue(ResultInt), E);
15225 };
15226
15227 switch (BuiltinOp) {
15228 default:
15229 return false;
15230
15231 case Builtin::BI__builtin_dynamic_object_size:
15232 case Builtin::BI__builtin_object_size: {
15233 // The type was checked when we built the expression.
15234 unsigned Type =
15235 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
15236 assert(Type <= 3 && "unexpected type");
15237
15238 uint64_t Size;
15239 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
15240 return Success(Size, E);
15241
15242 if (E->getArg(0)->HasSideEffects(Info.Ctx))
15243 return Success((Type & 2) ? 0 : -1, E);
15244
15245 // Expression had no side effects, but we couldn't statically determine the
15246 // size of the referenced object.
15247 switch (Info.EvalMode) {
15248 case EvaluationMode::ConstantExpression:
15249 case EvaluationMode::ConstantFold:
15250 case EvaluationMode::IgnoreSideEffects:
15251 // Leave it to IR generation.
15252 return Error(E);
15253 case EvaluationMode::ConstantExpressionUnevaluated:
15254 // Reduce it to a constant now.
15255 return Success((Type & 2) ? 0 : -1, E);
15256 }
15257
15258 llvm_unreachable("unexpected EvalMode");
15259 }
15260
15261 case Builtin::BI__builtin_os_log_format_buffer_size: {
15262 analyze_os_log::OSLogBufferLayout Layout;
15263 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
15264 return Success(Layout.size().getQuantity(), E);
15265 }
15266
15267 case Builtin::BI__builtin_is_aligned: {
15268 APValue Src;
15269 APSInt Alignment;
15270 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15271 return false;
15272 if (Src.isLValue()) {
15273 // If we evaluated a pointer, check the minimum known alignment.
15274 LValue Ptr;
15275 Ptr.setFrom(Info.Ctx, Src);
15276 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
15277 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
15278 // We can return true if the known alignment at the computed offset is
15279 // greater than the requested alignment.
15280 assert(PtrAlign.isPowerOfTwo());
15281 assert(Alignment.isPowerOf2());
15282 if (PtrAlign.getQuantity() >= Alignment)
15283 return Success(1, E);
15284 // If the alignment is not known to be sufficient, some cases could still
15285 // be aligned at run time. However, if the requested alignment is less or
15286 // equal to the base alignment and the offset is not aligned, we know that
15287 // the run-time value can never be aligned.
15288 if (BaseAlignment.getQuantity() >= Alignment &&
15289 PtrAlign.getQuantity() < Alignment)
15290 return Success(0, E);
15291 // Otherwise we can't infer whether the value is sufficiently aligned.
15292 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
15293 // in cases where we can't fully evaluate the pointer.
15294 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
15295 << Alignment;
15296 return false;
15297 }
15298 assert(Src.isInt());
15299 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
15300 }
15301 case Builtin::BI__builtin_align_up: {
15302 APValue Src;
15303 APSInt Alignment;
15304 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15305 return false;
15306 if (!Src.isInt())
15307 return Error(E);
15308 APSInt AlignedVal =
15309 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
15310 Src.getInt().isUnsigned());
15311 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15312 return Success(AlignedVal, E);
15313 }
15314 case Builtin::BI__builtin_align_down: {
15315 APValue Src;
15316 APSInt Alignment;
15317 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15318 return false;
15319 if (!Src.isInt())
15320 return Error(E);
15321 APSInt AlignedVal =
15322 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
15323 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15324 return Success(AlignedVal, E);
15325 }
15326
15327 case Builtin::BI__builtin_bitreverse8:
15328 case Builtin::BI__builtin_bitreverse16:
15329 case Builtin::BI__builtin_bitreverse32:
15330 case Builtin::BI__builtin_bitreverse64:
15331 case Builtin::BI__builtin_elementwise_bitreverse: {
15332 APSInt Val;
15333 if (!EvaluateInteger(E->getArg(0), Val, Info))
15334 return false;
15335
15336 return Success(Val.reverseBits(), E);
15337 }
15338 case Builtin::BI__builtin_bswapg:
15339 case Builtin::BI__builtin_bswap16:
15340 case Builtin::BI__builtin_bswap32:
15341 case Builtin::BI__builtin_bswap64: {
15342 APSInt Val;
15343 if (!EvaluateInteger(E->getArg(0), Val, Info))
15344 return false;
15345 if (Val.getBitWidth() == 8)
15346 return Success(Val, E);
15347
15348 return Success(Val.byteSwap(), E);
15349 }
15350
15351 case Builtin::BI__builtin_classify_type:
15352 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
15353
15354 case Builtin::BI__builtin_clrsb:
15355 case Builtin::BI__builtin_clrsbl:
15356 case Builtin::BI__builtin_clrsbll: {
15357 APSInt Val;
15358 if (!EvaluateInteger(E->getArg(0), Val, Info))
15359 return false;
15360
15361 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
15362 }
15363
15364 case Builtin::BI__builtin_clz:
15365 case Builtin::BI__builtin_clzl:
15366 case Builtin::BI__builtin_clzll:
15367 case Builtin::BI__builtin_clzs:
15368 case Builtin::BI__builtin_clzg:
15369 case Builtin::BI__builtin_elementwise_clzg:
15370 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
15371 case Builtin::BI__lzcnt:
15372 case Builtin::BI__lzcnt64: {
15373 APSInt Val;
15374 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15375 APValue Vec;
15376 if (!EvaluateVector(E->getArg(0), Vec, Info))
15377 return false;
15378 Val = ConvertBoolVectorToInt(Vec);
15379 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15380 return false;
15381 }
15382
15383 std::optional<APSInt> Fallback;
15384 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
15385 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
15386 E->getNumArgs() > 1) {
15387 APSInt FallbackTemp;
15388 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
15389 return false;
15390 Fallback = FallbackTemp;
15391 }
15392
15393 if (!Val) {
15394 if (Fallback)
15395 return Success(*Fallback, E);
15396
15397 // When the argument is 0, the result of GCC builtins is undefined,
15398 // whereas for Microsoft intrinsics, the result is the bit-width of the
15399 // argument.
15400 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
15401 BuiltinOp != Builtin::BI__lzcnt &&
15402 BuiltinOp != Builtin::BI__lzcnt64;
15403
15404 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
15405 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
15406 << /*IsTrailing=*/false;
15407 }
15408
15409 if (ZeroIsUndefined)
15410 return Error(E);
15411 }
15412
15413 return Success(Val.countl_zero(), E);
15414 }
15415
15416 case Builtin::BI__builtin_constant_p: {
15417 const Expr *Arg = E->getArg(0);
15418 if (EvaluateBuiltinConstantP(Info, Arg))
15419 return Success(true, E);
15420 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
15421 // Outside a constant context, eagerly evaluate to false in the presence
15422 // of side-effects in order to avoid -Wunsequenced false-positives in
15423 // a branch on __builtin_constant_p(expr).
15424 return Success(false, E);
15425 }
15426 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15427 return false;
15428 }
15429
15430 case Builtin::BI__noop:
15431 // __noop always evaluates successfully and returns 0.
15432 return Success(0, E);
15433
15434 case Builtin::BI__builtin_is_constant_evaluated: {
15435 const auto *Callee = Info.CurrentCall->getCallee();
15436 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
15437 (Info.CallStackDepth == 1 ||
15438 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
15439 Callee->getIdentifier() &&
15440 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
15441 // FIXME: Find a better way to avoid duplicated diagnostics.
15442 if (Info.EvalStatus.Diag)
15443 Info.report((Info.CallStackDepth == 1)
15444 ? E->getExprLoc()
15445 : Info.CurrentCall->getCallRange().getBegin(),
15446 diag::warn_is_constant_evaluated_always_true_constexpr)
15447 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
15448 : "std::is_constant_evaluated");
15449 }
15450
15451 return Success(Info.InConstantContext, E);
15452 }
15453
15454 case Builtin::BI__builtin_is_within_lifetime:
15455 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
15456 return Success(*result, E);
15457 return false;
15458
15459 case Builtin::BI__builtin_ctz:
15460 case Builtin::BI__builtin_ctzl:
15461 case Builtin::BI__builtin_ctzll:
15462 case Builtin::BI__builtin_ctzs:
15463 case Builtin::BI__builtin_ctzg:
15464 case Builtin::BI__builtin_elementwise_ctzg: {
15465 APSInt Val;
15466 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15467 APValue Vec;
15468 if (!EvaluateVector(E->getArg(0), Vec, Info))
15469 return false;
15470 Val = ConvertBoolVectorToInt(Vec);
15471 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15472 return false;
15473 }
15474
15475 std::optional<APSInt> Fallback;
15476 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
15477 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
15478 E->getNumArgs() > 1) {
15479 APSInt FallbackTemp;
15480 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
15481 return false;
15482 Fallback = FallbackTemp;
15483 }
15484
15485 if (!Val) {
15486 if (Fallback)
15487 return Success(*Fallback, E);
15488
15489 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
15490 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
15491 << /*IsTrailing=*/true;
15492 }
15493 return Error(E);
15494 }
15495
15496 return Success(Val.countr_zero(), E);
15497 }
15498
15499 case Builtin::BI__builtin_eh_return_data_regno: {
15500 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
15501 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
15502 return Success(Operand, E);
15503 }
15504
15505 case Builtin::BI__builtin_elementwise_abs: {
15506 APSInt Val;
15507 if (!EvaluateInteger(E->getArg(0), Val, Info))
15508 return false;
15509
15510 return Success(Val.abs(), E);
15511 }
15512
15513 case Builtin::BI__builtin_expect:
15514 case Builtin::BI__builtin_expect_with_probability:
15515 return Visit(E->getArg(0));
15516
15517 case Builtin::BI__builtin_ptrauth_string_discriminator: {
15518 const auto *Literal =
15520 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
15521 return Success(Result, E);
15522 }
15523
15524 case Builtin::BI__builtin_infer_alloc_token: {
15525 // If we fail to infer a type, this fails to be a constant expression; this
15526 // can be checked with __builtin_constant_p(...).
15527 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
15528 if (AllocType.isNull())
15529 return Error(
15530 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
15531 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
15532 if (!ATMD)
15533 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
15534 auto Mode =
15535 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
15536 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
15537 uint64_t MaxTokens =
15538 Info.getLangOpts().AllocTokenMax.value_or(~0ULL >> (64 - BitWidth));
15539 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
15540 if (!MaybeToken)
15541 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
15542 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
15543 }
15544
15545 case Builtin::BI__builtin_ffs:
15546 case Builtin::BI__builtin_ffsl:
15547 case Builtin::BI__builtin_ffsll: {
15548 APSInt Val;
15549 if (!EvaluateInteger(E->getArg(0), Val, Info))
15550 return false;
15551
15552 unsigned N = Val.countr_zero();
15553 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
15554 }
15555
15556 case Builtin::BI__builtin_fpclassify: {
15557 APFloat Val(0.0);
15558 if (!EvaluateFloat(E->getArg(5), Val, Info))
15559 return false;
15560 unsigned Arg;
15561 switch (Val.getCategory()) {
15562 case APFloat::fcNaN: Arg = 0; break;
15563 case APFloat::fcInfinity: Arg = 1; break;
15564 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
15565 case APFloat::fcZero: Arg = 4; break;
15566 }
15567 return Visit(E->getArg(Arg));
15568 }
15569
15570 case Builtin::BI__builtin_isinf_sign: {
15571 APFloat Val(0.0);
15572 return EvaluateFloat(E->getArg(0), Val, Info) &&
15573 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
15574 }
15575
15576 case Builtin::BI__builtin_isinf: {
15577 APFloat Val(0.0);
15578 return EvaluateFloat(E->getArg(0), Val, Info) &&
15579 Success(Val.isInfinity() ? 1 : 0, E);
15580 }
15581
15582 case Builtin::BI__builtin_isfinite: {
15583 APFloat Val(0.0);
15584 return EvaluateFloat(E->getArg(0), Val, Info) &&
15585 Success(Val.isFinite() ? 1 : 0, E);
15586 }
15587
15588 case Builtin::BI__builtin_isnan: {
15589 APFloat Val(0.0);
15590 return EvaluateFloat(E->getArg(0), Val, Info) &&
15591 Success(Val.isNaN() ? 1 : 0, E);
15592 }
15593
15594 case Builtin::BI__builtin_isnormal: {
15595 APFloat Val(0.0);
15596 return EvaluateFloat(E->getArg(0), Val, Info) &&
15597 Success(Val.isNormal() ? 1 : 0, E);
15598 }
15599
15600 case Builtin::BI__builtin_issubnormal: {
15601 APFloat Val(0.0);
15602 return EvaluateFloat(E->getArg(0), Val, Info) &&
15603 Success(Val.isDenormal() ? 1 : 0, E);
15604 }
15605
15606 case Builtin::BI__builtin_iszero: {
15607 APFloat Val(0.0);
15608 return EvaluateFloat(E->getArg(0), Val, Info) &&
15609 Success(Val.isZero() ? 1 : 0, E);
15610 }
15611
15612 case Builtin::BI__builtin_signbit:
15613 case Builtin::BI__builtin_signbitf:
15614 case Builtin::BI__builtin_signbitl: {
15615 APFloat Val(0.0);
15616 return EvaluateFloat(E->getArg(0), Val, Info) &&
15617 Success(Val.isNegative() ? 1 : 0, E);
15618 }
15619
15620 case Builtin::BI__builtin_isgreater:
15621 case Builtin::BI__builtin_isgreaterequal:
15622 case Builtin::BI__builtin_isless:
15623 case Builtin::BI__builtin_islessequal:
15624 case Builtin::BI__builtin_islessgreater:
15625 case Builtin::BI__builtin_isunordered: {
15626 APFloat LHS(0.0);
15627 APFloat RHS(0.0);
15628 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
15629 !EvaluateFloat(E->getArg(1), RHS, Info))
15630 return false;
15631
15632 return Success(
15633 [&] {
15634 switch (BuiltinOp) {
15635 case Builtin::BI__builtin_isgreater:
15636 return LHS > RHS;
15637 case Builtin::BI__builtin_isgreaterequal:
15638 return LHS >= RHS;
15639 case Builtin::BI__builtin_isless:
15640 return LHS < RHS;
15641 case Builtin::BI__builtin_islessequal:
15642 return LHS <= RHS;
15643 case Builtin::BI__builtin_islessgreater: {
15644 APFloat::cmpResult cmp = LHS.compare(RHS);
15645 return cmp == APFloat::cmpResult::cmpLessThan ||
15646 cmp == APFloat::cmpResult::cmpGreaterThan;
15647 }
15648 case Builtin::BI__builtin_isunordered:
15649 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
15650 default:
15651 llvm_unreachable("Unexpected builtin ID: Should be a floating "
15652 "point comparison function");
15653 }
15654 }()
15655 ? 1
15656 : 0,
15657 E);
15658 }
15659
15660 case Builtin::BI__builtin_issignaling: {
15661 APFloat Val(0.0);
15662 return EvaluateFloat(E->getArg(0), Val, Info) &&
15663 Success(Val.isSignaling() ? 1 : 0, E);
15664 }
15665
15666 case Builtin::BI__builtin_isfpclass: {
15667 APSInt MaskVal;
15668 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
15669 return false;
15670 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
15671 APFloat Val(0.0);
15672 return EvaluateFloat(E->getArg(0), Val, Info) &&
15673 Success((Val.classify() & Test) ? 1 : 0, E);
15674 }
15675
15676 case Builtin::BI__builtin_parity:
15677 case Builtin::BI__builtin_parityl:
15678 case Builtin::BI__builtin_parityll: {
15679 APSInt Val;
15680 if (!EvaluateInteger(E->getArg(0), Val, Info))
15681 return false;
15682
15683 return Success(Val.popcount() % 2, E);
15684 }
15685
15686 case Builtin::BI__builtin_abs:
15687 case Builtin::BI__builtin_labs:
15688 case Builtin::BI__builtin_llabs: {
15689 APSInt Val;
15690 if (!EvaluateInteger(E->getArg(0), Val, Info))
15691 return false;
15692 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
15693 /*IsUnsigned=*/false))
15694 return false;
15695 if (Val.isNegative())
15696 Val.negate();
15697 return Success(Val, E);
15698 }
15699
15700 case Builtin::BI__builtin_popcount:
15701 case Builtin::BI__builtin_popcountl:
15702 case Builtin::BI__builtin_popcountll:
15703 case Builtin::BI__builtin_popcountg:
15704 case Builtin::BI__builtin_elementwise_popcount:
15705 case Builtin::BI__popcnt16: // Microsoft variants of popcount
15706 case Builtin::BI__popcnt:
15707 case Builtin::BI__popcnt64: {
15708 APSInt Val;
15709 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
15710 APValue Vec;
15711 if (!EvaluateVector(E->getArg(0), Vec, Info))
15712 return false;
15713 Val = ConvertBoolVectorToInt(Vec);
15714 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
15715 return false;
15716 }
15717
15718 return Success(Val.popcount(), E);
15719 }
15720
15721 case Builtin::BI__builtin_rotateleft8:
15722 case Builtin::BI__builtin_rotateleft16:
15723 case Builtin::BI__builtin_rotateleft32:
15724 case Builtin::BI__builtin_rotateleft64:
15725 case Builtin::BI_rotl8: // Microsoft variants of rotate right
15726 case Builtin::BI_rotl16:
15727 case Builtin::BI_rotl:
15728 case Builtin::BI_lrotl:
15729 case Builtin::BI_rotl64: {
15730 APSInt Val, Amt;
15731 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15732 !EvaluateInteger(E->getArg(1), Amt, Info))
15733 return false;
15734
15735 return Success(Val.rotl(Amt), E);
15736 }
15737
15738 case Builtin::BI__builtin_rotateright8:
15739 case Builtin::BI__builtin_rotateright16:
15740 case Builtin::BI__builtin_rotateright32:
15741 case Builtin::BI__builtin_rotateright64:
15742 case Builtin::BI_rotr8: // Microsoft variants of rotate right
15743 case Builtin::BI_rotr16:
15744 case Builtin::BI_rotr:
15745 case Builtin::BI_lrotr:
15746 case Builtin::BI_rotr64: {
15747 APSInt Val, Amt;
15748 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
15749 !EvaluateInteger(E->getArg(1), Amt, Info))
15750 return false;
15751
15752 return Success(Val.rotr(Amt), E);
15753 }
15754
15755 case Builtin::BI__builtin_elementwise_add_sat: {
15756 APSInt LHS, RHS;
15757 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15758 !EvaluateInteger(E->getArg(1), RHS, Info))
15759 return false;
15760
15761 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
15762 return Success(APSInt(Result, !LHS.isSigned()), E);
15763 }
15764 case Builtin::BI__builtin_elementwise_sub_sat: {
15765 APSInt LHS, RHS;
15766 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15767 !EvaluateInteger(E->getArg(1), RHS, Info))
15768 return false;
15769
15770 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
15771 return Success(APSInt(Result, !LHS.isSigned()), E);
15772 }
15773 case Builtin::BI__builtin_elementwise_max: {
15774 APSInt LHS, RHS;
15775 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15776 !EvaluateInteger(E->getArg(1), RHS, Info))
15777 return false;
15778
15779 APInt Result = std::max(LHS, RHS);
15780 return Success(APSInt(Result, !LHS.isSigned()), E);
15781 }
15782 case Builtin::BI__builtin_elementwise_min: {
15783 APSInt LHS, RHS;
15784 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
15785 !EvaluateInteger(E->getArg(1), RHS, Info))
15786 return false;
15787
15788 APInt Result = std::min(LHS, RHS);
15789 return Success(APSInt(Result, !LHS.isSigned()), E);
15790 }
15791 case Builtin::BI__builtin_elementwise_fshl:
15792 case Builtin::BI__builtin_elementwise_fshr: {
15793 APSInt Hi, Lo, Shift;
15794 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
15795 !EvaluateInteger(E->getArg(1), Lo, Info) ||
15796 !EvaluateInteger(E->getArg(2), Shift, Info))
15797 return false;
15798
15799 switch (BuiltinOp) {
15800 case Builtin::BI__builtin_elementwise_fshl: {
15801 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
15802 return Success(Result, E);
15803 }
15804 case Builtin::BI__builtin_elementwise_fshr: {
15805 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
15806 return Success(Result, E);
15807 }
15808 }
15809 llvm_unreachable("Fully covered switch above");
15810 }
15811 case Builtin::BIstrlen:
15812 case Builtin::BIwcslen:
15813 // A call to strlen is not a constant expression.
15814 if (Info.getLangOpts().CPlusPlus11)
15815 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15816 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15817 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15818 else
15819 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15820 [[fallthrough]];
15821 case Builtin::BI__builtin_strlen:
15822 case Builtin::BI__builtin_wcslen: {
15823 // As an extension, we support __builtin_strlen() as a constant expression,
15824 // and support folding strlen() to a constant.
15825 uint64_t StrLen;
15826 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
15827 return Success(StrLen, E);
15828 return false;
15829 }
15830
15831 case Builtin::BIstrcmp:
15832 case Builtin::BIwcscmp:
15833 case Builtin::BIstrncmp:
15834 case Builtin::BIwcsncmp:
15835 case Builtin::BImemcmp:
15836 case Builtin::BIbcmp:
15837 case Builtin::BIwmemcmp:
15838 // A call to strlen is not a constant expression.
15839 if (Info.getLangOpts().CPlusPlus11)
15840 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
15841 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
15842 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
15843 else
15844 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
15845 [[fallthrough]];
15846 case Builtin::BI__builtin_strcmp:
15847 case Builtin::BI__builtin_wcscmp:
15848 case Builtin::BI__builtin_strncmp:
15849 case Builtin::BI__builtin_wcsncmp:
15850 case Builtin::BI__builtin_memcmp:
15851 case Builtin::BI__builtin_bcmp:
15852 case Builtin::BI__builtin_wmemcmp: {
15853 LValue String1, String2;
15854 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
15855 !EvaluatePointer(E->getArg(1), String2, Info))
15856 return false;
15857
15858 uint64_t MaxLength = uint64_t(-1);
15859 if (BuiltinOp != Builtin::BIstrcmp &&
15860 BuiltinOp != Builtin::BIwcscmp &&
15861 BuiltinOp != Builtin::BI__builtin_strcmp &&
15862 BuiltinOp != Builtin::BI__builtin_wcscmp) {
15863 APSInt N;
15864 if (!EvaluateInteger(E->getArg(2), N, Info))
15865 return false;
15866 MaxLength = N.getZExtValue();
15867 }
15868
15869 // Empty substrings compare equal by definition.
15870 if (MaxLength == 0u)
15871 return Success(0, E);
15872
15873 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15874 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
15875 String1.Designator.Invalid || String2.Designator.Invalid)
15876 return false;
15877
15878 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
15879 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
15880
15881 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
15882 BuiltinOp == Builtin::BIbcmp ||
15883 BuiltinOp == Builtin::BI__builtin_memcmp ||
15884 BuiltinOp == Builtin::BI__builtin_bcmp;
15885
15886 assert(IsRawByte ||
15887 (Info.Ctx.hasSameUnqualifiedType(
15888 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
15889 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
15890
15891 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
15892 // 'char8_t', but no other types.
15893 if (IsRawByte &&
15894 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
15895 // FIXME: Consider using our bit_cast implementation to support this.
15896 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
15897 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
15898 << CharTy2;
15899 return false;
15900 }
15901
15902 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
15903 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
15904 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
15905 Char1.isInt() && Char2.isInt();
15906 };
15907 const auto &AdvanceElems = [&] {
15908 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
15909 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
15910 };
15911
15912 bool StopAtNull =
15913 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
15914 BuiltinOp != Builtin::BIwmemcmp &&
15915 BuiltinOp != Builtin::BI__builtin_memcmp &&
15916 BuiltinOp != Builtin::BI__builtin_bcmp &&
15917 BuiltinOp != Builtin::BI__builtin_wmemcmp);
15918 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
15919 BuiltinOp == Builtin::BIwcsncmp ||
15920 BuiltinOp == Builtin::BIwmemcmp ||
15921 BuiltinOp == Builtin::BI__builtin_wcscmp ||
15922 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
15923 BuiltinOp == Builtin::BI__builtin_wmemcmp;
15924
15925 for (; MaxLength; --MaxLength) {
15926 APValue Char1, Char2;
15927 if (!ReadCurElems(Char1, Char2))
15928 return false;
15929 if (Char1.getInt().ne(Char2.getInt())) {
15930 if (IsWide) // wmemcmp compares with wchar_t signedness.
15931 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
15932 // memcmp always compares unsigned chars.
15933 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
15934 }
15935 if (StopAtNull && !Char1.getInt())
15936 return Success(0, E);
15937 assert(!(StopAtNull && !Char2.getInt()));
15938 if (!AdvanceElems())
15939 return false;
15940 }
15941 // We hit the strncmp / memcmp limit.
15942 return Success(0, E);
15943 }
15944
15945 case Builtin::BI__atomic_always_lock_free:
15946 case Builtin::BI__atomic_is_lock_free:
15947 case Builtin::BI__c11_atomic_is_lock_free: {
15948 APSInt SizeVal;
15949 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
15950 return false;
15951
15952 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
15953 // of two less than or equal to the maximum inline atomic width, we know it
15954 // is lock-free. If the size isn't a power of two, or greater than the
15955 // maximum alignment where we promote atomics, we know it is not lock-free
15956 // (at least not in the sense of atomic_is_lock_free). Otherwise,
15957 // the answer can only be determined at runtime; for example, 16-byte
15958 // atomics have lock-free implementations on some, but not all,
15959 // x86-64 processors.
15960
15961 // Check power-of-two.
15962 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
15963 if (Size.isPowerOfTwo()) {
15964 // Check against inlining width.
15965 unsigned InlineWidthBits =
15967 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
15968 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
15969 Size == CharUnits::One())
15970 return Success(1, E);
15971
15972 // If the pointer argument can be evaluated to a compile-time constant
15973 // integer (or nullptr), check if that value is appropriately aligned.
15974 const Expr *PtrArg = E->getArg(1);
15975 Expr::EvalResult ExprResult;
15976 APSInt IntResult;
15977 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
15978 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
15979 Info.Ctx) &&
15980 IntResult.isAligned(Size.getAsAlign()))
15981 return Success(1, E);
15982
15983 // Otherwise, check if the type's alignment against Size.
15984 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
15985 // Drop the potential implicit-cast to 'const volatile void*', getting
15986 // the underlying type.
15987 if (ICE->getCastKind() == CK_BitCast)
15988 PtrArg = ICE->getSubExpr();
15989 }
15990
15991 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
15992 QualType PointeeType = PtrTy->getPointeeType();
15993 if (!PointeeType->isIncompleteType() &&
15994 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
15995 // OK, we will inline operations on this object.
15996 return Success(1, E);
15997 }
15998 }
15999 }
16000 }
16001
16002 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
16003 Success(0, E) : Error(E);
16004 }
16005 case Builtin::BI__builtin_addcb:
16006 case Builtin::BI__builtin_addcs:
16007 case Builtin::BI__builtin_addc:
16008 case Builtin::BI__builtin_addcl:
16009 case Builtin::BI__builtin_addcll:
16010 case Builtin::BI__builtin_subcb:
16011 case Builtin::BI__builtin_subcs:
16012 case Builtin::BI__builtin_subc:
16013 case Builtin::BI__builtin_subcl:
16014 case Builtin::BI__builtin_subcll: {
16015 LValue CarryOutLValue;
16016 APSInt LHS, RHS, CarryIn, CarryOut, Result;
16017 QualType ResultType = E->getArg(0)->getType();
16018 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16019 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16020 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
16021 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
16022 return false;
16023 // Copy the number of bits and sign.
16024 Result = LHS;
16025 CarryOut = LHS;
16026
16027 bool FirstOverflowed = false;
16028 bool SecondOverflowed = false;
16029 switch (BuiltinOp) {
16030 default:
16031 llvm_unreachable("Invalid value for BuiltinOp");
16032 case Builtin::BI__builtin_addcb:
16033 case Builtin::BI__builtin_addcs:
16034 case Builtin::BI__builtin_addc:
16035 case Builtin::BI__builtin_addcl:
16036 case Builtin::BI__builtin_addcll:
16037 Result =
16038 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
16039 break;
16040 case Builtin::BI__builtin_subcb:
16041 case Builtin::BI__builtin_subcs:
16042 case Builtin::BI__builtin_subc:
16043 case Builtin::BI__builtin_subcl:
16044 case Builtin::BI__builtin_subcll:
16045 Result =
16046 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
16047 break;
16048 }
16049
16050 // It is possible for both overflows to happen but CGBuiltin uses an OR so
16051 // this is consistent.
16052 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
16053 APValue APV{CarryOut};
16054 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
16055 return false;
16056 return Success(Result, E);
16057 }
16058 case Builtin::BI__builtin_add_overflow:
16059 case Builtin::BI__builtin_sub_overflow:
16060 case Builtin::BI__builtin_mul_overflow:
16061 case Builtin::BI__builtin_sadd_overflow:
16062 case Builtin::BI__builtin_uadd_overflow:
16063 case Builtin::BI__builtin_uaddl_overflow:
16064 case Builtin::BI__builtin_uaddll_overflow:
16065 case Builtin::BI__builtin_usub_overflow:
16066 case Builtin::BI__builtin_usubl_overflow:
16067 case Builtin::BI__builtin_usubll_overflow:
16068 case Builtin::BI__builtin_umul_overflow:
16069 case Builtin::BI__builtin_umull_overflow:
16070 case Builtin::BI__builtin_umulll_overflow:
16071 case Builtin::BI__builtin_saddl_overflow:
16072 case Builtin::BI__builtin_saddll_overflow:
16073 case Builtin::BI__builtin_ssub_overflow:
16074 case Builtin::BI__builtin_ssubl_overflow:
16075 case Builtin::BI__builtin_ssubll_overflow:
16076 case Builtin::BI__builtin_smul_overflow:
16077 case Builtin::BI__builtin_smull_overflow:
16078 case Builtin::BI__builtin_smulll_overflow: {
16079 LValue ResultLValue;
16080 APSInt LHS, RHS;
16081
16082 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
16083 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16084 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16085 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
16086 return false;
16087
16088 APSInt Result;
16089 bool DidOverflow = false;
16090
16091 // If the types don't have to match, enlarge all 3 to the largest of them.
16092 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16093 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16094 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16095 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
16097 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
16099 uint64_t LHSSize = LHS.getBitWidth();
16100 uint64_t RHSSize = RHS.getBitWidth();
16101 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
16102 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
16103
16104 // Add an additional bit if the signedness isn't uniformly agreed to. We
16105 // could do this ONLY if there is a signed and an unsigned that both have
16106 // MaxBits, but the code to check that is pretty nasty. The issue will be
16107 // caught in the shrink-to-result later anyway.
16108 if (IsSigned && !AllSigned)
16109 ++MaxBits;
16110
16111 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
16112 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
16113 Result = APSInt(MaxBits, !IsSigned);
16114 }
16115
16116 // Find largest int.
16117 switch (BuiltinOp) {
16118 default:
16119 llvm_unreachable("Invalid value for BuiltinOp");
16120 case Builtin::BI__builtin_add_overflow:
16121 case Builtin::BI__builtin_sadd_overflow:
16122 case Builtin::BI__builtin_saddl_overflow:
16123 case Builtin::BI__builtin_saddll_overflow:
16124 case Builtin::BI__builtin_uadd_overflow:
16125 case Builtin::BI__builtin_uaddl_overflow:
16126 case Builtin::BI__builtin_uaddll_overflow:
16127 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
16128 : LHS.uadd_ov(RHS, DidOverflow);
16129 break;
16130 case Builtin::BI__builtin_sub_overflow:
16131 case Builtin::BI__builtin_ssub_overflow:
16132 case Builtin::BI__builtin_ssubl_overflow:
16133 case Builtin::BI__builtin_ssubll_overflow:
16134 case Builtin::BI__builtin_usub_overflow:
16135 case Builtin::BI__builtin_usubl_overflow:
16136 case Builtin::BI__builtin_usubll_overflow:
16137 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
16138 : LHS.usub_ov(RHS, DidOverflow);
16139 break;
16140 case Builtin::BI__builtin_mul_overflow:
16141 case Builtin::BI__builtin_smul_overflow:
16142 case Builtin::BI__builtin_smull_overflow:
16143 case Builtin::BI__builtin_smulll_overflow:
16144 case Builtin::BI__builtin_umul_overflow:
16145 case Builtin::BI__builtin_umull_overflow:
16146 case Builtin::BI__builtin_umulll_overflow:
16147 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
16148 : LHS.umul_ov(RHS, DidOverflow);
16149 break;
16150 }
16151
16152 // In the case where multiple sizes are allowed, truncate and see if
16153 // the values are the same.
16154 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16155 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16156 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16157 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
16158 // since it will give us the behavior of a TruncOrSelf in the case where
16159 // its parameter <= its size. We previously set Result to be at least the
16160 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
16161 // will work exactly like TruncOrSelf.
16162 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
16163 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
16164
16165 if (!APSInt::isSameValue(Temp, Result))
16166 DidOverflow = true;
16167 Result = Temp;
16168 }
16169
16170 APValue APV{Result};
16171 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16172 return false;
16173 return Success(DidOverflow, E);
16174 }
16175
16176 case Builtin::BI__builtin_reduce_add:
16177 case Builtin::BI__builtin_reduce_mul:
16178 case Builtin::BI__builtin_reduce_and:
16179 case Builtin::BI__builtin_reduce_or:
16180 case Builtin::BI__builtin_reduce_xor:
16181 case Builtin::BI__builtin_reduce_min:
16182 case Builtin::BI__builtin_reduce_max: {
16183 APValue Source;
16184 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
16185 return false;
16186
16187 unsigned SourceLen = Source.getVectorLength();
16188 APSInt Reduced = Source.getVectorElt(0).getInt();
16189 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
16190 switch (BuiltinOp) {
16191 default:
16192 return false;
16193 case Builtin::BI__builtin_reduce_add: {
16195 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16196 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
16197 return false;
16198 break;
16199 }
16200 case Builtin::BI__builtin_reduce_mul: {
16202 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16203 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
16204 return false;
16205 break;
16206 }
16207 case Builtin::BI__builtin_reduce_and: {
16208 Reduced &= Source.getVectorElt(EltNum).getInt();
16209 break;
16210 }
16211 case Builtin::BI__builtin_reduce_or: {
16212 Reduced |= Source.getVectorElt(EltNum).getInt();
16213 break;
16214 }
16215 case Builtin::BI__builtin_reduce_xor: {
16216 Reduced ^= Source.getVectorElt(EltNum).getInt();
16217 break;
16218 }
16219 case Builtin::BI__builtin_reduce_min: {
16220 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
16221 break;
16222 }
16223 case Builtin::BI__builtin_reduce_max: {
16224 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
16225 break;
16226 }
16227 }
16228 }
16229
16230 return Success(Reduced, E);
16231 }
16232
16233 case clang::X86::BI__builtin_ia32_addcarryx_u32:
16234 case clang::X86::BI__builtin_ia32_addcarryx_u64:
16235 case clang::X86::BI__builtin_ia32_subborrow_u32:
16236 case clang::X86::BI__builtin_ia32_subborrow_u64: {
16237 LValue ResultLValue;
16238 APSInt CarryIn, LHS, RHS;
16239 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
16240 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
16241 !EvaluateInteger(E->getArg(1), LHS, Info) ||
16242 !EvaluateInteger(E->getArg(2), RHS, Info) ||
16243 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
16244 return false;
16245
16246 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
16247 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
16248
16249 unsigned BitWidth = LHS.getBitWidth();
16250 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
16251 APInt ExResult =
16252 IsAdd
16253 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
16254 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
16255
16256 APInt Result = ExResult.extractBits(BitWidth, 0);
16257 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
16258
16259 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
16260 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16261 return false;
16262 return Success(CarryOut, E);
16263 }
16264
16265 case clang::X86::BI__builtin_ia32_movmskps:
16266 case clang::X86::BI__builtin_ia32_movmskpd:
16267 case clang::X86::BI__builtin_ia32_pmovmskb128:
16268 case clang::X86::BI__builtin_ia32_pmovmskb256:
16269 case clang::X86::BI__builtin_ia32_movmskps256:
16270 case clang::X86::BI__builtin_ia32_movmskpd256: {
16271 APValue Source;
16272 if (!Evaluate(Source, Info, E->getArg(0)))
16273 return false;
16274 unsigned SourceLen = Source.getVectorLength();
16275 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16276 QualType ElemQT = VT->getElementType();
16277 unsigned ResultLen = Info.Ctx.getTypeSize(
16278 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
16279 APInt Result(ResultLen, 0);
16280
16281 for (unsigned I = 0; I != SourceLen; ++I) {
16282 APInt Elem;
16283 if (ElemQT->isIntegerType()) {
16284 Elem = Source.getVectorElt(I).getInt();
16285 } else if (ElemQT->isRealFloatingType()) {
16286 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
16287 } else {
16288 return false;
16289 }
16290 Result.setBitVal(I, Elem.isNegative());
16291 }
16292 return Success(Result, E);
16293 }
16294
16295 case clang::X86::BI__builtin_ia32_bextr_u32:
16296 case clang::X86::BI__builtin_ia32_bextr_u64:
16297 case clang::X86::BI__builtin_ia32_bextri_u32:
16298 case clang::X86::BI__builtin_ia32_bextri_u64: {
16299 APSInt Val, Idx;
16300 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16301 !EvaluateInteger(E->getArg(1), Idx, Info))
16302 return false;
16303
16304 unsigned BitWidth = Val.getBitWidth();
16305 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
16306 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
16307 Length = Length > BitWidth ? BitWidth : Length;
16308
16309 // Handle out of bounds cases.
16310 if (Length == 0 || Shift >= BitWidth)
16311 return Success(0, E);
16312
16313 uint64_t Result = Val.getZExtValue() >> Shift;
16314 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
16315 return Success(Result, E);
16316 }
16317
16318 case clang::X86::BI__builtin_ia32_bzhi_si:
16319 case clang::X86::BI__builtin_ia32_bzhi_di: {
16320 APSInt Val, Idx;
16321 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16322 !EvaluateInteger(E->getArg(1), Idx, Info))
16323 return false;
16324
16325 unsigned BitWidth = Val.getBitWidth();
16326 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
16327 if (Index < BitWidth)
16328 Val.clearHighBits(BitWidth - Index);
16329 return Success(Val, E);
16330 }
16331
16332 case clang::X86::BI__builtin_ia32_ktestcqi:
16333 case clang::X86::BI__builtin_ia32_ktestchi:
16334 case clang::X86::BI__builtin_ia32_ktestcsi:
16335 case clang::X86::BI__builtin_ia32_ktestcdi: {
16336 APSInt A, B;
16337 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16338 !EvaluateInteger(E->getArg(1), B, Info))
16339 return false;
16340
16341 return Success((~A & B) == 0, E);
16342 }
16343
16344 case clang::X86::BI__builtin_ia32_ktestzqi:
16345 case clang::X86::BI__builtin_ia32_ktestzhi:
16346 case clang::X86::BI__builtin_ia32_ktestzsi:
16347 case clang::X86::BI__builtin_ia32_ktestzdi: {
16348 APSInt A, B;
16349 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16350 !EvaluateInteger(E->getArg(1), B, Info))
16351 return false;
16352
16353 return Success((A & B) == 0, E);
16354 }
16355
16356 case clang::X86::BI__builtin_ia32_kortestcqi:
16357 case clang::X86::BI__builtin_ia32_kortestchi:
16358 case clang::X86::BI__builtin_ia32_kortestcsi:
16359 case clang::X86::BI__builtin_ia32_kortestcdi: {
16360 APSInt A, B;
16361 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16362 !EvaluateInteger(E->getArg(1), B, Info))
16363 return false;
16364
16365 return Success(~(A | B) == 0, E);
16366 }
16367
16368 case clang::X86::BI__builtin_ia32_kortestzqi:
16369 case clang::X86::BI__builtin_ia32_kortestzhi:
16370 case clang::X86::BI__builtin_ia32_kortestzsi:
16371 case clang::X86::BI__builtin_ia32_kortestzdi: {
16372 APSInt A, B;
16373 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16374 !EvaluateInteger(E->getArg(1), B, Info))
16375 return false;
16376
16377 return Success((A | B) == 0, E);
16378 }
16379
16380 case clang::X86::BI__builtin_ia32_kunpckhi:
16381 case clang::X86::BI__builtin_ia32_kunpckdi:
16382 case clang::X86::BI__builtin_ia32_kunpcksi: {
16383 APSInt A, B;
16384 if (!EvaluateInteger(E->getArg(0), A, Info) ||
16385 !EvaluateInteger(E->getArg(1), B, Info))
16386 return false;
16387
16388 // Generic kunpack: extract lower half of each operand and concatenate
16389 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
16390 unsigned BW = A.getBitWidth();
16391 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
16392 return Success(Result, E);
16393 }
16394
16395 case clang::X86::BI__builtin_ia32_lzcnt_u16:
16396 case clang::X86::BI__builtin_ia32_lzcnt_u32:
16397 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
16398 APSInt Val;
16399 if (!EvaluateInteger(E->getArg(0), Val, Info))
16400 return false;
16401 return Success(Val.countLeadingZeros(), E);
16402 }
16403
16404 case clang::X86::BI__builtin_ia32_tzcnt_u16:
16405 case clang::X86::BI__builtin_ia32_tzcnt_u32:
16406 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
16407 APSInt Val;
16408 if (!EvaluateInteger(E->getArg(0), Val, Info))
16409 return false;
16410 return Success(Val.countTrailingZeros(), E);
16411 }
16412
16413 case clang::X86::BI__builtin_ia32_pdep_si:
16414 case clang::X86::BI__builtin_ia32_pdep_di: {
16415 APSInt Val, Msk;
16416 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16417 !EvaluateInteger(E->getArg(1), Msk, Info))
16418 return false;
16419
16420 unsigned BitWidth = Val.getBitWidth();
16421 APInt Result = APInt::getZero(BitWidth);
16422 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
16423 if (Msk[I])
16424 Result.setBitVal(I, Val[P++]);
16425 return Success(Result, E);
16426 }
16427
16428 case clang::X86::BI__builtin_ia32_pext_si:
16429 case clang::X86::BI__builtin_ia32_pext_di: {
16430 APSInt Val, Msk;
16431 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16432 !EvaluateInteger(E->getArg(1), Msk, Info))
16433 return false;
16434
16435 unsigned BitWidth = Val.getBitWidth();
16436 APInt Result = APInt::getZero(BitWidth);
16437 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
16438 if (Msk[I])
16439 Result.setBitVal(P++, Val[I]);
16440 return Success(Result, E);
16441 }
16442 case X86::BI__builtin_ia32_ptestz128:
16443 case X86::BI__builtin_ia32_ptestz256:
16444 case X86::BI__builtin_ia32_vtestzps:
16445 case X86::BI__builtin_ia32_vtestzps256:
16446 case X86::BI__builtin_ia32_vtestzpd:
16447 case X86::BI__builtin_ia32_vtestzpd256: {
16448 return EvalTestOp(
16449 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
16450 }
16451 case X86::BI__builtin_ia32_ptestc128:
16452 case X86::BI__builtin_ia32_ptestc256:
16453 case X86::BI__builtin_ia32_vtestcps:
16454 case X86::BI__builtin_ia32_vtestcps256:
16455 case X86::BI__builtin_ia32_vtestcpd:
16456 case X86::BI__builtin_ia32_vtestcpd256: {
16457 return EvalTestOp(
16458 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
16459 }
16460 case X86::BI__builtin_ia32_ptestnzc128:
16461 case X86::BI__builtin_ia32_ptestnzc256:
16462 case X86::BI__builtin_ia32_vtestnzcps:
16463 case X86::BI__builtin_ia32_vtestnzcps256:
16464 case X86::BI__builtin_ia32_vtestnzcpd:
16465 case X86::BI__builtin_ia32_vtestnzcpd256: {
16466 return EvalTestOp([](const APInt &A, const APInt &B) {
16467 return ((A & B) != 0) && ((~A & B) != 0);
16468 });
16469 }
16470 case X86::BI__builtin_ia32_kandqi:
16471 case X86::BI__builtin_ia32_kandhi:
16472 case X86::BI__builtin_ia32_kandsi:
16473 case X86::BI__builtin_ia32_kanddi: {
16474 return HandleMaskBinOp(
16475 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
16476 }
16477
16478 case X86::BI__builtin_ia32_kandnqi:
16479 case X86::BI__builtin_ia32_kandnhi:
16480 case X86::BI__builtin_ia32_kandnsi:
16481 case X86::BI__builtin_ia32_kandndi: {
16482 return HandleMaskBinOp(
16483 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
16484 }
16485
16486 case X86::BI__builtin_ia32_korqi:
16487 case X86::BI__builtin_ia32_korhi:
16488 case X86::BI__builtin_ia32_korsi:
16489 case X86::BI__builtin_ia32_kordi: {
16490 return HandleMaskBinOp(
16491 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
16492 }
16493
16494 case X86::BI__builtin_ia32_kxnorqi:
16495 case X86::BI__builtin_ia32_kxnorhi:
16496 case X86::BI__builtin_ia32_kxnorsi:
16497 case X86::BI__builtin_ia32_kxnordi: {
16498 return HandleMaskBinOp(
16499 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
16500 }
16501
16502 case X86::BI__builtin_ia32_kxorqi:
16503 case X86::BI__builtin_ia32_kxorhi:
16504 case X86::BI__builtin_ia32_kxorsi:
16505 case X86::BI__builtin_ia32_kxordi: {
16506 return HandleMaskBinOp(
16507 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
16508 }
16509
16510 case X86::BI__builtin_ia32_knotqi:
16511 case X86::BI__builtin_ia32_knothi:
16512 case X86::BI__builtin_ia32_knotsi:
16513 case X86::BI__builtin_ia32_knotdi: {
16514 APSInt Val;
16515 if (!EvaluateInteger(E->getArg(0), Val, Info))
16516 return false;
16517 APSInt Result = ~Val;
16518 return Success(APValue(Result), E);
16519 }
16520
16521 case X86::BI__builtin_ia32_kaddqi:
16522 case X86::BI__builtin_ia32_kaddhi:
16523 case X86::BI__builtin_ia32_kaddsi:
16524 case X86::BI__builtin_ia32_kadddi: {
16525 return HandleMaskBinOp(
16526 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
16527 }
16528
16529 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
16530 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
16531 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
16532 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
16533 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
16534 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
16535 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
16536 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
16537 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
16538 APValue Vec;
16539 APSInt IdxAPS;
16540 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
16541 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
16542 return false;
16543 unsigned N = Vec.getVectorLength();
16544 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
16545 return Success(Vec.getVectorElt(Idx).getInt(), E);
16546 }
16547
16548 case clang::X86::BI__builtin_ia32_cmpb128_mask:
16549 case clang::X86::BI__builtin_ia32_cmpw128_mask:
16550 case clang::X86::BI__builtin_ia32_cmpd128_mask:
16551 case clang::X86::BI__builtin_ia32_cmpq128_mask:
16552 case clang::X86::BI__builtin_ia32_cmpb256_mask:
16553 case clang::X86::BI__builtin_ia32_cmpw256_mask:
16554 case clang::X86::BI__builtin_ia32_cmpd256_mask:
16555 case clang::X86::BI__builtin_ia32_cmpq256_mask:
16556 case clang::X86::BI__builtin_ia32_cmpb512_mask:
16557 case clang::X86::BI__builtin_ia32_cmpw512_mask:
16558 case clang::X86::BI__builtin_ia32_cmpd512_mask:
16559 case clang::X86::BI__builtin_ia32_cmpq512_mask:
16560 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
16561 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
16562 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
16563 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
16564 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
16565 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
16566 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
16567 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
16568 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
16569 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
16570 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
16571 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
16572 assert(E->getNumArgs() == 4);
16573
16574 bool IsUnsigned =
16575 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
16576 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpq512_mask);
16577
16578 APValue LHS, RHS;
16579 APSInt Mask, Opcode;
16580 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
16581 !EvaluateVector(E->getArg(1), RHS, Info) ||
16582 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
16583 !EvaluateInteger(E->getArg(3), Mask, Info))
16584 return false;
16585
16586 assert(LHS.getVectorLength() == RHS.getVectorLength());
16587
16588 unsigned VectorLen = LHS.getVectorLength();
16589 unsigned RetWidth = Mask.getBitWidth();
16590
16591 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
16592
16593 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
16594 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
16595 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
16596 bool Result = false;
16597
16598 switch (Opcode.getExtValue() & 0x7) {
16599 case 0: // _MM_CMPINT_EQ
16600 Result = (A == B);
16601 break;
16602 case 1: // _MM_CMPINT_LT
16603 Result = IsUnsigned ? A.ult(B) : A.slt(B);
16604 break;
16605 case 2: // _MM_CMPINT_LE
16606 Result = IsUnsigned ? A.ule(B) : A.sle(B);
16607 break;
16608 case 3: // _MM_CMPINT_FALSE
16609 Result = false;
16610 break;
16611 case 4: // _MM_CMPINT_NE
16612 Result = (A != B);
16613 break;
16614 case 5: // _MM_CMPINT_NLT (>=)
16615 Result = IsUnsigned ? A.uge(B) : A.sge(B);
16616 break;
16617 case 6: // _MM_CMPINT_NLE (>)
16618 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
16619 break;
16620 case 7: // _MM_CMPINT_TRUE
16621 Result = true;
16622 break;
16623 }
16624
16625 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
16626 }
16627
16628 return Success(APValue(RetMask), E);
16629 }
16630 }
16631}
16632
16633/// Determine whether this is a pointer past the end of the complete
16634/// object referred to by the lvalue.
16636 const LValue &LV) {
16637 // A null pointer can be viewed as being "past the end" but we don't
16638 // choose to look at it that way here.
16639 if (!LV.getLValueBase())
16640 return false;
16641
16642 // If the designator is valid and refers to a subobject, we're not pointing
16643 // past the end.
16644 if (!LV.getLValueDesignator().Invalid &&
16645 !LV.getLValueDesignator().isOnePastTheEnd())
16646 return false;
16647
16648 // A pointer to an incomplete type might be past-the-end if the type's size is
16649 // zero. We cannot tell because the type is incomplete.
16650 QualType Ty = getType(LV.getLValueBase());
16651 if (Ty->isIncompleteType())
16652 return true;
16653
16654 // Can't be past the end of an invalid object.
16655 if (LV.getLValueDesignator().Invalid)
16656 return false;
16657
16658 // We're a past-the-end pointer if we point to the byte after the object,
16659 // no matter what our type or path is.
16660 auto Size = Ctx.getTypeSizeInChars(Ty);
16661 return LV.getLValueOffset() == Size;
16662}
16663
16664namespace {
16665
16666/// Data recursive integer evaluator of certain binary operators.
16667///
16668/// We use a data recursive algorithm for binary operators so that we are able
16669/// to handle extreme cases of chained binary operators without causing stack
16670/// overflow.
16671class DataRecursiveIntBinOpEvaluator {
16672 struct EvalResult {
16673 APValue Val;
16674 bool Failed = false;
16675
16676 EvalResult() = default;
16677
16678 void swap(EvalResult &RHS) {
16679 Val.swap(RHS.Val);
16680 Failed = RHS.Failed;
16681 RHS.Failed = false;
16682 }
16683 };
16684
16685 struct Job {
16686 const Expr *E;
16687 EvalResult LHSResult; // meaningful only for binary operator expression.
16688 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
16689
16690 Job() = default;
16691 Job(Job &&) = default;
16692
16693 void startSpeculativeEval(EvalInfo &Info) {
16694 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
16695 }
16696
16697 private:
16698 SpeculativeEvaluationRAII SpecEvalRAII;
16699 };
16700
16701 SmallVector<Job, 16> Queue;
16702
16703 IntExprEvaluator &IntEval;
16704 EvalInfo &Info;
16705 APValue &FinalResult;
16706
16707public:
16708 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
16709 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
16710
16711 /// True if \param E is a binary operator that we are going to handle
16712 /// data recursively.
16713 /// We handle binary operators that are comma, logical, or that have operands
16714 /// with integral or enumeration type.
16715 static bool shouldEnqueue(const BinaryOperator *E) {
16716 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
16720 }
16721
16722 bool Traverse(const BinaryOperator *E) {
16723 enqueue(E);
16724 EvalResult PrevResult;
16725 while (!Queue.empty())
16726 process(PrevResult);
16727
16728 if (PrevResult.Failed) return false;
16729
16730 FinalResult.swap(PrevResult.Val);
16731 return true;
16732 }
16733
16734private:
16735 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
16736 return IntEval.Success(Value, E, Result);
16737 }
16738 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
16739 return IntEval.Success(Value, E, Result);
16740 }
16741 bool Error(const Expr *E) {
16742 return IntEval.Error(E);
16743 }
16744 bool Error(const Expr *E, diag::kind D) {
16745 return IntEval.Error(E, D);
16746 }
16747
16748 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
16749 return Info.CCEDiag(E, D);
16750 }
16751
16752 // Returns true if visiting the RHS is necessary, false otherwise.
16753 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
16754 bool &SuppressRHSDiags);
16755
16756 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
16757 const BinaryOperator *E, APValue &Result);
16758
16759 void EvaluateExpr(const Expr *E, EvalResult &Result) {
16760 Result.Failed = !Evaluate(Result.Val, Info, E);
16761 if (Result.Failed)
16762 Result.Val = APValue();
16763 }
16764
16765 void process(EvalResult &Result);
16766
16767 void enqueue(const Expr *E) {
16768 E = E->IgnoreParens();
16769 Queue.resize(Queue.size()+1);
16770 Queue.back().E = E;
16771 Queue.back().Kind = Job::AnyExprKind;
16772 }
16773};
16774
16775}
16776
16777bool DataRecursiveIntBinOpEvaluator::
16778 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
16779 bool &SuppressRHSDiags) {
16780 if (E->getOpcode() == BO_Comma) {
16781 // Ignore LHS but note if we could not evaluate it.
16782 if (LHSResult.Failed)
16783 return Info.noteSideEffect();
16784 return true;
16785 }
16786
16787 if (E->isLogicalOp()) {
16788 bool LHSAsBool;
16789 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
16790 // We were able to evaluate the LHS, see if we can get away with not
16791 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
16792 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
16793 Success(LHSAsBool, E, LHSResult.Val);
16794 return false; // Ignore RHS
16795 }
16796 } else {
16797 LHSResult.Failed = true;
16798
16799 // Since we weren't able to evaluate the left hand side, it
16800 // might have had side effects.
16801 if (!Info.noteSideEffect())
16802 return false;
16803
16804 // We can't evaluate the LHS; however, sometimes the result
16805 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16806 // Don't ignore RHS and suppress diagnostics from this arm.
16807 SuppressRHSDiags = true;
16808 }
16809
16810 return true;
16811 }
16812
16813 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16815
16816 if (LHSResult.Failed && !Info.noteFailure())
16817 return false; // Ignore RHS;
16818
16819 return true;
16820}
16821
16822static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
16823 bool IsSub) {
16824 // Compute the new offset in the appropriate width, wrapping at 64 bits.
16825 // FIXME: When compiling for a 32-bit target, we should use 32-bit
16826 // offsets.
16827 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
16828 CharUnits &Offset = LVal.getLValueOffset();
16829 uint64_t Offset64 = Offset.getQuantity();
16830 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
16831 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
16832 : Offset64 + Index64);
16833}
16834
16835bool DataRecursiveIntBinOpEvaluator::
16836 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
16837 const BinaryOperator *E, APValue &Result) {
16838 if (E->getOpcode() == BO_Comma) {
16839 if (RHSResult.Failed)
16840 return false;
16841 Result = RHSResult.Val;
16842 return true;
16843 }
16844
16845 if (E->isLogicalOp()) {
16846 bool lhsResult, rhsResult;
16847 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
16848 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
16849
16850 if (LHSIsOK) {
16851 if (RHSIsOK) {
16852 if (E->getOpcode() == BO_LOr)
16853 return Success(lhsResult || rhsResult, E, Result);
16854 else
16855 return Success(lhsResult && rhsResult, E, Result);
16856 }
16857 } else {
16858 if (RHSIsOK) {
16859 // We can't evaluate the LHS; however, sometimes the result
16860 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
16861 if (rhsResult == (E->getOpcode() == BO_LOr))
16862 return Success(rhsResult, E, Result);
16863 }
16864 }
16865
16866 return false;
16867 }
16868
16869 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
16871
16872 if (LHSResult.Failed || RHSResult.Failed)
16873 return false;
16874
16875 const APValue &LHSVal = LHSResult.Val;
16876 const APValue &RHSVal = RHSResult.Val;
16877
16878 // Handle cases like (unsigned long)&a + 4.
16879 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
16880 Result = LHSVal;
16881 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
16882 return true;
16883 }
16884
16885 // Handle cases like 4 + (unsigned long)&a
16886 if (E->getOpcode() == BO_Add &&
16887 RHSVal.isLValue() && LHSVal.isInt()) {
16888 Result = RHSVal;
16889 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
16890 return true;
16891 }
16892
16893 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
16894 // Handle (intptr_t)&&A - (intptr_t)&&B.
16895 if (!LHSVal.getLValueOffset().isZero() ||
16896 !RHSVal.getLValueOffset().isZero())
16897 return false;
16898 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
16899 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
16900 if (!LHSExpr || !RHSExpr)
16901 return false;
16902 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
16903 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
16904 if (!LHSAddrExpr || !RHSAddrExpr)
16905 return false;
16906 // Make sure both labels come from the same function.
16907 if (LHSAddrExpr->getLabel()->getDeclContext() !=
16908 RHSAddrExpr->getLabel()->getDeclContext())
16909 return false;
16910 Result = APValue(LHSAddrExpr, RHSAddrExpr);
16911 return true;
16912 }
16913
16914 // All the remaining cases expect both operands to be an integer
16915 if (!LHSVal.isInt() || !RHSVal.isInt())
16916 return Error(E);
16917
16918 // Set up the width and signedness manually, in case it can't be deduced
16919 // from the operation we're performing.
16920 // FIXME: Don't do this in the cases where we can deduce it.
16921 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
16923 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
16924 RHSVal.getInt(), Value))
16925 return false;
16926 return Success(Value, E, Result);
16927}
16928
16929void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
16930 Job &job = Queue.back();
16931
16932 switch (job.Kind) {
16933 case Job::AnyExprKind: {
16934 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
16935 if (shouldEnqueue(Bop)) {
16936 job.Kind = Job::BinOpKind;
16937 enqueue(Bop->getLHS());
16938 return;
16939 }
16940 }
16941
16942 EvaluateExpr(job.E, Result);
16943 Queue.pop_back();
16944 return;
16945 }
16946
16947 case Job::BinOpKind: {
16948 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16949 bool SuppressRHSDiags = false;
16950 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
16951 Queue.pop_back();
16952 return;
16953 }
16954 if (SuppressRHSDiags)
16955 job.startSpeculativeEval(Info);
16956 job.LHSResult.swap(Result);
16957 job.Kind = Job::BinOpVisitedLHSKind;
16958 enqueue(Bop->getRHS());
16959 return;
16960 }
16961
16962 case Job::BinOpVisitedLHSKind: {
16963 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
16964 EvalResult RHS;
16965 RHS.swap(Result);
16966 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
16967 Queue.pop_back();
16968 return;
16969 }
16970 }
16971
16972 llvm_unreachable("Invalid Job::Kind!");
16973}
16974
16975namespace {
16976enum class CmpResult {
16977 Unequal,
16978 Less,
16979 Equal,
16980 Greater,
16981 Unordered,
16982};
16983}
16984
16985template <class SuccessCB, class AfterCB>
16986static bool
16988 SuccessCB &&Success, AfterCB &&DoAfter) {
16989 assert(!E->isValueDependent());
16990 assert(E->isComparisonOp() && "expected comparison operator");
16991 assert((E->getOpcode() == BO_Cmp ||
16993 "unsupported binary expression evaluation");
16994 auto Error = [&](const Expr *E) {
16995 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16996 return false;
16997 };
16998
16999 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
17000 bool IsEquality = E->isEqualityOp();
17001
17002 QualType LHSTy = E->getLHS()->getType();
17003 QualType RHSTy = E->getRHS()->getType();
17004
17005 if (LHSTy->isIntegralOrEnumerationType() &&
17006 RHSTy->isIntegralOrEnumerationType()) {
17007 APSInt LHS, RHS;
17008 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
17009 if (!LHSOK && !Info.noteFailure())
17010 return false;
17011 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
17012 return false;
17013 if (LHS < RHS)
17014 return Success(CmpResult::Less, E);
17015 if (LHS > RHS)
17016 return Success(CmpResult::Greater, E);
17017 return Success(CmpResult::Equal, E);
17018 }
17019
17020 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
17021 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
17022 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
17023
17024 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
17025 if (!LHSOK && !Info.noteFailure())
17026 return false;
17027 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
17028 return false;
17029 if (LHSFX < RHSFX)
17030 return Success(CmpResult::Less, E);
17031 if (LHSFX > RHSFX)
17032 return Success(CmpResult::Greater, E);
17033 return Success(CmpResult::Equal, E);
17034 }
17035
17036 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
17037 ComplexValue LHS, RHS;
17038 bool LHSOK;
17039 if (E->isAssignmentOp()) {
17040 LValue LV;
17041 EvaluateLValue(E->getLHS(), LV, Info);
17042 LHSOK = false;
17043 } else if (LHSTy->isRealFloatingType()) {
17044 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
17045 if (LHSOK) {
17046 LHS.makeComplexFloat();
17047 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
17048 }
17049 } else {
17050 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
17051 }
17052 if (!LHSOK && !Info.noteFailure())
17053 return false;
17054
17055 if (E->getRHS()->getType()->isRealFloatingType()) {
17056 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
17057 return false;
17058 RHS.makeComplexFloat();
17059 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
17060 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
17061 return false;
17062
17063 if (LHS.isComplexFloat()) {
17064 APFloat::cmpResult CR_r =
17065 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
17066 APFloat::cmpResult CR_i =
17067 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
17068 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
17069 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17070 } else {
17071 assert(IsEquality && "invalid complex comparison");
17072 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
17073 LHS.getComplexIntImag() == RHS.getComplexIntImag();
17074 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17075 }
17076 }
17077
17078 if (LHSTy->isRealFloatingType() &&
17079 RHSTy->isRealFloatingType()) {
17080 APFloat RHS(0.0), LHS(0.0);
17081
17082 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
17083 if (!LHSOK && !Info.noteFailure())
17084 return false;
17085
17086 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
17087 return false;
17088
17089 assert(E->isComparisonOp() && "Invalid binary operator!");
17090 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
17091 if (!Info.InConstantContext &&
17092 APFloatCmpResult == APFloat::cmpUnordered &&
17094 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
17095 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
17096 return false;
17097 }
17098 auto GetCmpRes = [&]() {
17099 switch (APFloatCmpResult) {
17100 case APFloat::cmpEqual:
17101 return CmpResult::Equal;
17102 case APFloat::cmpLessThan:
17103 return CmpResult::Less;
17104 case APFloat::cmpGreaterThan:
17105 return CmpResult::Greater;
17106 case APFloat::cmpUnordered:
17107 return CmpResult::Unordered;
17108 }
17109 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
17110 };
17111 return Success(GetCmpRes(), E);
17112 }
17113
17114 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
17115 LValue LHSValue, RHSValue;
17116
17117 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
17118 if (!LHSOK && !Info.noteFailure())
17119 return false;
17120
17121 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17122 return false;
17123
17124 // Reject differing bases from the normal codepath; we special-case
17125 // comparisons to null.
17126 if (!HasSameBase(LHSValue, RHSValue)) {
17127 // Bail out early if we're checking potential constant expression.
17128 // Otherwise, prefer to diagnose other issues.
17129 if (Info.checkingPotentialConstantExpression() &&
17130 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
17131 return false;
17132 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
17133 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
17134 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
17135 Info.FFDiag(E, DiagID)
17136 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
17137 return false;
17138 };
17139 // Inequalities and subtractions between unrelated pointers have
17140 // unspecified or undefined behavior.
17141 if (!IsEquality)
17142 return DiagComparison(
17143 diag::note_constexpr_pointer_comparison_unspecified);
17144 // A constant address may compare equal to the address of a symbol.
17145 // The one exception is that address of an object cannot compare equal
17146 // to a null pointer constant.
17147 // TODO: Should we restrict this to actual null pointers, and exclude the
17148 // case of zero cast to pointer type?
17149 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
17150 (!RHSValue.Base && !RHSValue.Offset.isZero()))
17151 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
17152 !RHSValue.Base);
17153 // C++2c [intro.object]/10:
17154 // Two objects [...] may have the same address if [...] they are both
17155 // potentially non-unique objects.
17156 // C++2c [intro.object]/9:
17157 // An object is potentially non-unique if it is a string literal object,
17158 // the backing array of an initializer list, or a subobject thereof.
17159 //
17160 // This makes the comparison result unspecified, so it's not a constant
17161 // expression.
17162 //
17163 // TODO: Do we need to handle the initializer list case here?
17164 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
17165 return DiagComparison(diag::note_constexpr_literal_comparison);
17166 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
17167 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
17168 !IsOpaqueConstantCall(LHSValue));
17169 // We can't tell whether weak symbols will end up pointing to the same
17170 // object.
17171 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
17172 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
17173 !IsWeakLValue(LHSValue));
17174 // We can't compare the address of the start of one object with the
17175 // past-the-end address of another object, per C++ DR1652.
17176 if (LHSValue.Base && LHSValue.Offset.isZero() &&
17177 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
17178 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17179 true);
17180 if (RHSValue.Base && RHSValue.Offset.isZero() &&
17181 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
17182 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17183 false);
17184 // We can't tell whether an object is at the same address as another
17185 // zero sized object.
17186 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
17187 (LHSValue.Base && isZeroSized(RHSValue)))
17188 return DiagComparison(
17189 diag::note_constexpr_pointer_comparison_zero_sized);
17190 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
17191 return DiagComparison(
17192 diag::note_constexpr_pointer_comparison_unspecified);
17193 // FIXME: Verify both variables are live.
17194 return Success(CmpResult::Unequal, E);
17195 }
17196
17197 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
17198 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
17199
17200 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
17201 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
17202
17203 // C++11 [expr.rel]p2:
17204 // - If two pointers point to non-static data members of the same object,
17205 // or to subobjects or array elements fo such members, recursively, the
17206 // pointer to the later declared member compares greater provided the
17207 // two members have the same access control and provided their class is
17208 // not a union.
17209 // [...]
17210 // - Otherwise pointer comparisons are unspecified.
17211 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
17212 bool WasArrayIndex;
17213 unsigned Mismatch = FindDesignatorMismatch(
17214 LHSValue.Base.isNull() ? QualType()
17215 : getType(LHSValue.Base).getNonReferenceType(),
17216 LHSDesignator, RHSDesignator, WasArrayIndex);
17217 // At the point where the designators diverge, the comparison has a
17218 // specified value if:
17219 // - we are comparing array indices
17220 // - we are comparing fields of a union, or fields with the same access
17221 // Otherwise, the result is unspecified and thus the comparison is not a
17222 // constant expression.
17223 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
17224 Mismatch < RHSDesignator.Entries.size()) {
17225 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
17226 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
17227 if (!LF && !RF)
17228 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
17229 else if (!LF)
17230 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
17231 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
17232 << RF->getParent() << RF;
17233 else if (!RF)
17234 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
17235 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
17236 << LF->getParent() << LF;
17237 else if (!LF->getParent()->isUnion() &&
17238 LF->getAccess() != RF->getAccess())
17239 Info.CCEDiag(E,
17240 diag::note_constexpr_pointer_comparison_differing_access)
17241 << LF << LF->getAccess() << RF << RF->getAccess()
17242 << LF->getParent();
17243 }
17244 }
17245
17246 // The comparison here must be unsigned, and performed with the same
17247 // width as the pointer.
17248 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
17249 uint64_t CompareLHS = LHSOffset.getQuantity();
17250 uint64_t CompareRHS = RHSOffset.getQuantity();
17251 assert(PtrSize <= 64 && "Unexpected pointer width");
17252 uint64_t Mask = ~0ULL >> (64 - PtrSize);
17253 CompareLHS &= Mask;
17254 CompareRHS &= Mask;
17255
17256 // If there is a base and this is a relational operator, we can only
17257 // compare pointers within the object in question; otherwise, the result
17258 // depends on where the object is located in memory.
17259 if (!LHSValue.Base.isNull() && IsRelational) {
17260 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
17261 if (BaseTy->isIncompleteType())
17262 return Error(E);
17263 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
17264 uint64_t OffsetLimit = Size.getQuantity();
17265 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
17266 return Error(E);
17267 }
17268
17269 if (CompareLHS < CompareRHS)
17270 return Success(CmpResult::Less, E);
17271 if (CompareLHS > CompareRHS)
17272 return Success(CmpResult::Greater, E);
17273 return Success(CmpResult::Equal, E);
17274 }
17275
17276 if (LHSTy->isMemberPointerType()) {
17277 assert(IsEquality && "unexpected member pointer operation");
17278 assert(RHSTy->isMemberPointerType() && "invalid comparison");
17279
17280 MemberPtr LHSValue, RHSValue;
17281
17282 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
17283 if (!LHSOK && !Info.noteFailure())
17284 return false;
17285
17286 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17287 return false;
17288
17289 // If either operand is a pointer to a weak function, the comparison is not
17290 // constant.
17291 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
17292 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
17293 << LHSValue.getDecl();
17294 return false;
17295 }
17296 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
17297 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
17298 << RHSValue.getDecl();
17299 return false;
17300 }
17301
17302 // C++11 [expr.eq]p2:
17303 // If both operands are null, they compare equal. Otherwise if only one is
17304 // null, they compare unequal.
17305 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
17306 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
17307 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
17308 }
17309
17310 // Otherwise if either is a pointer to a virtual member function, the
17311 // result is unspecified.
17312 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
17313 if (MD->isVirtual())
17314 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
17315 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
17316 if (MD->isVirtual())
17317 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
17318
17319 // Otherwise they compare equal if and only if they would refer to the
17320 // same member of the same most derived object or the same subobject if
17321 // they were dereferenced with a hypothetical object of the associated
17322 // class type.
17323 bool Equal = LHSValue == RHSValue;
17324 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
17325 }
17326
17327 if (LHSTy->isNullPtrType()) {
17328 assert(E->isComparisonOp() && "unexpected nullptr operation");
17329 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
17330 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
17331 // are compared, the result is true of the operator is <=, >= or ==, and
17332 // false otherwise.
17333 LValue Res;
17334 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
17335 !EvaluatePointer(E->getRHS(), Res, Info))
17336 return false;
17337 return Success(CmpResult::Equal, E);
17338 }
17339
17340 return DoAfter();
17341}
17342
17343bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
17344 if (!CheckLiteralType(Info, E))
17345 return false;
17346
17347 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
17349 switch (CR) {
17350 case CmpResult::Unequal:
17351 llvm_unreachable("should never produce Unequal for three-way comparison");
17352 case CmpResult::Less:
17353 CCR = ComparisonCategoryResult::Less;
17354 break;
17355 case CmpResult::Equal:
17356 CCR = ComparisonCategoryResult::Equal;
17357 break;
17358 case CmpResult::Greater:
17359 CCR = ComparisonCategoryResult::Greater;
17360 break;
17361 case CmpResult::Unordered:
17362 CCR = ComparisonCategoryResult::Unordered;
17363 break;
17364 }
17365 // Evaluation succeeded. Lookup the information for the comparison category
17366 // type and fetch the VarDecl for the result.
17367 const ComparisonCategoryInfo &CmpInfo =
17368 Info.Ctx.CompCategories.getInfoForType(E->getType());
17369 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
17370 // Check and evaluate the result as a constant expression.
17371 LValue LV;
17372 LV.set(VD);
17373 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
17374 return false;
17375 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
17376 ConstantExprKind::Normal);
17377 };
17378 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
17379 return ExprEvaluatorBaseTy::VisitBinCmp(E);
17380 });
17381}
17382
17383bool RecordExprEvaluator::VisitCXXParenListInitExpr(
17384 const CXXParenListInitExpr *E) {
17385 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
17386}
17387
17388bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
17389 // We don't support assignment in C. C++ assignments don't get here because
17390 // assignment is an lvalue in C++.
17391 if (E->isAssignmentOp()) {
17392 Error(E);
17393 if (!Info.noteFailure())
17394 return false;
17395 }
17396
17397 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
17398 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
17399
17400 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
17402 "DataRecursiveIntBinOpEvaluator should have handled integral types");
17403
17404 if (E->isComparisonOp()) {
17405 // Evaluate builtin binary comparisons by evaluating them as three-way
17406 // comparisons and then translating the result.
17407 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
17408 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
17409 "should only produce Unequal for equality comparisons");
17410 bool IsEqual = CR == CmpResult::Equal,
17411 IsLess = CR == CmpResult::Less,
17412 IsGreater = CR == CmpResult::Greater;
17413 auto Op = E->getOpcode();
17414 switch (Op) {
17415 default:
17416 llvm_unreachable("unsupported binary operator");
17417 case BO_EQ:
17418 case BO_NE:
17419 return Success(IsEqual == (Op == BO_EQ), E);
17420 case BO_LT:
17421 return Success(IsLess, E);
17422 case BO_GT:
17423 return Success(IsGreater, E);
17424 case BO_LE:
17425 return Success(IsEqual || IsLess, E);
17426 case BO_GE:
17427 return Success(IsEqual || IsGreater, E);
17428 }
17429 };
17430 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
17431 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17432 });
17433 }
17434
17435 QualType LHSTy = E->getLHS()->getType();
17436 QualType RHSTy = E->getRHS()->getType();
17437
17438 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
17439 E->getOpcode() == BO_Sub) {
17440 LValue LHSValue, RHSValue;
17441
17442 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
17443 if (!LHSOK && !Info.noteFailure())
17444 return false;
17445
17446 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17447 return false;
17448
17449 // Reject differing bases from the normal codepath; we special-case
17450 // comparisons to null.
17451 if (!HasSameBase(LHSValue, RHSValue)) {
17452 if (Info.checkingPotentialConstantExpression() &&
17453 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
17454 return false;
17455
17456 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
17457 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
17458
17459 auto DiagArith = [&](unsigned DiagID) {
17460 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
17461 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
17462 Info.FFDiag(E, DiagID) << LHS << RHS;
17463 if (LHSExpr && LHSExpr == RHSExpr)
17464 Info.Note(LHSExpr->getExprLoc(),
17465 diag::note_constexpr_repeated_literal_eval)
17466 << LHSExpr->getSourceRange();
17467 return false;
17468 };
17469
17470 if (!LHSExpr || !RHSExpr)
17471 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
17472
17473 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
17474 return DiagArith(diag::note_constexpr_literal_arith);
17475
17476 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
17477 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
17478 if (!LHSAddrExpr || !RHSAddrExpr)
17479 return Error(E);
17480 // Make sure both labels come from the same function.
17481 if (LHSAddrExpr->getLabel()->getDeclContext() !=
17482 RHSAddrExpr->getLabel()->getDeclContext())
17483 return Error(E);
17484 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
17485 }
17486 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
17487 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
17488
17489 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
17490 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
17491
17492 // C++11 [expr.add]p6:
17493 // Unless both pointers point to elements of the same array object, or
17494 // one past the last element of the array object, the behavior is
17495 // undefined.
17496 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
17497 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
17498 RHSDesignator))
17499 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
17500
17501 QualType Type = E->getLHS()->getType();
17502 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
17503
17504 CharUnits ElementSize;
17505 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
17506 return false;
17507
17508 // As an extension, a type may have zero size (empty struct or union in
17509 // C, array of zero length). Pointer subtraction in such cases has
17510 // undefined behavior, so is not constant.
17511 if (ElementSize.isZero()) {
17512 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
17513 << ElementType;
17514 return false;
17515 }
17516
17517 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
17518 // and produce incorrect results when it overflows. Such behavior
17519 // appears to be non-conforming, but is common, so perhaps we should
17520 // assume the standard intended for such cases to be undefined behavior
17521 // and check for them.
17522
17523 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
17524 // overflow in the final conversion to ptrdiff_t.
17525 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
17526 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
17527 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
17528 false);
17529 APSInt TrueResult = (LHS - RHS) / ElemSize;
17530 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
17531
17532 if (Result.extend(65) != TrueResult &&
17533 !HandleOverflow(Info, E, TrueResult, E->getType()))
17534 return false;
17535 return Success(Result, E);
17536 }
17537
17538 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
17539}
17540
17541/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
17542/// a result as the expression's type.
17543bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
17544 const UnaryExprOrTypeTraitExpr *E) {
17545 switch(E->getKind()) {
17546 case UETT_PreferredAlignOf:
17547 case UETT_AlignOf: {
17548 if (E->isArgumentType())
17549 return Success(
17550 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
17551 else
17552 return Success(
17553 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
17554 }
17555
17556 case UETT_PtrAuthTypeDiscriminator: {
17557 if (E->getArgumentType()->isDependentType())
17558 return false;
17559 return Success(
17561 }
17562 case UETT_VecStep: {
17563 QualType Ty = E->getTypeOfArgument();
17564
17565 if (Ty->isVectorType()) {
17566 unsigned n = Ty->castAs<VectorType>()->getNumElements();
17567
17568 // The vec_step built-in functions that take a 3-component
17569 // vector return 4. (OpenCL 1.1 spec 6.11.12)
17570 if (n == 3)
17571 n = 4;
17572
17573 return Success(n, E);
17574 } else
17575 return Success(1, E);
17576 }
17577
17578 case UETT_DataSizeOf:
17579 case UETT_SizeOf: {
17580 QualType SrcTy = E->getTypeOfArgument();
17581 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
17582 // the result is the size of the referenced type."
17583 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
17584 SrcTy = Ref->getPointeeType();
17585
17586 CharUnits Sizeof;
17587 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
17588 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
17589 : SizeOfType::SizeOf)) {
17590 return false;
17591 }
17592 return Success(Sizeof, E);
17593 }
17594 case UETT_OpenMPRequiredSimdAlign:
17595 assert(E->isArgumentType());
17596 return Success(
17597 Info.Ctx.toCharUnitsFromBits(
17599 .getQuantity(),
17600 E);
17601 case UETT_VectorElements: {
17602 QualType Ty = E->getTypeOfArgument();
17603 // If the vector has a fixed size, we can determine the number of elements
17604 // at compile time.
17605 if (const auto *VT = Ty->getAs<VectorType>())
17606 return Success(VT->getNumElements(), E);
17607
17608 assert(Ty->isSizelessVectorType());
17609 if (Info.InConstantContext)
17610 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
17611 << E->getSourceRange();
17612
17613 return false;
17614 }
17615 case UETT_CountOf: {
17616 QualType Ty = E->getTypeOfArgument();
17617 assert(Ty->isArrayType());
17618
17619 // We don't need to worry about array element qualifiers, so getting the
17620 // unsafe array type is fine.
17621 if (const auto *CAT =
17622 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
17623 return Success(CAT->getSize(), E);
17624 }
17625
17626 assert(!Ty->isConstantSizeType());
17627
17628 // If it's a variable-length array type, we need to check whether it is a
17629 // multidimensional array. If so, we need to check the size expression of
17630 // the VLA to see if it's a constant size. If so, we can return that value.
17631 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
17632 assert(VAT);
17633 if (VAT->getElementType()->isArrayType()) {
17634 // Variable array size expression could be missing (e.g. int a[*][10]) In
17635 // that case, it can't be a constant expression.
17636 if (!VAT->getSizeExpr()) {
17637 Info.FFDiag(E->getBeginLoc());
17638 return false;
17639 }
17640
17641 std::optional<APSInt> Res =
17642 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
17643 if (Res) {
17644 // The resulting value always has type size_t, so we need to make the
17645 // returned APInt have the correct sign and bit-width.
17646 APInt Val{
17647 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
17648 Res->getZExtValue()};
17649 return Success(Val, E);
17650 }
17651 }
17652
17653 // Definitely a variable-length type, which is not an ICE.
17654 // FIXME: Better diagnostic.
17655 Info.FFDiag(E->getBeginLoc());
17656 return false;
17657 }
17658 }
17659
17660 llvm_unreachable("unknown expr/type trait");
17661}
17662
17663bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
17664 CharUnits Result;
17665 unsigned n = OOE->getNumComponents();
17666 if (n == 0)
17667 return Error(OOE);
17668 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
17669 for (unsigned i = 0; i != n; ++i) {
17670 OffsetOfNode ON = OOE->getComponent(i);
17671 switch (ON.getKind()) {
17672 case OffsetOfNode::Array: {
17673 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
17674 APSInt IdxResult;
17675 if (!EvaluateInteger(Idx, IdxResult, Info))
17676 return false;
17677 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
17678 if (!AT)
17679 return Error(OOE);
17680 CurrentType = AT->getElementType();
17681 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
17682 Result += IdxResult.getSExtValue() * ElementSize;
17683 break;
17684 }
17685
17686 case OffsetOfNode::Field: {
17687 FieldDecl *MemberDecl = ON.getField();
17688 const auto *RD = CurrentType->getAsRecordDecl();
17689 if (!RD)
17690 return Error(OOE);
17691 if (RD->isInvalidDecl()) return false;
17692 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
17693 unsigned i = MemberDecl->getFieldIndex();
17694 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
17695 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
17696 CurrentType = MemberDecl->getType().getNonReferenceType();
17697 break;
17698 }
17699
17701 llvm_unreachable("dependent __builtin_offsetof");
17702
17703 case OffsetOfNode::Base: {
17704 CXXBaseSpecifier *BaseSpec = ON.getBase();
17705 if (BaseSpec->isVirtual())
17706 return Error(OOE);
17707
17708 // Find the layout of the class whose base we are looking into.
17709 const auto *RD = CurrentType->getAsCXXRecordDecl();
17710 if (!RD)
17711 return Error(OOE);
17712 if (RD->isInvalidDecl()) return false;
17713 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
17714
17715 // Find the base class itself.
17716 CurrentType = BaseSpec->getType();
17717 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
17718 if (!BaseRD)
17719 return Error(OOE);
17720
17721 // Add the offset to the base.
17722 Result += RL.getBaseClassOffset(BaseRD);
17723 break;
17724 }
17725 }
17726 }
17727 return Success(Result, OOE);
17728}
17729
17730bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
17731 switch (E->getOpcode()) {
17732 default:
17733 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
17734 // See C99 6.6p3.
17735 return Error(E);
17736 case UO_Extension:
17737 // FIXME: Should extension allow i-c-e extension expressions in its scope?
17738 // If so, we could clear the diagnostic ID.
17739 return Visit(E->getSubExpr());
17740 case UO_Plus:
17741 // The result is just the value.
17742 return Visit(E->getSubExpr());
17743 case UO_Minus: {
17744 if (!Visit(E->getSubExpr()))
17745 return false;
17746 if (!Result.isInt()) return Error(E);
17747 const APSInt &Value = Result.getInt();
17748 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
17749 if (Info.checkingForUndefinedBehavior())
17750 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
17751 diag::warn_integer_constant_overflow)
17752 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
17753 /*UpperCase=*/true, /*InsertSeparators=*/true)
17754 << E->getType() << E->getSourceRange();
17755
17756 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
17757 E->getType()))
17758 return false;
17759 }
17760 return Success(-Value, E);
17761 }
17762 case UO_Not: {
17763 if (!Visit(E->getSubExpr()))
17764 return false;
17765 if (!Result.isInt()) return Error(E);
17766 return Success(~Result.getInt(), E);
17767 }
17768 case UO_LNot: {
17769 bool bres;
17770 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
17771 return false;
17772 return Success(!bres, E);
17773 }
17774 }
17775}
17776
17777/// HandleCast - This is used to evaluate implicit or explicit casts where the
17778/// result type is integer.
17779bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
17780 const Expr *SubExpr = E->getSubExpr();
17781 QualType DestType = E->getType();
17782 QualType SrcType = SubExpr->getType();
17783
17784 switch (E->getCastKind()) {
17785 case CK_BaseToDerived:
17786 case CK_DerivedToBase:
17787 case CK_UncheckedDerivedToBase:
17788 case CK_Dynamic:
17789 case CK_ToUnion:
17790 case CK_ArrayToPointerDecay:
17791 case CK_FunctionToPointerDecay:
17792 case CK_NullToPointer:
17793 case CK_NullToMemberPointer:
17794 case CK_BaseToDerivedMemberPointer:
17795 case CK_DerivedToBaseMemberPointer:
17796 case CK_ReinterpretMemberPointer:
17797 case CK_ConstructorConversion:
17798 case CK_IntegralToPointer:
17799 case CK_ToVoid:
17800 case CK_VectorSplat:
17801 case CK_IntegralToFloating:
17802 case CK_FloatingCast:
17803 case CK_CPointerToObjCPointerCast:
17804 case CK_BlockPointerToObjCPointerCast:
17805 case CK_AnyPointerToBlockPointerCast:
17806 case CK_ObjCObjectLValueCast:
17807 case CK_FloatingRealToComplex:
17808 case CK_FloatingComplexToReal:
17809 case CK_FloatingComplexCast:
17810 case CK_FloatingComplexToIntegralComplex:
17811 case CK_IntegralRealToComplex:
17812 case CK_IntegralComplexCast:
17813 case CK_IntegralComplexToFloatingComplex:
17814 case CK_BuiltinFnToFnPtr:
17815 case CK_ZeroToOCLOpaqueType:
17816 case CK_NonAtomicToAtomic:
17817 case CK_AddressSpaceConversion:
17818 case CK_IntToOCLSampler:
17819 case CK_FloatingToFixedPoint:
17820 case CK_FixedPointToFloating:
17821 case CK_FixedPointCast:
17822 case CK_IntegralToFixedPoint:
17823 case CK_MatrixCast:
17824 case CK_HLSLAggregateSplatCast:
17825 llvm_unreachable("invalid cast kind for integral value");
17826
17827 case CK_BitCast:
17828 case CK_Dependent:
17829 case CK_LValueBitCast:
17830 case CK_ARCProduceObject:
17831 case CK_ARCConsumeObject:
17832 case CK_ARCReclaimReturnedObject:
17833 case CK_ARCExtendBlockObject:
17834 case CK_CopyAndAutoreleaseBlockObject:
17835 return Error(E);
17836
17837 case CK_UserDefinedConversion:
17838 case CK_LValueToRValue:
17839 case CK_AtomicToNonAtomic:
17840 case CK_NoOp:
17841 case CK_LValueToRValueBitCast:
17842 case CK_HLSLArrayRValue:
17843 return ExprEvaluatorBaseTy::VisitCastExpr(E);
17844
17845 case CK_MemberPointerToBoolean:
17846 case CK_PointerToBoolean:
17847 case CK_IntegralToBoolean:
17848 case CK_FloatingToBoolean:
17849 case CK_BooleanToSignedIntegral:
17850 case CK_FloatingComplexToBoolean:
17851 case CK_IntegralComplexToBoolean: {
17852 bool BoolResult;
17853 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
17854 return false;
17855 uint64_t IntResult = BoolResult;
17856 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
17857 IntResult = (uint64_t)-1;
17858 return Success(IntResult, E);
17859 }
17860
17861 case CK_FixedPointToIntegral: {
17862 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
17863 if (!EvaluateFixedPoint(SubExpr, Src, Info))
17864 return false;
17865 bool Overflowed;
17866 llvm::APSInt Result = Src.convertToInt(
17867 Info.Ctx.getIntWidth(DestType),
17868 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
17869 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
17870 return false;
17871 return Success(Result, E);
17872 }
17873
17874 case CK_FixedPointToBoolean: {
17875 // Unsigned padding does not affect this.
17876 APValue Val;
17877 if (!Evaluate(Val, Info, SubExpr))
17878 return false;
17879 return Success(Val.getFixedPoint().getBoolValue(), E);
17880 }
17881
17882 case CK_IntegralCast: {
17883 if (!Visit(SubExpr))
17884 return false;
17885
17886 if (!Result.isInt()) {
17887 // Allow casts of address-of-label differences if they are no-ops
17888 // or narrowing. (The narrowing case isn't actually guaranteed to
17889 // be constant-evaluatable except in some narrow cases which are hard
17890 // to detect here. We let it through on the assumption the user knows
17891 // what they are doing.)
17892 if (Result.isAddrLabelDiff())
17893 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
17894 // Only allow casts of lvalues if they are lossless.
17895 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
17896 }
17897
17898 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
17899 const auto *ED = DestType->getAsEnumDecl();
17900 // Check that the value is within the range of the enumeration values.
17901 //
17902 // This corressponds to [expr.static.cast]p10 which says:
17903 // A value of integral or enumeration type can be explicitly converted
17904 // to a complete enumeration type ... If the enumeration type does not
17905 // have a fixed underlying type, the value is unchanged if the original
17906 // value is within the range of the enumeration values ([dcl.enum]), and
17907 // otherwise, the behavior is undefined.
17908 //
17909 // This was resolved as part of DR2338 which has CD5 status.
17910 if (!ED->isFixed()) {
17911 llvm::APInt Min;
17912 llvm::APInt Max;
17913
17914 ED->getValueRange(Max, Min);
17915 --Max;
17916
17917 if (ED->getNumNegativeBits() &&
17918 (Max.slt(Result.getInt().getSExtValue()) ||
17919 Min.sgt(Result.getInt().getSExtValue())))
17920 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17921 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
17922 << Max.getSExtValue() << ED;
17923 else if (!ED->getNumNegativeBits() &&
17924 Max.ult(Result.getInt().getZExtValue()))
17925 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
17926 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
17927 << Max.getZExtValue() << ED;
17928 }
17929 }
17930
17931 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
17932 Result.getInt()), E);
17933 }
17934
17935 case CK_PointerToIntegral: {
17936 CCEDiag(E, diag::note_constexpr_invalid_cast)
17937 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
17938 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
17939
17940 LValue LV;
17941 if (!EvaluatePointer(SubExpr, LV, Info))
17942 return false;
17943
17944 if (LV.getLValueBase()) {
17945 // Only allow based lvalue casts if they are lossless.
17946 // FIXME: Allow a larger integer size than the pointer size, and allow
17947 // narrowing back down to pointer width in subsequent integral casts.
17948 // FIXME: Check integer type's active bits, not its type size.
17949 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
17950 return Error(E);
17951
17952 LV.Designator.setInvalid();
17953 LV.moveInto(Result);
17954 return true;
17955 }
17956
17957 APSInt AsInt;
17958 APValue V;
17959 LV.moveInto(V);
17960 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
17961 llvm_unreachable("Can't cast this!");
17962
17963 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
17964 }
17965
17966 case CK_IntegralComplexToReal: {
17967 ComplexValue C;
17968 if (!EvaluateComplex(SubExpr, C, Info))
17969 return false;
17970 return Success(C.getComplexIntReal(), E);
17971 }
17972
17973 case CK_FloatingToIntegral: {
17974 APFloat F(0.0);
17975 if (!EvaluateFloat(SubExpr, F, Info))
17976 return false;
17977
17978 APSInt Value;
17979 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
17980 return false;
17981 return Success(Value, E);
17982 }
17983 case CK_HLSLVectorTruncation: {
17984 APValue Val;
17985 if (!EvaluateVector(SubExpr, Val, Info))
17986 return Error(E);
17987 return Success(Val.getVectorElt(0), E);
17988 }
17989 case CK_HLSLElementwiseCast: {
17990 SmallVector<APValue> SrcVals;
17991 SmallVector<QualType> SrcTypes;
17992
17993 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
17994 return false;
17995
17996 // cast our single element
17997 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
17998 APValue ResultVal;
17999 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
18000 ResultVal))
18001 return false;
18002 return Success(ResultVal, E);
18003 }
18004 }
18005
18006 llvm_unreachable("unknown cast resulting in integral value");
18007}
18008
18009bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18010 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18011 ComplexValue LV;
18012 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18013 return false;
18014 if (!LV.isComplexInt())
18015 return Error(E);
18016 return Success(LV.getComplexIntReal(), E);
18017 }
18018
18019 return Visit(E->getSubExpr());
18020}
18021
18022bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18023 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
18024 ComplexValue LV;
18025 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18026 return false;
18027 if (!LV.isComplexInt())
18028 return Error(E);
18029 return Success(LV.getComplexIntImag(), E);
18030 }
18031
18032 VisitIgnoredValue(E->getSubExpr());
18033 return Success(0, E);
18034}
18035
18036bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
18037 return Success(E->getPackLength(), E);
18038}
18039
18040bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
18041 return Success(E->getValue(), E);
18042}
18043
18044bool IntExprEvaluator::VisitConceptSpecializationExpr(
18045 const ConceptSpecializationExpr *E) {
18046 return Success(E->isSatisfied(), E);
18047}
18048
18049bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
18050 return Success(E->isSatisfied(), E);
18051}
18052
18053bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18054 switch (E->getOpcode()) {
18055 default:
18056 // Invalid unary operators
18057 return Error(E);
18058 case UO_Plus:
18059 // The result is just the value.
18060 return Visit(E->getSubExpr());
18061 case UO_Minus: {
18062 if (!Visit(E->getSubExpr())) return false;
18063 if (!Result.isFixedPoint())
18064 return Error(E);
18065 bool Overflowed;
18066 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
18067 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
18068 return false;
18069 return Success(Negated, E);
18070 }
18071 case UO_LNot: {
18072 bool bres;
18073 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18074 return false;
18075 return Success(!bres, E);
18076 }
18077 }
18078}
18079
18080bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
18081 const Expr *SubExpr = E->getSubExpr();
18082 QualType DestType = E->getType();
18083 assert(DestType->isFixedPointType() &&
18084 "Expected destination type to be a fixed point type");
18085 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
18086
18087 switch (E->getCastKind()) {
18088 case CK_FixedPointCast: {
18089 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
18090 if (!EvaluateFixedPoint(SubExpr, Src, Info))
18091 return false;
18092 bool Overflowed;
18093 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
18094 if (Overflowed) {
18095 if (Info.checkingForUndefinedBehavior())
18096 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18097 diag::warn_fixedpoint_constant_overflow)
18098 << Result.toString() << E->getType();
18099 if (!HandleOverflow(Info, E, Result, E->getType()))
18100 return false;
18101 }
18102 return Success(Result, E);
18103 }
18104 case CK_IntegralToFixedPoint: {
18105 APSInt Src;
18106 if (!EvaluateInteger(SubExpr, Src, Info))
18107 return false;
18108
18109 bool Overflowed;
18110 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
18111 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18112
18113 if (Overflowed) {
18114 if (Info.checkingForUndefinedBehavior())
18115 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18116 diag::warn_fixedpoint_constant_overflow)
18117 << IntResult.toString() << E->getType();
18118 if (!HandleOverflow(Info, E, IntResult, E->getType()))
18119 return false;
18120 }
18121
18122 return Success(IntResult, E);
18123 }
18124 case CK_FloatingToFixedPoint: {
18125 APFloat Src(0.0);
18126 if (!EvaluateFloat(SubExpr, Src, Info))
18127 return false;
18128
18129 bool Overflowed;
18130 APFixedPoint Result = APFixedPoint::getFromFloatValue(
18131 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18132
18133 if (Overflowed) {
18134 if (Info.checkingForUndefinedBehavior())
18135 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18136 diag::warn_fixedpoint_constant_overflow)
18137 << Result.toString() << E->getType();
18138 if (!HandleOverflow(Info, E, Result, E->getType()))
18139 return false;
18140 }
18141
18142 return Success(Result, E);
18143 }
18144 case CK_NoOp:
18145 case CK_LValueToRValue:
18146 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18147 default:
18148 return Error(E);
18149 }
18150}
18151
18152bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18153 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18154 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18155
18156 const Expr *LHS = E->getLHS();
18157 const Expr *RHS = E->getRHS();
18158 FixedPointSemantics ResultFXSema =
18159 Info.Ctx.getFixedPointSemantics(E->getType());
18160
18161 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
18162 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
18163 return false;
18164 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
18165 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
18166 return false;
18167
18168 bool OpOverflow = false, ConversionOverflow = false;
18169 APFixedPoint Result(LHSFX.getSemantics());
18170 switch (E->getOpcode()) {
18171 case BO_Add: {
18172 Result = LHSFX.add(RHSFX, &OpOverflow)
18173 .convert(ResultFXSema, &ConversionOverflow);
18174 break;
18175 }
18176 case BO_Sub: {
18177 Result = LHSFX.sub(RHSFX, &OpOverflow)
18178 .convert(ResultFXSema, &ConversionOverflow);
18179 break;
18180 }
18181 case BO_Mul: {
18182 Result = LHSFX.mul(RHSFX, &OpOverflow)
18183 .convert(ResultFXSema, &ConversionOverflow);
18184 break;
18185 }
18186 case BO_Div: {
18187 if (RHSFX.getValue() == 0) {
18188 Info.FFDiag(E, diag::note_expr_divide_by_zero);
18189 return false;
18190 }
18191 Result = LHSFX.div(RHSFX, &OpOverflow)
18192 .convert(ResultFXSema, &ConversionOverflow);
18193 break;
18194 }
18195 case BO_Shl:
18196 case BO_Shr: {
18197 FixedPointSemantics LHSSema = LHSFX.getSemantics();
18198 llvm::APSInt RHSVal = RHSFX.getValue();
18199
18200 unsigned ShiftBW =
18201 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
18202 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
18203 // Embedded-C 4.1.6.2.2:
18204 // The right operand must be nonnegative and less than the total number
18205 // of (nonpadding) bits of the fixed-point operand ...
18206 if (RHSVal.isNegative())
18207 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
18208 else if (Amt != RHSVal)
18209 Info.CCEDiag(E, diag::note_constexpr_large_shift)
18210 << RHSVal << E->getType() << ShiftBW;
18211
18212 if (E->getOpcode() == BO_Shl)
18213 Result = LHSFX.shl(Amt, &OpOverflow);
18214 else
18215 Result = LHSFX.shr(Amt, &OpOverflow);
18216 break;
18217 }
18218 default:
18219 return false;
18220 }
18221 if (OpOverflow || ConversionOverflow) {
18222 if (Info.checkingForUndefinedBehavior())
18223 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18224 diag::warn_fixedpoint_constant_overflow)
18225 << Result.toString() << E->getType();
18226 if (!HandleOverflow(Info, E, Result, E->getType()))
18227 return false;
18228 }
18229 return Success(Result, E);
18230}
18231
18232//===----------------------------------------------------------------------===//
18233// Float Evaluation
18234//===----------------------------------------------------------------------===//
18235
18236namespace {
18237class FloatExprEvaluator
18238 : public ExprEvaluatorBase<FloatExprEvaluator> {
18239 APFloat &Result;
18240public:
18241 FloatExprEvaluator(EvalInfo &info, APFloat &result)
18242 : ExprEvaluatorBaseTy(info), Result(result) {}
18243
18244 bool Success(const APValue &V, const Expr *e) {
18245 Result = V.getFloat();
18246 return true;
18247 }
18248
18249 bool ZeroInitialization(const Expr *E) {
18250 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
18251 return true;
18252 }
18253
18254 bool VisitCallExpr(const CallExpr *E);
18255
18256 bool VisitUnaryOperator(const UnaryOperator *E);
18257 bool VisitBinaryOperator(const BinaryOperator *E);
18258 bool VisitFloatingLiteral(const FloatingLiteral *E);
18259 bool VisitCastExpr(const CastExpr *E);
18260
18261 bool VisitUnaryReal(const UnaryOperator *E);
18262 bool VisitUnaryImag(const UnaryOperator *E);
18263
18264 // FIXME: Missing: array subscript of vector, member of vector
18265};
18266} // end anonymous namespace
18267
18268static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
18269 assert(!E->isValueDependent());
18270 assert(E->isPRValue() && E->getType()->isRealFloatingType());
18271 return FloatExprEvaluator(Info, Result).Visit(E);
18272}
18273
18274static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
18275 QualType ResultTy,
18276 const Expr *Arg,
18277 bool SNaN,
18278 llvm::APFloat &Result) {
18279 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
18280 if (!S) return false;
18281
18282 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
18283
18284 llvm::APInt fill;
18285
18286 // Treat empty strings as if they were zero.
18287 if (S->getString().empty())
18288 fill = llvm::APInt(32, 0);
18289 else if (S->getString().getAsInteger(0, fill))
18290 return false;
18291
18292 if (Context.getTargetInfo().isNan2008()) {
18293 if (SNaN)
18294 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
18295 else
18296 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
18297 } else {
18298 // Prior to IEEE 754-2008, architectures were allowed to choose whether
18299 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
18300 // a different encoding to what became a standard in 2008, and for pre-
18301 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
18302 // sNaN. This is now known as "legacy NaN" encoding.
18303 if (SNaN)
18304 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
18305 else
18306 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
18307 }
18308
18309 return true;
18310}
18311
18312bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
18313 if (!IsConstantEvaluatedBuiltinCall(E))
18314 return ExprEvaluatorBaseTy::VisitCallExpr(E);
18315
18316 switch (E->getBuiltinCallee()) {
18317 default:
18318 return false;
18319
18320 case Builtin::BI__builtin_huge_val:
18321 case Builtin::BI__builtin_huge_valf:
18322 case Builtin::BI__builtin_huge_vall:
18323 case Builtin::BI__builtin_huge_valf16:
18324 case Builtin::BI__builtin_huge_valf128:
18325 case Builtin::BI__builtin_inf:
18326 case Builtin::BI__builtin_inff:
18327 case Builtin::BI__builtin_infl:
18328 case Builtin::BI__builtin_inff16:
18329 case Builtin::BI__builtin_inff128: {
18330 const llvm::fltSemantics &Sem =
18331 Info.Ctx.getFloatTypeSemantics(E->getType());
18332 Result = llvm::APFloat::getInf(Sem);
18333 return true;
18334 }
18335
18336 case Builtin::BI__builtin_nans:
18337 case Builtin::BI__builtin_nansf:
18338 case Builtin::BI__builtin_nansl:
18339 case Builtin::BI__builtin_nansf16:
18340 case Builtin::BI__builtin_nansf128:
18341 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
18342 true, Result))
18343 return Error(E);
18344 return true;
18345
18346 case Builtin::BI__builtin_nan:
18347 case Builtin::BI__builtin_nanf:
18348 case Builtin::BI__builtin_nanl:
18349 case Builtin::BI__builtin_nanf16:
18350 case Builtin::BI__builtin_nanf128:
18351 // If this is __builtin_nan() turn this into a nan, otherwise we
18352 // can't constant fold it.
18353 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
18354 false, Result))
18355 return Error(E);
18356 return true;
18357
18358 case Builtin::BI__builtin_elementwise_abs:
18359 case Builtin::BI__builtin_fabs:
18360 case Builtin::BI__builtin_fabsf:
18361 case Builtin::BI__builtin_fabsl:
18362 case Builtin::BI__builtin_fabsf128:
18363 // The C standard says "fabs raises no floating-point exceptions,
18364 // even if x is a signaling NaN. The returned value is independent of
18365 // the current rounding direction mode." Therefore constant folding can
18366 // proceed without regard to the floating point settings.
18367 // Reference, WG14 N2478 F.10.4.3
18368 if (!EvaluateFloat(E->getArg(0), Result, Info))
18369 return false;
18370
18371 if (Result.isNegative())
18372 Result.changeSign();
18373 return true;
18374
18375 case Builtin::BI__arithmetic_fence:
18376 return EvaluateFloat(E->getArg(0), Result, Info);
18377
18378 // FIXME: Builtin::BI__builtin_powi
18379 // FIXME: Builtin::BI__builtin_powif
18380 // FIXME: Builtin::BI__builtin_powil
18381
18382 case Builtin::BI__builtin_copysign:
18383 case Builtin::BI__builtin_copysignf:
18384 case Builtin::BI__builtin_copysignl:
18385 case Builtin::BI__builtin_copysignf128: {
18386 APFloat RHS(0.);
18387 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18388 !EvaluateFloat(E->getArg(1), RHS, Info))
18389 return false;
18390 Result.copySign(RHS);
18391 return true;
18392 }
18393
18394 case Builtin::BI__builtin_fmax:
18395 case Builtin::BI__builtin_fmaxf:
18396 case Builtin::BI__builtin_fmaxl:
18397 case Builtin::BI__builtin_fmaxf16:
18398 case Builtin::BI__builtin_fmaxf128: {
18399 APFloat RHS(0.);
18400 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18401 !EvaluateFloat(E->getArg(1), RHS, Info))
18402 return false;
18403 Result = maxnum(Result, RHS);
18404 return true;
18405 }
18406
18407 case Builtin::BI__builtin_fmin:
18408 case Builtin::BI__builtin_fminf:
18409 case Builtin::BI__builtin_fminl:
18410 case Builtin::BI__builtin_fminf16:
18411 case Builtin::BI__builtin_fminf128: {
18412 APFloat RHS(0.);
18413 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18414 !EvaluateFloat(E->getArg(1), RHS, Info))
18415 return false;
18416 Result = minnum(Result, RHS);
18417 return true;
18418 }
18419
18420 case Builtin::BI__builtin_fmaximum_num:
18421 case Builtin::BI__builtin_fmaximum_numf:
18422 case Builtin::BI__builtin_fmaximum_numl:
18423 case Builtin::BI__builtin_fmaximum_numf16:
18424 case Builtin::BI__builtin_fmaximum_numf128: {
18425 APFloat RHS(0.);
18426 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18427 !EvaluateFloat(E->getArg(1), RHS, Info))
18428 return false;
18429 Result = maximumnum(Result, RHS);
18430 return true;
18431 }
18432
18433 case Builtin::BI__builtin_fminimum_num:
18434 case Builtin::BI__builtin_fminimum_numf:
18435 case Builtin::BI__builtin_fminimum_numl:
18436 case Builtin::BI__builtin_fminimum_numf16:
18437 case Builtin::BI__builtin_fminimum_numf128: {
18438 APFloat RHS(0.);
18439 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18440 !EvaluateFloat(E->getArg(1), RHS, Info))
18441 return false;
18442 Result = minimumnum(Result, RHS);
18443 return true;
18444 }
18445
18446 case Builtin::BI__builtin_elementwise_fma: {
18447 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
18448 !E->getArg(2)->isPRValue()) {
18449 return false;
18450 }
18451 APFloat SourceY(0.), SourceZ(0.);
18452 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
18453 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
18454 !EvaluateFloat(E->getArg(2), SourceZ, Info))
18455 return false;
18456 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
18457 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
18458 return true;
18459 }
18460
18461 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
18462 APValue Vec;
18463 APSInt IdxAPS;
18464 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18465 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18466 return false;
18467 unsigned N = Vec.getVectorLength();
18468 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18469 return Success(Vec.getVectorElt(Idx), E);
18470 }
18471 }
18472}
18473
18474bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18475 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18476 ComplexValue CV;
18477 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
18478 return false;
18479 Result = CV.FloatReal;
18480 return true;
18481 }
18482
18483 return Visit(E->getSubExpr());
18484}
18485
18486bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18487 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18488 ComplexValue CV;
18489 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
18490 return false;
18491 Result = CV.FloatImag;
18492 return true;
18493 }
18494
18495 VisitIgnoredValue(E->getSubExpr());
18496 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
18497 Result = llvm::APFloat::getZero(Sem);
18498 return true;
18499}
18500
18501bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18502 switch (E->getOpcode()) {
18503 default: return Error(E);
18504 case UO_Plus:
18505 return EvaluateFloat(E->getSubExpr(), Result, Info);
18506 case UO_Minus:
18507 // In C standard, WG14 N2478 F.3 p4
18508 // "the unary - raises no floating point exceptions,
18509 // even if the operand is signalling."
18510 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
18511 return false;
18512 Result.changeSign();
18513 return true;
18514 }
18515}
18516
18517bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18518 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18519 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18520
18521 APFloat RHS(0.0);
18522 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
18523 if (!LHSOK && !Info.noteFailure())
18524 return false;
18525 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
18526 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
18527}
18528
18529bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
18530 Result = E->getValue();
18531 return true;
18532}
18533
18534bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
18535 const Expr* SubExpr = E->getSubExpr();
18536
18537 switch (E->getCastKind()) {
18538 default:
18539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18540
18541 case CK_HLSLAggregateSplatCast:
18542 llvm_unreachable("invalid cast kind for floating value");
18543
18544 case CK_IntegralToFloating: {
18545 APSInt IntResult;
18546 const FPOptions FPO = E->getFPFeaturesInEffect(
18547 Info.Ctx.getLangOpts());
18548 return EvaluateInteger(SubExpr, IntResult, Info) &&
18549 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
18550 IntResult, E->getType(), Result);
18551 }
18552
18553 case CK_FixedPointToFloating: {
18554 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
18555 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
18556 return false;
18557 Result =
18558 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
18559 return true;
18560 }
18561
18562 case CK_FloatingCast: {
18563 if (!Visit(SubExpr))
18564 return false;
18565 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
18566 Result);
18567 }
18568
18569 case CK_FloatingComplexToReal: {
18570 ComplexValue V;
18571 if (!EvaluateComplex(SubExpr, V, Info))
18572 return false;
18573 Result = V.getComplexFloatReal();
18574 return true;
18575 }
18576 case CK_HLSLVectorTruncation: {
18577 APValue Val;
18578 if (!EvaluateVector(SubExpr, Val, Info))
18579 return Error(E);
18580 return Success(Val.getVectorElt(0), E);
18581 }
18582 case CK_HLSLElementwiseCast: {
18583 SmallVector<APValue> SrcVals;
18584 SmallVector<QualType> SrcTypes;
18585
18586 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
18587 SrcTypes))
18588 return false;
18589 APValue Val;
18590
18591 // cast our single element
18592 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
18593 APValue ResultVal;
18594 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
18595 ResultVal))
18596 return false;
18597 return Success(ResultVal, E);
18598 }
18599 }
18600}
18601
18602//===----------------------------------------------------------------------===//
18603// Complex Evaluation (for float and integer)
18604//===----------------------------------------------------------------------===//
18605
18606namespace {
18607class ComplexExprEvaluator
18608 : public ExprEvaluatorBase<ComplexExprEvaluator> {
18609 ComplexValue &Result;
18610
18611public:
18612 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
18613 : ExprEvaluatorBaseTy(info), Result(Result) {}
18614
18615 bool Success(const APValue &V, const Expr *e) {
18616 Result.setFrom(V);
18617 return true;
18618 }
18619
18620 bool ZeroInitialization(const Expr *E);
18621
18622 //===--------------------------------------------------------------------===//
18623 // Visitor Methods
18624 //===--------------------------------------------------------------------===//
18625
18626 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
18627 bool VisitCastExpr(const CastExpr *E);
18628 bool VisitBinaryOperator(const BinaryOperator *E);
18629 bool VisitUnaryOperator(const UnaryOperator *E);
18630 bool VisitInitListExpr(const InitListExpr *E);
18631 bool VisitCallExpr(const CallExpr *E);
18632};
18633} // end anonymous namespace
18634
18635static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
18636 EvalInfo &Info) {
18637 assert(!E->isValueDependent());
18638 assert(E->isPRValue() && E->getType()->isAnyComplexType());
18639 return ComplexExprEvaluator(Info, Result).Visit(E);
18640}
18641
18642bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
18643 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
18644 if (ElemTy->isRealFloatingType()) {
18645 Result.makeComplexFloat();
18646 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
18647 Result.FloatReal = Zero;
18648 Result.FloatImag = Zero;
18649 } else {
18650 Result.makeComplexInt();
18651 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
18652 Result.IntReal = Zero;
18653 Result.IntImag = Zero;
18654 }
18655 return true;
18656}
18657
18658bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
18659 const Expr* SubExpr = E->getSubExpr();
18660
18661 if (SubExpr->getType()->isRealFloatingType()) {
18662 Result.makeComplexFloat();
18663 APFloat &Imag = Result.FloatImag;
18664 if (!EvaluateFloat(SubExpr, Imag, Info))
18665 return false;
18666
18667 Result.FloatReal = APFloat(Imag.getSemantics());
18668 return true;
18669 } else {
18670 assert(SubExpr->getType()->isIntegerType() &&
18671 "Unexpected imaginary literal.");
18672
18673 Result.makeComplexInt();
18674 APSInt &Imag = Result.IntImag;
18675 if (!EvaluateInteger(SubExpr, Imag, Info))
18676 return false;
18677
18678 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
18679 return true;
18680 }
18681}
18682
18683bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
18684
18685 switch (E->getCastKind()) {
18686 case CK_BitCast:
18687 case CK_BaseToDerived:
18688 case CK_DerivedToBase:
18689 case CK_UncheckedDerivedToBase:
18690 case CK_Dynamic:
18691 case CK_ToUnion:
18692 case CK_ArrayToPointerDecay:
18693 case CK_FunctionToPointerDecay:
18694 case CK_NullToPointer:
18695 case CK_NullToMemberPointer:
18696 case CK_BaseToDerivedMemberPointer:
18697 case CK_DerivedToBaseMemberPointer:
18698 case CK_MemberPointerToBoolean:
18699 case CK_ReinterpretMemberPointer:
18700 case CK_ConstructorConversion:
18701 case CK_IntegralToPointer:
18702 case CK_PointerToIntegral:
18703 case CK_PointerToBoolean:
18704 case CK_ToVoid:
18705 case CK_VectorSplat:
18706 case CK_IntegralCast:
18707 case CK_BooleanToSignedIntegral:
18708 case CK_IntegralToBoolean:
18709 case CK_IntegralToFloating:
18710 case CK_FloatingToIntegral:
18711 case CK_FloatingToBoolean:
18712 case CK_FloatingCast:
18713 case CK_CPointerToObjCPointerCast:
18714 case CK_BlockPointerToObjCPointerCast:
18715 case CK_AnyPointerToBlockPointerCast:
18716 case CK_ObjCObjectLValueCast:
18717 case CK_FloatingComplexToReal:
18718 case CK_FloatingComplexToBoolean:
18719 case CK_IntegralComplexToReal:
18720 case CK_IntegralComplexToBoolean:
18721 case CK_ARCProduceObject:
18722 case CK_ARCConsumeObject:
18723 case CK_ARCReclaimReturnedObject:
18724 case CK_ARCExtendBlockObject:
18725 case CK_CopyAndAutoreleaseBlockObject:
18726 case CK_BuiltinFnToFnPtr:
18727 case CK_ZeroToOCLOpaqueType:
18728 case CK_NonAtomicToAtomic:
18729 case CK_AddressSpaceConversion:
18730 case CK_IntToOCLSampler:
18731 case CK_FloatingToFixedPoint:
18732 case CK_FixedPointToFloating:
18733 case CK_FixedPointCast:
18734 case CK_FixedPointToBoolean:
18735 case CK_FixedPointToIntegral:
18736 case CK_IntegralToFixedPoint:
18737 case CK_MatrixCast:
18738 case CK_HLSLVectorTruncation:
18739 case CK_HLSLElementwiseCast:
18740 case CK_HLSLAggregateSplatCast:
18741 llvm_unreachable("invalid cast kind for complex value");
18742
18743 case CK_LValueToRValue:
18744 case CK_AtomicToNonAtomic:
18745 case CK_NoOp:
18746 case CK_LValueToRValueBitCast:
18747 case CK_HLSLArrayRValue:
18748 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18749
18750 case CK_Dependent:
18751 case CK_LValueBitCast:
18752 case CK_UserDefinedConversion:
18753 return Error(E);
18754
18755 case CK_FloatingRealToComplex: {
18756 APFloat &Real = Result.FloatReal;
18757 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
18758 return false;
18759
18760 Result.makeComplexFloat();
18761 Result.FloatImag = APFloat(Real.getSemantics());
18762 return true;
18763 }
18764
18765 case CK_FloatingComplexCast: {
18766 if (!Visit(E->getSubExpr()))
18767 return false;
18768
18769 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18770 QualType From
18771 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18772
18773 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
18774 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
18775 }
18776
18777 case CK_FloatingComplexToIntegralComplex: {
18778 if (!Visit(E->getSubExpr()))
18779 return false;
18780
18781 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18782 QualType From
18783 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18784 Result.makeComplexInt();
18785 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
18786 To, Result.IntReal) &&
18787 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
18788 To, Result.IntImag);
18789 }
18790
18791 case CK_IntegralRealToComplex: {
18792 APSInt &Real = Result.IntReal;
18793 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
18794 return false;
18795
18796 Result.makeComplexInt();
18797 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
18798 return true;
18799 }
18800
18801 case CK_IntegralComplexCast: {
18802 if (!Visit(E->getSubExpr()))
18803 return false;
18804
18805 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18806 QualType From
18807 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18808
18809 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
18810 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
18811 return true;
18812 }
18813
18814 case CK_IntegralComplexToFloatingComplex: {
18815 if (!Visit(E->getSubExpr()))
18816 return false;
18817
18818 const FPOptions FPO = E->getFPFeaturesInEffect(
18819 Info.Ctx.getLangOpts());
18820 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
18821 QualType From
18822 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
18823 Result.makeComplexFloat();
18824 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
18825 To, Result.FloatReal) &&
18826 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
18827 To, Result.FloatImag);
18828 }
18829 }
18830
18831 llvm_unreachable("unknown cast resulting in complex value");
18832}
18833
18834void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
18835 APFloat &ResR, APFloat &ResI) {
18836 // This is an implementation of complex multiplication according to the
18837 // constraints laid out in C11 Annex G. The implementation uses the
18838 // following naming scheme:
18839 // (a + ib) * (c + id)
18840
18841 APFloat AC = A * C;
18842 APFloat BD = B * D;
18843 APFloat AD = A * D;
18844 APFloat BC = B * C;
18845 ResR = AC - BD;
18846 ResI = AD + BC;
18847 if (ResR.isNaN() && ResI.isNaN()) {
18848 bool Recalc = false;
18849 if (A.isInfinity() || B.isInfinity()) {
18850 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18851 A);
18852 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18853 B);
18854 if (C.isNaN())
18855 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18856 if (D.isNaN())
18857 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18858 Recalc = true;
18859 }
18860 if (C.isInfinity() || D.isInfinity()) {
18861 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18862 C);
18863 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18864 D);
18865 if (A.isNaN())
18866 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18867 if (B.isNaN())
18868 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18869 Recalc = true;
18870 }
18871 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
18872 BC.isInfinity())) {
18873 if (A.isNaN())
18874 A = APFloat::copySign(APFloat(A.getSemantics()), A);
18875 if (B.isNaN())
18876 B = APFloat::copySign(APFloat(B.getSemantics()), B);
18877 if (C.isNaN())
18878 C = APFloat::copySign(APFloat(C.getSemantics()), C);
18879 if (D.isNaN())
18880 D = APFloat::copySign(APFloat(D.getSemantics()), D);
18881 Recalc = true;
18882 }
18883 if (Recalc) {
18884 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
18885 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
18886 }
18887 }
18888}
18889
18890void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
18891 APFloat &ResR, APFloat &ResI) {
18892 // This is an implementation of complex division according to the
18893 // constraints laid out in C11 Annex G. The implementation uses the
18894 // following naming scheme:
18895 // (a + ib) / (c + id)
18896
18897 int DenomLogB = 0;
18898 APFloat MaxCD = maxnum(abs(C), abs(D));
18899 if (MaxCD.isFinite()) {
18900 DenomLogB = ilogb(MaxCD);
18901 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
18902 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
18903 }
18904 APFloat Denom = C * C + D * D;
18905 ResR =
18906 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18907 ResI =
18908 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
18909 if (ResR.isNaN() && ResI.isNaN()) {
18910 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
18911 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
18912 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
18913 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
18914 D.isFinite()) {
18915 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
18916 A);
18917 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
18918 B);
18919 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
18920 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
18921 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
18922 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
18923 C);
18924 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
18925 D);
18926 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
18927 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
18928 }
18929 }
18930}
18931
18932bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18933 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18934 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18935
18936 // Track whether the LHS or RHS is real at the type system level. When this is
18937 // the case we can simplify our evaluation strategy.
18938 bool LHSReal = false, RHSReal = false;
18939
18940 bool LHSOK;
18941 if (E->getLHS()->getType()->isRealFloatingType()) {
18942 LHSReal = true;
18943 APFloat &Real = Result.FloatReal;
18944 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
18945 if (LHSOK) {
18946 Result.makeComplexFloat();
18947 Result.FloatImag = APFloat(Real.getSemantics());
18948 }
18949 } else {
18950 LHSOK = Visit(E->getLHS());
18951 }
18952 if (!LHSOK && !Info.noteFailure())
18953 return false;
18954
18955 ComplexValue RHS;
18956 if (E->getRHS()->getType()->isRealFloatingType()) {
18957 RHSReal = true;
18958 APFloat &Real = RHS.FloatReal;
18959 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
18960 return false;
18961 RHS.makeComplexFloat();
18962 RHS.FloatImag = APFloat(Real.getSemantics());
18963 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18964 return false;
18965
18966 assert(!(LHSReal && RHSReal) &&
18967 "Cannot have both operands of a complex operation be real.");
18968 switch (E->getOpcode()) {
18969 default: return Error(E);
18970 case BO_Add:
18971 if (Result.isComplexFloat()) {
18972 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
18973 APFloat::rmNearestTiesToEven);
18974 if (LHSReal)
18975 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18976 else if (!RHSReal)
18977 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
18978 APFloat::rmNearestTiesToEven);
18979 } else {
18980 Result.getComplexIntReal() += RHS.getComplexIntReal();
18981 Result.getComplexIntImag() += RHS.getComplexIntImag();
18982 }
18983 break;
18984 case BO_Sub:
18985 if (Result.isComplexFloat()) {
18986 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
18987 APFloat::rmNearestTiesToEven);
18988 if (LHSReal) {
18989 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
18990 Result.getComplexFloatImag().changeSign();
18991 } else if (!RHSReal) {
18992 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
18993 APFloat::rmNearestTiesToEven);
18994 }
18995 } else {
18996 Result.getComplexIntReal() -= RHS.getComplexIntReal();
18997 Result.getComplexIntImag() -= RHS.getComplexIntImag();
18998 }
18999 break;
19000 case BO_Mul:
19001 if (Result.isComplexFloat()) {
19002 // This is an implementation of complex multiplication according to the
19003 // constraints laid out in C11 Annex G. The implementation uses the
19004 // following naming scheme:
19005 // (a + ib) * (c + id)
19006 ComplexValue LHS = Result;
19007 APFloat &A = LHS.getComplexFloatReal();
19008 APFloat &B = LHS.getComplexFloatImag();
19009 APFloat &C = RHS.getComplexFloatReal();
19010 APFloat &D = RHS.getComplexFloatImag();
19011 APFloat &ResR = Result.getComplexFloatReal();
19012 APFloat &ResI = Result.getComplexFloatImag();
19013 if (LHSReal) {
19014 assert(!RHSReal && "Cannot have two real operands for a complex op!");
19015 ResR = A;
19016 ResI = A;
19017 // ResR = A * C;
19018 // ResI = A * D;
19019 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
19020 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
19021 return false;
19022 } else if (RHSReal) {
19023 // ResR = C * A;
19024 // ResI = C * B;
19025 ResR = C;
19026 ResI = C;
19027 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
19028 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
19029 return false;
19030 } else {
19031 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
19032 }
19033 } else {
19034 ComplexValue LHS = Result;
19035 Result.getComplexIntReal() =
19036 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
19037 LHS.getComplexIntImag() * RHS.getComplexIntImag());
19038 Result.getComplexIntImag() =
19039 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
19040 LHS.getComplexIntImag() * RHS.getComplexIntReal());
19041 }
19042 break;
19043 case BO_Div:
19044 if (Result.isComplexFloat()) {
19045 // This is an implementation of complex division according to the
19046 // constraints laid out in C11 Annex G. The implementation uses the
19047 // following naming scheme:
19048 // (a + ib) / (c + id)
19049 ComplexValue LHS = Result;
19050 APFloat &A = LHS.getComplexFloatReal();
19051 APFloat &B = LHS.getComplexFloatImag();
19052 APFloat &C = RHS.getComplexFloatReal();
19053 APFloat &D = RHS.getComplexFloatImag();
19054 APFloat &ResR = Result.getComplexFloatReal();
19055 APFloat &ResI = Result.getComplexFloatImag();
19056 if (RHSReal) {
19057 ResR = A;
19058 ResI = B;
19059 // ResR = A / C;
19060 // ResI = B / C;
19061 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
19062 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
19063 return false;
19064 } else {
19065 if (LHSReal) {
19066 // No real optimizations we can do here, stub out with zero.
19067 B = APFloat::getZero(A.getSemantics());
19068 }
19069 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
19070 }
19071 } else {
19072 ComplexValue LHS = Result;
19073 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
19074 RHS.getComplexIntImag() * RHS.getComplexIntImag();
19075 if (Den.isZero())
19076 return Error(E, diag::note_expr_divide_by_zero);
19077
19078 Result.getComplexIntReal() =
19079 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
19080 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
19081 Result.getComplexIntImag() =
19082 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
19083 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
19084 }
19085 break;
19086 }
19087
19088 return true;
19089}
19090
19091bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19092 // Get the operand value into 'Result'.
19093 if (!Visit(E->getSubExpr()))
19094 return false;
19095
19096 switch (E->getOpcode()) {
19097 default:
19098 return Error(E);
19099 case UO_Extension:
19100 return true;
19101 case UO_Plus:
19102 // The result is always just the subexpr.
19103 return true;
19104 case UO_Minus:
19105 if (Result.isComplexFloat()) {
19106 Result.getComplexFloatReal().changeSign();
19107 Result.getComplexFloatImag().changeSign();
19108 }
19109 else {
19110 Result.getComplexIntReal() = -Result.getComplexIntReal();
19111 Result.getComplexIntImag() = -Result.getComplexIntImag();
19112 }
19113 return true;
19114 case UO_Not:
19115 if (Result.isComplexFloat())
19116 Result.getComplexFloatImag().changeSign();
19117 else
19118 Result.getComplexIntImag() = -Result.getComplexIntImag();
19119 return true;
19120 }
19121}
19122
19123bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
19124 if (E->getNumInits() == 2) {
19125 if (E->getType()->isComplexType()) {
19126 Result.makeComplexFloat();
19127 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
19128 return false;
19129 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
19130 return false;
19131 } else {
19132 Result.makeComplexInt();
19133 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
19134 return false;
19135 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
19136 return false;
19137 }
19138 return true;
19139 }
19140 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
19141}
19142
19143bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
19144 if (!IsConstantEvaluatedBuiltinCall(E))
19145 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19146
19147 switch (E->getBuiltinCallee()) {
19148 case Builtin::BI__builtin_complex:
19149 Result.makeComplexFloat();
19150 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
19151 return false;
19152 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
19153 return false;
19154 return true;
19155
19156 default:
19157 return false;
19158 }
19159}
19160
19161//===----------------------------------------------------------------------===//
19162// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
19163// implicit conversion.
19164//===----------------------------------------------------------------------===//
19165
19166namespace {
19167class AtomicExprEvaluator :
19168 public ExprEvaluatorBase<AtomicExprEvaluator> {
19169 const LValue *This;
19170 APValue &Result;
19171public:
19172 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
19173 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
19174
19175 bool Success(const APValue &V, const Expr *E) {
19176 Result = V;
19177 return true;
19178 }
19179
19180 bool ZeroInitialization(const Expr *E) {
19181 ImplicitValueInitExpr VIE(
19182 E->getType()->castAs<AtomicType>()->getValueType());
19183 // For atomic-qualified class (and array) types in C++, initialize the
19184 // _Atomic-wrapped subobject directly, in-place.
19185 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
19186 : Evaluate(Result, Info, &VIE);
19187 }
19188
19189 bool VisitCastExpr(const CastExpr *E) {
19190 switch (E->getCastKind()) {
19191 default:
19192 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19193 case CK_NullToPointer:
19194 VisitIgnoredValue(E->getSubExpr());
19195 return ZeroInitialization(E);
19196 case CK_NonAtomicToAtomic:
19197 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
19198 : Evaluate(Result, Info, E->getSubExpr());
19199 }
19200 }
19201};
19202} // end anonymous namespace
19203
19204static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
19205 EvalInfo &Info) {
19206 assert(!E->isValueDependent());
19207 assert(E->isPRValue() && E->getType()->isAtomicType());
19208 return AtomicExprEvaluator(Info, This, Result).Visit(E);
19209}
19210
19211//===----------------------------------------------------------------------===//
19212// Void expression evaluation, primarily for a cast to void on the LHS of a
19213// comma operator
19214//===----------------------------------------------------------------------===//
19215
19216namespace {
19217class VoidExprEvaluator
19218 : public ExprEvaluatorBase<VoidExprEvaluator> {
19219public:
19220 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
19221
19222 bool Success(const APValue &V, const Expr *e) { return true; }
19223
19224 bool ZeroInitialization(const Expr *E) { return true; }
19225
19226 bool VisitCastExpr(const CastExpr *E) {
19227 switch (E->getCastKind()) {
19228 default:
19229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19230 case CK_ToVoid:
19231 VisitIgnoredValue(E->getSubExpr());
19232 return true;
19233 }
19234 }
19235
19236 bool VisitCallExpr(const CallExpr *E) {
19237 if (!IsConstantEvaluatedBuiltinCall(E))
19238 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19239
19240 switch (E->getBuiltinCallee()) {
19241 case Builtin::BI__assume:
19242 case Builtin::BI__builtin_assume:
19243 // The argument is not evaluated!
19244 return true;
19245
19246 case Builtin::BI__builtin_operator_delete:
19247 return HandleOperatorDeleteCall(Info, E);
19248
19249 default:
19250 return false;
19251 }
19252 }
19253
19254 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
19255};
19256} // end anonymous namespace
19257
19258bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
19259 // We cannot speculatively evaluate a delete expression.
19260 if (Info.SpeculativeEvaluationDepth)
19261 return false;
19262
19263 FunctionDecl *OperatorDelete = E->getOperatorDelete();
19264 if (!OperatorDelete
19265 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
19266 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
19267 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
19268 return false;
19269 }
19270
19271 const Expr *Arg = E->getArgument();
19272
19273 LValue Pointer;
19274 if (!EvaluatePointer(Arg, Pointer, Info))
19275 return false;
19276 if (Pointer.Designator.Invalid)
19277 return false;
19278
19279 // Deleting a null pointer has no effect.
19280 if (Pointer.isNullPointer()) {
19281 // This is the only case where we need to produce an extension warning:
19282 // the only other way we can succeed is if we find a dynamic allocation,
19283 // and we will have warned when we allocated it in that case.
19284 if (!Info.getLangOpts().CPlusPlus20)
19285 Info.CCEDiag(E, diag::note_constexpr_new);
19286 return true;
19287 }
19288
19289 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
19290 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
19291 if (!Alloc)
19292 return false;
19293 QualType AllocType = Pointer.Base.getDynamicAllocType();
19294
19295 // For the non-array case, the designator must be empty if the static type
19296 // does not have a virtual destructor.
19297 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
19299 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
19300 << Arg->getType()->getPointeeType() << AllocType;
19301 return false;
19302 }
19303
19304 // For a class type with a virtual destructor, the selected operator delete
19305 // is the one looked up when building the destructor.
19306 if (!E->isArrayForm() && !E->isGlobalDelete()) {
19307 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
19308 if (VirtualDelete &&
19309 !VirtualDelete
19310 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
19311 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
19312 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
19313 return false;
19314 }
19315 }
19316
19317 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
19318 (*Alloc)->Value, AllocType))
19319 return false;
19320
19321 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
19322 // The element was already erased. This means the destructor call also
19323 // deleted the object.
19324 // FIXME: This probably results in undefined behavior before we get this
19325 // far, and should be diagnosed elsewhere first.
19326 Info.FFDiag(E, diag::note_constexpr_double_delete);
19327 return false;
19328 }
19329
19330 return true;
19331}
19332
19333static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
19334 assert(!E->isValueDependent());
19335 assert(E->isPRValue() && E->getType()->isVoidType());
19336 return VoidExprEvaluator(Info).Visit(E);
19337}
19338
19339//===----------------------------------------------------------------------===//
19340// Top level Expr::EvaluateAsRValue method.
19341//===----------------------------------------------------------------------===//
19342
19343static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
19344 assert(!E->isValueDependent());
19345 // In C, function designators are not lvalues, but we evaluate them as if they
19346 // are.
19347 QualType T = E->getType();
19348 if (E->isGLValue() || T->isFunctionType()) {
19349 LValue LV;
19350 if (!EvaluateLValue(E, LV, Info))
19351 return false;
19352 LV.moveInto(Result);
19353 } else if (T->isVectorType()) {
19354 if (!EvaluateVector(E, Result, Info))
19355 return false;
19356 } else if (T->isIntegralOrEnumerationType()) {
19357 if (!IntExprEvaluator(Info, Result).Visit(E))
19358 return false;
19359 } else if (T->hasPointerRepresentation()) {
19360 LValue LV;
19361 if (!EvaluatePointer(E, LV, Info))
19362 return false;
19363 LV.moveInto(Result);
19364 } else if (T->isRealFloatingType()) {
19365 llvm::APFloat F(0.0);
19366 if (!EvaluateFloat(E, F, Info))
19367 return false;
19368 Result = APValue(F);
19369 } else if (T->isAnyComplexType()) {
19370 ComplexValue C;
19371 if (!EvaluateComplex(E, C, Info))
19372 return false;
19373 C.moveInto(Result);
19374 } else if (T->isFixedPointType()) {
19375 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
19376 } else if (T->isMemberPointerType()) {
19377 MemberPtr P;
19378 if (!EvaluateMemberPointer(E, P, Info))
19379 return false;
19380 P.moveInto(Result);
19381 return true;
19382 } else if (T->isArrayType()) {
19383 LValue LV;
19384 APValue &Value =
19385 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
19386 if (!EvaluateArray(E, LV, Value, Info))
19387 return false;
19388 Result = Value;
19389 } else if (T->isRecordType()) {
19390 LValue LV;
19391 APValue &Value =
19392 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
19393 if (!EvaluateRecord(E, LV, Value, Info))
19394 return false;
19395 Result = Value;
19396 } else if (T->isVoidType()) {
19397 if (!Info.getLangOpts().CPlusPlus11)
19398 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
19399 << E->getType();
19400 if (!EvaluateVoid(E, Info))
19401 return false;
19402 } else if (T->isAtomicType()) {
19403 QualType Unqual = T.getAtomicUnqualifiedType();
19404 if (Unqual->isArrayType() || Unqual->isRecordType()) {
19405 LValue LV;
19406 APValue &Value = Info.CurrentCall->createTemporary(
19407 E, Unqual, ScopeKind::FullExpression, LV);
19408 if (!EvaluateAtomic(E, &LV, Value, Info))
19409 return false;
19410 Result = Value;
19411 } else {
19412 if (!EvaluateAtomic(E, nullptr, Result, Info))
19413 return false;
19414 }
19415 } else if (Info.getLangOpts().CPlusPlus11) {
19416 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
19417 return false;
19418 } else {
19419 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19420 return false;
19421 }
19422
19423 return true;
19424}
19425
19426/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
19427/// cases, the in-place evaluation is essential, since later initializers for
19428/// an object can indirectly refer to subobjects which were initialized earlier.
19429static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
19430 const Expr *E, bool AllowNonLiteralTypes) {
19431 assert(!E->isValueDependent());
19432
19433 // Normally expressions passed to EvaluateInPlace have a type, but not when
19434 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
19435 // replaced with a CXXConstructExpr. This can happen in LLDB.
19436 if (E->getType().isNull())
19437 return false;
19438
19439 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
19440 return false;
19441
19442 if (E->isPRValue()) {
19443 // Evaluate arrays and record types in-place, so that later initializers can
19444 // refer to earlier-initialized members of the object.
19445 QualType T = E->getType();
19446 if (T->isArrayType())
19447 return EvaluateArray(E, This, Result, Info);
19448 else if (T->isRecordType())
19449 return EvaluateRecord(E, This, Result, Info);
19450 else if (T->isAtomicType()) {
19451 QualType Unqual = T.getAtomicUnqualifiedType();
19452 if (Unqual->isArrayType() || Unqual->isRecordType())
19453 return EvaluateAtomic(E, &This, Result, Info);
19454 }
19455 }
19456
19457 // For any other type, in-place evaluation is unimportant.
19458 return Evaluate(Result, Info, E);
19459}
19460
19461/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
19462/// lvalue-to-rvalue cast if it is an lvalue.
19463static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
19464 assert(!E->isValueDependent());
19465
19466 if (E->getType().isNull())
19467 return false;
19468
19469 if (!CheckLiteralType(Info, E))
19470 return false;
19471
19472 if (Info.EnableNewConstInterp) {
19473 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
19474 return false;
19475 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19476 ConstantExprKind::Normal);
19477 }
19478
19479 if (!::Evaluate(Result, Info, E))
19480 return false;
19481
19482 // Implicit lvalue-to-rvalue cast.
19483 if (E->isGLValue()) {
19484 LValue LV;
19485 LV.setFrom(Info.Ctx, Result);
19486 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19487 return false;
19488 }
19489
19490 // Check this core constant expression is a constant expression.
19491 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19492 ConstantExprKind::Normal) &&
19493 CheckMemoryLeaks(Info);
19494}
19495
19496static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
19497 const ASTContext &Ctx, bool &IsConst) {
19498 // Fast-path evaluations of integer literals, since we sometimes see files
19499 // containing vast quantities of these.
19500 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
19501 Result =
19502 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
19503 IsConst = true;
19504 return true;
19505 }
19506
19507 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
19508 Result = APValue(APSInt(APInt(1, L->getValue())));
19509 IsConst = true;
19510 return true;
19511 }
19512
19513 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
19514 Result = APValue(FL->getValue());
19515 IsConst = true;
19516 return true;
19517 }
19518
19519 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
19520 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
19521 IsConst = true;
19522 return true;
19523 }
19524
19525 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
19526 if (CE->hasAPValueResult()) {
19527 APValue APV = CE->getAPValueResult();
19528 if (!APV.isLValue()) {
19529 Result = std::move(APV);
19530 IsConst = true;
19531 return true;
19532 }
19533 }
19534
19535 // The SubExpr is usually just an IntegerLiteral.
19536 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
19537 }
19538
19539 // This case should be rare, but we need to check it before we check on
19540 // the type below.
19541 if (Exp->getType().isNull()) {
19542 IsConst = false;
19543 return true;
19544 }
19545
19546 return false;
19547}
19548
19551 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
19552 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
19553}
19554
19555static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
19556 const ASTContext &Ctx, EvalInfo &Info) {
19557 assert(!E->isValueDependent());
19558 bool IsConst;
19559 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
19560 return IsConst;
19561
19562 return EvaluateAsRValue(Info, E, Result.Val);
19563}
19564
19566 const ASTContext &Ctx,
19567 Expr::SideEffectsKind AllowSideEffects,
19568 EvalInfo &Info) {
19569 assert(!E->isValueDependent());
19571 return false;
19572
19573 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
19574 !ExprResult.Val.isInt() ||
19575 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19576 return false;
19577
19578 return true;
19579}
19580
19582 const ASTContext &Ctx,
19583 Expr::SideEffectsKind AllowSideEffects,
19584 EvalInfo &Info) {
19585 assert(!E->isValueDependent());
19586 if (!E->getType()->isFixedPointType())
19587 return false;
19588
19589 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
19590 return false;
19591
19592 if (!ExprResult.Val.isFixedPoint() ||
19593 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19594 return false;
19595
19596 return true;
19597}
19598
19599/// EvaluateAsRValue - Return true if this is a constant which we can fold using
19600/// any crazy technique (that has nothing to do with language standards) that
19601/// we want to. If this function returns true, it returns the folded constant
19602/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
19603/// will be applied to the result.
19605 bool InConstantContext) const {
19606 assert(!isValueDependent() &&
19607 "Expression evaluator can't be called on a dependent expression.");
19608 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
19609 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19610 Info.InConstantContext = InConstantContext;
19611 return ::EvaluateAsRValue(this, Result, Ctx, Info);
19612}
19613
19615 bool InConstantContext) const {
19616 assert(!isValueDependent() &&
19617 "Expression evaluator can't be called on a dependent expression.");
19618 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
19619 EvalResult Scratch;
19620 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
19621 HandleConversionToBool(Scratch.Val, Result);
19622}
19623
19625 SideEffectsKind AllowSideEffects,
19626 bool InConstantContext) const {
19627 assert(!isValueDependent() &&
19628 "Expression evaluator can't be called on a dependent expression.");
19629 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
19630 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19631 Info.InConstantContext = InConstantContext;
19632 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
19633}
19634
19636 SideEffectsKind AllowSideEffects,
19637 bool InConstantContext) const {
19638 assert(!isValueDependent() &&
19639 "Expression evaluator can't be called on a dependent expression.");
19640 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
19641 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
19642 Info.InConstantContext = InConstantContext;
19643 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
19644}
19645
19646bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
19647 SideEffectsKind AllowSideEffects,
19648 bool InConstantContext) const {
19649 assert(!isValueDependent() &&
19650 "Expression evaluator can't be called on a dependent expression.");
19651
19652 if (!getType()->isRealFloatingType())
19653 return false;
19654
19655 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
19657 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
19658 !ExprResult.Val.isFloat() ||
19659 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
19660 return false;
19661
19662 Result = ExprResult.Val.getFloat();
19663 return true;
19664}
19665
19667 bool InConstantContext) const {
19668 assert(!isValueDependent() &&
19669 "Expression evaluator can't be called on a dependent expression.");
19670
19671 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
19672 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
19673 Info.InConstantContext = InConstantContext;
19674 LValue LV;
19675 CheckedTemporaries CheckedTemps;
19676
19677 if (Info.EnableNewConstInterp) {
19678 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
19679 ConstantExprKind::Normal))
19680 return false;
19681
19682 LV.setFrom(Ctx, Result.Val);
19684 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
19685 ConstantExprKind::Normal, CheckedTemps);
19686 }
19687
19688 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
19689 Result.HasSideEffects ||
19692 ConstantExprKind::Normal, CheckedTemps))
19693 return false;
19694
19695 LV.moveInto(Result.Val);
19696 return true;
19697}
19698
19700 APValue DestroyedValue, QualType Type,
19701 SourceLocation Loc, Expr::EvalStatus &EStatus,
19702 bool IsConstantDestruction) {
19703 EvalInfo Info(Ctx, EStatus,
19704 IsConstantDestruction ? EvaluationMode::ConstantExpression
19706 Info.setEvaluatingDecl(Base, DestroyedValue,
19707 EvalInfo::EvaluatingDeclKind::Dtor);
19708 Info.InConstantContext = IsConstantDestruction;
19709
19710 LValue LVal;
19711 LVal.set(Base);
19712
19713 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
19714 EStatus.HasSideEffects)
19715 return false;
19716
19717 if (!Info.discardCleanups())
19718 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19719
19720 return true;
19721}
19722
19724 ConstantExprKind Kind) const {
19725 assert(!isValueDependent() &&
19726 "Expression evaluator can't be called on a dependent expression.");
19727 bool IsConst;
19728 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
19729 Result.Val.hasValue())
19730 return true;
19731
19732 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
19734 EvalInfo Info(Ctx, Result, EM);
19735 Info.InConstantContext = true;
19736
19737 if (Info.EnableNewConstInterp) {
19738 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
19739 return false;
19740 return CheckConstantExpression(Info, getExprLoc(),
19741 getStorageType(Ctx, this), Result.Val, Kind);
19742 }
19743
19744 // The type of the object we're initializing is 'const T' for a class NTTP.
19745 QualType T = getType();
19746 if (Kind == ConstantExprKind::ClassTemplateArgument)
19747 T.addConst();
19748
19749 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
19750 // represent the result of the evaluation. CheckConstantExpression ensures
19751 // this doesn't escape.
19752 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
19753 APValue::LValueBase Base(&BaseMTE);
19754 Info.setEvaluatingDecl(Base, Result.Val);
19755
19756 LValue LVal;
19757 LVal.set(Base);
19758 // C++23 [intro.execution]/p5
19759 // A full-expression is [...] a constant-expression
19760 // So we need to make sure temporary objects are destroyed after having
19761 // evaluating the expression (per C++23 [class.temporary]/p4).
19762 FullExpressionRAII Scope(Info);
19763 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
19764 Result.HasSideEffects || !Scope.destroy())
19765 return false;
19766
19767 if (!Info.discardCleanups())
19768 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19769
19770 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
19771 Result.Val, Kind))
19772 return false;
19773 if (!CheckMemoryLeaks(Info))
19774 return false;
19775
19776 // If this is a class template argument, it's required to have constant
19777 // destruction too.
19778 if (Kind == ConstantExprKind::ClassTemplateArgument &&
19780 true) ||
19781 Result.HasSideEffects)) {
19782 // FIXME: Prefix a note to indicate that the problem is lack of constant
19783 // destruction.
19784 return false;
19785 }
19786
19787 return true;
19788}
19789
19791 const VarDecl *VD,
19793 bool IsConstantInitialization) const {
19794 assert(!isValueDependent() &&
19795 "Expression evaluator can't be called on a dependent expression.");
19796 assert(VD && "Need a valid VarDecl");
19797
19798 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
19799 std::string Name;
19800 llvm::raw_string_ostream OS(Name);
19801 VD->printQualifiedName(OS);
19802 return Name;
19803 });
19804
19805 Expr::EvalStatus EStatus;
19806 EStatus.Diag = &Notes;
19807
19808 EvalInfo Info(Ctx, EStatus,
19809 (IsConstantInitialization &&
19810 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
19813 Info.setEvaluatingDecl(VD, Value);
19814 Info.InConstantContext = IsConstantInitialization;
19815
19816 SourceLocation DeclLoc = VD->getLocation();
19817 QualType DeclTy = VD->getType();
19818
19819 if (Info.EnableNewConstInterp) {
19820 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
19821 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
19822 return false;
19823
19824 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19825 ConstantExprKind::Normal);
19826 } else {
19827 LValue LVal;
19828 LVal.set(VD);
19829
19830 {
19831 // C++23 [intro.execution]/p5
19832 // A full-expression is ... an init-declarator ([dcl.decl]) or a
19833 // mem-initializer.
19834 // So we need to make sure temporary objects are destroyed after having
19835 // evaluated the expression (per C++23 [class.temporary]/p4).
19836 //
19837 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
19838 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
19839 // outermost FullExpr, such as ExprWithCleanups.
19840 FullExpressionRAII Scope(Info);
19841 if (!EvaluateInPlace(Value, Info, LVal, this,
19842 /*AllowNonLiteralTypes=*/true) ||
19843 EStatus.HasSideEffects)
19844 return false;
19845 }
19846
19847 // At this point, any lifetime-extended temporaries are completely
19848 // initialized.
19849 Info.performLifetimeExtension();
19850
19851 if (!Info.discardCleanups())
19852 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
19853 }
19854
19855 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
19856 ConstantExprKind::Normal) &&
19857 CheckMemoryLeaks(Info);
19858}
19859
19862 Expr::EvalStatus EStatus;
19863 EStatus.Diag = &Notes;
19864
19865 // Only treat the destruction as constant destruction if we formally have
19866 // constant initialization (or are usable in a constant expression).
19867 bool IsConstantDestruction = hasConstantInitialization();
19868
19869 // Make a copy of the value for the destructor to mutate, if we know it.
19870 // Otherwise, treat the value as default-initialized; if the destructor works
19871 // anyway, then the destruction is constant (and must be essentially empty).
19872 APValue DestroyedValue;
19873 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
19874 DestroyedValue = *getEvaluatedValue();
19875 else if (!handleDefaultInitValue(getType(), DestroyedValue))
19876 return false;
19877
19878 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
19879 getType(), getLocation(), EStatus,
19880 IsConstantDestruction) ||
19881 EStatus.HasSideEffects)
19882 return false;
19883
19884 ensureEvaluatedStmt()->HasConstantDestruction = true;
19885 return true;
19886}
19887
19888/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
19889/// constant folded, but discard the result.
19891 assert(!isValueDependent() &&
19892 "Expression evaluator can't be called on a dependent expression.");
19893
19895 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
19897}
19898
19899APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
19900 assert(!isValueDependent() &&
19901 "Expression evaluator can't be called on a dependent expression.");
19902
19903 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
19904 EvalResult EVResult;
19905 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19906 Info.InConstantContext = true;
19907
19908 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
19909 (void)Result;
19910 assert(Result && "Could not evaluate expression");
19911 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19912
19913 return EVResult.Val.getInt();
19914}
19915
19918 assert(!isValueDependent() &&
19919 "Expression evaluator can't be called on a dependent expression.");
19920
19921 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
19922 EvalResult EVResult;
19923 EVResult.Diag = Diag;
19924 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19925 Info.InConstantContext = true;
19926 Info.CheckingForUndefinedBehavior = true;
19927
19928 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
19929 (void)Result;
19930 assert(Result && "Could not evaluate expression");
19931 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
19932
19933 return EVResult.Val.getInt();
19934}
19935
19937 assert(!isValueDependent() &&
19938 "Expression evaluator can't be called on a dependent expression.");
19939
19940 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
19941 bool IsConst;
19942 EvalResult EVResult;
19943 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
19944 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
19945 Info.CheckingForUndefinedBehavior = true;
19946 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
19947 }
19948}
19949
19951 assert(Val.isLValue());
19952 return IsGlobalLValue(Val.getLValueBase());
19953}
19954
19955/// isIntegerConstantExpr - this recursive routine will test if an expression is
19956/// an integer constant expression.
19957
19958/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
19959/// comma, etc
19960
19961// CheckICE - This function does the fundamental ICE checking: the returned
19962// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
19963//
19964// Note that to reduce code duplication, this helper does no evaluation
19965// itself; the caller checks whether the expression is evaluatable, and
19966// in the rare cases where CheckICE actually cares about the evaluated
19967// value, it calls into Evaluate.
19968
19969namespace {
19970
19971enum ICEKind {
19972 /// This expression is an ICE.
19973 IK_ICE,
19974 /// This expression is not an ICE, but if it isn't evaluated, it's
19975 /// a legal subexpression for an ICE. This return value is used to handle
19976 /// the comma operator in C99 mode, and non-constant subexpressions.
19977 IK_ICEIfUnevaluated,
19978 /// This expression is not an ICE, and is not a legal subexpression for one.
19979 IK_NotICE
19980};
19981
19982struct ICEDiag {
19983 ICEKind Kind;
19984 SourceLocation Loc;
19985
19986 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
19987};
19988
19989}
19990
19991static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
19992
19993static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
19994
19995static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
19996 Expr::EvalResult EVResult;
19997 Expr::EvalStatus Status;
19998 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
19999
20000 Info.InConstantContext = true;
20001 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
20002 !EVResult.Val.isInt())
20003 return ICEDiag(IK_NotICE, E->getBeginLoc());
20004
20005 return NoDiag();
20006}
20007
20008static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
20009 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
20011 return ICEDiag(IK_NotICE, E->getBeginLoc());
20012
20013 switch (E->getStmtClass()) {
20014#define ABSTRACT_STMT(Node)
20015#define STMT(Node, Base) case Expr::Node##Class:
20016#define EXPR(Node, Base)
20017#include "clang/AST/StmtNodes.inc"
20018 case Expr::PredefinedExprClass:
20019 case Expr::FloatingLiteralClass:
20020 case Expr::ImaginaryLiteralClass:
20021 case Expr::StringLiteralClass:
20022 case Expr::ArraySubscriptExprClass:
20023 case Expr::MatrixSubscriptExprClass:
20024 case Expr::ArraySectionExprClass:
20025 case Expr::OMPArrayShapingExprClass:
20026 case Expr::OMPIteratorExprClass:
20027 case Expr::MemberExprClass:
20028 case Expr::CompoundAssignOperatorClass:
20029 case Expr::CompoundLiteralExprClass:
20030 case Expr::ExtVectorElementExprClass:
20031 case Expr::DesignatedInitExprClass:
20032 case Expr::ArrayInitLoopExprClass:
20033 case Expr::ArrayInitIndexExprClass:
20034 case Expr::NoInitExprClass:
20035 case Expr::DesignatedInitUpdateExprClass:
20036 case Expr::ImplicitValueInitExprClass:
20037 case Expr::ParenListExprClass:
20038 case Expr::VAArgExprClass:
20039 case Expr::AddrLabelExprClass:
20040 case Expr::StmtExprClass:
20041 case Expr::CXXMemberCallExprClass:
20042 case Expr::CUDAKernelCallExprClass:
20043 case Expr::CXXAddrspaceCastExprClass:
20044 case Expr::CXXDynamicCastExprClass:
20045 case Expr::CXXTypeidExprClass:
20046 case Expr::CXXUuidofExprClass:
20047 case Expr::MSPropertyRefExprClass:
20048 case Expr::MSPropertySubscriptExprClass:
20049 case Expr::CXXNullPtrLiteralExprClass:
20050 case Expr::UserDefinedLiteralClass:
20051 case Expr::CXXThisExprClass:
20052 case Expr::CXXThrowExprClass:
20053 case Expr::CXXNewExprClass:
20054 case Expr::CXXDeleteExprClass:
20055 case Expr::CXXPseudoDestructorExprClass:
20056 case Expr::UnresolvedLookupExprClass:
20057 case Expr::RecoveryExprClass:
20058 case Expr::DependentScopeDeclRefExprClass:
20059 case Expr::CXXConstructExprClass:
20060 case Expr::CXXInheritedCtorInitExprClass:
20061 case Expr::CXXStdInitializerListExprClass:
20062 case Expr::CXXBindTemporaryExprClass:
20063 case Expr::ExprWithCleanupsClass:
20064 case Expr::CXXTemporaryObjectExprClass:
20065 case Expr::CXXUnresolvedConstructExprClass:
20066 case Expr::CXXDependentScopeMemberExprClass:
20067 case Expr::UnresolvedMemberExprClass:
20068 case Expr::ObjCStringLiteralClass:
20069 case Expr::ObjCBoxedExprClass:
20070 case Expr::ObjCArrayLiteralClass:
20071 case Expr::ObjCDictionaryLiteralClass:
20072 case Expr::ObjCEncodeExprClass:
20073 case Expr::ObjCMessageExprClass:
20074 case Expr::ObjCSelectorExprClass:
20075 case Expr::ObjCProtocolExprClass:
20076 case Expr::ObjCIvarRefExprClass:
20077 case Expr::ObjCPropertyRefExprClass:
20078 case Expr::ObjCSubscriptRefExprClass:
20079 case Expr::ObjCIsaExprClass:
20080 case Expr::ObjCAvailabilityCheckExprClass:
20081 case Expr::ShuffleVectorExprClass:
20082 case Expr::ConvertVectorExprClass:
20083 case Expr::BlockExprClass:
20084 case Expr::NoStmtClass:
20085 case Expr::OpaqueValueExprClass:
20086 case Expr::PackExpansionExprClass:
20087 case Expr::SubstNonTypeTemplateParmPackExprClass:
20088 case Expr::FunctionParmPackExprClass:
20089 case Expr::AsTypeExprClass:
20090 case Expr::ObjCIndirectCopyRestoreExprClass:
20091 case Expr::MaterializeTemporaryExprClass:
20092 case Expr::PseudoObjectExprClass:
20093 case Expr::AtomicExprClass:
20094 case Expr::LambdaExprClass:
20095 case Expr::CXXFoldExprClass:
20096 case Expr::CoawaitExprClass:
20097 case Expr::DependentCoawaitExprClass:
20098 case Expr::CoyieldExprClass:
20099 case Expr::SYCLUniqueStableNameExprClass:
20100 case Expr::CXXParenListInitExprClass:
20101 case Expr::HLSLOutArgExprClass:
20102 return ICEDiag(IK_NotICE, E->getBeginLoc());
20103
20104 case Expr::InitListExprClass: {
20105 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
20106 // form "T x = { a };" is equivalent to "T x = a;".
20107 // Unless we're initializing a reference, T is a scalar as it is known to be
20108 // of integral or enumeration type.
20109 if (E->isPRValue())
20110 if (cast<InitListExpr>(E)->getNumInits() == 1)
20111 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
20112 return ICEDiag(IK_NotICE, E->getBeginLoc());
20113 }
20114
20115 case Expr::SizeOfPackExprClass:
20116 case Expr::GNUNullExprClass:
20117 case Expr::SourceLocExprClass:
20118 case Expr::EmbedExprClass:
20119 case Expr::OpenACCAsteriskSizeExprClass:
20120 return NoDiag();
20121
20122 case Expr::PackIndexingExprClass:
20123 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
20124
20125 case Expr::SubstNonTypeTemplateParmExprClass:
20126 return
20127 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
20128
20129 case Expr::ConstantExprClass:
20130 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
20131
20132 case Expr::ParenExprClass:
20133 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
20134 case Expr::GenericSelectionExprClass:
20135 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
20136 case Expr::IntegerLiteralClass:
20137 case Expr::FixedPointLiteralClass:
20138 case Expr::CharacterLiteralClass:
20139 case Expr::ObjCBoolLiteralExprClass:
20140 case Expr::CXXBoolLiteralExprClass:
20141 case Expr::CXXScalarValueInitExprClass:
20142 case Expr::TypeTraitExprClass:
20143 case Expr::ConceptSpecializationExprClass:
20144 case Expr::RequiresExprClass:
20145 case Expr::ArrayTypeTraitExprClass:
20146 case Expr::ExpressionTraitExprClass:
20147 case Expr::CXXNoexceptExprClass:
20148 return NoDiag();
20149 case Expr::CallExprClass:
20150 case Expr::CXXOperatorCallExprClass: {
20151 // C99 6.6/3 allows function calls within unevaluated subexpressions of
20152 // constant expressions, but they can never be ICEs because an ICE cannot
20153 // contain an operand of (pointer to) function type.
20154 const CallExpr *CE = cast<CallExpr>(E);
20155 if (CE->getBuiltinCallee())
20156 return CheckEvalInICE(E, Ctx);
20157 return ICEDiag(IK_NotICE, E->getBeginLoc());
20158 }
20159 case Expr::CXXRewrittenBinaryOperatorClass:
20160 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
20161 Ctx);
20162 case Expr::DeclRefExprClass: {
20163 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
20164 if (isa<EnumConstantDecl>(D))
20165 return NoDiag();
20166
20167 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
20168 // integer variables in constant expressions:
20169 //
20170 // C++ 7.1.5.1p2
20171 // A variable of non-volatile const-qualified integral or enumeration
20172 // type initialized by an ICE can be used in ICEs.
20173 //
20174 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
20175 // that mode, use of reference variables should not be allowed.
20176 const VarDecl *VD = dyn_cast<VarDecl>(D);
20177 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
20178 !VD->getType()->isReferenceType())
20179 return NoDiag();
20180
20181 return ICEDiag(IK_NotICE, E->getBeginLoc());
20182 }
20183 case Expr::UnaryOperatorClass: {
20184 const UnaryOperator *Exp = cast<UnaryOperator>(E);
20185 switch (Exp->getOpcode()) {
20186 case UO_PostInc:
20187 case UO_PostDec:
20188 case UO_PreInc:
20189 case UO_PreDec:
20190 case UO_AddrOf:
20191 case UO_Deref:
20192 case UO_Coawait:
20193 // C99 6.6/3 allows increment and decrement within unevaluated
20194 // subexpressions of constant expressions, but they can never be ICEs
20195 // because an ICE cannot contain an lvalue operand.
20196 return ICEDiag(IK_NotICE, E->getBeginLoc());
20197 case UO_Extension:
20198 case UO_LNot:
20199 case UO_Plus:
20200 case UO_Minus:
20201 case UO_Not:
20202 case UO_Real:
20203 case UO_Imag:
20204 return CheckICE(Exp->getSubExpr(), Ctx);
20205 }
20206 llvm_unreachable("invalid unary operator class");
20207 }
20208 case Expr::OffsetOfExprClass: {
20209 // Note that per C99, offsetof must be an ICE. And AFAIK, using
20210 // EvaluateAsRValue matches the proposed gcc behavior for cases like
20211 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
20212 // compliance: we should warn earlier for offsetof expressions with
20213 // array subscripts that aren't ICEs, and if the array subscripts
20214 // are ICEs, the value of the offsetof must be an integer constant.
20215 return CheckEvalInICE(E, Ctx);
20216 }
20217 case Expr::UnaryExprOrTypeTraitExprClass: {
20219 if ((Exp->getKind() == UETT_SizeOf) &&
20221 return ICEDiag(IK_NotICE, E->getBeginLoc());
20222 if (Exp->getKind() == UETT_CountOf) {
20223 QualType ArgTy = Exp->getTypeOfArgument();
20224 if (ArgTy->isVariableArrayType()) {
20225 // We need to look whether the array is multidimensional. If it is,
20226 // then we want to check the size expression manually to see whether
20227 // it is an ICE or not.
20228 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
20229 if (VAT->getElementType()->isArrayType())
20230 // Variable array size expression could be missing (e.g. int a[*][10])
20231 // In that case, it can't be a constant expression.
20232 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
20233 : ICEDiag(IK_NotICE, E->getBeginLoc());
20234
20235 // Otherwise, this is a regular VLA, which is definitely not an ICE.
20236 return ICEDiag(IK_NotICE, E->getBeginLoc());
20237 }
20238 }
20239 return NoDiag();
20240 }
20241 case Expr::BinaryOperatorClass: {
20242 const BinaryOperator *Exp = cast<BinaryOperator>(E);
20243 switch (Exp->getOpcode()) {
20244 case BO_PtrMemD:
20245 case BO_PtrMemI:
20246 case BO_Assign:
20247 case BO_MulAssign:
20248 case BO_DivAssign:
20249 case BO_RemAssign:
20250 case BO_AddAssign:
20251 case BO_SubAssign:
20252 case BO_ShlAssign:
20253 case BO_ShrAssign:
20254 case BO_AndAssign:
20255 case BO_XorAssign:
20256 case BO_OrAssign:
20257 // C99 6.6/3 allows assignments within unevaluated subexpressions of
20258 // constant expressions, but they can never be ICEs because an ICE cannot
20259 // contain an lvalue operand.
20260 return ICEDiag(IK_NotICE, E->getBeginLoc());
20261
20262 case BO_Mul:
20263 case BO_Div:
20264 case BO_Rem:
20265 case BO_Add:
20266 case BO_Sub:
20267 case BO_Shl:
20268 case BO_Shr:
20269 case BO_LT:
20270 case BO_GT:
20271 case BO_LE:
20272 case BO_GE:
20273 case BO_EQ:
20274 case BO_NE:
20275 case BO_And:
20276 case BO_Xor:
20277 case BO_Or:
20278 case BO_Comma:
20279 case BO_Cmp: {
20280 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
20281 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
20282 if (Exp->getOpcode() == BO_Div ||
20283 Exp->getOpcode() == BO_Rem) {
20284 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
20285 // we don't evaluate one.
20286 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
20287 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
20288 if (REval == 0)
20289 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20290 if (REval.isSigned() && REval.isAllOnes()) {
20291 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
20292 if (LEval.isMinSignedValue())
20293 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20294 }
20295 }
20296 }
20297 if (Exp->getOpcode() == BO_Comma) {
20298 if (Ctx.getLangOpts().C99) {
20299 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
20300 // if it isn't evaluated.
20301 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
20302 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
20303 } else {
20304 // In both C89 and C++, commas in ICEs are illegal.
20305 return ICEDiag(IK_NotICE, E->getBeginLoc());
20306 }
20307 }
20308 return Worst(LHSResult, RHSResult);
20309 }
20310 case BO_LAnd:
20311 case BO_LOr: {
20312 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
20313 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
20314 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
20315 // Rare case where the RHS has a comma "side-effect"; we need
20316 // to actually check the condition to see whether the side
20317 // with the comma is evaluated.
20318 if ((Exp->getOpcode() == BO_LAnd) !=
20319 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
20320 return RHSResult;
20321 return NoDiag();
20322 }
20323
20324 return Worst(LHSResult, RHSResult);
20325 }
20326 }
20327 llvm_unreachable("invalid binary operator kind");
20328 }
20329 case Expr::ImplicitCastExprClass:
20330 case Expr::CStyleCastExprClass:
20331 case Expr::CXXFunctionalCastExprClass:
20332 case Expr::CXXStaticCastExprClass:
20333 case Expr::CXXReinterpretCastExprClass:
20334 case Expr::CXXConstCastExprClass:
20335 case Expr::ObjCBridgedCastExprClass: {
20336 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
20337 if (isa<ExplicitCastExpr>(E)) {
20338 if (const FloatingLiteral *FL
20339 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
20340 unsigned DestWidth = Ctx.getIntWidth(E->getType());
20341 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
20342 APSInt IgnoredVal(DestWidth, !DestSigned);
20343 bool Ignored;
20344 // If the value does not fit in the destination type, the behavior is
20345 // undefined, so we are not required to treat it as a constant
20346 // expression.
20347 if (FL->getValue().convertToInteger(IgnoredVal,
20348 llvm::APFloat::rmTowardZero,
20349 &Ignored) & APFloat::opInvalidOp)
20350 return ICEDiag(IK_NotICE, E->getBeginLoc());
20351 return NoDiag();
20352 }
20353 }
20354 switch (cast<CastExpr>(E)->getCastKind()) {
20355 case CK_LValueToRValue:
20356 case CK_AtomicToNonAtomic:
20357 case CK_NonAtomicToAtomic:
20358 case CK_NoOp:
20359 case CK_IntegralToBoolean:
20360 case CK_IntegralCast:
20361 return CheckICE(SubExpr, Ctx);
20362 default:
20363 return ICEDiag(IK_NotICE, E->getBeginLoc());
20364 }
20365 }
20366 case Expr::BinaryConditionalOperatorClass: {
20368 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
20369 if (CommonResult.Kind == IK_NotICE) return CommonResult;
20370 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
20371 if (FalseResult.Kind == IK_NotICE) return FalseResult;
20372 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
20373 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
20374 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
20375 return FalseResult;
20376 }
20377 case Expr::ConditionalOperatorClass: {
20379 // If the condition (ignoring parens) is a __builtin_constant_p call,
20380 // then only the true side is actually considered in an integer constant
20381 // expression, and it is fully evaluated. This is an important GNU
20382 // extension. See GCC PR38377 for discussion.
20383 if (const CallExpr *CallCE
20384 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
20385 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
20386 return CheckEvalInICE(E, Ctx);
20387 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
20388 if (CondResult.Kind == IK_NotICE)
20389 return CondResult;
20390
20391 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
20392 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
20393
20394 if (TrueResult.Kind == IK_NotICE)
20395 return TrueResult;
20396 if (FalseResult.Kind == IK_NotICE)
20397 return FalseResult;
20398 if (CondResult.Kind == IK_ICEIfUnevaluated)
20399 return CondResult;
20400 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
20401 return NoDiag();
20402 // Rare case where the diagnostics depend on which side is evaluated
20403 // Note that if we get here, CondResult is 0, and at least one of
20404 // TrueResult and FalseResult is non-zero.
20405 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
20406 return FalseResult;
20407 return TrueResult;
20408 }
20409 case Expr::CXXDefaultArgExprClass:
20410 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
20411 case Expr::CXXDefaultInitExprClass:
20412 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
20413 case Expr::ChooseExprClass: {
20414 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
20415 }
20416 case Expr::BuiltinBitCastExprClass: {
20417 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
20418 return ICEDiag(IK_NotICE, E->getBeginLoc());
20419 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
20420 }
20421 }
20422
20423 llvm_unreachable("Invalid StmtClass!");
20424}
20425
20426/// Evaluate an expression as a C++11 integral constant expression.
20428 const Expr *E,
20429 llvm::APSInt *Value) {
20431 return false;
20432
20433 APValue Result;
20434 if (!E->isCXX11ConstantExpr(Ctx, &Result))
20435 return false;
20436
20437 if (!Result.isInt())
20438 return false;
20439
20440 if (Value) *Value = Result.getInt();
20441 return true;
20442}
20443
20445 assert(!isValueDependent() &&
20446 "Expression evaluator can't be called on a dependent expression.");
20447
20448 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
20449
20450 if (Ctx.getLangOpts().CPlusPlus11)
20451 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
20452
20453 ICEDiag D = CheckICE(this, Ctx);
20454 if (D.Kind != IK_ICE)
20455 return false;
20456 return true;
20457}
20458
20459std::optional<llvm::APSInt>
20461 if (isValueDependent()) {
20462 // Expression evaluator can't succeed on a dependent expression.
20463 return std::nullopt;
20464 }
20465
20466 if (Ctx.getLangOpts().CPlusPlus11) {
20467 APSInt Value;
20469 return Value;
20470 return std::nullopt;
20471 }
20472
20473 if (!isIntegerConstantExpr(Ctx))
20474 return std::nullopt;
20475
20476 // The only possible side-effects here are due to UB discovered in the
20477 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
20478 // required to treat the expression as an ICE, so we produce the folded
20479 // value.
20481 Expr::EvalStatus Status;
20482 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
20483 Info.InConstantContext = true;
20484
20485 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
20486 llvm_unreachable("ICE cannot be evaluated!");
20487
20488 return ExprResult.Val.getInt();
20489}
20490
20492 assert(!isValueDependent() &&
20493 "Expression evaluator can't be called on a dependent expression.");
20494
20495 return CheckICE(this, Ctx).Kind == IK_ICE;
20496}
20497
20499 assert(!isValueDependent() &&
20500 "Expression evaluator can't be called on a dependent expression.");
20501
20502 // We support this checking in C++98 mode in order to diagnose compatibility
20503 // issues.
20504 assert(Ctx.getLangOpts().CPlusPlus);
20505
20506 bool IsConst;
20507 APValue Scratch;
20508 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
20509 if (Result)
20510 *Result = Scratch;
20511 return true;
20512 }
20513
20514 // Build evaluation settings.
20515 Expr::EvalStatus Status;
20517 Status.Diag = &Diags;
20518 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
20519
20520 bool IsConstExpr =
20521 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
20522 // FIXME: We don't produce a diagnostic for this, but the callers that
20523 // call us on arbitrary full-expressions should generally not care.
20524 Info.discardCleanups() && !Status.HasSideEffects;
20525
20526 return IsConstExpr && Diags.empty();
20527}
20528
20530 const FunctionDecl *Callee,
20532 const Expr *This) const {
20533 assert(!isValueDependent() &&
20534 "Expression evaluator can't be called on a dependent expression.");
20535
20536 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
20537 std::string Name;
20538 llvm::raw_string_ostream OS(Name);
20539 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
20540 /*Qualified=*/true);
20541 return Name;
20542 });
20543
20544 Expr::EvalStatus Status;
20545 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
20546 Info.InConstantContext = true;
20547
20548 LValue ThisVal;
20549 const LValue *ThisPtr = nullptr;
20550 if (This) {
20551#ifndef NDEBUG
20552 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
20553 assert(MD && "Don't provide `this` for non-methods.");
20554 assert(MD->isImplicitObjectMemberFunction() &&
20555 "Don't provide `this` for methods without an implicit object.");
20556#endif
20557 if (!This->isValueDependent() &&
20558 EvaluateObjectArgument(Info, This, ThisVal) &&
20559 !Info.EvalStatus.HasSideEffects)
20560 ThisPtr = &ThisVal;
20561
20562 // Ignore any side-effects from a failed evaluation. This is safe because
20563 // they can't interfere with any other argument evaluation.
20564 Info.EvalStatus.HasSideEffects = false;
20565 }
20566
20567 CallRef Call = Info.CurrentCall->createCall(Callee);
20568 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
20569 I != E; ++I) {
20570 unsigned Idx = I - Args.begin();
20571 if (Idx >= Callee->getNumParams())
20572 break;
20573 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
20574 if ((*I)->isValueDependent() ||
20575 !EvaluateCallArg(PVD, *I, Call, Info) ||
20576 Info.EvalStatus.HasSideEffects) {
20577 // If evaluation fails, throw away the argument entirely.
20578 if (APValue *Slot = Info.getParamSlot(Call, PVD))
20579 *Slot = APValue();
20580 }
20581
20582 // Ignore any side-effects from a failed evaluation. This is safe because
20583 // they can't interfere with any other argument evaluation.
20584 Info.EvalStatus.HasSideEffects = false;
20585 }
20586
20587 // Parameter cleanups happen in the caller and are not part of this
20588 // evaluation.
20589 Info.discardCleanups();
20590 Info.EvalStatus.HasSideEffects = false;
20591
20592 // Build fake call to Callee.
20593 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
20594 Call);
20595 // FIXME: Missing ExprWithCleanups in enable_if conditions?
20596 FullExpressionRAII Scope(Info);
20597 return Evaluate(Value, Info, this) && Scope.destroy() &&
20598 !Info.EvalStatus.HasSideEffects;
20599}
20600
20603 PartialDiagnosticAt> &Diags) {
20604 // FIXME: It would be useful to check constexpr function templates, but at the
20605 // moment the constant expression evaluator cannot cope with the non-rigorous
20606 // ASTs which we build for dependent expressions.
20607 if (FD->isDependentContext())
20608 return true;
20609
20610 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
20611 std::string Name;
20612 llvm::raw_string_ostream OS(Name);
20614 /*Qualified=*/true);
20615 return Name;
20616 });
20617
20618 Expr::EvalStatus Status;
20619 Status.Diag = &Diags;
20620
20621 EvalInfo Info(FD->getASTContext(), Status,
20623 Info.InConstantContext = true;
20624 Info.CheckingPotentialConstantExpression = true;
20625
20626 // The constexpr VM attempts to compile all methods to bytecode here.
20627 if (Info.EnableNewConstInterp) {
20628 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
20629 return Diags.empty();
20630 }
20631
20632 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
20633 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
20634
20635 // Fabricate an arbitrary expression on the stack and pretend that it
20636 // is a temporary being used as the 'this' pointer.
20637 LValue This;
20638 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
20639 : Info.Ctx.IntTy);
20640 This.set({&VIE, Info.CurrentCall->Index});
20641
20643
20644 APValue Scratch;
20645 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
20646 // Evaluate the call as a constant initializer, to allow the construction
20647 // of objects of non-literal types.
20648 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
20649 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
20650 } else {
20651 SourceLocation Loc = FD->getLocation();
20653 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
20654 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
20655 /*ResultSlot=*/nullptr);
20656 }
20657
20658 return Diags.empty();
20659}
20660
20662 const FunctionDecl *FD,
20664 PartialDiagnosticAt> &Diags) {
20665 assert(!E->isValueDependent() &&
20666 "Expression evaluator can't be called on a dependent expression.");
20667
20668 Expr::EvalStatus Status;
20669 Status.Diag = &Diags;
20670
20671 EvalInfo Info(FD->getASTContext(), Status,
20673 Info.InConstantContext = true;
20674 Info.CheckingPotentialConstantExpression = true;
20675
20676 if (Info.EnableNewConstInterp) {
20678 return Diags.empty();
20679 }
20680
20681 // Fabricate a call stack frame to give the arguments a plausible cover story.
20682 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
20683 /*CallExpr=*/nullptr, CallRef());
20684
20685 APValue ResultScratch;
20686 Evaluate(ResultScratch, Info, E);
20687 return Diags.empty();
20688}
20689
20691 unsigned Type) const {
20692 if (!getType()->isPointerType())
20693 return false;
20694
20695 Expr::EvalStatus Status;
20696 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20697 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
20698}
20699
20700static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
20701 EvalInfo &Info, std::string *StringResult) {
20702 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
20703 return false;
20704
20705 LValue String;
20706
20707 if (!EvaluatePointer(E, String, Info))
20708 return false;
20709
20710 QualType CharTy = E->getType()->getPointeeType();
20711
20712 // Fast path: if it's a string literal, search the string value.
20713 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
20714 String.getLValueBase().dyn_cast<const Expr *>())) {
20715 StringRef Str = S->getBytes();
20716 int64_t Off = String.Offset.getQuantity();
20717 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
20718 S->getCharByteWidth() == 1 &&
20719 // FIXME: Add fast-path for wchar_t too.
20720 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
20721 Str = Str.substr(Off);
20722
20723 StringRef::size_type Pos = Str.find(0);
20724 if (Pos != StringRef::npos)
20725 Str = Str.substr(0, Pos);
20726
20727 Result = Str.size();
20728 if (StringResult)
20729 *StringResult = Str;
20730 return true;
20731 }
20732
20733 // Fall through to slow path.
20734 }
20735
20736 // Slow path: scan the bytes of the string looking for the terminating 0.
20737 for (uint64_t Strlen = 0; /**/; ++Strlen) {
20738 APValue Char;
20739 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
20740 !Char.isInt())
20741 return false;
20742 if (!Char.getInt()) {
20743 Result = Strlen;
20744 return true;
20745 } else if (StringResult)
20746 StringResult->push_back(Char.getInt().getExtValue());
20747 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
20748 return false;
20749 }
20750}
20751
20752std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
20753 Expr::EvalStatus Status;
20754 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20755 uint64_t Result;
20756 std::string StringResult;
20757
20758 if (Info.EnableNewConstInterp) {
20759 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
20760 return std::nullopt;
20761 return StringResult;
20762 }
20763
20764 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
20765 return StringResult;
20766 return std::nullopt;
20767}
20768
20769template <typename T>
20770static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
20771 const Expr *SizeExpression,
20772 const Expr *PtrExpression,
20773 ASTContext &Ctx,
20774 Expr::EvalResult &Status) {
20775 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
20776 Info.InConstantContext = true;
20777
20778 if (Info.EnableNewConstInterp)
20779 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
20780 PtrExpression, Result);
20781
20782 LValue String;
20783 FullExpressionRAII Scope(Info);
20784 APSInt SizeValue;
20785 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
20786 return false;
20787
20788 uint64_t Size = SizeValue.getZExtValue();
20789
20790 // FIXME: better protect against invalid or excessive sizes
20791 if constexpr (std::is_same_v<APValue, T>)
20792 Result = APValue(APValue::UninitArray{}, Size, Size);
20793 else {
20794 if (Size < Result.max_size())
20795 Result.reserve(Size);
20796 }
20797 if (!::EvaluatePointer(PtrExpression, String, Info))
20798 return false;
20799
20800 QualType CharTy = PtrExpression->getType()->getPointeeType();
20801 for (uint64_t I = 0; I < Size; ++I) {
20802 APValue Char;
20803 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
20804 Char))
20805 return false;
20806
20807 if constexpr (std::is_same_v<APValue, T>) {
20808 Result.getArrayInitializedElt(I) = std::move(Char);
20809 } else {
20810 APSInt C = Char.getInt();
20811
20812 assert(C.getBitWidth() <= 8 &&
20813 "string element not representable in char");
20814
20815 Result.push_back(static_cast<char>(C.getExtValue()));
20816 }
20817
20818 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
20819 return false;
20820 }
20821
20822 return Scope.destroy() && CheckMemoryLeaks(Info);
20823}
20824
20826 const Expr *SizeExpression,
20827 const Expr *PtrExpression, ASTContext &Ctx,
20828 EvalResult &Status) const {
20829 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20830 PtrExpression, Ctx, Status);
20831}
20832
20834 const Expr *SizeExpression,
20835 const Expr *PtrExpression, ASTContext &Ctx,
20836 EvalResult &Status) const {
20837 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
20838 PtrExpression, Ctx, Status);
20839}
20840
20841bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
20842 Expr::EvalStatus Status;
20843 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
20844
20845 if (Info.EnableNewConstInterp)
20846 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
20847
20848 return EvaluateBuiltinStrLen(this, Result, Info);
20849}
20850
20851namespace {
20852struct IsWithinLifetimeHandler {
20853 EvalInfo &Info;
20854 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
20855 using result_type = std::optional<bool>;
20856 std::optional<bool> failed() { return std::nullopt; }
20857 template <typename T>
20858 std::optional<bool> found(T &Subobj, QualType SubobjType) {
20859 return true;
20860 }
20861};
20862
20863std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
20864 const CallExpr *E) {
20865 EvalInfo &Info = IEE.Info;
20866 // Sometimes this is called during some sorts of constant folding / early
20867 // evaluation. These are meant for non-constant expressions and are not
20868 // necessary since this consteval builtin will never be evaluated at runtime.
20869 // Just fail to evaluate when not in a constant context.
20870 if (!Info.InConstantContext)
20871 return std::nullopt;
20872 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
20873 const Expr *Arg = E->getArg(0);
20874 if (Arg->isValueDependent())
20875 return std::nullopt;
20876 LValue Val;
20877 if (!EvaluatePointer(Arg, Val, Info))
20878 return std::nullopt;
20879
20880 if (Val.allowConstexprUnknown())
20881 return true;
20882
20883 auto Error = [&](int Diag) {
20884 bool CalledFromStd = false;
20885 const auto *Callee = Info.CurrentCall->getCallee();
20886 if (Callee && Callee->isInStdNamespace()) {
20887 const IdentifierInfo *Identifier = Callee->getIdentifier();
20888 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
20889 }
20890 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
20891 : E->getExprLoc(),
20892 diag::err_invalid_is_within_lifetime)
20893 << (CalledFromStd ? "std::is_within_lifetime"
20894 : "__builtin_is_within_lifetime")
20895 << Diag;
20896 return std::nullopt;
20897 };
20898 // C++2c [meta.const.eval]p4:
20899 // During the evaluation of an expression E as a core constant expression, a
20900 // call to this function is ill-formed unless p points to an object that is
20901 // usable in constant expressions or whose complete object's lifetime began
20902 // within E.
20903
20904 // Make sure it points to an object
20905 // nullptr does not point to an object
20906 if (Val.isNullPointer() || Val.getLValueBase().isNull())
20907 return Error(0);
20908 QualType T = Val.getLValueBase().getType();
20909 assert(!T->isFunctionType() &&
20910 "Pointers to functions should have been typed as function pointers "
20911 "which would have been rejected earlier");
20912 assert(T->isObjectType());
20913 // Hypothetical array element is not an object
20914 if (Val.getLValueDesignator().isOnePastTheEnd())
20915 return Error(1);
20916 assert(Val.getLValueDesignator().isValidSubobject() &&
20917 "Unchecked case for valid subobject");
20918 // All other ill-formed values should have failed EvaluatePointer, so the
20919 // object should be a pointer to an object that is usable in a constant
20920 // expression or whose complete lifetime began within the expression
20921 CompleteObject CO =
20922 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
20923 // The lifetime hasn't begun yet if we are still evaluating the
20924 // initializer ([basic.life]p(1.2))
20925 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
20926 return Error(2);
20927
20928 if (!CO)
20929 return false;
20930 IsWithinLifetimeHandler handler{Info};
20931 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
20932}
20933} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
llvm::APSInt APSInt
Definition Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
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 evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
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 handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
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 bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
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 bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:584
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isAbsent() const
Definition APValue.h:463
bool isComplexInt() const
Definition APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:204
ValueKind getKind() const
Definition APValue.h:461
unsigned getArrayInitializedElts() const
Definition APValue.h:595
static APValue IndeterminateValue()
Definition APValue.h:432
bool isFloat() const
Definition APValue.h:468
APFixedPoint & getFixedPoint()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:465
bool hasLValuePath() const
Definition APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
CharUnits & getLValueOffset()
Definition APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
APValue & getArrayFiller()
Definition APValue.h:587
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1059
bool isIndeterminate() const
Definition APValue.h:464
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool allowConstexprUnknown() const
Definition APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
bool isFixedPoint() const
Definition APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
APValue & getStructBase(unsigned i)
Definition APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:845
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
CanQualType VoidPtrTy
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:786
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:938
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<=>,...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CanQualType CharTy
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType IntTy
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:837
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:903
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4507
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
uint64_t getValue() const
Definition ExprCXX.h:3046
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8077
Attr - This represents one attribute.
Definition Attr.h:45
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4387
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4425
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4422
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4105
Expr * getLHS() const
Definition Expr.h:4022
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4066
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4072
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4119
SourceLocation getExprLoc() const
Definition Expr.h:4013
Expr * getRHS() const
Definition Expr.h:4024
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4058
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4049
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4108
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4017
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4773
const BlockDecl * getBlockDecl() const
Definition Expr.h:6570
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:431
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1618
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2690
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2667
bool isArrayForm() const
Definition ExprCXX.h:2654
bool isGlobalDelete() const
Definition ExprCXX.h:2653
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1790
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isInstance() const
Definition DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2845
QualType getAllocatedType() const
Definition ExprCXX.h:2436
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2471
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2505
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2496
SourceRange getSourceRange() const
Definition ExprCXX.h:2612
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2461
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2535
bool getValue() const
Definition ExprCXX.h:4334
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1673
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1784
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
bool isImplicit() const
Definition ExprCXX.h:1178
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
SourceLocation getBeginLoc() const
Definition Expr.h:3211
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3572
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3071
Decl * getCalleeDecl()
Definition Expr.h:3054
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1602
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
Definition Stmt.h:1900
Expr * getLHS()
Definition Stmt.h:1983
Expr * getRHS()
Definition Stmt.h:1995
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3610
path_iterator path_begin()
Definition Expr.h:3680
unsigned path_size() const
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3654
path_iterator path_end()
Definition Expr.h:3681
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3677
bool path_empty() const
Definition Expr.h:3678
Expr * getSubExpr()
Definition Expr.h:3660
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3724
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1629
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4818
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4234
QualType getComputationLHSType() const
Definition Expr.h:4268
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
bool hasStaticStorage() const
Definition Expr.h:3584
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5566
bool isFileScope() const
Definition Expr.h:3571
const Expr * getInitializer() const
Definition Expr.h:3567
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
bool body_empty() const
Definition Stmt.h:1764
Stmt *const * const_body_iterator
Definition Stmt.h:1792
body_iterator body_end()
Definition Stmt.h:1785
body_range body()
Definition Stmt.h:1783
body_iterator body_begin()
Definition Stmt.h:1784
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4325
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4357
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4348
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4352
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3823
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:3849
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3830
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
APValue getAPValueResult() const
Definition Expr.cpp:412
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4730
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4743
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
ValueDecl * getDecl()
Definition Expr.h:1338
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
decl_range decls()
Definition Stmt.h:1659
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
A decomposition declaration.
Definition DeclCXX.h:4245
auto flat_bindings() const
Definition DeclCXX.h:4288
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2812
Stmt * getBody()
Definition Stmt.h:2837
Expr * getCond()
Definition Stmt.h:2830
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
ChildElementIter< false > begin()
Definition Expr.h:5166
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3889
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:83
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:3093
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3966
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3088
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:3084
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:3668
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:3251
Expr()=delete
ConstantExprKind
Definition Expr.h:749
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4413
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4445
const Expr * getBase() const
Definition Expr.h:6515
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4741
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3407
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:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1575
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2868
Stmt * getInit()
Definition Stmt.h:2883
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1082
Stmt * getBody()
Definition Stmt.h:2912
Expr * getInc()
Definition Stmt.h:2911
Expr * getCond()
Definition Stmt.h:2910
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3268
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4194
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4182
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4318
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2783
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
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:3415
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
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:3114
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6396
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2239
Stmt * getThen()
Definition Stmt.h:2328
Stmt * getInit()
Definition Stmt.h:2389
bool isNonNegatedConsteval() const
Definition Stmt.h:2424
Expr * getCond()
Definition Stmt.h:2316
Stmt * getElse()
Definition Stmt.h:2337
bool isConsteval() const
Definition Stmt.h:2419
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1030
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:5991
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2460
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2446
unsigned getNumInits() const
Definition Expr.h:5263
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
ArrayRef< Expr * > inits()
Definition Expr.h:5283
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2108
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2096
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4922
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4947
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4939
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4955
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
bool isArrow() const
Definition Expr.h:3482
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2586
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2574
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2567
unsigned getNumComponents() const
Definition Expr.h:2582
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2479
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2426
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2430
@ Field
A field.
Definition Expr.h:2428
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2433
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2475
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
Expr * getSelectedExpr() const
Definition ExprCXX.h:4641
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
bool isExplicitObjectParameter() const
Definition Decl.h:1878
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6738
ArrayRef< Expr * > semantics()
Definition Expr.h:6762
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
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:8278
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:8463
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
void removeLocalVolatile()
Definition TypeBase.h:8394
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8386
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
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:8324
Represents a struct/union/class.
Definition Decl.h:4312
field_iterator field_end() const
Definition Decl.h:4518
field_range fields() const
Definition Decl.h:4515
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4512
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4364
bool field_empty() const
Definition Decl.h:4523
field_iterator field_begin() const
Definition Decl.cpp:5202
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2155
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:586
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4577
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4629
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4610
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4616
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4517
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2280
bool isIntType() const
Definition Expr.h:4975
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Definition Expr.h:4546
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
unsigned getLength() const
Definition Expr.h:1909
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1875
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
unsigned getCharByteWidth() const
Definition Expr.h:1910
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1873
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2489
Expr * getCond()
Definition Stmt.h:2552
Stmt * getBody()
Definition Stmt.h:2564
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1148
Stmt * getInit()
Definition Stmt.h:2569
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2620
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4888
bool isUnion() const
Definition Decl.h:3922
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:856
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
unsigned getCharWidth() const
Definition TargetInfo.h:518
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
bool getBoolValue() const
Definition ExprCXX.h:2949
const APValue & getAPValue() const
Definition ExprCXX.h:2954
bool isStoredAsBoolean() const
Definition ExprCXX.h:2945
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isFunctionReferenceType() const
Definition TypeBase.h:8589
bool isMFloat8Type() const
Definition TypeBase.h:8896
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:418
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2993
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9167
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8618
bool isNothrowT() const
Definition Type.cpp:3170
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:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
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:8989
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
bool isMemberDataPointerType() const
Definition TypeBase.h:8607
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8650
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isMemberPointerType() const
Definition TypeBase.h:8596
bool isAtomicType() const
Definition TypeBase.h:8697
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:9144
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isVectorType() const
Definition TypeBase.h:8654
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9035
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
QualType getArgumentType() const
Definition Expr.h:2668
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2704
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2694
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2326
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2298
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5501
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
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:1578
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2575
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2877
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2648
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2486
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2557
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
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:1184
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:1253
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:1358
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2677
Expr * getCond()
Definition Stmt.h:2729
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1209
Stmt * getBody()
Definition Stmt.h:2741
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:227
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:243
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:289
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:60
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:40
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:73
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:103
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:42
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2795
llvm::APFloat APFloat
Definition Floating.h:27
llvm::APInt APInt
Definition FixedPoint.h:19
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3514
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:42
@ CSK_ArrayToPointer
Definition State.h:46
@ CSK_Derived
Definition State.h:44
@ CSK_Base
Definition State.h:43
@ CSK_Real
Definition State.h:48
@ CSK_ArrayIndex
Definition State.h:47
@ CSK_Imag
Definition State.h:49
@ CSK_VectorElement
Definition State.h:50
@ CSK_Field
Definition State.h:45
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:26
@ AK_TypeId
Definition State.h:34
@ AK_Construct
Definition State.h:35
@ AK_Increment
Definition State.h:30
@ AK_DynamicCast
Definition State.h:33
@ AK_Read
Definition State.h:27
@ AK_Assign
Definition State.h:29
@ AK_IsWithinLifetime
Definition State.h:37
@ AK_MemberCall
Definition State.h:32
@ AK_ReadObjectRepresentation
Definition State.h:28
@ AK_Dereference
Definition State.h:38
@ AK_Destroy
Definition State.h:36
@ AK_Decrement
Definition State.h:31
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:609
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define trunc(__x)
Definition tgmath.h:1216
#define scalbn(__x, __y)
Definition tgmath.h:1165