clang 23.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 final : public interp::State {
798 public:
799 /// CurrentCall - The top of the constexpr call stack.
800 CallStackFrame *CurrentCall;
801
802 /// CallStackDepth - The number of calls in the call stack right now.
803 unsigned CallStackDepth;
804
805 /// NextCallIndex - The next call index to assign.
806 unsigned NextCallIndex;
807
808 /// StepsLeft - The remaining number of evaluation steps we're permitted
809 /// to perform. This is essentially a limit for the number of statements
810 /// we will evaluate.
811 unsigned StepsLeft;
812
813 /// Enable the experimental new constant interpreter. If an expression is
814 /// not supported by the interpreter, an error is triggered.
815 bool EnableNewConstInterp;
816
817 /// BottomFrame - The frame in which evaluation started. This must be
818 /// initialized after CurrentCall and CallStackDepth.
819 CallStackFrame BottomFrame;
820
821 /// A stack of values whose lifetimes end at the end of some surrounding
822 /// evaluation frame.
823 llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825 /// EvaluatingDecl - This is the declaration whose initializer is being
826 /// evaluated, if any.
827 APValue::LValueBase EvaluatingDecl;
828
829 enum class EvaluatingDeclKind {
830 None,
831 /// We're evaluating the construction of EvaluatingDecl.
832 Ctor,
833 /// We're evaluating the destruction of EvaluatingDecl.
834 Dtor,
835 };
836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838 /// EvaluatingDeclValue - This is the value being constructed for the
839 /// declaration whose initializer is being evaluated, if any.
840 APValue *EvaluatingDeclValue;
841
842 /// Stack of loops and 'switch' statements which we're currently
843 /// breaking/continuing; null entries are used to mark unlabeled
844 /// break/continue.
845 SmallVector<const Stmt *> BreakContinueStack;
846
847 /// Set of objects that are currently being constructed.
848 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
849 ObjectsUnderConstruction;
850
851 /// Current heap allocations, along with the location where each was
852 /// allocated. We use std::map here because we need stable addresses
853 /// for the stored APValues.
854 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
855
856 /// The number of heap allocations performed so far in this evaluation.
857 unsigned NumHeapAllocs = 0;
858
859 struct EvaluatingConstructorRAII {
860 EvalInfo &EI;
861 ObjectUnderConstruction Object;
862 bool DidInsert;
863 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
864 bool HasBases)
865 : EI(EI), Object(Object) {
866 DidInsert =
867 EI.ObjectsUnderConstruction
868 .insert({Object, HasBases ? ConstructionPhase::Bases
869 : ConstructionPhase::AfterBases})
870 .second;
871 }
872 void finishedConstructingBases() {
873 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
874 }
875 void finishedConstructingFields() {
876 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
877 }
878 ~EvaluatingConstructorRAII() {
879 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
880 }
881 };
882
883 struct EvaluatingDestructorRAII {
884 EvalInfo &EI;
885 ObjectUnderConstruction Object;
886 bool DidInsert;
887 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
888 : EI(EI), Object(Object) {
889 DidInsert = EI.ObjectsUnderConstruction
890 .insert({Object, ConstructionPhase::Destroying})
891 .second;
892 }
893 void startedDestroyingBases() {
894 EI.ObjectsUnderConstruction[Object] =
895 ConstructionPhase::DestroyingBases;
896 }
897 ~EvaluatingDestructorRAII() {
898 if (DidInsert)
899 EI.ObjectsUnderConstruction.erase(Object);
900 }
901 };
902
903 ConstructionPhase
904 isEvaluatingCtorDtor(APValue::LValueBase Base,
905 ArrayRef<APValue::LValuePathEntry> Path) {
906 return ObjectsUnderConstruction.lookup({Base, Path});
907 }
908
909 /// If we're currently speculatively evaluating, the outermost call stack
910 /// depth at which we can mutate state, otherwise 0.
911 unsigned SpeculativeEvaluationDepth = 0;
912
913 /// The current array initialization index, if we're performing array
914 /// initialization.
915 uint64_t ArrayInitIndex = -1;
916
917 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
918 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
919 CallStackDepth(0), NextCallIndex(1),
920 StepsLeft(C.getLangOpts().ConstexprStepLimit),
921 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
922 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
923 /*This=*/nullptr,
924 /*CallExpr=*/nullptr, CallRef()),
925 EvaluatingDecl((const ValueDecl *)nullptr),
926 EvaluatingDeclValue(nullptr) {
927 EvalMode = Mode;
928 }
929
930 ~EvalInfo() {
931 discardCleanups();
932 }
933
934 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
935 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
936 EvaluatingDecl = Base;
937 IsEvaluatingDecl = EDK;
938 EvaluatingDeclValue = &Value;
939 }
940
941 bool CheckCallLimit(SourceLocation Loc) {
942 // Don't perform any constexpr calls (other than the call we're checking)
943 // when checking a potential constant expression.
944 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
945 return false;
946 if (NextCallIndex == 0) {
947 // NextCallIndex has wrapped around.
948 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
949 return false;
950 }
951 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
952 return true;
953 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
954 << getLangOpts().ConstexprCallDepth;
955 return false;
956 }
957
958 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
959 uint64_t ElemCount, bool Diag) {
960 // FIXME: GH63562
961 // APValue stores array extents as unsigned,
962 // so anything that is greater that unsigned would overflow when
963 // constructing the array, we catch this here.
964 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
965 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
966 if (Diag)
967 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
968 return false;
969 }
970
971 // FIXME: GH63562
972 // Arrays allocate an APValue per element.
973 // We use the number of constexpr steps as a proxy for the maximum size
974 // of arrays to avoid exhausting the system resources, as initialization
975 // of each element is likely to take some number of steps anyway.
976 uint64_t Limit = getLangOpts().ConstexprStepLimit;
977 if (Limit != 0 && ElemCount > Limit) {
978 if (Diag)
979 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
980 << ElemCount << Limit;
981 return false;
982 }
983 return true;
984 }
985
986 std::pair<CallStackFrame *, unsigned>
987 getCallFrameAndDepth(unsigned CallIndex) {
988 assert(CallIndex && "no call index in getCallFrameAndDepth");
989 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
990 // be null in this loop.
991 unsigned Depth = CallStackDepth;
992 CallStackFrame *Frame = CurrentCall;
993 while (Frame->Index > CallIndex) {
994 Frame = Frame->Caller;
995 --Depth;
996 }
997 if (Frame->Index == CallIndex)
998 return {Frame, Depth};
999 return {nullptr, 0};
1000 }
1001
1002 bool nextStep(const Stmt *S) {
1003 if (getLangOpts().ConstexprStepLimit == 0)
1004 return true;
1005
1006 if (!StepsLeft) {
1007 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1008 return false;
1009 }
1010 --StepsLeft;
1011 return true;
1012 }
1013
1014 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1015
1016 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1017 std::optional<DynAlloc *> Result;
1018 auto It = HeapAllocs.find(DA);
1019 if (It != HeapAllocs.end())
1020 Result = &It->second;
1021 return Result;
1022 }
1023
1024 /// Get the allocated storage for the given parameter of the given call.
1025 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1026 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1027 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1028 : nullptr;
1029 }
1030
1031 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1032 struct StdAllocatorCaller {
1033 unsigned FrameIndex;
1034 QualType ElemType;
1035 const Expr *Call;
1036 explicit operator bool() const { return FrameIndex != 0; };
1037 };
1038
1039 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1040 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1041 Call = Call->Caller) {
1042 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1043 if (!MD)
1044 continue;
1045 const IdentifierInfo *FnII = MD->getIdentifier();
1046 if (!FnII || !FnII->isStr(FnName))
1047 continue;
1048
1049 const auto *CTSD =
1050 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1051 if (!CTSD)
1052 continue;
1053
1054 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1055 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1056 if (CTSD->isInStdNamespace() && ClassII &&
1057 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1058 TAL[0].getKind() == TemplateArgument::Type)
1059 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1060 }
1061
1062 return {};
1063 }
1064
1065 void performLifetimeExtension() {
1066 // Disable the cleanups for lifetime-extended temporaries.
1067 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1068 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1069 });
1070 }
1071
1072 /// Throw away any remaining cleanups at the end of evaluation. If any
1073 /// cleanups would have had a side-effect, note that as an unmodeled
1074 /// side-effect and return false. Otherwise, return true.
1075 bool discardCleanups() {
1076 for (Cleanup &C : CleanupStack) {
1077 if (C.hasSideEffect() && !noteSideEffect()) {
1078 CleanupStack.clear();
1079 return false;
1080 }
1081 }
1082 CleanupStack.clear();
1083 return true;
1084 }
1085
1086 private:
1087 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1088 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1089
1090 unsigned getCallStackDepth() override { return CallStackDepth; }
1091 bool stepsLeft() const override { return StepsLeft > 0; }
1092
1093 public:
1094 /// Notes that we failed to evaluate an expression that other expressions
1095 /// directly depend on, and determine if we should keep evaluating. This
1096 /// should only be called if we actually intend to keep evaluating.
1097 ///
1098 /// Call noteSideEffect() instead if we may be able to ignore the value that
1099 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1100 ///
1101 /// (Foo(), 1) // use noteSideEffect
1102 /// (Foo() || true) // use noteSideEffect
1103 /// Foo() + 1 // use noteFailure
1104 [[nodiscard]] bool noteFailure() {
1105 // Failure when evaluating some expression often means there is some
1106 // subexpression whose evaluation was skipped. Therefore, (because we
1107 // don't track whether we skipped an expression when unwinding after an
1108 // evaluation failure) every evaluation failure that bubbles up from a
1109 // subexpression implies that a side-effect has potentially happened. We
1110 // skip setting the HasSideEffects flag to true until we decide to
1111 // continue evaluating after that point, which happens here.
1112 bool KeepGoing = keepEvaluatingAfterFailure();
1113 EvalStatus.HasSideEffects |= KeepGoing;
1114 return KeepGoing;
1115 }
1116
1117 class ArrayInitLoopIndex {
1118 EvalInfo &Info;
1119 uint64_t OuterIndex;
1120
1121 public:
1122 ArrayInitLoopIndex(EvalInfo &Info)
1123 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1124 Info.ArrayInitIndex = 0;
1125 }
1126 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1127
1128 operator uint64_t&() { return Info.ArrayInitIndex; }
1129 };
1130 };
1131
1132 /// Object used to treat all foldable expressions as constant expressions.
1133 struct FoldConstant {
1134 EvalInfo &Info;
1135 bool Enabled;
1136 bool HadNoPriorDiags;
1137 EvaluationMode OldMode;
1138
1139 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1140 : Info(Info),
1141 Enabled(Enabled),
1142 HadNoPriorDiags(Info.EvalStatus.Diag &&
1143 Info.EvalStatus.Diag->empty() &&
1144 !Info.EvalStatus.HasSideEffects),
1145 OldMode(Info.EvalMode) {
1146 if (Enabled)
1147 Info.EvalMode = EvaluationMode::ConstantFold;
1148 }
1149 void keepDiagnostics() { Enabled = false; }
1150 ~FoldConstant() {
1151 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1152 !Info.EvalStatus.HasSideEffects)
1153 Info.EvalStatus.Diag->clear();
1154 Info.EvalMode = OldMode;
1155 }
1156 };
1157
1158 /// RAII object used to set the current evaluation mode to ignore
1159 /// side-effects.
1160 struct IgnoreSideEffectsRAII {
1161 EvalInfo &Info;
1162 EvaluationMode OldMode;
1163 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1164 : Info(Info), OldMode(Info.EvalMode) {
1165 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1166 }
1167
1168 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1169 };
1170
1171 /// RAII object used to optionally suppress diagnostics and side-effects from
1172 /// a speculative evaluation.
1173 class SpeculativeEvaluationRAII {
1174 EvalInfo *Info = nullptr;
1175 Expr::EvalStatus OldStatus;
1176 unsigned OldSpeculativeEvaluationDepth = 0;
1177
1178 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1179 Info = Other.Info;
1180 OldStatus = Other.OldStatus;
1181 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1182 Other.Info = nullptr;
1183 }
1184
1185 void maybeRestoreState() {
1186 if (!Info)
1187 return;
1188
1189 Info->EvalStatus = OldStatus;
1190 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1191 }
1192
1193 public:
1194 SpeculativeEvaluationRAII() = default;
1195
1196 SpeculativeEvaluationRAII(
1197 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1198 : Info(&Info), OldStatus(Info.EvalStatus),
1199 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1200 Info.EvalStatus.Diag = NewDiag;
1201 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1202 }
1203
1204 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1205 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1206 moveFromAndCancel(std::move(Other));
1207 }
1208
1209 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1210 maybeRestoreState();
1211 moveFromAndCancel(std::move(Other));
1212 return *this;
1213 }
1214
1215 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1216 };
1217
1218 /// RAII object wrapping a full-expression or block scope, and handling
1219 /// the ending of the lifetime of temporaries created within it.
1220 template<ScopeKind Kind>
1221 class ScopeRAII {
1222 EvalInfo &Info;
1223 unsigned OldStackSize;
1224 public:
1225 ScopeRAII(EvalInfo &Info)
1226 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1227 // Push a new temporary version. This is needed to distinguish between
1228 // temporaries created in different iterations of a loop.
1229 Info.CurrentCall->pushTempVersion();
1230 }
1231 bool destroy(bool RunDestructors = true) {
1232 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1233 OldStackSize = std::numeric_limits<unsigned>::max();
1234 return OK;
1235 }
1236 ~ScopeRAII() {
1237 if (OldStackSize != std::numeric_limits<unsigned>::max())
1238 destroy(false);
1239 // Body moved to a static method to encourage the compiler to inline away
1240 // instances of this class.
1241 Info.CurrentCall->popTempVersion();
1242 }
1243 private:
1244 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1245 unsigned OldStackSize) {
1246 assert(OldStackSize <= Info.CleanupStack.size() &&
1247 "running cleanups out of order?");
1248
1249 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1250 // for a full-expression scope.
1251 bool Success = true;
1252 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1253 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1254 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1255 Success = false;
1256 break;
1257 }
1258 }
1259 }
1260
1261 // Compact any retained cleanups.
1262 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1263 if (Kind != ScopeKind::Block)
1264 NewEnd =
1265 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1266 return C.isDestroyedAtEndOf(Kind);
1267 });
1268 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1269 return Success;
1270 }
1271 };
1272 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1273 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1274 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1275}
1276
1277bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1278 CheckSubobjectKind CSK) {
1279 if (Invalid)
1280 return false;
1281 if (isOnePastTheEnd()) {
1282 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1283 << CSK;
1284 setInvalid();
1285 return false;
1286 }
1287 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1288 // must actually be at least one array element; even a VLA cannot have a
1289 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1290 return true;
1291}
1292
1293void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1294 const Expr *E) {
1295 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1296 // Do not set the designator as invalid: we can represent this situation,
1297 // and correct handling of __builtin_object_size requires us to do so.
1298}
1299
1300void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1301 const Expr *E,
1302 const APSInt &N) {
1303 // If we're complaining, we must be able to statically determine the size of
1304 // the most derived array.
1305 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1306 Info.CCEDiag(E, diag::note_constexpr_array_index)
1307 << N << /*array*/ 0
1308 << static_cast<unsigned>(getMostDerivedArraySize());
1309 else
1310 Info.CCEDiag(E, diag::note_constexpr_array_index)
1311 << N << /*non-array*/ 1;
1312 setInvalid();
1313}
1314
1315CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1316 const FunctionDecl *Callee, const LValue *This,
1317 const Expr *CallExpr, CallRef Call)
1318 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1319 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1320 Index(Info.NextCallIndex++) {
1321 Info.CurrentCall = this;
1322 ++Info.CallStackDepth;
1323}
1324
1325CallStackFrame::~CallStackFrame() {
1326 assert(Info.CurrentCall == this && "calls retired out of order");
1327 --Info.CallStackDepth;
1328 Info.CurrentCall = Caller;
1329}
1330
1331static bool isRead(AccessKinds AK) {
1332 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1333 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1334}
1335
1337 switch (AK) {
1338 case AK_Read:
1340 case AK_MemberCall:
1341 case AK_DynamicCast:
1342 case AK_TypeId:
1344 case AK_Dereference:
1345 return false;
1346 case AK_Assign:
1347 case AK_Increment:
1348 case AK_Decrement:
1349 case AK_Construct:
1350 case AK_Destroy:
1351 return true;
1352 }
1353 llvm_unreachable("unknown access kind");
1354}
1355
1356static bool isAnyAccess(AccessKinds AK) {
1357 return isRead(AK) || isModification(AK);
1358}
1359
1360/// Is this an access per the C++ definition?
1362 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1363 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1364}
1365
1366/// Is this kind of access valid on an indeterminate object value?
1368 switch (AK) {
1369 case AK_Read:
1370 case AK_Increment:
1371 case AK_Decrement:
1372 case AK_Dereference:
1373 // These need the object's value.
1374 return false;
1375
1378 case AK_Assign:
1379 case AK_Construct:
1380 case AK_Destroy:
1381 // Construction and destruction don't need the value.
1382 return true;
1383
1384 case AK_MemberCall:
1385 case AK_DynamicCast:
1386 case AK_TypeId:
1387 // These aren't really meaningful on scalars.
1388 return true;
1389 }
1390 llvm_unreachable("unknown access kind");
1391}
1392
1393namespace {
1394 struct ComplexValue {
1395 private:
1396 bool IsInt;
1397
1398 public:
1399 APSInt IntReal, IntImag;
1400 APFloat FloatReal, FloatImag;
1401
1402 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1403
1404 void makeComplexFloat() { IsInt = false; }
1405 bool isComplexFloat() const { return !IsInt; }
1406 APFloat &getComplexFloatReal() { return FloatReal; }
1407 APFloat &getComplexFloatImag() { return FloatImag; }
1408
1409 void makeComplexInt() { IsInt = true; }
1410 bool isComplexInt() const { return IsInt; }
1411 APSInt &getComplexIntReal() { return IntReal; }
1412 APSInt &getComplexIntImag() { return IntImag; }
1413
1414 void moveInto(APValue &v) const {
1415 if (isComplexFloat())
1416 v = APValue(FloatReal, FloatImag);
1417 else
1418 v = APValue(IntReal, IntImag);
1419 }
1420 void setFrom(const APValue &v) {
1421 assert(v.isComplexFloat() || v.isComplexInt());
1422 if (v.isComplexFloat()) {
1423 makeComplexFloat();
1424 FloatReal = v.getComplexFloatReal();
1425 FloatImag = v.getComplexFloatImag();
1426 } else {
1427 makeComplexInt();
1428 IntReal = v.getComplexIntReal();
1429 IntImag = v.getComplexIntImag();
1430 }
1431 }
1432 };
1433
1434 struct LValue {
1435 APValue::LValueBase Base;
1436 CharUnits Offset;
1437 SubobjectDesignator Designator;
1438 bool IsNullPtr : 1;
1439 bool InvalidBase : 1;
1440 // P2280R4 track if we have an unknown reference or pointer.
1441 bool AllowConstexprUnknown = false;
1442
1443 const APValue::LValueBase getLValueBase() const { return Base; }
1444 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1445 CharUnits &getLValueOffset() { return Offset; }
1446 const CharUnits &getLValueOffset() const { return Offset; }
1447 SubobjectDesignator &getLValueDesignator() { return Designator; }
1448 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1449 bool isNullPointer() const { return IsNullPtr;}
1450
1451 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1452 unsigned getLValueVersion() const { return Base.getVersion(); }
1453
1454 void moveInto(APValue &V) const {
1455 if (Designator.Invalid)
1456 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1457 else {
1458 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1459 V = APValue(Base, Offset, Designator.Entries,
1460 Designator.IsOnePastTheEnd, IsNullPtr);
1461 }
1462 if (AllowConstexprUnknown)
1463 V.setConstexprUnknown();
1464 }
1465 void setFrom(const ASTContext &Ctx, const APValue &V) {
1466 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1467 Base = V.getLValueBase();
1468 Offset = V.getLValueOffset();
1469 InvalidBase = false;
1470 Designator = SubobjectDesignator(Ctx, V);
1471 IsNullPtr = V.isNullPointer();
1472 AllowConstexprUnknown = V.allowConstexprUnknown();
1473 }
1474
1475 void set(APValue::LValueBase B, bool BInvalid = false) {
1476#ifndef NDEBUG
1477 // We only allow a few types of invalid bases. Enforce that here.
1478 if (BInvalid) {
1479 const auto *E = B.get<const Expr *>();
1480 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1481 "Unexpected type of invalid base");
1482 }
1483#endif
1484
1485 Base = B;
1486 Offset = CharUnits::fromQuantity(0);
1487 InvalidBase = BInvalid;
1488 Designator = SubobjectDesignator(getType(B));
1489 IsNullPtr = false;
1490 AllowConstexprUnknown = false;
1491 }
1492
1493 void setNull(ASTContext &Ctx, QualType PointerTy) {
1494 Base = (const ValueDecl *)nullptr;
1495 Offset =
1497 InvalidBase = false;
1498 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1499 IsNullPtr = true;
1500 AllowConstexprUnknown = false;
1501 }
1502
1503 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1504 set(B, true);
1505 }
1506
1507 std::string toString(ASTContext &Ctx, QualType T) const {
1508 APValue Printable;
1509 moveInto(Printable);
1510 return Printable.getAsString(Ctx, T);
1511 }
1512
1513 private:
1514 // Check that this LValue is not based on a null pointer. If it is, produce
1515 // a diagnostic and mark the designator as invalid.
1516 template <typename GenDiagType>
1517 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1518 if (Designator.Invalid)
1519 return false;
1520 if (IsNullPtr) {
1521 GenDiag();
1522 Designator.setInvalid();
1523 return false;
1524 }
1525 return true;
1526 }
1527
1528 public:
1529 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1530 CheckSubobjectKind CSK) {
1531 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1532 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1533 });
1534 }
1535
1536 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1537 AccessKinds AK) {
1538 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1539 if (AK == AccessKinds::AK_Dereference)
1540 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1541 else
1542 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1543 });
1544 }
1545
1546 // Check this LValue refers to an object. If not, set the designator to be
1547 // invalid and emit a diagnostic.
1548 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1549 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1550 Designator.checkSubobject(Info, E, CSK);
1551 }
1552
1553 void addDecl(EvalInfo &Info, const Expr *E,
1554 const Decl *D, bool Virtual = false) {
1555 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1556 Designator.addDeclUnchecked(D, Virtual);
1557 }
1558 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1559 if (!Designator.Entries.empty()) {
1560 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1561 Designator.setInvalid();
1562 return;
1563 }
1564 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1565 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1566 getType(Base).getNonReferenceType()->isArrayType());
1567 Designator.FirstEntryIsAnUnsizedArray = true;
1568 Designator.addUnsizedArrayUnchecked(ElemTy);
1569 }
1570 }
1571 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1572 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1573 Designator.addArrayUnchecked(CAT);
1574 }
1575 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1576 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1577 Designator.addComplexUnchecked(EltTy, Imag);
1578 }
1579 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1580 uint64_t Size, uint64_t Idx) {
1581 if (checkSubobject(Info, E, CSK_VectorElement))
1582 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1583 }
1584 void clearIsNullPointer() {
1585 IsNullPtr = false;
1586 }
1587 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1588 const APSInt &Index, CharUnits ElementSize) {
1589 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1590 // but we're not required to diagnose it and it's valid in C++.)
1591 if (!Index)
1592 return;
1593
1594 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1595 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1596 // offsets.
1597 uint64_t Offset64 = Offset.getQuantity();
1598 uint64_t ElemSize64 = ElementSize.getQuantity();
1599 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1600 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1601
1602 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1603 Designator.adjustIndex(Info, E, Index, *this);
1604 clearIsNullPointer();
1605 }
1606 void adjustOffset(CharUnits N) {
1607 Offset += N;
1608 if (N.getQuantity())
1609 clearIsNullPointer();
1610 }
1611 };
1612
1613 struct MemberPtr {
1614 MemberPtr() {}
1615 explicit MemberPtr(const ValueDecl *Decl)
1616 : DeclAndIsDerivedMember(Decl, false) {}
1617
1618 /// The member or (direct or indirect) field referred to by this member
1619 /// pointer, or 0 if this is a null member pointer.
1620 const ValueDecl *getDecl() const {
1621 return DeclAndIsDerivedMember.getPointer();
1622 }
1623 /// Is this actually a member of some type derived from the relevant class?
1624 bool isDerivedMember() const {
1625 return DeclAndIsDerivedMember.getInt();
1626 }
1627 /// Get the class which the declaration actually lives in.
1628 const CXXRecordDecl *getContainingRecord() const {
1629 return cast<CXXRecordDecl>(
1630 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1631 }
1632
1633 void moveInto(APValue &V) const {
1634 V = APValue(getDecl(), isDerivedMember(), Path);
1635 }
1636 void setFrom(const APValue &V) {
1637 assert(V.isMemberPointer());
1638 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1639 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1640 Path.clear();
1641 llvm::append_range(Path, V.getMemberPointerPath());
1642 }
1643
1644 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1645 /// whether the member is a member of some class derived from the class type
1646 /// of the member pointer.
1647 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1648 /// Path - The path of base/derived classes from the member declaration's
1649 /// class (exclusive) to the class type of the member pointer (inclusive).
1650 SmallVector<const CXXRecordDecl*, 4> Path;
1651
1652 /// Perform a cast towards the class of the Decl (either up or down the
1653 /// hierarchy).
1654 bool castBack(const CXXRecordDecl *Class) {
1655 assert(!Path.empty());
1656 const CXXRecordDecl *Expected;
1657 if (Path.size() >= 2)
1658 Expected = Path[Path.size() - 2];
1659 else
1660 Expected = getContainingRecord();
1661 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1662 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1663 // if B does not contain the original member and is not a base or
1664 // derived class of the class containing the original member, the result
1665 // of the cast is undefined.
1666 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1667 // (D::*). We consider that to be a language defect.
1668 return false;
1669 }
1670 Path.pop_back();
1671 return true;
1672 }
1673 /// Perform a base-to-derived member pointer cast.
1674 bool castToDerived(const CXXRecordDecl *Derived) {
1675 if (!getDecl())
1676 return true;
1677 if (!isDerivedMember()) {
1678 Path.push_back(Derived);
1679 return true;
1680 }
1681 if (!castBack(Derived))
1682 return false;
1683 if (Path.empty())
1684 DeclAndIsDerivedMember.setInt(false);
1685 return true;
1686 }
1687 /// Perform a derived-to-base member pointer cast.
1688 bool castToBase(const CXXRecordDecl *Base) {
1689 if (!getDecl())
1690 return true;
1691 if (Path.empty())
1692 DeclAndIsDerivedMember.setInt(true);
1693 if (isDerivedMember()) {
1694 Path.push_back(Base);
1695 return true;
1696 }
1697 return castBack(Base);
1698 }
1699 };
1700
1701 /// Compare two member pointers, which are assumed to be of the same type.
1702 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1703 if (!LHS.getDecl() || !RHS.getDecl())
1704 return !LHS.getDecl() && !RHS.getDecl();
1705 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1706 return false;
1707 return LHS.Path == RHS.Path;
1708 }
1709}
1710
1711void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1712 const LValue &LV) {
1713 if (Invalid || !N)
1714 return;
1715 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1716 if (isMostDerivedAnUnsizedArray()) {
1717 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1718 // Can't verify -- trust that the user is doing the right thing (or if
1719 // not, trust that the caller will catch the bad behavior).
1720 // FIXME: Should we reject if this overflows, at least?
1721 Entries.back() =
1722 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1723 return;
1724 }
1725
1726 // [expr.add]p4: For the purposes of these operators, a pointer to a
1727 // nonarray object behaves the same as a pointer to the first element of
1728 // an array of length one with the type of the object as its element type.
1729 bool IsArray =
1730 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1731 uint64_t ArrayIndex =
1732 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1733 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1734
1735 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1736 if (!Info.checkingPotentialConstantExpression() ||
1737 !LV.AllowConstexprUnknown) {
1738 // Calculate the actual index in a wide enough type, so we can include
1739 // it in the note.
1740 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1741 (llvm::APInt &)N += ArrayIndex;
1742 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1743 diagnosePointerArithmetic(Info, E, N);
1744 }
1745 setInvalid();
1746 return;
1747 }
1748
1749 ArrayIndex += TruncatedN;
1750 assert(ArrayIndex <= ArraySize &&
1751 "bounds check succeeded for out-of-bounds index");
1752
1753 if (IsArray)
1754 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1755 else
1756 IsOnePastTheEnd = (ArrayIndex != 0);
1757}
1758
1759static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1760static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1761 const LValue &This, const Expr *E,
1762 bool AllowNonLiteralTypes = false);
1763static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1764 bool InvalidBaseOK = false);
1765static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1766 bool InvalidBaseOK = false);
1767static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1768 EvalInfo &Info);
1769static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1770static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1771static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1772 EvalInfo &Info);
1773static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1774static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1775static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1776static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1777 EvalInfo &Info);
1778static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1779static std::optional<uint64_t>
1780EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1781 std::string *StringResult = nullptr);
1782
1783/// Evaluate an integer or fixed point expression into an APResult.
1784static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1785 EvalInfo &Info);
1786
1787/// Evaluate only a fixed point expression into an APResult.
1788static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1789 EvalInfo &Info);
1790
1791//===----------------------------------------------------------------------===//
1792// Misc utilities
1793//===----------------------------------------------------------------------===//
1794
1795/// Negate an APSInt in place, converting it to a signed form if necessary, and
1796/// preserving its value (by extending by up to one bit as needed).
1797static void negateAsSigned(APSInt &Int) {
1798 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1799 Int = Int.extend(Int.getBitWidth() + 1);
1800 Int.setIsSigned(true);
1801 }
1802 Int = -Int;
1803}
1804
1805template<typename KeyT>
1806APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1807 ScopeKind Scope, LValue &LV) {
1808 unsigned Version = getTempVersion();
1809 APValue::LValueBase Base(Key, Index, Version);
1810 LV.set(Base);
1811 return createLocal(Base, Key, T, Scope);
1812}
1813
1814/// Allocate storage for a parameter of a function call made in this frame.
1815APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1816 LValue &LV) {
1817 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1818 APValue::LValueBase Base(PVD, Index, Args.Version);
1819 LV.set(Base);
1820 // We always destroy parameters at the end of the call, even if we'd allow
1821 // them to live to the end of the full-expression at runtime, in order to
1822 // give portable results and match other compilers.
1823 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1824}
1825
1826APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1827 QualType T, ScopeKind Scope) {
1828 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1829 unsigned Version = Base.getVersion();
1830 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1831 assert(Result.isAbsent() && "local created multiple times");
1832
1833 // If we're creating a local immediately in the operand of a speculative
1834 // evaluation, don't register a cleanup to be run outside the speculative
1835 // evaluation context, since we won't actually be able to initialize this
1836 // object.
1837 if (Index <= Info.SpeculativeEvaluationDepth) {
1838 if (T.isDestructedType())
1839 Info.noteSideEffect();
1840 } else {
1841 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1842 }
1843 return Result;
1844}
1845
1846APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1847 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1848 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1849 return nullptr;
1850 }
1851
1852 DynamicAllocLValue DA(NumHeapAllocs++);
1854 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1855 std::forward_as_tuple(DA), std::tuple<>());
1856 assert(Result.second && "reused a heap alloc index?");
1857 Result.first->second.AllocExpr = E;
1858 return &Result.first->second.Value;
1859}
1860
1861/// Produce a string describing the given constexpr call.
1862void CallStackFrame::describe(raw_ostream &Out) const {
1863 bool IsMemberCall = false;
1864 bool ExplicitInstanceParam = false;
1865 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1866 PrintingPolicy.SuppressLambdaBody = true;
1867
1868 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1869 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1870 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1871 }
1872
1873 if (!IsMemberCall)
1874 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1875 /*Qualified=*/false);
1876
1877 if (This && IsMemberCall) {
1878 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1879 const Expr *Object = MCE->getImplicitObjectArgument();
1880 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1881 /*Indentation=*/0);
1882 if (Object->getType()->isPointerType())
1883 Out << "->";
1884 else
1885 Out << ".";
1886 } else if (const auto *OCE =
1887 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1888 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1889 /*Indentation=*/0);
1890 Out << ".";
1891 } else {
1892 APValue Val;
1893 This->moveInto(Val);
1894 Val.printPretty(
1895 Out, Info.Ctx,
1896 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1897 Out << ".";
1898 }
1899 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1900 /*Qualified=*/false);
1901 }
1902
1903 Out << '(';
1904
1905 llvm::ListSeparator Comma;
1906 for (const ParmVarDecl *Param :
1907 Callee->parameters().slice(ExplicitInstanceParam)) {
1908 Out << Comma;
1909 const APValue *V = Info.getParamSlot(Arguments, Param);
1910 if (V)
1911 V->printPretty(Out, Info.Ctx, Param->getType());
1912 else
1913 Out << "<...>";
1914 }
1915
1916 Out << ')';
1917}
1918
1919/// Evaluate an expression to see if it had side-effects, and discard its
1920/// result.
1921/// \return \c true if the caller should keep evaluating.
1922static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1923 assert(!E->isValueDependent());
1924 APValue Scratch;
1925 if (!Evaluate(Scratch, Info, E))
1926 // We don't need the value, but we might have skipped a side effect here.
1927 return Info.noteSideEffect();
1928 return true;
1929}
1930
1931/// Should this call expression be treated as forming an opaque constant?
1932static bool IsOpaqueConstantCall(const CallExpr *E) {
1933 unsigned Builtin = E->getBuiltinCallee();
1934 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1935 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1936 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1937 Builtin == Builtin::BI__builtin_function_start);
1938}
1939
1940static bool IsOpaqueConstantCall(const LValue &LVal) {
1941 const auto *BaseExpr =
1942 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1943 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1944}
1945
1947 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1948 // constant expression of pointer type that evaluates to...
1949
1950 // ... a null pointer value, or a prvalue core constant expression of type
1951 // std::nullptr_t.
1952 if (!B)
1953 return true;
1954
1955 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1956 // ... the address of an object with static storage duration,
1957 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1958 return VD->hasGlobalStorage();
1960 return true;
1961 // ... the address of a function,
1962 // ... the address of a GUID [MS extension],
1963 // ... the address of an unnamed global constant
1965 }
1966
1967 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1968 return true;
1969
1970 const Expr *E = B.get<const Expr*>();
1971 switch (E->getStmtClass()) {
1972 default:
1973 return false;
1974 case Expr::CompoundLiteralExprClass: {
1976 return CLE->isFileScope() && CLE->isLValue();
1977 }
1978 case Expr::MaterializeTemporaryExprClass:
1979 // A materialized temporary might have been lifetime-extended to static
1980 // storage duration.
1981 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1982 // A string literal has static storage duration.
1983 case Expr::StringLiteralClass:
1984 case Expr::PredefinedExprClass:
1985 case Expr::ObjCStringLiteralClass:
1986 case Expr::ObjCEncodeExprClass:
1987 return true;
1988 case Expr::ObjCBoxedExprClass:
1989 case Expr::ObjCArrayLiteralClass:
1990 case Expr::ObjCDictionaryLiteralClass:
1991 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1992 case Expr::CallExprClass:
1994 // For GCC compatibility, &&label has static storage duration.
1995 case Expr::AddrLabelExprClass:
1996 return true;
1997 // A Block literal expression may be used as the initialization value for
1998 // Block variables at global or local static scope.
1999 case Expr::BlockExprClass:
2000 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2001 // The APValue generated from a __builtin_source_location will be emitted as a
2002 // literal.
2003 case Expr::SourceLocExprClass:
2004 return true;
2005 case Expr::ImplicitValueInitExprClass:
2006 // FIXME:
2007 // We can never form an lvalue with an implicit value initialization as its
2008 // base through expression evaluation, so these only appear in one case: the
2009 // implicit variable declaration we invent when checking whether a constexpr
2010 // constructor can produce a constant expression. We must assume that such
2011 // an expression might be a global lvalue.
2012 return true;
2013 }
2014}
2015
2016static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2017 return LVal.Base.dyn_cast<const ValueDecl*>();
2018}
2019
2020// Information about an LValueBase that is some kind of string.
2023 StringRef Bytes;
2025};
2026
2027// Gets the lvalue base of LVal as a string.
2028static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2029 LValueBaseString &AsString) {
2030 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2031 if (!BaseExpr)
2032 return false;
2033
2034 // For ObjCEncodeExpr, we need to compute and store the string.
2035 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2036 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2037 AsString.ObjCEncodeStorage);
2038 AsString.Bytes = AsString.ObjCEncodeStorage;
2039 AsString.CharWidth = 1;
2040 return true;
2041 }
2042
2043 // Otherwise, we have a StringLiteral.
2044 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2045 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2046 Lit = PE->getFunctionName();
2047
2048 if (!Lit)
2049 return false;
2050
2051 AsString.Bytes = Lit->getBytes();
2052 AsString.CharWidth = Lit->getCharByteWidth();
2053 return true;
2054}
2055
2056// Determine whether two string literals potentially overlap. This will be the
2057// case if they agree on the values of all the bytes on the overlapping region
2058// between them.
2059//
2060// The overlapping region is the portion of the two string literals that must
2061// overlap in memory if the pointers actually point to the same address at
2062// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2063// the overlapping region is "cdef\0", which in this case does agree, so the
2064// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2065// "bazbar" + 3, the overlapping region contains all of both strings, so they
2066// are not potentially overlapping, even though they agree from the given
2067// addresses onwards.
2068//
2069// See open core issue CWG2765 which is discussing the desired rule here.
2070static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2071 const LValue &LHS,
2072 const LValue &RHS) {
2073 LValueBaseString LHSString, RHSString;
2074 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2075 !GetLValueBaseAsString(Info, RHS, RHSString))
2076 return false;
2077
2078 // This is the byte offset to the location of the first character of LHS
2079 // within RHS. We don't need to look at the characters of one string that
2080 // would appear before the start of the other string if they were merged.
2081 CharUnits Offset = RHS.Offset - LHS.Offset;
2082 if (Offset.isNegative()) {
2083 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2084 return false;
2085 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2086 } else {
2087 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2088 return false;
2089 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2090 }
2091
2092 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2093 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2094 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2095 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2096
2097 // The null terminator isn't included in the string data, so check for it
2098 // manually. If the longer string doesn't have a null terminator where the
2099 // shorter string ends, they aren't potentially overlapping.
2100 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2101 if (Shorter.size() + NullByte >= Longer.size())
2102 break;
2103 if (Longer[Shorter.size() + NullByte])
2104 return false;
2105 }
2106
2107 // Otherwise, they're potentially overlapping if and only if the overlapping
2108 // region is the same.
2109 return Shorter == Longer.take_front(Shorter.size());
2110}
2111
2112static bool IsWeakLValue(const LValue &Value) {
2114 return Decl && Decl->isWeak();
2115}
2116
2117static bool isZeroSized(const LValue &Value) {
2119 if (isa_and_nonnull<VarDecl>(Decl)) {
2120 QualType Ty = Decl->getType();
2121 if (Ty->isArrayType())
2122 return Ty->isIncompleteType() ||
2123 Decl->getASTContext().getTypeSize(Ty) == 0;
2124 }
2125 return false;
2126}
2127
2128static bool HasSameBase(const LValue &A, const LValue &B) {
2129 if (!A.getLValueBase())
2130 return !B.getLValueBase();
2131 if (!B.getLValueBase())
2132 return false;
2133
2134 if (A.getLValueBase().getOpaqueValue() !=
2135 B.getLValueBase().getOpaqueValue())
2136 return false;
2137
2138 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2139 A.getLValueVersion() == B.getLValueVersion();
2140}
2141
2142static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2143 assert(Base && "no location for a null lvalue");
2144 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2145
2146 // For a parameter, find the corresponding call stack frame (if it still
2147 // exists), and point at the parameter of the function definition we actually
2148 // invoked.
2149 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2150 unsigned Idx = PVD->getFunctionScopeIndex();
2151 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2152 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2153 F->Arguments.Version == Base.getVersion() && F->Callee &&
2154 Idx < F->Callee->getNumParams()) {
2155 VD = F->Callee->getParamDecl(Idx);
2156 break;
2157 }
2158 }
2159 }
2160
2161 if (VD)
2162 Info.Note(VD->getLocation(), diag::note_declared_at);
2163 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2164 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2165 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2166 // FIXME: Produce a note for dangling pointers too.
2167 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2168 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2169 diag::note_constexpr_dynamic_alloc_here);
2170 }
2171
2172 // We have no information to show for a typeid(T) object.
2173}
2174
2179
2180/// Materialized temporaries that we've already checked to determine if they're
2181/// initializsed by a constant expression.
2184
2186 EvalInfo &Info, SourceLocation DiagLoc,
2187 QualType Type, const APValue &Value,
2188 ConstantExprKind Kind,
2189 const FieldDecl *SubobjectDecl,
2190 CheckedTemporaries &CheckedTemps);
2191
2192/// Check that this reference or pointer core constant expression is a valid
2193/// value for an address or reference constant expression. Return true if we
2194/// can fold this expression, whether or not it's a constant expression.
2195static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2196 QualType Type, const LValue &LVal,
2197 ConstantExprKind Kind,
2198 CheckedTemporaries &CheckedTemps) {
2199 bool IsReferenceType = Type->isReferenceType();
2200
2201 APValue::LValueBase Base = LVal.getLValueBase();
2202 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2203
2204 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2205 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2206
2207 // Additional restrictions apply in a template argument. We only enforce the
2208 // C++20 restrictions here; additional syntactic and semantic restrictions
2209 // are applied elsewhere.
2210 if (isTemplateArgument(Kind)) {
2211 int InvalidBaseKind = -1;
2212 StringRef Ident;
2213 if (Base.is<TypeInfoLValue>())
2214 InvalidBaseKind = 0;
2215 else if (isa_and_nonnull<StringLiteral>(BaseE))
2216 InvalidBaseKind = 1;
2217 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2218 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2219 InvalidBaseKind = 2;
2220 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2221 InvalidBaseKind = 3;
2222 Ident = PE->getIdentKindName();
2223 }
2224
2225 if (InvalidBaseKind != -1) {
2226 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2227 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2228 << Ident;
2229 return false;
2230 }
2231 }
2232
2233 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2234 FD && FD->isImmediateFunction()) {
2235 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2236 << !Type->isAnyPointerType();
2237 Info.Note(FD->getLocation(), diag::note_declared_at);
2238 return false;
2239 }
2240
2241 // Check that the object is a global. Note that the fake 'this' object we
2242 // manufacture when checking potential constant expressions is conservatively
2243 // assumed to be global here.
2244 if (!IsGlobalLValue(Base)) {
2245 if (Info.getLangOpts().CPlusPlus11) {
2246 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2247 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2248 << BaseVD;
2249 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2250 if (VarD && VarD->isConstexpr()) {
2251 // Non-static local constexpr variables have unintuitive semantics:
2252 // constexpr int a = 1;
2253 // constexpr const int *p = &a;
2254 // ... is invalid because the address of 'a' is not constant. Suggest
2255 // adding a 'static' in this case.
2256 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2257 << VarD
2258 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2259 } else {
2260 NoteLValueLocation(Info, Base);
2261 }
2262 } else {
2263 Info.FFDiag(Loc);
2264 }
2265 // Don't allow references to temporaries to escape.
2266 return false;
2267 }
2268 assert((Info.checkingPotentialConstantExpression() ||
2269 LVal.getLValueCallIndex() == 0) &&
2270 "have call index for global lvalue");
2271
2272 if (LVal.allowConstexprUnknown()) {
2273 if (BaseVD) {
2274 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2275 NoteLValueLocation(Info, Base);
2276 } else {
2277 Info.FFDiag(Loc);
2278 }
2279 return false;
2280 }
2281
2282 if (Base.is<DynamicAllocLValue>()) {
2283 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2284 << IsReferenceType << !Designator.Entries.empty();
2285 NoteLValueLocation(Info, Base);
2286 return false;
2287 }
2288
2289 if (BaseVD) {
2290 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2291 // Check if this is a thread-local variable.
2292 if (Var->getTLSKind())
2293 // FIXME: Diagnostic!
2294 return false;
2295
2296 // A dllimport variable never acts like a constant, unless we're
2297 // evaluating a value for use only in name mangling, and unless it's a
2298 // static local. For the latter case, we'd still need to evaluate the
2299 // constant expression in case we're inside a (inlined) function.
2300 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2301 !Var->isStaticLocal())
2302 return false;
2303
2304 // In CUDA/HIP device compilation, only device side variables have
2305 // constant addresses.
2306 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2307 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2308 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2309 !Var->hasAttr<CUDAConstantAttr>() &&
2310 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2311 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2312 Var->hasAttr<HIPManagedAttr>())
2313 return false;
2314 }
2315 }
2316 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2317 // __declspec(dllimport) must be handled very carefully:
2318 // We must never initialize an expression with the thunk in C++.
2319 // Doing otherwise would allow the same id-expression to yield
2320 // different addresses for the same function in different translation
2321 // units. However, this means that we must dynamically initialize the
2322 // expression with the contents of the import address table at runtime.
2323 //
2324 // The C language has no notion of ODR; furthermore, it has no notion of
2325 // dynamic initialization. This means that we are permitted to
2326 // perform initialization with the address of the thunk.
2327 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2328 FD->hasAttr<DLLImportAttr>())
2329 // FIXME: Diagnostic!
2330 return false;
2331 }
2332 } else if (const auto *MTE =
2333 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2334 if (CheckedTemps.insert(MTE).second) {
2335 QualType TempType = getType(Base);
2336 if (TempType.isDestructedType()) {
2337 Info.FFDiag(MTE->getExprLoc(),
2338 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2339 << TempType;
2340 return false;
2341 }
2342
2343 APValue *V = MTE->getOrCreateValue(false);
2344 assert(V && "evasluation result refers to uninitialised temporary");
2346 Info, MTE->getExprLoc(), TempType, *V, Kind,
2347 /*SubobjectDecl=*/nullptr, CheckedTemps))
2348 return false;
2349 }
2350 }
2351
2352 // Allow address constant expressions to be past-the-end pointers. This is
2353 // an extension: the standard requires them to point to an object.
2354 if (!IsReferenceType)
2355 return true;
2356
2357 // A reference constant expression must refer to an object.
2358 if (!Base) {
2359 // FIXME: diagnostic
2360 Info.CCEDiag(Loc);
2361 return true;
2362 }
2363
2364 // Does this refer one past the end of some object?
2365 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2366 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2367 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2368 NoteLValueLocation(Info, Base);
2369 }
2370
2371 return true;
2372}
2373
2374/// Member pointers are constant expressions unless they point to a
2375/// non-virtual dllimport member function.
2376static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2377 SourceLocation Loc,
2378 QualType Type,
2379 const APValue &Value,
2380 ConstantExprKind Kind) {
2381 const ValueDecl *Member = Value.getMemberPointerDecl();
2382 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2383 if (!FD)
2384 return true;
2385 if (FD->isImmediateFunction()) {
2386 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2387 Info.Note(FD->getLocation(), diag::note_declared_at);
2388 return false;
2389 }
2390 return isForManglingOnly(Kind) || FD->isVirtual() ||
2391 !FD->hasAttr<DLLImportAttr>();
2392}
2393
2394/// Check that this core constant expression is of literal type, and if not,
2395/// produce an appropriate diagnostic.
2396static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2397 const LValue *This = nullptr) {
2398 // The restriction to literal types does not exist in C++23 anymore.
2399 if (Info.getLangOpts().CPlusPlus23)
2400 return true;
2401
2402 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2403 return true;
2404
2405 // C++1y: A constant initializer for an object o [...] may also invoke
2406 // constexpr constructors for o and its subobjects even if those objects
2407 // are of non-literal class types.
2408 //
2409 // C++11 missed this detail for aggregates, so classes like this:
2410 // struct foo_t { union { int i; volatile int j; } u; };
2411 // are not (obviously) initializable like so:
2412 // __attribute__((__require_constant_initialization__))
2413 // static const foo_t x = {{0}};
2414 // because "i" is a subobject with non-literal initialization (due to the
2415 // volatile member of the union). See:
2416 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2417 // Therefore, we use the C++1y behavior.
2418 if (This && Info.EvaluatingDecl == This->getLValueBase())
2419 return true;
2420
2421 // Prvalue constant expressions must be of literal types.
2422 if (Info.getLangOpts().CPlusPlus11)
2423 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2424 << E->getType();
2425 else
2426 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2427 return false;
2428}
2429
2431 EvalInfo &Info, SourceLocation DiagLoc,
2432 QualType Type, const APValue &Value,
2433 ConstantExprKind Kind,
2434 const FieldDecl *SubobjectDecl,
2435 CheckedTemporaries &CheckedTemps) {
2436 if (!Value.hasValue()) {
2437 if (SubobjectDecl) {
2438 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2439 << /*(name)*/ 1 << SubobjectDecl;
2440 Info.Note(SubobjectDecl->getLocation(),
2441 diag::note_constexpr_subobject_declared_here);
2442 } else {
2443 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2444 << /*of type*/ 0 << Type;
2445 }
2446 return false;
2447 }
2448
2449 // We allow _Atomic(T) to be initialized from anything that T can be
2450 // initialized from.
2451 if (const AtomicType *AT = Type->getAs<AtomicType>())
2452 Type = AT->getValueType();
2453
2454 // Core issue 1454: For a literal constant expression of array or class type,
2455 // each subobject of its value shall have been initialized by a constant
2456 // expression.
2457 if (Value.isArray()) {
2459 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2460 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2461 Value.getArrayInitializedElt(I), Kind,
2462 SubobjectDecl, CheckedTemps))
2463 return false;
2464 }
2465 if (!Value.hasArrayFiller())
2466 return true;
2467 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2468 Value.getArrayFiller(), Kind, SubobjectDecl,
2469 CheckedTemps);
2470 }
2471 if (Value.isUnion() && Value.getUnionField()) {
2472 return CheckEvaluationResult(
2473 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2474 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2475 }
2476 if (Value.isStruct()) {
2477 auto *RD = Type->castAsRecordDecl();
2478 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2479 unsigned BaseIndex = 0;
2480 for (const CXXBaseSpecifier &BS : CD->bases()) {
2481 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2482 if (!BaseValue.hasValue()) {
2483 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2484 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2485 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2486 return false;
2487 }
2488 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2489 Kind, /*SubobjectDecl=*/nullptr,
2490 CheckedTemps))
2491 return false;
2492 ++BaseIndex;
2493 }
2494 }
2495 for (const auto *I : RD->fields()) {
2496 if (I->isUnnamedBitField())
2497 continue;
2498
2499 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2500 Value.getStructField(I->getFieldIndex()), Kind,
2501 I, CheckedTemps))
2502 return false;
2503 }
2504 }
2505
2506 if (Value.isLValue() &&
2508 LValue LVal;
2509 LVal.setFrom(Info.Ctx, Value);
2510 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2511 CheckedTemps);
2512 }
2513
2514 if (Value.isMemberPointer() &&
2516 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2517
2518 // Everything else is fine.
2519 return true;
2520}
2521
2522/// Check that this core constant expression value is a valid value for a
2523/// constant expression. If not, report an appropriate diagnostic. Does not
2524/// check that the expression is of literal type.
2525static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2526 QualType Type, const APValue &Value,
2527 ConstantExprKind Kind) {
2528 // Nothing to check for a constant expression of type 'cv void'.
2529 if (Type->isVoidType())
2530 return true;
2531
2532 CheckedTemporaries CheckedTemps;
2534 Info, DiagLoc, Type, Value, Kind,
2535 /*SubobjectDecl=*/nullptr, CheckedTemps);
2536}
2537
2538/// Check that this evaluated value is fully-initialized and can be loaded by
2539/// an lvalue-to-rvalue conversion.
2540static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2541 QualType Type, const APValue &Value) {
2542 CheckedTemporaries CheckedTemps;
2543 return CheckEvaluationResult(
2545 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2546}
2547
2548/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2549/// "the allocated storage is deallocated within the evaluation".
2550static bool CheckMemoryLeaks(EvalInfo &Info) {
2551 if (!Info.HeapAllocs.empty()) {
2552 // We can still fold to a constant despite a compile-time memory leak,
2553 // so long as the heap allocation isn't referenced in the result (we check
2554 // that in CheckConstantExpression).
2555 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2556 diag::note_constexpr_memory_leak)
2557 << unsigned(Info.HeapAllocs.size() - 1);
2558 }
2559 return true;
2560}
2561
2562static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2563 // A null base expression indicates a null pointer. These are always
2564 // evaluatable, and they are false unless the offset is zero.
2565 if (!Value.getLValueBase()) {
2566 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2567 Result = !Value.getLValueOffset().isZero();
2568 return true;
2569 }
2570
2571 // We have a non-null base. These are generally known to be true, but if it's
2572 // a weak declaration it can be null at runtime.
2573 Result = true;
2574 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2575 return !Decl || !Decl->isWeak();
2576}
2577
2578static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2579 // TODO: This function should produce notes if it fails.
2580 switch (Val.getKind()) {
2581 case APValue::None:
2583 return false;
2584 case APValue::Int:
2585 Result = Val.getInt().getBoolValue();
2586 return true;
2588 Result = Val.getFixedPoint().getBoolValue();
2589 return true;
2590 case APValue::Float:
2591 Result = !Val.getFloat().isZero();
2592 return true;
2594 Result = Val.getComplexIntReal().getBoolValue() ||
2595 Val.getComplexIntImag().getBoolValue();
2596 return true;
2598 Result = !Val.getComplexFloatReal().isZero() ||
2599 !Val.getComplexFloatImag().isZero();
2600 return true;
2601 case APValue::LValue:
2602 return EvalPointerValueAsBool(Val, Result);
2604 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2605 return false;
2606 }
2607 Result = Val.getMemberPointerDecl();
2608 return true;
2609 case APValue::Vector:
2610 case APValue::Matrix:
2611 case APValue::Array:
2612 case APValue::Struct:
2613 case APValue::Union:
2615 return false;
2616 }
2617
2618 llvm_unreachable("unknown APValue kind");
2619}
2620
2621static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2622 EvalInfo &Info) {
2623 assert(!E->isValueDependent());
2624 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2625 APValue Val;
2626 if (!Evaluate(Val, Info, E))
2627 return false;
2628 return HandleConversionToBool(Val, Result);
2629}
2630
2631template<typename T>
2632static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2633 const T &SrcValue, QualType DestType) {
2634 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2635 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2636 OBT && OBT->isTrapKind()) {
2637 return false;
2638 }
2639 return Info.noteUndefinedBehavior();
2640}
2641
2642static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2643 QualType SrcType, const APFloat &Value,
2644 QualType DestType, APSInt &Result) {
2645 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2646 // Determine whether we are converting to unsigned or signed.
2647 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2648
2649 Result = APSInt(DestWidth, !DestSigned);
2650 bool ignored;
2651 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2652 & APFloat::opInvalidOp)
2653 return HandleOverflow(Info, E, Value, DestType);
2654 return true;
2655}
2656
2657/// Get rounding mode to use in evaluation of the specified expression.
2658///
2659/// If rounding mode is unknown at compile time, still try to evaluate the
2660/// expression. If the result is exact, it does not depend on rounding mode.
2661/// So return "tonearest" mode instead of "dynamic".
2662static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2663 llvm::RoundingMode RM =
2664 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2665 if (RM == llvm::RoundingMode::Dynamic)
2666 RM = llvm::RoundingMode::NearestTiesToEven;
2667 return RM;
2668}
2669
2670/// Check if the given evaluation result is allowed for constant evaluation.
2671static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2672 APFloat::opStatus St) {
2673 // In a constant context, assume that any dynamic rounding mode or FP
2674 // exception state matches the default floating-point environment.
2675 if (Info.InConstantContext)
2676 return true;
2677
2678 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2679 if ((St & APFloat::opInexact) &&
2680 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2681 // Inexact result means that it depends on rounding mode. If the requested
2682 // mode is dynamic, the evaluation cannot be made in compile time.
2683 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2684 return false;
2685 }
2686
2687 if ((St != APFloat::opOK) &&
2688 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2690 FPO.getAllowFEnvAccess())) {
2691 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2692 return false;
2693 }
2694
2695 if ((St & APFloat::opStatus::opInvalidOp) &&
2697 // There is no usefully definable result.
2698 Info.FFDiag(E);
2699 return false;
2700 }
2701
2702 // FIXME: if:
2703 // - evaluation triggered other FP exception, and
2704 // - exception mode is not "ignore", and
2705 // - the expression being evaluated is not a part of global variable
2706 // initializer,
2707 // the evaluation probably need to be rejected.
2708 return true;
2709}
2710
2711static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2712 QualType SrcType, QualType DestType,
2713 APFloat &Result) {
2714 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2716 "HandleFloatToFloatCast has been checked with only CastExpr, "
2717 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2718 "the new expression or address the root cause of this usage.");
2719 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2720 APFloat::opStatus St;
2721 APFloat Value = Result;
2722 bool ignored;
2723 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2724 return checkFloatingPointResult(Info, E, St);
2725}
2726
2727static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2728 QualType DestType, QualType SrcType,
2729 const APSInt &Value) {
2730 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2731 // Figure out if this is a truncate, extend or noop cast.
2732 // If the input is signed, do a sign extend, noop, or truncate.
2733 APSInt Result = Value.extOrTrunc(DestWidth);
2734 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2735 if (DestType->isBooleanType())
2736 Result = Value.getBoolValue();
2737 return Result;
2738}
2739
2740static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2741 const FPOptions FPO,
2742 QualType SrcType, const APSInt &Value,
2743 QualType DestType, APFloat &Result) {
2744 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2745 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2746 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2747 return checkFloatingPointResult(Info, E, St);
2748}
2749
2750static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2751 APValue &Value, const FieldDecl *FD) {
2752 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2753
2754 if (!Value.isInt()) {
2755 // Trying to store a pointer-cast-to-integer into a bitfield.
2756 // FIXME: In this case, we should provide the diagnostic for casting
2757 // a pointer to an integer.
2758 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2759 Info.FFDiag(E);
2760 return false;
2761 }
2762
2763 APSInt &Int = Value.getInt();
2764 unsigned OldBitWidth = Int.getBitWidth();
2765 unsigned NewBitWidth = FD->getBitWidthValue();
2766 if (NewBitWidth < OldBitWidth)
2767 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2768 return true;
2769}
2770
2771/// Perform the given integer operation, which is known to need at most BitWidth
2772/// bits, and check for overflow in the original type (if that type was not an
2773/// unsigned type).
2774template<typename Operation>
2775static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2776 const APSInt &LHS, const APSInt &RHS,
2777 unsigned BitWidth, Operation Op,
2778 APSInt &Result) {
2779 if (LHS.isUnsigned()) {
2780 Result = Op(LHS, RHS);
2781 return true;
2782 }
2783
2784 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2785 Result = Value.trunc(LHS.getBitWidth());
2786 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2787 if (Info.checkingForUndefinedBehavior())
2788 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2789 diag::warn_integer_constant_overflow)
2790 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2791 /*UpperCase=*/true, /*InsertSeparators=*/true)
2792 << E->getType() << E->getSourceRange();
2793 return HandleOverflow(Info, E, Value, E->getType());
2794 }
2795 return true;
2796}
2797
2798/// Perform the given binary integer operation.
2799static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2800 const APSInt &LHS, BinaryOperatorKind Opcode,
2801 APSInt RHS, APSInt &Result) {
2802 bool HandleOverflowResult = true;
2803 switch (Opcode) {
2804 default:
2805 Info.FFDiag(E);
2806 return false;
2807 case BO_Mul:
2808 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2809 std::multiplies<APSInt>(), Result);
2810 case BO_Add:
2811 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2812 std::plus<APSInt>(), Result);
2813 case BO_Sub:
2814 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2815 std::minus<APSInt>(), Result);
2816 case BO_And: Result = LHS & RHS; return true;
2817 case BO_Xor: Result = LHS ^ RHS; return true;
2818 case BO_Or: Result = LHS | RHS; return true;
2819 case BO_Div:
2820 case BO_Rem:
2821 if (RHS == 0) {
2822 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2823 << E->getRHS()->getSourceRange();
2824 return false;
2825 }
2826 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2827 // this operation and gives the two's complement result.
2828 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2829 LHS.isMinSignedValue())
2830 HandleOverflowResult = HandleOverflow(
2831 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2832 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2833 return HandleOverflowResult;
2834 case BO_Shl: {
2835 if (Info.getLangOpts().OpenCL)
2836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2838 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2839 RHS.isUnsigned());
2840 else if (RHS.isSigned() && RHS.isNegative()) {
2841 // During constant-folding, a negative shift is an opposite shift. Such
2842 // a shift is not a constant expression.
2843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2844 if (!Info.noteUndefinedBehavior())
2845 return false;
2846 RHS = -RHS;
2847 goto shift_right;
2848 }
2849 shift_left:
2850 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2851 // the shifted type.
2852 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2853 if (SA != RHS) {
2854 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2855 << RHS << E->getType() << LHS.getBitWidth();
2856 if (!Info.noteUndefinedBehavior())
2857 return false;
2858 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2859 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2860 // operand, and must not overflow the corresponding unsigned type.
2861 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2862 // E1 x 2^E2 module 2^N.
2863 if (LHS.isNegative()) {
2864 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 } else if (LHS.countl_zero() < SA) {
2868 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2869 if (!Info.noteUndefinedBehavior())
2870 return false;
2871 }
2872 }
2873 Result = LHS << SA;
2874 return true;
2875 }
2876 case BO_Shr: {
2877 if (Info.getLangOpts().OpenCL)
2878 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2879 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2880 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2881 RHS.isUnsigned());
2882 else if (RHS.isSigned() && RHS.isNegative()) {
2883 // During constant-folding, a negative shift is an opposite shift. Such a
2884 // shift is not a constant expression.
2885 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2886 if (!Info.noteUndefinedBehavior())
2887 return false;
2888 RHS = -RHS;
2889 goto shift_left;
2890 }
2891 shift_right:
2892 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2893 // shifted type.
2894 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2895 if (SA != RHS) {
2896 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2897 << RHS << E->getType() << LHS.getBitWidth();
2898 if (!Info.noteUndefinedBehavior())
2899 return false;
2900 }
2901
2902 Result = LHS >> SA;
2903 return true;
2904 }
2905
2906 case BO_LT: Result = LHS < RHS; return true;
2907 case BO_GT: Result = LHS > RHS; return true;
2908 case BO_LE: Result = LHS <= RHS; return true;
2909 case BO_GE: Result = LHS >= RHS; return true;
2910 case BO_EQ: Result = LHS == RHS; return true;
2911 case BO_NE: Result = LHS != RHS; return true;
2912 case BO_Cmp:
2913 llvm_unreachable("BO_Cmp should be handled elsewhere");
2914 }
2915}
2916
2917/// Perform the given binary floating-point operation, in-place, on LHS.
2918static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2919 APFloat &LHS, BinaryOperatorKind Opcode,
2920 const APFloat &RHS) {
2921 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2922 APFloat::opStatus St;
2923 switch (Opcode) {
2924 default:
2925 Info.FFDiag(E);
2926 return false;
2927 case BO_Mul:
2928 St = LHS.multiply(RHS, RM);
2929 break;
2930 case BO_Add:
2931 St = LHS.add(RHS, RM);
2932 break;
2933 case BO_Sub:
2934 St = LHS.subtract(RHS, RM);
2935 break;
2936 case BO_Div:
2937 // [expr.mul]p4:
2938 // If the second operand of / or % is zero the behavior is undefined.
2939 if (RHS.isZero())
2940 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2941 St = LHS.divide(RHS, RM);
2942 break;
2943 }
2944
2945 // [expr.pre]p4:
2946 // If during the evaluation of an expression, the result is not
2947 // mathematically defined [...], the behavior is undefined.
2948 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2949 if (LHS.isNaN()) {
2950 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2951 return Info.noteUndefinedBehavior();
2952 }
2953
2954 return checkFloatingPointResult(Info, E, St);
2955}
2956
2957static bool handleLogicalOpForVector(const APInt &LHSValue,
2958 BinaryOperatorKind Opcode,
2959 const APInt &RHSValue, APInt &Result) {
2960 bool LHS = (LHSValue != 0);
2961 bool RHS = (RHSValue != 0);
2962
2963 if (Opcode == BO_LAnd)
2964 Result = LHS && RHS;
2965 else
2966 Result = LHS || RHS;
2967 return true;
2968}
2969static bool handleLogicalOpForVector(const APFloat &LHSValue,
2970 BinaryOperatorKind Opcode,
2971 const APFloat &RHSValue, APInt &Result) {
2972 bool LHS = !LHSValue.isZero();
2973 bool RHS = !RHSValue.isZero();
2974
2975 if (Opcode == BO_LAnd)
2976 Result = LHS && RHS;
2977 else
2978 Result = LHS || RHS;
2979 return true;
2980}
2981
2982static bool handleLogicalOpForVector(const APValue &LHSValue,
2983 BinaryOperatorKind Opcode,
2984 const APValue &RHSValue, APInt &Result) {
2985 // The result is always an int type, however operands match the first.
2986 if (LHSValue.getKind() == APValue::Int)
2987 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2988 RHSValue.getInt(), Result);
2989 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2990 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2991 RHSValue.getFloat(), Result);
2992}
2993
2994template <typename APTy>
2995static bool
2997 const APTy &RHSValue, APInt &Result) {
2998 switch (Opcode) {
2999 default:
3000 llvm_unreachable("unsupported binary operator");
3001 case BO_EQ:
3002 Result = (LHSValue == RHSValue);
3003 break;
3004 case BO_NE:
3005 Result = (LHSValue != RHSValue);
3006 break;
3007 case BO_LT:
3008 Result = (LHSValue < RHSValue);
3009 break;
3010 case BO_GT:
3011 Result = (LHSValue > RHSValue);
3012 break;
3013 case BO_LE:
3014 Result = (LHSValue <= RHSValue);
3015 break;
3016 case BO_GE:
3017 Result = (LHSValue >= RHSValue);
3018 break;
3019 }
3020
3021 // The boolean operations on these vector types use an instruction that
3022 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3023 // to -1 to make sure that we produce the correct value.
3024 Result.negate();
3025
3026 return true;
3027}
3028
3029static bool handleCompareOpForVector(const APValue &LHSValue,
3030 BinaryOperatorKind Opcode,
3031 const APValue &RHSValue, APInt &Result) {
3032 // The result is always an int type, however operands match the first.
3033 if (LHSValue.getKind() == APValue::Int)
3034 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3035 RHSValue.getInt(), Result);
3036 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3037 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3038 RHSValue.getFloat(), Result);
3039}
3040
3041// Perform binary operations for vector types, in place on the LHS.
3042static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3043 BinaryOperatorKind Opcode,
3044 APValue &LHSValue,
3045 const APValue &RHSValue) {
3046 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3047 "Operation not supported on vector types");
3048
3049 const auto *VT = E->getType()->castAs<VectorType>();
3050 unsigned NumElements = VT->getNumElements();
3051 QualType EltTy = VT->getElementType();
3052
3053 // In the cases (typically C as I've observed) where we aren't evaluating
3054 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3055 // just give up.
3056 if (!LHSValue.isVector()) {
3057 assert(LHSValue.isLValue() &&
3058 "A vector result that isn't a vector OR uncalculated LValue");
3059 Info.FFDiag(E);
3060 return false;
3061 }
3062
3063 assert(LHSValue.getVectorLength() == NumElements &&
3064 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3065
3066 SmallVector<APValue, 4> ResultElements;
3067
3068 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3069 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3070 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3071
3072 if (EltTy->isIntegerType()) {
3073 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3074 EltTy->isUnsignedIntegerType()};
3075 bool Success = true;
3076
3077 if (BinaryOperator::isLogicalOp(Opcode))
3078 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3079 else if (BinaryOperator::isComparisonOp(Opcode))
3080 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3081 else
3082 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3083 RHSElt.getInt(), EltResult);
3084
3085 if (!Success) {
3086 Info.FFDiag(E);
3087 return false;
3088 }
3089 ResultElements.emplace_back(EltResult);
3090
3091 } else if (EltTy->isFloatingType()) {
3092 assert(LHSElt.getKind() == APValue::Float &&
3093 RHSElt.getKind() == APValue::Float &&
3094 "Mismatched LHS/RHS/Result Type");
3095 APFloat LHSFloat = LHSElt.getFloat();
3096
3097 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3098 RHSElt.getFloat())) {
3099 Info.FFDiag(E);
3100 return false;
3101 }
3102
3103 ResultElements.emplace_back(LHSFloat);
3104 }
3105 }
3106
3107 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3108 return true;
3109}
3110
3111/// Cast an lvalue referring to a base subobject to a derived class, by
3112/// truncating the lvalue's path to the given length.
3113static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3114 const RecordDecl *TruncatedType,
3115 unsigned TruncatedElements) {
3116 SubobjectDesignator &D = Result.Designator;
3117
3118 // Check we actually point to a derived class object.
3119 if (TruncatedElements == D.Entries.size())
3120 return true;
3121 assert(TruncatedElements >= D.MostDerivedPathLength &&
3122 "not casting to a derived class");
3123 if (!Result.checkSubobject(Info, E, CSK_Derived))
3124 return false;
3125
3126 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3127 const RecordDecl *RD = TruncatedType;
3128 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3129 if (RD->isInvalidDecl()) return false;
3130 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3131 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3132 if (isVirtualBaseClass(D.Entries[I]))
3133 Result.Offset -= Layout.getVBaseClassOffset(Base);
3134 else
3135 Result.Offset -= Layout.getBaseClassOffset(Base);
3136 RD = Base;
3137 }
3138 D.Entries.resize(TruncatedElements);
3139 return true;
3140}
3141
3142static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3143 const CXXRecordDecl *Derived,
3144 const CXXRecordDecl *Base,
3145 const ASTRecordLayout *RL = nullptr) {
3146 if (!RL) {
3147 if (Derived->isInvalidDecl()) return false;
3148 RL = &Info.Ctx.getASTRecordLayout(Derived);
3149 }
3150
3151 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3152 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3153 return true;
3154}
3155
3156static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3157 const CXXRecordDecl *DerivedDecl,
3158 const CXXBaseSpecifier *Base) {
3159 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3160
3161 if (!Base->isVirtual())
3162 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3163
3164 SubobjectDesignator &D = Obj.Designator;
3165 if (D.Invalid)
3166 return false;
3167
3168 // Extract most-derived object and corresponding type.
3169 // FIXME: After implementing P2280R4 it became possible to get references
3170 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3171 // locations and if we see crashes in those locations in the future
3172 // it may make more sense to move this fix into Lvalue::set.
3173 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3174 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3175 return false;
3176
3177 // Find the virtual base class.
3178 if (DerivedDecl->isInvalidDecl()) return false;
3179 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3180 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3181 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3182 return true;
3183}
3184
3185static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3186 QualType Type, LValue &Result) {
3187 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3188 PathE = E->path_end();
3189 PathI != PathE; ++PathI) {
3190 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3191 *PathI))
3192 return false;
3193 Type = (*PathI)->getType();
3194 }
3195 return true;
3196}
3197
3198/// Cast an lvalue referring to a derived class to a known base subobject.
3199static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3200 const CXXRecordDecl *DerivedRD,
3201 const CXXRecordDecl *BaseRD) {
3202 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3203 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3204 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3205 llvm_unreachable("Class must be derived from the passed in base class!");
3206
3207 for (CXXBasePathElement &Elem : Paths.front())
3208 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3209 return false;
3210 return true;
3211}
3212
3213/// Update LVal to refer to the given field, which must be a member of the type
3214/// currently described by LVal.
3215static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3216 const FieldDecl *FD,
3217 const ASTRecordLayout *RL = nullptr) {
3218 if (!RL) {
3219 if (FD->getParent()->isInvalidDecl()) return false;
3220 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3221 }
3222
3223 unsigned I = FD->getFieldIndex();
3224 LVal.addDecl(Info, E, FD);
3225 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3226 return true;
3227}
3228
3229/// Update LVal to refer to the given indirect field.
3230static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3231 LValue &LVal,
3232 const IndirectFieldDecl *IFD) {
3233 for (const auto *C : IFD->chain())
3234 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3235 return false;
3236 return true;
3237}
3238
3243
3244/// Get the size of the given type in char units.
3245static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3247 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3248 // extension.
3249 if (Type->isVoidType() || Type->isFunctionType()) {
3250 Size = CharUnits::One();
3251 return true;
3252 }
3253
3254 if (Type->isDependentType()) {
3255 Info.FFDiag(Loc);
3256 return false;
3257 }
3258
3259 if (!Type->isConstantSizeType()) {
3260 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3261 // FIXME: Better diagnostic.
3262 Info.FFDiag(Loc);
3263 return false;
3264 }
3265
3266 if (SOT == SizeOfType::SizeOf)
3267 Size = Info.Ctx.getTypeSizeInChars(Type);
3268 else
3269 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3270 return true;
3271}
3272
3273/// Update a pointer value to model pointer arithmetic.
3274/// \param Info - Information about the ongoing evaluation.
3275/// \param E - The expression being evaluated, for diagnostic purposes.
3276/// \param LVal - The pointer value to be updated.
3277/// \param EltTy - The pointee type represented by LVal.
3278/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3279static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3280 LValue &LVal, QualType EltTy,
3281 APSInt Adjustment) {
3282 CharUnits SizeOfPointee;
3283 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3284 return false;
3285
3286 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3287 return true;
3288}
3289
3290static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3291 LValue &LVal, QualType EltTy,
3292 int64_t Adjustment) {
3293 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3294 APSInt::get(Adjustment));
3295}
3296
3297/// Update an lvalue to refer to a component of a complex number.
3298/// \param Info - Information about the ongoing evaluation.
3299/// \param LVal - The lvalue to be updated.
3300/// \param EltTy - The complex number's component type.
3301/// \param Imag - False for the real component, true for the imaginary.
3302static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3303 LValue &LVal, QualType EltTy,
3304 bool Imag) {
3305 if (Imag) {
3306 CharUnits SizeOfComponent;
3307 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3308 return false;
3309 LVal.Offset += SizeOfComponent;
3310 }
3311 LVal.addComplex(Info, E, EltTy, Imag);
3312 return true;
3313}
3314
3315static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3316 LValue &LVal, QualType EltTy,
3317 uint64_t Size, uint64_t Idx) {
3318 if (Idx) {
3319 CharUnits SizeOfElement;
3320 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3321 return false;
3322 LVal.Offset += SizeOfElement * Idx;
3323 }
3324 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3325 return true;
3326}
3327
3328/// Try to evaluate the initializer for a variable declaration.
3329///
3330/// \param Info Information about the ongoing evaluation.
3331/// \param E An expression to be used when printing diagnostics.
3332/// \param VD The variable whose initializer should be obtained.
3333/// \param Version The version of the variable within the frame.
3334/// \param Frame The frame in which the variable was created. Must be null
3335/// if this variable is not local to the evaluation.
3336/// \param Result Filled in with a pointer to the value of the variable.
3337static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3338 const VarDecl *VD, CallStackFrame *Frame,
3339 unsigned Version, APValue *&Result) {
3340 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3341 // and pointers.
3342 bool AllowConstexprUnknown =
3343 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3344
3345 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3346
3347 auto CheckUninitReference = [&](bool IsLocalVariable) {
3348 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3349 // C++23 [expr.const]p8
3350 // ... For such an object that is not usable in constant expressions, the
3351 // dynamic type of the object is constexpr-unknown. For such a reference
3352 // that is not usable in constant expressions, the reference is treated
3353 // as binding to an unspecified object of the referenced type whose
3354 // lifetime and that of all subobjects includes the entire constant
3355 // evaluation and whose dynamic type is constexpr-unknown.
3356 //
3357 // Variables that are part of the current evaluation are not
3358 // constexpr-unknown.
3359 if (!AllowConstexprUnknown || IsLocalVariable) {
3360 if (!Info.checkingPotentialConstantExpression())
3361 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3362 return false;
3363 }
3364 Result = nullptr;
3365 }
3366 return true;
3367 };
3368
3369 // If this is a local variable, dig out its value.
3370 if (Frame) {
3371 Result = Frame->getTemporary(VD, Version);
3372 if (Result)
3373 return CheckUninitReference(/*IsLocalVariable=*/true);
3374
3375 if (!isa<ParmVarDecl>(VD)) {
3376 // Assume variables referenced within a lambda's call operator that were
3377 // not declared within the call operator are captures and during checking
3378 // of a potential constant expression, assume they are unknown constant
3379 // expressions.
3380 assert(isLambdaCallOperator(Frame->Callee) &&
3381 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3382 "missing value for local variable");
3383 if (Info.checkingPotentialConstantExpression())
3384 return false;
3385
3386 llvm_unreachable(
3387 "A variable in a frame should either be a local or a parameter");
3388 }
3389 }
3390
3391 // If we're currently evaluating the initializer of this declaration, use that
3392 // in-flight value.
3393 if (Info.EvaluatingDecl == Base) {
3394 Result = Info.EvaluatingDeclValue;
3395 return CheckUninitReference(/*IsLocalVariable=*/false);
3396 }
3397
3398 // P2280R4 struck the restriction that variable of reference type lifetime
3399 // should begin within the evaluation of E
3400 // Used to be C++20 [expr.const]p5.12.2:
3401 // ... its lifetime began within the evaluation of E;
3402 if (isa<ParmVarDecl>(VD)) {
3403 if (AllowConstexprUnknown) {
3404 Result = nullptr;
3405 return true;
3406 }
3407
3408 // Assume parameters of a potential constant expression are usable in
3409 // constant expressions.
3410 if (!Info.checkingPotentialConstantExpression() ||
3411 !Info.CurrentCall->Callee ||
3412 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3413 if (Info.getLangOpts().CPlusPlus11) {
3414 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3415 << VD;
3416 NoteLValueLocation(Info, Base);
3417 } else {
3418 Info.FFDiag(E);
3419 }
3420 }
3421 return false;
3422 }
3423
3424 if (E->isValueDependent())
3425 return false;
3426
3427 // Dig out the initializer, and use the declaration which it's attached to.
3428 // FIXME: We should eventually check whether the variable has a reachable
3429 // initializing declaration.
3430 const Expr *Init = VD->getAnyInitializer(VD);
3431 // P2280R4 struck the restriction that variable of reference type should have
3432 // a preceding initialization.
3433 // Used to be C++20 [expr.const]p5.12:
3434 // ... reference has a preceding initialization and either ...
3435 if (!Init && !AllowConstexprUnknown) {
3436 // Don't diagnose during potential constant expression checking; an
3437 // initializer might be added later.
3438 if (!Info.checkingPotentialConstantExpression()) {
3439 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3440 << VD;
3441 NoteLValueLocation(Info, Base);
3442 }
3443 return false;
3444 }
3445
3446 // P2280R4 struck the initialization requirement for variables of reference
3447 // type so we can no longer assume we have an Init.
3448 // Used to be C++20 [expr.const]p5.12:
3449 // ... reference has a preceding initialization and either ...
3450 if (Init && Init->isValueDependent()) {
3451 // The DeclRefExpr is not value-dependent, but the variable it refers to
3452 // has a value-dependent initializer. This should only happen in
3453 // constant-folding cases, where the variable is not actually of a suitable
3454 // type for use in a constant expression (otherwise the DeclRefExpr would
3455 // have been value-dependent too), so diagnose that.
3456 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3457 if (!Info.checkingPotentialConstantExpression()) {
3458 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3459 ? diag::note_constexpr_ltor_non_constexpr
3460 : diag::note_constexpr_ltor_non_integral, 1)
3461 << VD << VD->getType();
3462 NoteLValueLocation(Info, Base);
3463 }
3464 return false;
3465 }
3466
3467 // Check that we can fold the initializer. In C++, we will have already done
3468 // this in the cases where it matters for conformance.
3469 // P2280R4 struck the initialization requirement for variables of reference
3470 // type so we can no longer assume we have an Init.
3471 // Used to be C++20 [expr.const]p5.12:
3472 // ... reference has a preceding initialization and either ...
3473 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3474 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3475 NoteLValueLocation(Info, Base);
3476 return false;
3477 }
3478
3479 // Check that the variable is actually usable in constant expressions. For a
3480 // const integral variable or a reference, we might have a non-constant
3481 // initializer that we can nonetheless evaluate the initializer for. Such
3482 // variables are not usable in constant expressions. In C++98, the
3483 // initializer also syntactically needs to be an ICE.
3484 //
3485 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3486 // expressions here; doing so would regress diagnostics for things like
3487 // reading from a volatile constexpr variable.
3488 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3489 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3490 !AllowConstexprUnknown) ||
3491 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3492 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3493 if (Init) {
3494 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3495 NoteLValueLocation(Info, Base);
3496 } else {
3497 Info.CCEDiag(E);
3498 }
3499 }
3500
3501 // Never use the initializer of a weak variable, not even for constant
3502 // folding. We can't be sure that this is the definition that will be used.
3503 if (VD->isWeak()) {
3504 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3505 NoteLValueLocation(Info, Base);
3506 return false;
3507 }
3508
3509 Result = VD->getEvaluatedValue();
3510
3511 if (!Result && !AllowConstexprUnknown)
3512 return false;
3513
3514 return CheckUninitReference(/*IsLocalVariable=*/false);
3515}
3516
3517/// Get the base index of the given base class within an APValue representing
3518/// the given derived class.
3519static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3520 const CXXRecordDecl *Base) {
3521 Base = Base->getCanonicalDecl();
3522 unsigned Index = 0;
3524 E = Derived->bases_end(); I != E; ++I, ++Index) {
3525 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3526 return Index;
3527 }
3528
3529 llvm_unreachable("base class missing from derived class's bases list");
3530}
3531
3532/// Extract the value of a character from a string literal.
3533static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3534 uint64_t Index) {
3535 assert(!isa<SourceLocExpr>(Lit) &&
3536 "SourceLocExpr should have already been converted to a StringLiteral");
3537
3538 // FIXME: Support MakeStringConstant
3539 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3540 std::string Str;
3541 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3542 assert(Index <= Str.size() && "Index too large");
3543 return APSInt::getUnsigned(Str.c_str()[Index]);
3544 }
3545
3546 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3547 Lit = PE->getFunctionName();
3548 const StringLiteral *S = cast<StringLiteral>(Lit);
3549 const ConstantArrayType *CAT =
3550 Info.Ctx.getAsConstantArrayType(S->getType());
3551 assert(CAT && "string literal isn't an array");
3552 QualType CharType = CAT->getElementType();
3553 assert(CharType->isIntegerType() && "unexpected character type");
3554 APSInt Value(Info.Ctx.getTypeSize(CharType),
3555 CharType->isUnsignedIntegerType());
3556 if (Index < S->getLength())
3557 Value = S->getCodeUnit(Index);
3558 return Value;
3559}
3560
3561// Expand a string literal into an array of characters.
3562//
3563// FIXME: This is inefficient; we should probably introduce something similar
3564// to the LLVM ConstantDataArray to make this cheaper.
3565static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3566 APValue &Result,
3567 QualType AllocType = QualType()) {
3568 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3569 AllocType.isNull() ? S->getType() : AllocType);
3570 assert(CAT && "string literal isn't an array");
3571 QualType CharType = CAT->getElementType();
3572 assert(CharType->isIntegerType() && "unexpected character type");
3573
3574 unsigned Elts = CAT->getZExtSize();
3575 Result = APValue(APValue::UninitArray(),
3576 std::min(S->getLength(), Elts), Elts);
3577 APSInt Value(Info.Ctx.getTypeSize(CharType),
3578 CharType->isUnsignedIntegerType());
3579 if (Result.hasArrayFiller())
3580 Result.getArrayFiller() = APValue(Value);
3581 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3582 Value = S->getCodeUnit(I);
3583 Result.getArrayInitializedElt(I) = APValue(Value);
3584 }
3585}
3586
3587// Expand an array so that it has more than Index filled elements.
3588static void expandArray(APValue &Array, unsigned Index) {
3589 unsigned Size = Array.getArraySize();
3590 assert(Index < Size);
3591
3592 // Always at least double the number of elements for which we store a value.
3593 unsigned OldElts = Array.getArrayInitializedElts();
3594 unsigned NewElts = std::max(Index+1, OldElts * 2);
3595 NewElts = std::min(Size, std::max(NewElts, 8u));
3596
3597 // Copy the data across.
3598 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3599 for (unsigned I = 0; I != OldElts; ++I)
3600 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3601 for (unsigned I = OldElts; I != NewElts; ++I)
3602 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3603 if (NewValue.hasArrayFiller())
3604 NewValue.getArrayFiller() = Array.getArrayFiller();
3605 Array.swap(NewValue);
3606}
3607
3608// Expand an indeterminate vector to materialize all elements.
3609static void expandVector(APValue &Vec, unsigned NumElements) {
3610 assert(Vec.isIndeterminate());
3612 Vec = APValue(Elts.data(), Elts.size());
3613}
3614
3615/// Determine whether a type would actually be read by an lvalue-to-rvalue
3616/// conversion. If it's of class type, we may assume that the copy operation
3617/// is trivial. Note that this is never true for a union type with fields
3618/// (because the copy always "reads" the active member) and always true for
3619/// a non-class type.
3620static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3622 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3623 return !RD || isReadByLvalueToRvalueConversion(RD);
3624}
3626 // FIXME: A trivial copy of a union copies the object representation, even if
3627 // the union is empty.
3628 if (RD->isUnion())
3629 return !RD->field_empty();
3630 if (RD->isEmpty())
3631 return false;
3632
3633 for (auto *Field : RD->fields())
3634 if (!Field->isUnnamedBitField() &&
3635 isReadByLvalueToRvalueConversion(Field->getType()))
3636 return true;
3637
3638 for (auto &BaseSpec : RD->bases())
3639 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3640 return true;
3641
3642 return false;
3643}
3644
3645/// Diagnose an attempt to read from any unreadable field within the specified
3646/// type, which might be a class type.
3647static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3648 QualType T) {
3649 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3650 if (!RD)
3651 return false;
3652
3653 if (!RD->hasMutableFields())
3654 return false;
3655
3656 for (auto *Field : RD->fields()) {
3657 // If we're actually going to read this field in some way, then it can't
3658 // be mutable. If we're in a union, then assigning to a mutable field
3659 // (even an empty one) can change the active member, so that's not OK.
3660 // FIXME: Add core issue number for the union case.
3661 if (Field->isMutable() &&
3662 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3663 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3664 Info.Note(Field->getLocation(), diag::note_declared_at);
3665 return true;
3666 }
3667
3668 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3669 return true;
3670 }
3671
3672 for (auto &BaseSpec : RD->bases())
3673 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3674 return true;
3675
3676 // All mutable fields were empty, and thus not actually read.
3677 return false;
3678}
3679
3680static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3682 bool MutableSubobject = false) {
3683 // A temporary or transient heap allocation we created.
3684 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3685 return true;
3686
3687 switch (Info.IsEvaluatingDecl) {
3688 case EvalInfo::EvaluatingDeclKind::None:
3689 return false;
3690
3691 case EvalInfo::EvaluatingDeclKind::Ctor:
3692 // The variable whose initializer we're evaluating.
3693 if (Info.EvaluatingDecl == Base)
3694 return true;
3695
3696 // A temporary lifetime-extended by the variable whose initializer we're
3697 // evaluating.
3698 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3699 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3700 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3701 return false;
3702
3703 case EvalInfo::EvaluatingDeclKind::Dtor:
3704 // C++2a [expr.const]p6:
3705 // [during constant destruction] the lifetime of a and its non-mutable
3706 // subobjects (but not its mutable subobjects) [are] considered to start
3707 // within e.
3708 if (MutableSubobject || Base != Info.EvaluatingDecl)
3709 return false;
3710 // FIXME: We can meaningfully extend this to cover non-const objects, but
3711 // we will need special handling: we should be able to access only
3712 // subobjects of such objects that are themselves declared const.
3713 QualType T = getType(Base);
3714 return T.isConstQualified() || T->isReferenceType();
3715 }
3716
3717 llvm_unreachable("unknown evaluating decl kind");
3718}
3719
3720static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3721 SourceLocation CallLoc = {}) {
3722 return Info.CheckArraySize(
3723 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3724 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3725 /*Diag=*/true);
3726}
3727
3728static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3729 QualType SourceTy, QualType DestTy,
3730 APValue const &Original, APValue &Result) {
3731 // boolean must be checked before integer
3732 // since IsIntegerType() is true for bool
3733 if (SourceTy->isBooleanType()) {
3734 if (DestTy->isBooleanType()) {
3735 Result = Original;
3736 return true;
3737 }
3738 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3739 bool BoolResult;
3740 if (!HandleConversionToBool(Original, BoolResult))
3741 return false;
3742 uint64_t IntResult = BoolResult;
3743 QualType IntType = DestTy->isIntegerType()
3744 ? DestTy
3745 : Info.Ctx.getIntTypeForBitwidth(64, false);
3746 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3747 }
3748 if (DestTy->isRealFloatingType()) {
3749 APValue Result2 = APValue(APFloat(0.0));
3750 if (!HandleIntToFloatCast(Info, E, FPO,
3751 Info.Ctx.getIntTypeForBitwidth(64, false),
3752 Result.getInt(), DestTy, Result2.getFloat()))
3753 return false;
3754 Result = std::move(Result2);
3755 }
3756 return true;
3757 }
3758 if (SourceTy->isIntegerType()) {
3759 if (DestTy->isRealFloatingType()) {
3760 Result = APValue(APFloat(0.0));
3761 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3762 DestTy, Result.getFloat());
3763 }
3764 if (DestTy->isBooleanType()) {
3765 bool BoolResult;
3766 if (!HandleConversionToBool(Original, BoolResult))
3767 return false;
3768 uint64_t IntResult = BoolResult;
3769 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3770 return true;
3771 }
3772 if (DestTy->isIntegerType()) {
3773 Result = APValue(
3774 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3775 return true;
3776 }
3777 } else if (SourceTy->isRealFloatingType()) {
3778 if (DestTy->isRealFloatingType()) {
3779 Result = Original;
3780 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3781 Result.getFloat());
3782 }
3783 if (DestTy->isBooleanType()) {
3784 bool BoolResult;
3785 if (!HandleConversionToBool(Original, BoolResult))
3786 return false;
3787 uint64_t IntResult = BoolResult;
3788 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3789 return true;
3790 }
3791 if (DestTy->isIntegerType()) {
3792 Result = APValue(APSInt());
3793 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3794 DestTy, Result.getInt());
3795 }
3796 }
3797
3798 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3799 return false;
3800}
3801
3802// do the heavy lifting for casting to aggregate types
3803// because we have to deal with bitfields specially
3804static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3805 const Expr *E, APValue &Result,
3806 QualType ResultType,
3807 SmallVectorImpl<APValue> &Elements,
3808 SmallVectorImpl<QualType> &ElTypes) {
3809
3811 {&Result, ResultType, 0}};
3812
3813 unsigned ElI = 0;
3814 while (!WorkList.empty() && ElI < Elements.size()) {
3815 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3816
3817 if (Type->isRealFloatingType()) {
3818 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3819 *Res))
3820 return false;
3821 ElI++;
3822 continue;
3823 }
3824 if (Type->isIntegerType()) {
3825 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3826 *Res))
3827 return false;
3828 if (BitWidth > 0) {
3829 if (!Res->isInt())
3830 return false;
3831 APSInt &Int = Res->getInt();
3832 unsigned OldBitWidth = Int.getBitWidth();
3833 unsigned NewBitWidth = BitWidth;
3834 if (NewBitWidth < OldBitWidth)
3835 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3836 }
3837 ElI++;
3838 continue;
3839 }
3840 if (Type->isVectorType()) {
3841 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3842 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3843 SmallVector<APValue> Vals(NumEl);
3844 for (unsigned I = 0; I < NumEl; ++I) {
3845 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3846 Vals[I]))
3847 return false;
3848 ElI++;
3849 }
3850 *Res = APValue(Vals.data(), NumEl);
3851 continue;
3852 }
3853 if (Type->isConstantArrayType()) {
3854 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3855 ->getElementType();
3856 uint64_t Size =
3857 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3858 *Res = APValue(APValue::UninitArray(), Size, Size);
3859 for (int64_t I = Size - 1; I > -1; --I)
3860 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3861 continue;
3862 }
3863 if (Type->isRecordType()) {
3864 const RecordDecl *RD = Type->getAsRecordDecl();
3865
3866 unsigned NumBases = 0;
3867 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3868 NumBases = CXXRD->getNumBases();
3869
3870 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3871
3873 // we need to traverse backwards
3874 // Visit the base classes.
3875 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3876 if (CXXRD->getNumBases() > 0) {
3877 assert(CXXRD->getNumBases() == 1);
3878 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3879 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3880 }
3881 }
3882
3883 // Visit the fields.
3884 for (FieldDecl *FD : RD->fields()) {
3885 unsigned FDBW = 0;
3886 if (FD->isUnnamedBitField())
3887 continue;
3888 if (FD->isBitField()) {
3889 FDBW = FD->getBitWidthValue();
3890 }
3891
3892 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3893 FD->getType(), FDBW);
3894 }
3895
3896 std::reverse(ReverseList.begin(), ReverseList.end());
3897 llvm::append_range(WorkList, ReverseList);
3898 continue;
3899 }
3900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3901 return false;
3902 }
3903 return true;
3904}
3905
3906static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3907 const FPOptions FPO,
3908 SmallVectorImpl<APValue> &Elements,
3909 SmallVectorImpl<QualType> &SrcTypes,
3910 SmallVectorImpl<QualType> &DestTypes,
3911 SmallVectorImpl<APValue> &Results) {
3912
3913 assert((Elements.size() == SrcTypes.size()) &&
3914 (Elements.size() == DestTypes.size()));
3915
3916 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3917 APValue Original = Elements[I];
3918 QualType SourceTy = SrcTypes[I];
3919 QualType DestTy = DestTypes[I];
3920
3921 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3922 return false;
3923 }
3924 return true;
3925}
3926
3927static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3928
3929 SmallVector<QualType> WorkList = {BaseTy};
3930
3931 unsigned Size = 0;
3932 while (!WorkList.empty()) {
3933 QualType Type = WorkList.pop_back_val();
3935 Type->isBooleanType()) {
3936 ++Size;
3937 continue;
3938 }
3939 if (Type->isVectorType()) {
3940 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3941 Size += NumEl;
3942 continue;
3943 }
3944 if (Type->isConstantMatrixType()) {
3945 unsigned NumEl =
3946 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3947 Size += NumEl;
3948 continue;
3949 }
3950 if (Type->isConstantArrayType()) {
3951 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3952 ->getElementType();
3953 uint64_t ArrSize =
3954 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3955 for (uint64_t I = 0; I < ArrSize; ++I) {
3956 WorkList.push_back(ElTy);
3957 }
3958 continue;
3959 }
3960 if (Type->isRecordType()) {
3961 const RecordDecl *RD = Type->getAsRecordDecl();
3962
3963 // Visit the base classes.
3964 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3965 if (CXXRD->getNumBases() > 0) {
3966 assert(CXXRD->getNumBases() == 1);
3967 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3968 WorkList.push_back(BS.getType());
3969 }
3970 }
3971
3972 // visit the fields.
3973 for (FieldDecl *FD : RD->fields()) {
3974 if (FD->isUnnamedBitField())
3975 continue;
3976 WorkList.push_back(FD->getType());
3977 }
3978 continue;
3979 }
3980 }
3981 return Size;
3982}
3983
3984static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
3985 QualType &SrcTy) {
3986 SrcTy = E->getType();
3987
3988 if (!Evaluate(SrcVal, Info, E))
3989 return false;
3990
3991 assert((SrcVal.isFloat() || SrcVal.isInt() ||
3992 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
3993 "Not a valid HLSLAggregateSplatCast.");
3994
3995 if (SrcVal.isVector()) {
3996 assert(SrcTy->isVectorType() && "Type mismatch.");
3997 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
3998 SrcVal = SrcVal.getVectorElt(0);
3999 }
4000 if (SrcVal.isMatrix()) {
4001 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4002 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4003 SrcVal = SrcVal.getMatrixElt(0, 0);
4004 }
4005 return true;
4006}
4007
4008static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4009 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4010 SmallVectorImpl<QualType> &Types, unsigned Size) {
4011
4012 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4013 unsigned Populated = 0;
4014 while (!WorkList.empty() && Populated < Size) {
4015 auto [Work, Type] = WorkList.pop_back_val();
4016
4017 if (Work.isFloat() || Work.isInt()) {
4018 Elements.push_back(Work);
4019 Types.push_back(Type);
4020 Populated++;
4021 continue;
4022 }
4023 if (Work.isVector()) {
4024 assert(Type->isVectorType() && "Type mismatch.");
4025 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4026 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4027 I++) {
4028 Elements.push_back(Work.getVectorElt(I));
4029 Types.push_back(ElTy);
4030 Populated++;
4031 }
4032 continue;
4033 }
4034 if (Work.isMatrix()) {
4035 assert(Type->isConstantMatrixType() && "Type mismatch.");
4036 const auto *MT = Type->castAs<ConstantMatrixType>();
4037 QualType ElTy = MT->getElementType();
4038 // Matrix elements are flattened in row-major order.
4039 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4040 Row++) {
4041 for (unsigned Col = 0;
4042 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4043 Elements.push_back(Work.getMatrixElt(Row, Col));
4044 Types.push_back(ElTy);
4045 Populated++;
4046 }
4047 }
4048 continue;
4049 }
4050 if (Work.isArray()) {
4051 assert(Type->isConstantArrayType() && "Type mismatch.");
4052 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4053 ->getElementType();
4054 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4055 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4056 }
4057 continue;
4058 }
4059
4060 if (Work.isStruct()) {
4061 assert(Type->isRecordType() && "Type mismatch.");
4062
4063 const RecordDecl *RD = Type->getAsRecordDecl();
4064
4066 // Visit the fields.
4067 for (FieldDecl *FD : RD->fields()) {
4068 if (FD->isUnnamedBitField())
4069 continue;
4070 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4071 FD->getType());
4072 }
4073
4074 std::reverse(ReverseList.begin(), ReverseList.end());
4075 llvm::append_range(WorkList, ReverseList);
4076
4077 // Visit the base classes.
4078 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4079 if (CXXRD->getNumBases() > 0) {
4080 assert(CXXRD->getNumBases() == 1);
4081 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4082 const APValue &Base = Work.getStructBase(0);
4083
4084 // Can happen in error cases.
4085 if (!Base.isStruct())
4086 return false;
4087
4088 WorkList.emplace_back(Base, BS.getType());
4089 }
4090 }
4091 continue;
4092 }
4093 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4094 return false;
4095 }
4096 return true;
4097}
4098
4099namespace {
4100/// A handle to a complete object (an object that is not a subobject of
4101/// another object).
4102struct CompleteObject {
4103 /// The identity of the object.
4104 APValue::LValueBase Base;
4105 /// The value of the complete object.
4106 APValue *Value;
4107 /// The type of the complete object.
4108 QualType Type;
4109
4110 CompleteObject() : Value(nullptr) {}
4111 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4112 : Base(Base), Value(Value), Type(Type) {}
4113
4114 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4115 // If this isn't a "real" access (eg, if it's just accessing the type
4116 // info), allow it. We assume the type doesn't change dynamically for
4117 // subobjects of constexpr objects (even though we'd hit UB here if it
4118 // did). FIXME: Is this right?
4119 if (!isAnyAccess(AK))
4120 return true;
4121
4122 // In C++14 onwards, it is permitted to read a mutable member whose
4123 // lifetime began within the evaluation.
4124 // FIXME: Should we also allow this in C++11?
4125 if (!Info.getLangOpts().CPlusPlus14 &&
4126 AK != AccessKinds::AK_IsWithinLifetime)
4127 return false;
4128 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4129 }
4130
4131 explicit operator bool() const { return !Type.isNull(); }
4132};
4133} // end anonymous namespace
4134
4135static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4136 bool IsMutable = false) {
4137 // C++ [basic.type.qualifier]p1:
4138 // - A const object is an object of type const T or a non-mutable subobject
4139 // of a const object.
4140 if (ObjType.isConstQualified() && !IsMutable)
4141 SubobjType.addConst();
4142 // - A volatile object is an object of type const T or a subobject of a
4143 // volatile object.
4144 if (ObjType.isVolatileQualified())
4145 SubobjType.addVolatile();
4146 return SubobjType;
4147}
4148
4149/// Find the designated sub-object of an rvalue.
4150template <typename SubobjectHandler>
4151static typename SubobjectHandler::result_type
4152findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4153 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4154 if (Sub.Invalid)
4155 // A diagnostic will have already been produced.
4156 return handler.failed();
4157 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4158 if (Info.getLangOpts().CPlusPlus11)
4159 Info.FFDiag(E, Sub.isOnePastTheEnd()
4160 ? diag::note_constexpr_access_past_end
4161 : diag::note_constexpr_access_unsized_array)
4162 << handler.AccessKind;
4163 else
4164 Info.FFDiag(E);
4165 return handler.failed();
4166 }
4167
4168 APValue *O = Obj.Value;
4169 QualType ObjType = Obj.Type;
4170 const FieldDecl *LastField = nullptr;
4171 const FieldDecl *VolatileField = nullptr;
4172
4173 // Walk the designator's path to find the subobject.
4174 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4175 // Reading an indeterminate value is undefined, but assigning over one is OK.
4176 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4177 (O->isIndeterminate() &&
4178 !isValidIndeterminateAccess(handler.AccessKind))) {
4179 // Object has ended lifetime.
4180 // If I is non-zero, some subobject (member or array element) of a
4181 // complete object has ended its lifetime, so this is valid for
4182 // IsWithinLifetime, resulting in false.
4183 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4184 return false;
4185 if (!Info.checkingPotentialConstantExpression()) {
4186 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4187 << handler.AccessKind << O->isIndeterminate()
4188 << E->getSourceRange();
4189 NoteLValueLocation(Info, Obj.Base);
4190 }
4191 return handler.failed();
4192 }
4193
4194 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4195 // const and volatile semantics are not applied on an object under
4196 // {con,de}struction.
4197 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4198 ObjType->isRecordType() &&
4199 Info.isEvaluatingCtorDtor(
4200 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4201 ConstructionPhase::None) {
4202 ObjType = Info.Ctx.getCanonicalType(ObjType);
4203 ObjType.removeLocalConst();
4204 ObjType.removeLocalVolatile();
4205 }
4206
4207 // If this is our last pass, check that the final object type is OK.
4208 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4209 // Accesses to volatile objects are prohibited.
4210 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4211 if (Info.getLangOpts().CPlusPlus) {
4212 int DiagKind;
4213 SourceLocation Loc;
4214 const NamedDecl *Decl = nullptr;
4215 if (VolatileField) {
4216 DiagKind = 2;
4217 Loc = VolatileField->getLocation();
4218 Decl = VolatileField;
4219 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4220 DiagKind = 1;
4221 Loc = VD->getLocation();
4222 Decl = VD;
4223 } else {
4224 DiagKind = 0;
4225 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4226 Loc = E->getExprLoc();
4227 }
4228 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4229 << handler.AccessKind << DiagKind << Decl;
4230 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4231 } else {
4232 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4233 }
4234 return handler.failed();
4235 }
4236
4237 // If we are reading an object of class type, there may still be more
4238 // things we need to check: if there are any mutable subobjects, we
4239 // cannot perform this read. (This only happens when performing a trivial
4240 // copy or assignment.)
4241 if (ObjType->isRecordType() &&
4242 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4243 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4244 return handler.failed();
4245 }
4246
4247 if (I == N) {
4248 if (!handler.found(*O, ObjType))
4249 return false;
4250
4251 // If we modified a bit-field, truncate it to the right width.
4252 if (isModification(handler.AccessKind) &&
4253 LastField && LastField->isBitField() &&
4254 !truncateBitfieldValue(Info, E, *O, LastField))
4255 return false;
4256
4257 return true;
4258 }
4259
4260 LastField = nullptr;
4261 if (ObjType->isArrayType()) {
4262 // Next subobject is an array element.
4263 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4265 "vla in literal type?");
4266 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4267 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4268 CAT && CAT->getSize().ule(Index)) {
4269 // Note, it should not be possible to form a pointer with a valid
4270 // designator which points more than one past the end of the array.
4271 if (Info.getLangOpts().CPlusPlus11)
4272 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4273 << handler.AccessKind;
4274 else
4275 Info.FFDiag(E);
4276 return handler.failed();
4277 }
4278
4279 ObjType = AT->getElementType();
4280
4281 if (O->getArrayInitializedElts() > Index)
4282 O = &O->getArrayInitializedElt(Index);
4283 else if (!isRead(handler.AccessKind)) {
4284 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4285 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4286 return handler.failed();
4287
4288 expandArray(*O, Index);
4289 O = &O->getArrayInitializedElt(Index);
4290 } else
4291 O = &O->getArrayFiller();
4292 } else if (ObjType->isAnyComplexType()) {
4293 // Next subobject is a complex number.
4294 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4295 if (Index > 1) {
4296 if (Info.getLangOpts().CPlusPlus11)
4297 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4298 << handler.AccessKind;
4299 else
4300 Info.FFDiag(E);
4301 return handler.failed();
4302 }
4303
4304 ObjType = getSubobjectType(
4305 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4306
4307 assert(I == N - 1 && "extracting subobject of scalar?");
4308 if (O->isComplexInt()) {
4309 return handler.found(Index ? O->getComplexIntImag()
4310 : O->getComplexIntReal(), ObjType);
4311 } else {
4312 assert(O->isComplexFloat());
4313 return handler.found(Index ? O->getComplexFloatImag()
4314 : O->getComplexFloatReal(), ObjType);
4315 }
4316 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4317 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4318 unsigned NumElements = VT->getNumElements();
4319 if (Index == NumElements) {
4320 if (Info.getLangOpts().CPlusPlus11)
4321 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4322 << handler.AccessKind;
4323 else
4324 Info.FFDiag(E);
4325 return handler.failed();
4326 }
4327
4328 if (Index > NumElements) {
4329 Info.CCEDiag(E, diag::note_constexpr_array_index)
4330 << Index << /*array*/ 0 << NumElements;
4331 return handler.failed();
4332 }
4333
4334 ObjType = VT->getElementType();
4335 assert(I == N - 1 && "extracting subobject of scalar?");
4336
4337 if (O->isIndeterminate()) {
4338 if (isRead(handler.AccessKind)) {
4339 Info.FFDiag(E);
4340 return handler.failed();
4341 }
4342 expandVector(*O, NumElements);
4343 }
4344 assert(O->isVector() && "unexpected object during vector element access");
4345 return handler.found(O->getVectorElt(Index), ObjType);
4346 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4347 if (Field->isMutable() &&
4348 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4349 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4350 << handler.AccessKind << Field;
4351 Info.Note(Field->getLocation(), diag::note_declared_at);
4352 return handler.failed();
4353 }
4354
4355 // Next subobject is a class, struct or union field.
4356 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4357 if (RD->isUnion()) {
4358 const FieldDecl *UnionField = O->getUnionField();
4359 if (!UnionField ||
4360 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4361 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4362 // Placement new onto an inactive union member makes it active.
4363 O->setUnion(Field, APValue());
4364 } else {
4365 // Pointer to/into inactive union member: Not within lifetime
4366 if (handler.AccessKind == AK_IsWithinLifetime)
4367 return false;
4368 // FIXME: If O->getUnionValue() is absent, report that there's no
4369 // active union member rather than reporting the prior active union
4370 // member. We'll need to fix nullptr_t to not use APValue() as its
4371 // representation first.
4372 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4373 << handler.AccessKind << Field << !UnionField << UnionField;
4374 return handler.failed();
4375 }
4376 }
4377 O = &O->getUnionValue();
4378 } else
4379 O = &O->getStructField(Field->getFieldIndex());
4380
4381 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4382 LastField = Field;
4383 if (Field->getType().isVolatileQualified())
4384 VolatileField = Field;
4385 } else {
4386 // Next subobject is a base class.
4387 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4388 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4389 O = &O->getStructBase(getBaseIndex(Derived, Base));
4390
4391 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4392 }
4393 }
4394}
4395
4396namespace {
4397struct ExtractSubobjectHandler {
4398 EvalInfo &Info;
4399 const Expr *E;
4400 APValue &Result;
4401 const AccessKinds AccessKind;
4402
4403 typedef bool result_type;
4404 bool failed() { return false; }
4405 bool found(APValue &Subobj, QualType SubobjType) {
4406 Result = Subobj;
4407 if (AccessKind == AK_ReadObjectRepresentation)
4408 return true;
4409 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4410 }
4411 bool found(APSInt &Value, QualType SubobjType) {
4412 Result = APValue(Value);
4413 return true;
4414 }
4415 bool found(APFloat &Value, QualType SubobjType) {
4416 Result = APValue(Value);
4417 return true;
4418 }
4419};
4420} // end anonymous namespace
4421
4422/// Extract the designated sub-object of an rvalue.
4423static bool extractSubobject(EvalInfo &Info, const Expr *E,
4424 const CompleteObject &Obj,
4425 const SubobjectDesignator &Sub, APValue &Result,
4426 AccessKinds AK = AK_Read) {
4427 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4428 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4429 return findSubobject(Info, E, Obj, Sub, Handler);
4430}
4431
4432namespace {
4433struct ModifySubobjectHandler {
4434 EvalInfo &Info;
4435 APValue &NewVal;
4436 const Expr *E;
4437
4438 typedef bool result_type;
4439 static const AccessKinds AccessKind = AK_Assign;
4440
4441 bool checkConst(QualType QT) {
4442 // Assigning to a const object has undefined behavior.
4443 if (QT.isConstQualified()) {
4444 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4445 return false;
4446 }
4447 return true;
4448 }
4449
4450 bool failed() { return false; }
4451 bool found(APValue &Subobj, QualType SubobjType) {
4452 if (!checkConst(SubobjType))
4453 return false;
4454 // We've been given ownership of NewVal, so just swap it in.
4455 Subobj.swap(NewVal);
4456 return true;
4457 }
4458 bool found(APSInt &Value, QualType SubobjType) {
4459 if (!checkConst(SubobjType))
4460 return false;
4461 if (!NewVal.isInt()) {
4462 // Maybe trying to write a cast pointer value into a complex?
4463 Info.FFDiag(E);
4464 return false;
4465 }
4466 Value = NewVal.getInt();
4467 return true;
4468 }
4469 bool found(APFloat &Value, QualType SubobjType) {
4470 if (!checkConst(SubobjType))
4471 return false;
4472 Value = NewVal.getFloat();
4473 return true;
4474 }
4475};
4476} // end anonymous namespace
4477
4478const AccessKinds ModifySubobjectHandler::AccessKind;
4479
4480/// Update the designated sub-object of an rvalue to the given value.
4481static bool modifySubobject(EvalInfo &Info, const Expr *E,
4482 const CompleteObject &Obj,
4483 const SubobjectDesignator &Sub,
4484 APValue &NewVal) {
4485 ModifySubobjectHandler Handler = { Info, NewVal, E };
4486 return findSubobject(Info, E, Obj, Sub, Handler);
4487}
4488
4489/// Find the position where two subobject designators diverge, or equivalently
4490/// the length of the common initial subsequence.
4491static unsigned FindDesignatorMismatch(QualType ObjType,
4492 const SubobjectDesignator &A,
4493 const SubobjectDesignator &B,
4494 bool &WasArrayIndex) {
4495 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4496 for (/**/; I != N; ++I) {
4497 if (!ObjType.isNull() &&
4498 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4499 // Next subobject is an array element.
4500 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4501 WasArrayIndex = true;
4502 return I;
4503 }
4504 if (ObjType->isAnyComplexType())
4505 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4506 else
4507 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4508 } else {
4509 if (A.Entries[I].getAsBaseOrMember() !=
4510 B.Entries[I].getAsBaseOrMember()) {
4511 WasArrayIndex = false;
4512 return I;
4513 }
4514 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4515 // Next subobject is a field.
4516 ObjType = FD->getType();
4517 else
4518 // Next subobject is a base class.
4519 ObjType = QualType();
4520 }
4521 }
4522 WasArrayIndex = false;
4523 return I;
4524}
4525
4526/// Determine whether the given subobject designators refer to elements of the
4527/// same array object.
4529 const SubobjectDesignator &A,
4530 const SubobjectDesignator &B) {
4531 if (A.Entries.size() != B.Entries.size())
4532 return false;
4533
4534 bool IsArray = A.MostDerivedIsArrayElement;
4535 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4536 // A is a subobject of the array element.
4537 return false;
4538
4539 // If A (and B) designates an array element, the last entry will be the array
4540 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4541 // of length 1' case, and the entire path must match.
4542 bool WasArrayIndex;
4543 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4544 return CommonLength >= A.Entries.size() - IsArray;
4545}
4546
4547/// Find the complete object to which an LValue refers.
4548static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4549 AccessKinds AK, const LValue &LVal,
4550 QualType LValType) {
4551 if (LVal.InvalidBase) {
4552 Info.FFDiag(E);
4553 return CompleteObject();
4554 }
4555
4556 if (!LVal.Base) {
4558 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4559 else
4560 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4561 return CompleteObject();
4562 }
4563
4564 CallStackFrame *Frame = nullptr;
4565 unsigned Depth = 0;
4566 if (LVal.getLValueCallIndex()) {
4567 std::tie(Frame, Depth) =
4568 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4569 if (!Frame) {
4570 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4571 << AK << /*Indeterminate=*/false << E->getSourceRange();
4572 NoteLValueLocation(Info, LVal.Base);
4573 return CompleteObject();
4574 }
4575 }
4576
4577 bool IsAccess = isAnyAccess(AK);
4578
4579 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4580 // is not a constant expression (even if the object is non-volatile). We also
4581 // apply this rule to C++98, in order to conform to the expected 'volatile'
4582 // semantics.
4583 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4584 if (Info.getLangOpts().CPlusPlus)
4585 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4586 << AK << LValType;
4587 else
4588 Info.FFDiag(E);
4589 return CompleteObject();
4590 }
4591
4592 // Compute value storage location and type of base object.
4593 APValue *BaseVal = nullptr;
4594 QualType BaseType = getType(LVal.Base);
4595
4596 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4597 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4598 // This is the object whose initializer we're evaluating, so its lifetime
4599 // started in the current evaluation.
4600 BaseVal = Info.EvaluatingDeclValue;
4601 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4602 // Allow reading from a GUID declaration.
4603 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4604 if (isModification(AK)) {
4605 // All the remaining cases do not permit modification of the object.
4606 Info.FFDiag(E, diag::note_constexpr_modify_global);
4607 return CompleteObject();
4608 }
4609 APValue &V = GD->getAsAPValue();
4610 if (V.isAbsent()) {
4611 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4612 << GD->getType();
4613 return CompleteObject();
4614 }
4615 return CompleteObject(LVal.Base, &V, GD->getType());
4616 }
4617
4618 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4619 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4620 if (isModification(AK)) {
4621 Info.FFDiag(E, diag::note_constexpr_modify_global);
4622 return CompleteObject();
4623 }
4624 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4625 GCD->getType());
4626 }
4627
4628 // Allow reading from template parameter objects.
4629 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4630 if (isModification(AK)) {
4631 Info.FFDiag(E, diag::note_constexpr_modify_global);
4632 return CompleteObject();
4633 }
4634 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4635 TPO->getType());
4636 }
4637
4638 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4639 // In C++11, constexpr, non-volatile variables initialized with constant
4640 // expressions are constant expressions too. Inside constexpr functions,
4641 // parameters are constant expressions even if they're non-const.
4642 // In C++1y, objects local to a constant expression (those with a Frame) are
4643 // both readable and writable inside constant expressions.
4644 // In C, such things can also be folded, although they are not ICEs.
4645 const VarDecl *VD = dyn_cast<VarDecl>(D);
4646 if (VD) {
4647 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4648 VD = VDef;
4649 }
4650 if (!VD || VD->isInvalidDecl()) {
4651 Info.FFDiag(E);
4652 return CompleteObject();
4653 }
4654
4655 bool IsConstant = BaseType.isConstant(Info.Ctx);
4656 bool ConstexprVar = false;
4657 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4658 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4659 ConstexprVar = VD->isConstexpr();
4660
4661 // Unless we're looking at a local variable or argument in a constexpr call,
4662 // the variable we're reading must be const (unless we are binding to a
4663 // reference).
4664 if (AK != clang::AK_Dereference && !Frame) {
4665 if (IsAccess && isa<ParmVarDecl>(VD)) {
4666 // Access of a parameter that's not associated with a frame isn't going
4667 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4668 // suitable diagnostic.
4669 } else if (Info.getLangOpts().CPlusPlus14 &&
4670 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4671 // OK, we can read and modify an object if we're in the process of
4672 // evaluating its initializer, because its lifetime began in this
4673 // evaluation.
4674 } else if (isModification(AK)) {
4675 // All the remaining cases do not permit modification of the object.
4676 Info.FFDiag(E, diag::note_constexpr_modify_global);
4677 return CompleteObject();
4678 } else if (VD->isConstexpr()) {
4679 // OK, we can read this variable.
4680 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4681 Info.FFDiag(E);
4682 return CompleteObject();
4683 } else if (BaseType->isIntegralOrEnumerationType()) {
4684 if (!IsConstant) {
4685 if (!IsAccess)
4686 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4687 if (Info.getLangOpts().CPlusPlus) {
4688 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4689 Info.Note(VD->getLocation(), diag::note_declared_at);
4690 } else {
4691 Info.FFDiag(E);
4692 }
4693 return CompleteObject();
4694 }
4695 } else if (!IsAccess) {
4696 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4697 } else if ((IsConstant || BaseType->isReferenceType()) &&
4698 Info.checkingPotentialConstantExpression() &&
4699 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4700 // This variable might end up being constexpr. Don't diagnose it yet.
4701 } else if (IsConstant) {
4702 // Keep evaluating to see what we can do. In particular, we support
4703 // folding of const floating-point types, in order to make static const
4704 // data members of such types (supported as an extension) more useful.
4705 if (Info.getLangOpts().CPlusPlus) {
4706 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4707 ? diag::note_constexpr_ltor_non_constexpr
4708 : diag::note_constexpr_ltor_non_integral, 1)
4709 << VD << BaseType;
4710 Info.Note(VD->getLocation(), diag::note_declared_at);
4711 } else {
4712 Info.CCEDiag(E);
4713 }
4714 } else {
4715 // Never allow reading a non-const value.
4716 if (Info.getLangOpts().CPlusPlus) {
4717 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4718 ? diag::note_constexpr_ltor_non_constexpr
4719 : diag::note_constexpr_ltor_non_integral, 1)
4720 << VD << BaseType;
4721 Info.Note(VD->getLocation(), diag::note_declared_at);
4722 } else {
4723 Info.FFDiag(E);
4724 }
4725 return CompleteObject();
4726 }
4727 }
4728
4729 // When binding to a reference, the variable does not need to be constexpr
4730 // or have constant initalization.
4731 if (AK != clang::AK_Dereference &&
4732 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4733 BaseVal))
4734 return CompleteObject();
4735 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4736 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4737 // we can't access a constexpr-unknown object.
4738 if (AK != clang::AK_Dereference && !BaseVal) {
4739 if (!Info.checkingPotentialConstantExpression()) {
4740 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4741 << AK << VD;
4742 Info.Note(VD->getLocation(), diag::note_declared_at);
4743 }
4744 return CompleteObject();
4745 }
4746 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4747 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4748 if (!Alloc) {
4749 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4750 return CompleteObject();
4751 }
4752 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4753 LVal.Base.getDynamicAllocType());
4754 }
4755 // When binding to a reference, the variable does not need to be
4756 // within its lifetime.
4757 else if (AK != clang::AK_Dereference) {
4758 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4759
4760 if (!Frame) {
4761 if (const MaterializeTemporaryExpr *MTE =
4762 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4763 assert(MTE->getStorageDuration() == SD_Static &&
4764 "should have a frame for a non-global materialized temporary");
4765
4766 // C++20 [expr.const]p4: [DR2126]
4767 // An object or reference is usable in constant expressions if it is
4768 // - a temporary object of non-volatile const-qualified literal type
4769 // whose lifetime is extended to that of a variable that is usable
4770 // in constant expressions
4771 //
4772 // C++20 [expr.const]p5:
4773 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4774 // - a non-volatile glvalue that refers to an object that is usable
4775 // in constant expressions, or
4776 // - a non-volatile glvalue of literal type that refers to a
4777 // non-volatile object whose lifetime began within the evaluation
4778 // of E;
4779 //
4780 // C++11 misses the 'began within the evaluation of e' check and
4781 // instead allows all temporaries, including things like:
4782 // int &&r = 1;
4783 // int x = ++r;
4784 // constexpr int k = r;
4785 // Therefore we use the C++14-onwards rules in C++11 too.
4786 //
4787 // Note that temporaries whose lifetimes began while evaluating a
4788 // variable's constructor are not usable while evaluating the
4789 // corresponding destructor, not even if they're of const-qualified
4790 // types.
4791 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4792 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4793 if (!IsAccess)
4794 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4795 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4796 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4797 return CompleteObject();
4798 }
4799
4800 BaseVal = MTE->getOrCreateValue(false);
4801 assert(BaseVal && "got reference to unevaluated temporary");
4802 } else if (const CompoundLiteralExpr *CLE =
4803 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4804 // According to GCC info page:
4805 //
4806 // 6.28 Compound Literals
4807 //
4808 // As an optimization, G++ sometimes gives array compound literals
4809 // longer lifetimes: when the array either appears outside a function or
4810 // has a const-qualified type. If foo and its initializer had elements
4811 // of type char *const rather than char *, or if foo were a global
4812 // variable, the array would have static storage duration. But it is
4813 // probably safest just to avoid the use of array compound literals in
4814 // C++ code.
4815 //
4816 // Obey that rule by checking constness for converted array types.
4817 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4818 !LValType->isArrayType() &&
4819 !CLETy.isConstant(Info.Ctx)) {
4820 Info.FFDiag(E);
4821 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4822 return CompleteObject();
4823 }
4824
4825 BaseVal = &CLE->getStaticValue();
4826 } else {
4827 if (!IsAccess)
4828 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4829 APValue Val;
4830 LVal.moveInto(Val);
4831 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4832 << AK
4833 << Val.getAsString(Info.Ctx,
4834 Info.Ctx.getLValueReferenceType(LValType));
4835 NoteLValueLocation(Info, LVal.Base);
4836 return CompleteObject();
4837 }
4838 } else if (AK != clang::AK_Dereference) {
4839 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4840 assert(BaseVal && "missing value for temporary");
4841 }
4842 }
4843
4844 // In C++14, we can't safely access any mutable state when we might be
4845 // evaluating after an unmodeled side effect. Parameters are modeled as state
4846 // in the caller, but aren't visible once the call returns, so they can be
4847 // modified in a speculatively-evaluated call.
4848 //
4849 // FIXME: Not all local state is mutable. Allow local constant subobjects
4850 // to be read here (but take care with 'mutable' fields).
4851 unsigned VisibleDepth = Depth;
4852 if (llvm::isa_and_nonnull<ParmVarDecl>(
4853 LVal.Base.dyn_cast<const ValueDecl *>()))
4854 ++VisibleDepth;
4855 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4856 Info.EvalStatus.HasSideEffects) ||
4857 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4858 return CompleteObject();
4859
4860 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4861}
4862
4863/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4864/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4865/// glvalue referred to by an entity of reference type.
4866///
4867/// \param Info - Information about the ongoing evaluation.
4868/// \param Conv - The expression for which we are performing the conversion.
4869/// Used for diagnostics.
4870/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4871/// case of a non-class type).
4872/// \param LVal - The glvalue on which we are attempting to perform this action.
4873/// \param RVal - The produced value will be placed here.
4874/// \param WantObjectRepresentation - If true, we're looking for the object
4875/// representation rather than the value, and in particular,
4876/// there is no requirement that the result be fully initialized.
4877static bool
4879 const LValue &LVal, APValue &RVal,
4880 bool WantObjectRepresentation = false) {
4881 if (LVal.Designator.Invalid)
4882 return false;
4883
4884 // Check for special cases where there is no existing APValue to look at.
4885 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4886
4887 AccessKinds AK =
4888 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4889
4890 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4892 // Special-case character extraction so we don't have to construct an
4893 // APValue for the whole string.
4894 assert(LVal.Designator.Entries.size() <= 1 &&
4895 "Can only read characters from string literals");
4896 if (LVal.Designator.Entries.empty()) {
4897 // Fail for now for LValue to RValue conversion of an array.
4898 // (This shouldn't show up in C/C++, but it could be triggered by a
4899 // weird EvaluateAsRValue call from a tool.)
4900 Info.FFDiag(Conv);
4901 return false;
4902 }
4903 if (LVal.Designator.isOnePastTheEnd()) {
4904 if (Info.getLangOpts().CPlusPlus11)
4905 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4906 else
4907 Info.FFDiag(Conv);
4908 return false;
4909 }
4910 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4911 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4912 return true;
4913 }
4914 }
4915
4916 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4917 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4918}
4919
4920static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4921 QualType DestTy,
4922 SmallVectorImpl<APValue> &SrcVals,
4923 SmallVectorImpl<QualType> &SrcTypes) {
4924 APValue Val;
4925 if (!Evaluate(Val, Info, E))
4926 return false;
4927
4928 // must be dealing with a record
4929 if (Val.isLValue()) {
4930 LValue LVal;
4931 LVal.setFrom(Info.Ctx, Val);
4932 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4933 return false;
4934 }
4935
4936 unsigned NEls = elementwiseSize(Info, DestTy);
4937 // flatten the source
4938 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
4939 return false;
4940
4941 return true;
4942}
4943
4944/// Perform an assignment of Val to LVal. Takes ownership of Val.
4945static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4946 QualType LValType, APValue &Val) {
4947 if (LVal.Designator.Invalid)
4948 return false;
4949
4950 if (!Info.getLangOpts().CPlusPlus14) {
4951 Info.FFDiag(E);
4952 return false;
4953 }
4954
4955 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4956 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4957}
4958
4959namespace {
4960struct CompoundAssignSubobjectHandler {
4961 EvalInfo &Info;
4962 const CompoundAssignOperator *E;
4963 QualType PromotedLHSType;
4965 const APValue &RHS;
4966
4967 static const AccessKinds AccessKind = AK_Assign;
4968
4969 typedef bool result_type;
4970
4971 bool checkConst(QualType QT) {
4972 // Assigning to a const object has undefined behavior.
4973 if (QT.isConstQualified()) {
4974 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4975 return false;
4976 }
4977 return true;
4978 }
4979
4980 bool failed() { return false; }
4981 bool found(APValue &Subobj, QualType SubobjType) {
4982 switch (Subobj.getKind()) {
4983 case APValue::Int:
4984 return found(Subobj.getInt(), SubobjType);
4985 case APValue::Float:
4986 return found(Subobj.getFloat(), SubobjType);
4989 // FIXME: Implement complex compound assignment.
4990 Info.FFDiag(E);
4991 return false;
4992 case APValue::LValue:
4993 return foundPointer(Subobj, SubobjType);
4994 case APValue::Vector:
4995 return foundVector(Subobj, SubobjType);
4997 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4998 << /*read of=*/0 << /*uninitialized object=*/1
4999 << E->getLHS()->getSourceRange();
5000 return false;
5001 default:
5002 // FIXME: can this happen?
5003 Info.FFDiag(E);
5004 return false;
5005 }
5006 }
5007
5008 bool foundVector(APValue &Value, QualType SubobjType) {
5009 if (!checkConst(SubobjType))
5010 return false;
5011
5012 if (!SubobjType->isVectorType()) {
5013 Info.FFDiag(E);
5014 return false;
5015 }
5016 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5017 }
5018
5019 bool found(APSInt &Value, QualType SubobjType) {
5020 if (!checkConst(SubobjType))
5021 return false;
5022
5023 if (!SubobjType->isIntegerType()) {
5024 // We don't support compound assignment on integer-cast-to-pointer
5025 // values.
5026 Info.FFDiag(E);
5027 return false;
5028 }
5029
5030 if (RHS.isInt()) {
5031 APSInt LHS =
5032 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5033 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5034 return false;
5035 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5036 return true;
5037 } else if (RHS.isFloat()) {
5038 const FPOptions FPO = E->getFPFeaturesInEffect(
5039 Info.Ctx.getLangOpts());
5040 APFloat FValue(0.0);
5041 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5042 PromotedLHSType, FValue) &&
5043 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5044 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5045 Value);
5046 }
5047
5048 Info.FFDiag(E);
5049 return false;
5050 }
5051 bool found(APFloat &Value, QualType SubobjType) {
5052 return checkConst(SubobjType) &&
5053 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5054 Value) &&
5055 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5056 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5057 }
5058 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5059 if (!checkConst(SubobjType))
5060 return false;
5061
5062 QualType PointeeType;
5063 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5064 PointeeType = PT->getPointeeType();
5065
5066 if (PointeeType.isNull() || !RHS.isInt() ||
5067 (Opcode != BO_Add && Opcode != BO_Sub)) {
5068 Info.FFDiag(E);
5069 return false;
5070 }
5071
5072 APSInt Offset = RHS.getInt();
5073 if (Opcode == BO_Sub)
5074 negateAsSigned(Offset);
5075
5076 LValue LVal;
5077 LVal.setFrom(Info.Ctx, Subobj);
5078 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5079 return false;
5080 LVal.moveInto(Subobj);
5081 return true;
5082 }
5083};
5084} // end anonymous namespace
5085
5086const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5087
5088/// Perform a compound assignment of LVal <op>= RVal.
5089static bool handleCompoundAssignment(EvalInfo &Info,
5090 const CompoundAssignOperator *E,
5091 const LValue &LVal, QualType LValType,
5092 QualType PromotedLValType,
5093 BinaryOperatorKind Opcode,
5094 const APValue &RVal) {
5095 if (LVal.Designator.Invalid)
5096 return false;
5097
5098 if (!Info.getLangOpts().CPlusPlus14) {
5099 Info.FFDiag(E);
5100 return false;
5101 }
5102
5103 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5104 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5105 RVal };
5106 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5107}
5108
5109namespace {
5110struct IncDecSubobjectHandler {
5111 EvalInfo &Info;
5112 const UnaryOperator *E;
5114 APValue *Old;
5115
5116 typedef bool result_type;
5117
5118 bool checkConst(QualType QT) {
5119 // Assigning to a const object has undefined behavior.
5120 if (QT.isConstQualified()) {
5121 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5122 return false;
5123 }
5124 return true;
5125 }
5126
5127 bool failed() { return false; }
5128 bool found(APValue &Subobj, QualType SubobjType) {
5129 // Stash the old value. Also clear Old, so we don't clobber it later
5130 // if we're post-incrementing a complex.
5131 if (Old) {
5132 *Old = Subobj;
5133 Old = nullptr;
5134 }
5135
5136 switch (Subobj.getKind()) {
5137 case APValue::Int:
5138 return found(Subobj.getInt(), SubobjType);
5139 case APValue::Float:
5140 return found(Subobj.getFloat(), SubobjType);
5142 return found(Subobj.getComplexIntReal(),
5143 SubobjType->castAs<ComplexType>()->getElementType()
5144 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5146 return found(Subobj.getComplexFloatReal(),
5147 SubobjType->castAs<ComplexType>()->getElementType()
5148 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5149 case APValue::LValue:
5150 return foundPointer(Subobj, SubobjType);
5151 default:
5152 // FIXME: can this happen?
5153 Info.FFDiag(E);
5154 return false;
5155 }
5156 }
5157 bool found(APSInt &Value, QualType SubobjType) {
5158 if (!checkConst(SubobjType))
5159 return false;
5160
5161 if (!SubobjType->isIntegerType()) {
5162 // We don't support increment / decrement on integer-cast-to-pointer
5163 // values.
5164 Info.FFDiag(E);
5165 return false;
5166 }
5167
5168 if (Old) *Old = APValue(Value);
5169
5170 // bool arithmetic promotes to int, and the conversion back to bool
5171 // doesn't reduce mod 2^n, so special-case it.
5172 if (SubobjType->isBooleanType()) {
5173 if (AccessKind == AK_Increment)
5174 Value = 1;
5175 else
5176 Value = !Value;
5177 return true;
5178 }
5179
5180 bool WasNegative = Value.isNegative();
5181 if (AccessKind == AK_Increment) {
5182 ++Value;
5183
5184 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5185 !SubobjType.isWrapType()) {
5186 APSInt ActualValue(Value, /*IsUnsigned*/true);
5187 return HandleOverflow(Info, E, ActualValue, SubobjType);
5188 }
5189 } else {
5190 --Value;
5191
5192 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5193 !SubobjType.isWrapType()) {
5194 unsigned BitWidth = Value.getBitWidth();
5195 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5196 ActualValue.setBit(BitWidth);
5197 return HandleOverflow(Info, E, ActualValue, SubobjType);
5198 }
5199 }
5200 return true;
5201 }
5202 bool found(APFloat &Value, QualType SubobjType) {
5203 if (!checkConst(SubobjType))
5204 return false;
5205
5206 if (Old) *Old = APValue(Value);
5207
5208 APFloat One(Value.getSemantics(), 1);
5209 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5210 APFloat::opStatus St;
5211 if (AccessKind == AK_Increment)
5212 St = Value.add(One, RM);
5213 else
5214 St = Value.subtract(One, RM);
5215 return checkFloatingPointResult(Info, E, St);
5216 }
5217 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5218 if (!checkConst(SubobjType))
5219 return false;
5220
5221 QualType PointeeType;
5222 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5223 PointeeType = PT->getPointeeType();
5224 else {
5225 Info.FFDiag(E);
5226 return false;
5227 }
5228
5229 LValue LVal;
5230 LVal.setFrom(Info.Ctx, Subobj);
5231 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5232 AccessKind == AK_Increment ? 1 : -1))
5233 return false;
5234 LVal.moveInto(Subobj);
5235 return true;
5236 }
5237};
5238} // end anonymous namespace
5239
5240/// Perform an increment or decrement on LVal.
5241static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5242 QualType LValType, bool IsIncrement, APValue *Old) {
5243 if (LVal.Designator.Invalid)
5244 return false;
5245
5246 if (!Info.getLangOpts().CPlusPlus14) {
5247 Info.FFDiag(E);
5248 return false;
5249 }
5250
5251 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5252 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5253 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5254 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5255}
5256
5257/// Build an lvalue for the object argument of a member function call.
5258static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5259 LValue &This) {
5260 if (Object->getType()->isPointerType() && Object->isPRValue())
5261 return EvaluatePointer(Object, This, Info);
5262
5263 if (Object->isGLValue())
5264 return EvaluateLValue(Object, This, Info);
5265
5266 if (Object->getType()->isLiteralType(Info.Ctx))
5267 return EvaluateTemporary(Object, This, Info);
5268
5269 if (Object->getType()->isRecordType() && Object->isPRValue())
5270 return EvaluateTemporary(Object, This, Info);
5271
5272 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5273 return false;
5274}
5275
5276/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5277/// lvalue referring to the result.
5278///
5279/// \param Info - Information about the ongoing evaluation.
5280/// \param LV - An lvalue referring to the base of the member pointer.
5281/// \param RHS - The member pointer expression.
5282/// \param IncludeMember - Specifies whether the member itself is included in
5283/// the resulting LValue subobject designator. This is not possible when
5284/// creating a bound member function.
5285/// \return The field or method declaration to which the member pointer refers,
5286/// or 0 if evaluation fails.
5287static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5288 QualType LVType,
5289 LValue &LV,
5290 const Expr *RHS,
5291 bool IncludeMember = true) {
5292 MemberPtr MemPtr;
5293 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5294 return nullptr;
5295
5296 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5297 // member value, the behavior is undefined.
5298 if (!MemPtr.getDecl()) {
5299 // FIXME: Specific diagnostic.
5300 Info.FFDiag(RHS);
5301 return nullptr;
5302 }
5303
5304 if (MemPtr.isDerivedMember()) {
5305 // This is a member of some derived class. Truncate LV appropriately.
5306 // The end of the derived-to-base path for the base object must match the
5307 // derived-to-base path for the member pointer.
5308 // C++23 [expr.mptr.oper]p4:
5309 // If the result of E1 is an object [...] whose most derived object does
5310 // not contain the member to which E2 refers, the behavior is undefined.
5311 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5312 LV.Designator.Entries.size()) {
5313 Info.FFDiag(RHS);
5314 return nullptr;
5315 }
5316 unsigned PathLengthToMember =
5317 LV.Designator.Entries.size() - MemPtr.Path.size();
5318 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5319 const CXXRecordDecl *LVDecl = getAsBaseClass(
5320 LV.Designator.Entries[PathLengthToMember + I]);
5321 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5322 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5323 Info.FFDiag(RHS);
5324 return nullptr;
5325 }
5326 }
5327 // MemPtr.Path only contains the base classes of the class directly
5328 // containing the member E2. It is still necessary to check that the class
5329 // directly containing the member E2 lies on the derived-to-base path of E1
5330 // to avoid incorrectly permitting member pointer access into a sibling
5331 // class of the class containing the member E2. If this class would
5332 // correspond to the most-derived class of E1, it either isn't contained in
5333 // LV.Designator.Entries or the corresponding entry refers to an array
5334 // element instead. Therefore get the most derived class directly in this
5335 // case. Otherwise the previous entry should correpond to this class.
5336 const CXXRecordDecl *LastLVDecl =
5337 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5338 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5339 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5340 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5341 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5342 Info.FFDiag(RHS);
5343 return nullptr;
5344 }
5345
5346 // Truncate the lvalue to the appropriate derived class.
5347 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5348 PathLengthToMember))
5349 return nullptr;
5350 } else if (!MemPtr.Path.empty()) {
5351 // Extend the LValue path with the member pointer's path.
5352 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5353 MemPtr.Path.size() + IncludeMember);
5354
5355 // Walk down to the appropriate base class.
5356 if (const PointerType *PT = LVType->getAs<PointerType>())
5357 LVType = PT->getPointeeType();
5358 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5359 assert(RD && "member pointer access on non-class-type expression");
5360 // The first class in the path is that of the lvalue.
5361 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5362 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5363 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5364 return nullptr;
5365 RD = Base;
5366 }
5367 // Finally cast to the class containing the member.
5368 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5369 MemPtr.getContainingRecord()))
5370 return nullptr;
5371 }
5372
5373 // Add the member. Note that we cannot build bound member functions here.
5374 if (IncludeMember) {
5375 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5376 if (!HandleLValueMember(Info, RHS, LV, FD))
5377 return nullptr;
5378 } else if (const IndirectFieldDecl *IFD =
5379 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5380 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5381 return nullptr;
5382 } else {
5383 llvm_unreachable("can't construct reference to bound member function");
5384 }
5385 }
5386
5387 return MemPtr.getDecl();
5388}
5389
5390static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5391 const BinaryOperator *BO,
5392 LValue &LV,
5393 bool IncludeMember = true) {
5394 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5395
5396 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5397 if (Info.noteFailure()) {
5398 MemberPtr MemPtr;
5399 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5400 }
5401 return nullptr;
5402 }
5403
5404 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5405 BO->getRHS(), IncludeMember);
5406}
5407
5408/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5409/// the provided lvalue, which currently refers to the base object.
5410static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5411 LValue &Result) {
5412 SubobjectDesignator &D = Result.Designator;
5413 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5414 return false;
5415
5416 QualType TargetQT = E->getType();
5417 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5418 TargetQT = PT->getPointeeType();
5419
5420 auto InvalidCast = [&]() {
5421 if (!Info.checkingPotentialConstantExpression() ||
5422 !Result.AllowConstexprUnknown) {
5423 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5424 << D.MostDerivedType << TargetQT;
5425 }
5426 return false;
5427 };
5428
5429 // Check this cast lands within the final derived-to-base subobject path.
5430 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5431 return InvalidCast();
5432
5433 // Check the type of the final cast. We don't need to check the path,
5434 // since a cast can only be formed if the path is unique.
5435 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5436 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5437 const CXXRecordDecl *FinalType;
5438 if (NewEntriesSize == D.MostDerivedPathLength)
5439 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5440 else
5441 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5442 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5443 return InvalidCast();
5444
5445 // Truncate the lvalue to the appropriate derived class.
5446 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5447}
5448
5449/// Get the value to use for a default-initialized object of type T.
5450/// Return false if it encounters something invalid.
5451static bool handleDefaultInitValue(QualType T, APValue &Result) {
5452 bool Success = true;
5453
5454 // If there is already a value present don't overwrite it.
5455 if (!Result.isAbsent())
5456 return true;
5457
5458 if (auto *RD = T->getAsCXXRecordDecl()) {
5459 if (RD->isInvalidDecl()) {
5460 Result = APValue();
5461 return false;
5462 }
5463 if (RD->isUnion()) {
5464 Result = APValue((const FieldDecl *)nullptr);
5465 return true;
5466 }
5467 Result =
5468 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5469
5470 unsigned Index = 0;
5471 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5472 End = RD->bases_end();
5473 I != End; ++I, ++Index)
5474 Success &=
5475 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5476
5477 for (const auto *I : RD->fields()) {
5478 if (I->isUnnamedBitField())
5479 continue;
5481 I->getType(), Result.getStructField(I->getFieldIndex()));
5482 }
5483 return Success;
5484 }
5485
5486 if (auto *AT =
5487 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5488 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5489 if (Result.hasArrayFiller())
5490 Success &=
5491 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5492
5493 return Success;
5494 }
5495
5496 Result = APValue::IndeterminateValue();
5497 return true;
5498}
5499
5500namespace {
5501enum EvalStmtResult {
5502 /// Evaluation failed.
5503 ESR_Failed,
5504 /// Hit a 'return' statement.
5505 ESR_Returned,
5506 /// Evaluation succeeded.
5507 ESR_Succeeded,
5508 /// Hit a 'continue' statement.
5509 ESR_Continue,
5510 /// Hit a 'break' statement.
5511 ESR_Break,
5512 /// Still scanning for 'case' or 'default' statement.
5513 ESR_CaseNotFound
5514};
5515}
5516/// Evaluates the initializer of a reference.
5517static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5518 const ValueDecl *D,
5519 const Expr *Init, LValue &Result,
5520 APValue &Val) {
5521 assert(Init->isGLValue() && D->getType()->isReferenceType());
5522 // A reference is an lvalue.
5523 if (!EvaluateLValue(Init, Result, Info))
5524 return false;
5525 // [C++26][decl.ref]
5526 // The object designated by such a glvalue can be outside its lifetime
5527 // Because a null pointer value or a pointer past the end of an object
5528 // does not point to an object, a reference in a well-defined program cannot
5529 // refer to such things;
5530 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5531 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5532 return false;
5533 }
5534
5535 // Save the result.
5536 Result.moveInto(Val);
5537 return true;
5538}
5539
5540static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5541 if (VD->isInvalidDecl())
5542 return false;
5543 // We don't need to evaluate the initializer for a static local.
5544 if (!VD->hasLocalStorage())
5545 return true;
5546
5547 LValue Result;
5548 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5549 ScopeKind::Block, Result);
5550
5551 const Expr *InitE = VD->getInit();
5552 if (!InitE) {
5553 if (VD->getType()->isDependentType())
5554 return Info.noteSideEffect();
5555 return handleDefaultInitValue(VD->getType(), Val);
5556 }
5557 if (InitE->isValueDependent())
5558 return false;
5559
5560 // For references to objects, check they do not designate a one-past-the-end
5561 // object.
5562 if (VD->getType()->isReferenceType()) {
5563 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5564 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5565 // Wipe out any partially-computed value, to allow tracking that this
5566 // evaluation failed.
5567 Val = APValue();
5568 return false;
5569 }
5570
5571 return true;
5572}
5573
5574static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5575 const DecompositionDecl *DD);
5576
5577static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5578 bool EvaluateConditionDecl = false) {
5579 bool OK = true;
5580 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5581 OK &= EvaluateVarDecl(Info, VD);
5582
5583 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5584 EvaluateConditionDecl && DD)
5585 OK &= EvaluateDecompositionDeclInit(Info, DD);
5586
5587 return OK;
5588}
5589
5590static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5591 const DecompositionDecl *DD) {
5592 bool OK = true;
5593 for (auto *BD : DD->flat_bindings())
5594 if (auto *VD = BD->getHoldingVar())
5595 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5596
5597 return OK;
5598}
5599
5600static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5601 const VarDecl *VD) {
5602 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5603 if (!EvaluateDecompositionDeclInit(Info, DD))
5604 return false;
5605 }
5606 return true;
5607}
5608
5609static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5610 assert(E->isValueDependent());
5611 if (Info.noteSideEffect())
5612 return true;
5613 assert(E->containsErrors() && "valid value-dependent expression should never "
5614 "reach invalid code path.");
5615 return false;
5616}
5617
5618/// Evaluate a condition (either a variable declaration or an expression).
5619static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5620 const Expr *Cond, bool &Result) {
5621 if (Cond->isValueDependent())
5622 return false;
5623 FullExpressionRAII Scope(Info);
5624 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5625 return false;
5626 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5627 return false;
5628 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5629 return false;
5630 return Scope.destroy();
5631}
5632
5633namespace {
5634/// A location where the result (returned value) of evaluating a
5635/// statement should be stored.
5636struct StmtResult {
5637 /// The APValue that should be filled in with the returned value.
5638 APValue &Value;
5639 /// The location containing the result, if any (used to support RVO).
5640 const LValue *Slot;
5641};
5642
5643struct TempVersionRAII {
5644 CallStackFrame &Frame;
5645
5646 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5647 Frame.pushTempVersion();
5648 }
5649
5650 ~TempVersionRAII() {
5651 Frame.popTempVersion();
5652 }
5653};
5654
5655}
5656
5657static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5658 const Stmt *S,
5659 const SwitchCase *SC = nullptr);
5660
5661/// Helper to implement named break/continue. Returns 'true' if the evaluation
5662/// result should be propagated up. Otherwise, it sets the evaluation result
5663/// to either Continue to continue the current loop, or Succeeded to break it.
5664static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5665 const Stmt *LoopOrSwitch,
5667 EvalStmtResult &ESR) {
5668 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5669
5670 // For loops, map Succeeded to Continue so we don't have to check for both.
5671 if (!IsSwitch && ESR == ESR_Succeeded) {
5672 ESR = ESR_Continue;
5673 return false;
5674 }
5675
5676 if (ESR != ESR_Break && ESR != ESR_Continue)
5677 return false;
5678
5679 // Are we breaking out of or continuing this statement?
5680 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5681 const Stmt *StackTop = Info.BreakContinueStack.back();
5682 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5683 Info.BreakContinueStack.pop_back();
5684 if (ESR == ESR_Break)
5685 ESR = ESR_Succeeded;
5686 return false;
5687 }
5688
5689 // We're not. Propagate the result up.
5690 for (BlockScopeRAII *S : Scopes) {
5691 if (!S->destroy()) {
5692 ESR = ESR_Failed;
5693 break;
5694 }
5695 }
5696 return true;
5697}
5698
5699/// Evaluate the body of a loop, and translate the result as appropriate.
5700static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5701 const Stmt *Body,
5702 const SwitchCase *Case = nullptr) {
5703 BlockScopeRAII Scope(Info);
5704
5705 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5706 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5707 ESR = ESR_Failed;
5708
5709 return ESR;
5710}
5711
5712/// Evaluate a switch statement.
5713static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5714 const SwitchStmt *SS) {
5715 BlockScopeRAII Scope(Info);
5716
5717 // Evaluate the switch condition.
5718 APSInt Value;
5719 {
5720 if (const Stmt *Init = SS->getInit()) {
5721 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5722 if (ESR != ESR_Succeeded) {
5723 if (ESR != ESR_Failed && !Scope.destroy())
5724 ESR = ESR_Failed;
5725 return ESR;
5726 }
5727 }
5728
5729 FullExpressionRAII CondScope(Info);
5730 if (SS->getConditionVariable() &&
5731 !EvaluateDecl(Info, SS->getConditionVariable()))
5732 return ESR_Failed;
5733 if (SS->getCond()->isValueDependent()) {
5734 // We don't know what the value is, and which branch should jump to.
5735 EvaluateDependentExpr(SS->getCond(), Info);
5736 return ESR_Failed;
5737 }
5738 if (!EvaluateInteger(SS->getCond(), Value, Info))
5739 return ESR_Failed;
5740
5742 return ESR_Failed;
5743
5744 if (!CondScope.destroy())
5745 return ESR_Failed;
5746 }
5747
5748 // Find the switch case corresponding to the value of the condition.
5749 // FIXME: Cache this lookup.
5750 const SwitchCase *Found = nullptr;
5751 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5752 SC = SC->getNextSwitchCase()) {
5753 if (isa<DefaultStmt>(SC)) {
5754 Found = SC;
5755 continue;
5756 }
5757
5758 const CaseStmt *CS = cast<CaseStmt>(SC);
5759 const Expr *LHS = CS->getLHS();
5760 const Expr *RHS = CS->getRHS();
5761 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5762 return ESR_Failed;
5763 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5764 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5765 if (LHSValue <= Value && Value <= RHSValue) {
5766 Found = SC;
5767 break;
5768 }
5769 }
5770
5771 if (!Found)
5772 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5773
5774 // Search the switch body for the switch case and evaluate it from there.
5775 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5776 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5777 return ESR_Failed;
5778 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5779 return ESR;
5780
5781 switch (ESR) {
5782 case ESR_Break:
5783 llvm_unreachable("Should have been converted to Succeeded");
5784 case ESR_Succeeded:
5785 case ESR_Continue:
5786 case ESR_Failed:
5787 case ESR_Returned:
5788 return ESR;
5789 case ESR_CaseNotFound:
5790 // This can only happen if the switch case is nested within a statement
5791 // expression. We have no intention of supporting that.
5792 Info.FFDiag(Found->getBeginLoc(),
5793 diag::note_constexpr_stmt_expr_unsupported);
5794 return ESR_Failed;
5795 }
5796 llvm_unreachable("Invalid EvalStmtResult!");
5797}
5798
5799static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5800 // An expression E is a core constant expression unless the evaluation of E
5801 // would evaluate one of the following: [C++23] - a control flow that passes
5802 // through a declaration of a variable with static or thread storage duration
5803 // unless that variable is usable in constant expressions.
5804 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5805 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5806 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5807 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5808 return false;
5809 }
5810 return true;
5811}
5812
5813// Evaluate a statement.
5814static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5815 const Stmt *S, const SwitchCase *Case) {
5816 if (!Info.nextStep(S))
5817 return ESR_Failed;
5818
5819 // If we're hunting down a 'case' or 'default' label, recurse through
5820 // substatements until we hit the label.
5821 if (Case) {
5822 switch (S->getStmtClass()) {
5823 case Stmt::CompoundStmtClass:
5824 // FIXME: Precompute which substatement of a compound statement we
5825 // would jump to, and go straight there rather than performing a
5826 // linear scan each time.
5827 case Stmt::LabelStmtClass:
5828 case Stmt::AttributedStmtClass:
5829 case Stmt::DoStmtClass:
5830 break;
5831
5832 case Stmt::CaseStmtClass:
5833 case Stmt::DefaultStmtClass:
5834 if (Case == S)
5835 Case = nullptr;
5836 break;
5837
5838 case Stmt::IfStmtClass: {
5839 // FIXME: Precompute which side of an 'if' we would jump to, and go
5840 // straight there rather than scanning both sides.
5841 const IfStmt *IS = cast<IfStmt>(S);
5842
5843 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5844 // preceded by our switch label.
5845 BlockScopeRAII Scope(Info);
5846
5847 // Step into the init statement in case it brings an (uninitialized)
5848 // variable into scope.
5849 if (const Stmt *Init = IS->getInit()) {
5850 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5851 if (ESR != ESR_CaseNotFound) {
5852 assert(ESR != ESR_Succeeded);
5853 return ESR;
5854 }
5855 }
5856
5857 // Condition variable must be initialized if it exists.
5858 // FIXME: We can skip evaluating the body if there's a condition
5859 // variable, as there can't be any case labels within it.
5860 // (The same is true for 'for' statements.)
5861
5862 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5863 if (ESR == ESR_Failed)
5864 return ESR;
5865 if (ESR != ESR_CaseNotFound)
5866 return Scope.destroy() ? ESR : ESR_Failed;
5867 if (!IS->getElse())
5868 return ESR_CaseNotFound;
5869
5870 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5871 if (ESR == ESR_Failed)
5872 return ESR;
5873 if (ESR != ESR_CaseNotFound)
5874 return Scope.destroy() ? ESR : ESR_Failed;
5875 return ESR_CaseNotFound;
5876 }
5877
5878 case Stmt::WhileStmtClass: {
5879 EvalStmtResult ESR =
5880 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5881 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5882 return ESR;
5883 if (ESR != ESR_Continue)
5884 return ESR;
5885 break;
5886 }
5887
5888 case Stmt::ForStmtClass: {
5889 const ForStmt *FS = cast<ForStmt>(S);
5890 BlockScopeRAII Scope(Info);
5891
5892 // Step into the init statement in case it brings an (uninitialized)
5893 // variable into scope.
5894 if (const Stmt *Init = FS->getInit()) {
5895 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5896 if (ESR != ESR_CaseNotFound) {
5897 assert(ESR != ESR_Succeeded);
5898 return ESR;
5899 }
5900 }
5901
5902 EvalStmtResult ESR =
5903 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5904 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5905 return ESR;
5906 if (ESR != ESR_Continue)
5907 return ESR;
5908 if (const auto *Inc = FS->getInc()) {
5909 if (Inc->isValueDependent()) {
5910 if (!EvaluateDependentExpr(Inc, Info))
5911 return ESR_Failed;
5912 } else {
5913 FullExpressionRAII IncScope(Info);
5914 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5915 return ESR_Failed;
5916 }
5917 }
5918 break;
5919 }
5920
5921 case Stmt::DeclStmtClass: {
5922 // Start the lifetime of any uninitialized variables we encounter. They
5923 // might be used by the selected branch of the switch.
5924 const DeclStmt *DS = cast<DeclStmt>(S);
5925 for (const auto *D : DS->decls()) {
5926 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5927 if (!CheckLocalVariableDeclaration(Info, VD))
5928 return ESR_Failed;
5929 if (VD->hasLocalStorage() && !VD->getInit())
5930 if (!EvaluateVarDecl(Info, VD))
5931 return ESR_Failed;
5932 // FIXME: If the variable has initialization that can't be jumped
5933 // over, bail out of any immediately-surrounding compound-statement
5934 // too. There can't be any case labels here.
5935 }
5936 }
5937 return ESR_CaseNotFound;
5938 }
5939
5940 default:
5941 return ESR_CaseNotFound;
5942 }
5943 }
5944
5945 switch (S->getStmtClass()) {
5946 default:
5947 if (const Expr *E = dyn_cast<Expr>(S)) {
5948 if (E->isValueDependent()) {
5949 if (!EvaluateDependentExpr(E, Info))
5950 return ESR_Failed;
5951 } else {
5952 // Don't bother evaluating beyond an expression-statement which couldn't
5953 // be evaluated.
5954 // FIXME: Do we need the FullExpressionRAII object here?
5955 // VisitExprWithCleanups should create one when necessary.
5956 FullExpressionRAII Scope(Info);
5957 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5958 return ESR_Failed;
5959 }
5960 return ESR_Succeeded;
5961 }
5962
5963 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5964 return ESR_Failed;
5965
5966 case Stmt::NullStmtClass:
5967 return ESR_Succeeded;
5968
5969 case Stmt::DeclStmtClass: {
5970 const DeclStmt *DS = cast<DeclStmt>(S);
5971 for (const auto *D : DS->decls()) {
5972 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5973 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5974 return ESR_Failed;
5975 // Each declaration initialization is its own full-expression.
5976 FullExpressionRAII Scope(Info);
5977 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5978 !Info.noteFailure())
5979 return ESR_Failed;
5980 if (!Scope.destroy())
5981 return ESR_Failed;
5982 }
5983 return ESR_Succeeded;
5984 }
5985
5986 case Stmt::ReturnStmtClass: {
5987 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5988 FullExpressionRAII Scope(Info);
5989 if (RetExpr && RetExpr->isValueDependent()) {
5990 EvaluateDependentExpr(RetExpr, Info);
5991 // We know we returned, but we don't know what the value is.
5992 return ESR_Failed;
5993 }
5994 if (RetExpr &&
5995 !(Result.Slot
5996 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5997 : Evaluate(Result.Value, Info, RetExpr)))
5998 return ESR_Failed;
5999 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6000 }
6001
6002 case Stmt::CompoundStmtClass: {
6003 BlockScopeRAII Scope(Info);
6004
6005 const CompoundStmt *CS = cast<CompoundStmt>(S);
6006 for (const auto *BI : CS->body()) {
6007 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6008 if (ESR == ESR_Succeeded)
6009 Case = nullptr;
6010 else if (ESR != ESR_CaseNotFound) {
6011 if (ESR != ESR_Failed && !Scope.destroy())
6012 return ESR_Failed;
6013 return ESR;
6014 }
6015 }
6016 if (Case)
6017 return ESR_CaseNotFound;
6018 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6019 }
6020
6021 case Stmt::IfStmtClass: {
6022 const IfStmt *IS = cast<IfStmt>(S);
6023
6024 // Evaluate the condition, as either a var decl or as an expression.
6025 BlockScopeRAII Scope(Info);
6026 if (const Stmt *Init = IS->getInit()) {
6027 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6028 if (ESR != ESR_Succeeded) {
6029 if (ESR != ESR_Failed && !Scope.destroy())
6030 return ESR_Failed;
6031 return ESR;
6032 }
6033 }
6034 bool Cond;
6035 if (IS->isConsteval()) {
6037 // If we are not in a constant context, if consteval should not evaluate
6038 // to true.
6039 if (!Info.InConstantContext)
6040 Cond = !Cond;
6041 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6042 Cond))
6043 return ESR_Failed;
6044
6045 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6046 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6047 if (ESR != ESR_Succeeded) {
6048 if (ESR != ESR_Failed && !Scope.destroy())
6049 return ESR_Failed;
6050 return ESR;
6051 }
6052 }
6053 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6054 }
6055
6056 case Stmt::WhileStmtClass: {
6057 const WhileStmt *WS = cast<WhileStmt>(S);
6058 while (true) {
6059 BlockScopeRAII Scope(Info);
6060 bool Continue;
6061 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6062 Continue))
6063 return ESR_Failed;
6064 if (!Continue)
6065 break;
6066
6067 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6068 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6069 return ESR;
6070
6071 if (ESR != ESR_Continue) {
6072 if (ESR != ESR_Failed && !Scope.destroy())
6073 return ESR_Failed;
6074 return ESR;
6075 }
6076 if (!Scope.destroy())
6077 return ESR_Failed;
6078 }
6079 return ESR_Succeeded;
6080 }
6081
6082 case Stmt::DoStmtClass: {
6083 const DoStmt *DS = cast<DoStmt>(S);
6084 bool Continue;
6085 do {
6086 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6087 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6088 return ESR;
6089 if (ESR != ESR_Continue)
6090 return ESR;
6091 Case = nullptr;
6092
6093 if (DS->getCond()->isValueDependent()) {
6094 EvaluateDependentExpr(DS->getCond(), Info);
6095 // Bailout as we don't know whether to keep going or terminate the loop.
6096 return ESR_Failed;
6097 }
6098 FullExpressionRAII CondScope(Info);
6099 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6100 !CondScope.destroy())
6101 return ESR_Failed;
6102 } while (Continue);
6103 return ESR_Succeeded;
6104 }
6105
6106 case Stmt::ForStmtClass: {
6107 const ForStmt *FS = cast<ForStmt>(S);
6108 BlockScopeRAII ForScope(Info);
6109 if (FS->getInit()) {
6110 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6111 if (ESR != ESR_Succeeded) {
6112 if (ESR != ESR_Failed && !ForScope.destroy())
6113 return ESR_Failed;
6114 return ESR;
6115 }
6116 }
6117 while (true) {
6118 BlockScopeRAII IterScope(Info);
6119 bool Continue = true;
6120 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6121 FS->getCond(), Continue))
6122 return ESR_Failed;
6123
6124 if (!Continue) {
6125 if (!IterScope.destroy())
6126 return ESR_Failed;
6127 break;
6128 }
6129
6130 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6131 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6132 return ESR;
6133 if (ESR != ESR_Continue) {
6134 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6135 return ESR_Failed;
6136 return ESR;
6137 }
6138
6139 if (const auto *Inc = FS->getInc()) {
6140 if (Inc->isValueDependent()) {
6141 if (!EvaluateDependentExpr(Inc, Info))
6142 return ESR_Failed;
6143 } else {
6144 FullExpressionRAII IncScope(Info);
6145 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6146 return ESR_Failed;
6147 }
6148 }
6149
6150 if (!IterScope.destroy())
6151 return ESR_Failed;
6152 }
6153 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6154 }
6155
6156 case Stmt::CXXForRangeStmtClass: {
6158 BlockScopeRAII Scope(Info);
6159
6160 // Evaluate the init-statement if present.
6161 if (FS->getInit()) {
6162 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6163 if (ESR != ESR_Succeeded) {
6164 if (ESR != ESR_Failed && !Scope.destroy())
6165 return ESR_Failed;
6166 return ESR;
6167 }
6168 }
6169
6170 // Initialize the __range variable.
6171 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6172 if (ESR != ESR_Succeeded) {
6173 if (ESR != ESR_Failed && !Scope.destroy())
6174 return ESR_Failed;
6175 return ESR;
6176 }
6177
6178 // In error-recovery cases it's possible to get here even if we failed to
6179 // synthesize the __begin and __end variables.
6180 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6181 return ESR_Failed;
6182
6183 // Create the __begin and __end iterators.
6184 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6185 if (ESR != ESR_Succeeded) {
6186 if (ESR != ESR_Failed && !Scope.destroy())
6187 return ESR_Failed;
6188 return ESR;
6189 }
6190 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6191 if (ESR != ESR_Succeeded) {
6192 if (ESR != ESR_Failed && !Scope.destroy())
6193 return ESR_Failed;
6194 return ESR;
6195 }
6196
6197 while (true) {
6198 // Condition: __begin != __end.
6199 {
6200 if (FS->getCond()->isValueDependent()) {
6201 EvaluateDependentExpr(FS->getCond(), Info);
6202 // We don't know whether to keep going or terminate the loop.
6203 return ESR_Failed;
6204 }
6205 bool Continue = true;
6206 FullExpressionRAII CondExpr(Info);
6207 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6208 return ESR_Failed;
6209 if (!Continue)
6210 break;
6211 }
6212
6213 // User's variable declaration, initialized by *__begin.
6214 BlockScopeRAII InnerScope(Info);
6215 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6216 if (ESR != ESR_Succeeded) {
6217 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6218 return ESR_Failed;
6219 return ESR;
6220 }
6221
6222 // Loop body.
6223 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6224 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6225 return ESR;
6226 if (ESR != ESR_Continue) {
6227 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6228 return ESR_Failed;
6229 return ESR;
6230 }
6231 if (FS->getInc()->isValueDependent()) {
6232 if (!EvaluateDependentExpr(FS->getInc(), Info))
6233 return ESR_Failed;
6234 } else {
6235 // Increment: ++__begin
6236 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6237 return ESR_Failed;
6238 }
6239
6240 if (!InnerScope.destroy())
6241 return ESR_Failed;
6242 }
6243
6244 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6245 }
6246
6247 case Stmt::SwitchStmtClass:
6248 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6249
6250 case Stmt::ContinueStmtClass:
6251 case Stmt::BreakStmtClass: {
6252 auto *B = cast<LoopControlStmt>(S);
6253 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6254 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6255 }
6256
6257 case Stmt::LabelStmtClass:
6258 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6259
6260 case Stmt::AttributedStmtClass: {
6261 const auto *AS = cast<AttributedStmt>(S);
6262 const auto *SS = AS->getSubStmt();
6263 MSConstexprContextRAII ConstexprContext(
6264 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6265 isa<ReturnStmt>(SS));
6266
6267 auto LO = Info.Ctx.getLangOpts();
6268 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6269 for (auto *Attr : AS->getAttrs()) {
6270 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6271 if (!AA)
6272 continue;
6273
6274 auto *Assumption = AA->getAssumption();
6275 if (Assumption->isValueDependent())
6276 return ESR_Failed;
6277
6278 if (Assumption->HasSideEffects(Info.Ctx))
6279 continue;
6280
6281 bool Value;
6282 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6283 return ESR_Failed;
6284 if (!Value) {
6285 Info.CCEDiag(Assumption->getExprLoc(),
6286 diag::note_constexpr_assumption_failed);
6287 return ESR_Failed;
6288 }
6289 }
6290 }
6291
6292 return EvaluateStmt(Result, Info, SS, Case);
6293 }
6294
6295 case Stmt::CaseStmtClass:
6296 case Stmt::DefaultStmtClass:
6297 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6298 case Stmt::CXXTryStmtClass:
6299 // Evaluate try blocks by evaluating all sub statements.
6300 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6301 }
6302}
6303
6304/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6305/// default constructor. If so, we'll fold it whether or not it's marked as
6306/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6307/// so we need special handling.
6308static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6309 const CXXConstructorDecl *CD,
6310 bool IsValueInitialization) {
6311 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6312 return false;
6313
6314 // Value-initialization does not call a trivial default constructor, so such a
6315 // call is a core constant expression whether or not the constructor is
6316 // constexpr.
6317 if (!CD->isConstexpr() && !IsValueInitialization) {
6318 if (Info.getLangOpts().CPlusPlus11) {
6319 // FIXME: If DiagDecl is an implicitly-declared special member function,
6320 // we should be much more explicit about why it's not constexpr.
6321 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6322 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6323 Info.Note(CD->getLocation(), diag::note_declared_at);
6324 } else {
6325 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6326 }
6327 }
6328 return true;
6329}
6330
6331/// CheckConstexprFunction - Check that a function can be called in a constant
6332/// expression.
6333static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6335 const FunctionDecl *Definition,
6336 const Stmt *Body) {
6337 // Potential constant expressions can contain calls to declared, but not yet
6338 // defined, constexpr functions.
6339 if (Info.checkingPotentialConstantExpression() && !Definition &&
6340 Declaration->isConstexpr())
6341 return false;
6342
6343 // Bail out if the function declaration itself is invalid. We will
6344 // have produced a relevant diagnostic while parsing it, so just
6345 // note the problematic sub-expression.
6346 if (Declaration->isInvalidDecl()) {
6347 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6348 return false;
6349 }
6350
6351 // DR1872: An instantiated virtual constexpr function can't be called in a
6352 // constant expression (prior to C++20). We can still constant-fold such a
6353 // call.
6354 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6355 cast<CXXMethodDecl>(Declaration)->isVirtual())
6356 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6357
6358 if (Definition && Definition->isInvalidDecl()) {
6359 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6360 return false;
6361 }
6362
6363 // Can we evaluate this function call?
6364 if (Definition && Body &&
6365 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6366 Definition->hasAttr<MSConstexprAttr>())))
6367 return true;
6368
6369 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6370 // Special note for the assert() macro, as the normal error message falsely
6371 // implies we cannot use an assertion during constant evaluation.
6372 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6373 // FIXME: Instead of checking for an implementation-defined function,
6374 // check and evaluate the assert() macro.
6375 StringRef Name = DiagDecl->getName();
6376 bool AssertFailed =
6377 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6378 if (AssertFailed) {
6379 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6380 return false;
6381 }
6382 }
6383
6384 if (Info.getLangOpts().CPlusPlus11) {
6385 // If this function is not constexpr because it is an inherited
6386 // non-constexpr constructor, diagnose that directly.
6387 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6388 if (CD && CD->isInheritingConstructor()) {
6389 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6390 if (!Inherited->isConstexpr())
6391 DiagDecl = CD = Inherited;
6392 }
6393
6394 // FIXME: If DiagDecl is an implicitly-declared special member function
6395 // or an inheriting constructor, we should be much more explicit about why
6396 // it's not constexpr.
6397 if (CD && CD->isInheritingConstructor())
6398 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6399 << CD->getInheritedConstructor().getConstructor()->getParent();
6400 else
6401 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6402 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6403 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6404 } else {
6405 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6406 }
6407 return false;
6408}
6409
6410namespace {
6411struct CheckDynamicTypeHandler {
6413 typedef bool result_type;
6414 bool failed() { return false; }
6415 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6416 bool found(APSInt &Value, QualType SubobjType) { return true; }
6417 bool found(APFloat &Value, QualType SubobjType) { return true; }
6418};
6419} // end anonymous namespace
6420
6421/// Check that we can access the notional vptr of an object / determine its
6422/// dynamic type.
6423static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6424 AccessKinds AK, bool Polymorphic) {
6425 if (This.Designator.Invalid)
6426 return false;
6427
6428 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6429
6430 if (!Obj)
6431 return false;
6432
6433 if (!Obj.Value) {
6434 // The object is not usable in constant expressions, so we can't inspect
6435 // its value to see if it's in-lifetime or what the active union members
6436 // are. We can still check for a one-past-the-end lvalue.
6437 if (This.Designator.isOnePastTheEnd() ||
6438 This.Designator.isMostDerivedAnUnsizedArray()) {
6439 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6440 ? diag::note_constexpr_access_past_end
6441 : diag::note_constexpr_access_unsized_array)
6442 << AK;
6443 return false;
6444 } else if (Polymorphic) {
6445 // Conservatively refuse to perform a polymorphic operation if we would
6446 // not be able to read a notional 'vptr' value.
6447 if (!Info.checkingPotentialConstantExpression() ||
6448 !This.AllowConstexprUnknown) {
6449 APValue Val;
6450 This.moveInto(Val);
6451 QualType StarThisType =
6452 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6453 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6454 << AK << Val.getAsString(Info.Ctx, StarThisType);
6455 }
6456 return false;
6457 }
6458 return true;
6459 }
6460
6461 CheckDynamicTypeHandler Handler{AK};
6462 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6463}
6464
6465/// Check that the pointee of the 'this' pointer in a member function call is
6466/// either within its lifetime or in its period of construction or destruction.
6467static bool
6469 const LValue &This,
6470 const CXXMethodDecl *NamedMember) {
6471 return checkDynamicType(
6472 Info, E, This,
6473 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6474}
6475
6477 /// The dynamic class type of the object.
6479 /// The corresponding path length in the lvalue.
6480 unsigned PathLength;
6481};
6482
6483static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6484 unsigned PathLength) {
6485 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6486 Designator.Entries.size() && "invalid path length");
6487 return (PathLength == Designator.MostDerivedPathLength)
6488 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6489 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6490}
6491
6492/// Determine the dynamic type of an object.
6493static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6494 const Expr *E,
6495 LValue &This,
6496 AccessKinds AK) {
6497 // If we don't have an lvalue denoting an object of class type, there is no
6498 // meaningful dynamic type. (We consider objects of non-class type to have no
6499 // dynamic type.)
6500 if (!checkDynamicType(Info, E, This, AK,
6501 AK != AK_TypeId || This.AllowConstexprUnknown))
6502 return std::nullopt;
6503
6504 if (This.Designator.Invalid)
6505 return std::nullopt;
6506
6507 // Refuse to compute a dynamic type in the presence of virtual bases. This
6508 // shouldn't happen other than in constant-folding situations, since literal
6509 // types can't have virtual bases.
6510 //
6511 // Note that consumers of DynamicType assume that the type has no virtual
6512 // bases, and will need modifications if this restriction is relaxed.
6513 const CXXRecordDecl *Class =
6514 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6515 if (!Class || Class->getNumVBases()) {
6516 Info.FFDiag(E);
6517 return std::nullopt;
6518 }
6519
6520 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6521 // binary search here instead. But the overwhelmingly common case is that
6522 // we're not in the middle of a constructor, so it probably doesn't matter
6523 // in practice.
6524 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6525 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6526 PathLength <= Path.size(); ++PathLength) {
6527 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6528 Path.slice(0, PathLength))) {
6529 case ConstructionPhase::Bases:
6530 case ConstructionPhase::DestroyingBases:
6531 // We're constructing or destroying a base class. This is not the dynamic
6532 // type.
6533 break;
6534
6535 case ConstructionPhase::None:
6536 case ConstructionPhase::AfterBases:
6537 case ConstructionPhase::AfterFields:
6538 case ConstructionPhase::Destroying:
6539 // We've finished constructing the base classes and not yet started
6540 // destroying them again, so this is the dynamic type.
6541 return DynamicType{getBaseClassType(This.Designator, PathLength),
6542 PathLength};
6543 }
6544 }
6545
6546 // CWG issue 1517: we're constructing a base class of the object described by
6547 // 'This', so that object has not yet begun its period of construction and
6548 // any polymorphic operation on it results in undefined behavior.
6549 Info.FFDiag(E);
6550 return std::nullopt;
6551}
6552
6553/// Perform virtual dispatch.
6555 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6556 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6557 std::optional<DynamicType> DynType = ComputeDynamicType(
6558 Info, E, This,
6560 if (!DynType)
6561 return nullptr;
6562
6563 // Find the final overrider. It must be declared in one of the classes on the
6564 // path from the dynamic type to the static type.
6565 // FIXME: If we ever allow literal types to have virtual base classes, that
6566 // won't be true.
6567 const CXXMethodDecl *Callee = Found;
6568 unsigned PathLength = DynType->PathLength;
6569 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6570 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6571 const CXXMethodDecl *Overrider =
6572 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6573 if (Overrider) {
6574 Callee = Overrider;
6575 break;
6576 }
6577 }
6578
6579 // C++2a [class.abstract]p6:
6580 // the effect of making a virtual call to a pure virtual function [...] is
6581 // undefined
6582 if (Callee->isPureVirtual()) {
6583 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6584 Info.Note(Callee->getLocation(), diag::note_declared_at);
6585 return nullptr;
6586 }
6587
6588 // If necessary, walk the rest of the path to determine the sequence of
6589 // covariant adjustment steps to apply.
6590 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6591 Found->getReturnType())) {
6592 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6593 for (unsigned CovariantPathLength = PathLength + 1;
6594 CovariantPathLength != This.Designator.Entries.size();
6595 ++CovariantPathLength) {
6596 const CXXRecordDecl *NextClass =
6597 getBaseClassType(This.Designator, CovariantPathLength);
6598 const CXXMethodDecl *Next =
6599 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6600 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6601 Next->getReturnType(), CovariantAdjustmentPath.back()))
6602 CovariantAdjustmentPath.push_back(Next->getReturnType());
6603 }
6604 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6605 CovariantAdjustmentPath.back()))
6606 CovariantAdjustmentPath.push_back(Found->getReturnType());
6607 }
6608
6609 // Perform 'this' adjustment.
6610 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6611 return nullptr;
6612
6613 return Callee;
6614}
6615
6616/// Perform the adjustment from a value returned by a virtual function to
6617/// a value of the statically expected type, which may be a pointer or
6618/// reference to a base class of the returned type.
6619static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6620 APValue &Result,
6621 ArrayRef<QualType> Path) {
6622 assert(Result.isLValue() &&
6623 "unexpected kind of APValue for covariant return");
6624 if (Result.isNullPointer())
6625 return true;
6626
6627 LValue LVal;
6628 LVal.setFrom(Info.Ctx, Result);
6629
6630 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6631 for (unsigned I = 1; I != Path.size(); ++I) {
6632 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6633 assert(OldClass && NewClass && "unexpected kind of covariant return");
6634 if (OldClass != NewClass &&
6635 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6636 return false;
6637 OldClass = NewClass;
6638 }
6639
6640 LVal.moveInto(Result);
6641 return true;
6642}
6643
6644/// Determine whether \p Base, which is known to be a direct base class of
6645/// \p Derived, is a public base class.
6646static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6647 const CXXRecordDecl *Base) {
6648 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6649 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6650 if (BaseClass && declaresSameEntity(BaseClass, Base))
6651 return BaseSpec.getAccessSpecifier() == AS_public;
6652 }
6653 llvm_unreachable("Base is not a direct base of Derived");
6654}
6655
6656/// Apply the given dynamic cast operation on the provided lvalue.
6657///
6658/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6659/// to find a suitable target subobject.
6660static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6661 LValue &Ptr) {
6662 // We can't do anything with a non-symbolic pointer value.
6663 SubobjectDesignator &D = Ptr.Designator;
6664 if (D.Invalid)
6665 return false;
6666
6667 // C++ [expr.dynamic.cast]p6:
6668 // If v is a null pointer value, the result is a null pointer value.
6669 if (Ptr.isNullPointer() && !E->isGLValue())
6670 return true;
6671
6672 // For all the other cases, we need the pointer to point to an object within
6673 // its lifetime / period of construction / destruction, and we need to know
6674 // its dynamic type.
6675 std::optional<DynamicType> DynType =
6676 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6677 if (!DynType)
6678 return false;
6679
6680 // C++ [expr.dynamic.cast]p7:
6681 // If T is "pointer to cv void", then the result is a pointer to the most
6682 // derived object
6683 if (E->getType()->isVoidPointerType())
6684 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6685
6687 assert(C && "dynamic_cast target is not void pointer nor class");
6688 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6689
6690 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6691 // C++ [expr.dynamic.cast]p9:
6692 if (!E->isGLValue()) {
6693 // The value of a failed cast to pointer type is the null pointer value
6694 // of the required result type.
6695 Ptr.setNull(Info.Ctx, E->getType());
6696 return true;
6697 }
6698
6699 // A failed cast to reference type throws [...] std::bad_cast.
6700 unsigned DiagKind;
6701 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6702 DynType->Type->isDerivedFrom(C)))
6703 DiagKind = 0;
6704 else if (!Paths || Paths->begin() == Paths->end())
6705 DiagKind = 1;
6706 else if (Paths->isAmbiguous(CQT))
6707 DiagKind = 2;
6708 else {
6709 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6710 DiagKind = 3;
6711 }
6712 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6713 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6714 << Info.Ctx.getCanonicalTagType(DynType->Type)
6715 << E->getType().getUnqualifiedType();
6716 return false;
6717 };
6718
6719 // Runtime check, phase 1:
6720 // Walk from the base subobject towards the derived object looking for the
6721 // target type.
6722 for (int PathLength = Ptr.Designator.Entries.size();
6723 PathLength >= (int)DynType->PathLength; --PathLength) {
6724 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6725 if (declaresSameEntity(Class, C))
6726 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6727 // We can only walk across public inheritance edges.
6728 if (PathLength > (int)DynType->PathLength &&
6729 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6730 Class))
6731 return RuntimeCheckFailed(nullptr);
6732 }
6733
6734 // Runtime check, phase 2:
6735 // Search the dynamic type for an unambiguous public base of type C.
6736 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6737 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6738 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6739 Paths.front().Access == AS_public) {
6740 // Downcast to the dynamic type...
6741 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6742 return false;
6743 // ... then upcast to the chosen base class subobject.
6744 for (CXXBasePathElement &Elem : Paths.front())
6745 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6746 return false;
6747 return true;
6748 }
6749
6750 // Otherwise, the runtime check fails.
6751 return RuntimeCheckFailed(&Paths);
6752}
6753
6754namespace {
6755struct StartLifetimeOfUnionMemberHandler {
6756 EvalInfo &Info;
6757 const Expr *LHSExpr;
6758 const FieldDecl *Field;
6759 bool DuringInit;
6760 bool Failed = false;
6761 static const AccessKinds AccessKind = AK_Assign;
6762
6763 typedef bool result_type;
6764 bool failed() { return Failed; }
6765 bool found(APValue &Subobj, QualType SubobjType) {
6766 // We are supposed to perform no initialization but begin the lifetime of
6767 // the object. We interpret that as meaning to do what default
6768 // initialization of the object would do if all constructors involved were
6769 // trivial:
6770 // * All base, non-variant member, and array element subobjects' lifetimes
6771 // begin
6772 // * No variant members' lifetimes begin
6773 // * All scalar subobjects whose lifetimes begin have indeterminate values
6774 assert(SubobjType->isUnionType());
6775 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6776 // This union member is already active. If it's also in-lifetime, there's
6777 // nothing to do.
6778 if (Subobj.getUnionValue().hasValue())
6779 return true;
6780 } else if (DuringInit) {
6781 // We're currently in the process of initializing a different union
6782 // member. If we carried on, that initialization would attempt to
6783 // store to an inactive union member, resulting in undefined behavior.
6784 Info.FFDiag(LHSExpr,
6785 diag::note_constexpr_union_member_change_during_init);
6786 return false;
6787 }
6789 Failed = !handleDefaultInitValue(Field->getType(), Result);
6790 Subobj.setUnion(Field, Result);
6791 return true;
6792 }
6793 bool found(APSInt &Value, QualType SubobjType) {
6794 llvm_unreachable("wrong value kind for union object");
6795 }
6796 bool found(APFloat &Value, QualType SubobjType) {
6797 llvm_unreachable("wrong value kind for union object");
6798 }
6799};
6800} // end anonymous namespace
6801
6802const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6803
6804/// Handle a builtin simple-assignment or a call to a trivial assignment
6805/// operator whose left-hand side might involve a union member access. If it
6806/// does, implicitly start the lifetime of any accessed union elements per
6807/// C++20 [class.union]5.
6808static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6809 const Expr *LHSExpr,
6810 const LValue &LHS) {
6811 if (LHS.InvalidBase || LHS.Designator.Invalid)
6812 return false;
6813
6815 // C++ [class.union]p5:
6816 // define the set S(E) of subexpressions of E as follows:
6817 unsigned PathLength = LHS.Designator.Entries.size();
6818 for (const Expr *E = LHSExpr; E != nullptr;) {
6819 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6820 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6821 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6822 // Note that we can't implicitly start the lifetime of a reference,
6823 // so we don't need to proceed any further if we reach one.
6824 if (!FD || FD->getType()->isReferenceType())
6825 break;
6826
6827 // ... and also contains A.B if B names a union member ...
6828 if (FD->getParent()->isUnion()) {
6829 // ... of a non-class, non-array type, or of a class type with a
6830 // trivial default constructor that is not deleted, or an array of
6831 // such types.
6832 auto *RD =
6833 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6834 if (!RD || RD->hasTrivialDefaultConstructor())
6835 UnionPathLengths.push_back({PathLength - 1, FD});
6836 }
6837
6838 E = ME->getBase();
6839 --PathLength;
6840 assert(declaresSameEntity(FD,
6841 LHS.Designator.Entries[PathLength]
6842 .getAsBaseOrMember().getPointer()));
6843
6844 // -- If E is of the form A[B] and is interpreted as a built-in array
6845 // subscripting operator, S(E) is [S(the array operand, if any)].
6846 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6847 // Step over an ArrayToPointerDecay implicit cast.
6848 auto *Base = ASE->getBase()->IgnoreImplicit();
6849 if (!Base->getType()->isArrayType())
6850 break;
6851
6852 E = Base;
6853 --PathLength;
6854
6855 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6856 // Step over a derived-to-base conversion.
6857 E = ICE->getSubExpr();
6858 if (ICE->getCastKind() == CK_NoOp)
6859 continue;
6860 if (ICE->getCastKind() != CK_DerivedToBase &&
6861 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6862 break;
6863 // Walk path backwards as we walk up from the base to the derived class.
6864 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6865 if (Elt->isVirtual()) {
6866 // A class with virtual base classes never has a trivial default
6867 // constructor, so S(E) is empty in this case.
6868 E = nullptr;
6869 break;
6870 }
6871
6872 --PathLength;
6873 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6874 LHS.Designator.Entries[PathLength]
6875 .getAsBaseOrMember().getPointer()));
6876 }
6877
6878 // -- Otherwise, S(E) is empty.
6879 } else {
6880 break;
6881 }
6882 }
6883
6884 // Common case: no unions' lifetimes are started.
6885 if (UnionPathLengths.empty())
6886 return true;
6887
6888 // if modification of X [would access an inactive union member], an object
6889 // of the type of X is implicitly created
6890 CompleteObject Obj =
6891 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6892 if (!Obj)
6893 return false;
6894 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6895 llvm::reverse(UnionPathLengths)) {
6896 // Form a designator for the union object.
6897 SubobjectDesignator D = LHS.Designator;
6898 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6899
6900 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6901 ConstructionPhase::AfterBases;
6902 StartLifetimeOfUnionMemberHandler StartLifetime{
6903 Info, LHSExpr, LengthAndField.second, DuringInit};
6904 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6905 return false;
6906 }
6907
6908 return true;
6909}
6910
6911static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6912 CallRef Call, EvalInfo &Info, bool NonNull = false,
6913 APValue **EvaluatedArg = nullptr) {
6914 LValue LV;
6915 // Create the parameter slot and register its destruction. For a vararg
6916 // argument, create a temporary.
6917 // FIXME: For calling conventions that destroy parameters in the callee,
6918 // should we consider performing destruction when the function returns
6919 // instead?
6920 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6921 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6922 ScopeKind::Call, LV);
6923 if (!EvaluateInPlace(V, Info, LV, Arg))
6924 return false;
6925
6926 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6927 // undefined behavior, so is non-constant.
6928 if (NonNull && V.isLValue() && V.isNullPointer()) {
6929 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6930 return false;
6931 }
6932
6933 if (EvaluatedArg)
6934 *EvaluatedArg = &V;
6935
6936 return true;
6937}
6938
6939/// Evaluate the arguments to a function call.
6940static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6941 EvalInfo &Info, const FunctionDecl *Callee,
6942 bool RightToLeft = false,
6943 LValue *ObjectArg = nullptr) {
6944 bool Success = true;
6945 llvm::SmallBitVector ForbiddenNullArgs;
6946 if (Callee->hasAttr<NonNullAttr>()) {
6947 ForbiddenNullArgs.resize(Args.size());
6948 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6949 if (!Attr->args_size()) {
6950 ForbiddenNullArgs.set();
6951 break;
6952 } else
6953 for (auto Idx : Attr->args()) {
6954 unsigned ASTIdx = Idx.getASTIndex();
6955 if (ASTIdx >= Args.size())
6956 continue;
6957 ForbiddenNullArgs[ASTIdx] = true;
6958 }
6959 }
6960 }
6961 for (unsigned I = 0; I < Args.size(); I++) {
6962 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6963 const ParmVarDecl *PVD =
6964 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6965 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6966 APValue *That = nullptr;
6967 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6968 // If we're checking for a potential constant expression, evaluate all
6969 // initializers even if some of them fail.
6970 if (!Info.noteFailure())
6971 return false;
6972 Success = false;
6973 }
6974 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6975 ObjectArg->setFrom(Info.Ctx, *That);
6976 }
6977 return Success;
6978}
6979
6980/// Perform a trivial copy from Param, which is the parameter of a copy or move
6981/// constructor or assignment operator.
6982static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6983 const Expr *E, APValue &Result,
6984 bool CopyObjectRepresentation) {
6985 // Find the reference argument.
6986 CallStackFrame *Frame = Info.CurrentCall;
6987 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6988 if (!RefValue) {
6989 Info.FFDiag(E);
6990 return false;
6991 }
6992
6993 // Copy out the contents of the RHS object.
6994 LValue RefLValue;
6995 RefLValue.setFrom(Info.Ctx, *RefValue);
6997 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6998 CopyObjectRepresentation);
6999}
7000
7001/// Evaluate a function call.
7003 const FunctionDecl *Callee,
7004 const LValue *ObjectArg, const Expr *E,
7005 ArrayRef<const Expr *> Args, CallRef Call,
7006 const Stmt *Body, EvalInfo &Info,
7007 APValue &Result, const LValue *ResultSlot) {
7008 if (!Info.CheckCallLimit(CallLoc))
7009 return false;
7010
7011 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7012
7013 // For a trivial copy or move assignment, perform an APValue copy. This is
7014 // essential for unions, where the operations performed by the assignment
7015 // operator cannot be represented as statements.
7016 //
7017 // Skip this for non-union classes with no fields; in that case, the defaulted
7018 // copy/move does not actually read the object.
7019 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7020 if (MD && MD->isDefaulted() &&
7021 (MD->getParent()->isUnion() ||
7022 (MD->isTrivial() &&
7024 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7025 assert(ObjectArg &&
7027 APValue RHSValue;
7028 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7029 MD->getParent()->isUnion()))
7030 return false;
7031
7032 LValue Obj;
7033 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7035 RHSValue))
7036 return false;
7037 ObjectArg->moveInto(Result);
7038 return true;
7039 } else if (MD && isLambdaCallOperator(MD)) {
7040 // We're in a lambda; determine the lambda capture field maps unless we're
7041 // just constexpr checking a lambda's call operator. constexpr checking is
7042 // done before the captures have been added to the closure object (unless
7043 // we're inferring constexpr-ness), so we don't have access to them in this
7044 // case. But since we don't need the captures to constexpr check, we can
7045 // just ignore them.
7046 if (!Info.checkingPotentialConstantExpression())
7047 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7048 Frame.LambdaThisCaptureField);
7049 }
7050
7051 StmtResult Ret = {Result, ResultSlot};
7052 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7053 if (ESR == ESR_Succeeded) {
7054 if (Callee->getReturnType()->isVoidType())
7055 return true;
7056 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7057 }
7058 return ESR == ESR_Returned;
7059}
7060
7061/// Evaluate a constructor call.
7062static bool HandleConstructorCall(const Expr *E, const LValue &This,
7063 CallRef Call,
7065 EvalInfo &Info, APValue &Result) {
7066 SourceLocation CallLoc = E->getExprLoc();
7067 if (!Info.CheckCallLimit(CallLoc))
7068 return false;
7069
7070 const CXXRecordDecl *RD = Definition->getParent();
7071 if (RD->getNumVBases()) {
7072 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7073 return false;
7074 }
7075
7076 EvalInfo::EvaluatingConstructorRAII EvalObj(
7077 Info,
7078 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7079 RD->getNumBases());
7080 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7081
7082 // FIXME: Creating an APValue just to hold a nonexistent return value is
7083 // wasteful.
7084 APValue RetVal;
7085 StmtResult Ret = {RetVal, nullptr};
7086
7087 // If it's a delegating constructor, delegate.
7088 if (Definition->isDelegatingConstructor()) {
7090 if ((*I)->getInit()->isValueDependent()) {
7091 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7092 return false;
7093 } else {
7094 FullExpressionRAII InitScope(Info);
7095 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7096 !InitScope.destroy())
7097 return false;
7098 }
7099 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7100 }
7101
7102 // For a trivial copy or move constructor, perform an APValue copy. This is
7103 // essential for unions (or classes with anonymous union members), where the
7104 // operations performed by the constructor cannot be represented by
7105 // ctor-initializers.
7106 //
7107 // Skip this for empty non-union classes; we should not perform an
7108 // lvalue-to-rvalue conversion on them because their copy constructor does not
7109 // actually read them.
7110 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7111 (Definition->getParent()->isUnion() ||
7112 (Definition->isTrivial() &&
7114 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7115 Definition->getParent()->isUnion());
7116 }
7117
7118 // Reserve space for the struct members.
7119 if (!Result.hasValue()) {
7120 if (!RD->isUnion())
7121 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7122 RD->getNumFields());
7123 else
7124 // A union starts with no active member.
7125 Result = APValue((const FieldDecl*)nullptr);
7126 }
7127
7128 if (RD->isInvalidDecl()) return false;
7129 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7130
7131 // A scope for temporaries lifetime-extended by reference members.
7132 BlockScopeRAII LifetimeExtendedScope(Info);
7133
7134 bool Success = true;
7135 unsigned BasesSeen = 0;
7136#ifndef NDEBUG
7138#endif
7140 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7141 // We might be initializing the same field again if this is an indirect
7142 // field initialization.
7143 if (FieldIt == RD->field_end() ||
7144 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7145 assert(Indirect && "fields out of order?");
7146 return;
7147 }
7148
7149 // Default-initialize any fields with no explicit initializer.
7150 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7151 assert(FieldIt != RD->field_end() && "missing field?");
7152 if (!FieldIt->isUnnamedBitField())
7154 FieldIt->getType(),
7155 Result.getStructField(FieldIt->getFieldIndex()));
7156 }
7157 ++FieldIt;
7158 };
7159 for (const auto *I : Definition->inits()) {
7160 LValue Subobject = This;
7161 LValue SubobjectParent = This;
7162 APValue *Value = &Result;
7163
7164 // Determine the subobject to initialize.
7165 FieldDecl *FD = nullptr;
7166 if (I->isBaseInitializer()) {
7167 QualType BaseType(I->getBaseClass(), 0);
7168#ifndef NDEBUG
7169 // Non-virtual base classes are initialized in the order in the class
7170 // definition. We have already checked for virtual base classes.
7171 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7172 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7173 "base class initializers not in expected order");
7174 ++BaseIt;
7175#endif
7176 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7177 BaseType->getAsCXXRecordDecl(), &Layout))
7178 return false;
7179 Value = &Result.getStructBase(BasesSeen++);
7180 } else if ((FD = I->getMember())) {
7181 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7182 return false;
7183 if (RD->isUnion()) {
7184 Result = APValue(FD);
7185 Value = &Result.getUnionValue();
7186 } else {
7187 SkipToField(FD, false);
7188 Value = &Result.getStructField(FD->getFieldIndex());
7189 }
7190 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7191 // Walk the indirect field decl's chain to find the object to initialize,
7192 // and make sure we've initialized every step along it.
7193 auto IndirectFieldChain = IFD->chain();
7194 for (auto *C : IndirectFieldChain) {
7195 FD = cast<FieldDecl>(C);
7197 // Switch the union field if it differs. This happens if we had
7198 // preceding zero-initialization, and we're now initializing a union
7199 // subobject other than the first.
7200 // FIXME: In this case, the values of the other subobjects are
7201 // specified, since zero-initialization sets all padding bits to zero.
7202 if (!Value->hasValue() ||
7203 (Value->isUnion() &&
7204 !declaresSameEntity(Value->getUnionField(), FD))) {
7205 if (CD->isUnion())
7206 *Value = APValue(FD);
7207 else
7208 // FIXME: This immediately starts the lifetime of all members of
7209 // an anonymous struct. It would be preferable to strictly start
7210 // member lifetime in initialization order.
7211 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7212 *Value);
7213 }
7214 // Store Subobject as its parent before updating it for the last element
7215 // in the chain.
7216 if (C == IndirectFieldChain.back())
7217 SubobjectParent = Subobject;
7218 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7219 return false;
7220 if (CD->isUnion())
7221 Value = &Value->getUnionValue();
7222 else {
7223 if (C == IndirectFieldChain.front() && !RD->isUnion())
7224 SkipToField(FD, true);
7225 Value = &Value->getStructField(FD->getFieldIndex());
7226 }
7227 }
7228 } else {
7229 llvm_unreachable("unknown base initializer kind");
7230 }
7231
7232 // Need to override This for implicit field initializers as in this case
7233 // This refers to innermost anonymous struct/union containing initializer,
7234 // not to currently constructed class.
7235 const Expr *Init = I->getInit();
7236 if (Init->isValueDependent()) {
7237 if (!EvaluateDependentExpr(Init, Info))
7238 return false;
7239 } else {
7240 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7242 FullExpressionRAII InitScope(Info);
7243 if (FD && FD->getType()->isReferenceType() &&
7244 !FD->getType()->isFunctionReferenceType()) {
7245 LValue Result;
7246 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7247 *Value)) {
7248 if (!Info.noteFailure())
7249 return false;
7250 Success = false;
7251 }
7252 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7253 (FD && FD->isBitField() &&
7254 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7255 // If we're checking for a potential constant expression, evaluate all
7256 // initializers even if some of them fail.
7257 if (!Info.noteFailure())
7258 return false;
7259 Success = false;
7260 }
7261 }
7262
7263 // This is the point at which the dynamic type of the object becomes this
7264 // class type.
7265 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7266 EvalObj.finishedConstructingBases();
7267 }
7268
7269 // Default-initialize any remaining fields.
7270 if (!RD->isUnion()) {
7271 for (; FieldIt != RD->field_end(); ++FieldIt) {
7272 if (!FieldIt->isUnnamedBitField())
7274 FieldIt->getType(),
7275 Result.getStructField(FieldIt->getFieldIndex()));
7276 }
7277 }
7278
7279 EvalObj.finishedConstructingFields();
7280
7281 return Success &&
7282 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7283 LifetimeExtendedScope.destroy();
7284}
7285
7286static bool HandleConstructorCall(const Expr *E, const LValue &This,
7289 EvalInfo &Info, APValue &Result) {
7290 CallScopeRAII CallScope(Info);
7291 CallRef Call = Info.CurrentCall->createCall(Definition);
7292 if (!EvaluateArgs(Args, Call, Info, Definition))
7293 return false;
7294
7295 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7296 CallScope.destroy();
7297}
7298
7299static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7300 const LValue &This, APValue &Value,
7301 QualType T) {
7302 // Objects can only be destroyed while they're within their lifetimes.
7303 // FIXME: We have no representation for whether an object of type nullptr_t
7304 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7305 // as indeterminate instead?
7306 if (Value.isAbsent() && !T->isNullPtrType()) {
7307 APValue Printable;
7308 This.moveInto(Printable);
7309 Info.FFDiag(CallRange.getBegin(),
7310 diag::note_constexpr_destroy_out_of_lifetime)
7311 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7312 return false;
7313 }
7314
7315 // Invent an expression for location purposes.
7316 // FIXME: We shouldn't need to do this.
7317 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7318
7319 // For arrays, destroy elements right-to-left.
7320 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7321 uint64_t Size = CAT->getZExtSize();
7322 QualType ElemT = CAT->getElementType();
7323
7324 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7325 return false;
7326
7327 LValue ElemLV = This;
7328 ElemLV.addArray(Info, &LocE, CAT);
7329 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7330 return false;
7331
7332 // Ensure that we have actual array elements available to destroy; the
7333 // destructors might mutate the value, so we can't run them on the array
7334 // filler.
7335 if (Size && Size > Value.getArrayInitializedElts())
7336 expandArray(Value, Value.getArraySize() - 1);
7337
7338 // The size of the array might have been reduced by
7339 // a placement new.
7340 for (Size = Value.getArraySize(); Size != 0; --Size) {
7341 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7342 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7343 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7344 return false;
7345 }
7346
7347 // End the lifetime of this array now.
7348 Value = APValue();
7349 return true;
7350 }
7351
7352 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7353 if (!RD) {
7354 if (T.isDestructedType()) {
7355 Info.FFDiag(CallRange.getBegin(),
7356 diag::note_constexpr_unsupported_destruction)
7357 << T;
7358 return false;
7359 }
7360
7361 Value = APValue();
7362 return true;
7363 }
7364
7365 if (RD->getNumVBases()) {
7366 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7367 return false;
7368 }
7369
7370 const CXXDestructorDecl *DD = RD->getDestructor();
7371 if (!DD && !RD->hasTrivialDestructor()) {
7372 Info.FFDiag(CallRange.getBegin());
7373 return false;
7374 }
7375
7376 if (!DD || DD->isTrivial() ||
7377 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7378 // A trivial destructor just ends the lifetime of the object. Check for
7379 // this case before checking for a body, because we might not bother
7380 // building a body for a trivial destructor. Note that it doesn't matter
7381 // whether the destructor is constexpr in this case; all trivial
7382 // destructors are constexpr.
7383 //
7384 // If an anonymous union would be destroyed, some enclosing destructor must
7385 // have been explicitly defined, and the anonymous union destruction should
7386 // have no effect.
7387 Value = APValue();
7388 return true;
7389 }
7390
7391 if (!Info.CheckCallLimit(CallRange.getBegin()))
7392 return false;
7393
7394 const FunctionDecl *Definition = nullptr;
7395 const Stmt *Body = DD->getBody(Definition);
7396
7397 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7398 return false;
7399
7400 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7401 CallRef());
7402
7403 // We're now in the period of destruction of this object.
7404 unsigned BasesLeft = RD->getNumBases();
7405 EvalInfo::EvaluatingDestructorRAII EvalObj(
7406 Info,
7407 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7408 if (!EvalObj.DidInsert) {
7409 // C++2a [class.dtor]p19:
7410 // the behavior is undefined if the destructor is invoked for an object
7411 // whose lifetime has ended
7412 // (Note that formally the lifetime ends when the period of destruction
7413 // begins, even though certain uses of the object remain valid until the
7414 // period of destruction ends.)
7415 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7416 return false;
7417 }
7418
7419 // FIXME: Creating an APValue just to hold a nonexistent return value is
7420 // wasteful.
7421 APValue RetVal;
7422 StmtResult Ret = {RetVal, nullptr};
7423 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7424 return false;
7425
7426 // A union destructor does not implicitly destroy its members.
7427 if (RD->isUnion())
7428 return true;
7429
7430 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7431
7432 // We don't have a good way to iterate fields in reverse, so collect all the
7433 // fields first and then walk them backwards.
7434 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7435 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7436 if (FD->isUnnamedBitField())
7437 continue;
7438
7439 LValue Subobject = This;
7440 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7441 return false;
7442
7443 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7444 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7445 FD->getType()))
7446 return false;
7447 }
7448
7449 if (BasesLeft != 0)
7450 EvalObj.startedDestroyingBases();
7451
7452 // Destroy base classes in reverse order.
7453 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7454 --BasesLeft;
7455
7456 QualType BaseType = Base.getType();
7457 LValue Subobject = This;
7458 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7459 BaseType->getAsCXXRecordDecl(), &Layout))
7460 return false;
7461
7462 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7463 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7464 BaseType))
7465 return false;
7466 }
7467 assert(BasesLeft == 0 && "NumBases was wrong?");
7468
7469 // The period of destruction ends now. The object is gone.
7470 Value = APValue();
7471 return true;
7472}
7473
7474namespace {
7475struct DestroyObjectHandler {
7476 EvalInfo &Info;
7477 const Expr *E;
7478 const LValue &This;
7479 const AccessKinds AccessKind;
7480
7481 typedef bool result_type;
7482 bool failed() { return false; }
7483 bool found(APValue &Subobj, QualType SubobjType) {
7484 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7485 SubobjType);
7486 }
7487 bool found(APSInt &Value, QualType SubobjType) {
7488 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7489 return false;
7490 }
7491 bool found(APFloat &Value, QualType SubobjType) {
7492 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7493 return false;
7494 }
7495};
7496}
7497
7498/// Perform a destructor or pseudo-destructor call on the given object, which
7499/// might in general not be a complete object.
7500static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7501 const LValue &This, QualType ThisType) {
7502 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7503 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7504 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7505}
7506
7507/// Destroy and end the lifetime of the given complete object.
7508static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7510 QualType T) {
7511 // If we've had an unmodeled side-effect, we can't rely on mutable state
7512 // (such as the object we're about to destroy) being correct.
7513 if (Info.EvalStatus.HasSideEffects)
7514 return false;
7515
7516 LValue LV;
7517 LV.set({LVBase});
7518 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7519}
7520
7521/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7522static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7523 LValue &Result) {
7524 if (Info.checkingPotentialConstantExpression() ||
7525 Info.SpeculativeEvaluationDepth)
7526 return false;
7527
7528 // This is permitted only within a call to std::allocator<T>::allocate.
7529 auto Caller = Info.getStdAllocatorCaller("allocate");
7530 if (!Caller) {
7531 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7532 ? diag::note_constexpr_new_untyped
7533 : diag::note_constexpr_new);
7534 return false;
7535 }
7536
7537 QualType ElemType = Caller.ElemType;
7538 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7539 Info.FFDiag(E->getExprLoc(),
7540 diag::note_constexpr_new_not_complete_object_type)
7541 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7542 return false;
7543 }
7544
7545 APSInt ByteSize;
7546 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7547 return false;
7548 bool IsNothrow = false;
7549 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7550 EvaluateIgnoredValue(Info, E->getArg(I));
7551 IsNothrow |= E->getType()->isNothrowT();
7552 }
7553
7554 CharUnits ElemSize;
7555 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7556 return false;
7557 APInt Size, Remainder;
7558 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7559 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7560 if (Remainder != 0) {
7561 // This likely indicates a bug in the implementation of 'std::allocator'.
7562 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7563 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7564 return false;
7565 }
7566
7567 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7568 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7569 if (IsNothrow) {
7570 Result.setNull(Info.Ctx, E->getType());
7571 return true;
7572 }
7573 return false;
7574 }
7575
7576 QualType AllocType = Info.Ctx.getConstantArrayType(
7577 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7578 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7579 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7580 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7581 return true;
7582}
7583
7585 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7586 if (CXXDestructorDecl *DD = RD->getDestructor())
7587 return DD->isVirtual();
7588 return false;
7589}
7590
7592 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7593 if (CXXDestructorDecl *DD = RD->getDestructor())
7594 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7595 return nullptr;
7596}
7597
7598/// Check that the given object is a suitable pointer to a heap allocation that
7599/// still exists and is of the right kind for the purpose of a deletion.
7600///
7601/// On success, returns the heap allocation to deallocate. On failure, produces
7602/// a diagnostic and returns std::nullopt.
7603static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7604 const LValue &Pointer,
7605 DynAlloc::Kind DeallocKind) {
7606 auto PointerAsString = [&] {
7607 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7608 };
7609
7610 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7611 if (!DA) {
7612 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7613 << PointerAsString();
7614 if (Pointer.Base)
7615 NoteLValueLocation(Info, Pointer.Base);
7616 return std::nullopt;
7617 }
7618
7619 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7620 if (!Alloc) {
7621 Info.FFDiag(E, diag::note_constexpr_double_delete);
7622 return std::nullopt;
7623 }
7624
7625 if (DeallocKind != (*Alloc)->getKind()) {
7626 QualType AllocType = Pointer.Base.getDynamicAllocType();
7627 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7628 << DeallocKind << (*Alloc)->getKind() << AllocType;
7629 NoteLValueLocation(Info, Pointer.Base);
7630 return std::nullopt;
7631 }
7632
7633 bool Subobject = false;
7634 if (DeallocKind == DynAlloc::New) {
7635 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7636 Pointer.Designator.isOnePastTheEnd();
7637 } else {
7638 Subobject = Pointer.Designator.Entries.size() != 1 ||
7639 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7640 }
7641 if (Subobject) {
7642 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7643 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7644 return std::nullopt;
7645 }
7646
7647 return Alloc;
7648}
7649
7650// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7651static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7652 if (Info.checkingPotentialConstantExpression() ||
7653 Info.SpeculativeEvaluationDepth)
7654 return false;
7655
7656 // This is permitted only within a call to std::allocator<T>::deallocate.
7657 if (!Info.getStdAllocatorCaller("deallocate")) {
7658 Info.FFDiag(E->getExprLoc());
7659 return true;
7660 }
7661
7662 LValue Pointer;
7663 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7664 return false;
7665 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7666 EvaluateIgnoredValue(Info, E->getArg(I));
7667
7668 if (Pointer.Designator.Invalid)
7669 return false;
7670
7671 // Deleting a null pointer would have no effect, but it's not permitted by
7672 // std::allocator<T>::deallocate's contract.
7673 if (Pointer.isNullPointer()) {
7674 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7675 return true;
7676 }
7677
7678 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7679 return false;
7680
7681 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7682 return true;
7683}
7684
7685//===----------------------------------------------------------------------===//
7686// Generic Evaluation
7687//===----------------------------------------------------------------------===//
7688namespace {
7689
7690class BitCastBuffer {
7691 // FIXME: We're going to need bit-level granularity when we support
7692 // bit-fields.
7693 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7694 // we don't support a host or target where that is the case. Still, we should
7695 // use a more generic type in case we ever do.
7696 SmallVector<std::optional<unsigned char>, 32> Bytes;
7697
7698 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7699 "Need at least 8 bit unsigned char");
7700
7701 bool TargetIsLittleEndian;
7702
7703public:
7704 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7705 : Bytes(Width.getQuantity()),
7706 TargetIsLittleEndian(TargetIsLittleEndian) {}
7707
7708 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7709 SmallVectorImpl<unsigned char> &Output) const {
7710 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7711 // If a byte of an integer is uninitialized, then the whole integer is
7712 // uninitialized.
7713 if (!Bytes[I.getQuantity()])
7714 return false;
7715 Output.push_back(*Bytes[I.getQuantity()]);
7716 }
7717 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7718 std::reverse(Output.begin(), Output.end());
7719 return true;
7720 }
7721
7722 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7723 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7724 std::reverse(Input.begin(), Input.end());
7725
7726 size_t Index = 0;
7727 for (unsigned char Byte : Input) {
7728 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7729 Bytes[Offset.getQuantity() + Index] = Byte;
7730 ++Index;
7731 }
7732 }
7733
7734 size_t size() { return Bytes.size(); }
7735};
7736
7737/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7738/// target would represent the value at runtime.
7739class APValueToBufferConverter {
7740 EvalInfo &Info;
7741 BitCastBuffer Buffer;
7742 const CastExpr *BCE;
7743
7744 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7745 const CastExpr *BCE)
7746 : Info(Info),
7747 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7748 BCE(BCE) {}
7749
7750 bool visit(const APValue &Val, QualType Ty) {
7751 return visit(Val, Ty, CharUnits::fromQuantity(0));
7752 }
7753
7754 // Write out Val with type Ty into Buffer starting at Offset.
7755 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7756 assert((size_t)Offset.getQuantity() <= Buffer.size());
7757
7758 // As a special case, nullptr_t has an indeterminate value.
7759 if (Ty->isNullPtrType())
7760 return true;
7761
7762 // Dig through Src to find the byte at SrcOffset.
7763 switch (Val.getKind()) {
7765 case APValue::None:
7766 return true;
7767
7768 case APValue::Int:
7769 return visitInt(Val.getInt(), Ty, Offset);
7770 case APValue::Float:
7771 return visitFloat(Val.getFloat(), Ty, Offset);
7772 case APValue::Array:
7773 return visitArray(Val, Ty, Offset);
7774 case APValue::Struct:
7775 return visitRecord(Val, Ty, Offset);
7776 case APValue::Vector:
7777 return visitVector(Val, Ty, Offset);
7778
7781 return visitComplex(Val, Ty, Offset);
7783 // FIXME: We should support these.
7784
7785 case APValue::LValue:
7786 case APValue::Matrix:
7787 case APValue::Union:
7790 Info.FFDiag(BCE->getBeginLoc(),
7791 diag::note_constexpr_bit_cast_unsupported_type)
7792 << Ty;
7793 return false;
7794 }
7795 }
7796 llvm_unreachable("Unhandled APValue::ValueKind");
7797 }
7798
7799 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7800 const RecordDecl *RD = Ty->getAsRecordDecl();
7801 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7802
7803 // Visit the base classes.
7804 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7805 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7806 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7807 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7808 const APValue &Base = Val.getStructBase(I);
7809
7810 // Can happen in error cases.
7811 if (!Base.isStruct())
7812 return false;
7813
7814 if (!visitRecord(Base, BS.getType(),
7815 Layout.getBaseClassOffset(BaseDecl) + Offset))
7816 return false;
7817 }
7818 }
7819
7820 // Visit the fields.
7821 unsigned FieldIdx = 0;
7822 for (FieldDecl *FD : RD->fields()) {
7823 if (FD->isBitField()) {
7824 Info.FFDiag(BCE->getBeginLoc(),
7825 diag::note_constexpr_bit_cast_unsupported_bitfield);
7826 return false;
7827 }
7828
7829 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7830
7831 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7832 "only bit-fields can have sub-char alignment");
7833 CharUnits FieldOffset =
7834 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7835 QualType FieldTy = FD->getType();
7836 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7837 return false;
7838 ++FieldIdx;
7839 }
7840
7841 return true;
7842 }
7843
7844 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7845 const auto *CAT =
7846 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7847 if (!CAT)
7848 return false;
7849
7850 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7851 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7852 unsigned ArraySize = Val.getArraySize();
7853 // First, initialize the initialized elements.
7854 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7855 const APValue &SubObj = Val.getArrayInitializedElt(I);
7856 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7857 return false;
7858 }
7859
7860 // Next, initialize the rest of the array using the filler.
7861 if (Val.hasArrayFiller()) {
7862 const APValue &Filler = Val.getArrayFiller();
7863 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7864 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7865 return false;
7866 }
7867 }
7868
7869 return true;
7870 }
7871
7872 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7873 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7874 QualType EltTy = ComplexTy->getElementType();
7875 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7876 bool IsInt = Val.isComplexInt();
7877
7878 if (IsInt) {
7879 if (!visitInt(Val.getComplexIntReal(), EltTy,
7880 Offset + (0 * EltSizeChars)))
7881 return false;
7882 if (!visitInt(Val.getComplexIntImag(), EltTy,
7883 Offset + (1 * EltSizeChars)))
7884 return false;
7885 } else {
7886 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7887 Offset + (0 * EltSizeChars)))
7888 return false;
7889 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7890 Offset + (1 * EltSizeChars)))
7891 return false;
7892 }
7893
7894 return true;
7895 }
7896
7897 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7898 const VectorType *VTy = Ty->castAs<VectorType>();
7899 QualType EltTy = VTy->getElementType();
7900 unsigned NElts = VTy->getNumElements();
7901
7902 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7903 // Special handling for OpenCL bool vectors:
7904 // Since these vectors are stored as packed bits, but we can't write
7905 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7906 // together into an appropriately sized APInt and write them all out at
7907 // once. Because we don't accept vectors where NElts * EltSize isn't a
7908 // multiple of the char size, there will be no padding space, so we don't
7909 // have to worry about writing data which should have been left
7910 // uninitialized.
7911 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7912
7913 llvm::APInt Res = llvm::APInt::getZero(NElts);
7914 for (unsigned I = 0; I < NElts; ++I) {
7915 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7916 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7917 "bool vector element must be 1-bit unsigned integer!");
7918
7919 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7920 }
7921
7922 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7923 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7924 Buffer.writeObject(Offset, Bytes);
7925 } else {
7926 // Iterate over each of the elements and write them out to the buffer at
7927 // the appropriate offset.
7928 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7929 for (unsigned I = 0; I < NElts; ++I) {
7930 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7931 return false;
7932 }
7933 }
7934
7935 return true;
7936 }
7937
7938 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7939 APSInt AdjustedVal = Val;
7940 unsigned Width = AdjustedVal.getBitWidth();
7941 if (Ty->isBooleanType()) {
7942 Width = Info.Ctx.getTypeSize(Ty);
7943 AdjustedVal = AdjustedVal.extend(Width);
7944 }
7945
7946 SmallVector<uint8_t, 8> Bytes(Width / 8);
7947 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7948 Buffer.writeObject(Offset, Bytes);
7949 return true;
7950 }
7951
7952 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7953 APSInt AsInt(Val.bitcastToAPInt());
7954 return visitInt(AsInt, Ty, Offset);
7955 }
7956
7957public:
7958 static std::optional<BitCastBuffer>
7959 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7960 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7961 APValueToBufferConverter Converter(Info, DstSize, BCE);
7962 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7963 return std::nullopt;
7964 return Converter.Buffer;
7965 }
7966};
7967
7968/// Write an BitCastBuffer into an APValue.
7969class BufferToAPValueConverter {
7970 EvalInfo &Info;
7971 const BitCastBuffer &Buffer;
7972 const CastExpr *BCE;
7973
7974 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7975 const CastExpr *BCE)
7976 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7977
7978 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7979 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7980 // Ideally this will be unreachable.
7981 std::nullopt_t unsupportedType(QualType Ty) {
7982 Info.FFDiag(BCE->getBeginLoc(),
7983 diag::note_constexpr_bit_cast_unsupported_type)
7984 << Ty;
7985 return std::nullopt;
7986 }
7987
7988 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7989 Info.FFDiag(BCE->getBeginLoc(),
7990 diag::note_constexpr_bit_cast_unrepresentable_value)
7991 << Ty << toString(Val, /*Radix=*/10);
7992 return std::nullopt;
7993 }
7994
7995 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7996 const EnumType *EnumSugar = nullptr) {
7997 if (T->isNullPtrType()) {
7998 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7999 return APValue((Expr *)nullptr,
8000 /*Offset=*/CharUnits::fromQuantity(NullValue),
8001 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8002 }
8003
8004 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8005
8006 // Work around floating point types that contain unused padding bytes. This
8007 // is really just `long double` on x86, which is the only fundamental type
8008 // with padding bytes.
8009 if (T->isRealFloatingType()) {
8010 const llvm::fltSemantics &Semantics =
8011 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8012 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8013 assert(NumBits % 8 == 0);
8014 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8015 if (NumBytes != SizeOf)
8016 SizeOf = NumBytes;
8017 }
8018
8019 SmallVector<uint8_t, 8> Bytes;
8020 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8021 // If this is std::byte or unsigned char, then its okay to store an
8022 // indeterminate value.
8023 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8024 bool IsUChar =
8025 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8026 T->isSpecificBuiltinType(BuiltinType::Char_U));
8027 if (!IsStdByte && !IsUChar) {
8028 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8029 Info.FFDiag(BCE->getExprLoc(),
8030 diag::note_constexpr_bit_cast_indet_dest)
8031 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8032 return std::nullopt;
8033 }
8034
8036 }
8037
8038 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8039 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8040
8041 if (T->isIntegralOrEnumerationType()) {
8042 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8043
8044 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8045 if (IntWidth != Val.getBitWidth()) {
8046 APSInt Truncated = Val.trunc(IntWidth);
8047 if (Truncated.extend(Val.getBitWidth()) != Val)
8048 return unrepresentableValue(QualType(T, 0), Val);
8049 Val = Truncated;
8050 }
8051
8052 return APValue(Val);
8053 }
8054
8055 if (T->isRealFloatingType()) {
8056 const llvm::fltSemantics &Semantics =
8057 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8058 return APValue(APFloat(Semantics, Val));
8059 }
8060
8061 return unsupportedType(QualType(T, 0));
8062 }
8063
8064 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8065 const RecordDecl *RD = RTy->getAsRecordDecl();
8066 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8067
8068 unsigned NumBases = 0;
8069 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8070 NumBases = CXXRD->getNumBases();
8071
8072 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8073
8074 // Visit the base classes.
8075 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8076 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8077 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8078 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8079
8080 std::optional<APValue> SubObj = visitType(
8081 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8082 if (!SubObj)
8083 return std::nullopt;
8084 ResultVal.getStructBase(I) = *SubObj;
8085 }
8086 }
8087
8088 // Visit the fields.
8089 unsigned FieldIdx = 0;
8090 for (FieldDecl *FD : RD->fields()) {
8091 // FIXME: We don't currently support bit-fields. A lot of the logic for
8092 // this is in CodeGen, so we need to factor it around.
8093 if (FD->isBitField()) {
8094 Info.FFDiag(BCE->getBeginLoc(),
8095 diag::note_constexpr_bit_cast_unsupported_bitfield);
8096 return std::nullopt;
8097 }
8098
8099 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8100 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8101
8102 CharUnits FieldOffset =
8103 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8104 Offset;
8105 QualType FieldTy = FD->getType();
8106 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8107 if (!SubObj)
8108 return std::nullopt;
8109 ResultVal.getStructField(FieldIdx) = *SubObj;
8110 ++FieldIdx;
8111 }
8112
8113 return ResultVal;
8114 }
8115
8116 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8117 QualType RepresentationType =
8118 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8119 assert(!RepresentationType.isNull() &&
8120 "enum forward decl should be caught by Sema");
8121 const auto *AsBuiltin =
8122 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8123 // Recurse into the underlying type. Treat std::byte transparently as
8124 // unsigned char.
8125 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8126 }
8127
8128 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8129 size_t Size = Ty->getLimitedSize();
8130 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8131
8132 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8133 for (size_t I = 0; I != Size; ++I) {
8134 std::optional<APValue> ElementValue =
8135 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8136 if (!ElementValue)
8137 return std::nullopt;
8138 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8139 }
8140
8141 return ArrayValue;
8142 }
8143
8144 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8145 QualType ElementType = Ty->getElementType();
8146 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8147 bool IsInt = ElementType->isIntegerType();
8148
8149 std::optional<APValue> Values[2];
8150 for (unsigned I = 0; I != 2; ++I) {
8151 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8152 if (!Values[I])
8153 return std::nullopt;
8154 }
8155
8156 if (IsInt)
8157 return APValue(Values[0]->getInt(), Values[1]->getInt());
8158 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8159 }
8160
8161 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8162 QualType EltTy = VTy->getElementType();
8163 unsigned NElts = VTy->getNumElements();
8164 unsigned EltSize =
8165 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8166
8167 SmallVector<APValue, 4> Elts;
8168 Elts.reserve(NElts);
8169 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8170 // Special handling for OpenCL bool vectors:
8171 // Since these vectors are stored as packed bits, but we can't read
8172 // individual bits from the BitCastBuffer, we'll buffer all of the
8173 // elements together into an appropriately sized APInt and write them all
8174 // out at once. Because we don't accept vectors where NElts * EltSize
8175 // isn't a multiple of the char size, there will be no padding space, so
8176 // we don't have to worry about reading any padding data which didn't
8177 // actually need to be accessed.
8178 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8179
8180 SmallVector<uint8_t, 8> Bytes;
8181 Bytes.reserve(NElts / 8);
8182 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8183 return std::nullopt;
8184
8185 APSInt SValInt(NElts, true);
8186 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8187
8188 for (unsigned I = 0; I < NElts; ++I) {
8189 llvm::APInt Elt =
8190 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8191 Elts.emplace_back(
8192 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8193 }
8194 } else {
8195 // Iterate over each of the elements and read them from the buffer at
8196 // the appropriate offset.
8197 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8198 for (unsigned I = 0; I < NElts; ++I) {
8199 std::optional<APValue> EltValue =
8200 visitType(EltTy, Offset + I * EltSizeChars);
8201 if (!EltValue)
8202 return std::nullopt;
8203 Elts.push_back(std::move(*EltValue));
8204 }
8205 }
8206
8207 return APValue(Elts.data(), Elts.size());
8208 }
8209
8210 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8211 return unsupportedType(QualType(Ty, 0));
8212 }
8213
8214 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8215 QualType Can = Ty.getCanonicalType();
8216
8217 switch (Can->getTypeClass()) {
8218#define TYPE(Class, Base) \
8219 case Type::Class: \
8220 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8221#define ABSTRACT_TYPE(Class, Base)
8222#define NON_CANONICAL_TYPE(Class, Base) \
8223 case Type::Class: \
8224 llvm_unreachable("non-canonical type should be impossible!");
8225#define DEPENDENT_TYPE(Class, Base) \
8226 case Type::Class: \
8227 llvm_unreachable( \
8228 "dependent types aren't supported in the constant evaluator!");
8229#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8230 case Type::Class: \
8231 llvm_unreachable("either dependent or not canonical!");
8232#include "clang/AST/TypeNodes.inc"
8233 }
8234 llvm_unreachable("Unhandled Type::TypeClass");
8235 }
8236
8237public:
8238 // Pull out a full value of type DstType.
8239 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8240 const CastExpr *BCE) {
8241 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8242 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8243 }
8244};
8245
8246static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8247 QualType Ty, EvalInfo *Info,
8248 const ASTContext &Ctx,
8249 bool CheckingDest) {
8250 Ty = Ty.getCanonicalType();
8251
8252 auto diag = [&](int Reason) {
8253 if (Info)
8254 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8255 << CheckingDest << (Reason == 4) << Reason;
8256 return false;
8257 };
8258 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8259 if (Info)
8260 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8261 << NoteTy << Construct << Ty;
8262 return false;
8263 };
8264
8265 if (Ty->isUnionType())
8266 return diag(0);
8267 if (Ty->isPointerType())
8268 return diag(1);
8269 if (Ty->isMemberPointerType())
8270 return diag(2);
8271 if (Ty.isVolatileQualified())
8272 return diag(3);
8273
8274 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8275 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8276 for (CXXBaseSpecifier &BS : CXXRD->bases())
8277 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8278 CheckingDest))
8279 return note(1, BS.getType(), BS.getBeginLoc());
8280 }
8281 for (FieldDecl *FD : Record->fields()) {
8282 if (FD->getType()->isReferenceType())
8283 return diag(4);
8284 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8285 CheckingDest))
8286 return note(0, FD->getType(), FD->getBeginLoc());
8287 }
8288 }
8289
8290 if (Ty->isArrayType() &&
8291 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8292 Info, Ctx, CheckingDest))
8293 return false;
8294
8295 if (const auto *VTy = Ty->getAs<VectorType>()) {
8296 QualType EltTy = VTy->getElementType();
8297 unsigned NElts = VTy->getNumElements();
8298 unsigned EltSize =
8299 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8300
8301 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8302 // The vector's size in bits is not a multiple of the target's byte size,
8303 // so its layout is unspecified. For now, we'll simply treat these cases
8304 // as unsupported (this should only be possible with OpenCL bool vectors
8305 // whose element count isn't a multiple of the byte size).
8306 if (Info)
8307 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8308 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8309 return false;
8310 }
8311
8312 if (EltTy->isRealFloatingType() &&
8313 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8314 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8315 // by both clang and LLVM, so for now we won't allow bit_casts involving
8316 // it in a constexpr context.
8317 if (Info)
8318 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8319 << EltTy;
8320 return false;
8321 }
8322 }
8323
8324 return true;
8325}
8326
8327static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8328 const ASTContext &Ctx,
8329 const CastExpr *BCE) {
8330 bool DestOK = checkBitCastConstexprEligibilityType(
8331 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8332 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8333 BCE->getBeginLoc(),
8334 BCE->getSubExpr()->getType(), Info, Ctx, false);
8335 return SourceOK;
8336}
8337
8338static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8339 const APValue &SourceRValue,
8340 const CastExpr *BCE) {
8341 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8342 "no host or target supports non 8-bit chars");
8343
8344 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8345 return false;
8346
8347 // Read out SourceValue into a char buffer.
8348 std::optional<BitCastBuffer> Buffer =
8349 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8350 if (!Buffer)
8351 return false;
8352
8353 // Write out the buffer into a new APValue.
8354 std::optional<APValue> MaybeDestValue =
8355 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8356 if (!MaybeDestValue)
8357 return false;
8358
8359 DestValue = std::move(*MaybeDestValue);
8360 return true;
8361}
8362
8363static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8364 APValue &SourceValue,
8365 const CastExpr *BCE) {
8366 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8367 "no host or target supports non 8-bit chars");
8368 assert(SourceValue.isLValue() &&
8369 "LValueToRValueBitcast requires an lvalue operand!");
8370
8371 LValue SourceLValue;
8372 APValue SourceRValue;
8373 SourceLValue.setFrom(Info.Ctx, SourceValue);
8375 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8376 SourceRValue, /*WantObjectRepresentation=*/true))
8377 return false;
8378
8379 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8380}
8381
8382template <class Derived>
8383class ExprEvaluatorBase
8384 : public ConstStmtVisitor<Derived, bool> {
8385private:
8386 Derived &getDerived() { return static_cast<Derived&>(*this); }
8387 bool DerivedSuccess(const APValue &V, const Expr *E) {
8388 return getDerived().Success(V, E);
8389 }
8390 bool DerivedZeroInitialization(const Expr *E) {
8391 return getDerived().ZeroInitialization(E);
8392 }
8393
8394 // Check whether a conditional operator with a non-constant condition is a
8395 // potential constant expression. If neither arm is a potential constant
8396 // expression, then the conditional operator is not either.
8397 template<typename ConditionalOperator>
8398 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8399 assert(Info.checkingPotentialConstantExpression());
8400
8401 // Speculatively evaluate both arms.
8402 SmallVector<PartialDiagnosticAt, 8> Diag;
8403 {
8404 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8405 StmtVisitorTy::Visit(E->getFalseExpr());
8406 if (Diag.empty())
8407 return;
8408 }
8409
8410 {
8411 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8412 Diag.clear();
8413 StmtVisitorTy::Visit(E->getTrueExpr());
8414 if (Diag.empty())
8415 return;
8416 }
8417
8418 Error(E, diag::note_constexpr_conditional_never_const);
8419 }
8420
8421
8422 template<typename ConditionalOperator>
8423 bool HandleConditionalOperator(const ConditionalOperator *E) {
8424 bool BoolResult;
8425 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8426 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8427 CheckPotentialConstantConditional(E);
8428 return false;
8429 }
8430 if (Info.noteFailure()) {
8431 StmtVisitorTy::Visit(E->getTrueExpr());
8432 StmtVisitorTy::Visit(E->getFalseExpr());
8433 }
8434 return false;
8435 }
8436
8437 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8438 return StmtVisitorTy::Visit(EvalExpr);
8439 }
8440
8441protected:
8442 EvalInfo &Info;
8443 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8444 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8445
8446 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8447 return Info.CCEDiag(E, D);
8448 }
8449
8450 bool ZeroInitialization(const Expr *E) { return Error(E); }
8451
8452 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8453 unsigned BuiltinOp = E->getBuiltinCallee();
8454 return BuiltinOp != 0 &&
8455 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8456 }
8457
8458public:
8459 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8460
8461 EvalInfo &getEvalInfo() { return Info; }
8462
8463 /// Report an evaluation error. This should only be called when an error is
8464 /// first discovered. When propagating an error, just return false.
8465 bool Error(const Expr *E, diag::kind D) {
8466 Info.FFDiag(E, D) << E->getSourceRange();
8467 return false;
8468 }
8469 bool Error(const Expr *E) {
8470 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8471 }
8472
8473 bool VisitStmt(const Stmt *) {
8474 llvm_unreachable("Expression evaluator should not be called on stmts");
8475 }
8476 bool VisitExpr(const Expr *E) {
8477 return Error(E);
8478 }
8479
8480 bool VisitEmbedExpr(const EmbedExpr *E) {
8481 const auto It = E->begin();
8482 return StmtVisitorTy::Visit(*It);
8483 }
8484
8485 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8486 return StmtVisitorTy::Visit(E->getFunctionName());
8487 }
8488 bool VisitConstantExpr(const ConstantExpr *E) {
8489 if (E->hasAPValueResult())
8490 return DerivedSuccess(E->getAPValueResult(), E);
8491
8492 return StmtVisitorTy::Visit(E->getSubExpr());
8493 }
8494
8495 bool VisitParenExpr(const ParenExpr *E)
8496 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8497 bool VisitUnaryExtension(const UnaryOperator *E)
8498 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8499 bool VisitUnaryPlus(const UnaryOperator *E)
8500 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8501 bool VisitChooseExpr(const ChooseExpr *E)
8502 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8503 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8504 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8505 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8506 { return StmtVisitorTy::Visit(E->getReplacement()); }
8507 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8508 TempVersionRAII RAII(*Info.CurrentCall);
8509 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8510 return StmtVisitorTy::Visit(E->getExpr());
8511 }
8512 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8513 TempVersionRAII RAII(*Info.CurrentCall);
8514 // The initializer may not have been parsed yet, or might be erroneous.
8515 if (!E->getExpr())
8516 return Error(E);
8517 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8518 return StmtVisitorTy::Visit(E->getExpr());
8519 }
8520
8521 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8522 FullExpressionRAII Scope(Info);
8523 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8524 }
8525
8526 // Temporaries are registered when created, so we don't care about
8527 // CXXBindTemporaryExpr.
8528 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8529 return StmtVisitorTy::Visit(E->getSubExpr());
8530 }
8531
8532 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8533 CCEDiag(E, diag::note_constexpr_invalid_cast)
8534 << diag::ConstexprInvalidCastKind::Reinterpret;
8535 return static_cast<Derived*>(this)->VisitCastExpr(E);
8536 }
8537 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8538 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8539 CCEDiag(E, diag::note_constexpr_invalid_cast)
8540 << diag::ConstexprInvalidCastKind::Dynamic;
8541 return static_cast<Derived*>(this)->VisitCastExpr(E);
8542 }
8543 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8544 return static_cast<Derived*>(this)->VisitCastExpr(E);
8545 }
8546
8547 bool VisitBinaryOperator(const BinaryOperator *E) {
8548 switch (E->getOpcode()) {
8549 default:
8550 return Error(E);
8551
8552 case BO_Comma:
8553 VisitIgnoredValue(E->getLHS());
8554 return StmtVisitorTy::Visit(E->getRHS());
8555
8556 case BO_PtrMemD:
8557 case BO_PtrMemI: {
8558 LValue Obj;
8559 if (!HandleMemberPointerAccess(Info, E, Obj))
8560 return false;
8562 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8563 return false;
8564 return DerivedSuccess(Result, E);
8565 }
8566 }
8567 }
8568
8569 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8570 return StmtVisitorTy::Visit(E->getSemanticForm());
8571 }
8572
8573 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8574 // Evaluate and cache the common expression. We treat it as a temporary,
8575 // even though it's not quite the same thing.
8576 LValue CommonLV;
8577 if (!Evaluate(Info.CurrentCall->createTemporary(
8578 E->getOpaqueValue(),
8579 getStorageType(Info.Ctx, E->getOpaqueValue()),
8580 ScopeKind::FullExpression, CommonLV),
8581 Info, E->getCommon()))
8582 return false;
8583
8584 return HandleConditionalOperator(E);
8585 }
8586
8587 bool VisitConditionalOperator(const ConditionalOperator *E) {
8588 bool IsBcpCall = false;
8589 // If the condition (ignoring parens) is a __builtin_constant_p call,
8590 // the result is a constant expression if it can be folded without
8591 // side-effects. This is an important GNU extension. See GCC PR38377
8592 // for discussion.
8593 if (const CallExpr *CallCE =
8594 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8595 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8596 IsBcpCall = true;
8597
8598 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8599 // constant expression; we can't check whether it's potentially foldable.
8600 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8601 // it would return 'false' in this mode.
8602 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8603 return false;
8604
8605 FoldConstant Fold(Info, IsBcpCall);
8606 if (!HandleConditionalOperator(E)) {
8607 Fold.keepDiagnostics();
8608 return false;
8609 }
8610
8611 return true;
8612 }
8613
8614 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8615 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8616 Value && !Value->isAbsent())
8617 return DerivedSuccess(*Value, E);
8618
8619 const Expr *Source = E->getSourceExpr();
8620 if (!Source)
8621 return Error(E);
8622 if (Source == E) {
8623 assert(0 && "OpaqueValueExpr recursively refers to itself");
8624 return Error(E);
8625 }
8626 return StmtVisitorTy::Visit(Source);
8627 }
8628
8629 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8630 for (const Expr *SemE : E->semantics()) {
8631 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8632 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8633 // result expression: there could be two different LValues that would
8634 // refer to the same object in that case, and we can't model that.
8635 if (SemE == E->getResultExpr())
8636 return Error(E);
8637
8638 // Unique OVEs get evaluated if and when we encounter them when
8639 // emitting the rest of the semantic form, rather than eagerly.
8640 if (OVE->isUnique())
8641 continue;
8642
8643 LValue LV;
8644 if (!Evaluate(Info.CurrentCall->createTemporary(
8645 OVE, getStorageType(Info.Ctx, OVE),
8646 ScopeKind::FullExpression, LV),
8647 Info, OVE->getSourceExpr()))
8648 return false;
8649 } else if (SemE == E->getResultExpr()) {
8650 if (!StmtVisitorTy::Visit(SemE))
8651 return false;
8652 } else {
8653 if (!EvaluateIgnoredValue(Info, SemE))
8654 return false;
8655 }
8656 }
8657 return true;
8658 }
8659
8660 bool VisitCallExpr(const CallExpr *E) {
8662 if (!handleCallExpr(E, Result, nullptr))
8663 return false;
8664 return DerivedSuccess(Result, E);
8665 }
8666
8667 bool handleCallExpr(const CallExpr *E, APValue &Result,
8668 const LValue *ResultSlot) {
8669 CallScopeRAII CallScope(Info);
8670
8671 const Expr *Callee = E->getCallee()->IgnoreParens();
8672 QualType CalleeType = Callee->getType();
8673
8674 const FunctionDecl *FD = nullptr;
8675 LValue *This = nullptr, ObjectArg;
8676 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8677 bool HasQualifier = false;
8678
8679 CallRef Call;
8680
8681 // Extract function decl and 'this' pointer from the callee.
8682 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8683 const CXXMethodDecl *Member = nullptr;
8684 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8685 // Explicit bound member calls, such as x.f() or p->g();
8686 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8687 return false;
8688 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8689 if (!Member)
8690 return Error(Callee);
8691 This = &ObjectArg;
8692 HasQualifier = ME->hasQualifier();
8693 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8694 // Indirect bound member calls ('.*' or '->*').
8695 const ValueDecl *D =
8696 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8697 if (!D)
8698 return false;
8699 Member = dyn_cast<CXXMethodDecl>(D);
8700 if (!Member)
8701 return Error(Callee);
8702 This = &ObjectArg;
8703 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8704 if (!Info.getLangOpts().CPlusPlus20)
8705 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8706 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8707 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8708 } else
8709 return Error(Callee);
8710 FD = Member;
8711 } else if (CalleeType->isFunctionPointerType()) {
8712 LValue CalleeLV;
8713 if (!EvaluatePointer(Callee, CalleeLV, Info))
8714 return false;
8715
8716 if (!CalleeLV.getLValueOffset().isZero())
8717 return Error(Callee);
8718 if (CalleeLV.isNullPointer()) {
8719 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8720 << const_cast<Expr *>(Callee);
8721 return false;
8722 }
8723 FD = dyn_cast_or_null<FunctionDecl>(
8724 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8725 if (!FD)
8726 return Error(Callee);
8727 // Don't call function pointers which have been cast to some other type.
8728 // Per DR (no number yet), the caller and callee can differ in noexcept.
8729 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8730 CalleeType->getPointeeType(), FD->getType())) {
8731 return Error(E);
8732 }
8733
8734 // For an (overloaded) assignment expression, evaluate the RHS before the
8735 // LHS.
8736 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8737 if (OCE && OCE->isAssignmentOp()) {
8738 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8739 Call = Info.CurrentCall->createCall(FD);
8740 bool HasThis = false;
8741 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8742 HasThis = MD->isImplicitObjectMemberFunction();
8743 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8744 /*RightToLeft=*/true, &ObjectArg))
8745 return false;
8746 }
8747
8748 // Overloaded operator calls to member functions are represented as normal
8749 // calls with '*this' as the first argument.
8750 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8751 if (MD &&
8752 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8753 // FIXME: When selecting an implicit conversion for an overloaded
8754 // operator delete, we sometimes try to evaluate calls to conversion
8755 // operators without a 'this' parameter!
8756 if (Args.empty())
8757 return Error(E);
8758
8759 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8760 return false;
8761
8762 // If we are calling a static operator, the 'this' argument needs to be
8763 // ignored after being evaluated.
8764 if (MD->isInstance())
8765 This = &ObjectArg;
8766
8767 // If this is syntactically a simple assignment using a trivial
8768 // assignment operator, start the lifetimes of union members as needed,
8769 // per C++20 [class.union]5.
8770 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8771 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8772 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8773 return false;
8774
8775 Args = Args.slice(1);
8776 } else if (MD && MD->isLambdaStaticInvoker()) {
8777 // Map the static invoker for the lambda back to the call operator.
8778 // Conveniently, we don't have to slice out the 'this' argument (as is
8779 // being done for the non-static case), since a static member function
8780 // doesn't have an implicit argument passed in.
8781 const CXXRecordDecl *ClosureClass = MD->getParent();
8782 assert(
8783 ClosureClass->captures().empty() &&
8784 "Number of captures must be zero for conversion to function-ptr");
8785
8786 const CXXMethodDecl *LambdaCallOp =
8787 ClosureClass->getLambdaCallOperator();
8788
8789 // Set 'FD', the function that will be called below, to the call
8790 // operator. If the closure object represents a generic lambda, find
8791 // the corresponding specialization of the call operator.
8792
8793 if (ClosureClass->isGenericLambda()) {
8794 assert(MD->isFunctionTemplateSpecialization() &&
8795 "A generic lambda's static-invoker function must be a "
8796 "template specialization");
8797 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8798 FunctionTemplateDecl *CallOpTemplate =
8799 LambdaCallOp->getDescribedFunctionTemplate();
8800 void *InsertPos = nullptr;
8801 FunctionDecl *CorrespondingCallOpSpecialization =
8802 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8803 assert(CorrespondingCallOpSpecialization &&
8804 "We must always have a function call operator specialization "
8805 "that corresponds to our static invoker specialization");
8806 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8807 FD = CorrespondingCallOpSpecialization;
8808 } else
8809 FD = LambdaCallOp;
8811 if (FD->getDeclName().isAnyOperatorNew()) {
8812 LValue Ptr;
8813 if (!HandleOperatorNewCall(Info, E, Ptr))
8814 return false;
8815 Ptr.moveInto(Result);
8816 return CallScope.destroy();
8817 } else {
8818 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8819 }
8820 }
8821 } else
8822 return Error(E);
8823
8824 // Evaluate the arguments now if we've not already done so.
8825 if (!Call) {
8826 Call = Info.CurrentCall->createCall(FD);
8827 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8828 &ObjectArg))
8829 return false;
8830 }
8831
8832 SmallVector<QualType, 4> CovariantAdjustmentPath;
8833 if (This) {
8834 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8835 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8836 // Perform virtual dispatch, if necessary.
8837 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8838 CovariantAdjustmentPath);
8839 if (!FD)
8840 return false;
8841 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8842 // Check that the 'this' pointer points to an object of the right type.
8843 // FIXME: If this is an assignment operator call, we may need to change
8844 // the active union member before we check this.
8845 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8846 return false;
8847 }
8848 }
8849
8850 // Destructor calls are different enough that they have their own codepath.
8851 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8852 assert(This && "no 'this' pointer for destructor call");
8853 return HandleDestruction(Info, E, *This,
8854 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8855 CallScope.destroy();
8856 }
8857
8858 const FunctionDecl *Definition = nullptr;
8859 Stmt *Body = FD->getBody(Definition);
8860 SourceLocation Loc = E->getExprLoc();
8861
8862 // Treat the object argument as `this` when evaluating defaulted
8863 // special menmber functions
8865 This = &ObjectArg;
8866
8867 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8868 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8869 Result, ResultSlot))
8870 return false;
8871
8872 if (!CovariantAdjustmentPath.empty() &&
8874 CovariantAdjustmentPath))
8875 return false;
8876
8877 return CallScope.destroy();
8878 }
8879
8880 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8881 return StmtVisitorTy::Visit(E->getInitializer());
8882 }
8883 bool VisitInitListExpr(const InitListExpr *E) {
8884 if (E->getNumInits() == 0)
8885 return DerivedZeroInitialization(E);
8886 if (E->getNumInits() == 1)
8887 return StmtVisitorTy::Visit(E->getInit(0));
8888 return Error(E);
8889 }
8890 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8891 return DerivedZeroInitialization(E);
8892 }
8893 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8894 return DerivedZeroInitialization(E);
8895 }
8896 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8897 return DerivedZeroInitialization(E);
8898 }
8899
8900 /// A member expression where the object is a prvalue is itself a prvalue.
8901 bool VisitMemberExpr(const MemberExpr *E) {
8902 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8903 "missing temporary materialization conversion");
8904 assert(!E->isArrow() && "missing call to bound member function?");
8905
8906 APValue Val;
8907 if (!Evaluate(Val, Info, E->getBase()))
8908 return false;
8909
8910 QualType BaseTy = E->getBase()->getType();
8911
8912 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8913 if (!FD) return Error(E);
8914 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8915 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8916 FD->getParent()->getCanonicalDecl() &&
8917 "record / field mismatch");
8918
8919 // Note: there is no lvalue base here. But this case should only ever
8920 // happen in C or in C++98, where we cannot be evaluating a constexpr
8921 // constructor, which is the only case the base matters.
8922 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8923 SubobjectDesignator Designator(BaseTy);
8924 Designator.addDeclUnchecked(FD);
8925
8927 return extractSubobject(Info, E, Obj, Designator, Result) &&
8928 DerivedSuccess(Result, E);
8929 }
8930
8931 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8932 APValue Val;
8933 if (!Evaluate(Val, Info, E->getBase()))
8934 return false;
8935
8936 if (Val.isVector()) {
8937 SmallVector<uint32_t, 4> Indices;
8938 E->getEncodedElementAccess(Indices);
8939 if (Indices.size() == 1) {
8940 // Return scalar.
8941 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8942 } else {
8943 // Construct new APValue vector.
8944 SmallVector<APValue, 4> Elts;
8945 for (unsigned I = 0; I < Indices.size(); ++I) {
8946 Elts.push_back(Val.getVectorElt(Indices[I]));
8947 }
8948 APValue VecResult(Elts.data(), Indices.size());
8949 return DerivedSuccess(VecResult, E);
8950 }
8951 }
8952
8953 return false;
8954 }
8955
8956 bool VisitCastExpr(const CastExpr *E) {
8957 switch (E->getCastKind()) {
8958 default:
8959 break;
8960
8961 case CK_AtomicToNonAtomic: {
8962 APValue AtomicVal;
8963 // This does not need to be done in place even for class/array types:
8964 // atomic-to-non-atomic conversion implies copying the object
8965 // representation.
8966 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8967 return false;
8968 return DerivedSuccess(AtomicVal, E);
8969 }
8970
8971 case CK_NoOp:
8972 case CK_UserDefinedConversion:
8973 return StmtVisitorTy::Visit(E->getSubExpr());
8974
8975 case CK_HLSLArrayRValue: {
8976 const Expr *SubExpr = E->getSubExpr();
8977 if (!SubExpr->isGLValue()) {
8978 APValue Val;
8979 if (!Evaluate(Val, Info, SubExpr))
8980 return false;
8981 return DerivedSuccess(Val, E);
8982 }
8983
8984 LValue LVal;
8985 if (!EvaluateLValue(SubExpr, LVal, Info))
8986 return false;
8987 APValue RVal;
8988 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8989 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
8990 RVal))
8991 return false;
8992 return DerivedSuccess(RVal, E);
8993 }
8994 case CK_LValueToRValue: {
8995 LValue LVal;
8996 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8997 return false;
8998 APValue RVal;
8999 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9001 LVal, RVal))
9002 return false;
9003 return DerivedSuccess(RVal, E);
9004 }
9005 case CK_LValueToRValueBitCast: {
9006 APValue DestValue, SourceValue;
9007 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9008 return false;
9009 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9010 return false;
9011 return DerivedSuccess(DestValue, E);
9012 }
9013
9014 case CK_AddressSpaceConversion: {
9015 APValue Value;
9016 if (!Evaluate(Value, Info, E->getSubExpr()))
9017 return false;
9018 return DerivedSuccess(Value, E);
9019 }
9020 }
9021
9022 return Error(E);
9023 }
9024
9025 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9026 return VisitUnaryPostIncDec(UO);
9027 }
9028 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9029 return VisitUnaryPostIncDec(UO);
9030 }
9031 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9032 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9033 return Error(UO);
9034
9035 LValue LVal;
9036 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9037 return false;
9038 APValue RVal;
9039 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9040 UO->isIncrementOp(), &RVal))
9041 return false;
9042 return DerivedSuccess(RVal, UO);
9043 }
9044
9045 bool VisitStmtExpr(const StmtExpr *E) {
9046 // We will have checked the full-expressions inside the statement expression
9047 // when they were completed, and don't need to check them again now.
9048 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9049 false);
9050
9051 const CompoundStmt *CS = E->getSubStmt();
9052 if (CS->body_empty())
9053 return true;
9054
9055 BlockScopeRAII Scope(Info);
9057 BE = CS->body_end();
9058 /**/; ++BI) {
9059 if (BI + 1 == BE) {
9060 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9061 if (!FinalExpr) {
9062 Info.FFDiag((*BI)->getBeginLoc(),
9063 diag::note_constexpr_stmt_expr_unsupported);
9064 return false;
9065 }
9066 return this->Visit(FinalExpr) && Scope.destroy();
9067 }
9068
9070 StmtResult Result = { ReturnValue, nullptr };
9071 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9072 if (ESR != ESR_Succeeded) {
9073 // FIXME: If the statement-expression terminated due to 'return',
9074 // 'break', or 'continue', it would be nice to propagate that to
9075 // the outer statement evaluation rather than bailing out.
9076 if (ESR != ESR_Failed)
9077 Info.FFDiag((*BI)->getBeginLoc(),
9078 diag::note_constexpr_stmt_expr_unsupported);
9079 return false;
9080 }
9081 }
9082
9083 llvm_unreachable("Return from function from the loop above.");
9084 }
9085
9086 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9087 return StmtVisitorTy::Visit(E->getSelectedExpr());
9088 }
9089
9090 /// Visit a value which is evaluated, but whose value is ignored.
9091 void VisitIgnoredValue(const Expr *E) {
9092 EvaluateIgnoredValue(Info, E);
9093 }
9094
9095 /// Potentially visit a MemberExpr's base expression.
9096 void VisitIgnoredBaseExpression(const Expr *E) {
9097 // While MSVC doesn't evaluate the base expression, it does diagnose the
9098 // presence of side-effecting behavior.
9099 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9100 return;
9101 VisitIgnoredValue(E);
9102 }
9103};
9104
9105} // namespace
9106
9107//===----------------------------------------------------------------------===//
9108// Common base class for lvalue and temporary evaluation.
9109//===----------------------------------------------------------------------===//
9110namespace {
9111template<class Derived>
9112class LValueExprEvaluatorBase
9113 : public ExprEvaluatorBase<Derived> {
9114protected:
9115 LValue &Result;
9116 bool InvalidBaseOK;
9117 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9118 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9119
9120 bool Success(APValue::LValueBase B) {
9121 Result.set(B);
9122 return true;
9123 }
9124
9125 bool evaluatePointer(const Expr *E, LValue &Result) {
9126 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9127 }
9128
9129public:
9130 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9131 : ExprEvaluatorBaseTy(Info), Result(Result),
9132 InvalidBaseOK(InvalidBaseOK) {}
9133
9134 bool Success(const APValue &V, const Expr *E) {
9135 Result.setFrom(this->Info.Ctx, V);
9136 return true;
9137 }
9138
9139 bool VisitMemberExpr(const MemberExpr *E) {
9140 // Handle non-static data members.
9141 QualType BaseTy;
9142 bool EvalOK;
9143 if (E->isArrow()) {
9144 EvalOK = evaluatePointer(E->getBase(), Result);
9145 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9146 } else if (E->getBase()->isPRValue()) {
9147 assert(E->getBase()->getType()->isRecordType());
9148 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9149 BaseTy = E->getBase()->getType();
9150 } else {
9151 EvalOK = this->Visit(E->getBase());
9152 BaseTy = E->getBase()->getType();
9153 }
9154 if (!EvalOK) {
9155 if (!InvalidBaseOK)
9156 return false;
9157 Result.setInvalid(E);
9158 return true;
9159 }
9160
9161 const ValueDecl *MD = E->getMemberDecl();
9162 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9163 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9164 FD->getParent()->getCanonicalDecl() &&
9165 "record / field mismatch");
9166 (void)BaseTy;
9167 if (!HandleLValueMember(this->Info, E, Result, FD))
9168 return false;
9169 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9170 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9171 return false;
9172 } else
9173 return this->Error(E);
9174
9175 if (MD->getType()->isReferenceType()) {
9176 APValue RefValue;
9177 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9178 RefValue))
9179 return false;
9180 return Success(RefValue, E);
9181 }
9182 return true;
9183 }
9184
9185 bool VisitBinaryOperator(const BinaryOperator *E) {
9186 switch (E->getOpcode()) {
9187 default:
9188 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9189
9190 case BO_PtrMemD:
9191 case BO_PtrMemI:
9192 return HandleMemberPointerAccess(this->Info, E, Result);
9193 }
9194 }
9195
9196 bool VisitCastExpr(const CastExpr *E) {
9197 switch (E->getCastKind()) {
9198 default:
9199 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9200
9201 case CK_DerivedToBase:
9202 case CK_UncheckedDerivedToBase:
9203 if (!this->Visit(E->getSubExpr()))
9204 return false;
9205
9206 // Now figure out the necessary offset to add to the base LV to get from
9207 // the derived class to the base class.
9208 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9209 Result);
9210 }
9211 }
9212};
9213}
9214
9215//===----------------------------------------------------------------------===//
9216// LValue Evaluation
9217//
9218// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9219// function designators (in C), decl references to void objects (in C), and
9220// temporaries (if building with -Wno-address-of-temporary).
9221//
9222// LValue evaluation produces values comprising a base expression of one of the
9223// following types:
9224// - Declarations
9225// * VarDecl
9226// * FunctionDecl
9227// - Literals
9228// * CompoundLiteralExpr in C (and in global scope in C++)
9229// * StringLiteral
9230// * PredefinedExpr
9231// * ObjCStringLiteralExpr
9232// * ObjCEncodeExpr
9233// * AddrLabelExpr
9234// * BlockExpr
9235// * CallExpr for a MakeStringConstant builtin
9236// - typeid(T) expressions, as TypeInfoLValues
9237// - Locals and temporaries
9238// * MaterializeTemporaryExpr
9239// * Any Expr, with a CallIndex indicating the function in which the temporary
9240// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9241// from the AST (FIXME).
9242// * A MaterializeTemporaryExpr that has static storage duration, with no
9243// CallIndex, for a lifetime-extended temporary.
9244// * The ConstantExpr that is currently being evaluated during evaluation of an
9245// immediate invocation.
9246// plus an offset in bytes.
9247//===----------------------------------------------------------------------===//
9248namespace {
9249class LValueExprEvaluator
9250 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9251public:
9252 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9253 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9254
9255 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9256 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9257
9258 bool VisitCallExpr(const CallExpr *E);
9259 bool VisitDeclRefExpr(const DeclRefExpr *E);
9260 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9261 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9262 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9263 bool VisitMemberExpr(const MemberExpr *E);
9264 bool VisitStringLiteral(const StringLiteral *E) {
9265 return Success(
9266 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9267 }
9268 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9269 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9270 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9271 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9272 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9273 bool VisitUnaryDeref(const UnaryOperator *E);
9274 bool VisitUnaryReal(const UnaryOperator *E);
9275 bool VisitUnaryImag(const UnaryOperator *E);
9276 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9277 return VisitUnaryPreIncDec(UO);
9278 }
9279 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9280 return VisitUnaryPreIncDec(UO);
9281 }
9282 bool VisitBinAssign(const BinaryOperator *BO);
9283 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9284
9285 bool VisitCastExpr(const CastExpr *E) {
9286 switch (E->getCastKind()) {
9287 default:
9288 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9289
9290 case CK_LValueBitCast:
9291 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9292 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9293 << Info.Ctx.getLangOpts().CPlusPlus;
9294 if (!Visit(E->getSubExpr()))
9295 return false;
9296 Result.Designator.setInvalid();
9297 return true;
9298
9299 case CK_BaseToDerived:
9300 if (!Visit(E->getSubExpr()))
9301 return false;
9302 return HandleBaseToDerivedCast(Info, E, Result);
9303
9304 case CK_Dynamic:
9305 if (!Visit(E->getSubExpr()))
9306 return false;
9308 }
9309 }
9310};
9311} // end anonymous namespace
9312
9313/// Get an lvalue to a field of a lambda's closure type.
9314static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9315 const CXXMethodDecl *MD, const FieldDecl *FD,
9316 bool LValueToRValueConversion) {
9317 // Static lambda function call operators can't have captures. We already
9318 // diagnosed this, so bail out here.
9319 if (MD->isStatic()) {
9320 assert(Info.CurrentCall->This == nullptr &&
9321 "This should not be set for a static call operator");
9322 return false;
9323 }
9324
9325 // Start with 'Result' referring to the complete closure object...
9327 // Self may be passed by reference or by value.
9328 const ParmVarDecl *Self = MD->getParamDecl(0);
9329 if (Self->getType()->isReferenceType()) {
9330 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9331 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9332 Result.setFrom(Info.Ctx, *RefValue);
9333 } else {
9334 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9335 CallStackFrame *Frame =
9336 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9337 .first;
9338 unsigned Version = Info.CurrentCall->Arguments.Version;
9339 Result.set({VD, Frame->Index, Version});
9340 }
9341 } else
9342 Result = *Info.CurrentCall->This;
9343
9344 // ... then update it to refer to the field of the closure object
9345 // that represents the capture.
9346 if (!HandleLValueMember(Info, E, Result, FD))
9347 return false;
9348
9349 // And if the field is of reference type (or if we captured '*this' by
9350 // reference), update 'Result' to refer to what
9351 // the field refers to.
9352 if (LValueToRValueConversion) {
9353 APValue RVal;
9354 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9355 return false;
9356 Result.setFrom(Info.Ctx, RVal);
9357 }
9358 return true;
9359}
9360
9361/// Evaluate an expression as an lvalue. This can be legitimately called on
9362/// expressions which are not glvalues, in three cases:
9363/// * function designators in C, and
9364/// * "extern void" objects
9365/// * @selector() expressions in Objective-C
9366static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9367 bool InvalidBaseOK) {
9368 assert(!E->isValueDependent());
9369 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9371 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9372}
9373
9374bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9375 const ValueDecl *D = E->getDecl();
9376
9377 // If we are within a lambda's call operator, check whether the 'VD' referred
9378 // to within 'E' actually represents a lambda-capture that maps to a
9379 // data-member/field within the closure object, and if so, evaluate to the
9380 // field or what the field refers to.
9381 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9383 // We don't always have a complete capture-map when checking or inferring if
9384 // the function call operator meets the requirements of a constexpr function
9385 // - but we don't need to evaluate the captures to determine constexprness
9386 // (dcl.constexpr C++17).
9387 if (Info.checkingPotentialConstantExpression())
9388 return false;
9389
9390 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9391 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9392 return HandleLambdaCapture(Info, E, Result, MD, FD,
9393 FD->getType()->isReferenceType());
9394 }
9395 }
9396
9397 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9398 UnnamedGlobalConstantDecl>(D))
9399 return Success(cast<ValueDecl>(D));
9400 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9401 return VisitVarDecl(E, VD);
9402 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9403 return Visit(BD->getBinding());
9404 return Error(E);
9405}
9406
9407bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9408 CallStackFrame *Frame = nullptr;
9409 unsigned Version = 0;
9410 if (VD->hasLocalStorage()) {
9411 // Only if a local variable was declared in the function currently being
9412 // evaluated, do we expect to be able to find its value in the current
9413 // frame. (Otherwise it was likely declared in an enclosing context and
9414 // could either have a valid evaluatable value (for e.g. a constexpr
9415 // variable) or be ill-formed (and trigger an appropriate evaluation
9416 // diagnostic)).
9417 CallStackFrame *CurrFrame = Info.CurrentCall;
9418 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9419 // Function parameters are stored in some caller's frame. (Usually the
9420 // immediate caller, but for an inherited constructor they may be more
9421 // distant.)
9422 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9423 if (CurrFrame->Arguments) {
9424 VD = CurrFrame->Arguments.getOrigParam(PVD);
9425 Frame =
9426 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9427 Version = CurrFrame->Arguments.Version;
9428 }
9429 } else {
9430 Frame = CurrFrame;
9431 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9432 }
9433 }
9434 }
9435
9436 if (!VD->getType()->isReferenceType()) {
9437 if (Frame) {
9438 Result.set({VD, Frame->Index, Version});
9439 return true;
9440 }
9441 return Success(VD);
9442 }
9443
9444 if (!Info.getLangOpts().CPlusPlus11) {
9445 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9446 << VD << VD->getType();
9447 Info.Note(VD->getLocation(), diag::note_declared_at);
9448 }
9449
9450 APValue *V;
9451 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9452 return false;
9453
9454 if (!V) {
9455 Result.set(VD);
9456 Result.AllowConstexprUnknown = true;
9457 return true;
9458 }
9459
9460 return Success(*V, E);
9461}
9462
9463bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9464 if (!IsConstantEvaluatedBuiltinCall(E))
9465 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9466
9467 switch (E->getBuiltinCallee()) {
9468 default:
9469 return false;
9470 case Builtin::BIas_const:
9471 case Builtin::BIforward:
9472 case Builtin::BIforward_like:
9473 case Builtin::BImove:
9474 case Builtin::BImove_if_noexcept:
9475 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9476 return Visit(E->getArg(0));
9477 break;
9478 }
9479
9480 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9481}
9482
9483bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9484 const MaterializeTemporaryExpr *E) {
9485 // Walk through the expression to find the materialized temporary itself.
9488 const Expr *Inner =
9489 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9490
9491 // If we passed any comma operators, evaluate their LHSs.
9492 for (const Expr *E : CommaLHSs)
9493 if (!EvaluateIgnoredValue(Info, E))
9494 return false;
9495
9496 // A materialized temporary with static storage duration can appear within the
9497 // result of a constant expression evaluation, so we need to preserve its
9498 // value for use outside this evaluation.
9499 APValue *Value;
9500 if (E->getStorageDuration() == SD_Static) {
9501 if (Info.EvalMode == EvaluationMode::ConstantFold)
9502 return false;
9503 // FIXME: What about SD_Thread?
9504 Value = E->getOrCreateValue(true);
9505 *Value = APValue();
9506 Result.set(E);
9507 } else {
9508 Value = &Info.CurrentCall->createTemporary(
9509 E, Inner->getType(),
9510 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9511 : ScopeKind::Block,
9512 Result);
9513 }
9514
9515 QualType Type = Inner->getType();
9516
9517 // Materialize the temporary itself.
9518 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9519 *Value = APValue();
9520 return false;
9521 }
9522
9523 // Adjust our lvalue to refer to the desired subobject.
9524 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9525 --I;
9526 switch (Adjustments[I].Kind) {
9528 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9529 Type, Result))
9530 return false;
9531 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9532 break;
9533
9535 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9536 return false;
9537 Type = Adjustments[I].Field->getType();
9538 break;
9539
9541 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9542 Adjustments[I].Ptr.RHS))
9543 return false;
9544 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9545 break;
9546 }
9547 }
9548
9549 return true;
9550}
9551
9552bool
9553LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9554 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9555 "lvalue compound literal in c++?");
9556 APValue *Lit;
9557 // If CompountLiteral has static storage, its value can be used outside
9558 // this expression. So evaluate it once and store it in ASTContext.
9559 if (E->hasStaticStorage()) {
9560 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9561 Result.set(E);
9562 // Reset any previously evaluated state, otherwise evaluation below might
9563 // fail.
9564 // FIXME: Should we just re-use the previously evaluated value instead?
9565 *Lit = APValue();
9566 } else {
9567 assert(!Info.getLangOpts().CPlusPlus);
9568 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9569 ScopeKind::Block, Result);
9570 }
9571 // FIXME: Evaluating in place isn't always right. We should figure out how to
9572 // use appropriate evaluation context here, see
9573 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9574 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9575 *Lit = APValue();
9576 return false;
9577 }
9578 return true;
9579}
9580
9581bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9582 TypeInfoLValue TypeInfo;
9583
9584 if (!E->isPotentiallyEvaluated()) {
9585 if (E->isTypeOperand())
9586 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9587 else
9588 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9589 } else {
9590 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9591 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9592 << E->getExprOperand()->getType()
9593 << E->getExprOperand()->getSourceRange();
9594 }
9595
9596 if (!Visit(E->getExprOperand()))
9597 return false;
9598
9599 std::optional<DynamicType> DynType =
9601 if (!DynType)
9602 return false;
9603
9604 TypeInfo = TypeInfoLValue(
9605 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9606 }
9607
9608 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9609}
9610
9611bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9612 return Success(E->getGuidDecl());
9613}
9614
9615bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9616 // Handle static data members.
9617 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9618 VisitIgnoredBaseExpression(E->getBase());
9619 return VisitVarDecl(E, VD);
9620 }
9621
9622 // Handle static member functions.
9623 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9624 if (MD->isStatic()) {
9625 VisitIgnoredBaseExpression(E->getBase());
9626 return Success(MD);
9627 }
9628 }
9629
9630 // Handle non-static data members.
9631 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9632}
9633
9634bool LValueExprEvaluator::VisitExtVectorElementExpr(
9635 const ExtVectorElementExpr *E) {
9636 bool Success = true;
9637
9638 APValue Val;
9639 if (!Evaluate(Val, Info, E->getBase())) {
9640 if (!Info.noteFailure())
9641 return false;
9642 Success = false;
9643 }
9644
9646 E->getEncodedElementAccess(Indices);
9647 // FIXME: support accessing more than one element
9648 if (Indices.size() > 1)
9649 return false;
9650
9651 if (Success) {
9652 Result.setFrom(Info.Ctx, Val);
9653 QualType BaseType = E->getBase()->getType();
9654 if (E->isArrow())
9655 BaseType = BaseType->getPointeeType();
9656 const auto *VT = BaseType->castAs<VectorType>();
9657 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9658 VT->getNumElements(), Indices[0]);
9659 }
9660
9661 return Success;
9662}
9663
9664bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9665 if (E->getBase()->getType()->isSveVLSBuiltinType())
9666 return Error(E);
9667
9668 APSInt Index;
9669 bool Success = true;
9670
9671 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9672 APValue Val;
9673 if (!Evaluate(Val, Info, E->getBase())) {
9674 if (!Info.noteFailure())
9675 return false;
9676 Success = false;
9677 }
9678
9679 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9680 if (!Info.noteFailure())
9681 return false;
9682 Success = false;
9683 }
9684
9685 if (Success) {
9686 Result.setFrom(Info.Ctx, Val);
9687 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9688 VT->getNumElements(), Index.getZExtValue());
9689 }
9690
9691 return Success;
9692 }
9693
9694 // C++17's rules require us to evaluate the LHS first, regardless of which
9695 // side is the base.
9696 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9697 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9698 : !EvaluateInteger(SubExpr, Index, Info)) {
9699 if (!Info.noteFailure())
9700 return false;
9701 Success = false;
9702 }
9703 }
9704
9705 return Success &&
9706 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9707}
9708
9709bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9710 bool Success = evaluatePointer(E->getSubExpr(), Result);
9711 // [C++26][expr.unary.op]
9712 // If the operand points to an object or function, the result
9713 // denotes that object or function; otherwise, the behavior is undefined.
9714 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9715 // immediately.
9717 return Success;
9719 E->getType())) ||
9720 Info.noteUndefinedBehavior();
9721}
9722
9723bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9724 if (!Visit(E->getSubExpr()))
9725 return false;
9726 // __real is a no-op on scalar lvalues.
9727 if (E->getSubExpr()->getType()->isAnyComplexType())
9728 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9729 return true;
9730}
9731
9732bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9733 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9734 "lvalue __imag__ on scalar?");
9735 if (!Visit(E->getSubExpr()))
9736 return false;
9737 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9738 return true;
9739}
9740
9741bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9742 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9743 return Error(UO);
9744
9745 if (!this->Visit(UO->getSubExpr()))
9746 return false;
9747
9748 return handleIncDec(
9749 this->Info, UO, Result, UO->getSubExpr()->getType(),
9750 UO->isIncrementOp(), nullptr);
9751}
9752
9753bool LValueExprEvaluator::VisitCompoundAssignOperator(
9754 const CompoundAssignOperator *CAO) {
9755 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9756 return Error(CAO);
9757
9758 bool Success = true;
9759
9760 // C++17 onwards require that we evaluate the RHS first.
9761 APValue RHS;
9762 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9763 if (!Info.noteFailure())
9764 return false;
9765 Success = false;
9766 }
9767
9768 // The overall lvalue result is the result of evaluating the LHS.
9769 if (!this->Visit(CAO->getLHS()) || !Success)
9770 return false;
9771
9773 this->Info, CAO,
9774 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9775 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9776}
9777
9778bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9779 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9780 return Error(E);
9781
9782 bool Success = true;
9783
9784 // C++17 onwards require that we evaluate the RHS first.
9785 APValue NewVal;
9786 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9787 if (!Info.noteFailure())
9788 return false;
9789 Success = false;
9790 }
9791
9792 if (!this->Visit(E->getLHS()) || !Success)
9793 return false;
9794
9795 if (Info.getLangOpts().CPlusPlus20 &&
9797 return false;
9798
9799 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9800 NewVal);
9801}
9802
9803//===----------------------------------------------------------------------===//
9804// Pointer Evaluation
9805//===----------------------------------------------------------------------===//
9806
9807/// Convenience function. LVal's base must be a call to an alloc_size
9808/// function.
9810 const LValue &LVal,
9811 llvm::APInt &Result) {
9812 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9813 "Can't get the size of a non alloc_size function");
9814 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9815 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9816 std::optional<llvm::APInt> Size =
9817 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9818 if (!Size)
9819 return false;
9820
9821 Result = std::move(*Size);
9822 return true;
9823}
9824
9825/// Attempts to evaluate the given LValueBase as the result of a call to
9826/// a function with the alloc_size attribute. If it was possible to do so, this
9827/// function will return true, make Result's Base point to said function call,
9828/// and mark Result's Base as invalid.
9830 LValue &Result) {
9831 if (Base.isNull())
9832 return false;
9833
9834 // Because we do no form of static analysis, we only support const variables.
9835 //
9836 // Additionally, we can't support parameters, nor can we support static
9837 // variables (in the latter case, use-before-assign isn't UB; in the former,
9838 // we have no clue what they'll be assigned to).
9839 const auto *VD =
9840 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9841 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9842 return false;
9843
9844 const Expr *Init = VD->getAnyInitializer();
9845 if (!Init || Init->getType().isNull())
9846 return false;
9847
9848 const Expr *E = Init->IgnoreParens();
9849 if (!tryUnwrapAllocSizeCall(E))
9850 return false;
9851
9852 // Store E instead of E unwrapped so that the type of the LValue's base is
9853 // what the user wanted.
9854 Result.setInvalid(E);
9855
9856 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9857 Result.addUnsizedArray(Info, E, Pointee);
9858 return true;
9859}
9860
9861namespace {
9862class PointerExprEvaluator
9863 : public ExprEvaluatorBase<PointerExprEvaluator> {
9864 LValue &Result;
9865 bool InvalidBaseOK;
9866
9867 bool Success(const Expr *E) {
9868 Result.set(E);
9869 return true;
9870 }
9871
9872 bool evaluateLValue(const Expr *E, LValue &Result) {
9873 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9874 }
9875
9876 bool evaluatePointer(const Expr *E, LValue &Result) {
9877 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9878 }
9879
9880 bool visitNonBuiltinCallExpr(const CallExpr *E);
9881public:
9882
9883 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9884 : ExprEvaluatorBaseTy(info), Result(Result),
9885 InvalidBaseOK(InvalidBaseOK) {}
9886
9887 bool Success(const APValue &V, const Expr *E) {
9888 Result.setFrom(Info.Ctx, V);
9889 return true;
9890 }
9891 bool ZeroInitialization(const Expr *E) {
9892 Result.setNull(Info.Ctx, E->getType());
9893 return true;
9894 }
9895
9896 bool VisitBinaryOperator(const BinaryOperator *E);
9897 bool VisitCastExpr(const CastExpr* E);
9898 bool VisitUnaryAddrOf(const UnaryOperator *E);
9899 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9900 { return Success(E); }
9901 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9903 return Success(E);
9904 if (Info.noteFailure())
9905 EvaluateIgnoredValue(Info, E->getSubExpr());
9906 return Error(E);
9907 }
9908 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
9909 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9910 }
9911 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
9912 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9913 }
9914 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9915 { return Success(E); }
9916 bool VisitCallExpr(const CallExpr *E);
9917 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9918 bool VisitBlockExpr(const BlockExpr *E) {
9919 if (!E->getBlockDecl()->hasCaptures())
9920 return Success(E);
9921 return Error(E);
9922 }
9923 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9924 auto DiagnoseInvalidUseOfThis = [&] {
9925 if (Info.getLangOpts().CPlusPlus11)
9926 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9927 else
9928 Info.FFDiag(E);
9929 };
9930
9931 // Can't look at 'this' when checking a potential constant expression.
9932 if (Info.checkingPotentialConstantExpression())
9933 return false;
9934
9935 bool IsExplicitLambda =
9936 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9937 if (!IsExplicitLambda) {
9938 if (!Info.CurrentCall->This) {
9939 DiagnoseInvalidUseOfThis();
9940 return false;
9941 }
9942
9943 Result = *Info.CurrentCall->This;
9944 }
9945
9946 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9947 // Ensure we actually have captured 'this'. If something was wrong with
9948 // 'this' capture, the error would have been previously reported.
9949 // Otherwise we can be inside of a default initialization of an object
9950 // declared by lambda's body, so no need to return false.
9951 if (!Info.CurrentCall->LambdaThisCaptureField) {
9952 if (IsExplicitLambda && !Info.CurrentCall->This) {
9953 DiagnoseInvalidUseOfThis();
9954 return false;
9955 }
9956
9957 return true;
9958 }
9959
9960 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9961 return HandleLambdaCapture(
9962 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9963 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9964 }
9965 return true;
9966 }
9967
9968 bool VisitCXXNewExpr(const CXXNewExpr *E);
9969
9970 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9971 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9972 APValue LValResult = E->EvaluateInContext(
9973 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9974 Result.setFrom(Info.Ctx, LValResult);
9975 return true;
9976 }
9977
9978 bool VisitEmbedExpr(const EmbedExpr *E) {
9979 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9980 return true;
9981 }
9982
9983 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9984 std::string ResultStr = E->ComputeName(Info.Ctx);
9985
9986 QualType CharTy = Info.Ctx.CharTy.withConst();
9987 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9988 ResultStr.size() + 1);
9989 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9990 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9991
9992 StringLiteral *SL =
9993 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9994 /*Pascal*/ false, ArrayTy, E->getLocation());
9995
9996 evaluateLValue(SL, Result);
9997 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9998 return true;
9999 }
10000
10001 // FIXME: Missing: @protocol, @selector
10002};
10003} // end anonymous namespace
10004
10005static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10006 bool InvalidBaseOK) {
10007 assert(!E->isValueDependent());
10008 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10009 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10010}
10011
10012bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10013 if (E->getOpcode() != BO_Add &&
10014 E->getOpcode() != BO_Sub)
10015 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10016
10017 const Expr *PExp = E->getLHS();
10018 const Expr *IExp = E->getRHS();
10019 if (IExp->getType()->isPointerType())
10020 std::swap(PExp, IExp);
10021
10022 bool EvalPtrOK = evaluatePointer(PExp, Result);
10023 if (!EvalPtrOK && !Info.noteFailure())
10024 return false;
10025
10026 llvm::APSInt Offset;
10027 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10028 return false;
10029
10030 if (E->getOpcode() == BO_Sub)
10031 negateAsSigned(Offset);
10032
10033 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10034 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10035}
10036
10037bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10038 return evaluateLValue(E->getSubExpr(), Result);
10039}
10040
10041// Is the provided decl 'std::source_location::current'?
10043 if (!FD)
10044 return false;
10045 const IdentifierInfo *FnII = FD->getIdentifier();
10046 if (!FnII || !FnII->isStr("current"))
10047 return false;
10048
10049 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10050 if (!RD)
10051 return false;
10052
10053 const IdentifierInfo *ClassII = RD->getIdentifier();
10054 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10055}
10056
10057bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10058 const Expr *SubExpr = E->getSubExpr();
10059
10060 switch (E->getCastKind()) {
10061 default:
10062 break;
10063 case CK_BitCast:
10064 case CK_CPointerToObjCPointerCast:
10065 case CK_BlockPointerToObjCPointerCast:
10066 case CK_AnyPointerToBlockPointerCast:
10067 case CK_AddressSpaceConversion:
10068 if (!Visit(SubExpr))
10069 return false;
10070 if (E->getType()->isFunctionPointerType() ||
10071 SubExpr->getType()->isFunctionPointerType()) {
10072 // Casting between two function pointer types, or between a function
10073 // pointer and an object pointer, is always a reinterpret_cast.
10074 CCEDiag(E, diag::note_constexpr_invalid_cast)
10075 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10076 << Info.Ctx.getLangOpts().CPlusPlus;
10077 Result.Designator.setInvalid();
10078 } else if (!E->getType()->isVoidPointerType()) {
10079 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10080 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10081 // also static_casts, but we disallow them as a resolution to DR1312.
10082 //
10083 // In some circumstances, we permit casting from void* to cv1 T*, when the
10084 // actual pointee object is actually a cv2 T.
10085 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10086 !Result.IsNullPtr;
10087 bool VoidPtrCastMaybeOK =
10088 Result.IsNullPtr ||
10089 (HasValidResult &&
10090 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10091 E->getType()->getPointeeType()));
10092 // 1. We'll allow it in std::allocator::allocate, and anything which that
10093 // calls.
10094 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10095 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10096 // We'll allow it in the body of std::source_location::current. GCC's
10097 // implementation had a parameter of type `void*`, and casts from
10098 // that back to `const __impl*` in its body.
10099 if (VoidPtrCastMaybeOK &&
10100 (Info.getStdAllocatorCaller("allocate") ||
10101 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10102 Info.getLangOpts().CPlusPlus26)) {
10103 // Permitted.
10104 } else {
10105 if (SubExpr->getType()->isVoidPointerType() &&
10106 Info.getLangOpts().CPlusPlus) {
10107 if (HasValidResult)
10108 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10109 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10110 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10111 << E->getType()->getPointeeType();
10112 else
10113 CCEDiag(E, diag::note_constexpr_invalid_cast)
10114 << diag::ConstexprInvalidCastKind::CastFrom
10115 << SubExpr->getType();
10116 } else
10117 CCEDiag(E, diag::note_constexpr_invalid_cast)
10118 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10119 << Info.Ctx.getLangOpts().CPlusPlus;
10120 Result.Designator.setInvalid();
10121 }
10122 }
10123 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10124 ZeroInitialization(E);
10125 return true;
10126
10127 case CK_DerivedToBase:
10128 case CK_UncheckedDerivedToBase:
10129 if (!evaluatePointer(E->getSubExpr(), Result))
10130 return false;
10131 if (!Result.Base && Result.Offset.isZero())
10132 return true;
10133
10134 // Now figure out the necessary offset to add to the base LV to get from
10135 // the derived class to the base class.
10136 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10137 castAs<PointerType>()->getPointeeType(),
10138 Result);
10139
10140 case CK_BaseToDerived:
10141 if (!Visit(E->getSubExpr()))
10142 return false;
10143 if (!Result.Base && Result.Offset.isZero())
10144 return true;
10145 return HandleBaseToDerivedCast(Info, E, Result);
10146
10147 case CK_Dynamic:
10148 if (!Visit(E->getSubExpr()))
10149 return false;
10151
10152 case CK_NullToPointer:
10153 VisitIgnoredValue(E->getSubExpr());
10154 return ZeroInitialization(E);
10155
10156 case CK_IntegralToPointer: {
10157 CCEDiag(E, diag::note_constexpr_invalid_cast)
10158 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10159 << Info.Ctx.getLangOpts().CPlusPlus;
10160
10161 APValue Value;
10162 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10163 break;
10164
10165 if (Value.isInt()) {
10166 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10167 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10168 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10169 Result.setNull(Info.Ctx, E->getType());
10170 } else {
10171 Result.Base = (Expr *)nullptr;
10172 Result.InvalidBase = false;
10173 Result.Offset = CharUnits::fromQuantity(N);
10174 Result.Designator.setInvalid();
10175 Result.IsNullPtr = false;
10176 }
10177 return true;
10178 } else {
10179 // In rare instances, the value isn't an lvalue.
10180 // For example, when the value is the difference between the addresses of
10181 // two labels. We reject that as a constant expression because we can't
10182 // compute a valid offset to convert into a pointer.
10183 if (!Value.isLValue())
10184 return false;
10185
10186 // Cast is of an lvalue, no need to change value.
10187 Result.setFrom(Info.Ctx, Value);
10188 return true;
10189 }
10190 }
10191
10192 case CK_ArrayToPointerDecay: {
10193 if (SubExpr->isGLValue()) {
10194 if (!evaluateLValue(SubExpr, Result))
10195 return false;
10196 } else {
10197 APValue &Value = Info.CurrentCall->createTemporary(
10198 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10199 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10200 return false;
10201 }
10202 // The result is a pointer to the first element of the array.
10203 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10204 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10205 Result.addArray(Info, E, CAT);
10206 else
10207 Result.addUnsizedArray(Info, E, AT->getElementType());
10208 return true;
10209 }
10210
10211 case CK_FunctionToPointerDecay:
10212 return evaluateLValue(SubExpr, Result);
10213
10214 case CK_LValueToRValue: {
10215 LValue LVal;
10216 if (!evaluateLValue(E->getSubExpr(), LVal))
10217 return false;
10218
10219 APValue RVal;
10220 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10222 LVal, RVal))
10223 return InvalidBaseOK &&
10224 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10225 return Success(RVal, E);
10226 }
10227 }
10228
10229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10230}
10231
10233 UnaryExprOrTypeTrait ExprKind) {
10234 // C++ [expr.alignof]p3:
10235 // When alignof is applied to a reference type, the result is the
10236 // alignment of the referenced type.
10237 T = T.getNonReferenceType();
10238
10239 if (T.getQualifiers().hasUnaligned())
10240 return CharUnits::One();
10241
10242 const bool AlignOfReturnsPreferred =
10243 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10244
10245 // __alignof is defined to return the preferred alignment.
10246 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10247 // as well.
10248 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10249 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10250 // alignof and _Alignof are defined to return the ABI alignment.
10251 else if (ExprKind == UETT_AlignOf)
10252 return Ctx.getTypeAlignInChars(T.getTypePtr());
10253 else
10254 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10255}
10256
10258 UnaryExprOrTypeTrait ExprKind) {
10259 E = E->IgnoreParens();
10260
10261 // The kinds of expressions that we have special-case logic here for
10262 // should be kept up to date with the special checks for those
10263 // expressions in Sema.
10264
10265 // alignof decl is always accepted, even if it doesn't make sense: we default
10266 // to 1 in those cases.
10267 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10268 return Ctx.getDeclAlign(DRE->getDecl(),
10269 /*RefAsPointee*/ true);
10270
10271 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10272 return Ctx.getDeclAlign(ME->getMemberDecl(),
10273 /*RefAsPointee*/ true);
10274
10275 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10276}
10277
10278static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10279 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10280 return Info.Ctx.getDeclAlign(VD);
10281 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10282 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10283 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10284}
10285
10286/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10287/// __builtin_is_aligned and __builtin_assume_aligned.
10288static bool getAlignmentArgument(const Expr *E, QualType ForType,
10289 EvalInfo &Info, APSInt &Alignment) {
10290 if (!EvaluateInteger(E, Alignment, Info))
10291 return false;
10292 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10293 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10294 return false;
10295 }
10296 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10297 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10298 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10299 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10300 << MaxValue << ForType << Alignment;
10301 return false;
10302 }
10303 // Ensure both alignment and source value have the same bit width so that we
10304 // don't assert when computing the resulting value.
10305 APSInt ExtAlignment =
10306 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10307 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10308 "Alignment should not be changed by ext/trunc");
10309 Alignment = ExtAlignment;
10310 assert(Alignment.getBitWidth() == SrcWidth);
10311 return true;
10312}
10313
10314// To be clear: this happily visits unsupported builtins. Better name welcomed.
10315bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10316 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10317 return true;
10318
10319 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10320 return false;
10321
10322 Result.setInvalid(E);
10323 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10324 Result.addUnsizedArray(Info, E, PointeeTy);
10325 return true;
10326}
10327
10328bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10329 if (!IsConstantEvaluatedBuiltinCall(E))
10330 return visitNonBuiltinCallExpr(E);
10331 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10332}
10333
10334// Determine if T is a character type for which we guarantee that
10335// sizeof(T) == 1.
10337 return T->isCharType() || T->isChar8Type();
10338}
10339
10340bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10341 unsigned BuiltinOp) {
10342 if (IsOpaqueConstantCall(E))
10343 return Success(E);
10344
10345 switch (BuiltinOp) {
10346 case Builtin::BIaddressof:
10347 case Builtin::BI__addressof:
10348 case Builtin::BI__builtin_addressof:
10349 return evaluateLValue(E->getArg(0), Result);
10350 case Builtin::BI__builtin_assume_aligned: {
10351 // We need to be very careful here because: if the pointer does not have the
10352 // asserted alignment, then the behavior is undefined, and undefined
10353 // behavior is non-constant.
10354 if (!evaluatePointer(E->getArg(0), Result))
10355 return false;
10356
10357 LValue OffsetResult(Result);
10358 APSInt Alignment;
10359 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10360 Alignment))
10361 return false;
10362 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10363
10364 if (E->getNumArgs() > 2) {
10365 APSInt Offset;
10366 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10367 return false;
10368
10369 int64_t AdditionalOffset = -Offset.getZExtValue();
10370 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10371 }
10372
10373 // If there is a base object, then it must have the correct alignment.
10374 if (OffsetResult.Base) {
10375 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10376
10377 if (BaseAlignment < Align) {
10378 Result.Designator.setInvalid();
10379 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10380 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10381 return false;
10382 }
10383 }
10384
10385 // The offset must also have the correct alignment.
10386 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10387 Result.Designator.setInvalid();
10388
10389 (OffsetResult.Base
10390 ? CCEDiag(E->getArg(0),
10391 diag::note_constexpr_baa_insufficient_alignment)
10392 << 1
10393 : CCEDiag(E->getArg(0),
10394 diag::note_constexpr_baa_value_insufficient_alignment))
10395 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10396 return false;
10397 }
10398
10399 return true;
10400 }
10401 case Builtin::BI__builtin_align_up:
10402 case Builtin::BI__builtin_align_down: {
10403 if (!evaluatePointer(E->getArg(0), Result))
10404 return false;
10405 APSInt Alignment;
10406 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10407 Alignment))
10408 return false;
10409 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10410 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10411 // For align_up/align_down, we can return the same value if the alignment
10412 // is known to be greater or equal to the requested value.
10413 if (PtrAlign.getQuantity() >= Alignment)
10414 return true;
10415
10416 // The alignment could be greater than the minimum at run-time, so we cannot
10417 // infer much about the resulting pointer value. One case is possible:
10418 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10419 // can infer the correct index if the requested alignment is smaller than
10420 // the base alignment so we can perform the computation on the offset.
10421 if (BaseAlignment.getQuantity() >= Alignment) {
10422 assert(Alignment.getBitWidth() <= 64 &&
10423 "Cannot handle > 64-bit address-space");
10424 uint64_t Alignment64 = Alignment.getZExtValue();
10425 CharUnits NewOffset = CharUnits::fromQuantity(
10426 BuiltinOp == Builtin::BI__builtin_align_down
10427 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10428 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10429 Result.adjustOffset(NewOffset - Result.Offset);
10430 // TODO: diagnose out-of-bounds values/only allow for arrays?
10431 return true;
10432 }
10433 // Otherwise, we cannot constant-evaluate the result.
10434 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10435 << Alignment;
10436 return false;
10437 }
10438 case Builtin::BI__builtin_operator_new:
10439 return HandleOperatorNewCall(Info, E, Result);
10440 case Builtin::BI__builtin_launder:
10441 return evaluatePointer(E->getArg(0), Result);
10442 case Builtin::BIstrchr:
10443 case Builtin::BIwcschr:
10444 case Builtin::BImemchr:
10445 case Builtin::BIwmemchr:
10446 if (Info.getLangOpts().CPlusPlus11)
10447 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10448 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10449 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10450 else
10451 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10452 [[fallthrough]];
10453 case Builtin::BI__builtin_strchr:
10454 case Builtin::BI__builtin_wcschr:
10455 case Builtin::BI__builtin_memchr:
10456 case Builtin::BI__builtin_char_memchr:
10457 case Builtin::BI__builtin_wmemchr: {
10458 if (!Visit(E->getArg(0)))
10459 return false;
10460 APSInt Desired;
10461 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10462 return false;
10463 uint64_t MaxLength = uint64_t(-1);
10464 if (BuiltinOp != Builtin::BIstrchr &&
10465 BuiltinOp != Builtin::BIwcschr &&
10466 BuiltinOp != Builtin::BI__builtin_strchr &&
10467 BuiltinOp != Builtin::BI__builtin_wcschr) {
10468 APSInt N;
10469 if (!EvaluateInteger(E->getArg(2), N, Info))
10470 return false;
10471 MaxLength = N.getZExtValue();
10472 }
10473 // We cannot find the value if there are no candidates to match against.
10474 if (MaxLength == 0u)
10475 return ZeroInitialization(E);
10476 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10477 Result.Designator.Invalid)
10478 return false;
10479 QualType CharTy = Result.Designator.getType(Info.Ctx);
10480 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10481 BuiltinOp == Builtin::BI__builtin_memchr;
10482 assert(IsRawByte ||
10483 Info.Ctx.hasSameUnqualifiedType(
10484 CharTy, E->getArg(0)->getType()->getPointeeType()));
10485 // Pointers to const void may point to objects of incomplete type.
10486 if (IsRawByte && CharTy->isIncompleteType()) {
10487 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10488 return false;
10489 }
10490 // Give up on byte-oriented matching against multibyte elements.
10491 // FIXME: We can compare the bytes in the correct order.
10492 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10493 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10494 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10495 return false;
10496 }
10497 // Figure out what value we're actually looking for (after converting to
10498 // the corresponding unsigned type if necessary).
10499 uint64_t DesiredVal;
10500 bool StopAtNull = false;
10501 switch (BuiltinOp) {
10502 case Builtin::BIstrchr:
10503 case Builtin::BI__builtin_strchr:
10504 // strchr compares directly to the passed integer, and therefore
10505 // always fails if given an int that is not a char.
10506 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10507 E->getArg(1)->getType(),
10508 Desired),
10509 Desired))
10510 return ZeroInitialization(E);
10511 StopAtNull = true;
10512 [[fallthrough]];
10513 case Builtin::BImemchr:
10514 case Builtin::BI__builtin_memchr:
10515 case Builtin::BI__builtin_char_memchr:
10516 // memchr compares by converting both sides to unsigned char. That's also
10517 // correct for strchr if we get this far (to cope with plain char being
10518 // unsigned in the strchr case).
10519 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10520 break;
10521
10522 case Builtin::BIwcschr:
10523 case Builtin::BI__builtin_wcschr:
10524 StopAtNull = true;
10525 [[fallthrough]];
10526 case Builtin::BIwmemchr:
10527 case Builtin::BI__builtin_wmemchr:
10528 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10529 DesiredVal = Desired.getZExtValue();
10530 break;
10531 }
10532
10533 for (; MaxLength; --MaxLength) {
10534 APValue Char;
10535 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10536 !Char.isInt())
10537 return false;
10538 if (Char.getInt().getZExtValue() == DesiredVal)
10539 return true;
10540 if (StopAtNull && !Char.getInt())
10541 break;
10542 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10543 return false;
10544 }
10545 // Not found: return nullptr.
10546 return ZeroInitialization(E);
10547 }
10548
10549 case Builtin::BImemcpy:
10550 case Builtin::BImemmove:
10551 case Builtin::BIwmemcpy:
10552 case Builtin::BIwmemmove:
10553 if (Info.getLangOpts().CPlusPlus11)
10554 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10555 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10556 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10557 else
10558 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10559 [[fallthrough]];
10560 case Builtin::BI__builtin_memcpy:
10561 case Builtin::BI__builtin_memmove:
10562 case Builtin::BI__builtin_wmemcpy:
10563 case Builtin::BI__builtin_wmemmove: {
10564 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10565 BuiltinOp == Builtin::BIwmemmove ||
10566 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10567 BuiltinOp == Builtin::BI__builtin_wmemmove;
10568 bool Move = BuiltinOp == Builtin::BImemmove ||
10569 BuiltinOp == Builtin::BIwmemmove ||
10570 BuiltinOp == Builtin::BI__builtin_memmove ||
10571 BuiltinOp == Builtin::BI__builtin_wmemmove;
10572
10573 // The result of mem* is the first argument.
10574 if (!Visit(E->getArg(0)))
10575 return false;
10576 LValue Dest = Result;
10577
10578 LValue Src;
10579 if (!EvaluatePointer(E->getArg(1), Src, Info))
10580 return false;
10581
10582 APSInt N;
10583 if (!EvaluateInteger(E->getArg(2), N, Info))
10584 return false;
10585 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10586
10587 // If the size is zero, we treat this as always being a valid no-op.
10588 // (Even if one of the src and dest pointers is null.)
10589 if (!N)
10590 return true;
10591
10592 // Otherwise, if either of the operands is null, we can't proceed. Don't
10593 // try to determine the type of the copied objects, because there aren't
10594 // any.
10595 if (!Src.Base || !Dest.Base) {
10596 APValue Val;
10597 (!Src.Base ? Src : Dest).moveInto(Val);
10598 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10599 << Move << WChar << !!Src.Base
10600 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10601 return false;
10602 }
10603 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10604 return false;
10605
10606 // We require that Src and Dest are both pointers to arrays of
10607 // trivially-copyable type. (For the wide version, the designator will be
10608 // invalid if the designated object is not a wchar_t.)
10609 QualType T = Dest.Designator.getType(Info.Ctx);
10610 QualType SrcT = Src.Designator.getType(Info.Ctx);
10611 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10612 // FIXME: Consider using our bit_cast implementation to support this.
10613 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10614 return false;
10615 }
10616 if (T->isIncompleteType()) {
10617 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10618 return false;
10619 }
10620 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10621 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10622 return false;
10623 }
10624
10625 // Figure out how many T's we're copying.
10626 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10627 if (TSize == 0)
10628 return false;
10629 if (!WChar) {
10630 uint64_t Remainder;
10631 llvm::APInt OrigN = N;
10632 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10633 if (Remainder) {
10634 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10635 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10636 << (unsigned)TSize;
10637 return false;
10638 }
10639 }
10640
10641 // Check that the copying will remain within the arrays, just so that we
10642 // can give a more meaningful diagnostic. This implicitly also checks that
10643 // N fits into 64 bits.
10644 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10645 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10646 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10647 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10648 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10649 << toString(N, 10, /*Signed*/false);
10650 return false;
10651 }
10652 uint64_t NElems = N.getZExtValue();
10653 uint64_t NBytes = NElems * TSize;
10654
10655 // Check for overlap.
10656 int Direction = 1;
10657 if (HasSameBase(Src, Dest)) {
10658 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10659 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10660 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10661 // Dest is inside the source region.
10662 if (!Move) {
10663 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10664 return false;
10665 }
10666 // For memmove and friends, copy backwards.
10667 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10668 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10669 return false;
10670 Direction = -1;
10671 } else if (!Move && SrcOffset >= DestOffset &&
10672 SrcOffset - DestOffset < NBytes) {
10673 // Src is inside the destination region for memcpy: invalid.
10674 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10675 return false;
10676 }
10677 }
10678
10679 while (true) {
10680 APValue Val;
10681 // FIXME: Set WantObjectRepresentation to true if we're copying a
10682 // char-like type?
10683 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10684 !handleAssignment(Info, E, Dest, T, Val))
10685 return false;
10686 // Do not iterate past the last element; if we're copying backwards, that
10687 // might take us off the start of the array.
10688 if (--NElems == 0)
10689 return true;
10690 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10691 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10692 return false;
10693 }
10694 }
10695
10696 default:
10697 return false;
10698 }
10699}
10700
10701static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10702 APValue &Result, const InitListExpr *ILE,
10703 QualType AllocType);
10704static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10705 APValue &Result,
10706 const CXXConstructExpr *CCE,
10707 QualType AllocType);
10708
10709bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10710 if (!Info.getLangOpts().CPlusPlus20)
10711 Info.CCEDiag(E, diag::note_constexpr_new);
10712
10713 // We cannot speculatively evaluate a delete expression.
10714 if (Info.SpeculativeEvaluationDepth)
10715 return false;
10716
10717 FunctionDecl *OperatorNew = E->getOperatorNew();
10718 QualType AllocType = E->getAllocatedType();
10719 QualType TargetType = AllocType;
10720
10721 bool IsNothrow = false;
10722 bool IsPlacement = false;
10723
10724 if (E->getNumPlacementArgs() == 1 &&
10725 E->getPlacementArg(0)->getType()->isNothrowT()) {
10726 // The only new-placement list we support is of the form (std::nothrow).
10727 //
10728 // FIXME: There is no restriction on this, but it's not clear that any
10729 // other form makes any sense. We get here for cases such as:
10730 //
10731 // new (std::align_val_t{N}) X(int)
10732 //
10733 // (which should presumably be valid only if N is a multiple of
10734 // alignof(int), and in any case can't be deallocated unless N is
10735 // alignof(X) and X has new-extended alignment).
10736 LValue Nothrow;
10737 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10738 return false;
10739 IsNothrow = true;
10740 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10741 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10742 (Info.CurrentCall->CanEvalMSConstexpr &&
10743 OperatorNew->hasAttr<MSConstexprAttr>())) {
10744 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10745 return false;
10746 if (Result.Designator.Invalid)
10747 return false;
10748 TargetType = E->getPlacementArg(0)->getType();
10749 IsPlacement = true;
10750 } else {
10751 Info.FFDiag(E, diag::note_constexpr_new_placement)
10752 << /*C++26 feature*/ 1 << E->getSourceRange();
10753 return false;
10754 }
10755 } else if (E->getNumPlacementArgs()) {
10756 Info.FFDiag(E, diag::note_constexpr_new_placement)
10757 << /*Unsupported*/ 0 << E->getSourceRange();
10758 return false;
10759 } else if (!OperatorNew
10760 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10761 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10762 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10763 return false;
10764 }
10765
10766 const Expr *Init = E->getInitializer();
10767 const InitListExpr *ResizedArrayILE = nullptr;
10768 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10769 bool ValueInit = false;
10770
10771 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10772 const Expr *Stripped = *ArraySize;
10773 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10774 Stripped = ICE->getSubExpr())
10775 if (ICE->getCastKind() != CK_NoOp &&
10776 ICE->getCastKind() != CK_IntegralCast)
10777 break;
10778
10779 llvm::APSInt ArrayBound;
10780 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10781 return false;
10782
10783 // C++ [expr.new]p9:
10784 // The expression is erroneous if:
10785 // -- [...] its value before converting to size_t [or] applying the
10786 // second standard conversion sequence is less than zero
10787 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10788 if (IsNothrow)
10789 return ZeroInitialization(E);
10790
10791 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10792 << ArrayBound << (*ArraySize)->getSourceRange();
10793 return false;
10794 }
10795
10796 // -- its value is such that the size of the allocated object would
10797 // exceed the implementation-defined limit
10798 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10800 Info.Ctx, AllocType, ArrayBound),
10801 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10802 if (IsNothrow)
10803 return ZeroInitialization(E);
10804 return false;
10805 }
10806
10807 // -- the new-initializer is a braced-init-list and the number of
10808 // array elements for which initializers are provided [...]
10809 // exceeds the number of elements to initialize
10810 if (!Init) {
10811 // No initialization is performed.
10812 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10814 ValueInit = true;
10815 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10816 ResizedArrayCCE = CCE;
10817 } else {
10818 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10819 assert(CAT && "unexpected type for array initializer");
10820
10821 unsigned Bits =
10822 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10823 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10824 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10825 if (InitBound.ugt(AllocBound)) {
10826 if (IsNothrow)
10827 return ZeroInitialization(E);
10828
10829 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10830 << toString(AllocBound, 10, /*Signed=*/false)
10831 << toString(InitBound, 10, /*Signed=*/false)
10832 << (*ArraySize)->getSourceRange();
10833 return false;
10834 }
10835
10836 // If the sizes differ, we must have an initializer list, and we need
10837 // special handling for this case when we initialize.
10838 if (InitBound != AllocBound)
10839 ResizedArrayILE = cast<InitListExpr>(Init);
10840 }
10841
10842 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10843 ArraySizeModifier::Normal, 0);
10844 } else {
10845 assert(!AllocType->isArrayType() &&
10846 "array allocation with non-array new");
10847 }
10848
10849 APValue *Val;
10850 if (IsPlacement) {
10852 struct FindObjectHandler {
10853 EvalInfo &Info;
10854 const Expr *E;
10855 QualType AllocType;
10856 const AccessKinds AccessKind;
10857 APValue *Value;
10858
10859 typedef bool result_type;
10860 bool failed() { return false; }
10861 bool checkConst(QualType QT) {
10862 if (QT.isConstQualified()) {
10863 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10864 return false;
10865 }
10866 return true;
10867 }
10868 bool found(APValue &Subobj, QualType SubobjType) {
10869 if (!checkConst(SubobjType))
10870 return false;
10871 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10872 // old name of the object to be used to name the new object.
10873 unsigned SubobjectSize = 1;
10874 unsigned AllocSize = 1;
10875 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10876 AllocSize = CAT->getZExtSize();
10877 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10878 SubobjectSize = CAT->getZExtSize();
10879 if (SubobjectSize < AllocSize ||
10880 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10881 Info.Ctx.getBaseElementType(AllocType))) {
10882 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10883 << SubobjType << AllocType;
10884 return false;
10885 }
10886 Value = &Subobj;
10887 return true;
10888 }
10889 bool found(APSInt &Value, QualType SubobjType) {
10890 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10891 return false;
10892 }
10893 bool found(APFloat &Value, QualType SubobjType) {
10894 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10895 return false;
10896 }
10897 } Handler = {Info, E, AllocType, AK, nullptr};
10898
10899 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10900 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10901 return false;
10902
10903 Val = Handler.Value;
10904
10905 // [basic.life]p1:
10906 // The lifetime of an object o of type T ends when [...] the storage
10907 // which the object occupies is [...] reused by an object that is not
10908 // nested within o (6.6.2).
10909 *Val = APValue();
10910 } else {
10911 // Perform the allocation and obtain a pointer to the resulting object.
10912 Val = Info.createHeapAlloc(E, AllocType, Result);
10913 if (!Val)
10914 return false;
10915 }
10916
10917 if (ValueInit) {
10918 ImplicitValueInitExpr VIE(AllocType);
10919 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10920 return false;
10921 } else if (ResizedArrayILE) {
10922 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10923 AllocType))
10924 return false;
10925 } else if (ResizedArrayCCE) {
10926 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10927 AllocType))
10928 return false;
10929 } else if (Init) {
10930 if (!EvaluateInPlace(*Val, Info, Result, Init))
10931 return false;
10932 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10933 return false;
10934 }
10935
10936 // Array new returns a pointer to the first element, not a pointer to the
10937 // array.
10938 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10939 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10940
10941 return true;
10942}
10943//===----------------------------------------------------------------------===//
10944// Member Pointer Evaluation
10945//===----------------------------------------------------------------------===//
10946
10947namespace {
10948class MemberPointerExprEvaluator
10949 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10950 MemberPtr &Result;
10951
10952 bool Success(const ValueDecl *D) {
10953 Result = MemberPtr(D);
10954 return true;
10955 }
10956public:
10957
10958 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10959 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10960
10961 bool Success(const APValue &V, const Expr *E) {
10962 Result.setFrom(V);
10963 return true;
10964 }
10965 bool ZeroInitialization(const Expr *E) {
10966 return Success((const ValueDecl*)nullptr);
10967 }
10968
10969 bool VisitCastExpr(const CastExpr *E);
10970 bool VisitUnaryAddrOf(const UnaryOperator *E);
10971};
10972} // end anonymous namespace
10973
10974static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10975 EvalInfo &Info) {
10976 assert(!E->isValueDependent());
10977 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10978 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10979}
10980
10981bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10982 switch (E->getCastKind()) {
10983 default:
10984 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10985
10986 case CK_NullToMemberPointer:
10987 VisitIgnoredValue(E->getSubExpr());
10988 return ZeroInitialization(E);
10989
10990 case CK_BaseToDerivedMemberPointer: {
10991 if (!Visit(E->getSubExpr()))
10992 return false;
10993 if (E->path_empty())
10994 return true;
10995 // Base-to-derived member pointer casts store the path in derived-to-base
10996 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10997 // the wrong end of the derived->base arc, so stagger the path by one class.
10998 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10999 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11000 PathI != PathE; ++PathI) {
11001 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11002 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11003 if (!Result.castToDerived(Derived))
11004 return Error(E);
11005 }
11006 if (!Result.castToDerived(E->getType()
11007 ->castAs<MemberPointerType>()
11008 ->getMostRecentCXXRecordDecl()))
11009 return Error(E);
11010 return true;
11011 }
11012
11013 case CK_DerivedToBaseMemberPointer:
11014 if (!Visit(E->getSubExpr()))
11015 return false;
11016 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11017 PathE = E->path_end(); PathI != PathE; ++PathI) {
11018 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11019 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11020 if (!Result.castToBase(Base))
11021 return Error(E);
11022 }
11023 return true;
11024 }
11025}
11026
11027bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11028 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11029 // member can be formed.
11030 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11031}
11032
11033//===----------------------------------------------------------------------===//
11034// Record Evaluation
11035//===----------------------------------------------------------------------===//
11036
11037namespace {
11038 class RecordExprEvaluator
11039 : public ExprEvaluatorBase<RecordExprEvaluator> {
11040 const LValue &This;
11041 APValue &Result;
11042 public:
11043
11044 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11045 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11046
11047 bool Success(const APValue &V, const Expr *E) {
11048 Result = V;
11049 return true;
11050 }
11051 bool ZeroInitialization(const Expr *E) {
11052 return ZeroInitialization(E, E->getType());
11053 }
11054 bool ZeroInitialization(const Expr *E, QualType T);
11055
11056 bool VisitCallExpr(const CallExpr *E) {
11057 return handleCallExpr(E, Result, &This);
11058 }
11059 bool VisitCastExpr(const CastExpr *E);
11060 bool VisitInitListExpr(const InitListExpr *E);
11061 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11062 return VisitCXXConstructExpr(E, E->getType());
11063 }
11064 bool VisitLambdaExpr(const LambdaExpr *E);
11065 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11066 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11067 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11068 bool VisitBinCmp(const BinaryOperator *E);
11069 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11070 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11071 ArrayRef<Expr *> Args);
11072 };
11073}
11074
11075/// Perform zero-initialization on an object of non-union class type.
11076/// C++11 [dcl.init]p5:
11077/// To zero-initialize an object or reference of type T means:
11078/// [...]
11079/// -- if T is a (possibly cv-qualified) non-union class type,
11080/// each non-static data member and each base-class subobject is
11081/// zero-initialized
11082static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11083 const RecordDecl *RD,
11084 const LValue &This, APValue &Result) {
11085 assert(!RD->isUnion() && "Expected non-union class type");
11086 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11087 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11088 RD->getNumFields());
11089
11090 if (RD->isInvalidDecl()) return false;
11091 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11092
11093 if (CD) {
11094 unsigned Index = 0;
11096 End = CD->bases_end(); I != End; ++I, ++Index) {
11097 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11098 LValue Subobject = This;
11099 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11100 return false;
11101 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11102 Result.getStructBase(Index)))
11103 return false;
11104 }
11105 }
11106
11107 for (const auto *I : RD->fields()) {
11108 // -- if T is a reference type, no initialization is performed.
11109 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11110 continue;
11111
11112 LValue Subobject = This;
11113 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11114 return false;
11115
11116 ImplicitValueInitExpr VIE(I->getType());
11117 if (!EvaluateInPlace(
11118 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11119 return false;
11120 }
11121
11122 return true;
11123}
11124
11125bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11126 const auto *RD = T->castAsRecordDecl();
11127 if (RD->isInvalidDecl()) return false;
11128 if (RD->isUnion()) {
11129 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11130 // object's first non-static named data member is zero-initialized
11132 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11133 ++I;
11134 if (I == RD->field_end()) {
11135 Result = APValue((const FieldDecl*)nullptr);
11136 return true;
11137 }
11138
11139 LValue Subobject = This;
11140 if (!HandleLValueMember(Info, E, Subobject, *I))
11141 return false;
11142 Result = APValue(*I);
11143 ImplicitValueInitExpr VIE(I->getType());
11144 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11145 }
11146
11147 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11148 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11149 return false;
11150 }
11151
11152 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11153}
11154
11155bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11156 switch (E->getCastKind()) {
11157 default:
11158 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11159
11160 case CK_ConstructorConversion:
11161 return Visit(E->getSubExpr());
11162
11163 case CK_DerivedToBase:
11164 case CK_UncheckedDerivedToBase: {
11165 APValue DerivedObject;
11166 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11167 return false;
11168 if (!DerivedObject.isStruct())
11169 return Error(E->getSubExpr());
11170
11171 // Derived-to-base rvalue conversion: just slice off the derived part.
11172 APValue *Value = &DerivedObject;
11173 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11174 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11175 PathE = E->path_end(); PathI != PathE; ++PathI) {
11176 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11177 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11178 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11179 RD = Base;
11180 }
11181 Result = *Value;
11182 return true;
11183 }
11184 case CK_HLSLAggregateSplatCast: {
11185 APValue Val;
11186 QualType ValTy;
11187
11188 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11189 return false;
11190
11191 unsigned NEls = elementwiseSize(Info, E->getType());
11192 // splat our Val
11193 SmallVector<APValue> SplatEls(NEls, Val);
11194 SmallVector<QualType> SplatType(NEls, ValTy);
11195
11196 // cast the elements and construct our struct result
11197 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11198 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11199 SplatType))
11200 return false;
11201
11202 return true;
11203 }
11204 case CK_HLSLElementwiseCast: {
11205 SmallVector<APValue> SrcEls;
11206 SmallVector<QualType> SrcTypes;
11207
11208 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11209 SrcTypes))
11210 return false;
11211
11212 // cast the elements and construct our struct result
11213 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11214 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11215 SrcTypes))
11216 return false;
11217
11218 return true;
11219 }
11220 }
11221}
11222
11223bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11224 if (E->isTransparent())
11225 return Visit(E->getInit(0));
11226 return VisitCXXParenListOrInitListExpr(E, E->inits());
11227}
11228
11229bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11230 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11231 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11232 if (RD->isInvalidDecl()) return false;
11233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11234 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11235
11236 EvalInfo::EvaluatingConstructorRAII EvalObj(
11237 Info,
11238 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11239 CXXRD && CXXRD->getNumBases());
11240
11241 if (RD->isUnion()) {
11242 const FieldDecl *Field;
11243 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11244 Field = ILE->getInitializedFieldInUnion();
11245 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11246 Field = PLIE->getInitializedFieldInUnion();
11247 } else {
11248 llvm_unreachable(
11249 "Expression is neither an init list nor a C++ paren list");
11250 }
11251
11252 Result = APValue(Field);
11253 if (!Field)
11254 return true;
11255
11256 // If the initializer list for a union does not contain any elements, the
11257 // first element of the union is value-initialized.
11258 // FIXME: The element should be initialized from an initializer list.
11259 // Is this difference ever observable for initializer lists which
11260 // we don't build?
11261 ImplicitValueInitExpr VIE(Field->getType());
11262 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11263
11264 LValue Subobject = This;
11265 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11266 return false;
11267
11268 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11269 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11270 isa<CXXDefaultInitExpr>(InitExpr));
11271
11272 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11273 if (Field->isBitField())
11274 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11275 Field);
11276 return true;
11277 }
11278
11279 return false;
11280 }
11281
11282 if (!Result.hasValue())
11283 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11284 RD->getNumFields());
11285 unsigned ElementNo = 0;
11286 bool Success = true;
11287
11288 // Initialize base classes.
11289 if (CXXRD && CXXRD->getNumBases()) {
11290 for (const auto &Base : CXXRD->bases()) {
11291 assert(ElementNo < Args.size() && "missing init for base class");
11292 const Expr *Init = Args[ElementNo];
11293
11294 LValue Subobject = This;
11295 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11296 return false;
11297
11298 APValue &FieldVal = Result.getStructBase(ElementNo);
11299 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11300 if (!Info.noteFailure())
11301 return false;
11302 Success = false;
11303 }
11304 ++ElementNo;
11305 }
11306
11307 EvalObj.finishedConstructingBases();
11308 }
11309
11310 // Initialize members.
11311 for (const auto *Field : RD->fields()) {
11312 // Anonymous bit-fields are not considered members of the class for
11313 // purposes of aggregate initialization.
11314 if (Field->isUnnamedBitField())
11315 continue;
11316
11317 LValue Subobject = This;
11318
11319 bool HaveInit = ElementNo < Args.size();
11320
11321 // FIXME: Diagnostics here should point to the end of the initializer
11322 // list, not the start.
11323 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11324 Subobject, Field, &Layout))
11325 return false;
11326
11327 // Perform an implicit value-initialization for members beyond the end of
11328 // the initializer list.
11329 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11330 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11331
11332 if (Field->getType()->isIncompleteArrayType()) {
11333 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11334 if (!CAT->isZeroSize()) {
11335 // Bail out for now. This might sort of "work", but the rest of the
11336 // code isn't really prepared to handle it.
11337 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11338 return false;
11339 }
11340 }
11341 }
11342
11343 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11344 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11346
11347 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11348 if (Field->getType()->isReferenceType()) {
11349 LValue Result;
11351 FieldVal)) {
11352 if (!Info.noteFailure())
11353 return false;
11354 Success = false;
11355 }
11356 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11357 (Field->isBitField() &&
11358 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11359 if (!Info.noteFailure())
11360 return false;
11361 Success = false;
11362 }
11363 }
11364
11365 EvalObj.finishedConstructingFields();
11366
11367 return Success;
11368}
11369
11370bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11371 QualType T) {
11372 // Note that E's type is not necessarily the type of our class here; we might
11373 // be initializing an array element instead.
11374 const CXXConstructorDecl *FD = E->getConstructor();
11375 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11376
11377 bool ZeroInit = E->requiresZeroInitialization();
11378 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11379 if (ZeroInit)
11380 return ZeroInitialization(E, T);
11381
11382 return handleDefaultInitValue(T, Result);
11383 }
11384
11385 const FunctionDecl *Definition = nullptr;
11386 auto Body = FD->getBody(Definition);
11387
11388 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11389 return false;
11390
11391 // Avoid materializing a temporary for an elidable copy/move constructor.
11392 if (E->isElidable() && !ZeroInit) {
11393 // FIXME: This only handles the simplest case, where the source object
11394 // is passed directly as the first argument to the constructor.
11395 // This should also handle stepping though implicit casts and
11396 // and conversion sequences which involve two steps, with a
11397 // conversion operator followed by a converting constructor.
11398 const Expr *SrcObj = E->getArg(0);
11399 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11400 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11401 if (const MaterializeTemporaryExpr *ME =
11402 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11403 return Visit(ME->getSubExpr());
11404 }
11405
11406 if (ZeroInit && !ZeroInitialization(E, T))
11407 return false;
11408
11409 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11410 return HandleConstructorCall(E, This, Args,
11412 Result);
11413}
11414
11415bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11416 const CXXInheritedCtorInitExpr *E) {
11417 if (!Info.CurrentCall) {
11418 assert(Info.checkingPotentialConstantExpression());
11419 return false;
11420 }
11421
11422 const CXXConstructorDecl *FD = E->getConstructor();
11423 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11424 return false;
11425
11426 const FunctionDecl *Definition = nullptr;
11427 auto Body = FD->getBody(Definition);
11428
11429 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11430 return false;
11431
11432 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11434 Result);
11435}
11436
11437bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11438 const CXXStdInitializerListExpr *E) {
11439 const ConstantArrayType *ArrayType =
11440 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11441
11442 LValue Array;
11443 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11444 return false;
11445
11446 assert(ArrayType && "unexpected type for array initializer");
11447
11448 // Get a pointer to the first element of the array.
11449 Array.addArray(Info, E, ArrayType);
11450
11451 // FIXME: What if the initializer_list type has base classes, etc?
11452 Result = APValue(APValue::UninitStruct(), 0, 2);
11453 Array.moveInto(Result.getStructField(0));
11454
11455 auto *Record = E->getType()->castAsRecordDecl();
11456 RecordDecl::field_iterator Field = Record->field_begin();
11457 assert(Field != Record->field_end() &&
11458 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11459 ArrayType->getElementType()) &&
11460 "Expected std::initializer_list first field to be const E *");
11461 ++Field;
11462 assert(Field != Record->field_end() &&
11463 "Expected std::initializer_list to have two fields");
11464
11465 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11466 // Length.
11467 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11468 } else {
11469 // End pointer.
11470 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11471 ArrayType->getElementType()) &&
11472 "Expected std::initializer_list second field to be const E *");
11473 if (!HandleLValueArrayAdjustment(Info, E, Array,
11474 ArrayType->getElementType(),
11475 ArrayType->getZExtSize()))
11476 return false;
11477 Array.moveInto(Result.getStructField(1));
11478 }
11479
11480 assert(++Field == Record->field_end() &&
11481 "Expected std::initializer_list to only have two fields");
11482
11483 return true;
11484}
11485
11486bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11487 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11488 if (ClosureClass->isInvalidDecl())
11489 return false;
11490
11491 const size_t NumFields = ClosureClass->getNumFields();
11492
11493 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11494 E->capture_init_end()) &&
11495 "The number of lambda capture initializers should equal the number of "
11496 "fields within the closure type");
11497
11498 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11499 // Iterate through all the lambda's closure object's fields and initialize
11500 // them.
11501 auto *CaptureInitIt = E->capture_init_begin();
11502 bool Success = true;
11503 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11504 for (const auto *Field : ClosureClass->fields()) {
11505 assert(CaptureInitIt != E->capture_init_end());
11506 // Get the initializer for this field
11507 Expr *const CurFieldInit = *CaptureInitIt++;
11508
11509 // If there is no initializer, either this is a VLA or an error has
11510 // occurred.
11511 if (!CurFieldInit || CurFieldInit->containsErrors())
11512 return Error(E);
11513
11514 LValue Subobject = This;
11515
11516 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11517 return false;
11518
11519 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11520 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11521 if (!Info.keepEvaluatingAfterFailure())
11522 return false;
11523 Success = false;
11524 }
11525 }
11526 return Success;
11527}
11528
11529static bool EvaluateRecord(const Expr *E, const LValue &This,
11530 APValue &Result, EvalInfo &Info) {
11531 assert(!E->isValueDependent());
11532 assert(E->isPRValue() && E->getType()->isRecordType() &&
11533 "can't evaluate expression as a record rvalue");
11534 return RecordExprEvaluator(Info, This, Result).Visit(E);
11535}
11536
11537//===----------------------------------------------------------------------===//
11538// Temporary Evaluation
11539//
11540// Temporaries are represented in the AST as rvalues, but generally behave like
11541// lvalues. The full-object of which the temporary is a subobject is implicitly
11542// materialized so that a reference can bind to it.
11543//===----------------------------------------------------------------------===//
11544namespace {
11545class TemporaryExprEvaluator
11546 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11547public:
11548 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11549 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11550
11551 /// Visit an expression which constructs the value of this temporary.
11552 bool VisitConstructExpr(const Expr *E) {
11553 APValue &Value = Info.CurrentCall->createTemporary(
11554 E, E->getType(), ScopeKind::FullExpression, Result);
11555 return EvaluateInPlace(Value, Info, Result, E);
11556 }
11557
11558 bool VisitCastExpr(const CastExpr *E) {
11559 switch (E->getCastKind()) {
11560 default:
11561 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11562
11563 case CK_ConstructorConversion:
11564 return VisitConstructExpr(E->getSubExpr());
11565 }
11566 }
11567 bool VisitInitListExpr(const InitListExpr *E) {
11568 return VisitConstructExpr(E);
11569 }
11570 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11571 return VisitConstructExpr(E);
11572 }
11573 bool VisitCallExpr(const CallExpr *E) {
11574 return VisitConstructExpr(E);
11575 }
11576 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11577 return VisitConstructExpr(E);
11578 }
11579 bool VisitLambdaExpr(const LambdaExpr *E) {
11580 return VisitConstructExpr(E);
11581 }
11582};
11583} // end anonymous namespace
11584
11585/// Evaluate an expression of record type as a temporary.
11586static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11587 assert(!E->isValueDependent());
11588 assert(E->isPRValue() && E->getType()->isRecordType());
11589 return TemporaryExprEvaluator(Info, Result).Visit(E);
11590}
11591
11592//===----------------------------------------------------------------------===//
11593// Vector Evaluation
11594//===----------------------------------------------------------------------===//
11595
11596namespace {
11597 class VectorExprEvaluator
11598 : public ExprEvaluatorBase<VectorExprEvaluator> {
11599 APValue &Result;
11600 public:
11601
11602 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11603 : ExprEvaluatorBaseTy(info), Result(Result) {}
11604
11605 bool Success(ArrayRef<APValue> V, const Expr *E) {
11606 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11607 // FIXME: remove this APValue copy.
11608 Result = APValue(V.data(), V.size());
11609 return true;
11610 }
11611 bool Success(const APValue &V, const Expr *E) {
11612 assert(V.isVector());
11613 Result = V;
11614 return true;
11615 }
11616 bool ZeroInitialization(const Expr *E);
11617
11618 bool VisitUnaryReal(const UnaryOperator *E)
11619 { return Visit(E->getSubExpr()); }
11620 bool VisitCastExpr(const CastExpr* E);
11621 bool VisitInitListExpr(const InitListExpr *E);
11622 bool VisitUnaryImag(const UnaryOperator *E);
11623 bool VisitBinaryOperator(const BinaryOperator *E);
11624 bool VisitUnaryOperator(const UnaryOperator *E);
11625 bool VisitCallExpr(const CallExpr *E);
11626 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11627 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11628
11629 // FIXME: Missing: conditional operator (for GNU
11630 // conditional select), ExtVectorElementExpr
11631 };
11632} // end anonymous namespace
11633
11634static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11635 assert(E->isPRValue() && E->getType()->isVectorType() &&
11636 "not a vector prvalue");
11637 return VectorExprEvaluator(Info, Result).Visit(E);
11638}
11639
11640static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11641 assert(Val.isVector() && "expected vector APValue");
11642 unsigned NumElts = Val.getVectorLength();
11643
11644 // Each element is one bit, so create an integer with NumElts bits.
11645 llvm::APInt Result(NumElts, 0);
11646
11647 for (unsigned I = 0; I < NumElts; ++I) {
11648 const APValue &Elt = Val.getVectorElt(I);
11649 assert(Elt.isInt() && "expected integer element in bool vector");
11650
11651 if (Elt.getInt().getBoolValue())
11652 Result.setBit(I);
11653 }
11654
11655 return Result;
11656}
11657
11658bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11659 const VectorType *VTy = E->getType()->castAs<VectorType>();
11660 unsigned NElts = VTy->getNumElements();
11661
11662 const Expr *SE = E->getSubExpr();
11663 QualType SETy = SE->getType();
11664
11665 switch (E->getCastKind()) {
11666 case CK_VectorSplat: {
11667 APValue Val = APValue();
11668 if (SETy->isIntegerType()) {
11669 APSInt IntResult;
11670 if (!EvaluateInteger(SE, IntResult, Info))
11671 return false;
11672 Val = APValue(std::move(IntResult));
11673 } else if (SETy->isRealFloatingType()) {
11674 APFloat FloatResult(0.0);
11675 if (!EvaluateFloat(SE, FloatResult, Info))
11676 return false;
11677 Val = APValue(std::move(FloatResult));
11678 } else {
11679 return Error(E);
11680 }
11681
11682 // Splat and create vector APValue.
11683 SmallVector<APValue, 4> Elts(NElts, Val);
11684 return Success(Elts, E);
11685 }
11686 case CK_BitCast: {
11687 APValue SVal;
11688 if (!Evaluate(SVal, Info, SE))
11689 return false;
11690
11691 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11692 // Give up if the input isn't an int, float, or vector. For example, we
11693 // reject "(v4i16)(intptr_t)&a".
11694 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11695 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11696 << Info.Ctx.getLangOpts().CPlusPlus;
11697 return false;
11698 }
11699
11700 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11701 return false;
11702
11703 return true;
11704 }
11705 case CK_HLSLVectorTruncation: {
11706 APValue Val;
11707 SmallVector<APValue, 4> Elements;
11708 if (!EvaluateVector(SE, Val, Info))
11709 return Error(E);
11710 for (unsigned I = 0; I < NElts; I++)
11711 Elements.push_back(Val.getVectorElt(I));
11712 return Success(Elements, E);
11713 }
11714 case CK_HLSLMatrixTruncation: {
11715 // Matrix truncation occurs in row-major order.
11716 APValue Val;
11717 if (!EvaluateMatrix(SE, Val, Info))
11718 return Error(E);
11719 SmallVector<APValue, 16> Elements;
11720 for (unsigned Row = 0;
11721 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
11722 for (unsigned Col = 0;
11723 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
11724 Elements.push_back(Val.getMatrixElt(Row, Col));
11725 return Success(Elements, E);
11726 }
11727 case CK_HLSLAggregateSplatCast: {
11728 APValue Val;
11729 QualType ValTy;
11730
11731 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11732 return false;
11733
11734 // cast our Val once.
11736 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11737 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11738 Result))
11739 return false;
11740
11741 SmallVector<APValue, 4> SplatEls(NElts, Result);
11742 return Success(SplatEls, E);
11743 }
11744 case CK_HLSLElementwiseCast: {
11745 SmallVector<APValue> SrcVals;
11746 SmallVector<QualType> SrcTypes;
11747
11748 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11749 return false;
11750
11751 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11752 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11753 SmallVector<APValue, 4> ResultEls(NElts);
11754 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11755 ResultEls))
11756 return false;
11757 return Success(ResultEls, E);
11758 }
11759 default:
11760 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11761 }
11762}
11763
11764bool
11765VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11766 const VectorType *VT = E->getType()->castAs<VectorType>();
11767 unsigned NumInits = E->getNumInits();
11768 unsigned NumElements = VT->getNumElements();
11769
11770 QualType EltTy = VT->getElementType();
11771 SmallVector<APValue, 4> Elements;
11772
11773 // MFloat8 type doesn't have constants and thus constant folding
11774 // is impossible.
11775 if (EltTy->isMFloat8Type())
11776 return false;
11777
11778 // The number of initializers can be less than the number of
11779 // vector elements. For OpenCL, this can be due to nested vector
11780 // initialization. For GCC compatibility, missing trailing elements
11781 // should be initialized with zeroes.
11782 unsigned CountInits = 0, CountElts = 0;
11783 while (CountElts < NumElements) {
11784 // Handle nested vector initialization.
11785 if (CountInits < NumInits
11786 && E->getInit(CountInits)->getType()->isVectorType()) {
11787 APValue v;
11788 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11789 return Error(E);
11790 unsigned vlen = v.getVectorLength();
11791 for (unsigned j = 0; j < vlen; j++)
11792 Elements.push_back(v.getVectorElt(j));
11793 CountElts += vlen;
11794 } else if (EltTy->isIntegerType()) {
11795 llvm::APSInt sInt(32);
11796 if (CountInits < NumInits) {
11797 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11798 return false;
11799 } else // trailing integer zero.
11800 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11801 Elements.push_back(APValue(sInt));
11802 CountElts++;
11803 } else {
11804 llvm::APFloat f(0.0);
11805 if (CountInits < NumInits) {
11806 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11807 return false;
11808 } else // trailing float zero.
11809 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11810 Elements.push_back(APValue(f));
11811 CountElts++;
11812 }
11813 CountInits++;
11814 }
11815 return Success(Elements, E);
11816}
11817
11818bool
11819VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11820 const auto *VT = E->getType()->castAs<VectorType>();
11821 QualType EltTy = VT->getElementType();
11822 APValue ZeroElement;
11823 if (EltTy->isIntegerType())
11824 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11825 else
11826 ZeroElement =
11827 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11828
11829 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11830 return Success(Elements, E);
11831}
11832
11833bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11834 VisitIgnoredValue(E->getSubExpr());
11835 return ZeroInitialization(E);
11836}
11837
11838bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11839 BinaryOperatorKind Op = E->getOpcode();
11840 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11841 "Operation not supported on vector types");
11842
11843 if (Op == BO_Comma)
11844 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11845
11846 Expr *LHS = E->getLHS();
11847 Expr *RHS = E->getRHS();
11848
11849 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11850 "Must both be vector types");
11851 // Checking JUST the types are the same would be fine, except shifts don't
11852 // need to have their types be the same (since you always shift by an int).
11853 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11854 E->getType()->castAs<VectorType>()->getNumElements() &&
11855 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11856 E->getType()->castAs<VectorType>()->getNumElements() &&
11857 "All operands must be the same size.");
11858
11859 APValue LHSValue;
11860 APValue RHSValue;
11861 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11862 if (!LHSOK && !Info.noteFailure())
11863 return false;
11864 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11865 return false;
11866
11867 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11868 return false;
11869
11870 return Success(LHSValue, E);
11871}
11872
11873static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11874 QualType ResultTy,
11876 APValue Elt) {
11877 switch (Op) {
11878 case UO_Plus:
11879 // Nothing to do here.
11880 return Elt;
11881 case UO_Minus:
11882 if (Elt.getKind() == APValue::Int) {
11883 Elt.getInt().negate();
11884 } else {
11885 assert(Elt.getKind() == APValue::Float &&
11886 "Vector can only be int or float type");
11887 Elt.getFloat().changeSign();
11888 }
11889 return Elt;
11890 case UO_Not:
11891 // This is only valid for integral types anyway, so we don't have to handle
11892 // float here.
11893 assert(Elt.getKind() == APValue::Int &&
11894 "Vector operator ~ can only be int");
11895 Elt.getInt().flipAllBits();
11896 return Elt;
11897 case UO_LNot: {
11898 if (Elt.getKind() == APValue::Int) {
11899 Elt.getInt() = !Elt.getInt();
11900 // operator ! on vectors returns -1 for 'truth', so negate it.
11901 Elt.getInt().negate();
11902 return Elt;
11903 }
11904 assert(Elt.getKind() == APValue::Float &&
11905 "Vector can only be int or float type");
11906 // Float types result in an int of the same size, but -1 for true, or 0 for
11907 // false.
11908 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11909 ResultTy->isUnsignedIntegerType()};
11910 if (Elt.getFloat().isZero())
11911 EltResult.setAllBits();
11912 else
11913 EltResult.clearAllBits();
11914
11915 return APValue{EltResult};
11916 }
11917 default:
11918 // FIXME: Implement the rest of the unary operators.
11919 return std::nullopt;
11920 }
11921}
11922
11923bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11924 Expr *SubExpr = E->getSubExpr();
11925 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11926 // This result element type differs in the case of negating a floating point
11927 // vector, since the result type is the a vector of the equivilant sized
11928 // integer.
11929 const QualType ResultEltTy = VD->getElementType();
11930 UnaryOperatorKind Op = E->getOpcode();
11931
11932 APValue SubExprValue;
11933 if (!Evaluate(SubExprValue, Info, SubExpr))
11934 return false;
11935
11936 // FIXME: This vector evaluator someday needs to be changed to be LValue
11937 // aware/keep LValue information around, rather than dealing with just vector
11938 // types directly. Until then, we cannot handle cases where the operand to
11939 // these unary operators is an LValue. The only case I've been able to see
11940 // cause this is operator++ assigning to a member expression (only valid in
11941 // altivec compilations) in C mode, so this shouldn't limit us too much.
11942 if (SubExprValue.isLValue())
11943 return false;
11944
11945 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11946 "Vector length doesn't match type?");
11947
11948 SmallVector<APValue, 4> ResultElements;
11949 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11950 std::optional<APValue> Elt = handleVectorUnaryOperator(
11951 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11952 if (!Elt)
11953 return false;
11954 ResultElements.push_back(*Elt);
11955 }
11956 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11957}
11958
11959static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11960 const Expr *E, QualType SourceTy,
11961 QualType DestTy, APValue const &Original,
11962 APValue &Result) {
11963 if (SourceTy->isIntegerType()) {
11964 if (DestTy->isRealFloatingType()) {
11965 Result = APValue(APFloat(0.0));
11966 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11967 DestTy, Result.getFloat());
11968 }
11969 if (DestTy->isIntegerType()) {
11970 Result = APValue(
11971 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11972 return true;
11973 }
11974 } else if (SourceTy->isRealFloatingType()) {
11975 if (DestTy->isRealFloatingType()) {
11976 Result = Original;
11977 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11978 Result.getFloat());
11979 }
11980 if (DestTy->isIntegerType()) {
11981 Result = APValue(APSInt());
11982 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11983 DestTy, Result.getInt());
11984 }
11985 }
11986
11987 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11988 << SourceTy << DestTy;
11989 return false;
11990}
11991
11992static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
11993 llvm::function_ref<APInt(const APSInt &)> PackFn) {
11994 APValue LHS, RHS;
11995 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
11996 !EvaluateAsRValue(Info, E->getArg(1), RHS))
11997 return false;
11998
11999 unsigned LHSVecLen = LHS.getVectorLength();
12000 unsigned RHSVecLen = RHS.getVectorLength();
12001
12002 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12003 "pack builtin LHSVecLen must equal to RHSVecLen");
12004
12005 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12006 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12007
12008 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12009 QualType DstElemTy = DstVT->getElementType();
12010 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12011
12012 const unsigned SrcPerLane = 128 / SrcBits;
12013 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12014
12016 Out.reserve(LHSVecLen + RHSVecLen);
12017
12018 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12019 unsigned base = Lane * SrcPerLane;
12020 for (unsigned I = 0; I != SrcPerLane; ++I)
12021 Out.emplace_back(APValue(
12022 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12023 for (unsigned I = 0; I != SrcPerLane; ++I)
12024 Out.emplace_back(APValue(
12025 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12026 }
12027
12028 Result = APValue(Out.data(), Out.size());
12029 return true;
12030}
12031
12033 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12034 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12035 GetSourceIndex) {
12036
12037 const auto *VT = Call->getType()->getAs<VectorType>();
12038 if (!VT)
12039 return false;
12040
12041 unsigned ShuffleMask = 0;
12042 APValue A, MaskVector, B;
12043 bool IsVectorMask = false;
12044 bool IsSingleOperand = (Call->getNumArgs() == 2);
12045
12046 if (IsSingleOperand) {
12047 QualType MaskType = Call->getArg(1)->getType();
12048 if (MaskType->isVectorType()) {
12049 IsVectorMask = true;
12050 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12051 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12052 return false;
12053 B = A;
12054 } else if (MaskType->isIntegerType()) {
12055 APSInt MaskImm;
12056 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12057 return false;
12058 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12059 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12060 return false;
12061 B = A;
12062 } else {
12063 return false;
12064 }
12065 } else {
12066 QualType Arg2Type = Call->getArg(2)->getType();
12067 if (Arg2Type->isVectorType()) {
12068 IsVectorMask = true;
12069 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12070 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12071 !EvaluateAsRValue(Info, Call->getArg(2), B))
12072 return false;
12073 } else if (Arg2Type->isIntegerType()) {
12074 APSInt MaskImm;
12075 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12076 return false;
12077 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12078 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12079 !EvaluateAsRValue(Info, Call->getArg(1), B))
12080 return false;
12081 } else {
12082 return false;
12083 }
12084 }
12085
12086 unsigned NumElts = VT->getNumElements();
12087 SmallVector<APValue, 64> ResultElements;
12088 ResultElements.reserve(NumElts);
12089
12090 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12091 if (IsVectorMask) {
12092 ShuffleMask = static_cast<unsigned>(
12093 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12094 }
12095 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12096
12097 if (SrcIdx < 0) {
12098 // Zero out this element
12099 QualType ElemTy = VT->getElementType();
12100 if (ElemTy->isRealFloatingType()) {
12101 ResultElements.push_back(
12102 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12103 } else if (ElemTy->isIntegerType()) {
12104 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12105 ResultElements.push_back(APValue(Zero));
12106 } else {
12107 // Other types of fallback logic
12108 ResultElements.push_back(APValue());
12109 }
12110 } else {
12111 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12112 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12113 }
12114 }
12115
12116 Out = APValue(ResultElements.data(), ResultElements.size());
12117 return true;
12118}
12119static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12120 APFloat OrigVal, APValue &Result) {
12121
12122 if (OrigVal.isInfinity()) {
12123 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12124 return false;
12125 }
12126 if (OrigVal.isNaN()) {
12127 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12128 return false;
12129 }
12130
12131 APFloat Val = OrigVal;
12132 bool LosesInfo = false;
12133 APFloat::opStatus Status = Val.convert(
12134 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12135
12136 if (LosesInfo || Val.isDenormal()) {
12137 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12138 return false;
12139 }
12140
12141 if (Status != APFloat::opOK) {
12142 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12143 return false;
12144 }
12145
12146 Result = APValue(Val);
12147 return true;
12148}
12150 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12151 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12152 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12153
12154 APValue Source, Count;
12155 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12156 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12157 return false;
12158
12159 assert(Call->getNumArgs() == 2);
12160
12161 QualType SourceTy = Call->getArg(0)->getType();
12162 assert(SourceTy->isVectorType() &&
12163 Call->getArg(1)->getType()->isVectorType());
12164
12165 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12166 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12167 unsigned DestLen = Source.getVectorLength();
12168 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12169 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12170 unsigned NumBitsInQWord = 64;
12171 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12173 Result.reserve(DestLen);
12174
12175 uint64_t CountLQWord = 0;
12176 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12177 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12178 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12179 }
12180
12181 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12182 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12183 if (CountLQWord < DestEltWidth) {
12184 Result.push_back(
12185 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12186 } else {
12187 Result.push_back(
12188 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12189 }
12190 }
12191 Out = APValue(Result.data(), Result.size());
12192 return true;
12193}
12194
12195std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12196 std::optional<APSInt> RoundingMode,
12197 bool IsMin) {
12198 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12199 if (RoundingMode.value_or(DefaultMode) != 4)
12200 return std::nullopt;
12201 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12202 B.isInfinity() || B.isDenormal())
12203 return std::nullopt;
12204 if (A.isZero() && B.isZero())
12205 return B;
12206 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12207}
12208
12209bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12210 if (!IsConstantEvaluatedBuiltinCall(E))
12211 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12212
12213 auto EvaluateBinOpExpr =
12214 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12215 APValue SourceLHS, SourceRHS;
12216 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12217 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12218 return false;
12219
12220 auto *DestTy = E->getType()->castAs<VectorType>();
12221 QualType DestEltTy = DestTy->getElementType();
12222 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12223 unsigned SourceLen = SourceLHS.getVectorLength();
12224 SmallVector<APValue, 4> ResultElements;
12225 ResultElements.reserve(SourceLen);
12226
12227 if (SourceRHS.isInt()) {
12228 const APSInt &RHS = SourceRHS.getInt();
12229 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12230 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12231 ResultElements.push_back(
12232 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12233 }
12234 } else {
12235 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12236 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12237 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12238 ResultElements.push_back(
12239 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12240 }
12241 }
12242 return Success(APValue(ResultElements.data(), SourceLen), E);
12243 };
12244
12245 auto EvaluateFpBinOpExpr =
12246 [&](llvm::function_ref<std::optional<APFloat>(
12247 const APFloat &, const APFloat &, std::optional<APSInt>)>
12248 Fn,
12249 bool IsScalar = false) {
12250 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12251 APValue A, B;
12252 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12253 !EvaluateAsRValue(Info, E->getArg(1), B))
12254 return false;
12255
12256 assert(A.isVector() && B.isVector());
12257 assert(A.getVectorLength() == B.getVectorLength());
12258
12259 std::optional<APSInt> RoundingMode;
12260 if (E->getNumArgs() == 3) {
12261 APSInt Imm;
12262 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12263 return false;
12264 RoundingMode = Imm;
12265 }
12266
12267 unsigned NumElems = A.getVectorLength();
12268 SmallVector<APValue, 4> ResultElements;
12269 ResultElements.reserve(NumElems);
12270
12271 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12272 if (IsScalar && EltNum > 0) {
12273 ResultElements.push_back(A.getVectorElt(EltNum));
12274 continue;
12275 }
12276 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12277 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12278 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12279 if (!Result)
12280 return false;
12281 ResultElements.push_back(APValue(*Result));
12282 }
12283 return Success(APValue(ResultElements.data(), NumElems), E);
12284 };
12285
12286 auto EvaluateScalarFpRoundMaskBinOp =
12287 [&](llvm::function_ref<std::optional<APFloat>(
12288 const APFloat &, const APFloat &, std::optional<APSInt>)>
12289 Fn) {
12290 assert(E->getNumArgs() == 5);
12291 APValue VecA, VecB, VecSrc;
12292 APSInt MaskVal, Rounding;
12293
12294 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12295 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12296 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12297 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12298 !EvaluateInteger(E->getArg(4), Rounding, Info))
12299 return false;
12300
12301 unsigned NumElems = VecA.getVectorLength();
12302 SmallVector<APValue, 8> ResultElements;
12303 ResultElements.reserve(NumElems);
12304
12305 if (MaskVal.getZExtValue() & 1) {
12306 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12307 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12308 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12309 if (!Result)
12310 return false;
12311 ResultElements.push_back(APValue(*Result));
12312 } else {
12313 ResultElements.push_back(VecSrc.getVectorElt(0));
12314 }
12315
12316 for (unsigned I = 1; I < NumElems; ++I)
12317 ResultElements.push_back(VecA.getVectorElt(I));
12318
12319 return Success(APValue(ResultElements.data(), NumElems), E);
12320 };
12321
12322 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12323 APSInt Mask;
12324 APValue AVal, WVal;
12325 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12326 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12327 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12328 return false;
12329
12330 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12332 Res.reserve(Len);
12333 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12334 for (unsigned I = 1; I < Len; ++I)
12335 Res.push_back(WVal.getVectorElt(I));
12336 APValue V(Res.data(), Res.size());
12337 return Success(V, E);
12338 };
12339
12340 switch (E->getBuiltinCallee()) {
12341 default:
12342 return false;
12343 case Builtin::BI__builtin_elementwise_popcount:
12344 case Builtin::BI__builtin_elementwise_bitreverse: {
12345 APValue Source;
12346 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12347 return false;
12348
12349 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12350 unsigned SourceLen = Source.getVectorLength();
12351 SmallVector<APValue, 4> ResultElements;
12352 ResultElements.reserve(SourceLen);
12353
12354 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12355 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12356 switch (E->getBuiltinCallee()) {
12357 case Builtin::BI__builtin_elementwise_popcount:
12358 ResultElements.push_back(APValue(
12359 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12360 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12361 break;
12362 case Builtin::BI__builtin_elementwise_bitreverse:
12363 ResultElements.push_back(
12364 APValue(APSInt(Elt.reverseBits(),
12365 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12366 break;
12367 }
12368 }
12369
12370 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12371 }
12372 case Builtin::BI__builtin_elementwise_abs: {
12373 APValue Source;
12374 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12375 return false;
12376
12377 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12378 unsigned SourceLen = Source.getVectorLength();
12379 SmallVector<APValue, 4> ResultElements;
12380 ResultElements.reserve(SourceLen);
12381
12382 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12383 APValue CurrentEle = Source.getVectorElt(EltNum);
12384 APValue Val = DestEltTy->isFloatingType()
12385 ? APValue(llvm::abs(CurrentEle.getFloat()))
12386 : APValue(APSInt(
12387 CurrentEle.getInt().abs(),
12388 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12389 ResultElements.push_back(Val);
12390 }
12391
12392 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12393 }
12394
12395 case Builtin::BI__builtin_elementwise_add_sat:
12396 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12397 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12398 });
12399
12400 case Builtin::BI__builtin_elementwise_sub_sat:
12401 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12402 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12403 });
12404
12405 case X86::BI__builtin_ia32_extract128i256:
12406 case X86::BI__builtin_ia32_vextractf128_pd256:
12407 case X86::BI__builtin_ia32_vextractf128_ps256:
12408 case X86::BI__builtin_ia32_vextractf128_si256: {
12409 APValue SourceVec, SourceImm;
12410 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12411 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12412 return false;
12413
12414 if (!SourceVec.isVector())
12415 return false;
12416
12417 const auto *RetVT = E->getType()->castAs<VectorType>();
12418 unsigned RetLen = RetVT->getNumElements();
12419 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12420
12421 SmallVector<APValue, 32> ResultElements;
12422 ResultElements.reserve(RetLen);
12423
12424 for (unsigned I = 0; I < RetLen; I++)
12425 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12426
12427 return Success(APValue(ResultElements.data(), RetLen), E);
12428 }
12429
12430 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12431 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12432 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12433 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12434 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12435 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12436 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12437 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12438 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12439 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12440 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12441 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12442 assert(E->getNumArgs() == 1);
12443 APSInt Mask;
12444 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12445 return false;
12446
12447 QualType VecTy = E->getType();
12448 const VectorType *VT = VecTy->castAs<VectorType>();
12449 unsigned VectorLen = VT->getNumElements();
12450 QualType ElemTy = VT->getElementType();
12451 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12452
12454 for (unsigned I = 0; I != VectorLen; ++I) {
12455 bool BitSet = Mask[I];
12456 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12457 if (BitSet) {
12458 ElemVal.setAllBits();
12459 }
12460 Elems.push_back(APValue(ElemVal));
12461 }
12462 return Success(APValue(Elems.data(), VectorLen), E);
12463 }
12464
12465 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12466 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12467 case X86::BI__builtin_ia32_extracti32x4_mask:
12468 case X86::BI__builtin_ia32_extractf32x4_mask:
12469 case X86::BI__builtin_ia32_extracti32x8_mask:
12470 case X86::BI__builtin_ia32_extractf32x8_mask:
12471 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12472 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12473 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12474 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12475 case X86::BI__builtin_ia32_extracti64x4_mask:
12476 case X86::BI__builtin_ia32_extractf64x4_mask: {
12477 APValue SourceVec, MergeVec;
12478 APSInt Imm, MaskImm;
12479
12480 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12481 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12482 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12483 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12484 return false;
12485
12486 const auto *RetVT = E->getType()->castAs<VectorType>();
12487 unsigned RetLen = RetVT->getNumElements();
12488
12489 if (!SourceVec.isVector() || !MergeVec.isVector())
12490 return false;
12491 unsigned SrcLen = SourceVec.getVectorLength();
12492 unsigned Lanes = SrcLen / RetLen;
12493 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12494 unsigned Base = Lane * RetLen;
12495
12496 SmallVector<APValue, 32> ResultElements;
12497 ResultElements.reserve(RetLen);
12498 for (unsigned I = 0; I < RetLen; ++I) {
12499 if (MaskImm[I])
12500 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12501 else
12502 ResultElements.push_back(MergeVec.getVectorElt(I));
12503 }
12504 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12505 }
12506
12507 case clang::X86::BI__builtin_ia32_pavgb128:
12508 case clang::X86::BI__builtin_ia32_pavgw128:
12509 case clang::X86::BI__builtin_ia32_pavgb256:
12510 case clang::X86::BI__builtin_ia32_pavgw256:
12511 case clang::X86::BI__builtin_ia32_pavgb512:
12512 case clang::X86::BI__builtin_ia32_pavgw512:
12513 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12514
12515 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12516 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12517 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12518 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12519 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12520 .extractBits(16, 1);
12521 });
12522
12523 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12524 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12525 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12526 case clang::X86::BI__builtin_ia32_pmaddwd128:
12527 case clang::X86::BI__builtin_ia32_pmaddwd256:
12528 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12529 APValue SourceLHS, SourceRHS;
12530 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12531 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12532 return false;
12533
12534 auto *DestTy = E->getType()->castAs<VectorType>();
12535 QualType DestEltTy = DestTy->getElementType();
12536 unsigned SourceLen = SourceLHS.getVectorLength();
12537 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12538 SmallVector<APValue, 4> ResultElements;
12539 ResultElements.reserve(SourceLen / 2);
12540
12541 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12542 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12543 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12544 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12545 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12546 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12547
12548 switch (E->getBuiltinCallee()) {
12549 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12550 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12551 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12552 ResultElements.push_back(APValue(
12553 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12554 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12555 DestUnsigned)));
12556 break;
12557 case clang::X86::BI__builtin_ia32_pmaddwd128:
12558 case clang::X86::BI__builtin_ia32_pmaddwd256:
12559 case clang::X86::BI__builtin_ia32_pmaddwd512:
12560 ResultElements.push_back(
12561 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12562 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12563 DestUnsigned)));
12564 break;
12565 }
12566 }
12567
12568 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12569 }
12570
12571 case clang::X86::BI__builtin_ia32_pmulhuw128:
12572 case clang::X86::BI__builtin_ia32_pmulhuw256:
12573 case clang::X86::BI__builtin_ia32_pmulhuw512:
12574 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12575
12576 case clang::X86::BI__builtin_ia32_pmulhw128:
12577 case clang::X86::BI__builtin_ia32_pmulhw256:
12578 case clang::X86::BI__builtin_ia32_pmulhw512:
12579 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12580
12581 case clang::X86::BI__builtin_ia32_psllv2di:
12582 case clang::X86::BI__builtin_ia32_psllv4di:
12583 case clang::X86::BI__builtin_ia32_psllv4si:
12584 case clang::X86::BI__builtin_ia32_psllv8di:
12585 case clang::X86::BI__builtin_ia32_psllv8hi:
12586 case clang::X86::BI__builtin_ia32_psllv8si:
12587 case clang::X86::BI__builtin_ia32_psllv16hi:
12588 case clang::X86::BI__builtin_ia32_psllv16si:
12589 case clang::X86::BI__builtin_ia32_psllv32hi:
12590 case clang::X86::BI__builtin_ia32_psllwi128:
12591 case clang::X86::BI__builtin_ia32_pslldi128:
12592 case clang::X86::BI__builtin_ia32_psllqi128:
12593 case clang::X86::BI__builtin_ia32_psllwi256:
12594 case clang::X86::BI__builtin_ia32_pslldi256:
12595 case clang::X86::BI__builtin_ia32_psllqi256:
12596 case clang::X86::BI__builtin_ia32_psllwi512:
12597 case clang::X86::BI__builtin_ia32_pslldi512:
12598 case clang::X86::BI__builtin_ia32_psllqi512:
12599 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12600 if (RHS.uge(LHS.getBitWidth())) {
12601 return APInt::getZero(LHS.getBitWidth());
12602 }
12603 return LHS.shl(RHS.getZExtValue());
12604 });
12605
12606 case clang::X86::BI__builtin_ia32_psrav4si:
12607 case clang::X86::BI__builtin_ia32_psrav8di:
12608 case clang::X86::BI__builtin_ia32_psrav8hi:
12609 case clang::X86::BI__builtin_ia32_psrav8si:
12610 case clang::X86::BI__builtin_ia32_psrav16hi:
12611 case clang::X86::BI__builtin_ia32_psrav16si:
12612 case clang::X86::BI__builtin_ia32_psrav32hi:
12613 case clang::X86::BI__builtin_ia32_psravq128:
12614 case clang::X86::BI__builtin_ia32_psravq256:
12615 case clang::X86::BI__builtin_ia32_psrawi128:
12616 case clang::X86::BI__builtin_ia32_psradi128:
12617 case clang::X86::BI__builtin_ia32_psraqi128:
12618 case clang::X86::BI__builtin_ia32_psrawi256:
12619 case clang::X86::BI__builtin_ia32_psradi256:
12620 case clang::X86::BI__builtin_ia32_psraqi256:
12621 case clang::X86::BI__builtin_ia32_psrawi512:
12622 case clang::X86::BI__builtin_ia32_psradi512:
12623 case clang::X86::BI__builtin_ia32_psraqi512:
12624 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12625 if (RHS.uge(LHS.getBitWidth())) {
12626 return LHS.ashr(LHS.getBitWidth() - 1);
12627 }
12628 return LHS.ashr(RHS.getZExtValue());
12629 });
12630
12631 case clang::X86::BI__builtin_ia32_psrlv2di:
12632 case clang::X86::BI__builtin_ia32_psrlv4di:
12633 case clang::X86::BI__builtin_ia32_psrlv4si:
12634 case clang::X86::BI__builtin_ia32_psrlv8di:
12635 case clang::X86::BI__builtin_ia32_psrlv8hi:
12636 case clang::X86::BI__builtin_ia32_psrlv8si:
12637 case clang::X86::BI__builtin_ia32_psrlv16hi:
12638 case clang::X86::BI__builtin_ia32_psrlv16si:
12639 case clang::X86::BI__builtin_ia32_psrlv32hi:
12640 case clang::X86::BI__builtin_ia32_psrlwi128:
12641 case clang::X86::BI__builtin_ia32_psrldi128:
12642 case clang::X86::BI__builtin_ia32_psrlqi128:
12643 case clang::X86::BI__builtin_ia32_psrlwi256:
12644 case clang::X86::BI__builtin_ia32_psrldi256:
12645 case clang::X86::BI__builtin_ia32_psrlqi256:
12646 case clang::X86::BI__builtin_ia32_psrlwi512:
12647 case clang::X86::BI__builtin_ia32_psrldi512:
12648 case clang::X86::BI__builtin_ia32_psrlqi512:
12649 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12650 if (RHS.uge(LHS.getBitWidth())) {
12651 return APInt::getZero(LHS.getBitWidth());
12652 }
12653 return LHS.lshr(RHS.getZExtValue());
12654 });
12655 case X86::BI__builtin_ia32_packsswb128:
12656 case X86::BI__builtin_ia32_packsswb256:
12657 case X86::BI__builtin_ia32_packsswb512:
12658 case X86::BI__builtin_ia32_packssdw128:
12659 case X86::BI__builtin_ia32_packssdw256:
12660 case X86::BI__builtin_ia32_packssdw512:
12661 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12662 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12663 });
12664 case X86::BI__builtin_ia32_packusdw128:
12665 case X86::BI__builtin_ia32_packusdw256:
12666 case X86::BI__builtin_ia32_packusdw512:
12667 case X86::BI__builtin_ia32_packuswb128:
12668 case X86::BI__builtin_ia32_packuswb256:
12669 case X86::BI__builtin_ia32_packuswb512:
12670 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12671 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12672 });
12673 case clang::X86::BI__builtin_ia32_selectss_128:
12674 return EvalSelectScalar(4);
12675 case clang::X86::BI__builtin_ia32_selectsd_128:
12676 return EvalSelectScalar(2);
12677 case clang::X86::BI__builtin_ia32_selectsh_128:
12678 case clang::X86::BI__builtin_ia32_selectsbf_128:
12679 return EvalSelectScalar(8);
12680 case clang::X86::BI__builtin_ia32_pmuldq128:
12681 case clang::X86::BI__builtin_ia32_pmuldq256:
12682 case clang::X86::BI__builtin_ia32_pmuldq512:
12683 case clang::X86::BI__builtin_ia32_pmuludq128:
12684 case clang::X86::BI__builtin_ia32_pmuludq256:
12685 case clang::X86::BI__builtin_ia32_pmuludq512: {
12686 APValue SourceLHS, SourceRHS;
12687 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12688 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12689 return false;
12690
12691 unsigned SourceLen = SourceLHS.getVectorLength();
12692 SmallVector<APValue, 4> ResultElements;
12693 ResultElements.reserve(SourceLen / 2);
12694
12695 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12696 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12697 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12698
12699 switch (E->getBuiltinCallee()) {
12700 case clang::X86::BI__builtin_ia32_pmuludq128:
12701 case clang::X86::BI__builtin_ia32_pmuludq256:
12702 case clang::X86::BI__builtin_ia32_pmuludq512:
12703 ResultElements.push_back(
12704 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12705 break;
12706 case clang::X86::BI__builtin_ia32_pmuldq128:
12707 case clang::X86::BI__builtin_ia32_pmuldq256:
12708 case clang::X86::BI__builtin_ia32_pmuldq512:
12709 ResultElements.push_back(
12710 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12711 break;
12712 }
12713 }
12714
12715 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12716 }
12717
12718 case X86::BI__builtin_ia32_vpmadd52luq128:
12719 case X86::BI__builtin_ia32_vpmadd52luq256:
12720 case X86::BI__builtin_ia32_vpmadd52luq512: {
12721 APValue A, B, C;
12722 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12723 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12724 !EvaluateAsRValue(Info, E->getArg(2), C))
12725 return false;
12726
12727 unsigned ALen = A.getVectorLength();
12728 SmallVector<APValue, 4> ResultElements;
12729 ResultElements.reserve(ALen);
12730
12731 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12732 APInt AElt = A.getVectorElt(EltNum).getInt();
12733 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12734 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12735 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12736 ResultElements.push_back(APValue(ResElt));
12737 }
12738
12739 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12740 }
12741 case X86::BI__builtin_ia32_vpmadd52huq128:
12742 case X86::BI__builtin_ia32_vpmadd52huq256:
12743 case X86::BI__builtin_ia32_vpmadd52huq512: {
12744 APValue A, B, C;
12745 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12746 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12747 !EvaluateAsRValue(Info, E->getArg(2), C))
12748 return false;
12749
12750 unsigned ALen = A.getVectorLength();
12751 SmallVector<APValue, 4> ResultElements;
12752 ResultElements.reserve(ALen);
12753
12754 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12755 APInt AElt = A.getVectorElt(EltNum).getInt();
12756 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12757 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12758 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12759 ResultElements.push_back(APValue(ResElt));
12760 }
12761
12762 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12763 }
12764
12765 case clang::X86::BI__builtin_ia32_vprotbi:
12766 case clang::X86::BI__builtin_ia32_vprotdi:
12767 case clang::X86::BI__builtin_ia32_vprotqi:
12768 case clang::X86::BI__builtin_ia32_vprotwi:
12769 case clang::X86::BI__builtin_ia32_prold128:
12770 case clang::X86::BI__builtin_ia32_prold256:
12771 case clang::X86::BI__builtin_ia32_prold512:
12772 case clang::X86::BI__builtin_ia32_prolq128:
12773 case clang::X86::BI__builtin_ia32_prolq256:
12774 case clang::X86::BI__builtin_ia32_prolq512:
12775 return EvaluateBinOpExpr(
12776 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12777
12778 case clang::X86::BI__builtin_ia32_prord128:
12779 case clang::X86::BI__builtin_ia32_prord256:
12780 case clang::X86::BI__builtin_ia32_prord512:
12781 case clang::X86::BI__builtin_ia32_prorq128:
12782 case clang::X86::BI__builtin_ia32_prorq256:
12783 case clang::X86::BI__builtin_ia32_prorq512:
12784 return EvaluateBinOpExpr(
12785 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12786
12787 case Builtin::BI__builtin_elementwise_max:
12788 case Builtin::BI__builtin_elementwise_min: {
12789 APValue SourceLHS, SourceRHS;
12790 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12791 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12792 return false;
12793
12794 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12795
12796 if (!DestEltTy->isIntegerType())
12797 return false;
12798
12799 unsigned SourceLen = SourceLHS.getVectorLength();
12800 SmallVector<APValue, 4> ResultElements;
12801 ResultElements.reserve(SourceLen);
12802
12803 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12804 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12805 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12806 switch (E->getBuiltinCallee()) {
12807 case Builtin::BI__builtin_elementwise_max:
12808 ResultElements.push_back(
12809 APValue(APSInt(std::max(LHS, RHS),
12810 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12811 break;
12812 case Builtin::BI__builtin_elementwise_min:
12813 ResultElements.push_back(
12814 APValue(APSInt(std::min(LHS, RHS),
12815 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12816 break;
12817 }
12818 }
12819
12820 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12821 }
12822 case X86::BI__builtin_ia32_vpshldd128:
12823 case X86::BI__builtin_ia32_vpshldd256:
12824 case X86::BI__builtin_ia32_vpshldd512:
12825 case X86::BI__builtin_ia32_vpshldq128:
12826 case X86::BI__builtin_ia32_vpshldq256:
12827 case X86::BI__builtin_ia32_vpshldq512:
12828 case X86::BI__builtin_ia32_vpshldw128:
12829 case X86::BI__builtin_ia32_vpshldw256:
12830 case X86::BI__builtin_ia32_vpshldw512: {
12831 APValue SourceHi, SourceLo, SourceAmt;
12832 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12833 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12834 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12835 return false;
12836
12837 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12838 unsigned SourceLen = SourceHi.getVectorLength();
12839 SmallVector<APValue, 32> ResultElements;
12840 ResultElements.reserve(SourceLen);
12841
12842 APInt Amt = SourceAmt.getInt();
12843 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12844 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12845 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12846 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12847 ResultElements.push_back(
12849 }
12850
12851 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12852 }
12853 case X86::BI__builtin_ia32_vpshrdd128:
12854 case X86::BI__builtin_ia32_vpshrdd256:
12855 case X86::BI__builtin_ia32_vpshrdd512:
12856 case X86::BI__builtin_ia32_vpshrdq128:
12857 case X86::BI__builtin_ia32_vpshrdq256:
12858 case X86::BI__builtin_ia32_vpshrdq512:
12859 case X86::BI__builtin_ia32_vpshrdw128:
12860 case X86::BI__builtin_ia32_vpshrdw256:
12861 case X86::BI__builtin_ia32_vpshrdw512: {
12862 // NOTE: Reversed Hi/Lo operands.
12863 APValue SourceHi, SourceLo, SourceAmt;
12864 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12865 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12866 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12867 return false;
12868
12869 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12870 unsigned SourceLen = SourceHi.getVectorLength();
12871 SmallVector<APValue, 32> ResultElements;
12872 ResultElements.reserve(SourceLen);
12873
12874 APInt Amt = SourceAmt.getInt();
12875 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12876 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12877 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12878 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12879 ResultElements.push_back(
12881 }
12882
12883 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12884 }
12885 case X86::BI__builtin_ia32_compressdf128_mask:
12886 case X86::BI__builtin_ia32_compressdf256_mask:
12887 case X86::BI__builtin_ia32_compressdf512_mask:
12888 case X86::BI__builtin_ia32_compressdi128_mask:
12889 case X86::BI__builtin_ia32_compressdi256_mask:
12890 case X86::BI__builtin_ia32_compressdi512_mask:
12891 case X86::BI__builtin_ia32_compresshi128_mask:
12892 case X86::BI__builtin_ia32_compresshi256_mask:
12893 case X86::BI__builtin_ia32_compresshi512_mask:
12894 case X86::BI__builtin_ia32_compressqi128_mask:
12895 case X86::BI__builtin_ia32_compressqi256_mask:
12896 case X86::BI__builtin_ia32_compressqi512_mask:
12897 case X86::BI__builtin_ia32_compresssf128_mask:
12898 case X86::BI__builtin_ia32_compresssf256_mask:
12899 case X86::BI__builtin_ia32_compresssf512_mask:
12900 case X86::BI__builtin_ia32_compresssi128_mask:
12901 case X86::BI__builtin_ia32_compresssi256_mask:
12902 case X86::BI__builtin_ia32_compresssi512_mask: {
12903 APValue Source, Passthru;
12904 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
12905 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
12906 return false;
12907 APSInt Mask;
12908 if (!EvaluateInteger(E->getArg(2), Mask, Info))
12909 return false;
12910
12911 unsigned NumElts = Source.getVectorLength();
12912 SmallVector<APValue, 64> ResultElements;
12913 ResultElements.reserve(NumElts);
12914
12915 for (unsigned I = 0; I != NumElts; ++I) {
12916 if (Mask[I])
12917 ResultElements.push_back(Source.getVectorElt(I));
12918 }
12919 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
12920 ResultElements.push_back(Passthru.getVectorElt(I));
12921 }
12922
12923 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12924 }
12925 case X86::BI__builtin_ia32_expanddf128_mask:
12926 case X86::BI__builtin_ia32_expanddf256_mask:
12927 case X86::BI__builtin_ia32_expanddf512_mask:
12928 case X86::BI__builtin_ia32_expanddi128_mask:
12929 case X86::BI__builtin_ia32_expanddi256_mask:
12930 case X86::BI__builtin_ia32_expanddi512_mask:
12931 case X86::BI__builtin_ia32_expandhi128_mask:
12932 case X86::BI__builtin_ia32_expandhi256_mask:
12933 case X86::BI__builtin_ia32_expandhi512_mask:
12934 case X86::BI__builtin_ia32_expandqi128_mask:
12935 case X86::BI__builtin_ia32_expandqi256_mask:
12936 case X86::BI__builtin_ia32_expandqi512_mask:
12937 case X86::BI__builtin_ia32_expandsf128_mask:
12938 case X86::BI__builtin_ia32_expandsf256_mask:
12939 case X86::BI__builtin_ia32_expandsf512_mask:
12940 case X86::BI__builtin_ia32_expandsi128_mask:
12941 case X86::BI__builtin_ia32_expandsi256_mask:
12942 case X86::BI__builtin_ia32_expandsi512_mask: {
12943 APValue Source, Passthru;
12944 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
12945 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
12946 return false;
12947 APSInt Mask;
12948 if (!EvaluateInteger(E->getArg(2), Mask, Info))
12949 return false;
12950
12951 unsigned NumElts = Source.getVectorLength();
12952 SmallVector<APValue, 64> ResultElements;
12953 ResultElements.reserve(NumElts);
12954
12955 unsigned SourceIdx = 0;
12956 for (unsigned I = 0; I != NumElts; ++I) {
12957 if (Mask[I])
12958 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
12959 else
12960 ResultElements.push_back(Passthru.getVectorElt(I));
12961 }
12962 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12963 }
12964 case X86::BI__builtin_ia32_vpconflictsi_128:
12965 case X86::BI__builtin_ia32_vpconflictsi_256:
12966 case X86::BI__builtin_ia32_vpconflictsi_512:
12967 case X86::BI__builtin_ia32_vpconflictdi_128:
12968 case X86::BI__builtin_ia32_vpconflictdi_256:
12969 case X86::BI__builtin_ia32_vpconflictdi_512: {
12970 APValue Source;
12971
12972 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12973 return false;
12974
12975 unsigned SourceLen = Source.getVectorLength();
12976 SmallVector<APValue, 32> ResultElements;
12977 ResultElements.reserve(SourceLen);
12978
12979 const auto *VecT = E->getType()->castAs<VectorType>();
12980 bool DestUnsigned =
12981 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12982
12983 for (unsigned I = 0; I != SourceLen; ++I) {
12984 const APValue &EltI = Source.getVectorElt(I);
12985
12986 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12987 for (unsigned J = 0; J != I; ++J) {
12988 const APValue &EltJ = Source.getVectorElt(J);
12989 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12990 }
12991 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12992 }
12993 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12994 }
12995 case X86::BI__builtin_ia32_blendpd:
12996 case X86::BI__builtin_ia32_blendpd256:
12997 case X86::BI__builtin_ia32_blendps:
12998 case X86::BI__builtin_ia32_blendps256:
12999 case X86::BI__builtin_ia32_pblendw128:
13000 case X86::BI__builtin_ia32_pblendw256:
13001 case X86::BI__builtin_ia32_pblendd128:
13002 case X86::BI__builtin_ia32_pblendd256: {
13003 APValue SourceF, SourceT, SourceC;
13004 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13005 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13006 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13007 return false;
13008
13009 const APInt &C = SourceC.getInt();
13010 unsigned SourceLen = SourceF.getVectorLength();
13011 SmallVector<APValue, 32> ResultElements;
13012 ResultElements.reserve(SourceLen);
13013 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13014 const APValue &F = SourceF.getVectorElt(EltNum);
13015 const APValue &T = SourceT.getVectorElt(EltNum);
13016 ResultElements.push_back(C[EltNum % 8] ? T : F);
13017 }
13018
13019 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13020 }
13021
13022 case X86::BI__builtin_ia32_psignb128:
13023 case X86::BI__builtin_ia32_psignb256:
13024 case X86::BI__builtin_ia32_psignw128:
13025 case X86::BI__builtin_ia32_psignw256:
13026 case X86::BI__builtin_ia32_psignd128:
13027 case X86::BI__builtin_ia32_psignd256:
13028 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13029 if (BElem.isZero())
13030 return APInt::getZero(AElem.getBitWidth());
13031 if (BElem.isNegative())
13032 return -AElem;
13033 return AElem;
13034 });
13035
13036 case X86::BI__builtin_ia32_blendvpd:
13037 case X86::BI__builtin_ia32_blendvpd256:
13038 case X86::BI__builtin_ia32_blendvps:
13039 case X86::BI__builtin_ia32_blendvps256:
13040 case X86::BI__builtin_ia32_pblendvb128:
13041 case X86::BI__builtin_ia32_pblendvb256: {
13042 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13043 APValue SourceF, SourceT, SourceC;
13044 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13045 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13046 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13047 return false;
13048
13049 unsigned SourceLen = SourceF.getVectorLength();
13050 SmallVector<APValue, 32> ResultElements;
13051 ResultElements.reserve(SourceLen);
13052
13053 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13054 const APValue &F = SourceF.getVectorElt(EltNum);
13055 const APValue &T = SourceT.getVectorElt(EltNum);
13056 const APValue &C = SourceC.getVectorElt(EltNum);
13057 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13058 ResultElements.push_back(M.isNegative() ? T : F);
13059 }
13060
13061 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13062 }
13063 case X86::BI__builtin_ia32_selectb_128:
13064 case X86::BI__builtin_ia32_selectb_256:
13065 case X86::BI__builtin_ia32_selectb_512:
13066 case X86::BI__builtin_ia32_selectw_128:
13067 case X86::BI__builtin_ia32_selectw_256:
13068 case X86::BI__builtin_ia32_selectw_512:
13069 case X86::BI__builtin_ia32_selectd_128:
13070 case X86::BI__builtin_ia32_selectd_256:
13071 case X86::BI__builtin_ia32_selectd_512:
13072 case X86::BI__builtin_ia32_selectq_128:
13073 case X86::BI__builtin_ia32_selectq_256:
13074 case X86::BI__builtin_ia32_selectq_512:
13075 case X86::BI__builtin_ia32_selectph_128:
13076 case X86::BI__builtin_ia32_selectph_256:
13077 case X86::BI__builtin_ia32_selectph_512:
13078 case X86::BI__builtin_ia32_selectpbf_128:
13079 case X86::BI__builtin_ia32_selectpbf_256:
13080 case X86::BI__builtin_ia32_selectpbf_512:
13081 case X86::BI__builtin_ia32_selectps_128:
13082 case X86::BI__builtin_ia32_selectps_256:
13083 case X86::BI__builtin_ia32_selectps_512:
13084 case X86::BI__builtin_ia32_selectpd_128:
13085 case X86::BI__builtin_ia32_selectpd_256:
13086 case X86::BI__builtin_ia32_selectpd_512: {
13087 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13088 APValue SourceMask, SourceLHS, SourceRHS;
13089 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13090 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13091 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13092 return false;
13093
13094 APSInt Mask = SourceMask.getInt();
13095 unsigned SourceLen = SourceLHS.getVectorLength();
13096 SmallVector<APValue, 4> ResultElements;
13097 ResultElements.reserve(SourceLen);
13098
13099 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13100 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13101 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13102 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13103 }
13104
13105 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13106 }
13107
13108 case X86::BI__builtin_ia32_cvtsd2ss: {
13109 APValue VecA, VecB;
13110 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13111 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13112 return false;
13113
13114 SmallVector<APValue, 4> Elements;
13115
13116 APValue ResultVal;
13117 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13118 ResultVal))
13119 return false;
13120
13121 Elements.push_back(ResultVal);
13122
13123 unsigned NumEltsA = VecA.getVectorLength();
13124 for (unsigned I = 1; I < NumEltsA; ++I) {
13125 Elements.push_back(VecA.getVectorElt(I));
13126 }
13127
13128 return Success(Elements, E);
13129 }
13130 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13131 APValue VecA, VecB, VecSrc, MaskValue;
13132
13133 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13134 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13135 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13136 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13137 return false;
13138
13139 unsigned Mask = MaskValue.getInt().getZExtValue();
13140 SmallVector<APValue, 4> Elements;
13141
13142 if (Mask & 1) {
13143 APValue ResultVal;
13144 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13145 ResultVal))
13146 return false;
13147 Elements.push_back(ResultVal);
13148 } else {
13149 Elements.push_back(VecSrc.getVectorElt(0));
13150 }
13151
13152 unsigned NumEltsA = VecA.getVectorLength();
13153 for (unsigned I = 1; I < NumEltsA; ++I) {
13154 Elements.push_back(VecA.getVectorElt(I));
13155 }
13156
13157 return Success(Elements, E);
13158 }
13159 case X86::BI__builtin_ia32_cvtpd2ps:
13160 case X86::BI__builtin_ia32_cvtpd2ps256:
13161 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13162 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13163
13164 const auto BuiltinID = E->getBuiltinCallee();
13165 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13166 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13167
13168 APValue InputValue;
13169 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13170 return false;
13171
13172 APValue MergeValue;
13173 unsigned Mask = 0xFFFFFFFF;
13174 bool NeedsMerge = false;
13175 if (IsMasked) {
13176 APValue MaskValue;
13177 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13178 return false;
13179 Mask = MaskValue.getInt().getZExtValue();
13180 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13181 for (unsigned I = 0; I < NumEltsResult; ++I) {
13182 if (!((Mask >> I) & 1)) {
13183 NeedsMerge = true;
13184 break;
13185 }
13186 }
13187 if (NeedsMerge) {
13188 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13189 return false;
13190 }
13191 }
13192
13193 unsigned NumEltsResult =
13194 E->getType()->getAs<VectorType>()->getNumElements();
13195 unsigned NumEltsInput = InputValue.getVectorLength();
13196 SmallVector<APValue, 8> Elements;
13197 for (unsigned I = 0; I < NumEltsResult; ++I) {
13198 if (IsMasked && !((Mask >> I) & 1)) {
13199 if (!NeedsMerge) {
13200 return false;
13201 }
13202 Elements.push_back(MergeValue.getVectorElt(I));
13203 continue;
13204 }
13205
13206 if (I >= NumEltsInput) {
13207 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13208 continue;
13209 }
13210
13211 APValue ResultVal;
13213 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13214 return false;
13215
13216 Elements.push_back(ResultVal);
13217 }
13218 return Success(Elements, E);
13219 }
13220
13221 case X86::BI__builtin_ia32_shufps:
13222 case X86::BI__builtin_ia32_shufps256:
13223 case X86::BI__builtin_ia32_shufps512: {
13224 APValue R;
13225 if (!evalShuffleGeneric(
13226 Info, E, R,
13227 [](unsigned DstIdx,
13228 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13229 constexpr unsigned LaneBits = 128u;
13230 unsigned NumElemPerLane = LaneBits / 32;
13231 unsigned NumSelectableElems = NumElemPerLane / 2;
13232 unsigned BitsPerElem = 2;
13233 unsigned IndexMask = (1u << BitsPerElem) - 1;
13234 unsigned MaskBits = 8;
13235 unsigned Lane = DstIdx / NumElemPerLane;
13236 unsigned ElemInLane = DstIdx % NumElemPerLane;
13237 unsigned LaneOffset = Lane * NumElemPerLane;
13238 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13239 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13240 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13241 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13242 }))
13243 return false;
13244 return Success(R, E);
13245 }
13246 case X86::BI__builtin_ia32_shufpd:
13247 case X86::BI__builtin_ia32_shufpd256:
13248 case X86::BI__builtin_ia32_shufpd512: {
13249 APValue R;
13250 if (!evalShuffleGeneric(
13251 Info, E, R,
13252 [](unsigned DstIdx,
13253 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13254 constexpr unsigned LaneBits = 128u;
13255 unsigned NumElemPerLane = LaneBits / 64;
13256 unsigned NumSelectableElems = NumElemPerLane / 2;
13257 unsigned BitsPerElem = 1;
13258 unsigned IndexMask = (1u << BitsPerElem) - 1;
13259 unsigned MaskBits = 8;
13260 unsigned Lane = DstIdx / NumElemPerLane;
13261 unsigned ElemInLane = DstIdx % NumElemPerLane;
13262 unsigned LaneOffset = Lane * NumElemPerLane;
13263 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13264 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13265 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13266 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13267 }))
13268 return false;
13269 return Success(R, E);
13270 }
13271 case X86::BI__builtin_ia32_insertps128: {
13272 APValue R;
13273 if (!evalShuffleGeneric(
13274 Info, E, R,
13275 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13276 // Bits [3:0]: zero mask - if bit is set, zero this element
13277 if ((Mask & (1 << DstIdx)) != 0) {
13278 return {0, -1};
13279 }
13280 // Bits [7:6]: select element from source vector Y (0-3)
13281 // Bits [5:4]: select destination position (0-3)
13282 unsigned SrcElem = (Mask >> 6) & 0x3;
13283 unsigned DstElem = (Mask >> 4) & 0x3;
13284 if (DstIdx == DstElem) {
13285 // Insert element from source vector (B) at this position
13286 return {1, static_cast<int>(SrcElem)};
13287 } else {
13288 // Copy from destination vector (A)
13289 return {0, static_cast<int>(DstIdx)};
13290 }
13291 }))
13292 return false;
13293 return Success(R, E);
13294 }
13295 case X86::BI__builtin_ia32_pshufb128:
13296 case X86::BI__builtin_ia32_pshufb256:
13297 case X86::BI__builtin_ia32_pshufb512: {
13298 APValue R;
13299 if (!evalShuffleGeneric(
13300 Info, E, R,
13301 [](unsigned DstIdx,
13302 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13303 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13304 if (Ctlb & 0x80)
13305 return std::make_pair(0, -1);
13306
13307 unsigned LaneBase = (DstIdx / 16) * 16;
13308 unsigned SrcOffset = Ctlb & 0x0F;
13309 unsigned SrcIdx = LaneBase + SrcOffset;
13310 return std::make_pair(0, static_cast<int>(SrcIdx));
13311 }))
13312 return false;
13313 return Success(R, E);
13314 }
13315
13316 case X86::BI__builtin_ia32_pshuflw:
13317 case X86::BI__builtin_ia32_pshuflw256:
13318 case X86::BI__builtin_ia32_pshuflw512: {
13319 APValue R;
13320 if (!evalShuffleGeneric(
13321 Info, E, R,
13322 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13323 constexpr unsigned LaneBits = 128u;
13324 constexpr unsigned ElemBits = 16u;
13325 constexpr unsigned LaneElts = LaneBits / ElemBits;
13326 constexpr unsigned HalfSize = 4;
13327 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13328 unsigned LaneIdx = DstIdx % LaneElts;
13329 if (LaneIdx < HalfSize) {
13330 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13331 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13332 }
13333 return std::make_pair(0, static_cast<int>(DstIdx));
13334 }))
13335 return false;
13336 return Success(R, E);
13337 }
13338
13339 case X86::BI__builtin_ia32_pshufhw:
13340 case X86::BI__builtin_ia32_pshufhw256:
13341 case X86::BI__builtin_ia32_pshufhw512: {
13342 APValue R;
13343 if (!evalShuffleGeneric(
13344 Info, E, R,
13345 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13346 constexpr unsigned LaneBits = 128u;
13347 constexpr unsigned ElemBits = 16u;
13348 constexpr unsigned LaneElts = LaneBits / ElemBits;
13349 constexpr unsigned HalfSize = 4;
13350 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13351 unsigned LaneIdx = DstIdx % LaneElts;
13352 if (LaneIdx >= HalfSize) {
13353 unsigned Rel = LaneIdx - HalfSize;
13354 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13355 return std::make_pair(
13356 0, static_cast<int>(LaneBase + HalfSize + Sel));
13357 }
13358 return std::make_pair(0, static_cast<int>(DstIdx));
13359 }))
13360 return false;
13361 return Success(R, E);
13362 }
13363
13364 case X86::BI__builtin_ia32_pshufd:
13365 case X86::BI__builtin_ia32_pshufd256:
13366 case X86::BI__builtin_ia32_pshufd512:
13367 case X86::BI__builtin_ia32_vpermilps:
13368 case X86::BI__builtin_ia32_vpermilps256:
13369 case X86::BI__builtin_ia32_vpermilps512: {
13370 APValue R;
13371 if (!evalShuffleGeneric(
13372 Info, E, R,
13373 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13374 constexpr unsigned LaneBits = 128u;
13375 constexpr unsigned ElemBits = 32u;
13376 constexpr unsigned LaneElts = LaneBits / ElemBits;
13377 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13378 unsigned LaneIdx = DstIdx % LaneElts;
13379 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13380 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13381 }))
13382 return false;
13383 return Success(R, E);
13384 }
13385
13386 case X86::BI__builtin_ia32_vpermilvarpd:
13387 case X86::BI__builtin_ia32_vpermilvarpd256:
13388 case X86::BI__builtin_ia32_vpermilvarpd512: {
13389 APValue R;
13390 if (!evalShuffleGeneric(
13391 Info, E, R,
13392 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13393 unsigned NumElemPerLane = 2;
13394 unsigned Lane = DstIdx / NumElemPerLane;
13395 unsigned Offset = Mask & 0b10 ? 1 : 0;
13396 return std::make_pair(
13397 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13398 }))
13399 return false;
13400 return Success(R, E);
13401 }
13402
13403 case X86::BI__builtin_ia32_vpermilpd:
13404 case X86::BI__builtin_ia32_vpermilpd256:
13405 case X86::BI__builtin_ia32_vpermilpd512: {
13406 APValue R;
13407 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13408 unsigned NumElemPerLane = 2;
13409 unsigned BitsPerElem = 1;
13410 unsigned MaskBits = 8;
13411 unsigned IndexMask = 0x1;
13412 unsigned Lane = DstIdx / NumElemPerLane;
13413 unsigned LaneOffset = Lane * NumElemPerLane;
13414 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13415 unsigned Index = (Control >> BitIndex) & IndexMask;
13416 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13417 }))
13418 return false;
13419 return Success(R, E);
13420 }
13421
13422 case X86::BI__builtin_ia32_permdf256:
13423 case X86::BI__builtin_ia32_permdi256: {
13424 APValue R;
13425 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13426 // permute4x64 operates on 4 64-bit elements
13427 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13428 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13429 return std::make_pair(0, static_cast<int>(Index));
13430 }))
13431 return false;
13432 return Success(R, E);
13433 }
13434
13435 case X86::BI__builtin_ia32_vpermilvarps:
13436 case X86::BI__builtin_ia32_vpermilvarps256:
13437 case X86::BI__builtin_ia32_vpermilvarps512: {
13438 APValue R;
13439 if (!evalShuffleGeneric(
13440 Info, E, R,
13441 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13442 unsigned NumElemPerLane = 4;
13443 unsigned Lane = DstIdx / NumElemPerLane;
13444 unsigned Offset = Mask & 0b11;
13445 return std::make_pair(
13446 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13447 }))
13448 return false;
13449 return Success(R, E);
13450 }
13451
13452 case X86::BI__builtin_ia32_vpmultishiftqb128:
13453 case X86::BI__builtin_ia32_vpmultishiftqb256:
13454 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13455 assert(E->getNumArgs() == 2);
13456
13457 APValue A, B;
13458 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13459 return false;
13460
13461 assert(A.getVectorLength() == B.getVectorLength());
13462 unsigned NumBytesInQWord = 8;
13463 unsigned NumBitsInByte = 8;
13464 unsigned NumBytes = A.getVectorLength();
13465 unsigned NumQWords = NumBytes / NumBytesInQWord;
13467 Result.reserve(NumBytes);
13468
13469 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13470 APInt BQWord(64, 0);
13471 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13472 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13473 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13474 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13475 }
13476
13477 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13478 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13479 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13480
13481 APInt Byte(8, 0);
13482 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13483 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13484 }
13485 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13486 }
13487 }
13488 return Success(APValue(Result.data(), Result.size()), E);
13489 }
13490
13491 case X86::BI__builtin_ia32_phminposuw128: {
13492 APValue Source;
13493 if (!Evaluate(Source, Info, E->getArg(0)))
13494 return false;
13495 unsigned SourceLen = Source.getVectorLength();
13496 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13497 QualType ElemQT = VT->getElementType();
13498 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13499
13500 APInt MinIndex(ElemBitWidth, 0);
13501 APInt MinVal = Source.getVectorElt(0).getInt();
13502 for (unsigned I = 1; I != SourceLen; ++I) {
13503 APInt Val = Source.getVectorElt(I).getInt();
13504 if (MinVal.ugt(Val)) {
13505 MinVal = Val;
13506 MinIndex = I;
13507 }
13508 }
13509
13510 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13511 ->castAs<VectorType>()
13512 ->getElementType()
13513 ->isUnsignedIntegerOrEnumerationType();
13514
13516 Result.reserve(SourceLen);
13517 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13518 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13519 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13520 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13521 }
13522 return Success(APValue(Result.data(), Result.size()), E);
13523 }
13524
13525 case X86::BI__builtin_ia32_psraq128:
13526 case X86::BI__builtin_ia32_psraq256:
13527 case X86::BI__builtin_ia32_psraq512:
13528 case X86::BI__builtin_ia32_psrad128:
13529 case X86::BI__builtin_ia32_psrad256:
13530 case X86::BI__builtin_ia32_psrad512:
13531 case X86::BI__builtin_ia32_psraw128:
13532 case X86::BI__builtin_ia32_psraw256:
13533 case X86::BI__builtin_ia32_psraw512: {
13534 APValue R;
13535 if (!evalShiftWithCount(
13536 Info, E, R,
13537 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13538 [](const APInt &Elt, unsigned Width) {
13539 return Elt.ashr(Width - 1);
13540 }))
13541 return false;
13542 return Success(R, E);
13543 }
13544
13545 case X86::BI__builtin_ia32_psllq128:
13546 case X86::BI__builtin_ia32_psllq256:
13547 case X86::BI__builtin_ia32_psllq512:
13548 case X86::BI__builtin_ia32_pslld128:
13549 case X86::BI__builtin_ia32_pslld256:
13550 case X86::BI__builtin_ia32_pslld512:
13551 case X86::BI__builtin_ia32_psllw128:
13552 case X86::BI__builtin_ia32_psllw256:
13553 case X86::BI__builtin_ia32_psllw512: {
13554 APValue R;
13555 if (!evalShiftWithCount(
13556 Info, E, R,
13557 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13558 [](const APInt &Elt, unsigned Width) {
13559 return APInt::getZero(Width);
13560 }))
13561 return false;
13562 return Success(R, E);
13563 }
13564
13565 case X86::BI__builtin_ia32_psrlq128:
13566 case X86::BI__builtin_ia32_psrlq256:
13567 case X86::BI__builtin_ia32_psrlq512:
13568 case X86::BI__builtin_ia32_psrld128:
13569 case X86::BI__builtin_ia32_psrld256:
13570 case X86::BI__builtin_ia32_psrld512:
13571 case X86::BI__builtin_ia32_psrlw128:
13572 case X86::BI__builtin_ia32_psrlw256:
13573 case X86::BI__builtin_ia32_psrlw512: {
13574 APValue R;
13575 if (!evalShiftWithCount(
13576 Info, E, R,
13577 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13578 [](const APInt &Elt, unsigned Width) {
13579 return APInt::getZero(Width);
13580 }))
13581 return false;
13582 return Success(R, E);
13583 }
13584
13585 case X86::BI__builtin_ia32_pternlogd128_mask:
13586 case X86::BI__builtin_ia32_pternlogd256_mask:
13587 case X86::BI__builtin_ia32_pternlogd512_mask:
13588 case X86::BI__builtin_ia32_pternlogq128_mask:
13589 case X86::BI__builtin_ia32_pternlogq256_mask:
13590 case X86::BI__builtin_ia32_pternlogq512_mask: {
13591 APValue AValue, BValue, CValue, ImmValue, UValue;
13592 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13593 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13594 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13595 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13596 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13597 return false;
13598
13599 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13600 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13601 APInt Imm = ImmValue.getInt();
13602 APInt U = UValue.getInt();
13603 unsigned ResultLen = AValue.getVectorLength();
13604 SmallVector<APValue, 16> ResultElements;
13605 ResultElements.reserve(ResultLen);
13606
13607 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13608 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13609 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13610 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13611
13612 if (U[EltNum]) {
13613 unsigned BitWidth = ALane.getBitWidth();
13614 APInt ResLane(BitWidth, 0);
13615
13616 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13617 unsigned ABit = ALane[Bit];
13618 unsigned BBit = BLane[Bit];
13619 unsigned CBit = CLane[Bit];
13620
13621 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13622 ResLane.setBitVal(Bit, Imm[Idx]);
13623 }
13624 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13625 } else {
13626 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13627 }
13628 }
13629 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13630 }
13631 case X86::BI__builtin_ia32_pternlogd128_maskz:
13632 case X86::BI__builtin_ia32_pternlogd256_maskz:
13633 case X86::BI__builtin_ia32_pternlogd512_maskz:
13634 case X86::BI__builtin_ia32_pternlogq128_maskz:
13635 case X86::BI__builtin_ia32_pternlogq256_maskz:
13636 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13637 APValue AValue, BValue, CValue, ImmValue, UValue;
13638 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13639 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13640 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13641 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13642 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13643 return false;
13644
13645 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13646 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13647 APInt Imm = ImmValue.getInt();
13648 APInt U = UValue.getInt();
13649 unsigned ResultLen = AValue.getVectorLength();
13650 SmallVector<APValue, 16> ResultElements;
13651 ResultElements.reserve(ResultLen);
13652
13653 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13654 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13655 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13656 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13657
13658 unsigned BitWidth = ALane.getBitWidth();
13659 APInt ResLane(BitWidth, 0);
13660
13661 if (U[EltNum]) {
13662 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13663 unsigned ABit = ALane[Bit];
13664 unsigned BBit = BLane[Bit];
13665 unsigned CBit = CLane[Bit];
13666
13667 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13668 ResLane.setBitVal(Bit, Imm[Idx]);
13669 }
13670 }
13671 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13672 }
13673 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13674 }
13675
13676 case Builtin::BI__builtin_elementwise_clzg:
13677 case Builtin::BI__builtin_elementwise_ctzg: {
13678 APValue SourceLHS;
13679 std::optional<APValue> Fallback;
13680 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13681 return false;
13682 if (E->getNumArgs() > 1) {
13683 APValue FallbackTmp;
13684 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13685 return false;
13686 Fallback = FallbackTmp;
13687 }
13688
13689 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13690 unsigned SourceLen = SourceLHS.getVectorLength();
13691 SmallVector<APValue, 4> ResultElements;
13692 ResultElements.reserve(SourceLen);
13693
13694 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13695 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13696 if (!LHS) {
13697 // Without a fallback, a zero element is undefined
13698 if (!Fallback) {
13699 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13700 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13701 Builtin::BI__builtin_elementwise_ctzg);
13702 return false;
13703 }
13704 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13705 continue;
13706 }
13707 switch (E->getBuiltinCallee()) {
13708 case Builtin::BI__builtin_elementwise_clzg:
13709 ResultElements.push_back(APValue(
13710 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13711 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13712 break;
13713 case Builtin::BI__builtin_elementwise_ctzg:
13714 ResultElements.push_back(APValue(
13715 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13716 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13717 break;
13718 }
13719 }
13720
13721 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13722 }
13723
13724 case Builtin::BI__builtin_elementwise_fma: {
13725 APValue SourceX, SourceY, SourceZ;
13726 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13727 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13728 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13729 return false;
13730
13731 unsigned SourceLen = SourceX.getVectorLength();
13732 SmallVector<APValue> ResultElements;
13733 ResultElements.reserve(SourceLen);
13734 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13735 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13736 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13737 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13738 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13739 APFloat Result(X);
13740 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13741 ResultElements.push_back(APValue(Result));
13742 }
13743 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13744 }
13745
13746 case clang::X86::BI__builtin_ia32_phaddw128:
13747 case clang::X86::BI__builtin_ia32_phaddw256:
13748 case clang::X86::BI__builtin_ia32_phaddd128:
13749 case clang::X86::BI__builtin_ia32_phaddd256:
13750 case clang::X86::BI__builtin_ia32_phaddsw128:
13751 case clang::X86::BI__builtin_ia32_phaddsw256:
13752
13753 case clang::X86::BI__builtin_ia32_phsubw128:
13754 case clang::X86::BI__builtin_ia32_phsubw256:
13755 case clang::X86::BI__builtin_ia32_phsubd128:
13756 case clang::X86::BI__builtin_ia32_phsubd256:
13757 case clang::X86::BI__builtin_ia32_phsubsw128:
13758 case clang::X86::BI__builtin_ia32_phsubsw256: {
13759 APValue SourceLHS, SourceRHS;
13760 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13761 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13762 return false;
13763 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13764 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13765
13766 unsigned NumElts = SourceLHS.getVectorLength();
13767 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13768 unsigned EltsPerLane = 128 / EltBits;
13769 SmallVector<APValue, 4> ResultElements;
13770 ResultElements.reserve(NumElts);
13771
13772 for (unsigned LaneStart = 0; LaneStart != NumElts;
13773 LaneStart += EltsPerLane) {
13774 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13775 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13776 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13777 switch (E->getBuiltinCallee()) {
13778 case clang::X86::BI__builtin_ia32_phaddw128:
13779 case clang::X86::BI__builtin_ia32_phaddw256:
13780 case clang::X86::BI__builtin_ia32_phaddd128:
13781 case clang::X86::BI__builtin_ia32_phaddd256: {
13782 APSInt Res(LHSA + LHSB, DestUnsigned);
13783 ResultElements.push_back(APValue(Res));
13784 break;
13785 }
13786 case clang::X86::BI__builtin_ia32_phaddsw128:
13787 case clang::X86::BI__builtin_ia32_phaddsw256: {
13788 APSInt Res(LHSA.sadd_sat(LHSB));
13789 ResultElements.push_back(APValue(Res));
13790 break;
13791 }
13792 case clang::X86::BI__builtin_ia32_phsubw128:
13793 case clang::X86::BI__builtin_ia32_phsubw256:
13794 case clang::X86::BI__builtin_ia32_phsubd128:
13795 case clang::X86::BI__builtin_ia32_phsubd256: {
13796 APSInt Res(LHSA - LHSB, DestUnsigned);
13797 ResultElements.push_back(APValue(Res));
13798 break;
13799 }
13800 case clang::X86::BI__builtin_ia32_phsubsw128:
13801 case clang::X86::BI__builtin_ia32_phsubsw256: {
13802 APSInt Res(LHSA.ssub_sat(LHSB));
13803 ResultElements.push_back(APValue(Res));
13804 break;
13805 }
13806 }
13807 }
13808 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13809 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13810 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13811 switch (E->getBuiltinCallee()) {
13812 case clang::X86::BI__builtin_ia32_phaddw128:
13813 case clang::X86::BI__builtin_ia32_phaddw256:
13814 case clang::X86::BI__builtin_ia32_phaddd128:
13815 case clang::X86::BI__builtin_ia32_phaddd256: {
13816 APSInt Res(RHSA + RHSB, DestUnsigned);
13817 ResultElements.push_back(APValue(Res));
13818 break;
13819 }
13820 case clang::X86::BI__builtin_ia32_phaddsw128:
13821 case clang::X86::BI__builtin_ia32_phaddsw256: {
13822 APSInt Res(RHSA.sadd_sat(RHSB));
13823 ResultElements.push_back(APValue(Res));
13824 break;
13825 }
13826 case clang::X86::BI__builtin_ia32_phsubw128:
13827 case clang::X86::BI__builtin_ia32_phsubw256:
13828 case clang::X86::BI__builtin_ia32_phsubd128:
13829 case clang::X86::BI__builtin_ia32_phsubd256: {
13830 APSInt Res(RHSA - RHSB, DestUnsigned);
13831 ResultElements.push_back(APValue(Res));
13832 break;
13833 }
13834 case clang::X86::BI__builtin_ia32_phsubsw128:
13835 case clang::X86::BI__builtin_ia32_phsubsw256: {
13836 APSInt Res(RHSA.ssub_sat(RHSB));
13837 ResultElements.push_back(APValue(Res));
13838 break;
13839 }
13840 }
13841 }
13842 }
13843 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13844 }
13845 case clang::X86::BI__builtin_ia32_haddpd:
13846 case clang::X86::BI__builtin_ia32_haddps:
13847 case clang::X86::BI__builtin_ia32_haddps256:
13848 case clang::X86::BI__builtin_ia32_haddpd256:
13849 case clang::X86::BI__builtin_ia32_hsubpd:
13850 case clang::X86::BI__builtin_ia32_hsubps:
13851 case clang::X86::BI__builtin_ia32_hsubps256:
13852 case clang::X86::BI__builtin_ia32_hsubpd256: {
13853 APValue SourceLHS, SourceRHS;
13854 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13855 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13856 return false;
13857 unsigned NumElts = SourceLHS.getVectorLength();
13858 SmallVector<APValue, 4> ResultElements;
13859 ResultElements.reserve(NumElts);
13860 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13861 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13862 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13863 unsigned NumLanes = NumElts * EltBits / 128;
13864 unsigned NumElemsPerLane = NumElts / NumLanes;
13865 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13866
13867 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13868 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13869 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13870 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13871 switch (E->getBuiltinCallee()) {
13872 case clang::X86::BI__builtin_ia32_haddpd:
13873 case clang::X86::BI__builtin_ia32_haddps:
13874 case clang::X86::BI__builtin_ia32_haddps256:
13875 case clang::X86::BI__builtin_ia32_haddpd256:
13876 LHSA.add(LHSB, RM);
13877 break;
13878 case clang::X86::BI__builtin_ia32_hsubpd:
13879 case clang::X86::BI__builtin_ia32_hsubps:
13880 case clang::X86::BI__builtin_ia32_hsubps256:
13881 case clang::X86::BI__builtin_ia32_hsubpd256:
13882 LHSA.subtract(LHSB, RM);
13883 break;
13884 }
13885 ResultElements.push_back(APValue(LHSA));
13886 }
13887 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13888 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13889 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13890 switch (E->getBuiltinCallee()) {
13891 case clang::X86::BI__builtin_ia32_haddpd:
13892 case clang::X86::BI__builtin_ia32_haddps:
13893 case clang::X86::BI__builtin_ia32_haddps256:
13894 case clang::X86::BI__builtin_ia32_haddpd256:
13895 RHSA.add(RHSB, RM);
13896 break;
13897 case clang::X86::BI__builtin_ia32_hsubpd:
13898 case clang::X86::BI__builtin_ia32_hsubps:
13899 case clang::X86::BI__builtin_ia32_hsubps256:
13900 case clang::X86::BI__builtin_ia32_hsubpd256:
13901 RHSA.subtract(RHSB, RM);
13902 break;
13903 }
13904 ResultElements.push_back(APValue(RHSA));
13905 }
13906 }
13907 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13908 }
13909 case clang::X86::BI__builtin_ia32_addsubpd:
13910 case clang::X86::BI__builtin_ia32_addsubps:
13911 case clang::X86::BI__builtin_ia32_addsubpd256:
13912 case clang::X86::BI__builtin_ia32_addsubps256: {
13913 // Addsub: alternates between subtraction and addition
13914 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13915 APValue SourceLHS, SourceRHS;
13916 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13917 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13918 return false;
13919 unsigned NumElems = SourceLHS.getVectorLength();
13920 SmallVector<APValue, 8> ResultElements;
13921 ResultElements.reserve(NumElems);
13922 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13923
13924 for (unsigned I = 0; I != NumElems; ++I) {
13925 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13926 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13927 if (I % 2 == 0) {
13928 // Even indices: subtract
13929 LHS.subtract(RHS, RM);
13930 } else {
13931 // Odd indices: add
13932 LHS.add(RHS, RM);
13933 }
13934 ResultElements.push_back(APValue(LHS));
13935 }
13936 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13937 }
13938 case clang::X86::BI__builtin_ia32_pclmulqdq128:
13939 case clang::X86::BI__builtin_ia32_pclmulqdq256:
13940 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
13941 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
13942 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
13943 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
13944 APValue SourceLHS, SourceRHS;
13945 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13946 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13947 return false;
13948
13949 APSInt Imm8;
13950 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
13951 return false;
13952
13953 // Extract bits 0 and 4 from imm8
13954 bool SelectUpperA = (Imm8 & 0x01) != 0;
13955 bool SelectUpperB = (Imm8 & 0x10) != 0;
13956
13957 unsigned NumElems = SourceLHS.getVectorLength();
13958 SmallVector<APValue, 8> ResultElements;
13959 ResultElements.reserve(NumElems);
13960 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13961 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13962
13963 // Process each 128-bit lane
13964 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
13965 // Get the two 64-bit halves of the first operand
13966 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
13967 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
13968 // Get the two 64-bit halves of the second operand
13969 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
13970 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
13971
13972 // Select the appropriate 64-bit values based on imm8
13973 APInt A = SelectUpperA ? A1 : A0;
13974 APInt B = SelectUpperB ? B1 : B0;
13975
13976 // Extend both operands to 128 bits for carry-less multiplication
13977 APInt A128 = A.zext(128);
13978 APInt B128 = B.zext(128);
13979
13980 // Use APIntOps::clmul for carry-less multiplication
13981 APInt Result = llvm::APIntOps::clmul(A128, B128);
13982
13983 // Split the 128-bit result into two 64-bit halves
13984 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
13985 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
13986
13987 ResultElements.push_back(APValue(ResultLow));
13988 ResultElements.push_back(APValue(ResultHigh));
13989 }
13990
13991 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13992 }
13993 case Builtin::BI__builtin_elementwise_fshl:
13994 case Builtin::BI__builtin_elementwise_fshr: {
13995 APValue SourceHi, SourceLo, SourceShift;
13996 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13997 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13998 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13999 return false;
14000
14001 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14002 if (!DestEltTy->isIntegerType())
14003 return false;
14004
14005 unsigned SourceLen = SourceHi.getVectorLength();
14006 SmallVector<APValue> ResultElements;
14007 ResultElements.reserve(SourceLen);
14008 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14009 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14010 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14011 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14012 switch (E->getBuiltinCallee()) {
14013 case Builtin::BI__builtin_elementwise_fshl:
14014 ResultElements.push_back(APValue(
14015 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14016 break;
14017 case Builtin::BI__builtin_elementwise_fshr:
14018 ResultElements.push_back(APValue(
14019 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14020 break;
14021 }
14022 }
14023
14024 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14025 }
14026
14027 case X86::BI__builtin_ia32_shuf_f32x4_256:
14028 case X86::BI__builtin_ia32_shuf_i32x4_256:
14029 case X86::BI__builtin_ia32_shuf_f64x2_256:
14030 case X86::BI__builtin_ia32_shuf_i64x2_256:
14031 case X86::BI__builtin_ia32_shuf_f32x4:
14032 case X86::BI__builtin_ia32_shuf_i32x4:
14033 case X86::BI__builtin_ia32_shuf_f64x2:
14034 case X86::BI__builtin_ia32_shuf_i64x2: {
14035 APValue SourceA, SourceB;
14036 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14037 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14038 return false;
14039
14040 APSInt Imm;
14041 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14042 return false;
14043
14044 // Destination and sources A, B all have the same type.
14045 unsigned NumElems = SourceA.getVectorLength();
14046 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14047 QualType ElemQT = VT->getElementType();
14048 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14049 unsigned LaneBits = 128u;
14050 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14051 unsigned NumElemsPerLane = LaneBits / ElemBits;
14052
14053 unsigned DstLen = SourceA.getVectorLength();
14054 SmallVector<APValue, 16> ResultElements;
14055 ResultElements.reserve(DstLen);
14056
14057 APValue R;
14058 if (!evalShuffleGeneric(
14059 Info, E, R,
14060 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14061 -> std::pair<unsigned, int> {
14062 // DstIdx determines source. ShuffleMask selects lane in source.
14063 unsigned BitsPerElem = NumLanes / 2;
14064 unsigned IndexMask = (1u << BitsPerElem) - 1;
14065 unsigned Lane = DstIdx / NumElemsPerLane;
14066 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14067 unsigned BitIdx = BitsPerElem * Lane;
14068 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14069 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14070 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14071 return {SrcIdx, IdxToPick};
14072 }))
14073 return false;
14074 return Success(R, E);
14075 }
14076
14077 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14078 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14079 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14080 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14081 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14082 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14083
14084 APValue X, A;
14085 APSInt Imm;
14086 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14087 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14088 !EvaluateInteger(E->getArg(2), Imm, Info))
14089 return false;
14090
14091 assert(X.isVector() && A.isVector());
14092 assert(X.getVectorLength() == A.getVectorLength());
14093
14094 bool IsInverse = false;
14095 switch (E->getBuiltinCallee()) {
14096 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14097 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14098 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14099 IsInverse = true;
14100 }
14101 }
14102
14103 unsigned NumBitsInByte = 8;
14104 unsigned NumBytesInQWord = 8;
14105 unsigned NumBitsInQWord = 64;
14106 unsigned NumBytes = A.getVectorLength();
14107 unsigned NumQWords = NumBytes / NumBytesInQWord;
14109 Result.reserve(NumBytes);
14110
14111 // computing A*X + Imm
14112 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14113 // Extract the QWords from X, A
14114 APInt XQWord(NumBitsInQWord, 0);
14115 APInt AQWord(NumBitsInQWord, 0);
14116 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14117 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14118 APInt XByte = X.getVectorElt(Idx).getInt();
14119 APInt AByte = A.getVectorElt(Idx).getInt();
14120 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14121 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14122 }
14123
14124 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14125 uint8_t XByte =
14126 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14127 Result.push_back(APValue(APSInt(
14128 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14129 }
14130 }
14131
14132 return Success(APValue(Result.data(), Result.size()), E);
14133 }
14134
14135 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14136 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14137 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14138 APValue A, B;
14139 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14140 !EvaluateAsRValue(Info, E->getArg(1), B))
14141 return false;
14142
14143 assert(A.isVector() && B.isVector());
14144 assert(A.getVectorLength() == B.getVectorLength());
14145
14146 unsigned NumBytes = A.getVectorLength();
14148 Result.reserve(NumBytes);
14149
14150 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14151 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14152 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14153 Result.push_back(APValue(
14154 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14155 }
14156
14157 return Success(APValue(Result.data(), Result.size()), E);
14158 }
14159
14160 case X86::BI__builtin_ia32_insertf32x4_256:
14161 case X86::BI__builtin_ia32_inserti32x4_256:
14162 case X86::BI__builtin_ia32_insertf64x2_256:
14163 case X86::BI__builtin_ia32_inserti64x2_256:
14164 case X86::BI__builtin_ia32_insertf32x4:
14165 case X86::BI__builtin_ia32_inserti32x4:
14166 case X86::BI__builtin_ia32_insertf64x2_512:
14167 case X86::BI__builtin_ia32_inserti64x2_512:
14168 case X86::BI__builtin_ia32_insertf32x8:
14169 case X86::BI__builtin_ia32_inserti32x8:
14170 case X86::BI__builtin_ia32_insertf64x4:
14171 case X86::BI__builtin_ia32_inserti64x4:
14172 case X86::BI__builtin_ia32_vinsertf128_ps256:
14173 case X86::BI__builtin_ia32_vinsertf128_pd256:
14174 case X86::BI__builtin_ia32_vinsertf128_si256:
14175 case X86::BI__builtin_ia32_insert128i256: {
14176 APValue SourceDst, SourceSub;
14177 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14178 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14179 return false;
14180
14181 APSInt Imm;
14182 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14183 return false;
14184
14185 assert(SourceDst.isVector() && SourceSub.isVector());
14186 unsigned DstLen = SourceDst.getVectorLength();
14187 unsigned SubLen = SourceSub.getVectorLength();
14188 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14189 unsigned NumLanes = DstLen / SubLen;
14190 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14191
14192 SmallVector<APValue, 16> ResultElements;
14193 ResultElements.reserve(DstLen);
14194
14195 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14196 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14197 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14198 else
14199 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14200 }
14201
14202 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14203 }
14204
14205 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14206 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14207 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14208 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14209 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14210 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14211 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14212 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14213 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14214 APValue VecVal;
14215 APSInt Scalar, IndexAPS;
14216 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14217 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14218 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14219 return false;
14220
14221 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14222 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14223 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14224 Scalar.setIsUnsigned(ElemUnsigned);
14225 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14226 APValue ElemAV(ElemAPS);
14227
14228 unsigned NumElems = VecVal.getVectorLength();
14229 unsigned Index =
14230 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14231
14233 Elems.reserve(NumElems);
14234 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14235 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14236
14237 return Success(APValue(Elems.data(), NumElems), E);
14238 }
14239
14240 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14241 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14242 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14243 APValue R;
14244 if (!evalShuffleGeneric(
14245 Info, E, R,
14246 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14247 unsigned LaneBase = (DstIdx / 16) * 16;
14248 unsigned LaneIdx = DstIdx % 16;
14249 if (LaneIdx < Shift)
14250 return std::make_pair(0, -1);
14251
14252 return std::make_pair(
14253 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14254 }))
14255 return false;
14256 return Success(R, E);
14257 }
14258
14259 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14260 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14261 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14262 APValue R;
14263 if (!evalShuffleGeneric(
14264 Info, E, R,
14265 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14266 unsigned LaneBase = (DstIdx / 16) * 16;
14267 unsigned LaneIdx = DstIdx % 16;
14268 if (LaneIdx + Shift < 16)
14269 return std::make_pair(
14270 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14271
14272 return std::make_pair(0, -1);
14273 }))
14274 return false;
14275 return Success(R, E);
14276 }
14277
14278 case X86::BI__builtin_ia32_palignr128:
14279 case X86::BI__builtin_ia32_palignr256:
14280 case X86::BI__builtin_ia32_palignr512: {
14281 APValue R;
14282 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14283 // Default to -1 → zero-fill this destination element
14284 unsigned VecIdx = 1;
14285 int ElemIdx = -1;
14286
14287 int Lane = DstIdx / 16;
14288 int Offset = DstIdx % 16;
14289
14290 // Elements come from VecB first, then VecA after the shift boundary
14291 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14292 if (ShiftedIdx < 16) { // from VecB
14293 ElemIdx = ShiftedIdx + (Lane * 16);
14294 } else if (ShiftedIdx < 32) { // from VecA
14295 VecIdx = 0;
14296 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14297 }
14298
14299 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14300 }))
14301 return false;
14302 return Success(R, E);
14303 }
14304 case X86::BI__builtin_ia32_alignd128:
14305 case X86::BI__builtin_ia32_alignd256:
14306 case X86::BI__builtin_ia32_alignd512:
14307 case X86::BI__builtin_ia32_alignq128:
14308 case X86::BI__builtin_ia32_alignq256:
14309 case X86::BI__builtin_ia32_alignq512: {
14310 APValue R;
14311 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14312 if (!evalShuffleGeneric(Info, E, R,
14313 [NumElems](unsigned DstIdx, unsigned Shift) {
14314 unsigned Imm = Shift & 0xFF;
14315 unsigned EffectiveShift = Imm & (NumElems - 1);
14316 unsigned SourcePos = DstIdx + EffectiveShift;
14317 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14318 unsigned ElemIdx = SourcePos & (NumElems - 1);
14319
14320 return std::pair<unsigned, int>{
14321 VecIdx, static_cast<int>(ElemIdx)};
14322 }))
14323 return false;
14324 return Success(R, E);
14325 }
14326 case X86::BI__builtin_ia32_permvarsi256:
14327 case X86::BI__builtin_ia32_permvarsf256:
14328 case X86::BI__builtin_ia32_permvardf512:
14329 case X86::BI__builtin_ia32_permvardi512:
14330 case X86::BI__builtin_ia32_permvarhi128: {
14331 APValue R;
14332 if (!evalShuffleGeneric(Info, E, R,
14333 [](unsigned DstIdx, unsigned ShuffleMask) {
14334 int Offset = ShuffleMask & 0x7;
14335 return std::pair<unsigned, int>{0, Offset};
14336 }))
14337 return false;
14338 return Success(R, E);
14339 }
14340 case X86::BI__builtin_ia32_permvarqi128:
14341 case X86::BI__builtin_ia32_permvarhi256:
14342 case X86::BI__builtin_ia32_permvarsi512:
14343 case X86::BI__builtin_ia32_permvarsf512: {
14344 APValue R;
14345 if (!evalShuffleGeneric(Info, E, R,
14346 [](unsigned DstIdx, unsigned ShuffleMask) {
14347 int Offset = ShuffleMask & 0xF;
14348 return std::pair<unsigned, int>{0, Offset};
14349 }))
14350 return false;
14351 return Success(R, E);
14352 }
14353 case X86::BI__builtin_ia32_permvardi256:
14354 case X86::BI__builtin_ia32_permvardf256: {
14355 APValue R;
14356 if (!evalShuffleGeneric(Info, E, R,
14357 [](unsigned DstIdx, unsigned ShuffleMask) {
14358 int Offset = ShuffleMask & 0x3;
14359 return std::pair<unsigned, int>{0, Offset};
14360 }))
14361 return false;
14362 return Success(R, E);
14363 }
14364 case X86::BI__builtin_ia32_permvarqi256:
14365 case X86::BI__builtin_ia32_permvarhi512: {
14366 APValue R;
14367 if (!evalShuffleGeneric(Info, E, R,
14368 [](unsigned DstIdx, unsigned ShuffleMask) {
14369 int Offset = ShuffleMask & 0x1F;
14370 return std::pair<unsigned, int>{0, Offset};
14371 }))
14372 return false;
14373 return Success(R, E);
14374 }
14375 case X86::BI__builtin_ia32_permvarqi512: {
14376 APValue R;
14377 if (!evalShuffleGeneric(Info, E, R,
14378 [](unsigned DstIdx, unsigned ShuffleMask) {
14379 int Offset = ShuffleMask & 0x3F;
14380 return std::pair<unsigned, int>{0, Offset};
14381 }))
14382 return false;
14383 return Success(R, E);
14384 }
14385 case X86::BI__builtin_ia32_vpermi2varq128:
14386 case X86::BI__builtin_ia32_vpermi2varpd128: {
14387 APValue R;
14388 if (!evalShuffleGeneric(Info, E, R,
14389 [](unsigned DstIdx, unsigned ShuffleMask) {
14390 int Offset = ShuffleMask & 0x1;
14391 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14392 return std::pair<unsigned, int>{SrcIdx, Offset};
14393 }))
14394 return false;
14395 return Success(R, E);
14396 }
14397 case X86::BI__builtin_ia32_vpermi2vard128:
14398 case X86::BI__builtin_ia32_vpermi2varps128:
14399 case X86::BI__builtin_ia32_vpermi2varq256:
14400 case X86::BI__builtin_ia32_vpermi2varpd256: {
14401 APValue R;
14402 if (!evalShuffleGeneric(Info, E, R,
14403 [](unsigned DstIdx, unsigned ShuffleMask) {
14404 int Offset = ShuffleMask & 0x3;
14405 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14406 return std::pair<unsigned, int>{SrcIdx, Offset};
14407 }))
14408 return false;
14409 return Success(R, E);
14410 }
14411 case X86::BI__builtin_ia32_vpermi2varhi128:
14412 case X86::BI__builtin_ia32_vpermi2vard256:
14413 case X86::BI__builtin_ia32_vpermi2varps256:
14414 case X86::BI__builtin_ia32_vpermi2varq512:
14415 case X86::BI__builtin_ia32_vpermi2varpd512: {
14416 APValue R;
14417 if (!evalShuffleGeneric(Info, E, R,
14418 [](unsigned DstIdx, unsigned ShuffleMask) {
14419 int Offset = ShuffleMask & 0x7;
14420 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14421 return std::pair<unsigned, int>{SrcIdx, Offset};
14422 }))
14423 return false;
14424 return Success(R, E);
14425 }
14426 case X86::BI__builtin_ia32_vpermi2varqi128:
14427 case X86::BI__builtin_ia32_vpermi2varhi256:
14428 case X86::BI__builtin_ia32_vpermi2vard512:
14429 case X86::BI__builtin_ia32_vpermi2varps512: {
14430 APValue R;
14431 if (!evalShuffleGeneric(Info, E, R,
14432 [](unsigned DstIdx, unsigned ShuffleMask) {
14433 int Offset = ShuffleMask & 0xF;
14434 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14435 return std::pair<unsigned, int>{SrcIdx, Offset};
14436 }))
14437 return false;
14438 return Success(R, E);
14439 }
14440 case X86::BI__builtin_ia32_vpermi2varqi256:
14441 case X86::BI__builtin_ia32_vpermi2varhi512: {
14442 APValue R;
14443 if (!evalShuffleGeneric(Info, E, R,
14444 [](unsigned DstIdx, unsigned ShuffleMask) {
14445 int Offset = ShuffleMask & 0x1F;
14446 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14447 return std::pair<unsigned, int>{SrcIdx, Offset};
14448 }))
14449 return false;
14450 return Success(R, E);
14451 }
14452 case X86::BI__builtin_ia32_vpermi2varqi512: {
14453 APValue R;
14454 if (!evalShuffleGeneric(Info, E, R,
14455 [](unsigned DstIdx, unsigned ShuffleMask) {
14456 int Offset = ShuffleMask & 0x3F;
14457 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14458 return std::pair<unsigned, int>{SrcIdx, Offset};
14459 }))
14460 return false;
14461 return Success(R, E);
14462 }
14463
14464 case clang::X86::BI__builtin_ia32_minps:
14465 case clang::X86::BI__builtin_ia32_minpd:
14466 case clang::X86::BI__builtin_ia32_minps256:
14467 case clang::X86::BI__builtin_ia32_minpd256:
14468 case clang::X86::BI__builtin_ia32_minps512:
14469 case clang::X86::BI__builtin_ia32_minpd512:
14470 case clang::X86::BI__builtin_ia32_minph128:
14471 case clang::X86::BI__builtin_ia32_minph256:
14472 case clang::X86::BI__builtin_ia32_minph512:
14473 return EvaluateFpBinOpExpr(
14474 [](const APFloat &A, const APFloat &B,
14475 std::optional<APSInt>) -> std::optional<APFloat> {
14476 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14477 B.isInfinity() || B.isDenormal())
14478 return std::nullopt;
14479 if (A.isZero() && B.isZero())
14480 return B;
14481 return llvm::minimum(A, B);
14482 });
14483
14484 case clang::X86::BI__builtin_ia32_minss:
14485 case clang::X86::BI__builtin_ia32_minsd:
14486 return EvaluateFpBinOpExpr(
14487 [](const APFloat &A, const APFloat &B,
14488 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14489 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14490 },
14491 /*IsScalar=*/true);
14492
14493 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14494 case clang::X86::BI__builtin_ia32_minss_round_mask:
14495 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14496 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14497 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14498 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14499 bool IsMin =
14500 E->getBuiltinCallee() ==
14501 clang::X86::BI__builtin_ia32_minsd_round_mask ||
14502 E->getBuiltinCallee() ==
14503 clang::X86::BI__builtin_ia32_minss_round_mask ||
14504 E->getBuiltinCallee() == clang::X86::BI__builtin_ia32_minsh_round_mask;
14505 return EvaluateScalarFpRoundMaskBinOp(
14506 [IsMin](const APFloat &A, const APFloat &B,
14507 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14508 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14509 });
14510 }
14511
14512 case clang::X86::BI__builtin_ia32_maxps:
14513 case clang::X86::BI__builtin_ia32_maxpd:
14514 case clang::X86::BI__builtin_ia32_maxps256:
14515 case clang::X86::BI__builtin_ia32_maxpd256:
14516 case clang::X86::BI__builtin_ia32_maxps512:
14517 case clang::X86::BI__builtin_ia32_maxpd512:
14518 case clang::X86::BI__builtin_ia32_maxph128:
14519 case clang::X86::BI__builtin_ia32_maxph256:
14520 case clang::X86::BI__builtin_ia32_maxph512:
14521 return EvaluateFpBinOpExpr(
14522 [](const APFloat &A, const APFloat &B,
14523 std::optional<APSInt>) -> std::optional<APFloat> {
14524 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14525 B.isInfinity() || B.isDenormal())
14526 return std::nullopt;
14527 if (A.isZero() && B.isZero())
14528 return B;
14529 return llvm::maximum(A, B);
14530 });
14531
14532 case clang::X86::BI__builtin_ia32_maxss:
14533 case clang::X86::BI__builtin_ia32_maxsd:
14534 return EvaluateFpBinOpExpr(
14535 [](const APFloat &A, const APFloat &B,
14536 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14537 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14538 },
14539 /*IsScalar=*/true);
14540
14541 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14542 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14543 APValue SrcVec;
14544 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14545 return false;
14546
14547 APSInt Imm;
14548 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14549 return false;
14550
14551 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14552 unsigned SrcNumElems = SrcVTy->getNumElements();
14553 const auto *DstVTy = E->getType()->castAs<VectorType>();
14554 unsigned DstNumElems = DstVTy->getNumElements();
14555 QualType DstElemTy = DstVTy->getElementType();
14556
14557 const llvm::fltSemantics &HalfSem =
14558 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14559
14560 int ImmVal = Imm.getZExtValue();
14561 bool UseMXCSR = (ImmVal & 4) != 0;
14562 bool IsFPConstrained =
14563 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14564
14565 llvm::RoundingMode RM;
14566 if (!UseMXCSR) {
14567 switch (ImmVal & 3) {
14568 case 0:
14569 RM = llvm::RoundingMode::NearestTiesToEven;
14570 break;
14571 case 1:
14572 RM = llvm::RoundingMode::TowardNegative;
14573 break;
14574 case 2:
14575 RM = llvm::RoundingMode::TowardPositive;
14576 break;
14577 case 3:
14578 RM = llvm::RoundingMode::TowardZero;
14579 break;
14580 default:
14581 llvm_unreachable("Invalid immediate rounding mode");
14582 }
14583 } else {
14584 RM = llvm::RoundingMode::NearestTiesToEven;
14585 }
14586
14587 SmallVector<APValue, 8> ResultElements;
14588 ResultElements.reserve(DstNumElems);
14589
14590 for (unsigned I = 0; I < SrcNumElems; ++I) {
14591 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14592
14593 bool LostInfo;
14594 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14595
14596 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14597 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14598 return false;
14599 }
14600
14601 APSInt DstInt(SrcVal.bitcastToAPInt(),
14603 ResultElements.push_back(APValue(DstInt));
14604 }
14605
14606 if (DstNumElems > SrcNumElems) {
14607 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14608 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14609 ResultElements.push_back(APValue(Zero));
14610 }
14611 }
14612
14613 return Success(ResultElements, E);
14614 }
14615 case X86::BI__builtin_ia32_vperm2f128_pd256:
14616 case X86::BI__builtin_ia32_vperm2f128_ps256:
14617 case X86::BI__builtin_ia32_vperm2f128_si256:
14618 case X86::BI__builtin_ia32_permti256: {
14619 unsigned NumElements =
14620 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14621 unsigned PreservedBitsCnt = NumElements >> 2;
14622 APValue R;
14623 if (!evalShuffleGeneric(
14624 Info, E, R,
14625 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14626 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14627 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14628
14629 if (ControlBits & 0b1000)
14630 return std::make_pair(0u, -1);
14631
14632 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14633 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14634 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14635 (DstIdx & PreservedBitsMask);
14636 return std::make_pair(SrcVecIdx, SrcIdx);
14637 }))
14638 return false;
14639 return Success(R, E);
14640 }
14641 }
14642}
14643
14644bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14645 APValue Source;
14646 QualType SourceVecType = E->getSrcExpr()->getType();
14647 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14648 return false;
14649
14650 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14651 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14652
14653 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14654
14655 auto SourceLen = Source.getVectorLength();
14656 SmallVector<APValue, 4> ResultElements;
14657 ResultElements.reserve(SourceLen);
14658 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14659 APValue Elt;
14660 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14661 Source.getVectorElt(EltNum), Elt))
14662 return false;
14663 ResultElements.push_back(std::move(Elt));
14664 }
14665
14666 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14667}
14668
14669static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14670 QualType ElemType, APValue const &VecVal1,
14671 APValue const &VecVal2, unsigned EltNum,
14672 APValue &Result) {
14673 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14674 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14675
14676 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14677 int64_t index = IndexVal.getExtValue();
14678 // The spec says that -1 should be treated as undef for optimizations,
14679 // but in constexpr we'd have to produce an APValue::Indeterminate,
14680 // which is prohibited from being a top-level constant value. Emit a
14681 // diagnostic instead.
14682 if (index == -1) {
14683 Info.FFDiag(
14684 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14685 << EltNum;
14686 return false;
14687 }
14688
14689 if (index < 0 ||
14690 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14691 llvm_unreachable("Out of bounds shuffle index");
14692
14693 if (index >= TotalElementsInInputVector1)
14694 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14695 else
14696 Result = VecVal1.getVectorElt(index);
14697 return true;
14698}
14699
14700bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14701 // FIXME: Unary shuffle with mask not currently supported.
14702 if (E->getNumSubExprs() == 2)
14703 return Error(E);
14704 APValue VecVal1;
14705 const Expr *Vec1 = E->getExpr(0);
14706 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14707 return false;
14708 APValue VecVal2;
14709 const Expr *Vec2 = E->getExpr(1);
14710 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14711 return false;
14712
14713 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14714 QualType DestElTy = DestVecTy->getElementType();
14715
14716 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14717
14718 SmallVector<APValue, 4> ResultElements;
14719 ResultElements.reserve(TotalElementsInOutputVector);
14720 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14721 APValue Elt;
14722 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14723 return false;
14724 ResultElements.push_back(std::move(Elt));
14725 }
14726
14727 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14728}
14729
14730//===----------------------------------------------------------------------===//
14731// Matrix Evaluation
14732//===----------------------------------------------------------------------===//
14733
14734namespace {
14735class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
14736 APValue &Result;
14737
14738public:
14739 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
14740 : ExprEvaluatorBaseTy(Info), Result(Result) {}
14741
14742 bool Success(ArrayRef<APValue> M, const Expr *E) {
14743 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
14744 assert(M.size() == CMTy->getNumElementsFlattened());
14745 // FIXME: remove this APValue copy.
14746 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
14747 return true;
14748 }
14749 bool Success(const APValue &M, const Expr *E) {
14750 assert(M.isMatrix() && "expected matrix");
14751 Result = M;
14752 return true;
14753 }
14754
14755 bool VisitCastExpr(const CastExpr *E);
14756 bool VisitInitListExpr(const InitListExpr *E);
14757};
14758} // end anonymous namespace
14759
14760static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
14761 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
14762 "not a matrix prvalue");
14763 return MatrixExprEvaluator(Info, Result).Visit(E);
14764}
14765
14766bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
14767 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14768 unsigned NumRows = MT->getNumRows();
14769 unsigned NumCols = MT->getNumColumns();
14770 unsigned NElts = NumRows * NumCols;
14771 QualType EltTy = MT->getElementType();
14772 const Expr *SE = E->getSubExpr();
14773
14774 switch (E->getCastKind()) {
14775 case CK_HLSLAggregateSplatCast: {
14776 APValue Val;
14777 QualType ValTy;
14778
14779 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14780 return false;
14781
14782 APValue CastedVal;
14783 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14784 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
14785 return false;
14786
14787 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
14788 return Success(SplatEls, E);
14789 }
14790 case CK_HLSLElementwiseCast: {
14791 SmallVector<APValue> SrcVals;
14792 SmallVector<QualType> SrcTypes;
14793
14794 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
14795 return false;
14796
14797 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14798 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
14799 SmallVector<APValue, 16> ResultEls(NElts);
14800 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
14801 ResultEls))
14802 return false;
14803 return Success(ResultEls, E);
14804 }
14805 default:
14806 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14807 }
14808}
14809
14810bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14811 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14812 QualType EltTy = MT->getElementType();
14813
14814 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
14815 "Expected number of elements in initializer list to match the number "
14816 "of matrix elements");
14817
14818 SmallVector<APValue, 16> Elements;
14819 Elements.reserve(MT->getNumElementsFlattened());
14820
14821 // The following loop assumes the elements of the matrix InitListExpr are in
14822 // row-major order, which matches the row-major ordering assumption of the
14823 // matrix APValue.
14824 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
14825 if (EltTy->isIntegerType()) {
14826 llvm::APSInt IntVal;
14827 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
14828 return false;
14829 Elements.push_back(APValue(IntVal));
14830 } else {
14831 llvm::APFloat FloatVal(0.0);
14832 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
14833 return false;
14834 Elements.push_back(APValue(FloatVal));
14835 }
14836 }
14837
14838 return Success(Elements, E);
14839}
14840
14841//===----------------------------------------------------------------------===//
14842// Array Evaluation
14843//===----------------------------------------------------------------------===//
14844
14845namespace {
14846 class ArrayExprEvaluator
14847 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14848 const LValue &This;
14849 APValue &Result;
14850 public:
14851
14852 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14853 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14854
14855 bool Success(const APValue &V, const Expr *E) {
14856 assert(V.isArray() && "expected array");
14857 Result = V;
14858 return true;
14859 }
14860
14861 bool ZeroInitialization(const Expr *E) {
14862 const ConstantArrayType *CAT =
14863 Info.Ctx.getAsConstantArrayType(E->getType());
14864 if (!CAT) {
14865 if (E->getType()->isIncompleteArrayType()) {
14866 // We can be asked to zero-initialize a flexible array member; this
14867 // is represented as an ImplicitValueInitExpr of incomplete array
14868 // type. In this case, the array has zero elements.
14869 Result = APValue(APValue::UninitArray(), 0, 0);
14870 return true;
14871 }
14872 // FIXME: We could handle VLAs here.
14873 return Error(E);
14874 }
14875
14876 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14877 if (!Result.hasArrayFiller())
14878 return true;
14879
14880 // Zero-initialize all elements.
14881 LValue Subobject = This;
14882 Subobject.addArray(Info, E, CAT);
14883 ImplicitValueInitExpr VIE(CAT->getElementType());
14884 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14885 }
14886
14887 bool VisitCallExpr(const CallExpr *E) {
14888 return handleCallExpr(E, Result, &This);
14889 }
14890 bool VisitCastExpr(const CastExpr *E);
14891 bool VisitInitListExpr(const InitListExpr *E,
14892 QualType AllocType = QualType());
14893 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14894 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14895 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14896 const LValue &Subobject,
14897 APValue *Value, QualType Type);
14898 bool VisitStringLiteral(const StringLiteral *E,
14899 QualType AllocType = QualType()) {
14900 expandStringLiteral(Info, E, Result, AllocType);
14901 return true;
14902 }
14903 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14904 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14905 ArrayRef<Expr *> Args,
14906 const Expr *ArrayFiller,
14907 QualType AllocType = QualType());
14908 };
14909} // end anonymous namespace
14910
14911static bool EvaluateArray(const Expr *E, const LValue &This,
14912 APValue &Result, EvalInfo &Info) {
14913 assert(!E->isValueDependent());
14914 assert(E->isPRValue() && E->getType()->isArrayType() &&
14915 "not an array prvalue");
14916 return ArrayExprEvaluator(Info, This, Result).Visit(E);
14917}
14918
14919static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
14920 APValue &Result, const InitListExpr *ILE,
14921 QualType AllocType) {
14922 assert(!ILE->isValueDependent());
14923 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
14924 "not an array prvalue");
14925 return ArrayExprEvaluator(Info, This, Result)
14926 .VisitInitListExpr(ILE, AllocType);
14927}
14928
14929static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
14930 APValue &Result,
14931 const CXXConstructExpr *CCE,
14932 QualType AllocType) {
14933 assert(!CCE->isValueDependent());
14934 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
14935 "not an array prvalue");
14936 return ArrayExprEvaluator(Info, This, Result)
14937 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
14938}
14939
14940// Return true iff the given array filler may depend on the element index.
14941static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
14942 // For now, just allow non-class value-initialization and initialization
14943 // lists comprised of them.
14944 if (isa<ImplicitValueInitExpr>(FillerExpr))
14945 return false;
14946 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
14947 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
14948 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
14949 return true;
14950 }
14951
14952 if (ILE->hasArrayFiller() &&
14953 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
14954 return true;
14955
14956 return false;
14957 }
14958 return true;
14959}
14960
14961bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
14962 const Expr *SE = E->getSubExpr();
14963
14964 switch (E->getCastKind()) {
14965 default:
14966 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14967 case CK_HLSLAggregateSplatCast: {
14968 APValue Val;
14969 QualType ValTy;
14970
14971 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14972 return false;
14973
14974 unsigned NEls = elementwiseSize(Info, E->getType());
14975
14976 SmallVector<APValue> SplatEls(NEls, Val);
14977 SmallVector<QualType> SplatType(NEls, ValTy);
14978
14979 // cast the elements
14980 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14981 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
14982 SplatType))
14983 return false;
14984
14985 return true;
14986 }
14987 case CK_HLSLElementwiseCast: {
14988 SmallVector<APValue> SrcEls;
14989 SmallVector<QualType> SrcTypes;
14990
14991 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
14992 return false;
14993
14994 // cast the elements
14995 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14996 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
14997 SrcTypes))
14998 return false;
14999 return true;
15000 }
15001 }
15002}
15003
15004bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15005 QualType AllocType) {
15006 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15007 AllocType.isNull() ? E->getType() : AllocType);
15008 if (!CAT)
15009 return Error(E);
15010
15011 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15012 // an appropriately-typed string literal enclosed in braces.
15013 if (E->isStringLiteralInit()) {
15014 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15015 // FIXME: Support ObjCEncodeExpr here once we support it in
15016 // ArrayExprEvaluator generally.
15017 if (!SL)
15018 return Error(E);
15019 return VisitStringLiteral(SL, AllocType);
15020 }
15021 // Any other transparent list init will need proper handling of the
15022 // AllocType; we can't just recurse to the inner initializer.
15023 assert(!E->isTransparent() &&
15024 "transparent array list initialization is not string literal init?");
15025
15026 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15027 AllocType);
15028}
15029
15030bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15031 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15032 QualType AllocType) {
15033 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15034 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15035
15036 bool Success = true;
15037
15038 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
15039 "zero-initialized array shouldn't have any initialized elts");
15040 APValue Filler;
15041 if (Result.isArray() && Result.hasArrayFiller())
15042 Filler = Result.getArrayFiller();
15043
15044 unsigned NumEltsToInit = Args.size();
15045 unsigned NumElts = CAT->getZExtSize();
15046
15047 // If the initializer might depend on the array index, run it for each
15048 // array element.
15049 if (NumEltsToInit != NumElts &&
15050 MaybeElementDependentArrayFiller(ArrayFiller)) {
15051 NumEltsToInit = NumElts;
15052 } else {
15053 for (auto *Init : Args) {
15054 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15055 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15056 }
15057 if (NumEltsToInit > NumElts)
15058 NumEltsToInit = NumElts;
15059 }
15060
15061 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15062 << NumEltsToInit << ".\n");
15063
15064 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15065
15066 // If the array was previously zero-initialized, preserve the
15067 // zero-initialized values.
15068 if (Filler.hasValue()) {
15069 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
15070 Result.getArrayInitializedElt(I) = Filler;
15071 if (Result.hasArrayFiller())
15072 Result.getArrayFiller() = Filler;
15073 }
15074
15075 LValue Subobject = This;
15076 Subobject.addArray(Info, ExprToVisit, CAT);
15077 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15078 if (Init->isValueDependent())
15079 return EvaluateDependentExpr(Init, Info);
15080
15081 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15082 Subobject, Init) ||
15083 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15084 CAT->getElementType(), 1)) {
15085 if (!Info.noteFailure())
15086 return false;
15087 Success = false;
15088 }
15089 return true;
15090 };
15091 unsigned ArrayIndex = 0;
15092 QualType DestTy = CAT->getElementType();
15093 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15094 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15095 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15096 if (ArrayIndex >= NumEltsToInit)
15097 break;
15098 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15099 StringLiteral *SL = EmbedS->getDataStringLiteral();
15100 for (unsigned I = EmbedS->getStartingElementPos(),
15101 N = EmbedS->getDataElementCount();
15102 I != EmbedS->getStartingElementPos() + N; ++I) {
15103 Value = SL->getCodeUnit(I);
15104 if (DestTy->isIntegerType()) {
15105 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15106 } else {
15107 assert(DestTy->isFloatingType() && "unexpected type");
15108 const FPOptions FPO =
15109 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15110 APFloat FValue(0.0);
15111 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15112 DestTy, FValue))
15113 return false;
15114 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15115 }
15116 ArrayIndex++;
15117 }
15118 } else {
15119 if (!Eval(Init, ArrayIndex))
15120 return false;
15121 ++ArrayIndex;
15122 }
15123 }
15124
15125 if (!Result.hasArrayFiller())
15126 return Success;
15127
15128 // If we get here, we have a trivial filler, which we can just evaluate
15129 // once and splat over the rest of the array elements.
15130 assert(ArrayFiller && "no array filler for incomplete init list");
15131 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15132 ArrayFiller) &&
15133 Success;
15134}
15135
15136bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15137 LValue CommonLV;
15138 if (E->getCommonExpr() &&
15139 !Evaluate(Info.CurrentCall->createTemporary(
15140 E->getCommonExpr(),
15141 getStorageType(Info.Ctx, E->getCommonExpr()),
15142 ScopeKind::FullExpression, CommonLV),
15143 Info, E->getCommonExpr()->getSourceExpr()))
15144 return false;
15145
15147
15148 uint64_t Elements = CAT->getZExtSize();
15149 Result = APValue(APValue::UninitArray(), Elements, Elements);
15150
15151 LValue Subobject = This;
15152 Subobject.addArray(Info, E, CAT);
15153
15154 bool Success = true;
15155 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15156 // C++ [class.temporary]/5
15157 // There are four contexts in which temporaries are destroyed at a different
15158 // point than the end of the full-expression. [...] The second context is
15159 // when a copy constructor is called to copy an element of an array while
15160 // the entire array is copied [...]. In either case, if the constructor has
15161 // one or more default arguments, the destruction of every temporary created
15162 // in a default argument is sequenced before the construction of the next
15163 // array element, if any.
15164 FullExpressionRAII Scope(Info);
15165
15166 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15167 Info, Subobject, E->getSubExpr()) ||
15168 !HandleLValueArrayAdjustment(Info, E, Subobject,
15169 CAT->getElementType(), 1)) {
15170 if (!Info.noteFailure())
15171 return false;
15172 Success = false;
15173 }
15174
15175 // Make sure we run the destructors too.
15176 Scope.destroy();
15177 }
15178
15179 return Success;
15180}
15181
15182bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15183 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15184}
15185
15186bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15187 const LValue &Subobject,
15188 APValue *Value,
15189 QualType Type) {
15190 bool HadZeroInit = Value->hasValue();
15191
15192 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15193 unsigned FinalSize = CAT->getZExtSize();
15194
15195 // Preserve the array filler if we had prior zero-initialization.
15196 APValue Filler =
15197 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15198 : APValue();
15199
15200 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15201 if (FinalSize == 0)
15202 return true;
15203
15204 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15205 Info, E->getExprLoc(), E->getConstructor(),
15207 LValue ArrayElt = Subobject;
15208 ArrayElt.addArray(Info, E, CAT);
15209 // We do the whole initialization in two passes, first for just one element,
15210 // then for the whole array. It's possible we may find out we can't do const
15211 // init in the first pass, in which case we avoid allocating a potentially
15212 // large array. We don't do more passes because expanding array requires
15213 // copying the data, which is wasteful.
15214 for (const unsigned N : {1u, FinalSize}) {
15215 unsigned OldElts = Value->getArrayInitializedElts();
15216 if (OldElts == N)
15217 break;
15218
15219 // Expand the array to appropriate size.
15220 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15221 for (unsigned I = 0; I < OldElts; ++I)
15222 NewValue.getArrayInitializedElt(I).swap(
15223 Value->getArrayInitializedElt(I));
15224 Value->swap(NewValue);
15225
15226 if (HadZeroInit)
15227 for (unsigned I = OldElts; I < N; ++I)
15228 Value->getArrayInitializedElt(I) = Filler;
15229
15230 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15231 // If we have a trivial constructor, only evaluate it once and copy
15232 // the result into all the array elements.
15233 APValue &FirstResult = Value->getArrayInitializedElt(0);
15234 for (unsigned I = OldElts; I < FinalSize; ++I)
15235 Value->getArrayInitializedElt(I) = FirstResult;
15236 } else {
15237 for (unsigned I = OldElts; I < N; ++I) {
15238 if (!VisitCXXConstructExpr(E, ArrayElt,
15239 &Value->getArrayInitializedElt(I),
15240 CAT->getElementType()) ||
15241 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15242 CAT->getElementType(), 1))
15243 return false;
15244 // When checking for const initilization any diagnostic is considered
15245 // an error.
15246 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15247 !Info.keepEvaluatingAfterFailure())
15248 return false;
15249 }
15250 }
15251 }
15252
15253 return true;
15254 }
15255
15256 if (!Type->isRecordType())
15257 return Error(E);
15258
15259 return RecordExprEvaluator(Info, Subobject, *Value)
15260 .VisitCXXConstructExpr(E, Type);
15261}
15262
15263bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15264 const CXXParenListInitExpr *E) {
15265 assert(E->getType()->isConstantArrayType() &&
15266 "Expression result is not a constant array type");
15267
15268 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15269 E->getArrayFiller());
15270}
15271
15272//===----------------------------------------------------------------------===//
15273// Integer Evaluation
15274//
15275// As a GNU extension, we support casting pointers to sufficiently-wide integer
15276// types and back in constant folding. Integer values are thus represented
15277// either as an integer-valued APValue, or as an lvalue-valued APValue.
15278//===----------------------------------------------------------------------===//
15279
15280namespace {
15281class IntExprEvaluator
15282 : public ExprEvaluatorBase<IntExprEvaluator> {
15283 APValue &Result;
15284public:
15285 IntExprEvaluator(EvalInfo &info, APValue &result)
15286 : ExprEvaluatorBaseTy(info), Result(result) {}
15287
15288 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15289 assert(E->getType()->isIntegralOrEnumerationType() &&
15290 "Invalid evaluation result.");
15291 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15292 "Invalid evaluation result.");
15293 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15294 "Invalid evaluation result.");
15295 Result = APValue(SI);
15296 return true;
15297 }
15298 bool Success(const llvm::APSInt &SI, const Expr *E) {
15299 return Success(SI, E, Result);
15300 }
15301
15302 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15303 assert(E->getType()->isIntegralOrEnumerationType() &&
15304 "Invalid evaluation result.");
15305 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15306 "Invalid evaluation result.");
15307 Result = APValue(APSInt(I));
15308 Result.getInt().setIsUnsigned(
15310 return true;
15311 }
15312 bool Success(const llvm::APInt &I, const Expr *E) {
15313 return Success(I, E, Result);
15314 }
15315
15316 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15317 assert(E->getType()->isIntegralOrEnumerationType() &&
15318 "Invalid evaluation result.");
15319 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15320 return true;
15321 }
15322 bool Success(uint64_t Value, const Expr *E) {
15323 return Success(Value, E, Result);
15324 }
15325
15326 bool Success(CharUnits Size, const Expr *E) {
15327 return Success(Size.getQuantity(), E);
15328 }
15329
15330 bool Success(const APValue &V, const Expr *E) {
15331 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15332 // pointer allow further evaluation of the value.
15333 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15334 V.allowConstexprUnknown()) {
15335 Result = V;
15336 return true;
15337 }
15338 return Success(V.getInt(), E);
15339 }
15340
15341 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15342
15343 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15344 const CallExpr *);
15345
15346 //===--------------------------------------------------------------------===//
15347 // Visitor Methods
15348 //===--------------------------------------------------------------------===//
15349
15350 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15351 return Success(E->getValue(), E);
15352 }
15353 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15354 return Success(E->getValue(), E);
15355 }
15356
15357 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15358 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15359 if (CheckReferencedDecl(E, E->getDecl()))
15360 return true;
15361
15362 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15363 }
15364 bool VisitMemberExpr(const MemberExpr *E) {
15365 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15366 VisitIgnoredBaseExpression(E->getBase());
15367 return true;
15368 }
15369
15370 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15371 }
15372
15373 bool VisitCallExpr(const CallExpr *E);
15374 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15375 bool VisitBinaryOperator(const BinaryOperator *E);
15376 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15377 bool VisitUnaryOperator(const UnaryOperator *E);
15378
15379 bool VisitCastExpr(const CastExpr* E);
15380 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15381
15382 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15383 return Success(E->getValue(), E);
15384 }
15385
15386 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15387 return Success(E->getValue(), E);
15388 }
15389
15390 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15391 if (Info.ArrayInitIndex == uint64_t(-1)) {
15392 // We were asked to evaluate this subexpression independent of the
15393 // enclosing ArrayInitLoopExpr. We can't do that.
15394 Info.FFDiag(E);
15395 return false;
15396 }
15397 return Success(Info.ArrayInitIndex, E);
15398 }
15399
15400 // Note, GNU defines __null as an integer, not a pointer.
15401 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15402 return ZeroInitialization(E);
15403 }
15404
15405 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15406 if (E->isStoredAsBoolean())
15407 return Success(E->getBoolValue(), E);
15408 if (E->getAPValue().isAbsent())
15409 return false;
15410 assert(E->getAPValue().isInt() && "APValue type not supported");
15411 return Success(E->getAPValue().getInt(), E);
15412 }
15413
15414 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15415 return Success(E->getValue(), E);
15416 }
15417
15418 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15419 return Success(E->getValue(), E);
15420 }
15421
15422 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15423 // This should not be evaluated during constant expr evaluation, as it
15424 // should always be in an unevaluated context (the args list of a 'gang' or
15425 // 'tile' clause).
15426 return Error(E);
15427 }
15428
15429 bool VisitUnaryReal(const UnaryOperator *E);
15430 bool VisitUnaryImag(const UnaryOperator *E);
15431
15432 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15433 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15434 bool VisitSourceLocExpr(const SourceLocExpr *E);
15435 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15436 bool VisitRequiresExpr(const RequiresExpr *E);
15437 // FIXME: Missing: array subscript of vector, member of vector
15438};
15439
15440class FixedPointExprEvaluator
15441 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15442 APValue &Result;
15443
15444 public:
15445 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15446 : ExprEvaluatorBaseTy(info), Result(result) {}
15447
15448 bool Success(const llvm::APInt &I, const Expr *E) {
15449 return Success(
15450 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15451 }
15452
15453 bool Success(uint64_t Value, const Expr *E) {
15454 return Success(
15455 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15456 }
15457
15458 bool Success(const APValue &V, const Expr *E) {
15459 return Success(V.getFixedPoint(), E);
15460 }
15461
15462 bool Success(const APFixedPoint &V, const Expr *E) {
15463 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15464 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15465 "Invalid evaluation result.");
15466 Result = APValue(V);
15467 return true;
15468 }
15469
15470 bool ZeroInitialization(const Expr *E) {
15471 return Success(0, E);
15472 }
15473
15474 //===--------------------------------------------------------------------===//
15475 // Visitor Methods
15476 //===--------------------------------------------------------------------===//
15477
15478 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15479 return Success(E->getValue(), E);
15480 }
15481
15482 bool VisitCastExpr(const CastExpr *E);
15483 bool VisitUnaryOperator(const UnaryOperator *E);
15484 bool VisitBinaryOperator(const BinaryOperator *E);
15485};
15486} // end anonymous namespace
15487
15488/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15489/// produce either the integer value or a pointer.
15490///
15491/// GCC has a heinous extension which folds casts between pointer types and
15492/// pointer-sized integral types. We support this by allowing the evaluation of
15493/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15494/// Some simple arithmetic on such values is supported (they are treated much
15495/// like char*).
15496static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
15497 EvalInfo &Info) {
15498 assert(!E->isValueDependent());
15499 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15500 return IntExprEvaluator(Info, Result).Visit(E);
15501}
15502
15503static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15504 assert(!E->isValueDependent());
15505 APValue Val;
15506 if (!EvaluateIntegerOrLValue(E, Val, Info))
15507 return false;
15508 if (!Val.isInt()) {
15509 // FIXME: It would be better to produce the diagnostic for casting
15510 // a pointer to an integer.
15511 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15512 return false;
15513 }
15514 Result = Val.getInt();
15515 return true;
15516}
15517
15518bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15520 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15521 return Success(Evaluated, E);
15522}
15523
15524static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15525 EvalInfo &Info) {
15526 assert(!E->isValueDependent());
15527 if (E->getType()->isFixedPointType()) {
15528 APValue Val;
15529 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15530 return false;
15531 if (!Val.isFixedPoint())
15532 return false;
15533
15534 Result = Val.getFixedPoint();
15535 return true;
15536 }
15537 return false;
15538}
15539
15540static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15541 EvalInfo &Info) {
15542 assert(!E->isValueDependent());
15543 if (E->getType()->isIntegerType()) {
15544 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15545 APSInt Val;
15546 if (!EvaluateInteger(E, Val, Info))
15547 return false;
15548 Result = APFixedPoint(Val, FXSema);
15549 return true;
15550 } else if (E->getType()->isFixedPointType()) {
15551 return EvaluateFixedPoint(E, Result, Info);
15552 }
15553 return false;
15554}
15555
15556/// Check whether the given declaration can be directly converted to an integral
15557/// rvalue. If not, no diagnostic is produced; there are other things we can
15558/// try.
15559bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15560 // Enums are integer constant exprs.
15561 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15562 // Check for signedness/width mismatches between E type and ECD value.
15563 bool SameSign = (ECD->getInitVal().isSigned()
15565 bool SameWidth = (ECD->getInitVal().getBitWidth()
15566 == Info.Ctx.getIntWidth(E->getType()));
15567 if (SameSign && SameWidth)
15568 return Success(ECD->getInitVal(), E);
15569 else {
15570 // Get rid of mismatch (otherwise Success assertions will fail)
15571 // by computing a new value matching the type of E.
15572 llvm::APSInt Val = ECD->getInitVal();
15573 if (!SameSign)
15574 Val.setIsSigned(!ECD->getInitVal().isSigned());
15575 if (!SameWidth)
15576 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15577 return Success(Val, E);
15578 }
15579 }
15580 return false;
15581}
15582
15583/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15584/// as GCC.
15586 const LangOptions &LangOpts) {
15587 assert(!T->isDependentType() && "unexpected dependent type");
15588
15589 QualType CanTy = T.getCanonicalType();
15590
15591 switch (CanTy->getTypeClass()) {
15592#define TYPE(ID, BASE)
15593#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15594#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15595#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15596#include "clang/AST/TypeNodes.inc"
15597 case Type::Auto:
15598 case Type::DeducedTemplateSpecialization:
15599 llvm_unreachable("unexpected non-canonical or dependent type");
15600
15601 case Type::Builtin:
15602 switch (cast<BuiltinType>(CanTy)->getKind()) {
15603#define BUILTIN_TYPE(ID, SINGLETON_ID)
15604#define SIGNED_TYPE(ID, SINGLETON_ID) \
15605 case BuiltinType::ID: return GCCTypeClass::Integer;
15606#define FLOATING_TYPE(ID, SINGLETON_ID) \
15607 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15608#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15609 case BuiltinType::ID: break;
15610#include "clang/AST/BuiltinTypes.def"
15611 case BuiltinType::Void:
15612 return GCCTypeClass::Void;
15613
15614 case BuiltinType::Bool:
15615 return GCCTypeClass::Bool;
15616
15617 case BuiltinType::Char_U:
15618 case BuiltinType::UChar:
15619 case BuiltinType::WChar_U:
15620 case BuiltinType::Char8:
15621 case BuiltinType::Char16:
15622 case BuiltinType::Char32:
15623 case BuiltinType::UShort:
15624 case BuiltinType::UInt:
15625 case BuiltinType::ULong:
15626 case BuiltinType::ULongLong:
15627 case BuiltinType::UInt128:
15628 return GCCTypeClass::Integer;
15629
15630 case BuiltinType::UShortAccum:
15631 case BuiltinType::UAccum:
15632 case BuiltinType::ULongAccum:
15633 case BuiltinType::UShortFract:
15634 case BuiltinType::UFract:
15635 case BuiltinType::ULongFract:
15636 case BuiltinType::SatUShortAccum:
15637 case BuiltinType::SatUAccum:
15638 case BuiltinType::SatULongAccum:
15639 case BuiltinType::SatUShortFract:
15640 case BuiltinType::SatUFract:
15641 case BuiltinType::SatULongFract:
15642 return GCCTypeClass::None;
15643
15644 case BuiltinType::NullPtr:
15645
15646 case BuiltinType::ObjCId:
15647 case BuiltinType::ObjCClass:
15648 case BuiltinType::ObjCSel:
15649#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15650 case BuiltinType::Id:
15651#include "clang/Basic/OpenCLImageTypes.def"
15652#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15653 case BuiltinType::Id:
15654#include "clang/Basic/OpenCLExtensionTypes.def"
15655 case BuiltinType::OCLSampler:
15656 case BuiltinType::OCLEvent:
15657 case BuiltinType::OCLClkEvent:
15658 case BuiltinType::OCLQueue:
15659 case BuiltinType::OCLReserveID:
15660#define SVE_TYPE(Name, Id, SingletonId) \
15661 case BuiltinType::Id:
15662#include "clang/Basic/AArch64ACLETypes.def"
15663#define PPC_VECTOR_TYPE(Name, Id, Size) \
15664 case BuiltinType::Id:
15665#include "clang/Basic/PPCTypes.def"
15666#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15667#include "clang/Basic/RISCVVTypes.def"
15668#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15669#include "clang/Basic/WebAssemblyReferenceTypes.def"
15670#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15671#include "clang/Basic/AMDGPUTypes.def"
15672#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15673#include "clang/Basic/HLSLIntangibleTypes.def"
15674 return GCCTypeClass::None;
15675
15676 case BuiltinType::Dependent:
15677 llvm_unreachable("unexpected dependent type");
15678 };
15679 llvm_unreachable("unexpected placeholder type");
15680
15681 case Type::Enum:
15682 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15683
15684 case Type::Pointer:
15685 case Type::ConstantArray:
15686 case Type::VariableArray:
15687 case Type::IncompleteArray:
15688 case Type::FunctionNoProto:
15689 case Type::FunctionProto:
15690 case Type::ArrayParameter:
15691 return GCCTypeClass::Pointer;
15692
15693 case Type::MemberPointer:
15694 return CanTy->isMemberDataPointerType()
15697
15698 case Type::Complex:
15699 return GCCTypeClass::Complex;
15700
15701 case Type::Record:
15702 return CanTy->isUnionType() ? GCCTypeClass::Union
15704
15705 case Type::Atomic:
15706 // GCC classifies _Atomic T the same as T.
15708 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15709
15710 case Type::Vector:
15711 case Type::ExtVector:
15712 return GCCTypeClass::Vector;
15713
15714 case Type::BlockPointer:
15715 case Type::ConstantMatrix:
15716 case Type::ObjCObject:
15717 case Type::ObjCInterface:
15718 case Type::ObjCObjectPointer:
15719 case Type::Pipe:
15720 case Type::HLSLAttributedResource:
15721 case Type::HLSLInlineSpirv:
15722 case Type::OverflowBehavior:
15723 // Classify all other types that don't fit into the regular
15724 // classification the same way.
15725 return GCCTypeClass::None;
15726
15727 case Type::BitInt:
15728 return GCCTypeClass::BitInt;
15729
15730 case Type::LValueReference:
15731 case Type::RValueReference:
15732 llvm_unreachable("invalid type for expression");
15733 }
15734
15735 llvm_unreachable("unexpected type class");
15736}
15737
15738/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15739/// as GCC.
15740static GCCTypeClass
15742 // If no argument was supplied, default to None. This isn't
15743 // ideal, however it is what gcc does.
15744 if (E->getNumArgs() == 0)
15745 return GCCTypeClass::None;
15746
15747 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15748 // being an ICE, but still folds it to a constant using the type of the first
15749 // argument.
15750 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15751}
15752
15753/// EvaluateBuiltinConstantPForLValue - Determine the result of
15754/// __builtin_constant_p when applied to the given pointer.
15755///
15756/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15757/// or it points to the first character of a string literal.
15760 if (Base.isNull()) {
15761 // A null base is acceptable.
15762 return true;
15763 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15764 if (!isa<StringLiteral>(E))
15765 return false;
15766 return LV.getLValueOffset().isZero();
15767 } else if (Base.is<TypeInfoLValue>()) {
15768 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15769 // evaluate to true.
15770 return true;
15771 } else {
15772 // Any other base is not constant enough for GCC.
15773 return false;
15774 }
15775}
15776
15777/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15778/// GCC as we can manage.
15779static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15780 // This evaluation is not permitted to have side-effects, so evaluate it in
15781 // a speculative evaluation context.
15782 SpeculativeEvaluationRAII SpeculativeEval(Info);
15783
15784 // Constant-folding is always enabled for the operand of __builtin_constant_p
15785 // (even when the enclosing evaluation context otherwise requires a strict
15786 // language-specific constant expression).
15787 FoldConstant Fold(Info, true);
15788
15789 QualType ArgType = Arg->getType();
15790
15791 // __builtin_constant_p always has one operand. The rules which gcc follows
15792 // are not precisely documented, but are as follows:
15793 //
15794 // - If the operand is of integral, floating, complex or enumeration type,
15795 // and can be folded to a known value of that type, it returns 1.
15796 // - If the operand can be folded to a pointer to the first character
15797 // of a string literal (or such a pointer cast to an integral type)
15798 // or to a null pointer or an integer cast to a pointer, it returns 1.
15799 //
15800 // Otherwise, it returns 0.
15801 //
15802 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15803 // its support for this did not work prior to GCC 9 and is not yet well
15804 // understood.
15805 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15806 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15807 ArgType->isNullPtrType()) {
15808 APValue V;
15809 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15810 Fold.keepDiagnostics();
15811 return false;
15812 }
15813
15814 // For a pointer (possibly cast to integer), there are special rules.
15815 if (V.getKind() == APValue::LValue)
15817
15818 // Otherwise, any constant value is good enough.
15819 return V.hasValue();
15820 }
15821
15822 // Anything else isn't considered to be sufficiently constant.
15823 return false;
15824}
15825
15826/// Retrieves the "underlying object type" of the given expression,
15827/// as used by __builtin_object_size.
15829 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15830 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15831 return VD->getType();
15832 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15834 return E->getType();
15835 } else if (B.is<TypeInfoLValue>()) {
15836 return B.getTypeInfoType();
15837 } else if (B.is<DynamicAllocLValue>()) {
15838 return B.getDynamicAllocType();
15839 }
15840
15841 return QualType();
15842}
15843
15844/// A more selective version of E->IgnoreParenCasts for
15845/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15846/// to change the type of E.
15847/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15848///
15849/// Always returns an RValue with a pointer representation.
15850static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15851 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15852
15853 const Expr *NoParens = E->IgnoreParens();
15854 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15855 if (Cast == nullptr)
15856 return NoParens;
15857
15858 // We only conservatively allow a few kinds of casts, because this code is
15859 // inherently a simple solution that seeks to support the common case.
15860 auto CastKind = Cast->getCastKind();
15861 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15862 CastKind != CK_AddressSpaceConversion)
15863 return NoParens;
15864
15865 const auto *SubExpr = Cast->getSubExpr();
15866 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15867 return NoParens;
15868 return ignorePointerCastsAndParens(SubExpr);
15869}
15870
15871/// Checks to see if the given LValue's Designator is at the end of the LValue's
15872/// record layout. e.g.
15873/// struct { struct { int a, b; } fst, snd; } obj;
15874/// obj.fst // no
15875/// obj.snd // yes
15876/// obj.fst.a // no
15877/// obj.fst.b // no
15878/// obj.snd.a // no
15879/// obj.snd.b // yes
15880///
15881/// Please note: this function is specialized for how __builtin_object_size
15882/// views "objects".
15883///
15884/// If this encounters an invalid RecordDecl or otherwise cannot determine the
15885/// correct result, it will always return true.
15886static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
15887 assert(!LVal.Designator.Invalid);
15888
15889 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
15890 const RecordDecl *Parent = FD->getParent();
15891 if (Parent->isInvalidDecl() || Parent->isUnion())
15892 return true;
15893 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
15894 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
15895 };
15896
15897 auto &Base = LVal.getLValueBase();
15898 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
15899 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
15900 if (!IsLastOrInvalidFieldDecl(FD))
15901 return false;
15902 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
15903 for (auto *FD : IFD->chain()) {
15904 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
15905 return false;
15906 }
15907 }
15908 }
15909
15910 unsigned I = 0;
15911 QualType BaseType = getType(Base);
15912 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
15913 // If we don't know the array bound, conservatively assume we're looking at
15914 // the final array element.
15915 ++I;
15916 if (BaseType->isIncompleteArrayType())
15917 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
15918 else
15919 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
15920 }
15921
15922 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
15923 const auto &Entry = LVal.Designator.Entries[I];
15924 if (BaseType->isArrayType()) {
15925 // Because __builtin_object_size treats arrays as objects, we can ignore
15926 // the index iff this is the last array in the Designator.
15927 if (I + 1 == E)
15928 return true;
15929 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
15930 uint64_t Index = Entry.getAsArrayIndex();
15931 if (Index + 1 != CAT->getZExtSize())
15932 return false;
15933 BaseType = CAT->getElementType();
15934 } else if (BaseType->isAnyComplexType()) {
15935 const auto *CT = BaseType->castAs<ComplexType>();
15936 uint64_t Index = Entry.getAsArrayIndex();
15937 if (Index != 1)
15938 return false;
15939 BaseType = CT->getElementType();
15940 } else if (auto *FD = getAsField(Entry)) {
15941 if (!IsLastOrInvalidFieldDecl(FD))
15942 return false;
15943 BaseType = FD->getType();
15944 } else {
15945 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
15946 return false;
15947 }
15948 }
15949 return true;
15950}
15951
15952/// Tests to see if the LValue has a user-specified designator (that isn't
15953/// necessarily valid). Note that this always returns 'true' if the LValue has
15954/// an unsized array as its first designator entry, because there's currently no
15955/// way to tell if the user typed *foo or foo[0].
15956static bool refersToCompleteObject(const LValue &LVal) {
15957 if (LVal.Designator.Invalid)
15958 return false;
15959
15960 if (!LVal.Designator.Entries.empty())
15961 return LVal.Designator.isMostDerivedAnUnsizedArray();
15962
15963 if (!LVal.InvalidBase)
15964 return true;
15965
15966 // If `E` is a MemberExpr, then the first part of the designator is hiding in
15967 // the LValueBase.
15968 const auto *E = LVal.Base.dyn_cast<const Expr *>();
15969 return !E || !isa<MemberExpr>(E);
15970}
15971
15972/// Attempts to detect a user writing into a piece of memory that's impossible
15973/// to figure out the size of by just using types.
15974static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
15975 const SubobjectDesignator &Designator = LVal.Designator;
15976 // Notes:
15977 // - Users can only write off of the end when we have an invalid base. Invalid
15978 // bases imply we don't know where the memory came from.
15979 // - We used to be a bit more aggressive here; we'd only be conservative if
15980 // the array at the end was flexible, or if it had 0 or 1 elements. This
15981 // broke some common standard library extensions (PR30346), but was
15982 // otherwise seemingly fine. It may be useful to reintroduce this behavior
15983 // with some sort of list. OTOH, it seems that GCC is always
15984 // conservative with the last element in structs (if it's an array), so our
15985 // current behavior is more compatible than an explicit list approach would
15986 // be.
15987 auto isFlexibleArrayMember = [&] {
15989 FAMKind StrictFlexArraysLevel =
15990 Ctx.getLangOpts().getStrictFlexArraysLevel();
15991
15992 if (Designator.isMostDerivedAnUnsizedArray())
15993 return true;
15994
15995 if (StrictFlexArraysLevel == FAMKind::Default)
15996 return true;
15997
15998 if (Designator.getMostDerivedArraySize() == 0 &&
15999 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16000 return true;
16001
16002 if (Designator.getMostDerivedArraySize() == 1 &&
16003 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16004 return true;
16005
16006 return false;
16007 };
16008
16009 return LVal.InvalidBase &&
16010 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16011 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16012 isDesignatorAtObjectEnd(Ctx, LVal);
16013}
16014
16015/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16016/// Fails if the conversion would cause loss of precision.
16017static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16018 CharUnits &Result) {
16019 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16020 if (Int.ugt(CharUnitsMax))
16021 return false;
16022 Result = CharUnits::fromQuantity(Int.getZExtValue());
16023 return true;
16024}
16025
16026/// If we're evaluating the object size of an instance of a struct that
16027/// contains a flexible array member, add the size of the initializer.
16028static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16029 const LValue &LV, CharUnits &Size) {
16030 if (!T.isNull() && T->isStructureType() &&
16031 T->castAsRecordDecl()->hasFlexibleArrayMember())
16032 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16033 if (const auto *VD = dyn_cast<VarDecl>(V))
16034 if (VD->hasInit())
16035 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16036}
16037
16038/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16039/// determine how many bytes exist from the beginning of the object to either
16040/// the end of the current subobject, or the end of the object itself, depending
16041/// on what the LValue looks like + the value of Type.
16042///
16043/// If this returns false, the value of Result is undefined.
16044static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16045 unsigned Type, const LValue &LVal,
16046 CharUnits &EndOffset) {
16047 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16048
16049 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16050 if (Ty.isNull())
16051 return false;
16052
16053 Ty = Ty.getNonReferenceType();
16054
16055 if (Ty->isIncompleteType() || Ty->isFunctionType())
16056 return false;
16057
16058 return HandleSizeof(Info, ExprLoc, Ty, Result);
16059 };
16060
16061 // We want to evaluate the size of the entire object. This is a valid fallback
16062 // for when Type=1 and the designator is invalid, because we're asked for an
16063 // upper-bound.
16064 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16065 // Type=3 wants a lower bound, so we can't fall back to this.
16066 if (Type == 3 && !DetermineForCompleteObject)
16067 return false;
16068
16069 llvm::APInt APEndOffset;
16070 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16071 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16072 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16073
16074 if (LVal.InvalidBase)
16075 return false;
16076
16077 QualType BaseTy = getObjectType(LVal.getLValueBase());
16078 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16079 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16080 return Ret;
16081 }
16082
16083 // We want to evaluate the size of a subobject.
16084 const SubobjectDesignator &Designator = LVal.Designator;
16085
16086 // The following is a moderately common idiom in C:
16087 //
16088 // struct Foo { int a; char c[1]; };
16089 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16090 // strcpy(&F->c[0], Bar);
16091 //
16092 // In order to not break too much legacy code, we need to support it.
16093 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16094 // If we can resolve this to an alloc_size call, we can hand that back,
16095 // because we know for certain how many bytes there are to write to.
16096 llvm::APInt APEndOffset;
16097 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16098 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16099 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16100
16101 // If we cannot determine the size of the initial allocation, then we can't
16102 // given an accurate upper-bound. However, we are still able to give
16103 // conservative lower-bounds for Type=3.
16104 if (Type == 1)
16105 return false;
16106 }
16107
16108 CharUnits BytesPerElem;
16109 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16110 return false;
16111
16112 // According to the GCC documentation, we want the size of the subobject
16113 // denoted by the pointer. But that's not quite right -- what we actually
16114 // want is the size of the immediately-enclosing array, if there is one.
16115 int64_t ElemsRemaining;
16116 if (Designator.MostDerivedIsArrayElement &&
16117 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16118 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16119 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16120 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16121 } else {
16122 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16123 }
16124
16125 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16126 return true;
16127}
16128
16129/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16130/// returns true and stores the result in @p Size.
16131///
16132/// If @p WasError is non-null, this will report whether the failure to evaluate
16133/// is to be treated as an Error in IntExprEvaluator.
16134static std::optional<uint64_t>
16135tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info) {
16136 // Determine the denoted object.
16137 LValue LVal;
16138 {
16139 // The operand of __builtin_object_size is never evaluated for side-effects.
16140 // If there are any, but we can determine the pointed-to object anyway, then
16141 // ignore the side-effects.
16142 SpeculativeEvaluationRAII SpeculativeEval(Info);
16143 IgnoreSideEffectsRAII Fold(Info);
16144
16145 if (E->isGLValue()) {
16146 // It's possible for us to be given GLValues if we're called via
16147 // Expr::tryEvaluateObjectSize.
16148 APValue RVal;
16149 if (!EvaluateAsRValue(Info, E, RVal))
16150 return std::nullopt;
16151 LVal.setFrom(Info.Ctx, RVal);
16152 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16153 /*InvalidBaseOK=*/true))
16154 return std::nullopt;
16155 }
16156
16157 // If we point to before the start of the object, there are no accessible
16158 // bytes.
16159 if (LVal.getLValueOffset().isNegative())
16160 return 0;
16161
16162 CharUnits EndOffset;
16163 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16164 return std::nullopt;
16165
16166 // If we've fallen outside of the end offset, just pretend there's nothing to
16167 // write to/read from.
16168 if (EndOffset <= LVal.getLValueOffset())
16169 return 0;
16170 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16171}
16172
16173bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16174 if (!IsConstantEvaluatedBuiltinCall(E))
16175 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16176 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
16177}
16178
16179static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16180 APValue &Val, APSInt &Alignment) {
16181 QualType SrcTy = E->getArg(0)->getType();
16182 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16183 return false;
16184 // Even though we are evaluating integer expressions we could get a pointer
16185 // argument for the __builtin_is_aligned() case.
16186 if (SrcTy->isPointerType()) {
16187 LValue Ptr;
16188 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16189 return false;
16190 Ptr.moveInto(Val);
16191 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16192 Info.FFDiag(E->getArg(0));
16193 return false;
16194 } else {
16195 APSInt SrcInt;
16196 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16197 return false;
16198 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16199 "Bit widths must be the same");
16200 Val = APValue(SrcInt);
16201 }
16202 assert(Val.hasValue());
16203 return true;
16204}
16205
16206bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16207 unsigned BuiltinOp) {
16208 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16209 Fn) {
16210 APValue SourceLHS, SourceRHS;
16211 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16212 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16213 return false;
16214
16215 unsigned SourceLen = SourceLHS.getVectorLength();
16216 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16217 QualType ElemQT = VT->getElementType();
16218 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16219
16220 APInt AWide(LaneWidth * SourceLen, 0);
16221 APInt BWide(LaneWidth * SourceLen, 0);
16222
16223 for (unsigned I = 0; I != SourceLen; ++I) {
16224 APInt ALane;
16225 APInt BLane;
16226 if (ElemQT->isIntegerType()) { // Get value.
16227 ALane = SourceLHS.getVectorElt(I).getInt();
16228 BLane = SourceRHS.getVectorElt(I).getInt();
16229 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16230 ALane =
16231 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16232 BLane =
16233 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16234 } else { // Must be integer or floating type.
16235 return false;
16236 }
16237 AWide.insertBits(ALane, I * LaneWidth);
16238 BWide.insertBits(BLane, I * LaneWidth);
16239 }
16240 return Success(Fn(AWide, BWide), E);
16241 };
16242
16243 auto HandleMaskBinOp =
16244 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16245 -> bool {
16246 APValue LHS, RHS;
16247 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16248 !Evaluate(RHS, Info, E->getArg(1)))
16249 return false;
16250
16251 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16252
16253 return Success(APValue(ResultInt), E);
16254 };
16255
16256 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16257 APSInt CRC, Data;
16258 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16259 !EvaluateInteger(E->getArg(1), Data, Info))
16260 return false;
16261
16262 uint64_t CRCVal = CRC.getZExtValue();
16263 uint64_t DataVal = Data.getZExtValue();
16264
16265 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16266 static const uint32_t CRC32C_POLY = 0x82F63B78;
16267
16268 // Process each byte
16269 uint32_t Result = static_cast<uint32_t>(CRCVal);
16270 for (unsigned I = 0; I != DataBytes; ++I) {
16271 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16272 Result ^= Byte;
16273 for (int J = 0; J != 8; ++J) {
16274 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16275 }
16276 }
16277
16278 return Success(Result, E);
16279 };
16280
16281 switch (BuiltinOp) {
16282 default:
16283 return false;
16284
16285 case X86::BI__builtin_ia32_crc32qi:
16286 return HandleCRC32(1);
16287 case X86::BI__builtin_ia32_crc32hi:
16288 return HandleCRC32(2);
16289 case X86::BI__builtin_ia32_crc32si:
16290 return HandleCRC32(4);
16291 case X86::BI__builtin_ia32_crc32di:
16292 return HandleCRC32(8);
16293
16294 case Builtin::BI__builtin_dynamic_object_size:
16295 case Builtin::BI__builtin_object_size: {
16296 // The type was checked when we built the expression.
16297 unsigned Type =
16298 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16299 assert(Type <= 3 && "unexpected type");
16300
16301 if (std::optional<uint64_t> Size =
16303 return Success(*Size, E);
16304
16305 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16306 return Success((Type & 2) ? 0 : -1, E);
16307
16308 // Expression had no side effects, but we couldn't statically determine the
16309 // size of the referenced object.
16310 switch (Info.EvalMode) {
16311 case EvaluationMode::ConstantExpression:
16312 case EvaluationMode::ConstantFold:
16313 case EvaluationMode::IgnoreSideEffects:
16314 // Leave it to IR generation.
16315 return Error(E);
16316 case EvaluationMode::ConstantExpressionUnevaluated:
16317 // Reduce it to a constant now.
16318 return Success((Type & 2) ? 0 : -1, E);
16319 }
16320
16321 llvm_unreachable("unexpected EvalMode");
16322 }
16323
16324 case Builtin::BI__builtin_os_log_format_buffer_size: {
16325 analyze_os_log::OSLogBufferLayout Layout;
16326 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16327 return Success(Layout.size().getQuantity(), E);
16328 }
16329
16330 case Builtin::BI__builtin_is_aligned: {
16331 APValue Src;
16332 APSInt Alignment;
16333 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16334 return false;
16335 if (Src.isLValue()) {
16336 // If we evaluated a pointer, check the minimum known alignment.
16337 LValue Ptr;
16338 Ptr.setFrom(Info.Ctx, Src);
16339 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16340 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16341 // We can return true if the known alignment at the computed offset is
16342 // greater than the requested alignment.
16343 assert(PtrAlign.isPowerOfTwo());
16344 assert(Alignment.isPowerOf2());
16345 if (PtrAlign.getQuantity() >= Alignment)
16346 return Success(1, E);
16347 // If the alignment is not known to be sufficient, some cases could still
16348 // be aligned at run time. However, if the requested alignment is less or
16349 // equal to the base alignment and the offset is not aligned, we know that
16350 // the run-time value can never be aligned.
16351 if (BaseAlignment.getQuantity() >= Alignment &&
16352 PtrAlign.getQuantity() < Alignment)
16353 return Success(0, E);
16354 // Otherwise we can't infer whether the value is sufficiently aligned.
16355 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16356 // in cases where we can't fully evaluate the pointer.
16357 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16358 << Alignment;
16359 return false;
16360 }
16361 assert(Src.isInt());
16362 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16363 }
16364 case Builtin::BI__builtin_align_up: {
16365 APValue Src;
16366 APSInt Alignment;
16367 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16368 return false;
16369 if (!Src.isInt())
16370 return Error(E);
16371 APSInt AlignedVal =
16372 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16373 Src.getInt().isUnsigned());
16374 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16375 return Success(AlignedVal, E);
16376 }
16377 case Builtin::BI__builtin_align_down: {
16378 APValue Src;
16379 APSInt Alignment;
16380 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16381 return false;
16382 if (!Src.isInt())
16383 return Error(E);
16384 APSInt AlignedVal =
16385 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16386 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16387 return Success(AlignedVal, E);
16388 }
16389
16390 case Builtin::BI__builtin_bitreverseg:
16391 case Builtin::BI__builtin_bitreverse8:
16392 case Builtin::BI__builtin_bitreverse16:
16393 case Builtin::BI__builtin_bitreverse32:
16394 case Builtin::BI__builtin_bitreverse64:
16395 case Builtin::BI__builtin_elementwise_bitreverse: {
16396 APSInt Val;
16397 if (!EvaluateInteger(E->getArg(0), Val, Info))
16398 return false;
16399
16400 return Success(Val.reverseBits(), E);
16401 }
16402 case Builtin::BI__builtin_bswapg:
16403 case Builtin::BI__builtin_bswap16:
16404 case Builtin::BI__builtin_bswap32:
16405 case Builtin::BI__builtin_bswap64: {
16406 APSInt Val;
16407 if (!EvaluateInteger(E->getArg(0), Val, Info))
16408 return false;
16409 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16410 return Success(Val, E);
16411
16412 return Success(Val.byteSwap(), E);
16413 }
16414
16415 case Builtin::BI__builtin_classify_type:
16416 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16417
16418 case Builtin::BI__builtin_clrsb:
16419 case Builtin::BI__builtin_clrsbl:
16420 case Builtin::BI__builtin_clrsbll: {
16421 APSInt Val;
16422 if (!EvaluateInteger(E->getArg(0), Val, Info))
16423 return false;
16424
16425 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16426 }
16427
16428 case Builtin::BI__builtin_clz:
16429 case Builtin::BI__builtin_clzl:
16430 case Builtin::BI__builtin_clzll:
16431 case Builtin::BI__builtin_clzs:
16432 case Builtin::BI__builtin_clzg:
16433 case Builtin::BI__builtin_elementwise_clzg:
16434 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16435 case Builtin::BI__lzcnt:
16436 case Builtin::BI__lzcnt64: {
16437 APSInt Val;
16438 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16439 APValue Vec;
16440 if (!EvaluateVector(E->getArg(0), Vec, Info))
16441 return false;
16442 Val = ConvertBoolVectorToInt(Vec);
16443 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16444 return false;
16445 }
16446
16447 std::optional<APSInt> Fallback;
16448 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16449 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16450 E->getNumArgs() > 1) {
16451 APSInt FallbackTemp;
16452 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16453 return false;
16454 Fallback = FallbackTemp;
16455 }
16456
16457 if (!Val) {
16458 if (Fallback)
16459 return Success(*Fallback, E);
16460
16461 // When the argument is 0, the result of GCC builtins is undefined,
16462 // whereas for Microsoft intrinsics, the result is the bit-width of the
16463 // argument.
16464 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16465 BuiltinOp != Builtin::BI__lzcnt &&
16466 BuiltinOp != Builtin::BI__lzcnt64;
16467
16468 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16469 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16470 << /*IsTrailing=*/false;
16471 }
16472
16473 if (ZeroIsUndefined)
16474 return Error(E);
16475 }
16476
16477 return Success(Val.countl_zero(), E);
16478 }
16479
16480 case Builtin::BI__builtin_constant_p: {
16481 const Expr *Arg = E->getArg(0);
16482 if (EvaluateBuiltinConstantP(Info, Arg))
16483 return Success(true, E);
16484 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16485 // Outside a constant context, eagerly evaluate to false in the presence
16486 // of side-effects in order to avoid -Wunsequenced false-positives in
16487 // a branch on __builtin_constant_p(expr).
16488 return Success(false, E);
16489 }
16490 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16491 return false;
16492 }
16493
16494 case Builtin::BI__noop:
16495 // __noop always evaluates successfully and returns 0.
16496 return Success(0, E);
16497
16498 case Builtin::BI__builtin_is_constant_evaluated: {
16499 const auto *Callee = Info.CurrentCall->getCallee();
16500 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16501 (Info.CallStackDepth == 1 ||
16502 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16503 Callee->getIdentifier() &&
16504 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16505 // FIXME: Find a better way to avoid duplicated diagnostics.
16506 if (Info.EvalStatus.Diag)
16507 Info.report((Info.CallStackDepth == 1)
16508 ? E->getExprLoc()
16509 : Info.CurrentCall->getCallRange().getBegin(),
16510 diag::warn_is_constant_evaluated_always_true_constexpr)
16511 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16512 : "std::is_constant_evaluated");
16513 }
16514
16515 return Success(Info.InConstantContext, E);
16516 }
16517
16518 case Builtin::BI__builtin_is_within_lifetime:
16519 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16520 return Success(*result, E);
16521 return false;
16522
16523 case Builtin::BI__builtin_ctz:
16524 case Builtin::BI__builtin_ctzl:
16525 case Builtin::BI__builtin_ctzll:
16526 case Builtin::BI__builtin_ctzs:
16527 case Builtin::BI__builtin_ctzg:
16528 case Builtin::BI__builtin_elementwise_ctzg: {
16529 APSInt Val;
16530 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16531 APValue Vec;
16532 if (!EvaluateVector(E->getArg(0), Vec, Info))
16533 return false;
16534 Val = ConvertBoolVectorToInt(Vec);
16535 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16536 return false;
16537 }
16538
16539 std::optional<APSInt> Fallback;
16540 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16541 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16542 E->getNumArgs() > 1) {
16543 APSInt FallbackTemp;
16544 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16545 return false;
16546 Fallback = FallbackTemp;
16547 }
16548
16549 if (!Val) {
16550 if (Fallback)
16551 return Success(*Fallback, E);
16552
16553 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16554 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16555 << /*IsTrailing=*/true;
16556 }
16557 return Error(E);
16558 }
16559
16560 return Success(Val.countr_zero(), E);
16561 }
16562
16563 case Builtin::BI__builtin_eh_return_data_regno: {
16564 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16565 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16566 return Success(Operand, E);
16567 }
16568
16569 case Builtin::BI__builtin_elementwise_abs: {
16570 APSInt Val;
16571 if (!EvaluateInteger(E->getArg(0), Val, Info))
16572 return false;
16573
16574 return Success(Val.abs(), E);
16575 }
16576
16577 case Builtin::BI__builtin_expect:
16578 case Builtin::BI__builtin_expect_with_probability:
16579 return Visit(E->getArg(0));
16580
16581 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16582 const auto *Literal =
16584 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16585 return Success(Result, E);
16586 }
16587
16588 case Builtin::BI__builtin_infer_alloc_token: {
16589 // If we fail to infer a type, this fails to be a constant expression; this
16590 // can be checked with __builtin_constant_p(...).
16591 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16592 if (AllocType.isNull())
16593 return Error(
16594 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16595 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16596 if (!ATMD)
16597 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16598 auto Mode =
16599 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16600 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16601 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16602 uint64_t MaxTokens =
16603 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16604 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16605 if (!MaybeToken)
16606 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16607 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16608 }
16609
16610 case Builtin::BI__builtin_ffs:
16611 case Builtin::BI__builtin_ffsl:
16612 case Builtin::BI__builtin_ffsll: {
16613 APSInt Val;
16614 if (!EvaluateInteger(E->getArg(0), Val, Info))
16615 return false;
16616
16617 unsigned N = Val.countr_zero();
16618 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16619 }
16620
16621 case Builtin::BI__builtin_fpclassify: {
16622 APFloat Val(0.0);
16623 if (!EvaluateFloat(E->getArg(5), Val, Info))
16624 return false;
16625 unsigned Arg;
16626 switch (Val.getCategory()) {
16627 case APFloat::fcNaN: Arg = 0; break;
16628 case APFloat::fcInfinity: Arg = 1; break;
16629 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16630 case APFloat::fcZero: Arg = 4; break;
16631 }
16632 return Visit(E->getArg(Arg));
16633 }
16634
16635 case Builtin::BI__builtin_isinf_sign: {
16636 APFloat Val(0.0);
16637 return EvaluateFloat(E->getArg(0), Val, Info) &&
16638 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16639 }
16640
16641 case Builtin::BI__builtin_isinf: {
16642 APFloat Val(0.0);
16643 return EvaluateFloat(E->getArg(0), Val, Info) &&
16644 Success(Val.isInfinity() ? 1 : 0, E);
16645 }
16646
16647 case Builtin::BI__builtin_isfinite: {
16648 APFloat Val(0.0);
16649 return EvaluateFloat(E->getArg(0), Val, Info) &&
16650 Success(Val.isFinite() ? 1 : 0, E);
16651 }
16652
16653 case Builtin::BI__builtin_isnan: {
16654 APFloat Val(0.0);
16655 return EvaluateFloat(E->getArg(0), Val, Info) &&
16656 Success(Val.isNaN() ? 1 : 0, E);
16657 }
16658
16659 case Builtin::BI__builtin_isnormal: {
16660 APFloat Val(0.0);
16661 return EvaluateFloat(E->getArg(0), Val, Info) &&
16662 Success(Val.isNormal() ? 1 : 0, E);
16663 }
16664
16665 case Builtin::BI__builtin_issubnormal: {
16666 APFloat Val(0.0);
16667 return EvaluateFloat(E->getArg(0), Val, Info) &&
16668 Success(Val.isDenormal() ? 1 : 0, E);
16669 }
16670
16671 case Builtin::BI__builtin_iszero: {
16672 APFloat Val(0.0);
16673 return EvaluateFloat(E->getArg(0), Val, Info) &&
16674 Success(Val.isZero() ? 1 : 0, E);
16675 }
16676
16677 case Builtin::BI__builtin_signbit:
16678 case Builtin::BI__builtin_signbitf:
16679 case Builtin::BI__builtin_signbitl: {
16680 APFloat Val(0.0);
16681 return EvaluateFloat(E->getArg(0), Val, Info) &&
16682 Success(Val.isNegative() ? 1 : 0, E);
16683 }
16684
16685 case Builtin::BI__builtin_isgreater:
16686 case Builtin::BI__builtin_isgreaterequal:
16687 case Builtin::BI__builtin_isless:
16688 case Builtin::BI__builtin_islessequal:
16689 case Builtin::BI__builtin_islessgreater:
16690 case Builtin::BI__builtin_isunordered: {
16691 APFloat LHS(0.0);
16692 APFloat RHS(0.0);
16693 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16694 !EvaluateFloat(E->getArg(1), RHS, Info))
16695 return false;
16696
16697 return Success(
16698 [&] {
16699 switch (BuiltinOp) {
16700 case Builtin::BI__builtin_isgreater:
16701 return LHS > RHS;
16702 case Builtin::BI__builtin_isgreaterequal:
16703 return LHS >= RHS;
16704 case Builtin::BI__builtin_isless:
16705 return LHS < RHS;
16706 case Builtin::BI__builtin_islessequal:
16707 return LHS <= RHS;
16708 case Builtin::BI__builtin_islessgreater: {
16709 APFloat::cmpResult cmp = LHS.compare(RHS);
16710 return cmp == APFloat::cmpResult::cmpLessThan ||
16711 cmp == APFloat::cmpResult::cmpGreaterThan;
16712 }
16713 case Builtin::BI__builtin_isunordered:
16714 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16715 default:
16716 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16717 "point comparison function");
16718 }
16719 }()
16720 ? 1
16721 : 0,
16722 E);
16723 }
16724
16725 case Builtin::BI__builtin_issignaling: {
16726 APFloat Val(0.0);
16727 return EvaluateFloat(E->getArg(0), Val, Info) &&
16728 Success(Val.isSignaling() ? 1 : 0, E);
16729 }
16730
16731 case Builtin::BI__builtin_isfpclass: {
16732 APSInt MaskVal;
16733 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16734 return false;
16735 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16736 APFloat Val(0.0);
16737 return EvaluateFloat(E->getArg(0), Val, Info) &&
16738 Success((Val.classify() & Test) ? 1 : 0, E);
16739 }
16740
16741 case Builtin::BI__builtin_parity:
16742 case Builtin::BI__builtin_parityl:
16743 case Builtin::BI__builtin_parityll: {
16744 APSInt Val;
16745 if (!EvaluateInteger(E->getArg(0), Val, Info))
16746 return false;
16747
16748 return Success(Val.popcount() % 2, E);
16749 }
16750
16751 case Builtin::BI__builtin_abs:
16752 case Builtin::BI__builtin_labs:
16753 case Builtin::BI__builtin_llabs: {
16754 APSInt Val;
16755 if (!EvaluateInteger(E->getArg(0), Val, Info))
16756 return false;
16757 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16758 /*IsUnsigned=*/false))
16759 return false;
16760 if (Val.isNegative())
16761 Val.negate();
16762 return Success(Val, E);
16763 }
16764
16765 case Builtin::BI__builtin_popcount:
16766 case Builtin::BI__builtin_popcountl:
16767 case Builtin::BI__builtin_popcountll:
16768 case Builtin::BI__builtin_popcountg:
16769 case Builtin::BI__builtin_elementwise_popcount:
16770 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16771 case Builtin::BI__popcnt:
16772 case Builtin::BI__popcnt64: {
16773 APSInt Val;
16774 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16775 APValue Vec;
16776 if (!EvaluateVector(E->getArg(0), Vec, Info))
16777 return false;
16778 Val = ConvertBoolVectorToInt(Vec);
16779 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16780 return false;
16781 }
16782
16783 return Success(Val.popcount(), E);
16784 }
16785
16786 case Builtin::BI__builtin_rotateleft8:
16787 case Builtin::BI__builtin_rotateleft16:
16788 case Builtin::BI__builtin_rotateleft32:
16789 case Builtin::BI__builtin_rotateleft64:
16790 case Builtin::BI__builtin_rotateright8:
16791 case Builtin::BI__builtin_rotateright16:
16792 case Builtin::BI__builtin_rotateright32:
16793 case Builtin::BI__builtin_rotateright64:
16794 case Builtin::BI__builtin_stdc_rotate_left:
16795 case Builtin::BI__builtin_stdc_rotate_right:
16796 case Builtin::BI_rotl8: // Microsoft variants of rotate left
16797 case Builtin::BI_rotl16:
16798 case Builtin::BI_rotl:
16799 case Builtin::BI_lrotl:
16800 case Builtin::BI_rotl64:
16801 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16802 case Builtin::BI_rotr16:
16803 case Builtin::BI_rotr:
16804 case Builtin::BI_lrotr:
16805 case Builtin::BI_rotr64: {
16806 APSInt Value, Amount;
16807 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
16808 !EvaluateInteger(E->getArg(1), Amount, Info))
16809 return false;
16810
16811 Amount = NormalizeRotateAmount(Value, Amount);
16812
16813 switch (BuiltinOp) {
16814 case Builtin::BI__builtin_rotateright8:
16815 case Builtin::BI__builtin_rotateright16:
16816 case Builtin::BI__builtin_rotateright32:
16817 case Builtin::BI__builtin_rotateright64:
16818 case Builtin::BI__builtin_stdc_rotate_right:
16819 case Builtin::BI_rotr8:
16820 case Builtin::BI_rotr16:
16821 case Builtin::BI_rotr:
16822 case Builtin::BI_lrotr:
16823 case Builtin::BI_rotr64:
16824 return Success(
16825 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
16826 default:
16827 return Success(
16828 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
16829 }
16830 }
16831
16832 case Builtin::BIstdc_leading_zeros:
16833 case Builtin::BIstdc_leading_ones:
16834 case Builtin::BIstdc_trailing_zeros:
16835 case Builtin::BIstdc_trailing_ones:
16836 case Builtin::BIstdc_first_leading_zero:
16837 case Builtin::BIstdc_first_leading_one:
16838 case Builtin::BIstdc_first_trailing_zero:
16839 case Builtin::BIstdc_first_trailing_one:
16840 case Builtin::BIstdc_count_zeros:
16841 case Builtin::BIstdc_count_ones:
16842 case Builtin::BIstdc_has_single_bit:
16843 case Builtin::BIstdc_bit_width:
16844 case Builtin::BIstdc_bit_floor:
16845 case Builtin::BIstdc_bit_ceil:
16846 case Builtin::BI__builtin_stdc_leading_zeros:
16847 case Builtin::BI__builtin_stdc_leading_ones:
16848 case Builtin::BI__builtin_stdc_trailing_zeros:
16849 case Builtin::BI__builtin_stdc_trailing_ones:
16850 case Builtin::BI__builtin_stdc_first_leading_zero:
16851 case Builtin::BI__builtin_stdc_first_leading_one:
16852 case Builtin::BI__builtin_stdc_first_trailing_zero:
16853 case Builtin::BI__builtin_stdc_first_trailing_one:
16854 case Builtin::BI__builtin_stdc_count_zeros:
16855 case Builtin::BI__builtin_stdc_count_ones:
16856 case Builtin::BI__builtin_stdc_has_single_bit:
16857 case Builtin::BI__builtin_stdc_bit_width:
16858 case Builtin::BI__builtin_stdc_bit_floor:
16859 case Builtin::BI__builtin_stdc_bit_ceil: {
16860 APSInt Val;
16861 if (!EvaluateInteger(E->getArg(0), Val, Info))
16862 return false;
16863
16864 unsigned BitWidth = Val.getBitWidth();
16865 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
16866
16867 switch (BuiltinOp) {
16868 case Builtin::BI__builtin_stdc_leading_zeros:
16869 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
16870 case Builtin::BI__builtin_stdc_leading_ones:
16871 return Success(APInt(ResBitWidth, Val.countl_one()), E);
16872 case Builtin::BI__builtin_stdc_trailing_zeros:
16873 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
16874 case Builtin::BI__builtin_stdc_trailing_ones:
16875 return Success(APInt(ResBitWidth, Val.countr_one()), E);
16876 case Builtin::BI__builtin_stdc_first_leading_zero:
16877 return Success(
16878 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
16879 case Builtin::BI__builtin_stdc_first_leading_one:
16880 return Success(
16881 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
16882 case Builtin::BI__builtin_stdc_first_trailing_zero:
16883 return Success(
16884 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
16885 case Builtin::BI__builtin_stdc_first_trailing_one:
16886 return Success(
16887 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
16888 case Builtin::BI__builtin_stdc_count_zeros: {
16889 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
16890 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
16891 }
16892 case Builtin::BI__builtin_stdc_count_ones: {
16893 APInt Cnt(ResBitWidth, Val.popcount());
16894 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
16895 }
16896 case Builtin::BI__builtin_stdc_has_single_bit: {
16897 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
16898 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
16899 }
16900 case Builtin::BI__builtin_stdc_bit_width:
16901 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
16902 case Builtin::BI__builtin_stdc_bit_floor: {
16903 if (Val.isZero())
16904 return Success(APInt(BitWidth, 0), E);
16905 unsigned Exp = BitWidth - Val.countl_zero() - 1;
16906 return Success(
16907 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
16908 }
16909 case Builtin::BI__builtin_stdc_bit_ceil: {
16910 if (Val.ule(1))
16911 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
16912 APInt ValMinusOne = Val - 1;
16913 unsigned LZ = ValMinusOne.countl_zero();
16914 if (LZ == 0)
16915 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
16916 E); // overflows; wrap to 0
16917 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
16918 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
16919 }
16920 default:
16921 llvm_unreachable("Unknown stdc builtin");
16922 }
16923 }
16924
16925 case Builtin::BI__builtin_elementwise_add_sat: {
16926 APSInt LHS, RHS;
16927 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16928 !EvaluateInteger(E->getArg(1), RHS, Info))
16929 return false;
16930
16931 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
16932 return Success(APSInt(Result, !LHS.isSigned()), E);
16933 }
16934 case Builtin::BI__builtin_elementwise_sub_sat: {
16935 APSInt LHS, RHS;
16936 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16937 !EvaluateInteger(E->getArg(1), RHS, Info))
16938 return false;
16939
16940 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
16941 return Success(APSInt(Result, !LHS.isSigned()), E);
16942 }
16943 case Builtin::BI__builtin_elementwise_max: {
16944 APSInt LHS, RHS;
16945 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16946 !EvaluateInteger(E->getArg(1), RHS, Info))
16947 return false;
16948
16949 APInt Result = std::max(LHS, RHS);
16950 return Success(APSInt(Result, !LHS.isSigned()), E);
16951 }
16952 case Builtin::BI__builtin_elementwise_min: {
16953 APSInt LHS, RHS;
16954 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16955 !EvaluateInteger(E->getArg(1), RHS, Info))
16956 return false;
16957
16958 APInt Result = std::min(LHS, RHS);
16959 return Success(APSInt(Result, !LHS.isSigned()), E);
16960 }
16961 case Builtin::BI__builtin_elementwise_fshl:
16962 case Builtin::BI__builtin_elementwise_fshr: {
16963 APSInt Hi, Lo, Shift;
16964 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
16965 !EvaluateInteger(E->getArg(1), Lo, Info) ||
16966 !EvaluateInteger(E->getArg(2), Shift, Info))
16967 return false;
16968
16969 switch (BuiltinOp) {
16970 case Builtin::BI__builtin_elementwise_fshl: {
16971 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
16972 return Success(Result, E);
16973 }
16974 case Builtin::BI__builtin_elementwise_fshr: {
16975 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
16976 return Success(Result, E);
16977 }
16978 }
16979 llvm_unreachable("Fully covered switch above");
16980 }
16981 case Builtin::BIstrlen:
16982 case Builtin::BIwcslen:
16983 // A call to strlen is not a constant expression.
16984 if (Info.getLangOpts().CPlusPlus11)
16985 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16986 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16987 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16988 else
16989 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16990 [[fallthrough]];
16991 case Builtin::BI__builtin_strlen:
16992 case Builtin::BI__builtin_wcslen: {
16993 // As an extension, we support __builtin_strlen() as a constant expression,
16994 // and support folding strlen() to a constant.
16995 if (std::optional<uint64_t> StrLen =
16996 EvaluateBuiltinStrLen(E->getArg(0), Info))
16997 return Success(*StrLen, E);
16998 return false;
16999 }
17000
17001 case Builtin::BIstrcmp:
17002 case Builtin::BIwcscmp:
17003 case Builtin::BIstrncmp:
17004 case Builtin::BIwcsncmp:
17005 case Builtin::BImemcmp:
17006 case Builtin::BIbcmp:
17007 case Builtin::BIwmemcmp:
17008 // A call to strlen is not a constant expression.
17009 if (Info.getLangOpts().CPlusPlus11)
17010 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17011 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17012 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17013 else
17014 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17015 [[fallthrough]];
17016 case Builtin::BI__builtin_strcmp:
17017 case Builtin::BI__builtin_wcscmp:
17018 case Builtin::BI__builtin_strncmp:
17019 case Builtin::BI__builtin_wcsncmp:
17020 case Builtin::BI__builtin_memcmp:
17021 case Builtin::BI__builtin_bcmp:
17022 case Builtin::BI__builtin_wmemcmp: {
17023 LValue String1, String2;
17024 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17025 !EvaluatePointer(E->getArg(1), String2, Info))
17026 return false;
17027
17028 uint64_t MaxLength = uint64_t(-1);
17029 if (BuiltinOp != Builtin::BIstrcmp &&
17030 BuiltinOp != Builtin::BIwcscmp &&
17031 BuiltinOp != Builtin::BI__builtin_strcmp &&
17032 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17033 APSInt N;
17034 if (!EvaluateInteger(E->getArg(2), N, Info))
17035 return false;
17036 MaxLength = N.getZExtValue();
17037 }
17038
17039 // Empty substrings compare equal by definition.
17040 if (MaxLength == 0u)
17041 return Success(0, E);
17042
17043 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17044 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17045 String1.Designator.Invalid || String2.Designator.Invalid)
17046 return false;
17047
17048 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17049 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17050
17051 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17052 BuiltinOp == Builtin::BIbcmp ||
17053 BuiltinOp == Builtin::BI__builtin_memcmp ||
17054 BuiltinOp == Builtin::BI__builtin_bcmp;
17055
17056 assert(IsRawByte ||
17057 (Info.Ctx.hasSameUnqualifiedType(
17058 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17059 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17060
17061 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17062 // 'char8_t', but no other types.
17063 if (IsRawByte &&
17064 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17065 // FIXME: Consider using our bit_cast implementation to support this.
17066 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17067 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17068 << CharTy2;
17069 return false;
17070 }
17071
17072 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17073 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17074 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17075 Char1.isInt() && Char2.isInt();
17076 };
17077 const auto &AdvanceElems = [&] {
17078 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17079 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17080 };
17081
17082 bool StopAtNull =
17083 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17084 BuiltinOp != Builtin::BIwmemcmp &&
17085 BuiltinOp != Builtin::BI__builtin_memcmp &&
17086 BuiltinOp != Builtin::BI__builtin_bcmp &&
17087 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17088 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17089 BuiltinOp == Builtin::BIwcsncmp ||
17090 BuiltinOp == Builtin::BIwmemcmp ||
17091 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17092 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17093 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17094
17095 for (; MaxLength; --MaxLength) {
17096 APValue Char1, Char2;
17097 if (!ReadCurElems(Char1, Char2))
17098 return false;
17099 if (Char1.getInt().ne(Char2.getInt())) {
17100 if (IsWide) // wmemcmp compares with wchar_t signedness.
17101 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17102 // memcmp always compares unsigned chars.
17103 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17104 }
17105 if (StopAtNull && !Char1.getInt())
17106 return Success(0, E);
17107 assert(!(StopAtNull && !Char2.getInt()));
17108 if (!AdvanceElems())
17109 return false;
17110 }
17111 // We hit the strncmp / memcmp limit.
17112 return Success(0, E);
17113 }
17114
17115 case Builtin::BI__atomic_always_lock_free:
17116 case Builtin::BI__atomic_is_lock_free:
17117 case Builtin::BI__c11_atomic_is_lock_free: {
17118 APSInt SizeVal;
17119 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17120 return false;
17121
17122 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17123 // of two less than or equal to the maximum inline atomic width, we know it
17124 // is lock-free. If the size isn't a power of two, or greater than the
17125 // maximum alignment where we promote atomics, we know it is not lock-free
17126 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17127 // the answer can only be determined at runtime; for example, 16-byte
17128 // atomics have lock-free implementations on some, but not all,
17129 // x86-64 processors.
17130
17131 // Check power-of-two.
17132 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17133 if (Size.isPowerOfTwo()) {
17134 // Check against inlining width.
17135 unsigned InlineWidthBits =
17136 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17137 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17138 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17139 Size == CharUnits::One())
17140 return Success(1, E);
17141
17142 // If the pointer argument can be evaluated to a compile-time constant
17143 // integer (or nullptr), check if that value is appropriately aligned.
17144 const Expr *PtrArg = E->getArg(1);
17145 Expr::EvalResult ExprResult;
17146 APSInt IntResult;
17147 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17148 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17149 Info.Ctx) &&
17150 IntResult.isAligned(Size.getAsAlign()))
17151 return Success(1, E);
17152
17153 // Otherwise, check if the type's alignment against Size.
17154 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17155 // Drop the potential implicit-cast to 'const volatile void*', getting
17156 // the underlying type.
17157 if (ICE->getCastKind() == CK_BitCast)
17158 PtrArg = ICE->getSubExpr();
17159 }
17160
17161 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17162 QualType PointeeType = PtrTy->getPointeeType();
17163 if (!PointeeType->isIncompleteType() &&
17164 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17165 // OK, we will inline operations on this object.
17166 return Success(1, E);
17167 }
17168 }
17169 }
17170 }
17171
17172 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17173 Success(0, E) : Error(E);
17174 }
17175 case Builtin::BI__builtin_addcb:
17176 case Builtin::BI__builtin_addcs:
17177 case Builtin::BI__builtin_addc:
17178 case Builtin::BI__builtin_addcl:
17179 case Builtin::BI__builtin_addcll:
17180 case Builtin::BI__builtin_subcb:
17181 case Builtin::BI__builtin_subcs:
17182 case Builtin::BI__builtin_subc:
17183 case Builtin::BI__builtin_subcl:
17184 case Builtin::BI__builtin_subcll: {
17185 LValue CarryOutLValue;
17186 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17187 QualType ResultType = E->getArg(0)->getType();
17188 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17189 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17190 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17191 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17192 return false;
17193 // Copy the number of bits and sign.
17194 Result = LHS;
17195 CarryOut = LHS;
17196
17197 bool FirstOverflowed = false;
17198 bool SecondOverflowed = false;
17199 switch (BuiltinOp) {
17200 default:
17201 llvm_unreachable("Invalid value for BuiltinOp");
17202 case Builtin::BI__builtin_addcb:
17203 case Builtin::BI__builtin_addcs:
17204 case Builtin::BI__builtin_addc:
17205 case Builtin::BI__builtin_addcl:
17206 case Builtin::BI__builtin_addcll:
17207 Result =
17208 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17209 break;
17210 case Builtin::BI__builtin_subcb:
17211 case Builtin::BI__builtin_subcs:
17212 case Builtin::BI__builtin_subc:
17213 case Builtin::BI__builtin_subcl:
17214 case Builtin::BI__builtin_subcll:
17215 Result =
17216 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17217 break;
17218 }
17219
17220 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17221 // this is consistent.
17222 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17223 APValue APV{CarryOut};
17224 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17225 return false;
17226 return Success(Result, E);
17227 }
17228 case Builtin::BI__builtin_add_overflow:
17229 case Builtin::BI__builtin_sub_overflow:
17230 case Builtin::BI__builtin_mul_overflow:
17231 case Builtin::BI__builtin_sadd_overflow:
17232 case Builtin::BI__builtin_uadd_overflow:
17233 case Builtin::BI__builtin_uaddl_overflow:
17234 case Builtin::BI__builtin_uaddll_overflow:
17235 case Builtin::BI__builtin_usub_overflow:
17236 case Builtin::BI__builtin_usubl_overflow:
17237 case Builtin::BI__builtin_usubll_overflow:
17238 case Builtin::BI__builtin_umul_overflow:
17239 case Builtin::BI__builtin_umull_overflow:
17240 case Builtin::BI__builtin_umulll_overflow:
17241 case Builtin::BI__builtin_saddl_overflow:
17242 case Builtin::BI__builtin_saddll_overflow:
17243 case Builtin::BI__builtin_ssub_overflow:
17244 case Builtin::BI__builtin_ssubl_overflow:
17245 case Builtin::BI__builtin_ssubll_overflow:
17246 case Builtin::BI__builtin_smul_overflow:
17247 case Builtin::BI__builtin_smull_overflow:
17248 case Builtin::BI__builtin_smulll_overflow: {
17249 LValue ResultLValue;
17250 APSInt LHS, RHS;
17251
17252 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17253 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17254 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17255 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17256 return false;
17257
17258 APSInt Result;
17259 bool DidOverflow = false;
17260
17261 // If the types don't have to match, enlarge all 3 to the largest of them.
17262 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17263 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17264 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17265 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17267 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17269 uint64_t LHSSize = LHS.getBitWidth();
17270 uint64_t RHSSize = RHS.getBitWidth();
17271 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
17272 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17273
17274 // Add an additional bit if the signedness isn't uniformly agreed to. We
17275 // could do this ONLY if there is a signed and an unsigned that both have
17276 // MaxBits, but the code to check that is pretty nasty. The issue will be
17277 // caught in the shrink-to-result later anyway.
17278 if (IsSigned && !AllSigned)
17279 ++MaxBits;
17280
17281 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17282 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17283 Result = APSInt(MaxBits, !IsSigned);
17284 }
17285
17286 // Find largest int.
17287 switch (BuiltinOp) {
17288 default:
17289 llvm_unreachable("Invalid value for BuiltinOp");
17290 case Builtin::BI__builtin_add_overflow:
17291 case Builtin::BI__builtin_sadd_overflow:
17292 case Builtin::BI__builtin_saddl_overflow:
17293 case Builtin::BI__builtin_saddll_overflow:
17294 case Builtin::BI__builtin_uadd_overflow:
17295 case Builtin::BI__builtin_uaddl_overflow:
17296 case Builtin::BI__builtin_uaddll_overflow:
17297 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17298 : LHS.uadd_ov(RHS, DidOverflow);
17299 break;
17300 case Builtin::BI__builtin_sub_overflow:
17301 case Builtin::BI__builtin_ssub_overflow:
17302 case Builtin::BI__builtin_ssubl_overflow:
17303 case Builtin::BI__builtin_ssubll_overflow:
17304 case Builtin::BI__builtin_usub_overflow:
17305 case Builtin::BI__builtin_usubl_overflow:
17306 case Builtin::BI__builtin_usubll_overflow:
17307 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17308 : LHS.usub_ov(RHS, DidOverflow);
17309 break;
17310 case Builtin::BI__builtin_mul_overflow:
17311 case Builtin::BI__builtin_smul_overflow:
17312 case Builtin::BI__builtin_smull_overflow:
17313 case Builtin::BI__builtin_smulll_overflow:
17314 case Builtin::BI__builtin_umul_overflow:
17315 case Builtin::BI__builtin_umull_overflow:
17316 case Builtin::BI__builtin_umulll_overflow:
17317 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17318 : LHS.umul_ov(RHS, DidOverflow);
17319 break;
17320 }
17321
17322 // In the case where multiple sizes are allowed, truncate and see if
17323 // the values are the same.
17324 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17325 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17326 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17327 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17328 // since it will give us the behavior of a TruncOrSelf in the case where
17329 // its parameter <= its size. We previously set Result to be at least the
17330 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
17331 // will work exactly like TruncOrSelf.
17332 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
17333 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17334
17335 if (!APSInt::isSameValue(Temp, Result))
17336 DidOverflow = true;
17337 Result = Temp;
17338 }
17339
17340 APValue APV{Result};
17341 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17342 return false;
17343 return Success(DidOverflow, E);
17344 }
17345
17346 case Builtin::BI__builtin_reduce_add:
17347 case Builtin::BI__builtin_reduce_mul:
17348 case Builtin::BI__builtin_reduce_and:
17349 case Builtin::BI__builtin_reduce_or:
17350 case Builtin::BI__builtin_reduce_xor:
17351 case Builtin::BI__builtin_reduce_min:
17352 case Builtin::BI__builtin_reduce_max: {
17353 APValue Source;
17354 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17355 return false;
17356
17357 unsigned SourceLen = Source.getVectorLength();
17358 APSInt Reduced = Source.getVectorElt(0).getInt();
17359 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17360 switch (BuiltinOp) {
17361 default:
17362 return false;
17363 case Builtin::BI__builtin_reduce_add: {
17365 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17366 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17367 return false;
17368 break;
17369 }
17370 case Builtin::BI__builtin_reduce_mul: {
17372 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17373 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17374 return false;
17375 break;
17376 }
17377 case Builtin::BI__builtin_reduce_and: {
17378 Reduced &= Source.getVectorElt(EltNum).getInt();
17379 break;
17380 }
17381 case Builtin::BI__builtin_reduce_or: {
17382 Reduced |= Source.getVectorElt(EltNum).getInt();
17383 break;
17384 }
17385 case Builtin::BI__builtin_reduce_xor: {
17386 Reduced ^= Source.getVectorElt(EltNum).getInt();
17387 break;
17388 }
17389 case Builtin::BI__builtin_reduce_min: {
17390 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17391 break;
17392 }
17393 case Builtin::BI__builtin_reduce_max: {
17394 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17395 break;
17396 }
17397 }
17398 }
17399
17400 return Success(Reduced, E);
17401 }
17402
17403 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17404 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17405 case clang::X86::BI__builtin_ia32_subborrow_u32:
17406 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17407 LValue ResultLValue;
17408 APSInt CarryIn, LHS, RHS;
17409 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17410 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17411 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17412 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17413 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17414 return false;
17415
17416 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17417 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17418
17419 unsigned BitWidth = LHS.getBitWidth();
17420 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17421 APInt ExResult =
17422 IsAdd
17423 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17424 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17425
17426 APInt Result = ExResult.extractBits(BitWidth, 0);
17427 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17428
17429 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17430 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17431 return false;
17432 return Success(CarryOut, E);
17433 }
17434
17435 case clang::X86::BI__builtin_ia32_movmskps:
17436 case clang::X86::BI__builtin_ia32_movmskpd:
17437 case clang::X86::BI__builtin_ia32_pmovmskb128:
17438 case clang::X86::BI__builtin_ia32_pmovmskb256:
17439 case clang::X86::BI__builtin_ia32_movmskps256:
17440 case clang::X86::BI__builtin_ia32_movmskpd256: {
17441 APValue Source;
17442 if (!Evaluate(Source, Info, E->getArg(0)))
17443 return false;
17444 unsigned SourceLen = Source.getVectorLength();
17445 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17446 QualType ElemQT = VT->getElementType();
17447 unsigned ResultLen = Info.Ctx.getTypeSize(
17448 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17449 APInt Result(ResultLen, 0);
17450
17451 for (unsigned I = 0; I != SourceLen; ++I) {
17452 APInt Elem;
17453 if (ElemQT->isIntegerType()) {
17454 Elem = Source.getVectorElt(I).getInt();
17455 } else if (ElemQT->isRealFloatingType()) {
17456 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17457 } else {
17458 return false;
17459 }
17460 Result.setBitVal(I, Elem.isNegative());
17461 }
17462 return Success(Result, E);
17463 }
17464
17465 case clang::X86::BI__builtin_ia32_bextr_u32:
17466 case clang::X86::BI__builtin_ia32_bextr_u64:
17467 case clang::X86::BI__builtin_ia32_bextri_u32:
17468 case clang::X86::BI__builtin_ia32_bextri_u64: {
17469 APSInt Val, Idx;
17470 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17471 !EvaluateInteger(E->getArg(1), Idx, Info))
17472 return false;
17473
17474 unsigned BitWidth = Val.getBitWidth();
17475 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17476 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17477 Length = Length > BitWidth ? BitWidth : Length;
17478
17479 // Handle out of bounds cases.
17480 if (Length == 0 || Shift >= BitWidth)
17481 return Success(0, E);
17482
17483 uint64_t Result = Val.getZExtValue() >> Shift;
17484 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17485 return Success(Result, E);
17486 }
17487
17488 case clang::X86::BI__builtin_ia32_bzhi_si:
17489 case clang::X86::BI__builtin_ia32_bzhi_di: {
17490 APSInt Val, Idx;
17491 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17492 !EvaluateInteger(E->getArg(1), Idx, Info))
17493 return false;
17494
17495 unsigned BitWidth = Val.getBitWidth();
17496 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17497 if (Index < BitWidth)
17498 Val.clearHighBits(BitWidth - Index);
17499 return Success(Val, E);
17500 }
17501
17502 case clang::X86::BI__builtin_ia32_ktestcqi:
17503 case clang::X86::BI__builtin_ia32_ktestchi:
17504 case clang::X86::BI__builtin_ia32_ktestcsi:
17505 case clang::X86::BI__builtin_ia32_ktestcdi: {
17506 APSInt A, B;
17507 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17508 !EvaluateInteger(E->getArg(1), B, Info))
17509 return false;
17510
17511 return Success((~A & B) == 0, E);
17512 }
17513
17514 case clang::X86::BI__builtin_ia32_ktestzqi:
17515 case clang::X86::BI__builtin_ia32_ktestzhi:
17516 case clang::X86::BI__builtin_ia32_ktestzsi:
17517 case clang::X86::BI__builtin_ia32_ktestzdi: {
17518 APSInt A, B;
17519 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17520 !EvaluateInteger(E->getArg(1), B, Info))
17521 return false;
17522
17523 return Success((A & B) == 0, E);
17524 }
17525
17526 case clang::X86::BI__builtin_ia32_kortestcqi:
17527 case clang::X86::BI__builtin_ia32_kortestchi:
17528 case clang::X86::BI__builtin_ia32_kortestcsi:
17529 case clang::X86::BI__builtin_ia32_kortestcdi: {
17530 APSInt A, B;
17531 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17532 !EvaluateInteger(E->getArg(1), B, Info))
17533 return false;
17534
17535 return Success(~(A | B) == 0, E);
17536 }
17537
17538 case clang::X86::BI__builtin_ia32_kortestzqi:
17539 case clang::X86::BI__builtin_ia32_kortestzhi:
17540 case clang::X86::BI__builtin_ia32_kortestzsi:
17541 case clang::X86::BI__builtin_ia32_kortestzdi: {
17542 APSInt A, B;
17543 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17544 !EvaluateInteger(E->getArg(1), B, Info))
17545 return false;
17546
17547 return Success((A | B) == 0, E);
17548 }
17549
17550 case clang::X86::BI__builtin_ia32_kunpckhi:
17551 case clang::X86::BI__builtin_ia32_kunpckdi:
17552 case clang::X86::BI__builtin_ia32_kunpcksi: {
17553 APSInt A, B;
17554 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17555 !EvaluateInteger(E->getArg(1), B, Info))
17556 return false;
17557
17558 // Generic kunpack: extract lower half of each operand and concatenate
17559 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17560 unsigned BW = A.getBitWidth();
17561 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17562 return Success(Result, E);
17563 }
17564
17565 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17566 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17567 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17568 APSInt Val;
17569 if (!EvaluateInteger(E->getArg(0), Val, Info))
17570 return false;
17571 return Success(Val.countLeadingZeros(), E);
17572 }
17573
17574 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17575 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17576 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17577 APSInt Val;
17578 if (!EvaluateInteger(E->getArg(0), Val, Info))
17579 return false;
17580 return Success(Val.countTrailingZeros(), E);
17581 }
17582
17583 case clang::X86::BI__builtin_ia32_pdep_si:
17584 case clang::X86::BI__builtin_ia32_pdep_di: {
17585 APSInt Val, Msk;
17586 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17587 !EvaluateInteger(E->getArg(1), Msk, Info))
17588 return false;
17589
17590 unsigned BitWidth = Val.getBitWidth();
17591 APInt Result = APInt::getZero(BitWidth);
17592 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17593 if (Msk[I])
17594 Result.setBitVal(I, Val[P++]);
17595 return Success(Result, E);
17596 }
17597
17598 case clang::X86::BI__builtin_ia32_pext_si:
17599 case clang::X86::BI__builtin_ia32_pext_di: {
17600 APSInt Val, Msk;
17601 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17602 !EvaluateInteger(E->getArg(1), Msk, Info))
17603 return false;
17604
17605 unsigned BitWidth = Val.getBitWidth();
17606 APInt Result = APInt::getZero(BitWidth);
17607 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17608 if (Msk[I])
17609 Result.setBitVal(P++, Val[I]);
17610 return Success(Result, E);
17611 }
17612 case X86::BI__builtin_ia32_ptestz128:
17613 case X86::BI__builtin_ia32_ptestz256:
17614 case X86::BI__builtin_ia32_vtestzps:
17615 case X86::BI__builtin_ia32_vtestzps256:
17616 case X86::BI__builtin_ia32_vtestzpd:
17617 case X86::BI__builtin_ia32_vtestzpd256: {
17618 return EvalTestOp(
17619 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17620 }
17621 case X86::BI__builtin_ia32_ptestc128:
17622 case X86::BI__builtin_ia32_ptestc256:
17623 case X86::BI__builtin_ia32_vtestcps:
17624 case X86::BI__builtin_ia32_vtestcps256:
17625 case X86::BI__builtin_ia32_vtestcpd:
17626 case X86::BI__builtin_ia32_vtestcpd256: {
17627 return EvalTestOp(
17628 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17629 }
17630 case X86::BI__builtin_ia32_ptestnzc128:
17631 case X86::BI__builtin_ia32_ptestnzc256:
17632 case X86::BI__builtin_ia32_vtestnzcps:
17633 case X86::BI__builtin_ia32_vtestnzcps256:
17634 case X86::BI__builtin_ia32_vtestnzcpd:
17635 case X86::BI__builtin_ia32_vtestnzcpd256: {
17636 return EvalTestOp([](const APInt &A, const APInt &B) {
17637 return ((A & B) != 0) && ((~A & B) != 0);
17638 });
17639 }
17640 case X86::BI__builtin_ia32_kandqi:
17641 case X86::BI__builtin_ia32_kandhi:
17642 case X86::BI__builtin_ia32_kandsi:
17643 case X86::BI__builtin_ia32_kanddi: {
17644 return HandleMaskBinOp(
17645 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17646 }
17647
17648 case X86::BI__builtin_ia32_kandnqi:
17649 case X86::BI__builtin_ia32_kandnhi:
17650 case X86::BI__builtin_ia32_kandnsi:
17651 case X86::BI__builtin_ia32_kandndi: {
17652 return HandleMaskBinOp(
17653 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17654 }
17655
17656 case X86::BI__builtin_ia32_korqi:
17657 case X86::BI__builtin_ia32_korhi:
17658 case X86::BI__builtin_ia32_korsi:
17659 case X86::BI__builtin_ia32_kordi: {
17660 return HandleMaskBinOp(
17661 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17662 }
17663
17664 case X86::BI__builtin_ia32_kxnorqi:
17665 case X86::BI__builtin_ia32_kxnorhi:
17666 case X86::BI__builtin_ia32_kxnorsi:
17667 case X86::BI__builtin_ia32_kxnordi: {
17668 return HandleMaskBinOp(
17669 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17670 }
17671
17672 case X86::BI__builtin_ia32_kxorqi:
17673 case X86::BI__builtin_ia32_kxorhi:
17674 case X86::BI__builtin_ia32_kxorsi:
17675 case X86::BI__builtin_ia32_kxordi: {
17676 return HandleMaskBinOp(
17677 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17678 }
17679
17680 case X86::BI__builtin_ia32_knotqi:
17681 case X86::BI__builtin_ia32_knothi:
17682 case X86::BI__builtin_ia32_knotsi:
17683 case X86::BI__builtin_ia32_knotdi: {
17684 APSInt Val;
17685 if (!EvaluateInteger(E->getArg(0), Val, Info))
17686 return false;
17687 APSInt Result = ~Val;
17688 return Success(APValue(Result), E);
17689 }
17690
17691 case X86::BI__builtin_ia32_kaddqi:
17692 case X86::BI__builtin_ia32_kaddhi:
17693 case X86::BI__builtin_ia32_kaddsi:
17694 case X86::BI__builtin_ia32_kadddi: {
17695 return HandleMaskBinOp(
17696 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17697 }
17698
17699 case X86::BI__builtin_ia32_kmovb:
17700 case X86::BI__builtin_ia32_kmovw:
17701 case X86::BI__builtin_ia32_kmovd:
17702 case X86::BI__builtin_ia32_kmovq: {
17703 APSInt Val;
17704 if (!EvaluateInteger(E->getArg(0), Val, Info))
17705 return false;
17706 return Success(Val, E);
17707 }
17708
17709 case X86::BI__builtin_ia32_kshiftliqi:
17710 case X86::BI__builtin_ia32_kshiftlihi:
17711 case X86::BI__builtin_ia32_kshiftlisi:
17712 case X86::BI__builtin_ia32_kshiftlidi: {
17713 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17714 unsigned Amt = RHS.getZExtValue() & 0xFF;
17715 if (Amt >= LHS.getBitWidth())
17716 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17717 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17718 });
17719 }
17720
17721 case X86::BI__builtin_ia32_kshiftriqi:
17722 case X86::BI__builtin_ia32_kshiftrihi:
17723 case X86::BI__builtin_ia32_kshiftrisi:
17724 case X86::BI__builtin_ia32_kshiftridi: {
17725 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17726 unsigned Amt = RHS.getZExtValue() & 0xFF;
17727 if (Amt >= LHS.getBitWidth())
17728 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17729 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17730 });
17731 }
17732
17733 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17734 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17735 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17736 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17737 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17738 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17739 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17740 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17741 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
17742 APValue Vec;
17743 APSInt IdxAPS;
17744 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17745 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17746 return false;
17747 unsigned N = Vec.getVectorLength();
17748 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17749 return Success(Vec.getVectorElt(Idx).getInt(), E);
17750 }
17751
17752 case clang::X86::BI__builtin_ia32_cvtb2mask128:
17753 case clang::X86::BI__builtin_ia32_cvtb2mask256:
17754 case clang::X86::BI__builtin_ia32_cvtb2mask512:
17755 case clang::X86::BI__builtin_ia32_cvtw2mask128:
17756 case clang::X86::BI__builtin_ia32_cvtw2mask256:
17757 case clang::X86::BI__builtin_ia32_cvtw2mask512:
17758 case clang::X86::BI__builtin_ia32_cvtd2mask128:
17759 case clang::X86::BI__builtin_ia32_cvtd2mask256:
17760 case clang::X86::BI__builtin_ia32_cvtd2mask512:
17761 case clang::X86::BI__builtin_ia32_cvtq2mask128:
17762 case clang::X86::BI__builtin_ia32_cvtq2mask256:
17763 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
17764 assert(E->getNumArgs() == 1);
17765 APValue Vec;
17766 if (!EvaluateVector(E->getArg(0), Vec, Info))
17767 return false;
17768
17769 unsigned VectorLen = Vec.getVectorLength();
17770 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
17771 llvm::APInt Bits(RetWidth, 0);
17772
17773 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
17774 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
17775 unsigned MSB = A[A.getBitWidth() - 1];
17776 Bits.setBitVal(ElemNum, MSB);
17777 }
17778
17779 APSInt RetMask(Bits, /*isUnsigned=*/true);
17780 return Success(APValue(RetMask), E);
17781 }
17782
17783 case clang::X86::BI__builtin_ia32_cmpb128_mask:
17784 case clang::X86::BI__builtin_ia32_cmpw128_mask:
17785 case clang::X86::BI__builtin_ia32_cmpd128_mask:
17786 case clang::X86::BI__builtin_ia32_cmpq128_mask:
17787 case clang::X86::BI__builtin_ia32_cmpb256_mask:
17788 case clang::X86::BI__builtin_ia32_cmpw256_mask:
17789 case clang::X86::BI__builtin_ia32_cmpd256_mask:
17790 case clang::X86::BI__builtin_ia32_cmpq256_mask:
17791 case clang::X86::BI__builtin_ia32_cmpb512_mask:
17792 case clang::X86::BI__builtin_ia32_cmpw512_mask:
17793 case clang::X86::BI__builtin_ia32_cmpd512_mask:
17794 case clang::X86::BI__builtin_ia32_cmpq512_mask:
17795 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
17796 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
17797 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
17798 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
17799 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
17800 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
17801 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
17802 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
17803 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
17804 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
17805 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
17806 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
17807 assert(E->getNumArgs() == 4);
17808
17809 bool IsUnsigned =
17810 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
17811 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
17812
17813 APValue LHS, RHS;
17814 APSInt Mask, Opcode;
17815 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
17816 !EvaluateVector(E->getArg(1), RHS, Info) ||
17817 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
17818 !EvaluateInteger(E->getArg(3), Mask, Info))
17819 return false;
17820
17821 assert(LHS.getVectorLength() == RHS.getVectorLength());
17822
17823 unsigned VectorLen = LHS.getVectorLength();
17824 unsigned RetWidth = Mask.getBitWidth();
17825
17826 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17827
17828 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
17829 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
17830 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
17831 bool Result = false;
17832
17833 switch (Opcode.getExtValue() & 0x7) {
17834 case 0: // _MM_CMPINT_EQ
17835 Result = (A == B);
17836 break;
17837 case 1: // _MM_CMPINT_LT
17838 Result = IsUnsigned ? A.ult(B) : A.slt(B);
17839 break;
17840 case 2: // _MM_CMPINT_LE
17841 Result = IsUnsigned ? A.ule(B) : A.sle(B);
17842 break;
17843 case 3: // _MM_CMPINT_FALSE
17844 Result = false;
17845 break;
17846 case 4: // _MM_CMPINT_NE
17847 Result = (A != B);
17848 break;
17849 case 5: // _MM_CMPINT_NLT (>=)
17850 Result = IsUnsigned ? A.uge(B) : A.sge(B);
17851 break;
17852 case 6: // _MM_CMPINT_NLE (>)
17853 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
17854 break;
17855 case 7: // _MM_CMPINT_TRUE
17856 Result = true;
17857 break;
17858 }
17859
17860 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
17861 }
17862
17863 return Success(APValue(RetMask), E);
17864 }
17865 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
17866 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
17867 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
17868 assert(E->getNumArgs() == 3);
17869
17870 APValue Source, ShuffleMask;
17871 APSInt ZeroMask;
17872 if (!EvaluateVector(E->getArg(0), Source, Info) ||
17873 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
17874 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
17875 return false;
17876
17877 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
17878 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
17879
17880 unsigned NumBytesInQWord = 8;
17881 unsigned NumBitsInByte = 8;
17882 unsigned NumBytes = Source.getVectorLength();
17883 unsigned NumQWords = NumBytes / NumBytesInQWord;
17884 unsigned RetWidth = ZeroMask.getBitWidth();
17885 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17886
17887 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
17888 APInt SourceQWord(64, 0);
17889 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17890 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
17891 .getInt()
17892 .getZExtValue();
17893 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
17894 }
17895
17896 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17897 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
17898 unsigned M =
17899 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
17900 if (ZeroMask[SelIdx]) {
17901 RetMask.setBitVal(SelIdx, SourceQWord[M]);
17902 }
17903 }
17904 }
17905 return Success(APValue(RetMask), E);
17906 }
17907 }
17908}
17909
17910/// Determine whether this is a pointer past the end of the complete
17911/// object referred to by the lvalue.
17913 const LValue &LV) {
17914 // A null pointer can be viewed as being "past the end" but we don't
17915 // choose to look at it that way here.
17916 if (!LV.getLValueBase())
17917 return false;
17918
17919 // If the designator is valid and refers to a subobject, we're not pointing
17920 // past the end.
17921 if (!LV.getLValueDesignator().Invalid &&
17922 !LV.getLValueDesignator().isOnePastTheEnd())
17923 return false;
17924
17925 // A pointer to an incomplete type might be past-the-end if the type's size is
17926 // zero. We cannot tell because the type is incomplete.
17927 QualType Ty = getType(LV.getLValueBase());
17928 if (Ty->isIncompleteType())
17929 return true;
17930
17931 // Can't be past the end of an invalid object.
17932 if (LV.getLValueDesignator().Invalid)
17933 return false;
17934
17935 // We're a past-the-end pointer if we point to the byte after the object,
17936 // no matter what our type or path is.
17937 auto Size = Ctx.getTypeSizeInChars(Ty);
17938 return LV.getLValueOffset() == Size;
17939}
17940
17941namespace {
17942
17943/// Data recursive integer evaluator of certain binary operators.
17944///
17945/// We use a data recursive algorithm for binary operators so that we are able
17946/// to handle extreme cases of chained binary operators without causing stack
17947/// overflow.
17948class DataRecursiveIntBinOpEvaluator {
17949 struct EvalResult {
17950 APValue Val;
17951 bool Failed = false;
17952
17953 EvalResult() = default;
17954
17955 void swap(EvalResult &RHS) {
17956 Val.swap(RHS.Val);
17957 Failed = RHS.Failed;
17958 RHS.Failed = false;
17959 }
17960 };
17961
17962 struct Job {
17963 const Expr *E;
17964 EvalResult LHSResult; // meaningful only for binary operator expression.
17965 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
17966
17967 Job() = default;
17968 Job(Job &&) = default;
17969
17970 void startSpeculativeEval(EvalInfo &Info) {
17971 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
17972 }
17973
17974 private:
17975 SpeculativeEvaluationRAII SpecEvalRAII;
17976 };
17977
17978 SmallVector<Job, 16> Queue;
17979
17980 IntExprEvaluator &IntEval;
17981 EvalInfo &Info;
17982 APValue &FinalResult;
17983
17984public:
17985 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
17986 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
17987
17988 /// True if \param E is a binary operator that we are going to handle
17989 /// data recursively.
17990 /// We handle binary operators that are comma, logical, or that have operands
17991 /// with integral or enumeration type.
17992 static bool shouldEnqueue(const BinaryOperator *E) {
17993 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
17997 }
17998
17999 bool Traverse(const BinaryOperator *E) {
18000 enqueue(E);
18001 EvalResult PrevResult;
18002 while (!Queue.empty())
18003 process(PrevResult);
18004
18005 if (PrevResult.Failed) return false;
18006
18007 FinalResult.swap(PrevResult.Val);
18008 return true;
18009 }
18010
18011private:
18012 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18013 return IntEval.Success(Value, E, Result);
18014 }
18015 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18016 return IntEval.Success(Value, E, Result);
18017 }
18018 bool Error(const Expr *E) {
18019 return IntEval.Error(E);
18020 }
18021 bool Error(const Expr *E, diag::kind D) {
18022 return IntEval.Error(E, D);
18023 }
18024
18025 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18026 return Info.CCEDiag(E, D);
18027 }
18028
18029 // Returns true if visiting the RHS is necessary, false otherwise.
18030 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18031 bool &SuppressRHSDiags);
18032
18033 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18034 const BinaryOperator *E, APValue &Result);
18035
18036 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18037 Result.Failed = !Evaluate(Result.Val, Info, E);
18038 if (Result.Failed)
18039 Result.Val = APValue();
18040 }
18041
18042 void process(EvalResult &Result);
18043
18044 void enqueue(const Expr *E) {
18045 E = E->IgnoreParens();
18046 Queue.resize(Queue.size()+1);
18047 Queue.back().E = E;
18048 Queue.back().Kind = Job::AnyExprKind;
18049 }
18050};
18051
18052}
18053
18054bool DataRecursiveIntBinOpEvaluator::
18055 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18056 bool &SuppressRHSDiags) {
18057 if (E->getOpcode() == BO_Comma) {
18058 // Ignore LHS but note if we could not evaluate it.
18059 if (LHSResult.Failed)
18060 return Info.noteSideEffect();
18061 return true;
18062 }
18063
18064 if (E->isLogicalOp()) {
18065 bool LHSAsBool;
18066 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18067 // We were able to evaluate the LHS, see if we can get away with not
18068 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18069 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18070 Success(LHSAsBool, E, LHSResult.Val);
18071 return false; // Ignore RHS
18072 }
18073 } else {
18074 LHSResult.Failed = true;
18075
18076 // Since we weren't able to evaluate the left hand side, it
18077 // might have had side effects.
18078 if (!Info.noteSideEffect())
18079 return false;
18080
18081 // We can't evaluate the LHS; however, sometimes the result
18082 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18083 // Don't ignore RHS and suppress diagnostics from this arm.
18084 SuppressRHSDiags = true;
18085 }
18086
18087 return true;
18088 }
18089
18090 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18092
18093 if (LHSResult.Failed && !Info.noteFailure())
18094 return false; // Ignore RHS;
18095
18096 return true;
18097}
18098
18099static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18100 bool IsSub) {
18101 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18102 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18103 // offsets.
18104 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18105 CharUnits &Offset = LVal.getLValueOffset();
18106 uint64_t Offset64 = Offset.getQuantity();
18107 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18108 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18109 : Offset64 + Index64);
18110}
18111
18112bool DataRecursiveIntBinOpEvaluator::
18113 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18114 const BinaryOperator *E, APValue &Result) {
18115 if (E->getOpcode() == BO_Comma) {
18116 if (RHSResult.Failed)
18117 return false;
18118 Result = RHSResult.Val;
18119 return true;
18120 }
18121
18122 if (E->isLogicalOp()) {
18123 bool lhsResult, rhsResult;
18124 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18125 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18126
18127 if (LHSIsOK) {
18128 if (RHSIsOK) {
18129 if (E->getOpcode() == BO_LOr)
18130 return Success(lhsResult || rhsResult, E, Result);
18131 else
18132 return Success(lhsResult && rhsResult, E, Result);
18133 }
18134 } else {
18135 if (RHSIsOK) {
18136 // We can't evaluate the LHS; however, sometimes the result
18137 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18138 if (rhsResult == (E->getOpcode() == BO_LOr))
18139 return Success(rhsResult, E, Result);
18140 }
18141 }
18142
18143 return false;
18144 }
18145
18146 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18148
18149 if (LHSResult.Failed || RHSResult.Failed)
18150 return false;
18151
18152 const APValue &LHSVal = LHSResult.Val;
18153 const APValue &RHSVal = RHSResult.Val;
18154
18155 // Handle cases like (unsigned long)&a + 4.
18156 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18157 Result = LHSVal;
18158 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18159 return true;
18160 }
18161
18162 // Handle cases like 4 + (unsigned long)&a
18163 if (E->getOpcode() == BO_Add &&
18164 RHSVal.isLValue() && LHSVal.isInt()) {
18165 Result = RHSVal;
18166 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18167 return true;
18168 }
18169
18170 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18171 // Handle (intptr_t)&&A - (intptr_t)&&B.
18172 if (!LHSVal.getLValueOffset().isZero() ||
18173 !RHSVal.getLValueOffset().isZero())
18174 return false;
18175 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18176 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18177 if (!LHSExpr || !RHSExpr)
18178 return false;
18179 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18180 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18181 if (!LHSAddrExpr || !RHSAddrExpr)
18182 return false;
18183 // Make sure both labels come from the same function.
18184 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18185 RHSAddrExpr->getLabel()->getDeclContext())
18186 return false;
18187 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18188 return true;
18189 }
18190
18191 // All the remaining cases expect both operands to be an integer
18192 if (!LHSVal.isInt() || !RHSVal.isInt())
18193 return Error(E);
18194
18195 // Set up the width and signedness manually, in case it can't be deduced
18196 // from the operation we're performing.
18197 // FIXME: Don't do this in the cases where we can deduce it.
18198 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18200 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18201 RHSVal.getInt(), Value))
18202 return false;
18203 return Success(Value, E, Result);
18204}
18205
18206void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18207 Job &job = Queue.back();
18208
18209 switch (job.Kind) {
18210 case Job::AnyExprKind: {
18211 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18212 if (shouldEnqueue(Bop)) {
18213 job.Kind = Job::BinOpKind;
18214 enqueue(Bop->getLHS());
18215 return;
18216 }
18217 }
18218
18219 EvaluateExpr(job.E, Result);
18220 Queue.pop_back();
18221 return;
18222 }
18223
18224 case Job::BinOpKind: {
18225 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18226 bool SuppressRHSDiags = false;
18227 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18228 Queue.pop_back();
18229 return;
18230 }
18231 if (SuppressRHSDiags)
18232 job.startSpeculativeEval(Info);
18233 job.LHSResult.swap(Result);
18234 job.Kind = Job::BinOpVisitedLHSKind;
18235 enqueue(Bop->getRHS());
18236 return;
18237 }
18238
18239 case Job::BinOpVisitedLHSKind: {
18240 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18241 EvalResult RHS;
18242 RHS.swap(Result);
18243 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18244 Queue.pop_back();
18245 return;
18246 }
18247 }
18248
18249 llvm_unreachable("Invalid Job::Kind!");
18250}
18251
18252namespace {
18253enum class CmpResult {
18254 Unequal,
18255 Less,
18256 Equal,
18257 Greater,
18258 Unordered,
18259};
18260}
18261
18262template <class SuccessCB, class AfterCB>
18263static bool
18265 SuccessCB &&Success, AfterCB &&DoAfter) {
18266 assert(!E->isValueDependent());
18267 assert(E->isComparisonOp() && "expected comparison operator");
18268 assert((E->getOpcode() == BO_Cmp ||
18270 "unsupported binary expression evaluation");
18271 auto Error = [&](const Expr *E) {
18272 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18273 return false;
18274 };
18275
18276 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18277 bool IsEquality = E->isEqualityOp();
18278
18279 QualType LHSTy = E->getLHS()->getType();
18280 QualType RHSTy = E->getRHS()->getType();
18281
18282 if (LHSTy->isIntegralOrEnumerationType() &&
18283 RHSTy->isIntegralOrEnumerationType()) {
18284 APSInt LHS, RHS;
18285 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18286 if (!LHSOK && !Info.noteFailure())
18287 return false;
18288 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18289 return false;
18290 if (LHS < RHS)
18291 return Success(CmpResult::Less, E);
18292 if (LHS > RHS)
18293 return Success(CmpResult::Greater, E);
18294 return Success(CmpResult::Equal, E);
18295 }
18296
18297 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18298 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18299 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18300
18301 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18302 if (!LHSOK && !Info.noteFailure())
18303 return false;
18304 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18305 return false;
18306 if (LHSFX < RHSFX)
18307 return Success(CmpResult::Less, E);
18308 if (LHSFX > RHSFX)
18309 return Success(CmpResult::Greater, E);
18310 return Success(CmpResult::Equal, E);
18311 }
18312
18313 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18314 ComplexValue LHS, RHS;
18315 bool LHSOK;
18316 if (E->isAssignmentOp()) {
18317 LValue LV;
18318 EvaluateLValue(E->getLHS(), LV, Info);
18319 LHSOK = false;
18320 } else if (LHSTy->isRealFloatingType()) {
18321 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18322 if (LHSOK) {
18323 LHS.makeComplexFloat();
18324 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18325 }
18326 } else {
18327 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18328 }
18329 if (!LHSOK && !Info.noteFailure())
18330 return false;
18331
18332 if (E->getRHS()->getType()->isRealFloatingType()) {
18333 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18334 return false;
18335 RHS.makeComplexFloat();
18336 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18337 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18338 return false;
18339
18340 if (LHS.isComplexFloat()) {
18341 APFloat::cmpResult CR_r =
18342 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18343 APFloat::cmpResult CR_i =
18344 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18345 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18346 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18347 } else {
18348 assert(IsEquality && "invalid complex comparison");
18349 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18350 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18351 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18352 }
18353 }
18354
18355 if (LHSTy->isRealFloatingType() &&
18356 RHSTy->isRealFloatingType()) {
18357 APFloat RHS(0.0), LHS(0.0);
18358
18359 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18360 if (!LHSOK && !Info.noteFailure())
18361 return false;
18362
18363 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18364 return false;
18365
18366 assert(E->isComparisonOp() && "Invalid binary operator!");
18367 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18368 if (!Info.InConstantContext &&
18369 APFloatCmpResult == APFloat::cmpUnordered &&
18370 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18371 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18372 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18373 return false;
18374 }
18375 auto GetCmpRes = [&]() {
18376 switch (APFloatCmpResult) {
18377 case APFloat::cmpEqual:
18378 return CmpResult::Equal;
18379 case APFloat::cmpLessThan:
18380 return CmpResult::Less;
18381 case APFloat::cmpGreaterThan:
18382 return CmpResult::Greater;
18383 case APFloat::cmpUnordered:
18384 return CmpResult::Unordered;
18385 }
18386 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18387 };
18388 return Success(GetCmpRes(), E);
18389 }
18390
18391 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18392 LValue LHSValue, RHSValue;
18393
18394 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18395 if (!LHSOK && !Info.noteFailure())
18396 return false;
18397
18398 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18399 return false;
18400
18401 // Reject differing bases from the normal codepath; we special-case
18402 // comparisons to null.
18403 if (!HasSameBase(LHSValue, RHSValue)) {
18404 // Bail out early if we're checking potential constant expression.
18405 // Otherwise, prefer to diagnose other issues.
18406 if (Info.checkingPotentialConstantExpression() &&
18407 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18408 return false;
18409 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18410 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18411 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18412 Info.FFDiag(E, DiagID)
18413 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18414 return false;
18415 };
18416 // Inequalities and subtractions between unrelated pointers have
18417 // unspecified or undefined behavior.
18418 if (!IsEquality)
18419 return DiagComparison(
18420 diag::note_constexpr_pointer_comparison_unspecified);
18421 // A constant address may compare equal to the address of a symbol.
18422 // The one exception is that address of an object cannot compare equal
18423 // to a null pointer constant.
18424 // TODO: Should we restrict this to actual null pointers, and exclude the
18425 // case of zero cast to pointer type?
18426 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18427 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18428 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18429 !RHSValue.Base);
18430 // C++2c [intro.object]/10:
18431 // Two objects [...] may have the same address if [...] they are both
18432 // potentially non-unique objects.
18433 // C++2c [intro.object]/9:
18434 // An object is potentially non-unique if it is a string literal object,
18435 // the backing array of an initializer list, or a subobject thereof.
18436 //
18437 // This makes the comparison result unspecified, so it's not a constant
18438 // expression.
18439 //
18440 // TODO: Do we need to handle the initializer list case here?
18441 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18442 return DiagComparison(diag::note_constexpr_literal_comparison);
18443 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18444 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18445 !IsOpaqueConstantCall(LHSValue));
18446 // We can't tell whether weak symbols will end up pointing to the same
18447 // object.
18448 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18449 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18450 !IsWeakLValue(LHSValue));
18451 // We can't compare the address of the start of one object with the
18452 // past-the-end address of another object, per C++ DR1652.
18453 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18454 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18455 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18456 true);
18457 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18458 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18459 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18460 false);
18461 // We can't tell whether an object is at the same address as another
18462 // zero sized object.
18463 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18464 (LHSValue.Base && isZeroSized(RHSValue)))
18465 return DiagComparison(
18466 diag::note_constexpr_pointer_comparison_zero_sized);
18467 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18468 return DiagComparison(
18469 diag::note_constexpr_pointer_comparison_unspecified);
18470 // FIXME: Verify both variables are live.
18471 return Success(CmpResult::Unequal, E);
18472 }
18473
18474 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18475 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18476
18477 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18478 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18479
18480 // C++11 [expr.rel]p2:
18481 // - If two pointers point to non-static data members of the same object,
18482 // or to subobjects or array elements fo such members, recursively, the
18483 // pointer to the later declared member compares greater provided the
18484 // two members have the same access control and provided their class is
18485 // not a union.
18486 // [...]
18487 // - Otherwise pointer comparisons are unspecified.
18488 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18489 bool WasArrayIndex;
18490 unsigned Mismatch = FindDesignatorMismatch(
18491 LHSValue.Base.isNull() ? QualType()
18492 : getType(LHSValue.Base).getNonReferenceType(),
18493 LHSDesignator, RHSDesignator, WasArrayIndex);
18494 // At the point where the designators diverge, the comparison has a
18495 // specified value if:
18496 // - we are comparing array indices
18497 // - we are comparing fields of a union, or fields with the same access
18498 // Otherwise, the result is unspecified and thus the comparison is not a
18499 // constant expression.
18500 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18501 Mismatch < RHSDesignator.Entries.size()) {
18502 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18503 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18504 if (!LF && !RF)
18505 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18506 else if (!LF)
18507 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18508 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18509 << RF->getParent() << RF;
18510 else if (!RF)
18511 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18512 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18513 << LF->getParent() << LF;
18514 else if (!LF->getParent()->isUnion() &&
18515 LF->getAccess() != RF->getAccess())
18516 Info.CCEDiag(E,
18517 diag::note_constexpr_pointer_comparison_differing_access)
18518 << LF << LF->getAccess() << RF << RF->getAccess()
18519 << LF->getParent();
18520 }
18521 }
18522
18523 // The comparison here must be unsigned, and performed with the same
18524 // width as the pointer.
18525 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18526 uint64_t CompareLHS = LHSOffset.getQuantity();
18527 uint64_t CompareRHS = RHSOffset.getQuantity();
18528 assert(PtrSize <= 64 && "Unexpected pointer width");
18529 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18530 CompareLHS &= Mask;
18531 CompareRHS &= Mask;
18532
18533 // If there is a base and this is a relational operator, we can only
18534 // compare pointers within the object in question; otherwise, the result
18535 // depends on where the object is located in memory.
18536 if (!LHSValue.Base.isNull() && IsRelational) {
18537 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18538 if (BaseTy->isIncompleteType())
18539 return Error(E);
18540 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18541 uint64_t OffsetLimit = Size.getQuantity();
18542 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18543 return Error(E);
18544 }
18545
18546 if (CompareLHS < CompareRHS)
18547 return Success(CmpResult::Less, E);
18548 if (CompareLHS > CompareRHS)
18549 return Success(CmpResult::Greater, E);
18550 return Success(CmpResult::Equal, E);
18551 }
18552
18553 if (LHSTy->isMemberPointerType()) {
18554 assert(IsEquality && "unexpected member pointer operation");
18555 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18556
18557 MemberPtr LHSValue, RHSValue;
18558
18559 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18560 if (!LHSOK && !Info.noteFailure())
18561 return false;
18562
18563 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18564 return false;
18565
18566 // If either operand is a pointer to a weak function, the comparison is not
18567 // constant.
18568 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18569 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18570 << LHSValue.getDecl();
18571 return false;
18572 }
18573 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18574 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18575 << RHSValue.getDecl();
18576 return false;
18577 }
18578
18579 // C++11 [expr.eq]p2:
18580 // If both operands are null, they compare equal. Otherwise if only one is
18581 // null, they compare unequal.
18582 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18583 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18584 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18585 }
18586
18587 // Otherwise if either is a pointer to a virtual member function, the
18588 // result is unspecified.
18589 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18590 if (MD->isVirtual())
18591 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18592 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18593 if (MD->isVirtual())
18594 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18595
18596 // Otherwise they compare equal if and only if they would refer to the
18597 // same member of the same most derived object or the same subobject if
18598 // they were dereferenced with a hypothetical object of the associated
18599 // class type.
18600 bool Equal = LHSValue == RHSValue;
18601 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18602 }
18603
18604 if (LHSTy->isNullPtrType()) {
18605 assert(E->isComparisonOp() && "unexpected nullptr operation");
18606 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18607 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18608 // are compared, the result is true of the operator is <=, >= or ==, and
18609 // false otherwise.
18610 LValue Res;
18611 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18612 !EvaluatePointer(E->getRHS(), Res, Info))
18613 return false;
18614 return Success(CmpResult::Equal, E);
18615 }
18616
18617 return DoAfter();
18618}
18619
18620bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18621 if (!CheckLiteralType(Info, E))
18622 return false;
18623
18624 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18626 switch (CR) {
18627 case CmpResult::Unequal:
18628 llvm_unreachable("should never produce Unequal for three-way comparison");
18629 case CmpResult::Less:
18630 CCR = ComparisonCategoryResult::Less;
18631 break;
18632 case CmpResult::Equal:
18633 CCR = ComparisonCategoryResult::Equal;
18634 break;
18635 case CmpResult::Greater:
18636 CCR = ComparisonCategoryResult::Greater;
18637 break;
18638 case CmpResult::Unordered:
18639 CCR = ComparisonCategoryResult::Unordered;
18640 break;
18641 }
18642 // Evaluation succeeded. Lookup the information for the comparison category
18643 // type and fetch the VarDecl for the result.
18644 const ComparisonCategoryInfo &CmpInfo =
18645 Info.Ctx.CompCategories.getInfoForType(E->getType());
18646 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18647 // Check and evaluate the result as a constant expression.
18648 LValue LV;
18649 LV.set(VD);
18650 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18651 return false;
18652 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18653 ConstantExprKind::Normal);
18654 };
18655 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18656 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18657 });
18658}
18659
18660bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18661 const CXXParenListInitExpr *E) {
18662 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18663}
18664
18665bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18666 // We don't support assignment in C. C++ assignments don't get here because
18667 // assignment is an lvalue in C++.
18668 if (E->isAssignmentOp()) {
18669 Error(E);
18670 if (!Info.noteFailure())
18671 return false;
18672 }
18673
18674 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18675 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18676
18677 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18679 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18680
18681 if (E->isComparisonOp()) {
18682 // Evaluate builtin binary comparisons by evaluating them as three-way
18683 // comparisons and then translating the result.
18684 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18685 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18686 "should only produce Unequal for equality comparisons");
18687 bool IsEqual = CR == CmpResult::Equal,
18688 IsLess = CR == CmpResult::Less,
18689 IsGreater = CR == CmpResult::Greater;
18690 auto Op = E->getOpcode();
18691 switch (Op) {
18692 default:
18693 llvm_unreachable("unsupported binary operator");
18694 case BO_EQ:
18695 case BO_NE:
18696 return Success(IsEqual == (Op == BO_EQ), E);
18697 case BO_LT:
18698 return Success(IsLess, E);
18699 case BO_GT:
18700 return Success(IsGreater, E);
18701 case BO_LE:
18702 return Success(IsEqual || IsLess, E);
18703 case BO_GE:
18704 return Success(IsEqual || IsGreater, E);
18705 }
18706 };
18707 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18709 });
18710 }
18711
18712 QualType LHSTy = E->getLHS()->getType();
18713 QualType RHSTy = E->getRHS()->getType();
18714
18715 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18716 E->getOpcode() == BO_Sub) {
18717 LValue LHSValue, RHSValue;
18718
18719 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18720 if (!LHSOK && !Info.noteFailure())
18721 return false;
18722
18723 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18724 return false;
18725
18726 // Reject differing bases from the normal codepath; we special-case
18727 // comparisons to null.
18728 if (!HasSameBase(LHSValue, RHSValue)) {
18729 if (Info.checkingPotentialConstantExpression() &&
18730 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18731 return false;
18732
18733 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18734 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18735
18736 auto DiagArith = [&](unsigned DiagID) {
18737 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18738 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18739 Info.FFDiag(E, DiagID) << LHS << RHS;
18740 if (LHSExpr && LHSExpr == RHSExpr)
18741 Info.Note(LHSExpr->getExprLoc(),
18742 diag::note_constexpr_repeated_literal_eval)
18743 << LHSExpr->getSourceRange();
18744 return false;
18745 };
18746
18747 if (!LHSExpr || !RHSExpr)
18748 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
18749
18750 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18751 return DiagArith(diag::note_constexpr_literal_arith);
18752
18753 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18754 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18755 if (!LHSAddrExpr || !RHSAddrExpr)
18756 return Error(E);
18757 // Make sure both labels come from the same function.
18758 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18759 RHSAddrExpr->getLabel()->getDeclContext())
18760 return Error(E);
18761 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
18762 }
18763 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18764 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18765
18766 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18767 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18768
18769 // C++11 [expr.add]p6:
18770 // Unless both pointers point to elements of the same array object, or
18771 // one past the last element of the array object, the behavior is
18772 // undefined.
18773 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
18774 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
18775 RHSDesignator))
18776 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
18777
18778 QualType Type = E->getLHS()->getType();
18779 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
18780
18781 CharUnits ElementSize;
18782 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
18783 return false;
18784
18785 // As an extension, a type may have zero size (empty struct or union in
18786 // C, array of zero length). Pointer subtraction in such cases has
18787 // undefined behavior, so is not constant.
18788 if (ElementSize.isZero()) {
18789 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
18790 << ElementType;
18791 return false;
18792 }
18793
18794 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
18795 // and produce incorrect results when it overflows. Such behavior
18796 // appears to be non-conforming, but is common, so perhaps we should
18797 // assume the standard intended for such cases to be undefined behavior
18798 // and check for them.
18799
18800 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
18801 // overflow in the final conversion to ptrdiff_t.
18802 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
18803 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
18804 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
18805 false);
18806 APSInt TrueResult = (LHS - RHS) / ElemSize;
18807 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
18808
18809 if (Result.extend(65) != TrueResult &&
18810 !HandleOverflow(Info, E, TrueResult, E->getType()))
18811 return false;
18812 return Success(Result, E);
18813 }
18814
18815 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18816}
18817
18818/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
18819/// a result as the expression's type.
18820bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
18821 const UnaryExprOrTypeTraitExpr *E) {
18822 switch(E->getKind()) {
18823 case UETT_PreferredAlignOf:
18824 case UETT_AlignOf: {
18825 if (E->isArgumentType())
18826 return Success(
18827 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
18828 else
18829 return Success(
18830 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
18831 }
18832
18833 case UETT_PtrAuthTypeDiscriminator: {
18834 if (E->getArgumentType()->isDependentType())
18835 return false;
18836 return Success(
18837 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
18838 }
18839 case UETT_VecStep: {
18840 QualType Ty = E->getTypeOfArgument();
18841
18842 if (Ty->isVectorType()) {
18843 unsigned n = Ty->castAs<VectorType>()->getNumElements();
18844
18845 // The vec_step built-in functions that take a 3-component
18846 // vector return 4. (OpenCL 1.1 spec 6.11.12)
18847 if (n == 3)
18848 n = 4;
18849
18850 return Success(n, E);
18851 } else
18852 return Success(1, E);
18853 }
18854
18855 case UETT_DataSizeOf:
18856 case UETT_SizeOf: {
18857 QualType SrcTy = E->getTypeOfArgument();
18858 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
18859 // the result is the size of the referenced type."
18860 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
18861 SrcTy = Ref->getPointeeType();
18862
18863 CharUnits Sizeof;
18864 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
18865 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
18866 : SizeOfType::SizeOf)) {
18867 return false;
18868 }
18869 return Success(Sizeof, E);
18870 }
18871 case UETT_OpenMPRequiredSimdAlign:
18872 assert(E->isArgumentType());
18873 return Success(
18874 Info.Ctx.toCharUnitsFromBits(
18875 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
18876 .getQuantity(),
18877 E);
18878 case UETT_VectorElements: {
18879 QualType Ty = E->getTypeOfArgument();
18880 // If the vector has a fixed size, we can determine the number of elements
18881 // at compile time.
18882 if (const auto *VT = Ty->getAs<VectorType>())
18883 return Success(VT->getNumElements(), E);
18884
18885 assert(Ty->isSizelessVectorType());
18886 if (Info.InConstantContext)
18887 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
18888 << E->getSourceRange();
18889
18890 return false;
18891 }
18892 case UETT_CountOf: {
18893 QualType Ty = E->getTypeOfArgument();
18894 assert(Ty->isArrayType());
18895
18896 // We don't need to worry about array element qualifiers, so getting the
18897 // unsafe array type is fine.
18898 if (const auto *CAT =
18899 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
18900 return Success(CAT->getSize(), E);
18901 }
18902
18903 assert(!Ty->isConstantSizeType());
18904
18905 // If it's a variable-length array type, we need to check whether it is a
18906 // multidimensional array. If so, we need to check the size expression of
18907 // the VLA to see if it's a constant size. If so, we can return that value.
18908 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
18909 assert(VAT);
18910 if (VAT->getElementType()->isArrayType()) {
18911 // Variable array size expression could be missing (e.g. int a[*][10]) In
18912 // that case, it can't be a constant expression.
18913 if (!VAT->getSizeExpr()) {
18914 Info.FFDiag(E->getBeginLoc());
18915 return false;
18916 }
18917
18918 std::optional<APSInt> Res =
18919 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
18920 if (Res) {
18921 // The resulting value always has type size_t, so we need to make the
18922 // returned APInt have the correct sign and bit-width.
18923 APInt Val{
18924 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
18925 Res->getZExtValue()};
18926 return Success(Val, E);
18927 }
18928 }
18929
18930 // Definitely a variable-length type, which is not an ICE.
18931 // FIXME: Better diagnostic.
18932 Info.FFDiag(E->getBeginLoc());
18933 return false;
18934 }
18935 }
18936
18937 llvm_unreachable("unknown expr/type trait");
18938}
18939
18940bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
18941 Info.Ctx.recordOffsetOfEvaluation(OOE);
18942 CharUnits Result;
18943 unsigned n = OOE->getNumComponents();
18944 if (n == 0)
18945 return Error(OOE);
18946 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
18947 for (unsigned i = 0; i != n; ++i) {
18948 OffsetOfNode ON = OOE->getComponent(i);
18949 switch (ON.getKind()) {
18950 case OffsetOfNode::Array: {
18951 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
18952 APSInt IdxResult;
18953 if (!EvaluateInteger(Idx, IdxResult, Info))
18954 return false;
18955 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
18956 if (!AT)
18957 return Error(OOE);
18958 CurrentType = AT->getElementType();
18959 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
18960 Result += IdxResult.getSExtValue() * ElementSize;
18961 break;
18962 }
18963
18964 case OffsetOfNode::Field: {
18965 FieldDecl *MemberDecl = ON.getField();
18966 const auto *RD = CurrentType->getAsRecordDecl();
18967 if (!RD)
18968 return Error(OOE);
18969 if (RD->isInvalidDecl()) return false;
18970 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18971 unsigned i = MemberDecl->getFieldIndex();
18972 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
18973 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
18974 CurrentType = MemberDecl->getType().getNonReferenceType();
18975 break;
18976 }
18977
18979 llvm_unreachable("dependent __builtin_offsetof");
18980
18981 case OffsetOfNode::Base: {
18982 CXXBaseSpecifier *BaseSpec = ON.getBase();
18983 if (BaseSpec->isVirtual())
18984 return Error(OOE);
18985
18986 // Find the layout of the class whose base we are looking into.
18987 const auto *RD = CurrentType->getAsCXXRecordDecl();
18988 if (!RD)
18989 return Error(OOE);
18990 if (RD->isInvalidDecl()) return false;
18991 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18992
18993 // Find the base class itself.
18994 CurrentType = BaseSpec->getType();
18995 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
18996 if (!BaseRD)
18997 return Error(OOE);
18998
18999 // Add the offset to the base.
19000 Result += RL.getBaseClassOffset(BaseRD);
19001 break;
19002 }
19003 }
19004 }
19005 return Success(Result, OOE);
19006}
19007
19008bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19009 switch (E->getOpcode()) {
19010 default:
19011 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19012 // See C99 6.6p3.
19013 return Error(E);
19014 case UO_Extension:
19015 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19016 // If so, we could clear the diagnostic ID.
19017 return Visit(E->getSubExpr());
19018 case UO_Plus:
19019 // The result is just the value.
19020 return Visit(E->getSubExpr());
19021 case UO_Minus: {
19022 if (!Visit(E->getSubExpr()))
19023 return false;
19024 if (!Result.isInt()) return Error(E);
19025 const APSInt &Value = Result.getInt();
19026 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19027 !E->getType().isWrapType()) {
19028 if (Info.checkingForUndefinedBehavior())
19029 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19030 diag::warn_integer_constant_overflow)
19031 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19032 /*UpperCase=*/true, /*InsertSeparators=*/true)
19033 << E->getType() << E->getSourceRange();
19034
19035 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19036 E->getType()))
19037 return false;
19038 }
19039 return Success(-Value, E);
19040 }
19041 case UO_Not: {
19042 if (!Visit(E->getSubExpr()))
19043 return false;
19044 if (!Result.isInt()) return Error(E);
19045 return Success(~Result.getInt(), E);
19046 }
19047 case UO_LNot: {
19048 bool bres;
19049 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19050 return false;
19051 return Success(!bres, E);
19052 }
19053 }
19054}
19055
19056/// HandleCast - This is used to evaluate implicit or explicit casts where the
19057/// result type is integer.
19058bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19059 const Expr *SubExpr = E->getSubExpr();
19060 QualType DestType = E->getType();
19061 QualType SrcType = SubExpr->getType();
19062
19063 switch (E->getCastKind()) {
19064 case CK_BaseToDerived:
19065 case CK_DerivedToBase:
19066 case CK_UncheckedDerivedToBase:
19067 case CK_Dynamic:
19068 case CK_ToUnion:
19069 case CK_ArrayToPointerDecay:
19070 case CK_FunctionToPointerDecay:
19071 case CK_NullToPointer:
19072 case CK_NullToMemberPointer:
19073 case CK_BaseToDerivedMemberPointer:
19074 case CK_DerivedToBaseMemberPointer:
19075 case CK_ReinterpretMemberPointer:
19076 case CK_ConstructorConversion:
19077 case CK_IntegralToPointer:
19078 case CK_ToVoid:
19079 case CK_VectorSplat:
19080 case CK_IntegralToFloating:
19081 case CK_FloatingCast:
19082 case CK_CPointerToObjCPointerCast:
19083 case CK_BlockPointerToObjCPointerCast:
19084 case CK_AnyPointerToBlockPointerCast:
19085 case CK_ObjCObjectLValueCast:
19086 case CK_FloatingRealToComplex:
19087 case CK_FloatingComplexToReal:
19088 case CK_FloatingComplexCast:
19089 case CK_FloatingComplexToIntegralComplex:
19090 case CK_IntegralRealToComplex:
19091 case CK_IntegralComplexCast:
19092 case CK_IntegralComplexToFloatingComplex:
19093 case CK_BuiltinFnToFnPtr:
19094 case CK_ZeroToOCLOpaqueType:
19095 case CK_NonAtomicToAtomic:
19096 case CK_AddressSpaceConversion:
19097 case CK_IntToOCLSampler:
19098 case CK_FloatingToFixedPoint:
19099 case CK_FixedPointToFloating:
19100 case CK_FixedPointCast:
19101 case CK_IntegralToFixedPoint:
19102 case CK_MatrixCast:
19103 case CK_HLSLAggregateSplatCast:
19104 llvm_unreachable("invalid cast kind for integral value");
19105
19106 case CK_BitCast:
19107 case CK_Dependent:
19108 case CK_LValueBitCast:
19109 case CK_ARCProduceObject:
19110 case CK_ARCConsumeObject:
19111 case CK_ARCReclaimReturnedObject:
19112 case CK_ARCExtendBlockObject:
19113 case CK_CopyAndAutoreleaseBlockObject:
19114 return Error(E);
19115
19116 case CK_UserDefinedConversion:
19117 case CK_LValueToRValue:
19118 case CK_AtomicToNonAtomic:
19119 case CK_NoOp:
19120 case CK_LValueToRValueBitCast:
19121 case CK_HLSLArrayRValue:
19122 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19123
19124 case CK_MemberPointerToBoolean:
19125 case CK_PointerToBoolean:
19126 case CK_IntegralToBoolean:
19127 case CK_FloatingToBoolean:
19128 case CK_BooleanToSignedIntegral:
19129 case CK_FloatingComplexToBoolean:
19130 case CK_IntegralComplexToBoolean: {
19131 bool BoolResult;
19132 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19133 return false;
19134 uint64_t IntResult = BoolResult;
19135 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19136 IntResult = (uint64_t)-1;
19137 return Success(IntResult, E);
19138 }
19139
19140 case CK_FixedPointToIntegral: {
19141 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19142 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19143 return false;
19144 bool Overflowed;
19145 llvm::APSInt Result = Src.convertToInt(
19146 Info.Ctx.getIntWidth(DestType),
19147 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19148 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19149 return false;
19150 return Success(Result, E);
19151 }
19152
19153 case CK_FixedPointToBoolean: {
19154 // Unsigned padding does not affect this.
19155 APValue Val;
19156 if (!Evaluate(Val, Info, SubExpr))
19157 return false;
19158 return Success(Val.getFixedPoint().getBoolValue(), E);
19159 }
19160
19161 case CK_IntegralCast: {
19162 if (!Visit(SubExpr))
19163 return false;
19164
19165 if (!Result.isInt()) {
19166 // Allow casts of address-of-label differences if they are no-ops
19167 // or narrowing, if the result is at least 32 bits wide.
19168 // (The narrowing case isn't actually guaranteed to
19169 // be constant-evaluatable except in some narrow cases which are hard
19170 // to detect here. We let it through on the assumption the user knows
19171 // what they are doing.)
19172 if (Result.isAddrLabelDiff()) {
19173 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19174 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19175 }
19176 // Only allow casts of lvalues if they are lossless.
19177 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19178 }
19179
19180 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19181 const auto *ED = DestType->getAsEnumDecl();
19182 // Check that the value is within the range of the enumeration values.
19183 //
19184 // This corressponds to [expr.static.cast]p10 which says:
19185 // A value of integral or enumeration type can be explicitly converted
19186 // to a complete enumeration type ... If the enumeration type does not
19187 // have a fixed underlying type, the value is unchanged if the original
19188 // value is within the range of the enumeration values ([dcl.enum]), and
19189 // otherwise, the behavior is undefined.
19190 //
19191 // This was resolved as part of DR2338 which has CD5 status.
19192 if (!ED->isFixed()) {
19193 llvm::APInt Min;
19194 llvm::APInt Max;
19195
19196 ED->getValueRange(Max, Min);
19197 --Max;
19198
19199 if (ED->getNumNegativeBits() &&
19200 (Max.slt(Result.getInt().getSExtValue()) ||
19201 Min.sgt(Result.getInt().getSExtValue())))
19202 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19203 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19204 << Max.getSExtValue() << ED;
19205 else if (!ED->getNumNegativeBits() &&
19206 Max.ult(Result.getInt().getZExtValue()))
19207 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19208 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19209 << Max.getZExtValue() << ED;
19210 }
19211 }
19212
19213 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19214 Result.getInt()), E);
19215 }
19216
19217 case CK_PointerToIntegral: {
19218 CCEDiag(E, diag::note_constexpr_invalid_cast)
19219 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19220 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19221
19222 LValue LV;
19223 if (!EvaluatePointer(SubExpr, LV, Info))
19224 return false;
19225
19226 if (LV.getLValueBase()) {
19227 // Only allow based lvalue casts if they are lossless.
19228 // FIXME: Allow a larger integer size than the pointer size, and allow
19229 // narrowing back down to pointer width in subsequent integral casts.
19230 // FIXME: Check integer type's active bits, not its type size.
19231 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19232 return Error(E);
19233
19234 LV.Designator.setInvalid();
19235 LV.moveInto(Result);
19236 return true;
19237 }
19238
19239 APSInt AsInt;
19240 APValue V;
19241 LV.moveInto(V);
19242 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19243 llvm_unreachable("Can't cast this!");
19244
19245 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19246 }
19247
19248 case CK_IntegralComplexToReal: {
19249 ComplexValue C;
19250 if (!EvaluateComplex(SubExpr, C, Info))
19251 return false;
19252 return Success(C.getComplexIntReal(), E);
19253 }
19254
19255 case CK_FloatingToIntegral: {
19256 APFloat F(0.0);
19257 if (!EvaluateFloat(SubExpr, F, Info))
19258 return false;
19259
19260 APSInt Value;
19261 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19262 return false;
19263 return Success(Value, E);
19264 }
19265 case CK_HLSLVectorTruncation: {
19266 APValue Val;
19267 if (!EvaluateVector(SubExpr, Val, Info))
19268 return Error(E);
19269 return Success(Val.getVectorElt(0), E);
19270 }
19271 case CK_HLSLMatrixTruncation: {
19272 APValue Val;
19273 if (!EvaluateMatrix(SubExpr, Val, Info))
19274 return Error(E);
19275 return Success(Val.getMatrixElt(0, 0), E);
19276 }
19277 case CK_HLSLElementwiseCast: {
19278 SmallVector<APValue> SrcVals;
19279 SmallVector<QualType> SrcTypes;
19280
19281 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19282 return false;
19283
19284 // cast our single element
19285 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19286 APValue ResultVal;
19287 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19288 ResultVal))
19289 return false;
19290 return Success(ResultVal, E);
19291 }
19292 }
19293
19294 llvm_unreachable("unknown cast resulting in integral value");
19295}
19296
19297bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19298 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19299 ComplexValue LV;
19300 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19301 return false;
19302 if (!LV.isComplexInt())
19303 return Error(E);
19304 return Success(LV.getComplexIntReal(), E);
19305 }
19306
19307 return Visit(E->getSubExpr());
19308}
19309
19310bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19311 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19312 ComplexValue LV;
19313 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19314 return false;
19315 if (!LV.isComplexInt())
19316 return Error(E);
19317 return Success(LV.getComplexIntImag(), E);
19318 }
19319
19320 VisitIgnoredValue(E->getSubExpr());
19321 return Success(0, E);
19322}
19323
19324bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19325 return Success(E->getPackLength(), E);
19326}
19327
19328bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19329 return Success(E->getValue(), E);
19330}
19331
19332bool IntExprEvaluator::VisitConceptSpecializationExpr(
19333 const ConceptSpecializationExpr *E) {
19334 return Success(E->isSatisfied(), E);
19335}
19336
19337bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19338 return Success(E->isSatisfied(), E);
19339}
19340
19341bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19342 switch (E->getOpcode()) {
19343 default:
19344 // Invalid unary operators
19345 return Error(E);
19346 case UO_Plus:
19347 // The result is just the value.
19348 return Visit(E->getSubExpr());
19349 case UO_Minus: {
19350 if (!Visit(E->getSubExpr())) return false;
19351 if (!Result.isFixedPoint())
19352 return Error(E);
19353 bool Overflowed;
19354 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19355 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19356 return false;
19357 return Success(Negated, E);
19358 }
19359 case UO_LNot: {
19360 bool bres;
19361 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19362 return false;
19363 return Success(!bres, E);
19364 }
19365 }
19366}
19367
19368bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19369 const Expr *SubExpr = E->getSubExpr();
19370 QualType DestType = E->getType();
19371 assert(DestType->isFixedPointType() &&
19372 "Expected destination type to be a fixed point type");
19373 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19374
19375 switch (E->getCastKind()) {
19376 case CK_FixedPointCast: {
19377 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19378 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19379 return false;
19380 bool Overflowed;
19381 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19382 if (Overflowed) {
19383 if (Info.checkingForUndefinedBehavior())
19384 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19385 diag::warn_fixedpoint_constant_overflow)
19386 << Result.toString() << E->getType();
19387 if (!HandleOverflow(Info, E, Result, E->getType()))
19388 return false;
19389 }
19390 return Success(Result, E);
19391 }
19392 case CK_IntegralToFixedPoint: {
19393 APSInt Src;
19394 if (!EvaluateInteger(SubExpr, Src, Info))
19395 return false;
19396
19397 bool Overflowed;
19398 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19399 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19400
19401 if (Overflowed) {
19402 if (Info.checkingForUndefinedBehavior())
19403 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19404 diag::warn_fixedpoint_constant_overflow)
19405 << IntResult.toString() << E->getType();
19406 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19407 return false;
19408 }
19409
19410 return Success(IntResult, E);
19411 }
19412 case CK_FloatingToFixedPoint: {
19413 APFloat Src(0.0);
19414 if (!EvaluateFloat(SubExpr, Src, Info))
19415 return false;
19416
19417 bool Overflowed;
19418 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19419 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19420
19421 if (Overflowed) {
19422 if (Info.checkingForUndefinedBehavior())
19423 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19424 diag::warn_fixedpoint_constant_overflow)
19425 << Result.toString() << E->getType();
19426 if (!HandleOverflow(Info, E, Result, E->getType()))
19427 return false;
19428 }
19429
19430 return Success(Result, E);
19431 }
19432 case CK_NoOp:
19433 case CK_LValueToRValue:
19434 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19435 default:
19436 return Error(E);
19437 }
19438}
19439
19440bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19441 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19442 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19443
19444 const Expr *LHS = E->getLHS();
19445 const Expr *RHS = E->getRHS();
19446 FixedPointSemantics ResultFXSema =
19447 Info.Ctx.getFixedPointSemantics(E->getType());
19448
19449 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19450 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19451 return false;
19452 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19453 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19454 return false;
19455
19456 bool OpOverflow = false, ConversionOverflow = false;
19457 APFixedPoint Result(LHSFX.getSemantics());
19458 switch (E->getOpcode()) {
19459 case BO_Add: {
19460 Result = LHSFX.add(RHSFX, &OpOverflow)
19461 .convert(ResultFXSema, &ConversionOverflow);
19462 break;
19463 }
19464 case BO_Sub: {
19465 Result = LHSFX.sub(RHSFX, &OpOverflow)
19466 .convert(ResultFXSema, &ConversionOverflow);
19467 break;
19468 }
19469 case BO_Mul: {
19470 Result = LHSFX.mul(RHSFX, &OpOverflow)
19471 .convert(ResultFXSema, &ConversionOverflow);
19472 break;
19473 }
19474 case BO_Div: {
19475 if (RHSFX.getValue() == 0) {
19476 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19477 return false;
19478 }
19479 Result = LHSFX.div(RHSFX, &OpOverflow)
19480 .convert(ResultFXSema, &ConversionOverflow);
19481 break;
19482 }
19483 case BO_Shl:
19484 case BO_Shr: {
19485 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19486 llvm::APSInt RHSVal = RHSFX.getValue();
19487
19488 unsigned ShiftBW =
19489 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19490 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19491 // Embedded-C 4.1.6.2.2:
19492 // The right operand must be nonnegative and less than the total number
19493 // of (nonpadding) bits of the fixed-point operand ...
19494 if (RHSVal.isNegative())
19495 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19496 else if (Amt != RHSVal)
19497 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19498 << RHSVal << E->getType() << ShiftBW;
19499
19500 if (E->getOpcode() == BO_Shl)
19501 Result = LHSFX.shl(Amt, &OpOverflow);
19502 else
19503 Result = LHSFX.shr(Amt, &OpOverflow);
19504 break;
19505 }
19506 default:
19507 return false;
19508 }
19509 if (OpOverflow || ConversionOverflow) {
19510 if (Info.checkingForUndefinedBehavior())
19511 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19512 diag::warn_fixedpoint_constant_overflow)
19513 << Result.toString() << E->getType();
19514 if (!HandleOverflow(Info, E, Result, E->getType()))
19515 return false;
19516 }
19517 return Success(Result, E);
19518}
19519
19520//===----------------------------------------------------------------------===//
19521// Float Evaluation
19522//===----------------------------------------------------------------------===//
19523
19524namespace {
19525class FloatExprEvaluator
19526 : public ExprEvaluatorBase<FloatExprEvaluator> {
19527 APFloat &Result;
19528public:
19529 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19530 : ExprEvaluatorBaseTy(info), Result(result) {}
19531
19532 bool Success(const APValue &V, const Expr *e) {
19533 Result = V.getFloat();
19534 return true;
19535 }
19536
19537 bool ZeroInitialization(const Expr *E) {
19538 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19539 return true;
19540 }
19541
19542 bool VisitCallExpr(const CallExpr *E);
19543
19544 bool VisitUnaryOperator(const UnaryOperator *E);
19545 bool VisitBinaryOperator(const BinaryOperator *E);
19546 bool VisitFloatingLiteral(const FloatingLiteral *E);
19547 bool VisitCastExpr(const CastExpr *E);
19548
19549 bool VisitUnaryReal(const UnaryOperator *E);
19550 bool VisitUnaryImag(const UnaryOperator *E);
19551
19552 // FIXME: Missing: array subscript of vector, member of vector
19553};
19554} // end anonymous namespace
19555
19556static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19557 assert(!E->isValueDependent());
19558 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19559 return FloatExprEvaluator(Info, Result).Visit(E);
19560}
19561
19562static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19563 QualType ResultTy,
19564 const Expr *Arg,
19565 bool SNaN,
19566 llvm::APFloat &Result) {
19567 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19568 if (!S) return false;
19569
19570 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19571
19572 llvm::APInt fill;
19573
19574 // Treat empty strings as if they were zero.
19575 if (S->getString().empty())
19576 fill = llvm::APInt(32, 0);
19577 else if (S->getString().getAsInteger(0, fill))
19578 return false;
19579
19580 if (Context.getTargetInfo().isNan2008()) {
19581 if (SNaN)
19582 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19583 else
19584 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19585 } else {
19586 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19587 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19588 // a different encoding to what became a standard in 2008, and for pre-
19589 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19590 // sNaN. This is now known as "legacy NaN" encoding.
19591 if (SNaN)
19592 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19593 else
19594 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19595 }
19596
19597 return true;
19598}
19599
19600bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19601 if (!IsConstantEvaluatedBuiltinCall(E))
19602 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19603
19604 switch (E->getBuiltinCallee()) {
19605 default:
19606 return false;
19607
19608 case Builtin::BI__builtin_huge_val:
19609 case Builtin::BI__builtin_huge_valf:
19610 case Builtin::BI__builtin_huge_vall:
19611 case Builtin::BI__builtin_huge_valf16:
19612 case Builtin::BI__builtin_huge_valf128:
19613 case Builtin::BI__builtin_inf:
19614 case Builtin::BI__builtin_inff:
19615 case Builtin::BI__builtin_infl:
19616 case Builtin::BI__builtin_inff16:
19617 case Builtin::BI__builtin_inff128: {
19618 const llvm::fltSemantics &Sem =
19619 Info.Ctx.getFloatTypeSemantics(E->getType());
19620 Result = llvm::APFloat::getInf(Sem);
19621 return true;
19622 }
19623
19624 case Builtin::BI__builtin_nans:
19625 case Builtin::BI__builtin_nansf:
19626 case Builtin::BI__builtin_nansl:
19627 case Builtin::BI__builtin_nansf16:
19628 case Builtin::BI__builtin_nansf128:
19629 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19630 true, Result))
19631 return Error(E);
19632 return true;
19633
19634 case Builtin::BI__builtin_nan:
19635 case Builtin::BI__builtin_nanf:
19636 case Builtin::BI__builtin_nanl:
19637 case Builtin::BI__builtin_nanf16:
19638 case Builtin::BI__builtin_nanf128:
19639 // If this is __builtin_nan() turn this into a nan, otherwise we
19640 // can't constant fold it.
19641 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19642 false, Result))
19643 return Error(E);
19644 return true;
19645
19646 case Builtin::BI__builtin_elementwise_abs:
19647 case Builtin::BI__builtin_fabs:
19648 case Builtin::BI__builtin_fabsf:
19649 case Builtin::BI__builtin_fabsl:
19650 case Builtin::BI__builtin_fabsf128:
19651 // The C standard says "fabs raises no floating-point exceptions,
19652 // even if x is a signaling NaN. The returned value is independent of
19653 // the current rounding direction mode." Therefore constant folding can
19654 // proceed without regard to the floating point settings.
19655 // Reference, WG14 N2478 F.10.4.3
19656 if (!EvaluateFloat(E->getArg(0), Result, Info))
19657 return false;
19658
19659 if (Result.isNegative())
19660 Result.changeSign();
19661 return true;
19662
19663 case Builtin::BI__arithmetic_fence:
19664 return EvaluateFloat(E->getArg(0), Result, Info);
19665
19666 // FIXME: Builtin::BI__builtin_powi
19667 // FIXME: Builtin::BI__builtin_powif
19668 // FIXME: Builtin::BI__builtin_powil
19669
19670 case Builtin::BI__builtin_copysign:
19671 case Builtin::BI__builtin_copysignf:
19672 case Builtin::BI__builtin_copysignl:
19673 case Builtin::BI__builtin_copysignf128: {
19674 APFloat RHS(0.);
19675 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19676 !EvaluateFloat(E->getArg(1), RHS, Info))
19677 return false;
19678 Result.copySign(RHS);
19679 return true;
19680 }
19681
19682 case Builtin::BI__builtin_fmax:
19683 case Builtin::BI__builtin_fmaxf:
19684 case Builtin::BI__builtin_fmaxl:
19685 case Builtin::BI__builtin_fmaxf16:
19686 case Builtin::BI__builtin_fmaxf128: {
19687 APFloat RHS(0.);
19688 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19689 !EvaluateFloat(E->getArg(1), RHS, Info))
19690 return false;
19691 Result = maxnum(Result, RHS);
19692 return true;
19693 }
19694
19695 case Builtin::BI__builtin_fmin:
19696 case Builtin::BI__builtin_fminf:
19697 case Builtin::BI__builtin_fminl:
19698 case Builtin::BI__builtin_fminf16:
19699 case Builtin::BI__builtin_fminf128: {
19700 APFloat RHS(0.);
19701 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19702 !EvaluateFloat(E->getArg(1), RHS, Info))
19703 return false;
19704 Result = minnum(Result, RHS);
19705 return true;
19706 }
19707
19708 case Builtin::BI__builtin_fmaximum_num:
19709 case Builtin::BI__builtin_fmaximum_numf:
19710 case Builtin::BI__builtin_fmaximum_numl:
19711 case Builtin::BI__builtin_fmaximum_numf16:
19712 case Builtin::BI__builtin_fmaximum_numf128: {
19713 APFloat RHS(0.);
19714 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19715 !EvaluateFloat(E->getArg(1), RHS, Info))
19716 return false;
19717 Result = maximumnum(Result, RHS);
19718 return true;
19719 }
19720
19721 case Builtin::BI__builtin_fminimum_num:
19722 case Builtin::BI__builtin_fminimum_numf:
19723 case Builtin::BI__builtin_fminimum_numl:
19724 case Builtin::BI__builtin_fminimum_numf16:
19725 case Builtin::BI__builtin_fminimum_numf128: {
19726 APFloat RHS(0.);
19727 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19728 !EvaluateFloat(E->getArg(1), RHS, Info))
19729 return false;
19730 Result = minimumnum(Result, RHS);
19731 return true;
19732 }
19733
19734 case Builtin::BI__builtin_elementwise_fma: {
19735 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19736 !E->getArg(2)->isPRValue()) {
19737 return false;
19738 }
19739 APFloat SourceY(0.), SourceZ(0.);
19740 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19741 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
19742 !EvaluateFloat(E->getArg(2), SourceZ, Info))
19743 return false;
19744 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
19745 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
19746 return true;
19747 }
19748
19749 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
19750 APValue Vec;
19751 APSInt IdxAPS;
19752 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
19753 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
19754 return false;
19755 unsigned N = Vec.getVectorLength();
19756 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19757 return Success(Vec.getVectorElt(Idx), E);
19758 }
19759 }
19760}
19761
19762bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19763 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19764 ComplexValue CV;
19765 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19766 return false;
19767 Result = CV.FloatReal;
19768 return true;
19769 }
19770
19771 return Visit(E->getSubExpr());
19772}
19773
19774bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19775 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19776 ComplexValue CV;
19777 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19778 return false;
19779 Result = CV.FloatImag;
19780 return true;
19781 }
19782
19783 VisitIgnoredValue(E->getSubExpr());
19784 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
19785 Result = llvm::APFloat::getZero(Sem);
19786 return true;
19787}
19788
19789bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19790 switch (E->getOpcode()) {
19791 default: return Error(E);
19792 case UO_Plus:
19793 return EvaluateFloat(E->getSubExpr(), Result, Info);
19794 case UO_Minus:
19795 // In C standard, WG14 N2478 F.3 p4
19796 // "the unary - raises no floating point exceptions,
19797 // even if the operand is signalling."
19798 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
19799 return false;
19800 Result.changeSign();
19801 return true;
19802 }
19803}
19804
19805bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19806 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19807 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19808
19809 APFloat RHS(0.0);
19810 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
19811 if (!LHSOK && !Info.noteFailure())
19812 return false;
19813 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
19814 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
19815}
19816
19817bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
19818 Result = E->getValue();
19819 return true;
19820}
19821
19822bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
19823 const Expr* SubExpr = E->getSubExpr();
19824
19825 switch (E->getCastKind()) {
19826 default:
19827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19828
19829 case CK_HLSLAggregateSplatCast:
19830 llvm_unreachable("invalid cast kind for floating value");
19831
19832 case CK_IntegralToFloating: {
19833 APSInt IntResult;
19834 const FPOptions FPO = E->getFPFeaturesInEffect(
19835 Info.Ctx.getLangOpts());
19836 return EvaluateInteger(SubExpr, IntResult, Info) &&
19837 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
19838 IntResult, E->getType(), Result);
19839 }
19840
19841 case CK_FixedPointToFloating: {
19842 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19843 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
19844 return false;
19845 Result =
19846 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
19847 return true;
19848 }
19849
19850 case CK_FloatingCast: {
19851 if (!Visit(SubExpr))
19852 return false;
19853 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
19854 Result);
19855 }
19856
19857 case CK_FloatingComplexToReal: {
19858 ComplexValue V;
19859 if (!EvaluateComplex(SubExpr, V, Info))
19860 return false;
19861 Result = V.getComplexFloatReal();
19862 return true;
19863 }
19864 case CK_HLSLVectorTruncation: {
19865 APValue Val;
19866 if (!EvaluateVector(SubExpr, Val, Info))
19867 return Error(E);
19868 return Success(Val.getVectorElt(0), E);
19869 }
19870 case CK_HLSLMatrixTruncation: {
19871 APValue Val;
19872 if (!EvaluateMatrix(SubExpr, Val, Info))
19873 return Error(E);
19874 return Success(Val.getMatrixElt(0, 0), E);
19875 }
19876 case CK_HLSLElementwiseCast: {
19877 SmallVector<APValue> SrcVals;
19878 SmallVector<QualType> SrcTypes;
19879
19880 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
19881 SrcTypes))
19882 return false;
19883 APValue Val;
19884
19885 // cast our single element
19886 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19887 APValue ResultVal;
19888 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
19889 ResultVal))
19890 return false;
19891 return Success(ResultVal, E);
19892 }
19893 }
19894}
19895
19896//===----------------------------------------------------------------------===//
19897// Complex Evaluation (for float and integer)
19898//===----------------------------------------------------------------------===//
19899
19900namespace {
19901class ComplexExprEvaluator
19902 : public ExprEvaluatorBase<ComplexExprEvaluator> {
19903 ComplexValue &Result;
19904
19905public:
19906 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
19907 : ExprEvaluatorBaseTy(info), Result(Result) {}
19908
19909 bool Success(const APValue &V, const Expr *e) {
19910 Result.setFrom(V);
19911 return true;
19912 }
19913
19914 bool ZeroInitialization(const Expr *E);
19915
19916 //===--------------------------------------------------------------------===//
19917 // Visitor Methods
19918 //===--------------------------------------------------------------------===//
19919
19920 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
19921 bool VisitCastExpr(const CastExpr *E);
19922 bool VisitBinaryOperator(const BinaryOperator *E);
19923 bool VisitUnaryOperator(const UnaryOperator *E);
19924 bool VisitInitListExpr(const InitListExpr *E);
19925 bool VisitCallExpr(const CallExpr *E);
19926};
19927} // end anonymous namespace
19928
19929static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
19930 EvalInfo &Info) {
19931 assert(!E->isValueDependent());
19932 assert(E->isPRValue() && E->getType()->isAnyComplexType());
19933 return ComplexExprEvaluator(Info, Result).Visit(E);
19934}
19935
19936bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
19937 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
19938 if (ElemTy->isRealFloatingType()) {
19939 Result.makeComplexFloat();
19940 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
19941 Result.FloatReal = Zero;
19942 Result.FloatImag = Zero;
19943 } else {
19944 Result.makeComplexInt();
19945 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
19946 Result.IntReal = Zero;
19947 Result.IntImag = Zero;
19948 }
19949 return true;
19950}
19951
19952bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
19953 const Expr* SubExpr = E->getSubExpr();
19954
19955 if (SubExpr->getType()->isRealFloatingType()) {
19956 Result.makeComplexFloat();
19957 APFloat &Imag = Result.FloatImag;
19958 if (!EvaluateFloat(SubExpr, Imag, Info))
19959 return false;
19960
19961 Result.FloatReal = APFloat(Imag.getSemantics());
19962 return true;
19963 } else {
19964 assert(SubExpr->getType()->isIntegerType() &&
19965 "Unexpected imaginary literal.");
19966
19967 Result.makeComplexInt();
19968 APSInt &Imag = Result.IntImag;
19969 if (!EvaluateInteger(SubExpr, Imag, Info))
19970 return false;
19971
19972 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
19973 return true;
19974 }
19975}
19976
19977bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
19978
19979 switch (E->getCastKind()) {
19980 case CK_BitCast:
19981 case CK_BaseToDerived:
19982 case CK_DerivedToBase:
19983 case CK_UncheckedDerivedToBase:
19984 case CK_Dynamic:
19985 case CK_ToUnion:
19986 case CK_ArrayToPointerDecay:
19987 case CK_FunctionToPointerDecay:
19988 case CK_NullToPointer:
19989 case CK_NullToMemberPointer:
19990 case CK_BaseToDerivedMemberPointer:
19991 case CK_DerivedToBaseMemberPointer:
19992 case CK_MemberPointerToBoolean:
19993 case CK_ReinterpretMemberPointer:
19994 case CK_ConstructorConversion:
19995 case CK_IntegralToPointer:
19996 case CK_PointerToIntegral:
19997 case CK_PointerToBoolean:
19998 case CK_ToVoid:
19999 case CK_VectorSplat:
20000 case CK_IntegralCast:
20001 case CK_BooleanToSignedIntegral:
20002 case CK_IntegralToBoolean:
20003 case CK_IntegralToFloating:
20004 case CK_FloatingToIntegral:
20005 case CK_FloatingToBoolean:
20006 case CK_FloatingCast:
20007 case CK_CPointerToObjCPointerCast:
20008 case CK_BlockPointerToObjCPointerCast:
20009 case CK_AnyPointerToBlockPointerCast:
20010 case CK_ObjCObjectLValueCast:
20011 case CK_FloatingComplexToReal:
20012 case CK_FloatingComplexToBoolean:
20013 case CK_IntegralComplexToReal:
20014 case CK_IntegralComplexToBoolean:
20015 case CK_ARCProduceObject:
20016 case CK_ARCConsumeObject:
20017 case CK_ARCReclaimReturnedObject:
20018 case CK_ARCExtendBlockObject:
20019 case CK_CopyAndAutoreleaseBlockObject:
20020 case CK_BuiltinFnToFnPtr:
20021 case CK_ZeroToOCLOpaqueType:
20022 case CK_NonAtomicToAtomic:
20023 case CK_AddressSpaceConversion:
20024 case CK_IntToOCLSampler:
20025 case CK_FloatingToFixedPoint:
20026 case CK_FixedPointToFloating:
20027 case CK_FixedPointCast:
20028 case CK_FixedPointToBoolean:
20029 case CK_FixedPointToIntegral:
20030 case CK_IntegralToFixedPoint:
20031 case CK_MatrixCast:
20032 case CK_HLSLVectorTruncation:
20033 case CK_HLSLMatrixTruncation:
20034 case CK_HLSLElementwiseCast:
20035 case CK_HLSLAggregateSplatCast:
20036 llvm_unreachable("invalid cast kind for complex value");
20037
20038 case CK_LValueToRValue:
20039 case CK_AtomicToNonAtomic:
20040 case CK_NoOp:
20041 case CK_LValueToRValueBitCast:
20042 case CK_HLSLArrayRValue:
20043 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20044
20045 case CK_Dependent:
20046 case CK_LValueBitCast:
20047 case CK_UserDefinedConversion:
20048 return Error(E);
20049
20050 case CK_FloatingRealToComplex: {
20051 APFloat &Real = Result.FloatReal;
20052 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20053 return false;
20054
20055 Result.makeComplexFloat();
20056 Result.FloatImag = APFloat(Real.getSemantics());
20057 return true;
20058 }
20059
20060 case CK_FloatingComplexCast: {
20061 if (!Visit(E->getSubExpr()))
20062 return false;
20063
20064 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20065 QualType From
20066 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20067
20068 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20069 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20070 }
20071
20072 case CK_FloatingComplexToIntegralComplex: {
20073 if (!Visit(E->getSubExpr()))
20074 return false;
20075
20076 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20077 QualType From
20078 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20079 Result.makeComplexInt();
20080 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20081 To, Result.IntReal) &&
20082 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20083 To, Result.IntImag);
20084 }
20085
20086 case CK_IntegralRealToComplex: {
20087 APSInt &Real = Result.IntReal;
20088 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20089 return false;
20090
20091 Result.makeComplexInt();
20092 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20093 return true;
20094 }
20095
20096 case CK_IntegralComplexCast: {
20097 if (!Visit(E->getSubExpr()))
20098 return false;
20099
20100 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20101 QualType From
20102 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20103
20104 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20105 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20106 return true;
20107 }
20108
20109 case CK_IntegralComplexToFloatingComplex: {
20110 if (!Visit(E->getSubExpr()))
20111 return false;
20112
20113 const FPOptions FPO = E->getFPFeaturesInEffect(
20114 Info.Ctx.getLangOpts());
20115 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20116 QualType From
20117 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20118 Result.makeComplexFloat();
20119 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20120 To, Result.FloatReal) &&
20121 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20122 To, Result.FloatImag);
20123 }
20124 }
20125
20126 llvm_unreachable("unknown cast resulting in complex value");
20127}
20128
20129uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
20130 // Lookup Table for Multiplicative Inverse in GF(2^8)
20131 const uint8_t GFInv[256] = {
20132 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20133 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20134 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20135 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20136 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20137 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20138 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20139 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20140 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20141 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20142 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20143 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20144 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20145 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20146 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20147 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20148 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20149 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20150 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20151 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20152 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20153 0xcd, 0x1a, 0x41, 0x1c};
20154
20155 return GFInv[Byte];
20156}
20157
20158uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20159 bool Inverse) {
20160 unsigned NumBitsInByte = 8;
20161 // Computing the affine transformation
20162 uint8_t RetByte = 0;
20163 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20164 uint8_t AByte =
20165 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20166 .getLoBits(8)
20167 .getZExtValue();
20168 uint8_t Product;
20169 if (Inverse) {
20170 Product = AByte & GFNIMultiplicativeInverse(XByte);
20171 } else {
20172 Product = AByte & XByte;
20173 }
20174 uint8_t Parity = 0;
20175
20176 // Dot product in GF(2) uses XOR instead of addition
20177 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20178 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20179 }
20180
20181 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20182 RetByte |= (Temp ^ Parity) << BitIdx;
20183 }
20184 return RetByte;
20185}
20186
20187uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
20188 // Multiplying two polynomials of degree 7
20189 // Polynomial of degree 7
20190 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20191 uint16_t TWord = 0;
20192 unsigned NumBitsInByte = 8;
20193 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20194 if ((BByte >> BitIdx) & 0x1) {
20195 TWord = TWord ^ (AByte << BitIdx);
20196 }
20197 }
20198
20199 // When multiplying two polynomials of degree 7
20200 // results in a polynomial of degree 14
20201 // so the result has to be reduced to 7
20202 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20203 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20204 if ((TWord >> BitIdx) & 0x1) {
20205 TWord = TWord ^ (0x11B << (BitIdx - 8));
20206 }
20207 }
20208 return (TWord & 0xFF);
20209}
20210
20211void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20212 APFloat &ResR, APFloat &ResI) {
20213 // This is an implementation of complex multiplication according to the
20214 // constraints laid out in C11 Annex G. The implementation uses the
20215 // following naming scheme:
20216 // (a + ib) * (c + id)
20217
20218 APFloat AC = A * C;
20219 APFloat BD = B * D;
20220 APFloat AD = A * D;
20221 APFloat BC = B * C;
20222 ResR = AC - BD;
20223 ResI = AD + BC;
20224 if (ResR.isNaN() && ResI.isNaN()) {
20225 bool Recalc = false;
20226 if (A.isInfinity() || B.isInfinity()) {
20227 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20228 A);
20229 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20230 B);
20231 if (C.isNaN())
20232 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20233 if (D.isNaN())
20234 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20235 Recalc = true;
20236 }
20237 if (C.isInfinity() || D.isInfinity()) {
20238 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20239 C);
20240 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20241 D);
20242 if (A.isNaN())
20243 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20244 if (B.isNaN())
20245 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20246 Recalc = true;
20247 }
20248 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20249 BC.isInfinity())) {
20250 if (A.isNaN())
20251 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20252 if (B.isNaN())
20253 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20254 if (C.isNaN())
20255 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20256 if (D.isNaN())
20257 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20258 Recalc = true;
20259 }
20260 if (Recalc) {
20261 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20262 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20263 }
20264 }
20265}
20266
20267void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20268 APFloat &ResR, APFloat &ResI) {
20269 // This is an implementation of complex division according to the
20270 // constraints laid out in C11 Annex G. The implementation uses the
20271 // following naming scheme:
20272 // (a + ib) / (c + id)
20273
20274 int DenomLogB = 0;
20275 APFloat MaxCD = maxnum(abs(C), abs(D));
20276 if (MaxCD.isFinite()) {
20277 DenomLogB = ilogb(MaxCD);
20278 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20279 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20280 }
20281 APFloat Denom = C * C + D * D;
20282 ResR =
20283 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20284 ResI =
20285 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20286 if (ResR.isNaN() && ResI.isNaN()) {
20287 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20288 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20289 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20290 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20291 D.isFinite()) {
20292 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20293 A);
20294 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20295 B);
20296 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20297 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20298 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20299 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20300 C);
20301 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20302 D);
20303 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20304 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20305 }
20306 }
20307}
20308
20310 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20311 APSInt NormAmt = Amount;
20312 unsigned BitWidth = Value.getBitWidth();
20313 unsigned AmtBitWidth = NormAmt.getBitWidth();
20314 if (BitWidth == 1) {
20315 // Rotating a 1-bit value is always a no-op
20316 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20317 } else if (BitWidth == 2) {
20318 // For 2-bit values: rotation amount is 0 or 1 based on
20319 // whether the amount is even or odd. We can't use srem here because
20320 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20321 NormAmt =
20322 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20323 } else {
20324 APInt Divisor;
20325 if (AmtBitWidth > BitWidth) {
20326 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20327 } else {
20328 Divisor = llvm::APInt(BitWidth, BitWidth);
20329 if (AmtBitWidth < BitWidth) {
20330 NormAmt = NormAmt.extend(BitWidth);
20331 }
20332 }
20333
20334 // Normalize to [0, BitWidth)
20335 if (NormAmt.isSigned()) {
20336 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20337 if (NormAmt.isNegative()) {
20338 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20339 NormAmt += SignedDivisor;
20340 }
20341 } else {
20342 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20343 }
20344 }
20345
20346 return NormAmt;
20347}
20348
20349bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20350 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20351 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20352
20353 // Track whether the LHS or RHS is real at the type system level. When this is
20354 // the case we can simplify our evaluation strategy.
20355 bool LHSReal = false, RHSReal = false;
20356
20357 bool LHSOK;
20358 if (E->getLHS()->getType()->isRealFloatingType()) {
20359 LHSReal = true;
20360 APFloat &Real = Result.FloatReal;
20361 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20362 if (LHSOK) {
20363 Result.makeComplexFloat();
20364 Result.FloatImag = APFloat(Real.getSemantics());
20365 }
20366 } else {
20367 LHSOK = Visit(E->getLHS());
20368 }
20369 if (!LHSOK && !Info.noteFailure())
20370 return false;
20371
20372 ComplexValue RHS;
20373 if (E->getRHS()->getType()->isRealFloatingType()) {
20374 RHSReal = true;
20375 APFloat &Real = RHS.FloatReal;
20376 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20377 return false;
20378 RHS.makeComplexFloat();
20379 RHS.FloatImag = APFloat(Real.getSemantics());
20380 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20381 return false;
20382
20383 assert(!(LHSReal && RHSReal) &&
20384 "Cannot have both operands of a complex operation be real.");
20385 switch (E->getOpcode()) {
20386 default: return Error(E);
20387 case BO_Add:
20388 if (Result.isComplexFloat()) {
20389 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20390 APFloat::rmNearestTiesToEven);
20391 if (LHSReal)
20392 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20393 else if (!RHSReal)
20394 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20395 APFloat::rmNearestTiesToEven);
20396 } else {
20397 Result.getComplexIntReal() += RHS.getComplexIntReal();
20398 Result.getComplexIntImag() += RHS.getComplexIntImag();
20399 }
20400 break;
20401 case BO_Sub:
20402 if (Result.isComplexFloat()) {
20403 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20404 APFloat::rmNearestTiesToEven);
20405 if (LHSReal) {
20406 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20407 Result.getComplexFloatImag().changeSign();
20408 } else if (!RHSReal) {
20409 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20410 APFloat::rmNearestTiesToEven);
20411 }
20412 } else {
20413 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20414 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20415 }
20416 break;
20417 case BO_Mul:
20418 if (Result.isComplexFloat()) {
20419 // This is an implementation of complex multiplication according to the
20420 // constraints laid out in C11 Annex G. The implementation uses the
20421 // following naming scheme:
20422 // (a + ib) * (c + id)
20423 ComplexValue LHS = Result;
20424 APFloat &A = LHS.getComplexFloatReal();
20425 APFloat &B = LHS.getComplexFloatImag();
20426 APFloat &C = RHS.getComplexFloatReal();
20427 APFloat &D = RHS.getComplexFloatImag();
20428 APFloat &ResR = Result.getComplexFloatReal();
20429 APFloat &ResI = Result.getComplexFloatImag();
20430 if (LHSReal) {
20431 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20432 ResR = A;
20433 ResI = A;
20434 // ResR = A * C;
20435 // ResI = A * D;
20436 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20437 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20438 return false;
20439 } else if (RHSReal) {
20440 // ResR = C * A;
20441 // ResI = C * B;
20442 ResR = C;
20443 ResI = C;
20444 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20445 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20446 return false;
20447 } else {
20448 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20449 }
20450 } else {
20451 ComplexValue LHS = Result;
20452 Result.getComplexIntReal() =
20453 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20454 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20455 Result.getComplexIntImag() =
20456 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20457 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20458 }
20459 break;
20460 case BO_Div:
20461 if (Result.isComplexFloat()) {
20462 // This is an implementation of complex division according to the
20463 // constraints laid out in C11 Annex G. The implementation uses the
20464 // following naming scheme:
20465 // (a + ib) / (c + id)
20466 ComplexValue LHS = Result;
20467 APFloat &A = LHS.getComplexFloatReal();
20468 APFloat &B = LHS.getComplexFloatImag();
20469 APFloat &C = RHS.getComplexFloatReal();
20470 APFloat &D = RHS.getComplexFloatImag();
20471 APFloat &ResR = Result.getComplexFloatReal();
20472 APFloat &ResI = Result.getComplexFloatImag();
20473 if (RHSReal) {
20474 ResR = A;
20475 ResI = B;
20476 // ResR = A / C;
20477 // ResI = B / C;
20478 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20479 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20480 return false;
20481 } else {
20482 if (LHSReal) {
20483 // No real optimizations we can do here, stub out with zero.
20484 B = APFloat::getZero(A.getSemantics());
20485 }
20486 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20487 }
20488 } else {
20489 ComplexValue LHS = Result;
20490 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20491 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20492 if (Den.isZero())
20493 return Error(E, diag::note_expr_divide_by_zero);
20494
20495 Result.getComplexIntReal() =
20496 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20497 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20498 Result.getComplexIntImag() =
20499 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20500 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20501 }
20502 break;
20503 }
20504
20505 return true;
20506}
20507
20508bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20509 // Get the operand value into 'Result'.
20510 if (!Visit(E->getSubExpr()))
20511 return false;
20512
20513 switch (E->getOpcode()) {
20514 default:
20515 return Error(E);
20516 case UO_Extension:
20517 return true;
20518 case UO_Plus:
20519 // The result is always just the subexpr.
20520 return true;
20521 case UO_Minus:
20522 if (Result.isComplexFloat()) {
20523 Result.getComplexFloatReal().changeSign();
20524 Result.getComplexFloatImag().changeSign();
20525 }
20526 else {
20527 Result.getComplexIntReal() = -Result.getComplexIntReal();
20528 Result.getComplexIntImag() = -Result.getComplexIntImag();
20529 }
20530 return true;
20531 case UO_Not:
20532 if (Result.isComplexFloat())
20533 Result.getComplexFloatImag().changeSign();
20534 else
20535 Result.getComplexIntImag() = -Result.getComplexIntImag();
20536 return true;
20537 }
20538}
20539
20540bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20541 if (E->getNumInits() == 2) {
20542 if (E->getType()->isComplexType()) {
20543 Result.makeComplexFloat();
20544 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20545 return false;
20546 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20547 return false;
20548 } else {
20549 Result.makeComplexInt();
20550 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20551 return false;
20552 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20553 return false;
20554 }
20555 return true;
20556 }
20557 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20558}
20559
20560bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20561 if (!IsConstantEvaluatedBuiltinCall(E))
20562 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20563
20564 switch (E->getBuiltinCallee()) {
20565 case Builtin::BI__builtin_complex:
20566 Result.makeComplexFloat();
20567 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20568 return false;
20569 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20570 return false;
20571 return true;
20572
20573 default:
20574 return false;
20575 }
20576}
20577
20578//===----------------------------------------------------------------------===//
20579// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20580// implicit conversion.
20581//===----------------------------------------------------------------------===//
20582
20583namespace {
20584class AtomicExprEvaluator :
20585 public ExprEvaluatorBase<AtomicExprEvaluator> {
20586 const LValue *This;
20587 APValue &Result;
20588public:
20589 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20590 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20591
20592 bool Success(const APValue &V, const Expr *E) {
20593 Result = V;
20594 return true;
20595 }
20596
20597 bool ZeroInitialization(const Expr *E) {
20598 ImplicitValueInitExpr VIE(
20599 E->getType()->castAs<AtomicType>()->getValueType());
20600 // For atomic-qualified class (and array) types in C++, initialize the
20601 // _Atomic-wrapped subobject directly, in-place.
20602 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20603 : Evaluate(Result, Info, &VIE);
20604 }
20605
20606 bool VisitCastExpr(const CastExpr *E) {
20607 switch (E->getCastKind()) {
20608 default:
20609 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20610 case CK_NullToPointer:
20611 VisitIgnoredValue(E->getSubExpr());
20612 return ZeroInitialization(E);
20613 case CK_NonAtomicToAtomic:
20614 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20615 : Evaluate(Result, Info, E->getSubExpr());
20616 }
20617 }
20618};
20619} // end anonymous namespace
20620
20621static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20622 EvalInfo &Info) {
20623 assert(!E->isValueDependent());
20624 assert(E->isPRValue() && E->getType()->isAtomicType());
20625 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20626}
20627
20628//===----------------------------------------------------------------------===//
20629// Void expression evaluation, primarily for a cast to void on the LHS of a
20630// comma operator
20631//===----------------------------------------------------------------------===//
20632
20633namespace {
20634class VoidExprEvaluator
20635 : public ExprEvaluatorBase<VoidExprEvaluator> {
20636public:
20637 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20638
20639 bool Success(const APValue &V, const Expr *e) { return true; }
20640
20641 bool ZeroInitialization(const Expr *E) { return true; }
20642
20643 bool VisitCastExpr(const CastExpr *E) {
20644 switch (E->getCastKind()) {
20645 default:
20646 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20647 case CK_ToVoid:
20648 VisitIgnoredValue(E->getSubExpr());
20649 return true;
20650 }
20651 }
20652
20653 bool VisitCallExpr(const CallExpr *E) {
20654 if (!IsConstantEvaluatedBuiltinCall(E))
20655 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20656
20657 switch (E->getBuiltinCallee()) {
20658 case Builtin::BI__assume:
20659 case Builtin::BI__builtin_assume:
20660 // The argument is not evaluated!
20661 return true;
20662
20663 case Builtin::BI__builtin_operator_delete:
20664 return HandleOperatorDeleteCall(Info, E);
20665
20666 default:
20667 return false;
20668 }
20669 }
20670
20671 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20672};
20673} // end anonymous namespace
20674
20675bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20676 // We cannot speculatively evaluate a delete expression.
20677 if (Info.SpeculativeEvaluationDepth)
20678 return false;
20679
20680 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20681 if (!OperatorDelete
20682 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20683 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20684 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20685 return false;
20686 }
20687
20688 const Expr *Arg = E->getArgument();
20689
20690 LValue Pointer;
20691 if (!EvaluatePointer(Arg, Pointer, Info))
20692 return false;
20693 if (Pointer.Designator.Invalid)
20694 return false;
20695
20696 // Deleting a null pointer has no effect.
20697 if (Pointer.isNullPointer()) {
20698 // This is the only case where we need to produce an extension warning:
20699 // the only other way we can succeed is if we find a dynamic allocation,
20700 // and we will have warned when we allocated it in that case.
20701 if (!Info.getLangOpts().CPlusPlus20)
20702 Info.CCEDiag(E, diag::note_constexpr_new);
20703 return true;
20704 }
20705
20706 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20707 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20708 if (!Alloc)
20709 return false;
20710 QualType AllocType = Pointer.Base.getDynamicAllocType();
20711
20712 // For the non-array case, the designator must be empty if the static type
20713 // does not have a virtual destructor.
20714 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20716 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20717 << Arg->getType()->getPointeeType() << AllocType;
20718 return false;
20719 }
20720
20721 // For a class type with a virtual destructor, the selected operator delete
20722 // is the one looked up when building the destructor.
20723 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20724 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20725 if (VirtualDelete &&
20726 !VirtualDelete
20727 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20728 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20729 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20730 return false;
20731 }
20732 }
20733
20734 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20735 (*Alloc)->Value, AllocType))
20736 return false;
20737
20738 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20739 // The element was already erased. This means the destructor call also
20740 // deleted the object.
20741 // FIXME: This probably results in undefined behavior before we get this
20742 // far, and should be diagnosed elsewhere first.
20743 Info.FFDiag(E, diag::note_constexpr_double_delete);
20744 return false;
20745 }
20746
20747 return true;
20748}
20749
20750static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
20751 assert(!E->isValueDependent());
20752 assert(E->isPRValue() && E->getType()->isVoidType());
20753 return VoidExprEvaluator(Info).Visit(E);
20754}
20755
20756//===----------------------------------------------------------------------===//
20757// Top level Expr::EvaluateAsRValue method.
20758//===----------------------------------------------------------------------===//
20759
20760static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
20761 assert(!E->isValueDependent());
20762 // In C, function designators are not lvalues, but we evaluate them as if they
20763 // are.
20764 QualType T = E->getType();
20765 if (E->isGLValue() || T->isFunctionType()) {
20766 LValue LV;
20767 if (!EvaluateLValue(E, LV, Info))
20768 return false;
20769 LV.moveInto(Result);
20770 } else if (T->isVectorType()) {
20771 if (!EvaluateVector(E, Result, Info))
20772 return false;
20773 } else if (T->isConstantMatrixType()) {
20774 if (!EvaluateMatrix(E, Result, Info))
20775 return false;
20776 } else if (T->isIntegralOrEnumerationType()) {
20777 if (!IntExprEvaluator(Info, Result).Visit(E))
20778 return false;
20779 } else if (T->hasPointerRepresentation()) {
20780 LValue LV;
20781 if (!EvaluatePointer(E, LV, Info))
20782 return false;
20783 LV.moveInto(Result);
20784 } else if (T->isRealFloatingType()) {
20785 llvm::APFloat F(0.0);
20786 if (!EvaluateFloat(E, F, Info))
20787 return false;
20788 Result = APValue(F);
20789 } else if (T->isAnyComplexType()) {
20790 ComplexValue C;
20791 if (!EvaluateComplex(E, C, Info))
20792 return false;
20793 C.moveInto(Result);
20794 } else if (T->isFixedPointType()) {
20795 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
20796 } else if (T->isMemberPointerType()) {
20797 MemberPtr P;
20798 if (!EvaluateMemberPointer(E, P, Info))
20799 return false;
20800 P.moveInto(Result);
20801 return true;
20802 } else if (T->isArrayType()) {
20803 LValue LV;
20804 APValue &Value =
20805 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20806 if (!EvaluateArray(E, LV, Value, Info))
20807 return false;
20808 Result = Value;
20809 } else if (T->isRecordType()) {
20810 LValue LV;
20811 APValue &Value =
20812 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20813 if (!EvaluateRecord(E, LV, Value, Info))
20814 return false;
20815 Result = Value;
20816 } else if (T->isVoidType()) {
20817 if (!Info.getLangOpts().CPlusPlus11)
20818 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
20819 << E->getType();
20820 if (!EvaluateVoid(E, Info))
20821 return false;
20822 } else if (T->isAtomicType()) {
20824 if (Unqual->isArrayType() || Unqual->isRecordType()) {
20825 LValue LV;
20826 APValue &Value = Info.CurrentCall->createTemporary(
20827 E, Unqual, ScopeKind::FullExpression, LV);
20828 if (!EvaluateAtomic(E, &LV, Value, Info))
20829 return false;
20830 Result = Value;
20831 } else {
20832 if (!EvaluateAtomic(E, nullptr, Result, Info))
20833 return false;
20834 }
20835 } else if (Info.getLangOpts().CPlusPlus11) {
20836 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
20837 return false;
20838 } else {
20839 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
20840 return false;
20841 }
20842
20843 return true;
20844}
20845
20846/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
20847/// cases, the in-place evaluation is essential, since later initializers for
20848/// an object can indirectly refer to subobjects which were initialized earlier.
20849static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
20850 const Expr *E, bool AllowNonLiteralTypes) {
20851 assert(!E->isValueDependent());
20852
20853 // Normally expressions passed to EvaluateInPlace have a type, but not when
20854 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
20855 // replaced with a CXXConstructExpr. This can happen in LLDB.
20856 if (E->getType().isNull())
20857 return false;
20858
20859 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
20860 return false;
20861
20862 if (E->isPRValue()) {
20863 // Evaluate arrays and record types in-place, so that later initializers can
20864 // refer to earlier-initialized members of the object.
20865 QualType T = E->getType();
20866 if (T->isArrayType())
20867 return EvaluateArray(E, This, Result, Info);
20868 else if (T->isRecordType())
20869 return EvaluateRecord(E, This, Result, Info);
20870 else if (T->isAtomicType()) {
20872 if (Unqual->isArrayType() || Unqual->isRecordType())
20873 return EvaluateAtomic(E, &This, Result, Info);
20874 }
20875 }
20876
20877 // For any other type, in-place evaluation is unimportant.
20878 return Evaluate(Result, Info, E);
20879}
20880
20881/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
20882/// lvalue-to-rvalue cast if it is an lvalue.
20883static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
20884 assert(!E->isValueDependent());
20885
20886 if (E->getType().isNull())
20887 return false;
20888
20889 if (!CheckLiteralType(Info, E))
20890 return false;
20891
20892 if (Info.EnableNewConstInterp) {
20893 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
20894 return false;
20895 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20896 ConstantExprKind::Normal);
20897 }
20898
20899 if (!::Evaluate(Result, Info, E))
20900 return false;
20901
20902 // Implicit lvalue-to-rvalue cast.
20903 if (E->isGLValue()) {
20904 LValue LV;
20905 LV.setFrom(Info.Ctx, Result);
20906 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
20907 return false;
20908 }
20909
20910 // Check this core constant expression is a constant expression.
20911 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20912 ConstantExprKind::Normal) &&
20913 CheckMemoryLeaks(Info);
20914}
20915
20916static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
20917 const ASTContext &Ctx, bool &IsConst) {
20918 // Fast-path evaluations of integer literals, since we sometimes see files
20919 // containing vast quantities of these.
20920 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
20921 Result =
20922 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
20923 IsConst = true;
20924 return true;
20925 }
20926
20927 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
20928 Result = APValue(APSInt(APInt(1, L->getValue())));
20929 IsConst = true;
20930 return true;
20931 }
20932
20933 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
20934 Result = APValue(FL->getValue());
20935 IsConst = true;
20936 return true;
20937 }
20938
20939 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
20940 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
20941 IsConst = true;
20942 return true;
20943 }
20944
20945 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
20946 if (CE->hasAPValueResult()) {
20947 APValue APV = CE->getAPValueResult();
20948 if (!APV.isLValue()) {
20949 Result = std::move(APV);
20950 IsConst = true;
20951 return true;
20952 }
20953 }
20954
20955 // The SubExpr is usually just an IntegerLiteral.
20956 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
20957 }
20958
20959 // This case should be rare, but we need to check it before we check on
20960 // the type below.
20961 if (Exp->getType().isNull()) {
20962 IsConst = false;
20963 return true;
20964 }
20965
20966 return false;
20967}
20968
20971 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
20972 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
20973}
20974
20975static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
20976 const ASTContext &Ctx, EvalInfo &Info) {
20977 assert(!E->isValueDependent());
20978 bool IsConst;
20979 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
20980 return IsConst;
20981
20982 return EvaluateAsRValue(Info, E, Result.Val);
20983}
20984
20986 const ASTContext &Ctx,
20987 Expr::SideEffectsKind AllowSideEffects,
20988 EvalInfo &Info) {
20989 assert(!E->isValueDependent());
20991 return false;
20992
20993 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
20994 !ExprResult.Val.isInt() ||
20995 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20996 return false;
20997
20998 return true;
20999}
21000
21002 const ASTContext &Ctx,
21003 Expr::SideEffectsKind AllowSideEffects,
21004 EvalInfo &Info) {
21005 assert(!E->isValueDependent());
21006 if (!E->getType()->isFixedPointType())
21007 return false;
21008
21009 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21010 return false;
21011
21012 if (!ExprResult.Val.isFixedPoint() ||
21013 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21014 return false;
21015
21016 return true;
21017}
21018
21019/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21020/// any crazy technique (that has nothing to do with language standards) that
21021/// we want to. If this function returns true, it returns the folded constant
21022/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21023/// will be applied to the result.
21025 bool InConstantContext) const {
21026 assert(!isValueDependent() &&
21027 "Expression evaluator can't be called on a dependent expression.");
21028 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21029 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21030 Info.InConstantContext = InConstantContext;
21031 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21032}
21033
21035 bool InConstantContext) const {
21036 assert(!isValueDependent() &&
21037 "Expression evaluator can't be called on a dependent expression.");
21038 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21039 EvalResult Scratch;
21040 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21041 HandleConversionToBool(Scratch.Val, Result);
21042}
21043
21045 SideEffectsKind AllowSideEffects,
21046 bool InConstantContext) const {
21047 assert(!isValueDependent() &&
21048 "Expression evaluator can't be called on a dependent expression.");
21049 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21050 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21051 Info.InConstantContext = InConstantContext;
21052 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21053}
21054
21056 SideEffectsKind AllowSideEffects,
21057 bool InConstantContext) const {
21058 assert(!isValueDependent() &&
21059 "Expression evaluator can't be called on a dependent expression.");
21060 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21061 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21062 Info.InConstantContext = InConstantContext;
21063 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21064}
21065
21066bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21067 SideEffectsKind AllowSideEffects,
21068 bool InConstantContext) const {
21069 assert(!isValueDependent() &&
21070 "Expression evaluator can't be called on a dependent expression.");
21071
21072 if (!getType()->isRealFloatingType())
21073 return false;
21074
21075 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21077 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21078 !ExprResult.Val.isFloat() ||
21079 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21080 return false;
21081
21082 Result = ExprResult.Val.getFloat();
21083 return true;
21084}
21085
21087 bool InConstantContext) const {
21088 assert(!isValueDependent() &&
21089 "Expression evaluator can't be called on a dependent expression.");
21090
21091 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21092 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21093 Info.InConstantContext = InConstantContext;
21094 LValue LV;
21095 CheckedTemporaries CheckedTemps;
21096
21097 if (Info.EnableNewConstInterp) {
21098 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21099 ConstantExprKind::Normal))
21100 return false;
21101
21102 LV.setFrom(Ctx, Result.Val);
21104 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21105 ConstantExprKind::Normal, CheckedTemps);
21106 }
21107
21108 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21109 Result.HasSideEffects ||
21112 ConstantExprKind::Normal, CheckedTemps))
21113 return false;
21114
21115 LV.moveInto(Result.Val);
21116 return true;
21117}
21118
21120 APValue DestroyedValue, QualType Type,
21121 SourceLocation Loc, Expr::EvalStatus &EStatus,
21122 bool IsConstantDestruction) {
21123 EvalInfo Info(Ctx, EStatus,
21124 IsConstantDestruction ? EvaluationMode::ConstantExpression
21126 Info.setEvaluatingDecl(Base, DestroyedValue,
21127 EvalInfo::EvaluatingDeclKind::Dtor);
21128 Info.InConstantContext = IsConstantDestruction;
21129
21130 LValue LVal;
21131 LVal.set(Base);
21132
21133 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21134 EStatus.HasSideEffects)
21135 return false;
21136
21137 if (!Info.discardCleanups())
21138 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21139
21140 return true;
21141}
21142
21144 ConstantExprKind Kind) const {
21145 assert(!isValueDependent() &&
21146 "Expression evaluator can't be called on a dependent expression.");
21147 bool IsConst;
21148 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21149 Result.Val.hasValue())
21150 return true;
21151
21152 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21154 EvalInfo Info(Ctx, Result, EM);
21155 Info.InConstantContext = true;
21156
21157 if (Info.EnableNewConstInterp) {
21158 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21159 return false;
21160 return CheckConstantExpression(Info, getExprLoc(),
21161 getStorageType(Ctx, this), Result.Val, Kind);
21162 }
21163
21164 // The type of the object we're initializing is 'const T' for a class NTTP.
21165 QualType T = getType();
21166 if (Kind == ConstantExprKind::ClassTemplateArgument)
21167 T.addConst();
21168
21169 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21170 // represent the result of the evaluation. CheckConstantExpression ensures
21171 // this doesn't escape.
21172 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21173 APValue::LValueBase Base(&BaseMTE);
21174 Info.setEvaluatingDecl(Base, Result.Val);
21175
21176 LValue LVal;
21177 LVal.set(Base);
21178 // C++23 [intro.execution]/p5
21179 // A full-expression is [...] a constant-expression
21180 // So we need to make sure temporary objects are destroyed after having
21181 // evaluating the expression (per C++23 [class.temporary]/p4).
21182 FullExpressionRAII Scope(Info);
21183 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21184 Result.HasSideEffects || !Scope.destroy())
21185 return false;
21186
21187 if (!Info.discardCleanups())
21188 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21189
21190 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21191 Result.Val, Kind))
21192 return false;
21193 if (!CheckMemoryLeaks(Info))
21194 return false;
21195
21196 // If this is a class template argument, it's required to have constant
21197 // destruction too.
21198 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21200 true) ||
21201 Result.HasSideEffects)) {
21202 // FIXME: Prefix a note to indicate that the problem is lack of constant
21203 // destruction.
21204 return false;
21205 }
21206
21207 return true;
21208}
21209
21211 const VarDecl *VD,
21213 bool IsConstantInitialization) const {
21214 assert(!isValueDependent() &&
21215 "Expression evaluator can't be called on a dependent expression.");
21216 assert(VD && "Need a valid VarDecl");
21217
21218 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21219 std::string Name;
21220 llvm::raw_string_ostream OS(Name);
21221 VD->printQualifiedName(OS);
21222 return Name;
21223 });
21224
21225 Expr::EvalStatus EStatus;
21226 EStatus.Diag = &Notes;
21227
21228 EvalInfo Info(Ctx, EStatus,
21229 (IsConstantInitialization &&
21230 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21233 Info.setEvaluatingDecl(VD, Value);
21234 Info.InConstantContext = IsConstantInitialization;
21235
21236 SourceLocation DeclLoc = VD->getLocation();
21237 QualType DeclTy = VD->getType();
21238
21239 if (Info.EnableNewConstInterp) {
21240 auto &InterpCtx = Ctx.getInterpContext();
21241 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
21242 return false;
21243
21244 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21245 ConstantExprKind::Normal);
21246 } else {
21247 LValue LVal;
21248 LVal.set(VD);
21249
21250 {
21251 // C++23 [intro.execution]/p5
21252 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21253 // mem-initializer.
21254 // So we need to make sure temporary objects are destroyed after having
21255 // evaluated the expression (per C++23 [class.temporary]/p4).
21256 //
21257 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21258 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21259 // outermost FullExpr, such as ExprWithCleanups.
21260 FullExpressionRAII Scope(Info);
21261 if (!EvaluateInPlace(Value, Info, LVal, this,
21262 /*AllowNonLiteralTypes=*/true) ||
21263 EStatus.HasSideEffects)
21264 return false;
21265 }
21266
21267 // At this point, any lifetime-extended temporaries are completely
21268 // initialized.
21269 Info.performLifetimeExtension();
21270
21271 if (!Info.discardCleanups())
21272 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21273 }
21274
21275 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21276 ConstantExprKind::Normal) &&
21277 CheckMemoryLeaks(Info);
21278}
21279
21282 Expr::EvalStatus EStatus;
21283 EStatus.Diag = &Notes;
21284
21285 // Only treat the destruction as constant destruction if we formally have
21286 // constant initialization (or are usable in a constant expression).
21287 bool IsConstantDestruction = hasConstantInitialization();
21288
21289 // Make a copy of the value for the destructor to mutate, if we know it.
21290 // Otherwise, treat the value as default-initialized; if the destructor works
21291 // anyway, then the destruction is constant (and must be essentially empty).
21292 APValue DestroyedValue;
21293 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
21294 DestroyedValue = *getEvaluatedValue();
21295 else if (!handleDefaultInitValue(getType(), DestroyedValue))
21296 return false;
21297
21298 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
21299 getType(), getLocation(), EStatus,
21300 IsConstantDestruction) ||
21301 EStatus.HasSideEffects)
21302 return false;
21303
21304 ensureEvaluatedStmt()->HasConstantDestruction = true;
21305 return true;
21306}
21307
21308/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21309/// constant folded, but discard the result.
21311 assert(!isValueDependent() &&
21312 "Expression evaluator can't be called on a dependent expression.");
21313
21315 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21317}
21318
21319APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21320 assert(!isValueDependent() &&
21321 "Expression evaluator can't be called on a dependent expression.");
21322
21323 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21324 EvalResult EVResult;
21325 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21326 Info.InConstantContext = true;
21327
21328 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21329 (void)Result;
21330 assert(Result && "Could not evaluate expression");
21331 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21332
21333 return EVResult.Val.getInt();
21334}
21335
21338 assert(!isValueDependent() &&
21339 "Expression evaluator can't be called on a dependent expression.");
21340
21341 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21342 EvalResult EVResult;
21343 EVResult.Diag = Diag;
21344 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21345 Info.InConstantContext = true;
21346 Info.CheckingForUndefinedBehavior = true;
21347
21348 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21349 (void)Result;
21350 assert(Result && "Could not evaluate expression");
21351 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21352
21353 return EVResult.Val.getInt();
21354}
21355
21357 assert(!isValueDependent() &&
21358 "Expression evaluator can't be called on a dependent expression.");
21359
21360 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21361 bool IsConst;
21362 EvalResult EVResult;
21363 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21364 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21365 Info.CheckingForUndefinedBehavior = true;
21366 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21367 }
21368}
21369
21371 assert(Val.isLValue());
21372 return IsGlobalLValue(Val.getLValueBase());
21373}
21374
21375/// isIntegerConstantExpr - this recursive routine will test if an expression is
21376/// an integer constant expression.
21377
21378/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21379/// comma, etc
21380
21381// CheckICE - This function does the fundamental ICE checking: the returned
21382// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21383//
21384// Note that to reduce code duplication, this helper does no evaluation
21385// itself; the caller checks whether the expression is evaluatable, and
21386// in the rare cases where CheckICE actually cares about the evaluated
21387// value, it calls into Evaluate.
21388
21389namespace {
21390
21391enum ICEKind {
21392 /// This expression is an ICE.
21393 IK_ICE,
21394 /// This expression is not an ICE, but if it isn't evaluated, it's
21395 /// a legal subexpression for an ICE. This return value is used to handle
21396 /// the comma operator in C99 mode, and non-constant subexpressions.
21397 IK_ICEIfUnevaluated,
21398 /// This expression is not an ICE, and is not a legal subexpression for one.
21399 IK_NotICE
21400};
21401
21402struct ICEDiag {
21403 ICEKind Kind;
21404 SourceLocation Loc;
21405
21406 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21407};
21408
21409}
21410
21411static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21412
21413static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21414
21415static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21416 Expr::EvalResult EVResult;
21417 Expr::EvalStatus Status;
21418 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21419
21420 Info.InConstantContext = true;
21421 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21422 !EVResult.Val.isInt())
21423 return ICEDiag(IK_NotICE, E->getBeginLoc());
21424
21425 return NoDiag();
21426}
21427
21428static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21429 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21431 return ICEDiag(IK_NotICE, E->getBeginLoc());
21432
21433 switch (E->getStmtClass()) {
21434#define ABSTRACT_STMT(Node)
21435#define STMT(Node, Base) case Expr::Node##Class:
21436#define EXPR(Node, Base)
21437#include "clang/AST/StmtNodes.inc"
21438 case Expr::PredefinedExprClass:
21439 case Expr::FloatingLiteralClass:
21440 case Expr::ImaginaryLiteralClass:
21441 case Expr::StringLiteralClass:
21442 case Expr::ArraySubscriptExprClass:
21443 case Expr::MatrixSingleSubscriptExprClass:
21444 case Expr::MatrixSubscriptExprClass:
21445 case Expr::ArraySectionExprClass:
21446 case Expr::OMPArrayShapingExprClass:
21447 case Expr::OMPIteratorExprClass:
21448 case Expr::CompoundAssignOperatorClass:
21449 case Expr::CompoundLiteralExprClass:
21450 case Expr::ExtVectorElementExprClass:
21451 case Expr::MatrixElementExprClass:
21452 case Expr::DesignatedInitExprClass:
21453 case Expr::ArrayInitLoopExprClass:
21454 case Expr::ArrayInitIndexExprClass:
21455 case Expr::NoInitExprClass:
21456 case Expr::DesignatedInitUpdateExprClass:
21457 case Expr::ImplicitValueInitExprClass:
21458 case Expr::ParenListExprClass:
21459 case Expr::VAArgExprClass:
21460 case Expr::AddrLabelExprClass:
21461 case Expr::StmtExprClass:
21462 case Expr::CXXMemberCallExprClass:
21463 case Expr::CUDAKernelCallExprClass:
21464 case Expr::CXXAddrspaceCastExprClass:
21465 case Expr::CXXDynamicCastExprClass:
21466 case Expr::CXXTypeidExprClass:
21467 case Expr::CXXUuidofExprClass:
21468 case Expr::MSPropertyRefExprClass:
21469 case Expr::MSPropertySubscriptExprClass:
21470 case Expr::CXXNullPtrLiteralExprClass:
21471 case Expr::UserDefinedLiteralClass:
21472 case Expr::CXXThisExprClass:
21473 case Expr::CXXThrowExprClass:
21474 case Expr::CXXNewExprClass:
21475 case Expr::CXXDeleteExprClass:
21476 case Expr::CXXPseudoDestructorExprClass:
21477 case Expr::UnresolvedLookupExprClass:
21478 case Expr::RecoveryExprClass:
21479 case Expr::DependentScopeDeclRefExprClass:
21480 case Expr::CXXConstructExprClass:
21481 case Expr::CXXInheritedCtorInitExprClass:
21482 case Expr::CXXStdInitializerListExprClass:
21483 case Expr::CXXBindTemporaryExprClass:
21484 case Expr::ExprWithCleanupsClass:
21485 case Expr::CXXTemporaryObjectExprClass:
21486 case Expr::CXXUnresolvedConstructExprClass:
21487 case Expr::CXXDependentScopeMemberExprClass:
21488 case Expr::UnresolvedMemberExprClass:
21489 case Expr::ObjCStringLiteralClass:
21490 case Expr::ObjCBoxedExprClass:
21491 case Expr::ObjCArrayLiteralClass:
21492 case Expr::ObjCDictionaryLiteralClass:
21493 case Expr::ObjCEncodeExprClass:
21494 case Expr::ObjCMessageExprClass:
21495 case Expr::ObjCSelectorExprClass:
21496 case Expr::ObjCProtocolExprClass:
21497 case Expr::ObjCIvarRefExprClass:
21498 case Expr::ObjCPropertyRefExprClass:
21499 case Expr::ObjCSubscriptRefExprClass:
21500 case Expr::ObjCIsaExprClass:
21501 case Expr::ObjCAvailabilityCheckExprClass:
21502 case Expr::ShuffleVectorExprClass:
21503 case Expr::ConvertVectorExprClass:
21504 case Expr::BlockExprClass:
21505 case Expr::NoStmtClass:
21506 case Expr::OpaqueValueExprClass:
21507 case Expr::PackExpansionExprClass:
21508 case Expr::SubstNonTypeTemplateParmPackExprClass:
21509 case Expr::FunctionParmPackExprClass:
21510 case Expr::AsTypeExprClass:
21511 case Expr::ObjCIndirectCopyRestoreExprClass:
21512 case Expr::MaterializeTemporaryExprClass:
21513 case Expr::PseudoObjectExprClass:
21514 case Expr::AtomicExprClass:
21515 case Expr::LambdaExprClass:
21516 case Expr::CXXFoldExprClass:
21517 case Expr::CoawaitExprClass:
21518 case Expr::DependentCoawaitExprClass:
21519 case Expr::CoyieldExprClass:
21520 case Expr::SYCLUniqueStableNameExprClass:
21521 case Expr::CXXParenListInitExprClass:
21522 case Expr::HLSLOutArgExprClass:
21523 return ICEDiag(IK_NotICE, E->getBeginLoc());
21524
21525 case Expr::MemberExprClass: {
21526 if (Ctx.getLangOpts().C23) {
21527 const Expr *ME = E->IgnoreParenImpCasts();
21528 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
21529 if (M->isArrow())
21530 return ICEDiag(IK_NotICE, E->getBeginLoc());
21531 ME = M->getBase()->IgnoreParenImpCasts();
21532 }
21533 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
21534 if (DRE) {
21535 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
21536 VD && VD->isConstexpr())
21537 return CheckEvalInICE(E, Ctx);
21538 }
21539 }
21540 return ICEDiag(IK_NotICE, E->getBeginLoc());
21541 }
21542
21543 case Expr::InitListExprClass: {
21544 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21545 // form "T x = { a };" is equivalent to "T x = a;".
21546 // Unless we're initializing a reference, T is a scalar as it is known to be
21547 // of integral or enumeration type.
21548 if (E->isPRValue())
21549 if (cast<InitListExpr>(E)->getNumInits() == 1)
21550 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21551 return ICEDiag(IK_NotICE, E->getBeginLoc());
21552 }
21553
21554 case Expr::SizeOfPackExprClass:
21555 case Expr::GNUNullExprClass:
21556 case Expr::SourceLocExprClass:
21557 case Expr::EmbedExprClass:
21558 case Expr::OpenACCAsteriskSizeExprClass:
21559 return NoDiag();
21560
21561 case Expr::PackIndexingExprClass:
21562 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21563
21564 case Expr::SubstNonTypeTemplateParmExprClass:
21565 return
21566 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21567
21568 case Expr::ConstantExprClass:
21569 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21570
21571 case Expr::ParenExprClass:
21572 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21573 case Expr::GenericSelectionExprClass:
21574 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21575 case Expr::IntegerLiteralClass:
21576 case Expr::FixedPointLiteralClass:
21577 case Expr::CharacterLiteralClass:
21578 case Expr::ObjCBoolLiteralExprClass:
21579 case Expr::CXXBoolLiteralExprClass:
21580 case Expr::CXXScalarValueInitExprClass:
21581 case Expr::TypeTraitExprClass:
21582 case Expr::ConceptSpecializationExprClass:
21583 case Expr::RequiresExprClass:
21584 case Expr::ArrayTypeTraitExprClass:
21585 case Expr::ExpressionTraitExprClass:
21586 case Expr::CXXNoexceptExprClass:
21587 case Expr::CXXReflectExprClass:
21588 return NoDiag();
21589 case Expr::CallExprClass:
21590 case Expr::CXXOperatorCallExprClass: {
21591 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21592 // constant expressions, but they can never be ICEs because an ICE cannot
21593 // contain an operand of (pointer to) function type.
21594 const CallExpr *CE = cast<CallExpr>(E);
21595 if (CE->getBuiltinCallee())
21596 return CheckEvalInICE(E, Ctx);
21597 return ICEDiag(IK_NotICE, E->getBeginLoc());
21598 }
21599 case Expr::CXXRewrittenBinaryOperatorClass:
21600 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21601 Ctx);
21602 case Expr::DeclRefExprClass: {
21603 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21604 if (isa<EnumConstantDecl>(D))
21605 return NoDiag();
21606
21607 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21608 // integer variables in constant expressions:
21609 //
21610 // C++ 7.1.5.1p2
21611 // A variable of non-volatile const-qualified integral or enumeration
21612 // type initialized by an ICE can be used in ICEs.
21613 //
21614 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21615 // that mode, use of reference variables should not be allowed.
21616 const VarDecl *VD = dyn_cast<VarDecl>(D);
21617 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21618 !VD->getType()->isReferenceType())
21619 return NoDiag();
21620
21621 return ICEDiag(IK_NotICE, E->getBeginLoc());
21622 }
21623 case Expr::UnaryOperatorClass: {
21624 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21625 switch (Exp->getOpcode()) {
21626 case UO_PostInc:
21627 case UO_PostDec:
21628 case UO_PreInc:
21629 case UO_PreDec:
21630 case UO_AddrOf:
21631 case UO_Deref:
21632 case UO_Coawait:
21633 // C99 6.6/3 allows increment and decrement within unevaluated
21634 // subexpressions of constant expressions, but they can never be ICEs
21635 // because an ICE cannot contain an lvalue operand.
21636 return ICEDiag(IK_NotICE, E->getBeginLoc());
21637 case UO_Extension:
21638 case UO_LNot:
21639 case UO_Plus:
21640 case UO_Minus:
21641 case UO_Not:
21642 case UO_Real:
21643 case UO_Imag:
21644 return CheckICE(Exp->getSubExpr(), Ctx);
21645 }
21646 llvm_unreachable("invalid unary operator class");
21647 }
21648 case Expr::OffsetOfExprClass: {
21649 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21650 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21651 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21652 // compliance: we should warn earlier for offsetof expressions with
21653 // array subscripts that aren't ICEs, and if the array subscripts
21654 // are ICEs, the value of the offsetof must be an integer constant.
21655 return CheckEvalInICE(E, Ctx);
21656 }
21657 case Expr::UnaryExprOrTypeTraitExprClass: {
21659 if ((Exp->getKind() == UETT_SizeOf) &&
21661 return ICEDiag(IK_NotICE, E->getBeginLoc());
21662 if (Exp->getKind() == UETT_CountOf) {
21663 QualType ArgTy = Exp->getTypeOfArgument();
21664 if (ArgTy->isVariableArrayType()) {
21665 // We need to look whether the array is multidimensional. If it is,
21666 // then we want to check the size expression manually to see whether
21667 // it is an ICE or not.
21668 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21669 if (VAT->getElementType()->isArrayType())
21670 // Variable array size expression could be missing (e.g. int a[*][10])
21671 // In that case, it can't be a constant expression.
21672 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21673 : ICEDiag(IK_NotICE, E->getBeginLoc());
21674
21675 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21676 return ICEDiag(IK_NotICE, E->getBeginLoc());
21677 }
21678 }
21679 return NoDiag();
21680 }
21681 case Expr::BinaryOperatorClass: {
21682 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21683 switch (Exp->getOpcode()) {
21684 case BO_PtrMemD:
21685 case BO_PtrMemI:
21686 case BO_Assign:
21687 case BO_MulAssign:
21688 case BO_DivAssign:
21689 case BO_RemAssign:
21690 case BO_AddAssign:
21691 case BO_SubAssign:
21692 case BO_ShlAssign:
21693 case BO_ShrAssign:
21694 case BO_AndAssign:
21695 case BO_XorAssign:
21696 case BO_OrAssign:
21697 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21698 // constant expressions, but they can never be ICEs because an ICE cannot
21699 // contain an lvalue operand.
21700 return ICEDiag(IK_NotICE, E->getBeginLoc());
21701
21702 case BO_Mul:
21703 case BO_Div:
21704 case BO_Rem:
21705 case BO_Add:
21706 case BO_Sub:
21707 case BO_Shl:
21708 case BO_Shr:
21709 case BO_LT:
21710 case BO_GT:
21711 case BO_LE:
21712 case BO_GE:
21713 case BO_EQ:
21714 case BO_NE:
21715 case BO_And:
21716 case BO_Xor:
21717 case BO_Or:
21718 case BO_Comma:
21719 case BO_Cmp: {
21720 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21721 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21722 if (Exp->getOpcode() == BO_Div ||
21723 Exp->getOpcode() == BO_Rem) {
21724 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21725 // we don't evaluate one.
21726 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21727 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21728 if (REval == 0)
21729 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21730 if (REval.isSigned() && REval.isAllOnes()) {
21731 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21732 if (LEval.isMinSignedValue())
21733 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21734 }
21735 }
21736 }
21737 if (Exp->getOpcode() == BO_Comma) {
21738 if (Ctx.getLangOpts().C99) {
21739 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21740 // if it isn't evaluated.
21741 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
21742 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21743 } else {
21744 // In both C89 and C++, commas in ICEs are illegal.
21745 return ICEDiag(IK_NotICE, E->getBeginLoc());
21746 }
21747 }
21748 return Worst(LHSResult, RHSResult);
21749 }
21750 case BO_LAnd:
21751 case BO_LOr: {
21752 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21753 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21754 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
21755 // Rare case where the RHS has a comma "side-effect"; we need
21756 // to actually check the condition to see whether the side
21757 // with the comma is evaluated.
21758 if ((Exp->getOpcode() == BO_LAnd) !=
21759 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
21760 return RHSResult;
21761 return NoDiag();
21762 }
21763
21764 return Worst(LHSResult, RHSResult);
21765 }
21766 }
21767 llvm_unreachable("invalid binary operator kind");
21768 }
21769 case Expr::ImplicitCastExprClass:
21770 case Expr::CStyleCastExprClass:
21771 case Expr::CXXFunctionalCastExprClass:
21772 case Expr::CXXStaticCastExprClass:
21773 case Expr::CXXReinterpretCastExprClass:
21774 case Expr::CXXConstCastExprClass:
21775 case Expr::ObjCBridgedCastExprClass: {
21776 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
21777 if (isa<ExplicitCastExpr>(E)) {
21778 if (const FloatingLiteral *FL
21779 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
21780 unsigned DestWidth = Ctx.getIntWidth(E->getType());
21781 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
21782 APSInt IgnoredVal(DestWidth, !DestSigned);
21783 bool Ignored;
21784 // If the value does not fit in the destination type, the behavior is
21785 // undefined, so we are not required to treat it as a constant
21786 // expression.
21787 if (FL->getValue().convertToInteger(IgnoredVal,
21788 llvm::APFloat::rmTowardZero,
21789 &Ignored) & APFloat::opInvalidOp)
21790 return ICEDiag(IK_NotICE, E->getBeginLoc());
21791 return NoDiag();
21792 }
21793 }
21794 switch (cast<CastExpr>(E)->getCastKind()) {
21795 case CK_LValueToRValue:
21796 case CK_AtomicToNonAtomic:
21797 case CK_NonAtomicToAtomic:
21798 case CK_NoOp:
21799 case CK_IntegralToBoolean:
21800 case CK_IntegralCast:
21801 return CheckICE(SubExpr, Ctx);
21802 default:
21803 return ICEDiag(IK_NotICE, E->getBeginLoc());
21804 }
21805 }
21806 case Expr::BinaryConditionalOperatorClass: {
21808 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
21809 if (CommonResult.Kind == IK_NotICE) return CommonResult;
21810 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21811 if (FalseResult.Kind == IK_NotICE) return FalseResult;
21812 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
21813 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
21814 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
21815 return FalseResult;
21816 }
21817 case Expr::ConditionalOperatorClass: {
21819 // If the condition (ignoring parens) is a __builtin_constant_p call,
21820 // then only the true side is actually considered in an integer constant
21821 // expression, and it is fully evaluated. This is an important GNU
21822 // extension. See GCC PR38377 for discussion.
21823 if (const CallExpr *CallCE
21824 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
21825 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
21826 return CheckEvalInICE(E, Ctx);
21827 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
21828 if (CondResult.Kind == IK_NotICE)
21829 return CondResult;
21830
21831 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
21832 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21833
21834 if (TrueResult.Kind == IK_NotICE)
21835 return TrueResult;
21836 if (FalseResult.Kind == IK_NotICE)
21837 return FalseResult;
21838 if (CondResult.Kind == IK_ICEIfUnevaluated)
21839 return CondResult;
21840 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
21841 return NoDiag();
21842 // Rare case where the diagnostics depend on which side is evaluated
21843 // Note that if we get here, CondResult is 0, and at least one of
21844 // TrueResult and FalseResult is non-zero.
21845 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
21846 return FalseResult;
21847 return TrueResult;
21848 }
21849 case Expr::CXXDefaultArgExprClass:
21850 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
21851 case Expr::CXXDefaultInitExprClass:
21852 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
21853 case Expr::ChooseExprClass: {
21854 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
21855 }
21856 case Expr::BuiltinBitCastExprClass: {
21857 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
21858 return ICEDiag(IK_NotICE, E->getBeginLoc());
21859 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
21860 }
21861 }
21862
21863 llvm_unreachable("Invalid StmtClass!");
21864}
21865
21866/// Evaluate an expression as a C++11 integral constant expression.
21868 const Expr *E,
21869 llvm::APSInt *Value) {
21871 return false;
21872
21873 APValue Result;
21874 if (!E->isCXX11ConstantExpr(Ctx, &Result))
21875 return false;
21876
21877 if (!Result.isInt())
21878 return false;
21879
21880 if (Value) *Value = Result.getInt();
21881 return true;
21882}
21883
21885 assert(!isValueDependent() &&
21886 "Expression evaluator can't be called on a dependent expression.");
21887
21888 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
21889
21890 if (Ctx.getLangOpts().CPlusPlus11)
21891 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
21892
21893 ICEDiag D = CheckICE(this, Ctx);
21894 if (D.Kind != IK_ICE)
21895 return false;
21896 return true;
21897}
21898
21899std::optional<llvm::APSInt>
21901 if (isValueDependent()) {
21902 // Expression evaluator can't succeed on a dependent expression.
21903 return std::nullopt;
21904 }
21905
21906 if (Ctx.getLangOpts().CPlusPlus11) {
21907 APSInt Value;
21909 return Value;
21910 return std::nullopt;
21911 }
21912
21913 if (!isIntegerConstantExpr(Ctx))
21914 return std::nullopt;
21915
21916 // The only possible side-effects here are due to UB discovered in the
21917 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
21918 // required to treat the expression as an ICE, so we produce the folded
21919 // value.
21921 Expr::EvalStatus Status;
21922 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
21923 Info.InConstantContext = true;
21924
21925 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
21926 llvm_unreachable("ICE cannot be evaluated!");
21927
21928 return ExprResult.Val.getInt();
21929}
21930
21932 assert(!isValueDependent() &&
21933 "Expression evaluator can't be called on a dependent expression.");
21934
21935 return CheckICE(this, Ctx).Kind == IK_ICE;
21936}
21937
21939 assert(!isValueDependent() &&
21940 "Expression evaluator can't be called on a dependent expression.");
21941
21942 // We support this checking in C++98 mode in order to diagnose compatibility
21943 // issues.
21944 assert(Ctx.getLangOpts().CPlusPlus);
21945
21946 bool IsConst;
21947 APValue Scratch;
21948 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
21949 if (Result)
21950 *Result = std::move(Scratch);
21951 return true;
21952 }
21953
21954 // Build evaluation settings.
21955 Expr::EvalStatus Status;
21957 Status.Diag = &Diags;
21958 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21959
21960 bool IsConstExpr =
21961 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
21962 // FIXME: We don't produce a diagnostic for this, but the callers that
21963 // call us on arbitrary full-expressions should generally not care.
21964 Info.discardCleanups() && !Status.HasSideEffects;
21965
21966 return IsConstExpr && Diags.empty();
21967}
21968
21970 const FunctionDecl *Callee,
21972 const Expr *This) const {
21973 assert(!isValueDependent() &&
21974 "Expression evaluator can't be called on a dependent expression.");
21975
21976 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
21977 std::string Name;
21978 llvm::raw_string_ostream OS(Name);
21979 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
21980 /*Qualified=*/true);
21981 return Name;
21982 });
21983
21984 Expr::EvalStatus Status;
21985 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
21986 Info.InConstantContext = true;
21987
21988 LValue ThisVal;
21989 const LValue *ThisPtr = nullptr;
21990 if (This) {
21991#ifndef NDEBUG
21992 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
21993 assert(MD && "Don't provide `this` for non-methods.");
21994 assert(MD->isImplicitObjectMemberFunction() &&
21995 "Don't provide `this` for methods without an implicit object.");
21996#endif
21997 if (!This->isValueDependent() &&
21998 EvaluateObjectArgument(Info, This, ThisVal) &&
21999 !Info.EvalStatus.HasSideEffects)
22000 ThisPtr = &ThisVal;
22001
22002 // Ignore any side-effects from a failed evaluation. This is safe because
22003 // they can't interfere with any other argument evaluation.
22004 Info.EvalStatus.HasSideEffects = false;
22005 }
22006
22007 CallRef Call = Info.CurrentCall->createCall(Callee);
22008 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22009 I != E; ++I) {
22010 unsigned Idx = I - Args.begin();
22011 if (Idx >= Callee->getNumParams())
22012 break;
22013 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22014 if ((*I)->isValueDependent() ||
22015 !EvaluateCallArg(PVD, *I, Call, Info) ||
22016 Info.EvalStatus.HasSideEffects) {
22017 // If evaluation fails, throw away the argument entirely.
22018 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22019 *Slot = APValue();
22020 }
22021
22022 // Ignore any side-effects from a failed evaluation. This is safe because
22023 // they can't interfere with any other argument evaluation.
22024 Info.EvalStatus.HasSideEffects = false;
22025 }
22026
22027 // Parameter cleanups happen in the caller and are not part of this
22028 // evaluation.
22029 Info.discardCleanups();
22030 Info.EvalStatus.HasSideEffects = false;
22031
22032 // Build fake call to Callee.
22033 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22034 Call);
22035 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22036 FullExpressionRAII Scope(Info);
22037 return Evaluate(Value, Info, this) && Scope.destroy() &&
22038 !Info.EvalStatus.HasSideEffects;
22039}
22040
22043 PartialDiagnosticAt> &Diags) {
22044 // FIXME: It would be useful to check constexpr function templates, but at the
22045 // moment the constant expression evaluator cannot cope with the non-rigorous
22046 // ASTs which we build for dependent expressions.
22047 if (FD->isDependentContext())
22048 return true;
22049
22050 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22051 std::string Name;
22052 llvm::raw_string_ostream OS(Name);
22054 /*Qualified=*/true);
22055 return Name;
22056 });
22057
22058 Expr::EvalStatus Status;
22059 Status.Diag = &Diags;
22060
22061 EvalInfo Info(FD->getASTContext(), Status,
22063 Info.InConstantContext = true;
22064 Info.CheckingPotentialConstantExpression = true;
22065
22066 // The constexpr VM attempts to compile all methods to bytecode here.
22067 if (Info.EnableNewConstInterp) {
22068 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22069 return Diags.empty();
22070 }
22071
22072 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22073 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22074
22075 // Fabricate an arbitrary expression on the stack and pretend that it
22076 // is a temporary being used as the 'this' pointer.
22077 LValue This;
22078 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22079 : Info.Ctx.IntTy);
22080 This.set({&VIE, Info.CurrentCall->Index});
22081
22083
22084 APValue Scratch;
22085 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22086 // Evaluate the call as a constant initializer, to allow the construction
22087 // of objects of non-literal types.
22088 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22089 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22090 } else {
22091 SourceLocation Loc = FD->getLocation();
22093 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22094 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22095 /*ResultSlot=*/nullptr);
22096 }
22097
22098 return Diags.empty();
22099}
22100
22102 const FunctionDecl *FD,
22104 PartialDiagnosticAt> &Diags) {
22105 assert(!E->isValueDependent() &&
22106 "Expression evaluator can't be called on a dependent expression.");
22107
22108 Expr::EvalStatus Status;
22109 Status.Diag = &Diags;
22110
22111 EvalInfo Info(FD->getASTContext(), Status,
22113 Info.InConstantContext = true;
22114 Info.CheckingPotentialConstantExpression = true;
22115
22116 if (Info.EnableNewConstInterp) {
22117 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22118 return Diags.empty();
22119 }
22120
22121 // Fabricate a call stack frame to give the arguments a plausible cover story.
22122 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22123 /*CallExpr=*/nullptr, CallRef());
22124
22125 APValue ResultScratch;
22126 Evaluate(ResultScratch, Info, E);
22127 return Diags.empty();
22128}
22129
22130std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22131 unsigned Type) const {
22132 if (!getType()->isPointerType())
22133 return std::nullopt;
22134
22135 Expr::EvalStatus Status;
22136 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22137 if (Info.EnableNewConstInterp)
22138 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22139 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22140}
22141
22142static std::optional<uint64_t>
22143EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22144 std::string *StringResult) {
22145 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22146 return std::nullopt;
22147
22148 LValue String;
22149
22150 if (!EvaluatePointer(E, String, Info))
22151 return std::nullopt;
22152
22153 QualType CharTy = E->getType()->getPointeeType();
22154
22155 // Fast path: if it's a string literal, search the string value.
22156 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22157 String.getLValueBase().dyn_cast<const Expr *>())) {
22158 StringRef Str = S->getBytes();
22159 int64_t Off = String.Offset.getQuantity();
22160 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22161 S->getCharByteWidth() == 1 &&
22162 // FIXME: Add fast-path for wchar_t too.
22163 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22164 Str = Str.substr(Off);
22165
22166 StringRef::size_type Pos = Str.find(0);
22167 if (Pos != StringRef::npos)
22168 Str = Str.substr(0, Pos);
22169
22170 if (StringResult)
22171 *StringResult = Str;
22172 return Str.size();
22173 }
22174
22175 // Fall through to slow path.
22176 }
22177
22178 // Slow path: scan the bytes of the string looking for the terminating 0.
22179 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22180 APValue Char;
22181 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22182 !Char.isInt())
22183 return std::nullopt;
22184 if (!Char.getInt())
22185 return Strlen;
22186 else if (StringResult)
22187 StringResult->push_back(Char.getInt().getExtValue());
22188 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22189 return std::nullopt;
22190 }
22191}
22192
22193std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22194 Expr::EvalStatus Status;
22195 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22196 std::string StringResult;
22197
22198 if (Info.EnableNewConstInterp) {
22199 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22200 return std::nullopt;
22201 return StringResult;
22202 }
22203
22204 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22205 return StringResult;
22206 return std::nullopt;
22207}
22208
22209template <typename T>
22210static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
22211 const Expr *SizeExpression,
22212 const Expr *PtrExpression,
22213 ASTContext &Ctx,
22214 Expr::EvalResult &Status) {
22215 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22216 Info.InConstantContext = true;
22217
22218 if (Info.EnableNewConstInterp)
22219 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22220 PtrExpression, Result);
22221
22222 LValue String;
22223 FullExpressionRAII Scope(Info);
22224 APSInt SizeValue;
22225 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22226 return false;
22227
22228 uint64_t Size = SizeValue.getZExtValue();
22229
22230 // FIXME: better protect against invalid or excessive sizes
22231 if constexpr (std::is_same_v<APValue, T>)
22232 Result = APValue(APValue::UninitArray{}, Size, Size);
22233 else {
22234 if (Size < Result.max_size())
22235 Result.reserve(Size);
22236 }
22237 if (!::EvaluatePointer(PtrExpression, String, Info))
22238 return false;
22239
22240 QualType CharTy = PtrExpression->getType()->getPointeeType();
22241 for (uint64_t I = 0; I < Size; ++I) {
22242 APValue Char;
22243 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22244 Char))
22245 return false;
22246
22247 if constexpr (std::is_same_v<APValue, T>) {
22248 Result.getArrayInitializedElt(I) = std::move(Char);
22249 } else {
22250 APSInt C = Char.getInt();
22251
22252 assert(C.getBitWidth() <= 8 &&
22253 "string element not representable in char");
22254
22255 Result.push_back(static_cast<char>(C.getExtValue()));
22256 }
22257
22258 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22259 return false;
22260 }
22261
22262 return Scope.destroy() && CheckMemoryLeaks(Info);
22263}
22264
22266 const Expr *SizeExpression,
22267 const Expr *PtrExpression, ASTContext &Ctx,
22268 EvalResult &Status) const {
22269 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22270 PtrExpression, Ctx, Status);
22271}
22272
22274 const Expr *SizeExpression,
22275 const Expr *PtrExpression, ASTContext &Ctx,
22276 EvalResult &Status) const {
22277 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22278 PtrExpression, Ctx, Status);
22279}
22280
22281std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22282 Expr::EvalStatus Status;
22283 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22284
22285 if (Info.EnableNewConstInterp)
22286 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22287 return EvaluateBuiltinStrLen(this, Info);
22288}
22289
22290namespace {
22291struct IsWithinLifetimeHandler {
22292 EvalInfo &Info;
22293 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22294 using result_type = std::optional<bool>;
22295 std::optional<bool> failed() { return std::nullopt; }
22296 template <typename T>
22297 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22298 return true;
22299 }
22300};
22301
22302std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22303 const CallExpr *E) {
22304 EvalInfo &Info = IEE.Info;
22305 // Sometimes this is called during some sorts of constant folding / early
22306 // evaluation. These are meant for non-constant expressions and are not
22307 // necessary since this consteval builtin will never be evaluated at runtime.
22308 // Just fail to evaluate when not in a constant context.
22309 if (!Info.InConstantContext)
22310 return std::nullopt;
22311 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22312 const Expr *Arg = E->getArg(0);
22313 if (Arg->isValueDependent())
22314 return std::nullopt;
22315 LValue Val;
22316 if (!EvaluatePointer(Arg, Val, Info))
22317 return std::nullopt;
22318
22319 if (Val.allowConstexprUnknown())
22320 return true;
22321
22322 auto Error = [&](int Diag) {
22323 bool CalledFromStd = false;
22324 const auto *Callee = Info.CurrentCall->getCallee();
22325 if (Callee && Callee->isInStdNamespace()) {
22326 const IdentifierInfo *Identifier = Callee->getIdentifier();
22327 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
22328 }
22329 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
22330 : E->getExprLoc(),
22331 diag::err_invalid_is_within_lifetime)
22332 << (CalledFromStd ? "std::is_within_lifetime"
22333 : "__builtin_is_within_lifetime")
22334 << Diag;
22335 return std::nullopt;
22336 };
22337 // C++2c [meta.const.eval]p4:
22338 // During the evaluation of an expression E as a core constant expression, a
22339 // call to this function is ill-formed unless p points to an object that is
22340 // usable in constant expressions or whose complete object's lifetime began
22341 // within E.
22342
22343 // Make sure it points to an object
22344 // nullptr does not point to an object
22345 if (Val.isNullPointer() || Val.getLValueBase().isNull())
22346 return Error(0);
22347 QualType T = Val.getLValueBase().getType();
22348 assert(!T->isFunctionType() &&
22349 "Pointers to functions should have been typed as function pointers "
22350 "which would have been rejected earlier");
22351 assert(T->isObjectType());
22352 // Hypothetical array element is not an object
22353 if (Val.getLValueDesignator().isOnePastTheEnd())
22354 return Error(1);
22355 assert(Val.getLValueDesignator().isValidSubobject() &&
22356 "Unchecked case for valid subobject");
22357 // All other ill-formed values should have failed EvaluatePointer, so the
22358 // object should be a pointer to an object that is usable in a constant
22359 // expression or whose complete lifetime began within the expression
22360 CompleteObject CO =
22361 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22362 // The lifetime hasn't begun yet if we are still evaluating the
22363 // initializer ([basic.life]p(1.2))
22364 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22365 return Error(2);
22366
22367 if (!CO)
22368 return false;
22369 IsWithinLifetimeHandler handler{Info};
22370 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22371}
22372} // 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:24
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 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)
std::optional< APFloat > EvalScalarMinMaxFp(const APFloat &A, const APFloat &B, std::optional< APSInt > RoundingMode, bool IsMin)
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 bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
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 std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
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)
static void expandVector(APValue &Vec, unsigned NumElements)
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)
static std::optional< uint64_t > EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info, std::string *StringResult=nullptr)
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 EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info)
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 bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
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...
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
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)
uint8_t GFNIMultiplicativeInverse(uint8_t Byte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
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.
llvm::json::Object Object
llvm::json::Array Array
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:208
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:222
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:634
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:482
APSInt & getInt()
Definition APValue.h:508
APValue & getStructField(unsigned i)
Definition APValue.h:667
unsigned getMatrixNumColumns() const
Definition APValue.h:599
const FieldDecl * getUnionField() const
Definition APValue.h:679
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isAbsent() const
Definition APValue.h:481
bool isComplexInt() const
Definition APValue.h:488
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:205
ValueKind getKind() const
Definition APValue.h:479
unsigned getArrayInitializedElts() const
Definition APValue.h:645
static APValue IndeterminateValue()
Definition APValue.h:450
bool isFloat() const
Definition APValue.h:486
APFixedPoint & getFixedPoint()
Definition APValue.h:530
bool hasValue() const
Definition APValue.h:483
bool hasLValuePath() const
Definition APValue.cpp:1030
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
APValue & getUnionValue()
Definition APValue.h:683
CharUnits & getLValueOffset()
Definition APValue.cpp:1025
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:717
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
APValue & getArrayFiller()
Definition APValue.h:637
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1091
bool isIndeterminate() const
Definition APValue.h:482
unsigned getMatrixNumRows() const
Definition APValue.h:595
bool isInt() const
Definition APValue.h:485
unsigned getArraySize() const
Definition APValue.h:649
bool allowConstexprUnknown() const
Definition APValue.h:329
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
bool isFixedPoint() const
Definition APValue.h:487
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
@ 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:494
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
APValue & getStructBase(unsigned i)
Definition APValue.h:662
bool isMatrix() const
Definition APValue.h:492
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
SourceManager & getSourceManager()
Definition ASTContext.h:859
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
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:851
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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:4576
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5986
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2753
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
QualType getElementType() const
Definition TypeBase.h:3784
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8230
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4456
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4510
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4494
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4491
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4174
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4188
SourceLocation getExprLoc() const
Definition Expr.h:4082
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4118
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4254
Opcode getOpcode() const
Definition Expr.h:4086
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4808
const BlockDecl * getBlockDecl() const
Definition Expr.h:6683
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) const
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:1519
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2624
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3051
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2710
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1107
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
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:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
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:2721
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:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2872
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2275
bool isInstance() const
Definition DeclCXX.h:2163
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2753
bool isStatic() const
Definition DeclCXX.cpp:2419
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2732
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2897
QualType getAllocatedType() const
Definition ExprCXX.h:2438
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:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
SourceRange getSourceRange() const
Definition ExprCXX.h:2614
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
bool getValue() const
Definition ExprCXX.h:4332
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
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:1679
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:1372
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:1790
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:2131
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
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:308
bool isImplicit() const
Definition ExprCXX.h:1181
bool isTypeOperand() const
Definition ExprCXX.h:888
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:899
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:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3592
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1592
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3239
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
Decl * getCalleeDecl()
Definition Expr.h:3123
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1603
CaseStmt - Represent a case statement.
Definition Stmt.h:1926
Expr * getLHS()
Definition Stmt.h:2009
Expr * getRHS()
Definition Stmt.h:2021
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
path_iterator path_begin()
Definition Expr.h:3749
unsigned path_size() const
Definition Expr.h:3748
CastKind getCastKind() const
Definition Expr.h:3723
path_iterator path_end()
Definition Expr.h:3750
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3746
bool path_empty() const
Definition Expr.h:3747
Expr * getSubExpr()
Definition Expr.h:3729
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3793
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:1632
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4887
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:3325
QualType getElementType() const
Definition TypeBase.h:3335
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4303
QualType getComputationLHSType() const
Definition Expr.h:4337
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
bool hasStaticStorage() const
Definition Expr.h:3653
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5684
bool isFileScope() const
Definition Expr.h:3640
const Expr * getInitializer() const
Definition Expr.h:3636
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1746
bool body_empty() const
Definition Stmt.h:1790
Stmt *const * const_body_iterator
Definition Stmt.h:1818
body_iterator body_end()
Definition Stmt.h:1811
body_range body()
Definition Stmt.h:1809
body_iterator body_begin()
Definition Stmt.h:1810
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4394
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4426
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4417
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4421
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3873
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:216
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:256
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:3899
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3880
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3906
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3886
APValue getAPValueResult() const
Definition Expr.cpp:413
bool hasAPValueResult() const
Definition Expr.h:1160
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4799
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4812
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
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:1273
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
ValueDecl * getDecl()
Definition Expr.h:1341
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1637
decl_range decls()
Definition Stmt.h:1685
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:450
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
A decomposition declaration.
Definition DeclCXX.h:4265
auto flat_bindings() const
Definition DeclCXX.h:4308
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2838
Stmt * getBody()
Definition Stmt.h:2863
Expr * getCond()
Definition Stmt.h:2856
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
const Expr * getBase() const
Definition Expr.h:6580
ChildElementIter< false > begin()
Definition Expr.h:5235
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
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:84
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:673
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:675
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:3095
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.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3989
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
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:3086
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...
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
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:3688
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:3253
Expr()=delete
ConstantExprKind
Definition Expr.h:752
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
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:4436
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4549
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4754
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3260
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3422
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:104
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1578
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2894
Stmt * getInit()
Definition Stmt.h:2909
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2938
Expr * getInc()
Definition Stmt.h:2937
Expr * getCond()
Definition Stmt.h:2936
const Expr * getSubExpr() const
Definition Expr.h:1065
Represents a function declaration or definition.
Definition Decl.h:2015
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3281
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4207
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4195
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3867
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2392
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4331
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2485
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:3428
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2400
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:3127
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:6467
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:2265
Stmt * getThen()
Definition Stmt.h:2354
Stmt * getInit()
Definition Stmt.h:2415
bool isNonNegatedConsteval() const
Definition Stmt.h:2450
Expr * getCond()
Definition Stmt.h:2342
Stmt * getElse()
Definition Stmt.h:2363
bool isConsteval() const
Definition Stmt.h:2445
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1746
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3482
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3503
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2462
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2448
unsigned getNumInits() const
Definition Expr.h:5332
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5404
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
ArrayRef< Expr * > inits()
Definition Expr.h:5352
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2110
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1402
@ 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:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4953
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
bool isArrow() const
Definition Expr.h:3551
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:1688
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2589
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2570
unsigned getNumComponents() const
Definition Expr.h:2585
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2482
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2488
@ Array
An index into an array.
Definition Expr.h:2429
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2433
@ Field
A field.
Definition Expr.h:2431
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2436
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2478
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2498
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1231
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2202
Represents a parameter to a function.
Definition Decl.h:1805
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1865
bool isExplicitObjectParameter() const
Definition Decl.h:1893
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
StringLiteral * getFunctionName()
Definition Expr.h:2052
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6851
ArrayRef< Expr * > semantics()
Definition Expr.h:6875
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2914
QualType withConst() const
Definition TypeBase.h:1165
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
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:8431
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:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
void removeLocalVolatile()
Definition TypeBase.h:8547
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1170
void removeLocalConst()
Definition TypeBase.h:8539
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3004
Represents a struct/union/class.
Definition Decl.h:4342
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4558
field_iterator field_end() const
Definition Decl.h:4548
field_range fields() const
Definition Decl.h:4545
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4542
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4394
bool field_empty() const
Definition Decl.h:4553
field_iterator field_begin() const
Definition Decl.cpp:5277
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2158
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:587
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:4646
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4698
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4679
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4685
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
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:2282
bool isIntType() const
Definition Expr.h:5044
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:4615
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
StmtClass getStmtClass() const
Definition Stmt.h:1499
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1878
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
unsigned getCharByteWidth() const
Definition Expr.h:1913
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1899
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2515
Expr * getCond()
Definition Stmt.h:2578
Stmt * getBody()
Definition Stmt.h:2590
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2595
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2646
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4901
bool isUnion() const
Definition Decl.h:3943
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:8413
bool getBoolValue() const
Definition ExprCXX.h:2951
const APValue & getAPValue() const
Definition ExprCXX.h:2956
bool isStoredAsBoolean() const
Definition ExprCXX.h:2947
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isFunctionReferenceType() const
Definition TypeBase.h:8742
bool isMFloat8Type() const
Definition TypeBase.h:9059
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:420
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3061
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:726
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9337
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
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:8771
bool isNothrowT() const
Definition Type.cpp:3245
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:714
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isConstantMatrixType() const
Definition TypeBase.h:8835
bool isPointerType() const
Definition TypeBase.h:8668
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
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:1923
bool isVariableArrayType() const
Definition TypeBase.h:8779
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2654
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
bool isMemberDataPointerType() const
Definition TypeBase.h:8760
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9003
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isAtomicType() const
Definition TypeBase.h:8860
bool isComplexIntegerType() const
Definition Type.cpp:732
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
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:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isVectorType() const
Definition TypeBase.h:8807
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isFloatingType() const
Definition Type.cpp:2342
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:2285
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2978
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isUnionType() const
Definition Type.cpp:720
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2616
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9205
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
QualType getArgumentType() const
Definition Expr.h:2671
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2707
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2697
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2660
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
SourceLocation getExprLoc() const
Definition Expr.h:2371
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2329
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2301
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:5583
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:1584
bool hasInit() const
Definition Decl.cpp:2411
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2649
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1593
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2588
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2890
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2661
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2379
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:2499
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2570
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:1383
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:2641
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:2388
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1268
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:2541
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1373
Expr * getSizeExpr() const
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2703
Expr * getCond()
Definition Stmt.h:2755
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2767
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:81
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:1424
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:56
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3111
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:3799
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:351
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1045
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:206
@ AS_public
Definition Specifiers.h:125
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:237
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:44
@ CSK_ArrayToPointer
Definition State.h:48
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Real
Definition State.h:50
@ CSK_ArrayIndex
Definition State.h:49
@ CSK_Imag
Definition State.h:51
@ CSK_VectorElement
Definition State.h:52
@ CSK_Field
Definition State.h:47
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
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:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_IsWithinLifetime
Definition State.h:39
@ AK_MemberCall
Definition State.h:34
@ AK_ReadObjectRepresentation
Definition State.h:30
@ AK_Dereference
Definition State.h:40
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
@ Type
The name was classified as a type.
Definition Sema.h:564
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:136
EvaluationMode
Definition State.h:55
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1761
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::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:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:612
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:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165