clang 22.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind");
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind");
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 // The type of Base is a reference type if the base is a constexpr-unknown
200 // variable. In that case, look through the reference type.
201 Type = getType(Base).getNonReferenceType();
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getZExtSize();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const auto *VT = Type->getAs<VectorType>()) {
224 Type = VT->getElementType();
225 ArraySize = VT->getNumElements();
226 MostDerivedLength = I + 1;
227 IsArray = true;
228 } else if (const FieldDecl *FD = getAsField(Path[I])) {
229 Type = FD->getType();
230 ArraySize = 0;
231 MostDerivedLength = I + 1;
232 IsArray = false;
233 } else {
234 // Path[I] describes a base class.
235 ArraySize = 0;
236 IsArray = false;
237 }
238 }
239 return MostDerivedLength;
240 }
241
242 /// A path from a glvalue to a subobject of that glvalue.
243 struct SubobjectDesignator {
244 /// True if the subobject was named in a manner not supported by C++11. Such
245 /// lvalues can still be folded, but they are not core constant expressions
246 /// and we cannot perform lvalue-to-rvalue conversions on them.
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned Invalid : 1;
249
250 /// Is this a pointer one past the end of an object?
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned IsOnePastTheEnd : 1;
253
254 /// Indicator of whether the first entry is an unsized array.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned FirstEntryIsAnUnsizedArray : 1;
257
258 /// Indicator of whether the most-derived object is an array element.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned MostDerivedIsArrayElement : 1;
261
262 /// The length of the path to the most-derived object of which this is a
263 /// subobject.
264 unsigned MostDerivedPathLength : 28;
265
266 /// The size of the array of which the most-derived object is an element.
267 /// This will always be 0 if the most-derived object is not an array
268 /// element. 0 is not an indicator of whether or not the most-derived object
269 /// is an array, however, because 0-length arrays are allowed.
270 ///
271 /// If the current array is an unsized array, the value of this is
272 /// undefined.
273 uint64_t MostDerivedArraySize;
274 /// The type of the most derived object referred to by this address.
275 QualType MostDerivedType;
276
277 typedef APValue::LValuePathEntry PathEntry;
278
279 /// The entries on the path from the glvalue to the designated subobject.
281
282 SubobjectDesignator() : Invalid(true) {}
283
284 explicit SubobjectDesignator(QualType T)
285 : Invalid(false), IsOnePastTheEnd(false),
286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287 MostDerivedPathLength(0), MostDerivedArraySize(0),
288 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
289
290 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
291 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
292 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
293 MostDerivedPathLength(0), MostDerivedArraySize(0) {
294 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
295 if (!Invalid) {
296 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
297 llvm::append_range(Entries, V.getLValuePath());
298 if (V.getLValueBase()) {
299 bool IsArray = false;
300 bool FirstIsUnsizedArray = false;
301 MostDerivedPathLength = findMostDerivedSubobject(
302 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
303 MostDerivedType, IsArray, FirstIsUnsizedArray);
304 MostDerivedIsArrayElement = IsArray;
305 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
306 }
307 }
308 }
309
310 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
311 unsigned NewLength) {
312 if (Invalid)
313 return;
314
315 assert(Base && "cannot truncate path for null pointer");
316 assert(NewLength <= Entries.size() && "not a truncation");
317
318 if (NewLength == Entries.size())
319 return;
320 Entries.resize(NewLength);
321
322 bool IsArray = false;
323 bool FirstIsUnsizedArray = false;
324 MostDerivedPathLength = findMostDerivedSubobject(
325 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
326 FirstIsUnsizedArray);
327 MostDerivedIsArrayElement = IsArray;
328 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
329 }
330
331 void setInvalid() {
332 Invalid = true;
333 Entries.clear();
334 }
335
336 /// Determine whether the most derived subobject is an array without a
337 /// known bound.
338 bool isMostDerivedAnUnsizedArray() const {
339 assert(!Invalid && "Calling this makes no sense on invalid designators");
340 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
341 }
342
343 /// Determine what the most derived array's size is. Results in an assertion
344 /// failure if the most derived array lacks a size.
345 uint64_t getMostDerivedArraySize() const {
346 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
347 return MostDerivedArraySize;
348 }
349
350 /// Determine whether this is a one-past-the-end pointer.
351 bool isOnePastTheEnd() const {
352 assert(!Invalid);
353 if (IsOnePastTheEnd)
354 return true;
355 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
356 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
357 MostDerivedArraySize)
358 return true;
359 return false;
360 }
361
362 /// Get the range of valid index adjustments in the form
363 /// {maximum value that can be subtracted from this pointer,
364 /// maximum value that can be added to this pointer}
365 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
366 if (Invalid || isMostDerivedAnUnsizedArray())
367 return {0, 0};
368
369 // [expr.add]p4: For the purposes of these operators, a pointer to a
370 // nonarray object behaves the same as a pointer to the first element of
371 // an array of length one with the type of the object as its element type.
372 bool IsArray = MostDerivedPathLength == Entries.size() &&
373 MostDerivedIsArrayElement;
374 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
375 : (uint64_t)IsOnePastTheEnd;
376 uint64_t ArraySize =
377 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
378 return {ArrayIndex, ArraySize - ArrayIndex};
379 }
380
381 /// Check that this refers to a valid subobject.
382 bool isValidSubobject() const {
383 if (Invalid)
384 return false;
385 return !isOnePastTheEnd();
386 }
387 /// Check that this refers to a valid subobject, and if not, produce a
388 /// relevant diagnostic and set the designator as invalid.
389 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
390
391 /// Get the type of the designated object.
392 QualType getType(ASTContext &Ctx) const {
393 assert(!Invalid && "invalid designator has no subobject type");
394 return MostDerivedPathLength == Entries.size()
395 ? MostDerivedType
396 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
397 }
398
399 /// Update this designator to refer to the first element within this array.
400 void addArrayUnchecked(const ConstantArrayType *CAT) {
401 Entries.push_back(PathEntry::ArrayIndex(0));
402
403 // This is a most-derived object.
404 MostDerivedType = CAT->getElementType();
405 MostDerivedIsArrayElement = true;
406 MostDerivedArraySize = CAT->getZExtSize();
407 MostDerivedPathLength = Entries.size();
408 }
409 /// Update this designator to refer to the first element within the array of
410 /// elements of type T. This is an array of unknown size.
411 void addUnsizedArrayUnchecked(QualType ElemTy) {
412 Entries.push_back(PathEntry::ArrayIndex(0));
413
414 MostDerivedType = ElemTy;
415 MostDerivedIsArrayElement = true;
416 // The value in MostDerivedArraySize is undefined in this case. So, set it
417 // to an arbitrary value that's likely to loudly break things if it's
418 // used.
419 MostDerivedArraySize = AssumedSizeForUnsizedArray;
420 MostDerivedPathLength = Entries.size();
421 }
422 /// Update this designator to refer to the given base or member of this
423 /// object.
424 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
425 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
426
427 // If this isn't a base class, it's a new most-derived object.
428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
429 MostDerivedType = FD->getType();
430 MostDerivedIsArrayElement = false;
431 MostDerivedArraySize = 0;
432 MostDerivedPathLength = Entries.size();
433 }
434 }
435 /// Update this designator to refer to the given complex component.
436 void addComplexUnchecked(QualType EltTy, bool Imag) {
437 Entries.push_back(PathEntry::ArrayIndex(Imag));
438
439 // This is technically a most-derived object, though in practice this
440 // is unlikely to matter.
441 MostDerivedType = EltTy;
442 MostDerivedIsArrayElement = true;
443 MostDerivedArraySize = 2;
444 MostDerivedPathLength = Entries.size();
445 }
446
447 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
448 uint64_t Idx) {
449 Entries.push_back(PathEntry::ArrayIndex(Idx));
450 MostDerivedType = EltTy;
451 MostDerivedPathLength = Entries.size();
452 MostDerivedArraySize = 0;
453 MostDerivedIsArrayElement = false;
454 }
455
456 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
457 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
458 const APSInt &N);
459 /// Add N to the address of this subobject.
460 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
461 };
462
463 /// A scope at the end of which an object can need to be destroyed.
464 enum class ScopeKind {
465 Block,
466 FullExpression,
467 Call
468 };
469
470 /// A reference to a particular call and its arguments.
471 struct CallRef {
472 CallRef() : OrigCallee(), CallIndex(0), Version() {}
473 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
474 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
475
476 explicit operator bool() const { return OrigCallee; }
477
478 /// Get the parameter that the caller initialized, corresponding to the
479 /// given parameter in the callee.
480 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
481 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
482 : PVD;
483 }
484
485 /// The callee at the point where the arguments were evaluated. This might
486 /// be different from the actual callee (a different redeclaration, or a
487 /// virtual override), but this function's parameters are the ones that
488 /// appear in the parameter map.
489 const FunctionDecl *OrigCallee;
490 /// The call index of the frame that holds the argument values.
491 unsigned CallIndex;
492 /// The version of the parameters corresponding to this call.
493 unsigned Version;
494 };
495
496 /// A stack frame in the constexpr call stack.
497 class CallStackFrame : public interp::Frame {
498 public:
499 EvalInfo &Info;
500
501 /// Parent - The caller of this stack frame.
502 CallStackFrame *Caller;
503
504 /// Callee - The function which was called.
505 const FunctionDecl *Callee;
506
507 /// This - The binding for the this pointer in this call, if any.
508 const LValue *This;
509
510 /// CallExpr - The syntactical structure of member function calls
511 const Expr *CallExpr;
512
513 /// Information on how to find the arguments to this call. Our arguments
514 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
515 /// key and this value as the version.
516 CallRef Arguments;
517
518 /// Source location information about the default argument or default
519 /// initializer expression we're evaluating, if any.
520 CurrentSourceLocExprScope CurSourceLocExprScope;
521
522 // Note that we intentionally use std::map here so that references to
523 // values are stable.
524 typedef std::pair<const void *, unsigned> MapKeyTy;
525 typedef std::map<MapKeyTy, APValue> MapTy;
526 /// Temporaries - Temporary lvalues materialized within this stack frame.
527 MapTy Temporaries;
528
529 /// CallRange - The source range of the call expression for this call.
530 SourceRange CallRange;
531
532 /// Index - The call index of this call.
533 unsigned Index;
534
535 /// The stack of integers for tracking version numbers for temporaries.
536 SmallVector<unsigned, 2> TempVersionStack = {1};
537 unsigned CurTempVersion = TempVersionStack.back();
538
539 unsigned getTempVersion() const { return TempVersionStack.back(); }
540
541 void pushTempVersion() {
542 TempVersionStack.push_back(++CurTempVersion);
543 }
544
545 void popTempVersion() {
546 TempVersionStack.pop_back();
547 }
548
549 CallRef createCall(const FunctionDecl *Callee) {
550 return {Callee, Index, ++CurTempVersion};
551 }
552
553 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
554 // on the overall stack usage of deeply-recursing constexpr evaluations.
555 // (We should cache this map rather than recomputing it repeatedly.)
556 // But let's try this and see how it goes; we can look into caching the map
557 // as a later change.
558
559 /// LambdaCaptureFields - Mapping from captured variables/this to
560 /// corresponding data members in the closure class.
561 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
562 FieldDecl *LambdaThisCaptureField = nullptr;
563
564 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
565 const FunctionDecl *Callee, const LValue *This,
566 const Expr *CallExpr, CallRef Arguments);
567 ~CallStackFrame();
568
569 // Return the temporary for Key whose version number is Version.
570 APValue *getTemporary(const void *Key, unsigned Version) {
571 MapKeyTy KV(Key, Version);
572 auto LB = Temporaries.lower_bound(KV);
573 if (LB != Temporaries.end() && LB->first == KV)
574 return &LB->second;
575 return nullptr;
576 }
577
578 // Return the current temporary for Key in the map.
579 APValue *getCurrentTemporary(const void *Key) {
580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582 return &std::prev(UB)->second;
583 return nullptr;
584 }
585
586 // Return the version number of the current temporary for Key.
587 unsigned getCurrentTemporaryVersion(const void *Key) const {
588 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
589 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
590 return std::prev(UB)->first.second;
591 return 0;
592 }
593
594 /// Allocate storage for an object of type T in this stack frame.
595 /// Populates LV with a handle to the created object. Key identifies
596 /// the temporary within the stack frame, and must not be reused without
597 /// bumping the temporary version number.
598 template<typename KeyT>
599 APValue &createTemporary(const KeyT *Key, QualType T,
600 ScopeKind Scope, LValue &LV);
601
602 /// Allocate storage for a parameter of a function call made in this frame.
603 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
604
605 void describe(llvm::raw_ostream &OS) const override;
606
607 Frame *getCaller() const override { return Caller; }
608 SourceRange getCallRange() const override { return CallRange; }
609 const FunctionDecl *getCallee() const override { return Callee; }
610
611 bool isStdFunction() const {
612 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
613 if (DC->isStdNamespace())
614 return true;
615 return false;
616 }
617
618 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
619 /// permitted. See MSConstexprDocs for description of permitted contexts.
620 bool CanEvalMSConstexpr = false;
621
622 private:
623 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
624 ScopeKind Scope);
625 };
626
627 /// Temporarily override 'this'.
628 class ThisOverrideRAII {
629 public:
630 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
631 : Frame(Frame), OldThis(Frame.This) {
632 if (Enable)
633 Frame.This = NewThis;
634 }
635 ~ThisOverrideRAII() {
636 Frame.This = OldThis;
637 }
638 private:
639 CallStackFrame &Frame;
640 const LValue *OldThis;
641 };
642
643 // A shorthand time trace scope struct, prints source range, for example
644 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
645 class ExprTimeTraceScope {
646 public:
647 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
648 : TimeScope(Name, [E, &Ctx] {
650 }) {}
651
652 private:
653 llvm::TimeTraceScope TimeScope;
654 };
655
656 /// RAII object used to change the current ability of
657 /// [[msvc::constexpr]] evaulation.
658 struct MSConstexprContextRAII {
659 CallStackFrame &Frame;
660 bool OldValue;
661 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
662 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
663 Frame.CanEvalMSConstexpr = Value;
664 }
665
666 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
667 };
668}
669
670static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
674 QualType T);
675
676namespace {
677 /// A cleanup, and a flag indicating whether it is lifetime-extended.
678 class Cleanup {
679 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 APValue::LValueBase Base;
681 QualType T;
682
683 public:
684 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
685 ScopeKind Scope)
686 : Value(Val, Scope), Base(Base), T(T) {}
687
688 /// Determine whether this cleanup should be performed at the end of the
689 /// given kind of scope.
690 bool isDestroyedAtEndOf(ScopeKind K) const {
691 return (int)Value.getInt() >= (int)K;
692 }
693 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
694 if (RunDestructors) {
695 SourceLocation Loc;
696 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
697 Loc = VD->getLocation();
698 else if (const Expr *E = Base.dyn_cast<const Expr*>())
699 Loc = E->getExprLoc();
700 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
701 }
702 *Value.getPointer() = APValue();
703 return true;
704 }
705
706 bool hasSideEffect() {
707 return T.isDestructedType();
708 }
709 };
710
711 /// A reference to an object whose construction we are currently evaluating.
712 struct ObjectUnderConstruction {
713 APValue::LValueBase Base;
714 ArrayRef<APValue::LValuePathEntry> Path;
715 friend bool operator==(const ObjectUnderConstruction &LHS,
716 const ObjectUnderConstruction &RHS) {
717 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
718 }
719 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
720 return llvm::hash_combine(Obj.Base, Obj.Path);
721 }
722 };
723 enum class ConstructionPhase {
724 None,
725 Bases,
726 AfterBases,
727 AfterFields,
728 Destroying,
729 DestroyingBases
730 };
731}
732
733namespace llvm {
734template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748};
749}
750
751namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo : public interp::State {
798 public:
799 ASTContext &Ctx;
800
801 /// EvalStatus - Contains information about the evaluation.
802 Expr::EvalStatus &EvalStatus;
803
804 /// CurrentCall - The top of the constexpr call stack.
805 CallStackFrame *CurrentCall;
806
807 /// CallStackDepth - The number of calls in the call stack right now.
808 unsigned CallStackDepth;
809
810 /// NextCallIndex - The next call index to assign.
811 unsigned NextCallIndex;
812
813 /// StepsLeft - The remaining number of evaluation steps we're permitted
814 /// to perform. This is essentially a limit for the number of statements
815 /// we will evaluate.
816 unsigned StepsLeft;
817
818 /// Enable the experimental new constant interpreter. If an expression is
819 /// not supported by the interpreter, an error is triggered.
820 bool EnableNewConstInterp;
821
822 /// BottomFrame - The frame in which evaluation started. This must be
823 /// initialized after CurrentCall and CallStackDepth.
824 CallStackFrame BottomFrame;
825
826 /// A stack of values whose lifetimes end at the end of some surrounding
827 /// evaluation frame.
828 llvm::SmallVector<Cleanup, 16> CleanupStack;
829
830 /// EvaluatingDecl - This is the declaration whose initializer is being
831 /// evaluated, if any.
832 APValue::LValueBase EvaluatingDecl;
833
834 enum class EvaluatingDeclKind {
835 None,
836 /// We're evaluating the construction of EvaluatingDecl.
837 Ctor,
838 /// We're evaluating the destruction of EvaluatingDecl.
839 Dtor,
840 };
841 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
842
843 /// EvaluatingDeclValue - This is the value being constructed for the
844 /// declaration whose initializer is being evaluated, if any.
845 APValue *EvaluatingDeclValue;
846
847 /// Stack of loops and 'switch' statements which we're currently
848 /// breaking/continuing; null entries are used to mark unlabeled
849 /// break/continue.
850 SmallVector<const Stmt *> BreakContinueStack;
851
852 /// Set of objects that are currently being constructed.
853 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
854 ObjectsUnderConstruction;
855
856 /// Current heap allocations, along with the location where each was
857 /// allocated. We use std::map here because we need stable addresses
858 /// for the stored APValues.
859 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
860
861 /// The number of heap allocations performed so far in this evaluation.
862 unsigned NumHeapAllocs = 0;
863
864 struct EvaluatingConstructorRAII {
865 EvalInfo &EI;
866 ObjectUnderConstruction Object;
867 bool DidInsert;
868 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
869 bool HasBases)
870 : EI(EI), Object(Object) {
871 DidInsert =
872 EI.ObjectsUnderConstruction
873 .insert({Object, HasBases ? ConstructionPhase::Bases
874 : ConstructionPhase::AfterBases})
875 .second;
876 }
877 void finishedConstructingBases() {
878 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
879 }
880 void finishedConstructingFields() {
881 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
882 }
883 ~EvaluatingConstructorRAII() {
884 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
885 }
886 };
887
888 struct EvaluatingDestructorRAII {
889 EvalInfo &EI;
890 ObjectUnderConstruction Object;
891 bool DidInsert;
892 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
893 : EI(EI), Object(Object) {
894 DidInsert = EI.ObjectsUnderConstruction
895 .insert({Object, ConstructionPhase::Destroying})
896 .second;
897 }
898 void startedDestroyingBases() {
899 EI.ObjectsUnderConstruction[Object] =
900 ConstructionPhase::DestroyingBases;
901 }
902 ~EvaluatingDestructorRAII() {
903 if (DidInsert)
904 EI.ObjectsUnderConstruction.erase(Object);
905 }
906 };
907
908 ConstructionPhase
909 isEvaluatingCtorDtor(APValue::LValueBase Base,
910 ArrayRef<APValue::LValuePathEntry> Path) {
911 return ObjectsUnderConstruction.lookup({Base, Path});
912 }
913
914 /// If we're currently speculatively evaluating, the outermost call stack
915 /// depth at which we can mutate state, otherwise 0.
916 unsigned SpeculativeEvaluationDepth = 0;
917
918 /// The current array initialization index, if we're performing array
919 /// initialization.
920 uint64_t ArrayInitIndex = -1;
921
922 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
923 /// notes attached to it will also be stored, otherwise they will not be.
924 bool HasActiveDiagnostic;
925
926 /// Have we emitted a diagnostic explaining why we couldn't constant
927 /// fold (not just why it's not strictly a constant expression)?
928 bool HasFoldFailureDiagnostic;
929
930 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
931 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
932 CallStackDepth(0), NextCallIndex(1),
933 StepsLeft(C.getLangOpts().ConstexprStepLimit),
934 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
935 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
936 /*This=*/nullptr,
937 /*CallExpr=*/nullptr, CallRef()),
938 EvaluatingDecl((const ValueDecl *)nullptr),
939 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
940 HasFoldFailureDiagnostic(false) {
941 EvalMode = Mode;
942 }
943
944 ~EvalInfo() {
945 discardCleanups();
946 }
947
948 ASTContext &getASTContext() const override { return Ctx; }
949 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
950
951 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
952 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
953 EvaluatingDecl = Base;
954 IsEvaluatingDecl = EDK;
955 EvaluatingDeclValue = &Value;
956 }
957
958 bool CheckCallLimit(SourceLocation Loc) {
959 // Don't perform any constexpr calls (other than the call we're checking)
960 // when checking a potential constant expression.
961 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
962 return false;
963 if (NextCallIndex == 0) {
964 // NextCallIndex has wrapped around.
965 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
966 return false;
967 }
968 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
969 return true;
970 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
971 << getLangOpts().ConstexprCallDepth;
972 return false;
973 }
974
975 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
976 uint64_t ElemCount, bool Diag) {
977 // FIXME: GH63562
978 // APValue stores array extents as unsigned,
979 // so anything that is greater that unsigned would overflow when
980 // constructing the array, we catch this here.
981 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
982 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
983 if (Diag)
984 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
985 return false;
986 }
987
988 // FIXME: GH63562
989 // Arrays allocate an APValue per element.
990 // We use the number of constexpr steps as a proxy for the maximum size
991 // of arrays to avoid exhausting the system resources, as initialization
992 // of each element is likely to take some number of steps anyway.
993 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
994 if (Limit != 0 && ElemCount > Limit) {
995 if (Diag)
996 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
997 << ElemCount << Limit;
998 return false;
999 }
1000 return true;
1001 }
1002
1003 std::pair<CallStackFrame *, unsigned>
1004 getCallFrameAndDepth(unsigned CallIndex) {
1005 assert(CallIndex && "no call index in getCallFrameAndDepth");
1006 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1007 // be null in this loop.
1008 unsigned Depth = CallStackDepth;
1009 CallStackFrame *Frame = CurrentCall;
1010 while (Frame->Index > CallIndex) {
1011 Frame = Frame->Caller;
1012 --Depth;
1013 }
1014 if (Frame->Index == CallIndex)
1015 return {Frame, Depth};
1016 return {nullptr, 0};
1017 }
1018
1019 bool nextStep(const Stmt *S) {
1020 if (Ctx.getLangOpts().ConstexprStepLimit == 0)
1021 return true;
1022
1023 if (!StepsLeft) {
1024 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1025 return false;
1026 }
1027 --StepsLeft;
1028 return true;
1029 }
1030
1031 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1032
1033 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1034 std::optional<DynAlloc *> Result;
1035 auto It = HeapAllocs.find(DA);
1036 if (It != HeapAllocs.end())
1037 Result = &It->second;
1038 return Result;
1039 }
1040
1041 /// Get the allocated storage for the given parameter of the given call.
1042 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1043 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1044 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1045 : nullptr;
1046 }
1047
1048 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1049 struct StdAllocatorCaller {
1050 unsigned FrameIndex;
1051 QualType ElemType;
1052 const Expr *Call;
1053 explicit operator bool() const { return FrameIndex != 0; };
1054 };
1055
1056 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1057 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1058 Call = Call->Caller) {
1059 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1060 if (!MD)
1061 continue;
1062 const IdentifierInfo *FnII = MD->getIdentifier();
1063 if (!FnII || !FnII->isStr(FnName))
1064 continue;
1065
1066 const auto *CTSD =
1067 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1068 if (!CTSD)
1069 continue;
1070
1071 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1072 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1073 if (CTSD->isInStdNamespace() && ClassII &&
1074 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1075 TAL[0].getKind() == TemplateArgument::Type)
1076 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1077 }
1078
1079 return {};
1080 }
1081
1082 void performLifetimeExtension() {
1083 // Disable the cleanups for lifetime-extended temporaries.
1084 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1085 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1086 });
1087 }
1088
1089 /// Throw away any remaining cleanups at the end of evaluation. If any
1090 /// cleanups would have had a side-effect, note that as an unmodeled
1091 /// side-effect and return false. Otherwise, return true.
1092 bool discardCleanups() {
1093 for (Cleanup &C : CleanupStack) {
1094 if (C.hasSideEffect() && !noteSideEffect()) {
1095 CleanupStack.clear();
1096 return false;
1097 }
1098 }
1099 CleanupStack.clear();
1100 return true;
1101 }
1102
1103 private:
1104 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1105 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1106
1107 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1108 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1109
1110 void setFoldFailureDiagnostic(bool Flag) override {
1111 HasFoldFailureDiagnostic = Flag;
1112 }
1113
1114 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1115
1116 // If we have a prior diagnostic, it will be noting that the expression
1117 // isn't a constant expression. This diagnostic is more important,
1118 // unless we require this evaluation to produce a constant expression.
1119 //
1120 // FIXME: We might want to show both diagnostics to the user in
1121 // EvaluationMode::ConstantFold mode.
1122 bool hasPriorDiagnostic() override {
1123 if (!EvalStatus.Diag->empty()) {
1124 switch (EvalMode) {
1125 case EvaluationMode::ConstantFold:
1126 case EvaluationMode::IgnoreSideEffects:
1127 if (!HasFoldFailureDiagnostic)
1128 break;
1129 // We've already failed to fold something. Keep that diagnostic.
1130 [[fallthrough]];
1131 case EvaluationMode::ConstantExpression:
1132 case EvaluationMode::ConstantExpressionUnevaluated:
1133 setActiveDiagnostic(false);
1134 return true;
1135 }
1136 }
1137 return false;
1138 }
1139
1140 unsigned getCallStackDepth() override { return CallStackDepth; }
1141
1142 public:
1143 /// Should we continue evaluation after encountering a side-effect that we
1144 /// couldn't model?
1145 bool keepEvaluatingAfterSideEffect() const override {
1146 switch (EvalMode) {
1147 case EvaluationMode::IgnoreSideEffects:
1148 return true;
1149
1150 case EvaluationMode::ConstantExpression:
1151 case EvaluationMode::ConstantExpressionUnevaluated:
1152 case EvaluationMode::ConstantFold:
1153 // By default, assume any side effect might be valid in some other
1154 // evaluation of this expression from a different context.
1155 return checkingPotentialConstantExpression() ||
1156 checkingForUndefinedBehavior();
1157 }
1158 llvm_unreachable("Missed EvalMode case");
1159 }
1160
1161 /// Note that we have had a side-effect, and determine whether we should
1162 /// keep evaluating.
1163 bool noteSideEffect() override {
1164 EvalStatus.HasSideEffects = true;
1165 return keepEvaluatingAfterSideEffect();
1166 }
1167
1168 /// Should we continue evaluation after encountering undefined behavior?
1169 bool keepEvaluatingAfterUndefinedBehavior() {
1170 switch (EvalMode) {
1171 case EvaluationMode::IgnoreSideEffects:
1172 case EvaluationMode::ConstantFold:
1173 return true;
1174
1175 case EvaluationMode::ConstantExpression:
1176 case EvaluationMode::ConstantExpressionUnevaluated:
1177 return checkingForUndefinedBehavior();
1178 }
1179 llvm_unreachable("Missed EvalMode case");
1180 }
1181
1182 /// Note that we hit something that was technically undefined behavior, but
1183 /// that we can evaluate past it (such as signed overflow or floating-point
1184 /// division by zero.)
1185 bool noteUndefinedBehavior() override {
1186 EvalStatus.HasUndefinedBehavior = true;
1187 return keepEvaluatingAfterUndefinedBehavior();
1188 }
1189
1190 /// Should we continue evaluation as much as possible after encountering a
1191 /// construct which can't be reduced to a value?
1192 bool keepEvaluatingAfterFailure() const override {
1193 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1194 if (Limit != 0 && !StepsLeft)
1195 return false;
1196
1197 switch (EvalMode) {
1198 case EvaluationMode::ConstantExpression:
1199 case EvaluationMode::ConstantExpressionUnevaluated:
1200 case EvaluationMode::ConstantFold:
1201 case EvaluationMode::IgnoreSideEffects:
1202 return checkingPotentialConstantExpression() ||
1203 checkingForUndefinedBehavior();
1204 }
1205 llvm_unreachable("Missed EvalMode case");
1206 }
1207
1208 /// Notes that we failed to evaluate an expression that other expressions
1209 /// directly depend on, and determine if we should keep evaluating. This
1210 /// should only be called if we actually intend to keep evaluating.
1211 ///
1212 /// Call noteSideEffect() instead if we may be able to ignore the value that
1213 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1214 ///
1215 /// (Foo(), 1) // use noteSideEffect
1216 /// (Foo() || true) // use noteSideEffect
1217 /// Foo() + 1 // use noteFailure
1218 [[nodiscard]] bool noteFailure() {
1219 // Failure when evaluating some expression often means there is some
1220 // subexpression whose evaluation was skipped. Therefore, (because we
1221 // don't track whether we skipped an expression when unwinding after an
1222 // evaluation failure) every evaluation failure that bubbles up from a
1223 // subexpression implies that a side-effect has potentially happened. We
1224 // skip setting the HasSideEffects flag to true until we decide to
1225 // continue evaluating after that point, which happens here.
1226 bool KeepGoing = keepEvaluatingAfterFailure();
1227 EvalStatus.HasSideEffects |= KeepGoing;
1228 return KeepGoing;
1229 }
1230
1231 class ArrayInitLoopIndex {
1232 EvalInfo &Info;
1233 uint64_t OuterIndex;
1234
1235 public:
1236 ArrayInitLoopIndex(EvalInfo &Info)
1237 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1238 Info.ArrayInitIndex = 0;
1239 }
1240 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1241
1242 operator uint64_t&() { return Info.ArrayInitIndex; }
1243 };
1244 };
1245
1246 /// Object used to treat all foldable expressions as constant expressions.
1247 struct FoldConstant {
1248 EvalInfo &Info;
1249 bool Enabled;
1250 bool HadNoPriorDiags;
1251 EvaluationMode OldMode;
1252
1253 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1254 : Info(Info),
1255 Enabled(Enabled),
1256 HadNoPriorDiags(Info.EvalStatus.Diag &&
1257 Info.EvalStatus.Diag->empty() &&
1258 !Info.EvalStatus.HasSideEffects),
1259 OldMode(Info.EvalMode) {
1260 if (Enabled)
1261 Info.EvalMode = EvaluationMode::ConstantFold;
1262 }
1263 void keepDiagnostics() { Enabled = false; }
1264 ~FoldConstant() {
1265 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1266 !Info.EvalStatus.HasSideEffects)
1267 Info.EvalStatus.Diag->clear();
1268 Info.EvalMode = OldMode;
1269 }
1270 };
1271
1272 /// RAII object used to set the current evaluation mode to ignore
1273 /// side-effects.
1274 struct IgnoreSideEffectsRAII {
1275 EvalInfo &Info;
1276 EvaluationMode OldMode;
1277 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1278 : Info(Info), OldMode(Info.EvalMode) {
1279 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1280 }
1281
1282 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1283 };
1284
1285 /// RAII object used to optionally suppress diagnostics and side-effects from
1286 /// a speculative evaluation.
1287 class SpeculativeEvaluationRAII {
1288 EvalInfo *Info = nullptr;
1289 Expr::EvalStatus OldStatus;
1290 unsigned OldSpeculativeEvaluationDepth = 0;
1291
1292 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1293 Info = Other.Info;
1294 OldStatus = Other.OldStatus;
1295 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1296 Other.Info = nullptr;
1297 }
1298
1299 void maybeRestoreState() {
1300 if (!Info)
1301 return;
1302
1303 Info->EvalStatus = OldStatus;
1304 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1305 }
1306
1307 public:
1308 SpeculativeEvaluationRAII() = default;
1309
1310 SpeculativeEvaluationRAII(
1311 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1312 : Info(&Info), OldStatus(Info.EvalStatus),
1313 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1314 Info.EvalStatus.Diag = NewDiag;
1315 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1316 }
1317
1318 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1319 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1320 moveFromAndCancel(std::move(Other));
1321 }
1322
1323 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1324 maybeRestoreState();
1325 moveFromAndCancel(std::move(Other));
1326 return *this;
1327 }
1328
1329 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1330 };
1331
1332 /// RAII object wrapping a full-expression or block scope, and handling
1333 /// the ending of the lifetime of temporaries created within it.
1334 template<ScopeKind Kind>
1335 class ScopeRAII {
1336 EvalInfo &Info;
1337 unsigned OldStackSize;
1338 public:
1339 ScopeRAII(EvalInfo &Info)
1340 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1341 // Push a new temporary version. This is needed to distinguish between
1342 // temporaries created in different iterations of a loop.
1343 Info.CurrentCall->pushTempVersion();
1344 }
1345 bool destroy(bool RunDestructors = true) {
1346 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1347 OldStackSize = std::numeric_limits<unsigned>::max();
1348 return OK;
1349 }
1350 ~ScopeRAII() {
1351 if (OldStackSize != std::numeric_limits<unsigned>::max())
1352 destroy(false);
1353 // Body moved to a static method to encourage the compiler to inline away
1354 // instances of this class.
1355 Info.CurrentCall->popTempVersion();
1356 }
1357 private:
1358 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1359 unsigned OldStackSize) {
1360 assert(OldStackSize <= Info.CleanupStack.size() &&
1361 "running cleanups out of order?");
1362
1363 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1364 // for a full-expression scope.
1365 bool Success = true;
1366 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1367 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1368 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1369 Success = false;
1370 break;
1371 }
1372 }
1373 }
1374
1375 // Compact any retained cleanups.
1376 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1377 if (Kind != ScopeKind::Block)
1378 NewEnd =
1379 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1380 return C.isDestroyedAtEndOf(Kind);
1381 });
1382 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1383 return Success;
1384 }
1385 };
1386 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1387 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1388 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1389}
1390
1391bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1392 CheckSubobjectKind CSK) {
1393 if (Invalid)
1394 return false;
1395 if (isOnePastTheEnd()) {
1396 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1397 << CSK;
1398 setInvalid();
1399 return false;
1400 }
1401 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1402 // must actually be at least one array element; even a VLA cannot have a
1403 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1404 return true;
1405}
1406
1407void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1408 const Expr *E) {
1409 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1410 // Do not set the designator as invalid: we can represent this situation,
1411 // and correct handling of __builtin_object_size requires us to do so.
1412}
1413
1414void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1415 const Expr *E,
1416 const APSInt &N) {
1417 // If we're complaining, we must be able to statically determine the size of
1418 // the most derived array.
1419 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1420 Info.CCEDiag(E, diag::note_constexpr_array_index)
1421 << N << /*array*/ 0
1422 << static_cast<unsigned>(getMostDerivedArraySize());
1423 else
1424 Info.CCEDiag(E, diag::note_constexpr_array_index)
1425 << N << /*non-array*/ 1;
1426 setInvalid();
1427}
1428
1429CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1430 const FunctionDecl *Callee, const LValue *This,
1431 const Expr *CallExpr, CallRef Call)
1432 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1433 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1434 Index(Info.NextCallIndex++) {
1435 Info.CurrentCall = this;
1436 ++Info.CallStackDepth;
1437}
1438
1439CallStackFrame::~CallStackFrame() {
1440 assert(Info.CurrentCall == this && "calls retired out of order");
1441 --Info.CallStackDepth;
1442 Info.CurrentCall = Caller;
1443}
1444
1445static bool isRead(AccessKinds AK) {
1446 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1447 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1448}
1449
1451 switch (AK) {
1452 case AK_Read:
1454 case AK_MemberCall:
1455 case AK_DynamicCast:
1456 case AK_TypeId:
1458 case AK_Dereference:
1459 return false;
1460 case AK_Assign:
1461 case AK_Increment:
1462 case AK_Decrement:
1463 case AK_Construct:
1464 case AK_Destroy:
1465 return true;
1466 }
1467 llvm_unreachable("unknown access kind");
1468}
1469
1470static bool isAnyAccess(AccessKinds AK) {
1471 return isRead(AK) || isModification(AK);
1472}
1473
1474/// Is this an access per the C++ definition?
1476 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1477 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1478}
1479
1480/// Is this kind of access valid on an indeterminate object value?
1482 switch (AK) {
1483 case AK_Read:
1484 case AK_Increment:
1485 case AK_Decrement:
1486 case AK_Dereference:
1487 // These need the object's value.
1488 return false;
1489
1492 case AK_Assign:
1493 case AK_Construct:
1494 case AK_Destroy:
1495 // Construction and destruction don't need the value.
1496 return true;
1497
1498 case AK_MemberCall:
1499 case AK_DynamicCast:
1500 case AK_TypeId:
1501 // These aren't really meaningful on scalars.
1502 return true;
1503 }
1504 llvm_unreachable("unknown access kind");
1505}
1506
1507namespace {
1508 struct ComplexValue {
1509 private:
1510 bool IsInt;
1511
1512 public:
1513 APSInt IntReal, IntImag;
1514 APFloat FloatReal, FloatImag;
1515
1516 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1517
1518 void makeComplexFloat() { IsInt = false; }
1519 bool isComplexFloat() const { return !IsInt; }
1520 APFloat &getComplexFloatReal() { return FloatReal; }
1521 APFloat &getComplexFloatImag() { return FloatImag; }
1522
1523 void makeComplexInt() { IsInt = true; }
1524 bool isComplexInt() const { return IsInt; }
1525 APSInt &getComplexIntReal() { return IntReal; }
1526 APSInt &getComplexIntImag() { return IntImag; }
1527
1528 void moveInto(APValue &v) const {
1529 if (isComplexFloat())
1530 v = APValue(FloatReal, FloatImag);
1531 else
1532 v = APValue(IntReal, IntImag);
1533 }
1534 void setFrom(const APValue &v) {
1535 assert(v.isComplexFloat() || v.isComplexInt());
1536 if (v.isComplexFloat()) {
1537 makeComplexFloat();
1538 FloatReal = v.getComplexFloatReal();
1539 FloatImag = v.getComplexFloatImag();
1540 } else {
1541 makeComplexInt();
1542 IntReal = v.getComplexIntReal();
1543 IntImag = v.getComplexIntImag();
1544 }
1545 }
1546 };
1547
1548 struct LValue {
1549 APValue::LValueBase Base;
1550 CharUnits Offset;
1551 SubobjectDesignator Designator;
1552 bool IsNullPtr : 1;
1553 bool InvalidBase : 1;
1554 // P2280R4 track if we have an unknown reference or pointer.
1555 bool AllowConstexprUnknown = false;
1556
1557 const APValue::LValueBase getLValueBase() const { return Base; }
1558 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1559 CharUnits &getLValueOffset() { return Offset; }
1560 const CharUnits &getLValueOffset() const { return Offset; }
1561 SubobjectDesignator &getLValueDesignator() { return Designator; }
1562 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1563 bool isNullPointer() const { return IsNullPtr;}
1564
1565 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1566 unsigned getLValueVersion() const { return Base.getVersion(); }
1567
1568 void moveInto(APValue &V) const {
1569 if (Designator.Invalid)
1570 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1571 else {
1572 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1573 V = APValue(Base, Offset, Designator.Entries,
1574 Designator.IsOnePastTheEnd, IsNullPtr);
1575 }
1576 if (AllowConstexprUnknown)
1577 V.setConstexprUnknown();
1578 }
1579 void setFrom(const ASTContext &Ctx, const APValue &V) {
1580 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1581 Base = V.getLValueBase();
1582 Offset = V.getLValueOffset();
1583 InvalidBase = false;
1584 Designator = SubobjectDesignator(Ctx, V);
1585 IsNullPtr = V.isNullPointer();
1586 AllowConstexprUnknown = V.allowConstexprUnknown();
1587 }
1588
1589 void set(APValue::LValueBase B, bool BInvalid = false) {
1590#ifndef NDEBUG
1591 // We only allow a few types of invalid bases. Enforce that here.
1592 if (BInvalid) {
1593 const auto *E = B.get<const Expr *>();
1594 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1595 "Unexpected type of invalid base");
1596 }
1597#endif
1598
1599 Base = B;
1600 Offset = CharUnits::fromQuantity(0);
1601 InvalidBase = BInvalid;
1602 Designator = SubobjectDesignator(getType(B));
1603 IsNullPtr = false;
1604 AllowConstexprUnknown = false;
1605 }
1606
1607 void setNull(ASTContext &Ctx, QualType PointerTy) {
1608 Base = (const ValueDecl *)nullptr;
1609 Offset =
1611 InvalidBase = false;
1612 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1613 IsNullPtr = true;
1614 AllowConstexprUnknown = false;
1615 }
1616
1617 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1618 set(B, true);
1619 }
1620
1621 std::string toString(ASTContext &Ctx, QualType T) const {
1622 APValue Printable;
1623 moveInto(Printable);
1624 return Printable.getAsString(Ctx, T);
1625 }
1626
1627 private:
1628 // Check that this LValue is not based on a null pointer. If it is, produce
1629 // a diagnostic and mark the designator as invalid.
1630 template <typename GenDiagType>
1631 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1632 if (Designator.Invalid)
1633 return false;
1634 if (IsNullPtr) {
1635 GenDiag();
1636 Designator.setInvalid();
1637 return false;
1638 }
1639 return true;
1640 }
1641
1642 public:
1643 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1644 CheckSubobjectKind CSK) {
1645 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1646 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1647 });
1648 }
1649
1650 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1651 AccessKinds AK) {
1652 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1653 if (AK == AccessKinds::AK_Dereference)
1654 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1655 else
1656 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1657 });
1658 }
1659
1660 // Check this LValue refers to an object. If not, set the designator to be
1661 // invalid and emit a diagnostic.
1662 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1663 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1664 Designator.checkSubobject(Info, E, CSK);
1665 }
1666
1667 void addDecl(EvalInfo &Info, const Expr *E,
1668 const Decl *D, bool Virtual = false) {
1669 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1670 Designator.addDeclUnchecked(D, Virtual);
1671 }
1672 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1673 if (!Designator.Entries.empty()) {
1674 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1675 Designator.setInvalid();
1676 return;
1677 }
1678 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1679 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1680 getType(Base).getNonReferenceType()->isArrayType());
1681 Designator.FirstEntryIsAnUnsizedArray = true;
1682 Designator.addUnsizedArrayUnchecked(ElemTy);
1683 }
1684 }
1685 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1686 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1687 Designator.addArrayUnchecked(CAT);
1688 }
1689 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1690 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1691 Designator.addComplexUnchecked(EltTy, Imag);
1692 }
1693 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1694 uint64_t Size, uint64_t Idx) {
1695 if (checkSubobject(Info, E, CSK_VectorElement))
1696 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1697 }
1698 void clearIsNullPointer() {
1699 IsNullPtr = false;
1700 }
1701 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1702 const APSInt &Index, CharUnits ElementSize) {
1703 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1704 // but we're not required to diagnose it and it's valid in C++.)
1705 if (!Index)
1706 return;
1707
1708 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1709 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1710 // offsets.
1711 uint64_t Offset64 = Offset.getQuantity();
1712 uint64_t ElemSize64 = ElementSize.getQuantity();
1713 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1714 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1715
1716 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1717 Designator.adjustIndex(Info, E, Index, *this);
1718 clearIsNullPointer();
1719 }
1720 void adjustOffset(CharUnits N) {
1721 Offset += N;
1722 if (N.getQuantity())
1723 clearIsNullPointer();
1724 }
1725 };
1726
1727 struct MemberPtr {
1728 MemberPtr() {}
1729 explicit MemberPtr(const ValueDecl *Decl)
1730 : DeclAndIsDerivedMember(Decl, false) {}
1731
1732 /// The member or (direct or indirect) field referred to by this member
1733 /// pointer, or 0 if this is a null member pointer.
1734 const ValueDecl *getDecl() const {
1735 return DeclAndIsDerivedMember.getPointer();
1736 }
1737 /// Is this actually a member of some type derived from the relevant class?
1738 bool isDerivedMember() const {
1739 return DeclAndIsDerivedMember.getInt();
1740 }
1741 /// Get the class which the declaration actually lives in.
1742 const CXXRecordDecl *getContainingRecord() const {
1743 return cast<CXXRecordDecl>(
1744 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1745 }
1746
1747 void moveInto(APValue &V) const {
1748 V = APValue(getDecl(), isDerivedMember(), Path);
1749 }
1750 void setFrom(const APValue &V) {
1751 assert(V.isMemberPointer());
1752 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1753 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1754 Path.clear();
1755 llvm::append_range(Path, V.getMemberPointerPath());
1756 }
1757
1758 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1759 /// whether the member is a member of some class derived from the class type
1760 /// of the member pointer.
1761 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1762 /// Path - The path of base/derived classes from the member declaration's
1763 /// class (exclusive) to the class type of the member pointer (inclusive).
1764 SmallVector<const CXXRecordDecl*, 4> Path;
1765
1766 /// Perform a cast towards the class of the Decl (either up or down the
1767 /// hierarchy).
1768 bool castBack(const CXXRecordDecl *Class) {
1769 assert(!Path.empty());
1770 const CXXRecordDecl *Expected;
1771 if (Path.size() >= 2)
1772 Expected = Path[Path.size() - 2];
1773 else
1774 Expected = getContainingRecord();
1775 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1776 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1777 // if B does not contain the original member and is not a base or
1778 // derived class of the class containing the original member, the result
1779 // of the cast is undefined.
1780 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1781 // (D::*). We consider that to be a language defect.
1782 return false;
1783 }
1784 Path.pop_back();
1785 return true;
1786 }
1787 /// Perform a base-to-derived member pointer cast.
1788 bool castToDerived(const CXXRecordDecl *Derived) {
1789 if (!getDecl())
1790 return true;
1791 if (!isDerivedMember()) {
1792 Path.push_back(Derived);
1793 return true;
1794 }
1795 if (!castBack(Derived))
1796 return false;
1797 if (Path.empty())
1798 DeclAndIsDerivedMember.setInt(false);
1799 return true;
1800 }
1801 /// Perform a derived-to-base member pointer cast.
1802 bool castToBase(const CXXRecordDecl *Base) {
1803 if (!getDecl())
1804 return true;
1805 if (Path.empty())
1806 DeclAndIsDerivedMember.setInt(true);
1807 if (isDerivedMember()) {
1808 Path.push_back(Base);
1809 return true;
1810 }
1811 return castBack(Base);
1812 }
1813 };
1814
1815 /// Compare two member pointers, which are assumed to be of the same type.
1816 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1817 if (!LHS.getDecl() || !RHS.getDecl())
1818 return !LHS.getDecl() && !RHS.getDecl();
1819 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1820 return false;
1821 return LHS.Path == RHS.Path;
1822 }
1823}
1824
1825void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1826 const LValue &LV) {
1827 if (Invalid || !N)
1828 return;
1829 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1830 if (isMostDerivedAnUnsizedArray()) {
1831 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1832 // Can't verify -- trust that the user is doing the right thing (or if
1833 // not, trust that the caller will catch the bad behavior).
1834 // FIXME: Should we reject if this overflows, at least?
1835 Entries.back() =
1836 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1837 return;
1838 }
1839
1840 // [expr.add]p4: For the purposes of these operators, a pointer to a
1841 // nonarray object behaves the same as a pointer to the first element of
1842 // an array of length one with the type of the object as its element type.
1843 bool IsArray =
1844 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1845 uint64_t ArrayIndex =
1846 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1847 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1848
1849 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1850 if (!Info.checkingPotentialConstantExpression() ||
1851 !LV.AllowConstexprUnknown) {
1852 // Calculate the actual index in a wide enough type, so we can include
1853 // it in the note.
1854 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1855 (llvm::APInt &)N += ArrayIndex;
1856 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1857 diagnosePointerArithmetic(Info, E, N);
1858 }
1859 setInvalid();
1860 return;
1861 }
1862
1863 ArrayIndex += TruncatedN;
1864 assert(ArrayIndex <= ArraySize &&
1865 "bounds check succeeded for out-of-bounds index");
1866
1867 if (IsArray)
1868 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1869 else
1870 IsOnePastTheEnd = (ArrayIndex != 0);
1871}
1872
1873static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1874static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1875 const LValue &This, const Expr *E,
1876 bool AllowNonLiteralTypes = false);
1877static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1878 bool InvalidBaseOK = false);
1879static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1880 bool InvalidBaseOK = false);
1881static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1882 EvalInfo &Info);
1883static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1884static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1885static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1886 EvalInfo &Info);
1887static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1888static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1889static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1890 EvalInfo &Info);
1891static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1892static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1893 EvalInfo &Info,
1894 std::string *StringResult = nullptr);
1895
1896/// Evaluate an integer or fixed point expression into an APResult.
1897static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1898 EvalInfo &Info);
1899
1900/// Evaluate only a fixed point expression into an APResult.
1901static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1902 EvalInfo &Info);
1903
1904//===----------------------------------------------------------------------===//
1905// Misc utilities
1906//===----------------------------------------------------------------------===//
1907
1908/// Negate an APSInt in place, converting it to a signed form if necessary, and
1909/// preserving its value (by extending by up to one bit as needed).
1910static void negateAsSigned(APSInt &Int) {
1911 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1912 Int = Int.extend(Int.getBitWidth() + 1);
1913 Int.setIsSigned(true);
1914 }
1915 Int = -Int;
1916}
1917
1918template<typename KeyT>
1919APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1920 ScopeKind Scope, LValue &LV) {
1921 unsigned Version = getTempVersion();
1922 APValue::LValueBase Base(Key, Index, Version);
1923 LV.set(Base);
1924 return createLocal(Base, Key, T, Scope);
1925}
1926
1927/// Allocate storage for a parameter of a function call made in this frame.
1928APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1929 LValue &LV) {
1930 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1931 APValue::LValueBase Base(PVD, Index, Args.Version);
1932 LV.set(Base);
1933 // We always destroy parameters at the end of the call, even if we'd allow
1934 // them to live to the end of the full-expression at runtime, in order to
1935 // give portable results and match other compilers.
1936 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1937}
1938
1939APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1940 QualType T, ScopeKind Scope) {
1941 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1942 unsigned Version = Base.getVersion();
1943 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1944 assert(Result.isAbsent() && "local created multiple times");
1945
1946 // If we're creating a local immediately in the operand of a speculative
1947 // evaluation, don't register a cleanup to be run outside the speculative
1948 // evaluation context, since we won't actually be able to initialize this
1949 // object.
1950 if (Index <= Info.SpeculativeEvaluationDepth) {
1951 if (T.isDestructedType())
1952 Info.noteSideEffect();
1953 } else {
1954 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1955 }
1956 return Result;
1957}
1958
1959APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1960 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1961 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1962 return nullptr;
1963 }
1964
1965 DynamicAllocLValue DA(NumHeapAllocs++);
1967 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1968 std::forward_as_tuple(DA), std::tuple<>());
1969 assert(Result.second && "reused a heap alloc index?");
1970 Result.first->second.AllocExpr = E;
1971 return &Result.first->second.Value;
1972}
1973
1974/// Produce a string describing the given constexpr call.
1975void CallStackFrame::describe(raw_ostream &Out) const {
1976 unsigned ArgIndex = 0;
1977 bool IsMemberCall =
1978 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1979 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1980
1981 if (!IsMemberCall)
1982 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1983 /*Qualified=*/false);
1984
1985 if (This && IsMemberCall) {
1986 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1987 const Expr *Object = MCE->getImplicitObjectArgument();
1988 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1989 /*Indentation=*/0);
1990 if (Object->getType()->isPointerType())
1991 Out << "->";
1992 else
1993 Out << ".";
1994 } else if (const auto *OCE =
1995 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1996 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1997 Info.Ctx.getPrintingPolicy(),
1998 /*Indentation=*/0);
1999 Out << ".";
2000 } else {
2001 APValue Val;
2002 This->moveInto(Val);
2003 Val.printPretty(
2004 Out, Info.Ctx,
2005 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2006 Out << ".";
2007 }
2008 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2009 /*Qualified=*/false);
2010 IsMemberCall = false;
2011 }
2012
2013 Out << '(';
2014
2015 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2016 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2017 if (ArgIndex > (unsigned)IsMemberCall)
2018 Out << ", ";
2019
2020 const ParmVarDecl *Param = *I;
2021 APValue *V = Info.getParamSlot(Arguments, Param);
2022 if (V)
2023 V->printPretty(Out, Info.Ctx, Param->getType());
2024 else
2025 Out << "<...>";
2026
2027 if (ArgIndex == 0 && IsMemberCall)
2028 Out << "->" << *Callee << '(';
2029 }
2030
2031 Out << ')';
2032}
2033
2034/// Evaluate an expression to see if it had side-effects, and discard its
2035/// result.
2036/// \return \c true if the caller should keep evaluating.
2037static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2038 assert(!E->isValueDependent());
2039 APValue Scratch;
2040 if (!Evaluate(Scratch, Info, E))
2041 // We don't need the value, but we might have skipped a side effect here.
2042 return Info.noteSideEffect();
2043 return true;
2044}
2045
2046/// Should this call expression be treated as forming an opaque constant?
2047static bool IsOpaqueConstantCall(const CallExpr *E) {
2048 unsigned Builtin = E->getBuiltinCallee();
2049 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2050 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2051 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2052 Builtin == Builtin::BI__builtin_function_start);
2053}
2054
2055static bool IsOpaqueConstantCall(const LValue &LVal) {
2056 const auto *BaseExpr =
2057 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2058 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2059}
2060
2062 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2063 // constant expression of pointer type that evaluates to...
2064
2065 // ... a null pointer value, or a prvalue core constant expression of type
2066 // std::nullptr_t.
2067 if (!B)
2068 return true;
2069
2070 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2071 // ... the address of an object with static storage duration,
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->hasGlobalStorage();
2075 return true;
2076 // ... the address of a function,
2077 // ... the address of a GUID [MS extension],
2078 // ... the address of an unnamed global constant
2080 }
2081
2082 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2083 return true;
2084
2085 const Expr *E = B.get<const Expr*>();
2086 switch (E->getStmtClass()) {
2087 default:
2088 return false;
2089 case Expr::CompoundLiteralExprClass: {
2091 return CLE->isFileScope() && CLE->isLValue();
2092 }
2093 case Expr::MaterializeTemporaryExprClass:
2094 // A materialized temporary might have been lifetime-extended to static
2095 // storage duration.
2096 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2097 // A string literal has static storage duration.
2098 case Expr::StringLiteralClass:
2099 case Expr::PredefinedExprClass:
2100 case Expr::ObjCStringLiteralClass:
2101 case Expr::ObjCEncodeExprClass:
2102 return true;
2103 case Expr::ObjCBoxedExprClass:
2104 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2105 case Expr::CallExprClass:
2107 // For GCC compatibility, &&label has static storage duration.
2108 case Expr::AddrLabelExprClass:
2109 return true;
2110 // A Block literal expression may be used as the initialization value for
2111 // Block variables at global or local static scope.
2112 case Expr::BlockExprClass:
2113 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2114 // The APValue generated from a __builtin_source_location will be emitted as a
2115 // literal.
2116 case Expr::SourceLocExprClass:
2117 return true;
2118 case Expr::ImplicitValueInitExprClass:
2119 // FIXME:
2120 // We can never form an lvalue with an implicit value initialization as its
2121 // base through expression evaluation, so these only appear in one case: the
2122 // implicit variable declaration we invent when checking whether a constexpr
2123 // constructor can produce a constant expression. We must assume that such
2124 // an expression might be a global lvalue.
2125 return true;
2126 }
2127}
2128
2129static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2130 return LVal.Base.dyn_cast<const ValueDecl*>();
2131}
2132
2133// Information about an LValueBase that is some kind of string.
2136 StringRef Bytes;
2138};
2139
2140// Gets the lvalue base of LVal as a string.
2141static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2142 LValueBaseString &AsString) {
2143 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2144 if (!BaseExpr)
2145 return false;
2146
2147 // For ObjCEncodeExpr, we need to compute and store the string.
2148 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2149 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2150 AsString.ObjCEncodeStorage);
2151 AsString.Bytes = AsString.ObjCEncodeStorage;
2152 AsString.CharWidth = 1;
2153 return true;
2154 }
2155
2156 // Otherwise, we have a StringLiteral.
2157 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2158 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2159 Lit = PE->getFunctionName();
2160
2161 if (!Lit)
2162 return false;
2163
2164 AsString.Bytes = Lit->getBytes();
2165 AsString.CharWidth = Lit->getCharByteWidth();
2166 return true;
2167}
2168
2169// Determine whether two string literals potentially overlap. This will be the
2170// case if they agree on the values of all the bytes on the overlapping region
2171// between them.
2172//
2173// The overlapping region is the portion of the two string literals that must
2174// overlap in memory if the pointers actually point to the same address at
2175// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2176// the overlapping region is "cdef\0", which in this case does agree, so the
2177// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2178// "bazbar" + 3, the overlapping region contains all of both strings, so they
2179// are not potentially overlapping, even though they agree from the given
2180// addresses onwards.
2181//
2182// See open core issue CWG2765 which is discussing the desired rule here.
2183static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2184 const LValue &LHS,
2185 const LValue &RHS) {
2186 LValueBaseString LHSString, RHSString;
2187 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2188 !GetLValueBaseAsString(Info, RHS, RHSString))
2189 return false;
2190
2191 // This is the byte offset to the location of the first character of LHS
2192 // within RHS. We don't need to look at the characters of one string that
2193 // would appear before the start of the other string if they were merged.
2194 CharUnits Offset = RHS.Offset - LHS.Offset;
2195 if (Offset.isNegative()) {
2196 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2197 return false;
2198 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2199 } else {
2200 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2201 return false;
2202 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2203 }
2204
2205 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2206 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2207 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2208 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2209
2210 // The null terminator isn't included in the string data, so check for it
2211 // manually. If the longer string doesn't have a null terminator where the
2212 // shorter string ends, they aren't potentially overlapping.
2213 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2214 if (Shorter.size() + NullByte >= Longer.size())
2215 break;
2216 if (Longer[Shorter.size() + NullByte])
2217 return false;
2218 }
2219
2220 // Otherwise, they're potentially overlapping if and only if the overlapping
2221 // region is the same.
2222 return Shorter == Longer.take_front(Shorter.size());
2223}
2224
2225static bool IsWeakLValue(const LValue &Value) {
2227 return Decl && Decl->isWeak();
2228}
2229
2230static bool isZeroSized(const LValue &Value) {
2232 if (isa_and_nonnull<VarDecl>(Decl)) {
2233 QualType Ty = Decl->getType();
2234 if (Ty->isArrayType())
2235 return Ty->isIncompleteType() ||
2236 Decl->getASTContext().getTypeSize(Ty) == 0;
2237 }
2238 return false;
2239}
2240
2241static bool HasSameBase(const LValue &A, const LValue &B) {
2242 if (!A.getLValueBase())
2243 return !B.getLValueBase();
2244 if (!B.getLValueBase())
2245 return false;
2246
2247 if (A.getLValueBase().getOpaqueValue() !=
2248 B.getLValueBase().getOpaqueValue())
2249 return false;
2250
2251 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2252 A.getLValueVersion() == B.getLValueVersion();
2253}
2254
2255static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2256 assert(Base && "no location for a null lvalue");
2257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2258
2259 // For a parameter, find the corresponding call stack frame (if it still
2260 // exists), and point at the parameter of the function definition we actually
2261 // invoked.
2262 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2263 unsigned Idx = PVD->getFunctionScopeIndex();
2264 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2265 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2266 F->Arguments.Version == Base.getVersion() && F->Callee &&
2267 Idx < F->Callee->getNumParams()) {
2268 VD = F->Callee->getParamDecl(Idx);
2269 break;
2270 }
2271 }
2272 }
2273
2274 if (VD)
2275 Info.Note(VD->getLocation(), diag::note_declared_at);
2276 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2277 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2278 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2279 // FIXME: Produce a note for dangling pointers too.
2280 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2281 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2282 diag::note_constexpr_dynamic_alloc_here);
2283 }
2284
2285 // We have no information to show for a typeid(T) object.
2286}
2287
2292
2293/// Materialized temporaries that we've already checked to determine if they're
2294/// initializsed by a constant expression.
2297
2299 EvalInfo &Info, SourceLocation DiagLoc,
2300 QualType Type, const APValue &Value,
2301 ConstantExprKind Kind,
2302 const FieldDecl *SubobjectDecl,
2303 CheckedTemporaries &CheckedTemps);
2304
2305/// Check that this reference or pointer core constant expression is a valid
2306/// value for an address or reference constant expression. Return true if we
2307/// can fold this expression, whether or not it's a constant expression.
2308static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2309 QualType Type, const LValue &LVal,
2310 ConstantExprKind Kind,
2311 CheckedTemporaries &CheckedTemps) {
2312 bool IsReferenceType = Type->isReferenceType();
2313
2314 APValue::LValueBase Base = LVal.getLValueBase();
2315 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2316
2317 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2318 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2319
2320 // Additional restrictions apply in a template argument. We only enforce the
2321 // C++20 restrictions here; additional syntactic and semantic restrictions
2322 // are applied elsewhere.
2323 if (isTemplateArgument(Kind)) {
2324 int InvalidBaseKind = -1;
2325 StringRef Ident;
2326 if (Base.is<TypeInfoLValue>())
2327 InvalidBaseKind = 0;
2328 else if (isa_and_nonnull<StringLiteral>(BaseE))
2329 InvalidBaseKind = 1;
2330 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2331 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2332 InvalidBaseKind = 2;
2333 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2334 InvalidBaseKind = 3;
2335 Ident = PE->getIdentKindName();
2336 }
2337
2338 if (InvalidBaseKind != -1) {
2339 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2340 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2341 << Ident;
2342 return false;
2343 }
2344 }
2345
2346 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2347 FD && FD->isImmediateFunction()) {
2348 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2349 << !Type->isAnyPointerType();
2350 Info.Note(FD->getLocation(), diag::note_declared_at);
2351 return false;
2352 }
2353
2354 // Check that the object is a global. Note that the fake 'this' object we
2355 // manufacture when checking potential constant expressions is conservatively
2356 // assumed to be global here.
2357 if (!IsGlobalLValue(Base)) {
2358 if (Info.getLangOpts().CPlusPlus11) {
2359 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2360 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2361 << BaseVD;
2362 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2363 if (VarD && VarD->isConstexpr()) {
2364 // Non-static local constexpr variables have unintuitive semantics:
2365 // constexpr int a = 1;
2366 // constexpr const int *p = &a;
2367 // ... is invalid because the address of 'a' is not constant. Suggest
2368 // adding a 'static' in this case.
2369 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2370 << VarD
2371 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2372 } else {
2373 NoteLValueLocation(Info, Base);
2374 }
2375 } else {
2376 Info.FFDiag(Loc);
2377 }
2378 // Don't allow references to temporaries to escape.
2379 return false;
2380 }
2381 assert((Info.checkingPotentialConstantExpression() ||
2382 LVal.getLValueCallIndex() == 0) &&
2383 "have call index for global lvalue");
2384
2385 if (LVal.allowConstexprUnknown()) {
2386 if (BaseVD) {
2387 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2388 NoteLValueLocation(Info, Base);
2389 } else {
2390 Info.FFDiag(Loc);
2391 }
2392 return false;
2393 }
2394
2395 if (Base.is<DynamicAllocLValue>()) {
2396 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2397 << IsReferenceType << !Designator.Entries.empty();
2398 NoteLValueLocation(Info, Base);
2399 return false;
2400 }
2401
2402 if (BaseVD) {
2403 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2404 // Check if this is a thread-local variable.
2405 if (Var->getTLSKind())
2406 // FIXME: Diagnostic!
2407 return false;
2408
2409 // A dllimport variable never acts like a constant, unless we're
2410 // evaluating a value for use only in name mangling.
2411 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2412 // FIXME: Diagnostic!
2413 return false;
2414
2415 // In CUDA/HIP device compilation, only device side variables have
2416 // constant addresses.
2417 if (Info.getASTContext().getLangOpts().CUDA &&
2418 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2419 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2420 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2421 !Var->hasAttr<CUDAConstantAttr>() &&
2422 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2423 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2424 Var->hasAttr<HIPManagedAttr>())
2425 return false;
2426 }
2427 }
2428 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2429 // __declspec(dllimport) must be handled very carefully:
2430 // We must never initialize an expression with the thunk in C++.
2431 // Doing otherwise would allow the same id-expression to yield
2432 // different addresses for the same function in different translation
2433 // units. However, this means that we must dynamically initialize the
2434 // expression with the contents of the import address table at runtime.
2435 //
2436 // The C language has no notion of ODR; furthermore, it has no notion of
2437 // dynamic initialization. This means that we are permitted to
2438 // perform initialization with the address of the thunk.
2439 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2440 FD->hasAttr<DLLImportAttr>())
2441 // FIXME: Diagnostic!
2442 return false;
2443 }
2444 } else if (const auto *MTE =
2445 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2446 if (CheckedTemps.insert(MTE).second) {
2447 QualType TempType = getType(Base);
2448 if (TempType.isDestructedType()) {
2449 Info.FFDiag(MTE->getExprLoc(),
2450 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2451 << TempType;
2452 return false;
2453 }
2454
2455 APValue *V = MTE->getOrCreateValue(false);
2456 assert(V && "evasluation result refers to uninitialised temporary");
2458 Info, MTE->getExprLoc(), TempType, *V, Kind,
2459 /*SubobjectDecl=*/nullptr, CheckedTemps))
2460 return false;
2461 }
2462 }
2463
2464 // Allow address constant expressions to be past-the-end pointers. This is
2465 // an extension: the standard requires them to point to an object.
2466 if (!IsReferenceType)
2467 return true;
2468
2469 // A reference constant expression must refer to an object.
2470 if (!Base) {
2471 // FIXME: diagnostic
2472 Info.CCEDiag(Loc);
2473 return true;
2474 }
2475
2476 // Does this refer one past the end of some object?
2477 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2478 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2479 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2480 NoteLValueLocation(Info, Base);
2481 }
2482
2483 return true;
2484}
2485
2486/// Member pointers are constant expressions unless they point to a
2487/// non-virtual dllimport member function.
2488static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2489 SourceLocation Loc,
2490 QualType Type,
2491 const APValue &Value,
2492 ConstantExprKind Kind) {
2493 const ValueDecl *Member = Value.getMemberPointerDecl();
2494 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2495 if (!FD)
2496 return true;
2497 if (FD->isImmediateFunction()) {
2498 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2499 Info.Note(FD->getLocation(), diag::note_declared_at);
2500 return false;
2501 }
2502 return isForManglingOnly(Kind) || FD->isVirtual() ||
2503 !FD->hasAttr<DLLImportAttr>();
2504}
2505
2506/// Check that this core constant expression is of literal type, and if not,
2507/// produce an appropriate diagnostic.
2508static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2509 const LValue *This = nullptr) {
2510 // The restriction to literal types does not exist in C++23 anymore.
2511 if (Info.getLangOpts().CPlusPlus23)
2512 return true;
2513
2514 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2515 return true;
2516
2517 // C++1y: A constant initializer for an object o [...] may also invoke
2518 // constexpr constructors for o and its subobjects even if those objects
2519 // are of non-literal class types.
2520 //
2521 // C++11 missed this detail for aggregates, so classes like this:
2522 // struct foo_t { union { int i; volatile int j; } u; };
2523 // are not (obviously) initializable like so:
2524 // __attribute__((__require_constant_initialization__))
2525 // static const foo_t x = {{0}};
2526 // because "i" is a subobject with non-literal initialization (due to the
2527 // volatile member of the union). See:
2528 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2529 // Therefore, we use the C++1y behavior.
2530 if (This && Info.EvaluatingDecl == This->getLValueBase())
2531 return true;
2532
2533 // Prvalue constant expressions must be of literal types.
2534 if (Info.getLangOpts().CPlusPlus11)
2535 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2536 << E->getType();
2537 else
2538 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2539 return false;
2540}
2541
2543 EvalInfo &Info, SourceLocation DiagLoc,
2544 QualType Type, const APValue &Value,
2545 ConstantExprKind Kind,
2546 const FieldDecl *SubobjectDecl,
2547 CheckedTemporaries &CheckedTemps) {
2548 if (!Value.hasValue()) {
2549 if (SubobjectDecl) {
2550 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2551 << /*(name)*/ 1 << SubobjectDecl;
2552 Info.Note(SubobjectDecl->getLocation(),
2553 diag::note_constexpr_subobject_declared_here);
2554 } else {
2555 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556 << /*of type*/ 0 << Type;
2557 }
2558 return false;
2559 }
2560
2561 // We allow _Atomic(T) to be initialized from anything that T can be
2562 // initialized from.
2563 if (const AtomicType *AT = Type->getAs<AtomicType>())
2564 Type = AT->getValueType();
2565
2566 // Core issue 1454: For a literal constant expression of array or class type,
2567 // each subobject of its value shall have been initialized by a constant
2568 // expression.
2569 if (Value.isArray()) {
2571 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2572 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2573 Value.getArrayInitializedElt(I), Kind,
2574 SubobjectDecl, CheckedTemps))
2575 return false;
2576 }
2577 if (!Value.hasArrayFiller())
2578 return true;
2579 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2580 Value.getArrayFiller(), Kind, SubobjectDecl,
2581 CheckedTemps);
2582 }
2583 if (Value.isUnion() && Value.getUnionField()) {
2584 return CheckEvaluationResult(
2585 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2586 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2587 }
2588 if (Value.isStruct()) {
2589 auto *RD = Type->castAsRecordDecl();
2590 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2591 unsigned BaseIndex = 0;
2592 for (const CXXBaseSpecifier &BS : CD->bases()) {
2593 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2594 if (!BaseValue.hasValue()) {
2595 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2596 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2597 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2598 return false;
2599 }
2600 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2601 Kind, /*SubobjectDecl=*/nullptr,
2602 CheckedTemps))
2603 return false;
2604 ++BaseIndex;
2605 }
2606 }
2607 for (const auto *I : RD->fields()) {
2608 if (I->isUnnamedBitField())
2609 continue;
2610
2611 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2612 Value.getStructField(I->getFieldIndex()), Kind,
2613 I, CheckedTemps))
2614 return false;
2615 }
2616 }
2617
2618 if (Value.isLValue() &&
2620 LValue LVal;
2621 LVal.setFrom(Info.Ctx, Value);
2622 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2623 CheckedTemps);
2624 }
2625
2626 if (Value.isMemberPointer() &&
2628 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2629
2630 // Everything else is fine.
2631 return true;
2632}
2633
2634/// Check that this core constant expression value is a valid value for a
2635/// constant expression. If not, report an appropriate diagnostic. Does not
2636/// check that the expression is of literal type.
2637static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2638 QualType Type, const APValue &Value,
2639 ConstantExprKind Kind) {
2640 // Nothing to check for a constant expression of type 'cv void'.
2641 if (Type->isVoidType())
2642 return true;
2643
2644 CheckedTemporaries CheckedTemps;
2646 Info, DiagLoc, Type, Value, Kind,
2647 /*SubobjectDecl=*/nullptr, CheckedTemps);
2648}
2649
2650/// Check that this evaluated value is fully-initialized and can be loaded by
2651/// an lvalue-to-rvalue conversion.
2652static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2653 QualType Type, const APValue &Value) {
2654 CheckedTemporaries CheckedTemps;
2655 return CheckEvaluationResult(
2657 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2658}
2659
2660/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2661/// "the allocated storage is deallocated within the evaluation".
2662static bool CheckMemoryLeaks(EvalInfo &Info) {
2663 if (!Info.HeapAllocs.empty()) {
2664 // We can still fold to a constant despite a compile-time memory leak,
2665 // so long as the heap allocation isn't referenced in the result (we check
2666 // that in CheckConstantExpression).
2667 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2668 diag::note_constexpr_memory_leak)
2669 << unsigned(Info.HeapAllocs.size() - 1);
2670 }
2671 return true;
2672}
2673
2674static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2675 // A null base expression indicates a null pointer. These are always
2676 // evaluatable, and they are false unless the offset is zero.
2677 if (!Value.getLValueBase()) {
2678 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2679 Result = !Value.getLValueOffset().isZero();
2680 return true;
2681 }
2682
2683 // We have a non-null base. These are generally known to be true, but if it's
2684 // a weak declaration it can be null at runtime.
2685 Result = true;
2686 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2687 return !Decl || !Decl->isWeak();
2688}
2689
2690static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2691 // TODO: This function should produce notes if it fails.
2692 switch (Val.getKind()) {
2693 case APValue::None:
2695 return false;
2696 case APValue::Int:
2697 Result = Val.getInt().getBoolValue();
2698 return true;
2700 Result = Val.getFixedPoint().getBoolValue();
2701 return true;
2702 case APValue::Float:
2703 Result = !Val.getFloat().isZero();
2704 return true;
2706 Result = Val.getComplexIntReal().getBoolValue() ||
2707 Val.getComplexIntImag().getBoolValue();
2708 return true;
2710 Result = !Val.getComplexFloatReal().isZero() ||
2711 !Val.getComplexFloatImag().isZero();
2712 return true;
2713 case APValue::LValue:
2714 return EvalPointerValueAsBool(Val, Result);
2716 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2717 return false;
2718 }
2719 Result = Val.getMemberPointerDecl();
2720 return true;
2721 case APValue::Vector:
2722 case APValue::Array:
2723 case APValue::Struct:
2724 case APValue::Union:
2726 return false;
2727 }
2728
2729 llvm_unreachable("unknown APValue kind");
2730}
2731
2732static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2733 EvalInfo &Info) {
2734 assert(!E->isValueDependent());
2735 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2736 APValue Val;
2737 if (!Evaluate(Val, Info, E))
2738 return false;
2739 return HandleConversionToBool(Val, Result);
2740}
2741
2742template<typename T>
2743static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2744 const T &SrcValue, QualType DestType) {
2745 Info.CCEDiag(E, diag::note_constexpr_overflow)
2746 << SrcValue << DestType;
2747 return Info.noteUndefinedBehavior();
2748}
2749
2750static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2751 QualType SrcType, const APFloat &Value,
2752 QualType DestType, APSInt &Result) {
2753 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2754 // Determine whether we are converting to unsigned or signed.
2755 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2756
2757 Result = APSInt(DestWidth, !DestSigned);
2758 bool ignored;
2759 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2760 & APFloat::opInvalidOp)
2761 return HandleOverflow(Info, E, Value, DestType);
2762 return true;
2763}
2764
2765/// Get rounding mode to use in evaluation of the specified expression.
2766///
2767/// If rounding mode is unknown at compile time, still try to evaluate the
2768/// expression. If the result is exact, it does not depend on rounding mode.
2769/// So return "tonearest" mode instead of "dynamic".
2770static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2771 llvm::RoundingMode RM =
2773 if (RM == llvm::RoundingMode::Dynamic)
2774 RM = llvm::RoundingMode::NearestTiesToEven;
2775 return RM;
2776}
2777
2778/// Check if the given evaluation result is allowed for constant evaluation.
2779static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2780 APFloat::opStatus St) {
2781 // In a constant context, assume that any dynamic rounding mode or FP
2782 // exception state matches the default floating-point environment.
2783 if (Info.InConstantContext)
2784 return true;
2785
2786 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2787 if ((St & APFloat::opInexact) &&
2788 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2789 // Inexact result means that it depends on rounding mode. If the requested
2790 // mode is dynamic, the evaluation cannot be made in compile time.
2791 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2792 return false;
2793 }
2794
2795 if ((St != APFloat::opOK) &&
2796 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2798 FPO.getAllowFEnvAccess())) {
2799 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2800 return false;
2801 }
2802
2803 if ((St & APFloat::opStatus::opInvalidOp) &&
2805 // There is no usefully definable result.
2806 Info.FFDiag(E);
2807 return false;
2808 }
2809
2810 // FIXME: if:
2811 // - evaluation triggered other FP exception, and
2812 // - exception mode is not "ignore", and
2813 // - the expression being evaluated is not a part of global variable
2814 // initializer,
2815 // the evaluation probably need to be rejected.
2816 return true;
2817}
2818
2819static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2820 QualType SrcType, QualType DestType,
2821 APFloat &Result) {
2822 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2824 "HandleFloatToFloatCast has been checked with only CastExpr, "
2825 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2826 "the new expression or address the root cause of this usage.");
2827 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2828 APFloat::opStatus St;
2829 APFloat Value = Result;
2830 bool ignored;
2831 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2832 return checkFloatingPointResult(Info, E, St);
2833}
2834
2835static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2836 QualType DestType, QualType SrcType,
2837 const APSInt &Value) {
2838 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2839 // Figure out if this is a truncate, extend or noop cast.
2840 // If the input is signed, do a sign extend, noop, or truncate.
2841 APSInt Result = Value.extOrTrunc(DestWidth);
2842 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2843 if (DestType->isBooleanType())
2844 Result = Value.getBoolValue();
2845 return Result;
2846}
2847
2848static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2849 const FPOptions FPO,
2850 QualType SrcType, const APSInt &Value,
2851 QualType DestType, APFloat &Result) {
2852 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2853 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2854 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2855 return checkFloatingPointResult(Info, E, St);
2856}
2857
2858static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2859 APValue &Value, const FieldDecl *FD) {
2860 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2861
2862 if (!Value.isInt()) {
2863 // Trying to store a pointer-cast-to-integer into a bitfield.
2864 // FIXME: In this case, we should provide the diagnostic for casting
2865 // a pointer to an integer.
2866 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2867 Info.FFDiag(E);
2868 return false;
2869 }
2870
2871 APSInt &Int = Value.getInt();
2872 unsigned OldBitWidth = Int.getBitWidth();
2873 unsigned NewBitWidth = FD->getBitWidthValue();
2874 if (NewBitWidth < OldBitWidth)
2875 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2876 return true;
2877}
2878
2879/// Perform the given integer operation, which is known to need at most BitWidth
2880/// bits, and check for overflow in the original type (if that type was not an
2881/// unsigned type).
2882template<typename Operation>
2883static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2884 const APSInt &LHS, const APSInt &RHS,
2885 unsigned BitWidth, Operation Op,
2886 APSInt &Result) {
2887 if (LHS.isUnsigned()) {
2888 Result = Op(LHS, RHS);
2889 return true;
2890 }
2891
2892 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2893 Result = Value.trunc(LHS.getBitWidth());
2894 if (Result.extend(BitWidth) != Value) {
2895 if (Info.checkingForUndefinedBehavior())
2896 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2897 diag::warn_integer_constant_overflow)
2898 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2899 /*UpperCase=*/true, /*InsertSeparators=*/true)
2900 << E->getType() << E->getSourceRange();
2901 return HandleOverflow(Info, E, Value, E->getType());
2902 }
2903 return true;
2904}
2905
2906/// Perform the given binary integer operation.
2907static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2908 const APSInt &LHS, BinaryOperatorKind Opcode,
2909 APSInt RHS, APSInt &Result) {
2910 bool HandleOverflowResult = true;
2911 switch (Opcode) {
2912 default:
2913 Info.FFDiag(E);
2914 return false;
2915 case BO_Mul:
2916 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2917 std::multiplies<APSInt>(), Result);
2918 case BO_Add:
2919 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2920 std::plus<APSInt>(), Result);
2921 case BO_Sub:
2922 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2923 std::minus<APSInt>(), Result);
2924 case BO_And: Result = LHS & RHS; return true;
2925 case BO_Xor: Result = LHS ^ RHS; return true;
2926 case BO_Or: Result = LHS | RHS; return true;
2927 case BO_Div:
2928 case BO_Rem:
2929 if (RHS == 0) {
2930 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2931 << E->getRHS()->getSourceRange();
2932 return false;
2933 }
2934 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2935 // this operation and gives the two's complement result.
2936 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2937 LHS.isMinSignedValue())
2938 HandleOverflowResult = HandleOverflow(
2939 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2940 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2941 return HandleOverflowResult;
2942 case BO_Shl: {
2943 if (Info.getLangOpts().OpenCL)
2944 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2945 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2946 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2947 RHS.isUnsigned());
2948 else if (RHS.isSigned() && RHS.isNegative()) {
2949 // During constant-folding, a negative shift is an opposite shift. Such
2950 // a shift is not a constant expression.
2951 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2952 if (!Info.noteUndefinedBehavior())
2953 return false;
2954 RHS = -RHS;
2955 goto shift_right;
2956 }
2957 shift_left:
2958 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2959 // the shifted type.
2960 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2961 if (SA != RHS) {
2962 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2963 << RHS << E->getType() << LHS.getBitWidth();
2964 if (!Info.noteUndefinedBehavior())
2965 return false;
2966 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2967 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2968 // operand, and must not overflow the corresponding unsigned type.
2969 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2970 // E1 x 2^E2 module 2^N.
2971 if (LHS.isNegative()) {
2972 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2973 if (!Info.noteUndefinedBehavior())
2974 return false;
2975 } else if (LHS.countl_zero() < SA) {
2976 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2977 if (!Info.noteUndefinedBehavior())
2978 return false;
2979 }
2980 }
2981 Result = LHS << SA;
2982 return true;
2983 }
2984 case BO_Shr: {
2985 if (Info.getLangOpts().OpenCL)
2986 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2987 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2988 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2989 RHS.isUnsigned());
2990 else if (RHS.isSigned() && RHS.isNegative()) {
2991 // During constant-folding, a negative shift is an opposite shift. Such a
2992 // shift is not a constant expression.
2993 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2994 if (!Info.noteUndefinedBehavior())
2995 return false;
2996 RHS = -RHS;
2997 goto shift_left;
2998 }
2999 shift_right:
3000 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3001 // shifted type.
3002 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3003 if (SA != RHS) {
3004 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3005 << RHS << E->getType() << LHS.getBitWidth();
3006 if (!Info.noteUndefinedBehavior())
3007 return false;
3008 }
3009
3010 Result = LHS >> SA;
3011 return true;
3012 }
3013
3014 case BO_LT: Result = LHS < RHS; return true;
3015 case BO_GT: Result = LHS > RHS; return true;
3016 case BO_LE: Result = LHS <= RHS; return true;
3017 case BO_GE: Result = LHS >= RHS; return true;
3018 case BO_EQ: Result = LHS == RHS; return true;
3019 case BO_NE: Result = LHS != RHS; return true;
3020 case BO_Cmp:
3021 llvm_unreachable("BO_Cmp should be handled elsewhere");
3022 }
3023}
3024
3025/// Perform the given binary floating-point operation, in-place, on LHS.
3026static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3027 APFloat &LHS, BinaryOperatorKind Opcode,
3028 const APFloat &RHS) {
3029 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3030 APFloat::opStatus St;
3031 switch (Opcode) {
3032 default:
3033 Info.FFDiag(E);
3034 return false;
3035 case BO_Mul:
3036 St = LHS.multiply(RHS, RM);
3037 break;
3038 case BO_Add:
3039 St = LHS.add(RHS, RM);
3040 break;
3041 case BO_Sub:
3042 St = LHS.subtract(RHS, RM);
3043 break;
3044 case BO_Div:
3045 // [expr.mul]p4:
3046 // If the second operand of / or % is zero the behavior is undefined.
3047 if (RHS.isZero())
3048 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3049 St = LHS.divide(RHS, RM);
3050 break;
3051 }
3052
3053 // [expr.pre]p4:
3054 // If during the evaluation of an expression, the result is not
3055 // mathematically defined [...], the behavior is undefined.
3056 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3057 if (LHS.isNaN()) {
3058 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3059 return Info.noteUndefinedBehavior();
3060 }
3061
3062 return checkFloatingPointResult(Info, E, St);
3063}
3064
3065static bool handleLogicalOpForVector(const APInt &LHSValue,
3066 BinaryOperatorKind Opcode,
3067 const APInt &RHSValue, APInt &Result) {
3068 bool LHS = (LHSValue != 0);
3069 bool RHS = (RHSValue != 0);
3070
3071 if (Opcode == BO_LAnd)
3072 Result = LHS && RHS;
3073 else
3074 Result = LHS || RHS;
3075 return true;
3076}
3077static bool handleLogicalOpForVector(const APFloat &LHSValue,
3078 BinaryOperatorKind Opcode,
3079 const APFloat &RHSValue, APInt &Result) {
3080 bool LHS = !LHSValue.isZero();
3081 bool RHS = !RHSValue.isZero();
3082
3083 if (Opcode == BO_LAnd)
3084 Result = LHS && RHS;
3085 else
3086 Result = LHS || RHS;
3087 return true;
3088}
3089
3090static bool handleLogicalOpForVector(const APValue &LHSValue,
3091 BinaryOperatorKind Opcode,
3092 const APValue &RHSValue, APInt &Result) {
3093 // The result is always an int type, however operands match the first.
3094 if (LHSValue.getKind() == APValue::Int)
3095 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3096 RHSValue.getInt(), Result);
3097 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3098 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3099 RHSValue.getFloat(), Result);
3100}
3101
3102template <typename APTy>
3103static bool
3105 const APTy &RHSValue, APInt &Result) {
3106 switch (Opcode) {
3107 default:
3108 llvm_unreachable("unsupported binary operator");
3109 case BO_EQ:
3110 Result = (LHSValue == RHSValue);
3111 break;
3112 case BO_NE:
3113 Result = (LHSValue != RHSValue);
3114 break;
3115 case BO_LT:
3116 Result = (LHSValue < RHSValue);
3117 break;
3118 case BO_GT:
3119 Result = (LHSValue > RHSValue);
3120 break;
3121 case BO_LE:
3122 Result = (LHSValue <= RHSValue);
3123 break;
3124 case BO_GE:
3125 Result = (LHSValue >= RHSValue);
3126 break;
3127 }
3128
3129 // The boolean operations on these vector types use an instruction that
3130 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3131 // to -1 to make sure that we produce the correct value.
3132 Result.negate();
3133
3134 return true;
3135}
3136
3137static bool handleCompareOpForVector(const APValue &LHSValue,
3138 BinaryOperatorKind Opcode,
3139 const APValue &RHSValue, APInt &Result) {
3140 // The result is always an int type, however operands match the first.
3141 if (LHSValue.getKind() == APValue::Int)
3142 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3143 RHSValue.getInt(), Result);
3144 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3145 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3146 RHSValue.getFloat(), Result);
3147}
3148
3149// Perform binary operations for vector types, in place on the LHS.
3150static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3151 BinaryOperatorKind Opcode,
3152 APValue &LHSValue,
3153 const APValue &RHSValue) {
3154 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3155 "Operation not supported on vector types");
3156
3157 const auto *VT = E->getType()->castAs<VectorType>();
3158 unsigned NumElements = VT->getNumElements();
3159 QualType EltTy = VT->getElementType();
3160
3161 // In the cases (typically C as I've observed) where we aren't evaluating
3162 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3163 // just give up.
3164 if (!LHSValue.isVector()) {
3165 assert(LHSValue.isLValue() &&
3166 "A vector result that isn't a vector OR uncalculated LValue");
3167 Info.FFDiag(E);
3168 return false;
3169 }
3170
3171 assert(LHSValue.getVectorLength() == NumElements &&
3172 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3173
3174 SmallVector<APValue, 4> ResultElements;
3175
3176 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3177 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3178 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3179
3180 if (EltTy->isIntegerType()) {
3181 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3182 EltTy->isUnsignedIntegerType()};
3183 bool Success = true;
3184
3185 if (BinaryOperator::isLogicalOp(Opcode))
3186 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3187 else if (BinaryOperator::isComparisonOp(Opcode))
3188 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3189 else
3190 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3191 RHSElt.getInt(), EltResult);
3192
3193 if (!Success) {
3194 Info.FFDiag(E);
3195 return false;
3196 }
3197 ResultElements.emplace_back(EltResult);
3198
3199 } else if (EltTy->isFloatingType()) {
3200 assert(LHSElt.getKind() == APValue::Float &&
3201 RHSElt.getKind() == APValue::Float &&
3202 "Mismatched LHS/RHS/Result Type");
3203 APFloat LHSFloat = LHSElt.getFloat();
3204
3205 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3206 RHSElt.getFloat())) {
3207 Info.FFDiag(E);
3208 return false;
3209 }
3210
3211 ResultElements.emplace_back(LHSFloat);
3212 }
3213 }
3214
3215 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3216 return true;
3217}
3218
3219/// Cast an lvalue referring to a base subobject to a derived class, by
3220/// truncating the lvalue's path to the given length.
3221static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3222 const RecordDecl *TruncatedType,
3223 unsigned TruncatedElements) {
3224 SubobjectDesignator &D = Result.Designator;
3225
3226 // Check we actually point to a derived class object.
3227 if (TruncatedElements == D.Entries.size())
3228 return true;
3229 assert(TruncatedElements >= D.MostDerivedPathLength &&
3230 "not casting to a derived class");
3231 if (!Result.checkSubobject(Info, E, CSK_Derived))
3232 return false;
3233
3234 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3235 const RecordDecl *RD = TruncatedType;
3236 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3237 if (RD->isInvalidDecl()) return false;
3238 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3239 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3240 if (isVirtualBaseClass(D.Entries[I]))
3241 Result.Offset -= Layout.getVBaseClassOffset(Base);
3242 else
3243 Result.Offset -= Layout.getBaseClassOffset(Base);
3244 RD = Base;
3245 }
3246 D.Entries.resize(TruncatedElements);
3247 return true;
3248}
3249
3250static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3251 const CXXRecordDecl *Derived,
3252 const CXXRecordDecl *Base,
3253 const ASTRecordLayout *RL = nullptr) {
3254 if (!RL) {
3255 if (Derived->isInvalidDecl()) return false;
3256 RL = &Info.Ctx.getASTRecordLayout(Derived);
3257 }
3258
3259 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3260 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3261 return true;
3262}
3263
3264static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3265 const CXXRecordDecl *DerivedDecl,
3266 const CXXBaseSpecifier *Base) {
3267 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3268
3269 if (!Base->isVirtual())
3270 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3271
3272 SubobjectDesignator &D = Obj.Designator;
3273 if (D.Invalid)
3274 return false;
3275
3276 // Extract most-derived object and corresponding type.
3277 // FIXME: After implementing P2280R4 it became possible to get references
3278 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3279 // locations and if we see crashes in those locations in the future
3280 // it may make more sense to move this fix into Lvalue::set.
3281 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3282 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3283 return false;
3284
3285 // Find the virtual base class.
3286 if (DerivedDecl->isInvalidDecl()) return false;
3287 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3289 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3290 return true;
3291}
3292
3293static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3294 QualType Type, LValue &Result) {
3295 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3296 PathE = E->path_end();
3297 PathI != PathE; ++PathI) {
3298 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3299 *PathI))
3300 return false;
3301 Type = (*PathI)->getType();
3302 }
3303 return true;
3304}
3305
3306/// Cast an lvalue referring to a derived class to a known base subobject.
3307static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3308 const CXXRecordDecl *DerivedRD,
3309 const CXXRecordDecl *BaseRD) {
3310 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3311 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3312 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3313 llvm_unreachable("Class must be derived from the passed in base class!");
3314
3315 for (CXXBasePathElement &Elem : Paths.front())
3316 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3317 return false;
3318 return true;
3319}
3320
3321/// Update LVal to refer to the given field, which must be a member of the type
3322/// currently described by LVal.
3323static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3324 const FieldDecl *FD,
3325 const ASTRecordLayout *RL = nullptr) {
3326 if (!RL) {
3327 if (FD->getParent()->isInvalidDecl()) return false;
3328 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3329 }
3330
3331 unsigned I = FD->getFieldIndex();
3332 LVal.addDecl(Info, E, FD);
3333 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3334 return true;
3335}
3336
3337/// Update LVal to refer to the given indirect field.
3338static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3339 LValue &LVal,
3340 const IndirectFieldDecl *IFD) {
3341 for (const auto *C : IFD->chain())
3342 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3343 return false;
3344 return true;
3345}
3346
3351
3352/// Get the size of the given type in char units.
3353static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3356 // extension.
3357 if (Type->isVoidType() || Type->isFunctionType()) {
3358 Size = CharUnits::One();
3359 return true;
3360 }
3361
3362 if (Type->isDependentType()) {
3363 Info.FFDiag(Loc);
3364 return false;
3365 }
3366
3367 if (!Type->isConstantSizeType()) {
3368 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3369 // FIXME: Better diagnostic.
3370 Info.FFDiag(Loc);
3371 return false;
3372 }
3373
3374 if (SOT == SizeOfType::SizeOf)
3375 Size = Info.Ctx.getTypeSizeInChars(Type);
3376 else
3377 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3378 return true;
3379}
3380
3381/// Update a pointer value to model pointer arithmetic.
3382/// \param Info - Information about the ongoing evaluation.
3383/// \param E - The expression being evaluated, for diagnostic purposes.
3384/// \param LVal - The pointer value to be updated.
3385/// \param EltTy - The pointee type represented by LVal.
3386/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3387static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3388 LValue &LVal, QualType EltTy,
3389 APSInt Adjustment) {
3390 CharUnits SizeOfPointee;
3391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3392 return false;
3393
3394 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3395 return true;
3396}
3397
3398static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3399 LValue &LVal, QualType EltTy,
3400 int64_t Adjustment) {
3401 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3402 APSInt::get(Adjustment));
3403}
3404
3405/// Update an lvalue to refer to a component of a complex number.
3406/// \param Info - Information about the ongoing evaluation.
3407/// \param LVal - The lvalue to be updated.
3408/// \param EltTy - The complex number's component type.
3409/// \param Imag - False for the real component, true for the imaginary.
3410static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3411 LValue &LVal, QualType EltTy,
3412 bool Imag) {
3413 if (Imag) {
3414 CharUnits SizeOfComponent;
3415 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3416 return false;
3417 LVal.Offset += SizeOfComponent;
3418 }
3419 LVal.addComplex(Info, E, EltTy, Imag);
3420 return true;
3421}
3422
3423static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3424 LValue &LVal, QualType EltTy,
3425 uint64_t Size, uint64_t Idx) {
3426 if (Idx) {
3427 CharUnits SizeOfElement;
3428 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3429 return false;
3430 LVal.Offset += SizeOfElement * Idx;
3431 }
3432 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3433 return true;
3434}
3435
3436/// Try to evaluate the initializer for a variable declaration.
3437///
3438/// \param Info Information about the ongoing evaluation.
3439/// \param E An expression to be used when printing diagnostics.
3440/// \param VD The variable whose initializer should be obtained.
3441/// \param Version The version of the variable within the frame.
3442/// \param Frame The frame in which the variable was created. Must be null
3443/// if this variable is not local to the evaluation.
3444/// \param Result Filled in with a pointer to the value of the variable.
3445static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3446 const VarDecl *VD, CallStackFrame *Frame,
3447 unsigned Version, APValue *&Result) {
3448 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3449 // and pointers.
3450 bool AllowConstexprUnknown =
3451 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3452
3453 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3454
3455 auto CheckUninitReference = [&](bool IsLocalVariable) {
3456 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3457 // C++23 [expr.const]p8
3458 // ... For such an object that is not usable in constant expressions, the
3459 // dynamic type of the object is constexpr-unknown. For such a reference
3460 // that is not usable in constant expressions, the reference is treated
3461 // as binding to an unspecified object of the referenced type whose
3462 // lifetime and that of all subobjects includes the entire constant
3463 // evaluation and whose dynamic type is constexpr-unknown.
3464 //
3465 // Variables that are part of the current evaluation are not
3466 // constexpr-unknown.
3467 if (!AllowConstexprUnknown || IsLocalVariable) {
3468 if (!Info.checkingPotentialConstantExpression())
3469 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3470 return false;
3471 }
3472 Result = nullptr;
3473 }
3474 return true;
3475 };
3476
3477 // If this is a local variable, dig out its value.
3478 if (Frame) {
3479 Result = Frame->getTemporary(VD, Version);
3480 if (Result)
3481 return CheckUninitReference(/*IsLocalVariable=*/true);
3482
3483 if (!isa<ParmVarDecl>(VD)) {
3484 // Assume variables referenced within a lambda's call operator that were
3485 // not declared within the call operator are captures and during checking
3486 // of a potential constant expression, assume they are unknown constant
3487 // expressions.
3488 assert(isLambdaCallOperator(Frame->Callee) &&
3489 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3490 "missing value for local variable");
3491 if (Info.checkingPotentialConstantExpression())
3492 return false;
3493 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3494 // still reachable at all?
3495 Info.FFDiag(E->getBeginLoc(),
3496 diag::note_unimplemented_constexpr_lambda_feature_ast)
3497 << "captures not currently allowed";
3498 return false;
3499 }
3500 }
3501
3502 // If we're currently evaluating the initializer of this declaration, use that
3503 // in-flight value.
3504 if (Info.EvaluatingDecl == Base) {
3505 Result = Info.EvaluatingDeclValue;
3506 return CheckUninitReference(/*IsLocalVariable=*/false);
3507 }
3508
3509 // P2280R4 struck the restriction that variable of reference type lifetime
3510 // should begin within the evaluation of E
3511 // Used to be C++20 [expr.const]p5.12.2:
3512 // ... its lifetime began within the evaluation of E;
3513 if (isa<ParmVarDecl>(VD)) {
3514 if (AllowConstexprUnknown) {
3515 Result = nullptr;
3516 return true;
3517 }
3518
3519 // Assume parameters of a potential constant expression are usable in
3520 // constant expressions.
3521 if (!Info.checkingPotentialConstantExpression() ||
3522 !Info.CurrentCall->Callee ||
3523 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3524 if (Info.getLangOpts().CPlusPlus11) {
3525 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3526 << VD;
3527 NoteLValueLocation(Info, Base);
3528 } else {
3529 Info.FFDiag(E);
3530 }
3531 }
3532 return false;
3533 }
3534
3535 if (E->isValueDependent())
3536 return false;
3537
3538 // Dig out the initializer, and use the declaration which it's attached to.
3539 // FIXME: We should eventually check whether the variable has a reachable
3540 // initializing declaration.
3541 const Expr *Init = VD->getAnyInitializer(VD);
3542 // P2280R4 struck the restriction that variable of reference type should have
3543 // a preceding initialization.
3544 // Used to be C++20 [expr.const]p5.12:
3545 // ... reference has a preceding initialization and either ...
3546 if (!Init && !AllowConstexprUnknown) {
3547 // Don't diagnose during potential constant expression checking; an
3548 // initializer might be added later.
3549 if (!Info.checkingPotentialConstantExpression()) {
3550 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3551 << VD;
3552 NoteLValueLocation(Info, Base);
3553 }
3554 return false;
3555 }
3556
3557 // P2280R4 struck the initialization requirement for variables of reference
3558 // type so we can no longer assume we have an Init.
3559 // Used to be C++20 [expr.const]p5.12:
3560 // ... reference has a preceding initialization and either ...
3561 if (Init && Init->isValueDependent()) {
3562 // The DeclRefExpr is not value-dependent, but the variable it refers to
3563 // has a value-dependent initializer. This should only happen in
3564 // constant-folding cases, where the variable is not actually of a suitable
3565 // type for use in a constant expression (otherwise the DeclRefExpr would
3566 // have been value-dependent too), so diagnose that.
3567 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3568 if (!Info.checkingPotentialConstantExpression()) {
3569 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3570 ? diag::note_constexpr_ltor_non_constexpr
3571 : diag::note_constexpr_ltor_non_integral, 1)
3572 << VD << VD->getType();
3573 NoteLValueLocation(Info, Base);
3574 }
3575 return false;
3576 }
3577
3578 // Check that we can fold the initializer. In C++, we will have already done
3579 // this in the cases where it matters for conformance.
3580 // P2280R4 struck the initialization requirement for variables of reference
3581 // type so we can no longer assume we have an Init.
3582 // Used to be C++20 [expr.const]p5.12:
3583 // ... reference has a preceding initialization and either ...
3584 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3585 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3586 NoteLValueLocation(Info, Base);
3587 return false;
3588 }
3589
3590 // Check that the variable is actually usable in constant expressions. For a
3591 // const integral variable or a reference, we might have a non-constant
3592 // initializer that we can nonetheless evaluate the initializer for. Such
3593 // variables are not usable in constant expressions. In C++98, the
3594 // initializer also syntactically needs to be an ICE.
3595 //
3596 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3597 // expressions here; doing so would regress diagnostics for things like
3598 // reading from a volatile constexpr variable.
3599 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3600 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3601 !AllowConstexprUnknown) ||
3602 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3603 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3604 if (Init) {
3605 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3606 NoteLValueLocation(Info, Base);
3607 } else {
3608 Info.CCEDiag(E);
3609 }
3610 }
3611
3612 // Never use the initializer of a weak variable, not even for constant
3613 // folding. We can't be sure that this is the definition that will be used.
3614 if (VD->isWeak()) {
3615 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3616 NoteLValueLocation(Info, Base);
3617 return false;
3618 }
3619
3620 Result = VD->getEvaluatedValue();
3621
3622 if (!Result && !AllowConstexprUnknown)
3623 return false;
3624
3625 return CheckUninitReference(/*IsLocalVariable=*/false);
3626}
3627
3628/// Get the base index of the given base class within an APValue representing
3629/// the given derived class.
3630static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3631 const CXXRecordDecl *Base) {
3632 Base = Base->getCanonicalDecl();
3633 unsigned Index = 0;
3635 E = Derived->bases_end(); I != E; ++I, ++Index) {
3636 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3637 return Index;
3638 }
3639
3640 llvm_unreachable("base class missing from derived class's bases list");
3641}
3642
3643/// Extract the value of a character from a string literal.
3644static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3645 uint64_t Index) {
3646 assert(!isa<SourceLocExpr>(Lit) &&
3647 "SourceLocExpr should have already been converted to a StringLiteral");
3648
3649 // FIXME: Support MakeStringConstant
3650 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3651 std::string Str;
3652 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3653 assert(Index <= Str.size() && "Index too large");
3654 return APSInt::getUnsigned(Str.c_str()[Index]);
3655 }
3656
3657 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3658 Lit = PE->getFunctionName();
3659 const StringLiteral *S = cast<StringLiteral>(Lit);
3660 const ConstantArrayType *CAT =
3661 Info.Ctx.getAsConstantArrayType(S->getType());
3662 assert(CAT && "string literal isn't an array");
3663 QualType CharType = CAT->getElementType();
3664 assert(CharType->isIntegerType() && "unexpected character type");
3665 APSInt Value(Info.Ctx.getTypeSize(CharType),
3666 CharType->isUnsignedIntegerType());
3667 if (Index < S->getLength())
3668 Value = S->getCodeUnit(Index);
3669 return Value;
3670}
3671
3672// Expand a string literal into an array of characters.
3673//
3674// FIXME: This is inefficient; we should probably introduce something similar
3675// to the LLVM ConstantDataArray to make this cheaper.
3676static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3677 APValue &Result,
3678 QualType AllocType = QualType()) {
3679 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3680 AllocType.isNull() ? S->getType() : AllocType);
3681 assert(CAT && "string literal isn't an array");
3682 QualType CharType = CAT->getElementType();
3683 assert(CharType->isIntegerType() && "unexpected character type");
3684
3685 unsigned Elts = CAT->getZExtSize();
3686 Result = APValue(APValue::UninitArray(),
3687 std::min(S->getLength(), Elts), Elts);
3688 APSInt Value(Info.Ctx.getTypeSize(CharType),
3689 CharType->isUnsignedIntegerType());
3690 if (Result.hasArrayFiller())
3691 Result.getArrayFiller() = APValue(Value);
3692 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3693 Value = S->getCodeUnit(I);
3694 Result.getArrayInitializedElt(I) = APValue(Value);
3695 }
3696}
3697
3698// Expand an array so that it has more than Index filled elements.
3699static void expandArray(APValue &Array, unsigned Index) {
3700 unsigned Size = Array.getArraySize();
3701 assert(Index < Size);
3702
3703 // Always at least double the number of elements for which we store a value.
3704 unsigned OldElts = Array.getArrayInitializedElts();
3705 unsigned NewElts = std::max(Index+1, OldElts * 2);
3706 NewElts = std::min(Size, std::max(NewElts, 8u));
3707
3708 // Copy the data across.
3709 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3710 for (unsigned I = 0; I != OldElts; ++I)
3711 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3712 for (unsigned I = OldElts; I != NewElts; ++I)
3713 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3714 if (NewValue.hasArrayFiller())
3715 NewValue.getArrayFiller() = Array.getArrayFiller();
3716 Array.swap(NewValue);
3717}
3718
3719/// Determine whether a type would actually be read by an lvalue-to-rvalue
3720/// conversion. If it's of class type, we may assume that the copy operation
3721/// is trivial. Note that this is never true for a union type with fields
3722/// (because the copy always "reads" the active member) and always true for
3723/// a non-class type.
3724static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3726 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3727 return !RD || isReadByLvalueToRvalueConversion(RD);
3728}
3730 // FIXME: A trivial copy of a union copies the object representation, even if
3731 // the union is empty.
3732 if (RD->isUnion())
3733 return !RD->field_empty();
3734 if (RD->isEmpty())
3735 return false;
3736
3737 for (auto *Field : RD->fields())
3738 if (!Field->isUnnamedBitField() &&
3739 isReadByLvalueToRvalueConversion(Field->getType()))
3740 return true;
3741
3742 for (auto &BaseSpec : RD->bases())
3743 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3744 return true;
3745
3746 return false;
3747}
3748
3749/// Diagnose an attempt to read from any unreadable field within the specified
3750/// type, which might be a class type.
3751static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3752 QualType T) {
3753 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3754 if (!RD)
3755 return false;
3756
3757 if (!RD->hasMutableFields())
3758 return false;
3759
3760 for (auto *Field : RD->fields()) {
3761 // If we're actually going to read this field in some way, then it can't
3762 // be mutable. If we're in a union, then assigning to a mutable field
3763 // (even an empty one) can change the active member, so that's not OK.
3764 // FIXME: Add core issue number for the union case.
3765 if (Field->isMutable() &&
3766 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3767 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3768 Info.Note(Field->getLocation(), diag::note_declared_at);
3769 return true;
3770 }
3771
3772 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3773 return true;
3774 }
3775
3776 for (auto &BaseSpec : RD->bases())
3777 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3778 return true;
3779
3780 // All mutable fields were empty, and thus not actually read.
3781 return false;
3782}
3783
3784static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3786 bool MutableSubobject = false) {
3787 // A temporary or transient heap allocation we created.
3788 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3789 return true;
3790
3791 switch (Info.IsEvaluatingDecl) {
3792 case EvalInfo::EvaluatingDeclKind::None:
3793 return false;
3794
3795 case EvalInfo::EvaluatingDeclKind::Ctor:
3796 // The variable whose initializer we're evaluating.
3797 if (Info.EvaluatingDecl == Base)
3798 return true;
3799
3800 // A temporary lifetime-extended by the variable whose initializer we're
3801 // evaluating.
3802 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3803 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3804 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3805 return false;
3806
3807 case EvalInfo::EvaluatingDeclKind::Dtor:
3808 // C++2a [expr.const]p6:
3809 // [during constant destruction] the lifetime of a and its non-mutable
3810 // subobjects (but not its mutable subobjects) [are] considered to start
3811 // within e.
3812 if (MutableSubobject || Base != Info.EvaluatingDecl)
3813 return false;
3814 // FIXME: We can meaningfully extend this to cover non-const objects, but
3815 // we will need special handling: we should be able to access only
3816 // subobjects of such objects that are themselves declared const.
3818 return T.isConstQualified() || T->isReferenceType();
3819 }
3820
3821 llvm_unreachable("unknown evaluating decl kind");
3822}
3823
3824static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3825 SourceLocation CallLoc = {}) {
3826 return Info.CheckArraySize(
3827 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3828 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3829 /*Diag=*/true);
3830}
3831
3832static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3833 QualType SourceTy, QualType DestTy,
3834 APValue const &Original, APValue &Result) {
3835 // boolean must be checked before integer
3836 // since IsIntegerType() is true for bool
3837 if (SourceTy->isBooleanType()) {
3838 if (DestTy->isBooleanType()) {
3839 Result = Original;
3840 return true;
3841 }
3842 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3843 bool BoolResult;
3844 if (!HandleConversionToBool(Original, BoolResult))
3845 return false;
3846 uint64_t IntResult = BoolResult;
3847 QualType IntType = DestTy->isIntegerType()
3848 ? DestTy
3849 : Info.Ctx.getIntTypeForBitwidth(64, false);
3850 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3851 }
3852 if (DestTy->isRealFloatingType()) {
3853 APValue Result2 = APValue(APFloat(0.0));
3854 if (!HandleIntToFloatCast(Info, E, FPO,
3855 Info.Ctx.getIntTypeForBitwidth(64, false),
3856 Result.getInt(), DestTy, Result2.getFloat()))
3857 return false;
3858 Result = Result2;
3859 }
3860 return true;
3861 }
3862 if (SourceTy->isIntegerType()) {
3863 if (DestTy->isRealFloatingType()) {
3864 Result = APValue(APFloat(0.0));
3865 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3866 DestTy, Result.getFloat());
3867 }
3868 if (DestTy->isBooleanType()) {
3869 bool BoolResult;
3870 if (!HandleConversionToBool(Original, BoolResult))
3871 return false;
3872 uint64_t IntResult = BoolResult;
3873 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3874 return true;
3875 }
3876 if (DestTy->isIntegerType()) {
3877 Result = APValue(
3878 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3879 return true;
3880 }
3881 } else if (SourceTy->isRealFloatingType()) {
3882 if (DestTy->isRealFloatingType()) {
3883 Result = Original;
3884 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3885 Result.getFloat());
3886 }
3887 if (DestTy->isBooleanType()) {
3888 bool BoolResult;
3889 if (!HandleConversionToBool(Original, BoolResult))
3890 return false;
3891 uint64_t IntResult = BoolResult;
3892 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3893 return true;
3894 }
3895 if (DestTy->isIntegerType()) {
3896 Result = APValue(APSInt());
3897 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3898 DestTy, Result.getInt());
3899 }
3900 }
3901
3902 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3903 return false;
3904}
3905
3906// do the heavy lifting for casting to aggregate types
3907// because we have to deal with bitfields specially
3908static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3909 const Expr *E, APValue &Result,
3910 QualType ResultType,
3911 SmallVectorImpl<APValue> &Elements,
3912 SmallVectorImpl<QualType> &ElTypes) {
3913
3915 {&Result, ResultType, 0}};
3916
3917 unsigned ElI = 0;
3918 while (!WorkList.empty() && ElI < Elements.size()) {
3919 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3920
3921 if (Type->isRealFloatingType()) {
3922 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3923 *Res))
3924 return false;
3925 ElI++;
3926 continue;
3927 }
3928 if (Type->isIntegerType()) {
3929 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3930 *Res))
3931 return false;
3932 if (BitWidth > 0) {
3933 if (!Res->isInt())
3934 return false;
3935 APSInt &Int = Res->getInt();
3936 unsigned OldBitWidth = Int.getBitWidth();
3937 unsigned NewBitWidth = BitWidth;
3938 if (NewBitWidth < OldBitWidth)
3939 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3940 }
3941 ElI++;
3942 continue;
3943 }
3944 if (Type->isVectorType()) {
3945 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3946 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3947 SmallVector<APValue> Vals(NumEl);
3948 for (unsigned I = 0; I < NumEl; ++I) {
3949 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3950 Vals[I]))
3951 return false;
3952 ElI++;
3953 }
3954 *Res = APValue(Vals.data(), NumEl);
3955 continue;
3956 }
3957 if (Type->isConstantArrayType()) {
3959 ->getElementType();
3960 uint64_t Size =
3961 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3962 *Res = APValue(APValue::UninitArray(), Size, Size);
3963 for (int64_t I = Size - 1; I > -1; --I)
3964 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3965 continue;
3966 }
3967 if (Type->isRecordType()) {
3968 const RecordDecl *RD = Type->getAsRecordDecl();
3969
3970 unsigned NumBases = 0;
3971 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3972 NumBases = CXXRD->getNumBases();
3973
3974 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3975
3977 // we need to traverse backwards
3978 // Visit the base classes.
3979 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3980 if (CXXRD->getNumBases() > 0) {
3981 assert(CXXRD->getNumBases() == 1);
3982 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3983 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3984 }
3985 }
3986
3987 // Visit the fields.
3988 for (FieldDecl *FD : RD->fields()) {
3989 unsigned FDBW = 0;
3990 if (FD->isUnnamedBitField())
3991 continue;
3992 if (FD->isBitField()) {
3993 FDBW = FD->getBitWidthValue();
3994 }
3995
3996 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3997 FD->getType(), FDBW);
3998 }
3999
4000 std::reverse(ReverseList.begin(), ReverseList.end());
4001 llvm::append_range(WorkList, ReverseList);
4002 continue;
4003 }
4004 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4005 return false;
4006 }
4007 return true;
4008}
4009
4010static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
4011 const FPOptions FPO,
4012 SmallVectorImpl<APValue> &Elements,
4013 SmallVectorImpl<QualType> &SrcTypes,
4014 SmallVectorImpl<QualType> &DestTypes,
4015 SmallVectorImpl<APValue> &Results) {
4016
4017 assert((Elements.size() == SrcTypes.size()) &&
4018 (Elements.size() == DestTypes.size()));
4019
4020 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4021 APValue Original = Elements[I];
4022 QualType SourceTy = SrcTypes[I];
4023 QualType DestTy = DestTypes[I];
4024
4025 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4026 return false;
4027 }
4028 return true;
4029}
4030
4031static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
4032
4033 SmallVector<QualType> WorkList = {BaseTy};
4034
4035 unsigned Size = 0;
4036 while (!WorkList.empty()) {
4037 QualType Type = WorkList.pop_back_val();
4039 Type->isBooleanType()) {
4040 ++Size;
4041 continue;
4042 }
4043 if (Type->isVectorType()) {
4044 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4045 Size += NumEl;
4046 continue;
4047 }
4048 if (Type->isConstantArrayType()) {
4050 ->getElementType();
4051 uint64_t ArrSize =
4052 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4053 for (uint64_t I = 0; I < ArrSize; ++I) {
4054 WorkList.push_back(ElTy);
4055 }
4056 continue;
4057 }
4058 if (Type->isRecordType()) {
4059 const RecordDecl *RD = Type->getAsRecordDecl();
4060
4061 // Visit the base classes.
4062 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4063 if (CXXRD->getNumBases() > 0) {
4064 assert(CXXRD->getNumBases() == 1);
4065 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4066 WorkList.push_back(BS.getType());
4067 }
4068 }
4069
4070 // visit the fields.
4071 for (FieldDecl *FD : RD->fields()) {
4072 if (FD->isUnnamedBitField())
4073 continue;
4074 WorkList.push_back(FD->getType());
4075 }
4076 continue;
4077 }
4078 }
4079 return Size;
4080}
4081
4082static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4083 QualType &SrcTy) {
4084 SrcTy = E->getType();
4085
4086 if (!Evaluate(SrcVal, Info, E))
4087 return false;
4088
4089 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4090 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4091 "Not a valid HLSLAggregateSplatCast.");
4092
4093 if (SrcVal.isVector()) {
4094 assert(SrcTy->isVectorType() && "Type mismatch.");
4095 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4096 SrcVal = SrcVal.getVectorElt(0);
4097 }
4098 return true;
4099}
4100
4101static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4102 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4103 SmallVectorImpl<QualType> &Types, unsigned Size) {
4104
4105 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4106 unsigned Populated = 0;
4107 while (!WorkList.empty() && Populated < Size) {
4108 auto [Work, Type] = WorkList.pop_back_val();
4109
4110 if (Work.isFloat() || Work.isInt()) {
4111 Elements.push_back(Work);
4112 Types.push_back(Type);
4113 Populated++;
4114 continue;
4115 }
4116 if (Work.isVector()) {
4117 assert(Type->isVectorType() && "Type mismatch.");
4118 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4119 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4120 I++) {
4121 Elements.push_back(Work.getVectorElt(I));
4122 Types.push_back(ElTy);
4123 Populated++;
4124 }
4125 continue;
4126 }
4127 if (Work.isArray()) {
4128 assert(Type->isConstantArrayType() && "Type mismatch.");
4130 ->getElementType();
4131 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4132 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4133 }
4134 continue;
4135 }
4136
4137 if (Work.isStruct()) {
4138 assert(Type->isRecordType() && "Type mismatch.");
4139
4140 const RecordDecl *RD = Type->getAsRecordDecl();
4141
4143 // Visit the fields.
4144 for (FieldDecl *FD : RD->fields()) {
4145 if (FD->isUnnamedBitField())
4146 continue;
4147 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4148 FD->getType());
4149 }
4150
4151 std::reverse(ReverseList.begin(), ReverseList.end());
4152 llvm::append_range(WorkList, ReverseList);
4153
4154 // Visit the base classes.
4155 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4156 if (CXXRD->getNumBases() > 0) {
4157 assert(CXXRD->getNumBases() == 1);
4158 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4159 const APValue &Base = Work.getStructBase(0);
4160
4161 // Can happen in error cases.
4162 if (!Base.isStruct())
4163 return false;
4164
4165 WorkList.emplace_back(Base, BS.getType());
4166 }
4167 }
4168 continue;
4169 }
4170 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4171 return false;
4172 }
4173 return true;
4174}
4175
4176namespace {
4177/// A handle to a complete object (an object that is not a subobject of
4178/// another object).
4179struct CompleteObject {
4180 /// The identity of the object.
4181 APValue::LValueBase Base;
4182 /// The value of the complete object.
4183 APValue *Value;
4184 /// The type of the complete object.
4185 QualType Type;
4186
4187 CompleteObject() : Value(nullptr) {}
4188 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4189 : Base(Base), Value(Value), Type(Type) {}
4190
4191 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4192 // If this isn't a "real" access (eg, if it's just accessing the type
4193 // info), allow it. We assume the type doesn't change dynamically for
4194 // subobjects of constexpr objects (even though we'd hit UB here if it
4195 // did). FIXME: Is this right?
4196 if (!isAnyAccess(AK))
4197 return true;
4198
4199 // In C++14 onwards, it is permitted to read a mutable member whose
4200 // lifetime began within the evaluation.
4201 // FIXME: Should we also allow this in C++11?
4202 if (!Info.getLangOpts().CPlusPlus14 &&
4203 AK != AccessKinds::AK_IsWithinLifetime)
4204 return false;
4205 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4206 }
4207
4208 explicit operator bool() const { return !Type.isNull(); }
4209};
4210} // end anonymous namespace
4211
4212static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4213 bool IsMutable = false) {
4214 // C++ [basic.type.qualifier]p1:
4215 // - A const object is an object of type const T or a non-mutable subobject
4216 // of a const object.
4217 if (ObjType.isConstQualified() && !IsMutable)
4218 SubobjType.addConst();
4219 // - A volatile object is an object of type const T or a subobject of a
4220 // volatile object.
4221 if (ObjType.isVolatileQualified())
4222 SubobjType.addVolatile();
4223 return SubobjType;
4224}
4225
4226/// Find the designated sub-object of an rvalue.
4227template <typename SubobjectHandler>
4228static typename SubobjectHandler::result_type
4229findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4230 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4231 if (Sub.Invalid)
4232 // A diagnostic will have already been produced.
4233 return handler.failed();
4234 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4235 if (Info.getLangOpts().CPlusPlus11)
4236 Info.FFDiag(E, Sub.isOnePastTheEnd()
4237 ? diag::note_constexpr_access_past_end
4238 : diag::note_constexpr_access_unsized_array)
4239 << handler.AccessKind;
4240 else
4241 Info.FFDiag(E);
4242 return handler.failed();
4243 }
4244
4245 APValue *O = Obj.Value;
4246 QualType ObjType = Obj.Type;
4247 const FieldDecl *LastField = nullptr;
4248 const FieldDecl *VolatileField = nullptr;
4249
4250 // Walk the designator's path to find the subobject.
4251 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4252 // Reading an indeterminate value is undefined, but assigning over one is OK.
4253 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4254 (O->isIndeterminate() &&
4255 !isValidIndeterminateAccess(handler.AccessKind))) {
4256 // Object has ended lifetime.
4257 // If I is non-zero, some subobject (member or array element) of a
4258 // complete object has ended its lifetime, so this is valid for
4259 // IsWithinLifetime, resulting in false.
4260 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4261 return false;
4262 if (!Info.checkingPotentialConstantExpression())
4263 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4264 << handler.AccessKind << O->isIndeterminate()
4265 << E->getSourceRange();
4266 return handler.failed();
4267 }
4268
4269 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4270 // const and volatile semantics are not applied on an object under
4271 // {con,de}struction.
4272 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4273 ObjType->isRecordType() &&
4274 Info.isEvaluatingCtorDtor(
4275 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4276 ConstructionPhase::None) {
4277 ObjType = Info.Ctx.getCanonicalType(ObjType);
4278 ObjType.removeLocalConst();
4279 ObjType.removeLocalVolatile();
4280 }
4281
4282 // If this is our last pass, check that the final object type is OK.
4283 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4284 // Accesses to volatile objects are prohibited.
4285 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4286 if (Info.getLangOpts().CPlusPlus) {
4287 int DiagKind;
4288 SourceLocation Loc;
4289 const NamedDecl *Decl = nullptr;
4290 if (VolatileField) {
4291 DiagKind = 2;
4292 Loc = VolatileField->getLocation();
4293 Decl = VolatileField;
4294 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4295 DiagKind = 1;
4296 Loc = VD->getLocation();
4297 Decl = VD;
4298 } else {
4299 DiagKind = 0;
4300 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4301 Loc = E->getExprLoc();
4302 }
4303 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4304 << handler.AccessKind << DiagKind << Decl;
4305 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4306 } else {
4307 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4308 }
4309 return handler.failed();
4310 }
4311
4312 // If we are reading an object of class type, there may still be more
4313 // things we need to check: if there are any mutable subobjects, we
4314 // cannot perform this read. (This only happens when performing a trivial
4315 // copy or assignment.)
4316 if (ObjType->isRecordType() &&
4317 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4318 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4319 return handler.failed();
4320 }
4321
4322 if (I == N) {
4323 if (!handler.found(*O, ObjType))
4324 return false;
4325
4326 // If we modified a bit-field, truncate it to the right width.
4327 if (isModification(handler.AccessKind) &&
4328 LastField && LastField->isBitField() &&
4329 !truncateBitfieldValue(Info, E, *O, LastField))
4330 return false;
4331
4332 return true;
4333 }
4334
4335 LastField = nullptr;
4336 if (ObjType->isArrayType()) {
4337 // Next subobject is an array element.
4338 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4340 "vla in literal type?");
4341 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4342 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4343 CAT && CAT->getSize().ule(Index)) {
4344 // Note, it should not be possible to form a pointer with a valid
4345 // designator which points more than one past the end of the array.
4346 if (Info.getLangOpts().CPlusPlus11)
4347 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4348 << handler.AccessKind;
4349 else
4350 Info.FFDiag(E);
4351 return handler.failed();
4352 }
4353
4354 ObjType = AT->getElementType();
4355
4356 if (O->getArrayInitializedElts() > Index)
4357 O = &O->getArrayInitializedElt(Index);
4358 else if (!isRead(handler.AccessKind)) {
4359 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4360 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4361 return handler.failed();
4362
4363 expandArray(*O, Index);
4364 O = &O->getArrayInitializedElt(Index);
4365 } else
4366 O = &O->getArrayFiller();
4367 } else if (ObjType->isAnyComplexType()) {
4368 // Next subobject is a complex number.
4369 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4370 if (Index > 1) {
4371 if (Info.getLangOpts().CPlusPlus11)
4372 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4373 << handler.AccessKind;
4374 else
4375 Info.FFDiag(E);
4376 return handler.failed();
4377 }
4378
4379 ObjType = getSubobjectType(
4380 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4381
4382 assert(I == N - 1 && "extracting subobject of scalar?");
4383 if (O->isComplexInt()) {
4384 return handler.found(Index ? O->getComplexIntImag()
4385 : O->getComplexIntReal(), ObjType);
4386 } else {
4387 assert(O->isComplexFloat());
4388 return handler.found(Index ? O->getComplexFloatImag()
4389 : O->getComplexFloatReal(), ObjType);
4390 }
4391 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4392 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4393 unsigned NumElements = VT->getNumElements();
4394 if (Index == NumElements) {
4395 if (Info.getLangOpts().CPlusPlus11)
4396 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4397 << handler.AccessKind;
4398 else
4399 Info.FFDiag(E);
4400 return handler.failed();
4401 }
4402
4403 if (Index > NumElements) {
4404 Info.CCEDiag(E, diag::note_constexpr_array_index)
4405 << Index << /*array*/ 0 << NumElements;
4406 return handler.failed();
4407 }
4408
4409 ObjType = VT->getElementType();
4410 assert(I == N - 1 && "extracting subobject of scalar?");
4411 return handler.found(O->getVectorElt(Index), ObjType);
4412 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4413 if (Field->isMutable() &&
4414 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4415 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4416 << handler.AccessKind << Field;
4417 Info.Note(Field->getLocation(), diag::note_declared_at);
4418 return handler.failed();
4419 }
4420
4421 // Next subobject is a class, struct or union field.
4422 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4423 if (RD->isUnion()) {
4424 const FieldDecl *UnionField = O->getUnionField();
4425 if (!UnionField ||
4426 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4427 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4428 // Placement new onto an inactive union member makes it active.
4429 O->setUnion(Field, APValue());
4430 } else {
4431 // Pointer to/into inactive union member: Not within lifetime
4432 if (handler.AccessKind == AK_IsWithinLifetime)
4433 return false;
4434 // FIXME: If O->getUnionValue() is absent, report that there's no
4435 // active union member rather than reporting the prior active union
4436 // member. We'll need to fix nullptr_t to not use APValue() as its
4437 // representation first.
4438 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4439 << handler.AccessKind << Field << !UnionField << UnionField;
4440 return handler.failed();
4441 }
4442 }
4443 O = &O->getUnionValue();
4444 } else
4445 O = &O->getStructField(Field->getFieldIndex());
4446
4447 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4448 LastField = Field;
4449 if (Field->getType().isVolatileQualified())
4450 VolatileField = Field;
4451 } else {
4452 // Next subobject is a base class.
4453 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4454 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4455 O = &O->getStructBase(getBaseIndex(Derived, Base));
4456
4457 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4458 }
4459 }
4460}
4461
4462namespace {
4463struct ExtractSubobjectHandler {
4464 EvalInfo &Info;
4465 const Expr *E;
4466 APValue &Result;
4467 const AccessKinds AccessKind;
4468
4469 typedef bool result_type;
4470 bool failed() { return false; }
4471 bool found(APValue &Subobj, QualType SubobjType) {
4472 Result = Subobj;
4473 if (AccessKind == AK_ReadObjectRepresentation)
4474 return true;
4475 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4476 }
4477 bool found(APSInt &Value, QualType SubobjType) {
4478 Result = APValue(Value);
4479 return true;
4480 }
4481 bool found(APFloat &Value, QualType SubobjType) {
4482 Result = APValue(Value);
4483 return true;
4484 }
4485};
4486} // end anonymous namespace
4487
4488/// Extract the designated sub-object of an rvalue.
4489static bool extractSubobject(EvalInfo &Info, const Expr *E,
4490 const CompleteObject &Obj,
4491 const SubobjectDesignator &Sub, APValue &Result,
4492 AccessKinds AK = AK_Read) {
4493 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4494 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4495 return findSubobject(Info, E, Obj, Sub, Handler);
4496}
4497
4498namespace {
4499struct ModifySubobjectHandler {
4500 EvalInfo &Info;
4501 APValue &NewVal;
4502 const Expr *E;
4503
4504 typedef bool result_type;
4505 static const AccessKinds AccessKind = AK_Assign;
4506
4507 bool checkConst(QualType QT) {
4508 // Assigning to a const object has undefined behavior.
4509 if (QT.isConstQualified()) {
4510 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4511 return false;
4512 }
4513 return true;
4514 }
4515
4516 bool failed() { return false; }
4517 bool found(APValue &Subobj, QualType SubobjType) {
4518 if (!checkConst(SubobjType))
4519 return false;
4520 // We've been given ownership of NewVal, so just swap it in.
4521 Subobj.swap(NewVal);
4522 return true;
4523 }
4524 bool found(APSInt &Value, QualType SubobjType) {
4525 if (!checkConst(SubobjType))
4526 return false;
4527 if (!NewVal.isInt()) {
4528 // Maybe trying to write a cast pointer value into a complex?
4529 Info.FFDiag(E);
4530 return false;
4531 }
4532 Value = NewVal.getInt();
4533 return true;
4534 }
4535 bool found(APFloat &Value, QualType SubobjType) {
4536 if (!checkConst(SubobjType))
4537 return false;
4538 Value = NewVal.getFloat();
4539 return true;
4540 }
4541};
4542} // end anonymous namespace
4543
4544const AccessKinds ModifySubobjectHandler::AccessKind;
4545
4546/// Update the designated sub-object of an rvalue to the given value.
4547static bool modifySubobject(EvalInfo &Info, const Expr *E,
4548 const CompleteObject &Obj,
4549 const SubobjectDesignator &Sub,
4550 APValue &NewVal) {
4551 ModifySubobjectHandler Handler = { Info, NewVal, E };
4552 return findSubobject(Info, E, Obj, Sub, Handler);
4553}
4554
4555/// Find the position where two subobject designators diverge, or equivalently
4556/// the length of the common initial subsequence.
4557static unsigned FindDesignatorMismatch(QualType ObjType,
4558 const SubobjectDesignator &A,
4559 const SubobjectDesignator &B,
4560 bool &WasArrayIndex) {
4561 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4562 for (/**/; I != N; ++I) {
4563 if (!ObjType.isNull() &&
4564 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4565 // Next subobject is an array element.
4566 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4567 WasArrayIndex = true;
4568 return I;
4569 }
4570 if (ObjType->isAnyComplexType())
4571 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4572 else
4573 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4574 } else {
4575 if (A.Entries[I].getAsBaseOrMember() !=
4576 B.Entries[I].getAsBaseOrMember()) {
4577 WasArrayIndex = false;
4578 return I;
4579 }
4580 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4581 // Next subobject is a field.
4582 ObjType = FD->getType();
4583 else
4584 // Next subobject is a base class.
4585 ObjType = QualType();
4586 }
4587 }
4588 WasArrayIndex = false;
4589 return I;
4590}
4591
4592/// Determine whether the given subobject designators refer to elements of the
4593/// same array object.
4595 const SubobjectDesignator &A,
4596 const SubobjectDesignator &B) {
4597 if (A.Entries.size() != B.Entries.size())
4598 return false;
4599
4600 bool IsArray = A.MostDerivedIsArrayElement;
4601 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4602 // A is a subobject of the array element.
4603 return false;
4604
4605 // If A (and B) designates an array element, the last entry will be the array
4606 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4607 // of length 1' case, and the entire path must match.
4608 bool WasArrayIndex;
4609 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4610 return CommonLength >= A.Entries.size() - IsArray;
4611}
4612
4613/// Find the complete object to which an LValue refers.
4614static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4615 AccessKinds AK, const LValue &LVal,
4616 QualType LValType) {
4617 if (LVal.InvalidBase) {
4618 Info.FFDiag(E);
4619 return CompleteObject();
4620 }
4621
4622 if (!LVal.Base) {
4624 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4625 else
4626 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4627 return CompleteObject();
4628 }
4629
4630 CallStackFrame *Frame = nullptr;
4631 unsigned Depth = 0;
4632 if (LVal.getLValueCallIndex()) {
4633 std::tie(Frame, Depth) =
4634 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4635 if (!Frame) {
4636 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4637 << AK << LVal.Base.is<const ValueDecl*>();
4638 NoteLValueLocation(Info, LVal.Base);
4639 return CompleteObject();
4640 }
4641 }
4642
4643 bool IsAccess = isAnyAccess(AK);
4644
4645 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4646 // is not a constant expression (even if the object is non-volatile). We also
4647 // apply this rule to C++98, in order to conform to the expected 'volatile'
4648 // semantics.
4649 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4650 if (Info.getLangOpts().CPlusPlus)
4651 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4652 << AK << LValType;
4653 else
4654 Info.FFDiag(E);
4655 return CompleteObject();
4656 }
4657
4658 // Compute value storage location and type of base object.
4659 APValue *BaseVal = nullptr;
4660 QualType BaseType = getType(LVal.Base);
4661
4662 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4663 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4664 // This is the object whose initializer we're evaluating, so its lifetime
4665 // started in the current evaluation.
4666 BaseVal = Info.EvaluatingDeclValue;
4667 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4668 // Allow reading from a GUID declaration.
4669 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4670 if (isModification(AK)) {
4671 // All the remaining cases do not permit modification of the object.
4672 Info.FFDiag(E, diag::note_constexpr_modify_global);
4673 return CompleteObject();
4674 }
4675 APValue &V = GD->getAsAPValue();
4676 if (V.isAbsent()) {
4677 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4678 << GD->getType();
4679 return CompleteObject();
4680 }
4681 return CompleteObject(LVal.Base, &V, GD->getType());
4682 }
4683
4684 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4685 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4686 if (isModification(AK)) {
4687 Info.FFDiag(E, diag::note_constexpr_modify_global);
4688 return CompleteObject();
4689 }
4690 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4691 GCD->getType());
4692 }
4693
4694 // Allow reading from template parameter objects.
4695 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4696 if (isModification(AK)) {
4697 Info.FFDiag(E, diag::note_constexpr_modify_global);
4698 return CompleteObject();
4699 }
4700 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4701 TPO->getType());
4702 }
4703
4704 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4705 // In C++11, constexpr, non-volatile variables initialized with constant
4706 // expressions are constant expressions too. Inside constexpr functions,
4707 // parameters are constant expressions even if they're non-const.
4708 // In C++1y, objects local to a constant expression (those with a Frame) are
4709 // both readable and writable inside constant expressions.
4710 // In C, such things can also be folded, although they are not ICEs.
4711 const VarDecl *VD = dyn_cast<VarDecl>(D);
4712 if (VD) {
4713 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4714 VD = VDef;
4715 }
4716 if (!VD || VD->isInvalidDecl()) {
4717 Info.FFDiag(E);
4718 return CompleteObject();
4719 }
4720
4721 bool IsConstant = BaseType.isConstant(Info.Ctx);
4722 bool ConstexprVar = false;
4723 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4724 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4725 ConstexprVar = VD->isConstexpr();
4726
4727 // Unless we're looking at a local variable or argument in a constexpr call,
4728 // the variable we're reading must be const (unless we are binding to a
4729 // reference).
4730 if (AK != clang::AK_Dereference && !Frame) {
4731 if (IsAccess && isa<ParmVarDecl>(VD)) {
4732 // Access of a parameter that's not associated with a frame isn't going
4733 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4734 // suitable diagnostic.
4735 } else if (Info.getLangOpts().CPlusPlus14 &&
4736 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4737 // OK, we can read and modify an object if we're in the process of
4738 // evaluating its initializer, because its lifetime began in this
4739 // evaluation.
4740 } else if (isModification(AK)) {
4741 // All the remaining cases do not permit modification of the object.
4742 Info.FFDiag(E, diag::note_constexpr_modify_global);
4743 return CompleteObject();
4744 } else if (VD->isConstexpr()) {
4745 // OK, we can read this variable.
4746 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4747 Info.FFDiag(E);
4748 return CompleteObject();
4749 } else if (BaseType->isIntegralOrEnumerationType()) {
4750 if (!IsConstant) {
4751 if (!IsAccess)
4752 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4753 if (Info.getLangOpts().CPlusPlus) {
4754 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4755 Info.Note(VD->getLocation(), diag::note_declared_at);
4756 } else {
4757 Info.FFDiag(E);
4758 }
4759 return CompleteObject();
4760 }
4761 } else if (!IsAccess) {
4762 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4763 } else if ((IsConstant || BaseType->isReferenceType()) &&
4764 Info.checkingPotentialConstantExpression() &&
4765 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4766 // This variable might end up being constexpr. Don't diagnose it yet.
4767 } else if (IsConstant) {
4768 // Keep evaluating to see what we can do. In particular, we support
4769 // folding of const floating-point types, in order to make static const
4770 // data members of such types (supported as an extension) more useful.
4771 if (Info.getLangOpts().CPlusPlus) {
4772 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4773 ? diag::note_constexpr_ltor_non_constexpr
4774 : diag::note_constexpr_ltor_non_integral, 1)
4775 << VD << BaseType;
4776 Info.Note(VD->getLocation(), diag::note_declared_at);
4777 } else {
4778 Info.CCEDiag(E);
4779 }
4780 } else {
4781 // Never allow reading a non-const value.
4782 if (Info.getLangOpts().CPlusPlus) {
4783 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4784 ? diag::note_constexpr_ltor_non_constexpr
4785 : diag::note_constexpr_ltor_non_integral, 1)
4786 << VD << BaseType;
4787 Info.Note(VD->getLocation(), diag::note_declared_at);
4788 } else {
4789 Info.FFDiag(E);
4790 }
4791 return CompleteObject();
4792 }
4793 }
4794
4795 // When binding to a reference, the variable does not need to be constexpr
4796 // or have constant initalization.
4797 if (AK != clang::AK_Dereference &&
4798 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4799 BaseVal))
4800 return CompleteObject();
4801 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4802 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4803 // we can't access a constexpr-unknown object.
4804 if (AK != clang::AK_Dereference && !BaseVal) {
4805 if (!Info.checkingPotentialConstantExpression()) {
4806 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4807 << AK << VD;
4808 Info.Note(VD->getLocation(), diag::note_declared_at);
4809 }
4810 return CompleteObject();
4811 }
4812 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4813 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4814 if (!Alloc) {
4815 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4816 return CompleteObject();
4817 }
4818 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4819 LVal.Base.getDynamicAllocType());
4820 }
4821 // When binding to a reference, the variable does not need to be
4822 // within its lifetime.
4823 else if (AK != clang::AK_Dereference) {
4824 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4825
4826 if (!Frame) {
4827 if (const MaterializeTemporaryExpr *MTE =
4828 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4829 assert(MTE->getStorageDuration() == SD_Static &&
4830 "should have a frame for a non-global materialized temporary");
4831
4832 // C++20 [expr.const]p4: [DR2126]
4833 // An object or reference is usable in constant expressions if it is
4834 // - a temporary object of non-volatile const-qualified literal type
4835 // whose lifetime is extended to that of a variable that is usable
4836 // in constant expressions
4837 //
4838 // C++20 [expr.const]p5:
4839 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4840 // - a non-volatile glvalue that refers to an object that is usable
4841 // in constant expressions, or
4842 // - a non-volatile glvalue of literal type that refers to a
4843 // non-volatile object whose lifetime began within the evaluation
4844 // of E;
4845 //
4846 // C++11 misses the 'began within the evaluation of e' check and
4847 // instead allows all temporaries, including things like:
4848 // int &&r = 1;
4849 // int x = ++r;
4850 // constexpr int k = r;
4851 // Therefore we use the C++14-onwards rules in C++11 too.
4852 //
4853 // Note that temporaries whose lifetimes began while evaluating a
4854 // variable's constructor are not usable while evaluating the
4855 // corresponding destructor, not even if they're of const-qualified
4856 // types.
4857 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4858 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4859 if (!IsAccess)
4860 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4861 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4862 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4863 return CompleteObject();
4864 }
4865
4866 BaseVal = MTE->getOrCreateValue(false);
4867 assert(BaseVal && "got reference to unevaluated temporary");
4868 } else if (const CompoundLiteralExpr *CLE =
4869 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4870 // According to GCC info page:
4871 //
4872 // 6.28 Compound Literals
4873 //
4874 // As an optimization, G++ sometimes gives array compound literals
4875 // longer lifetimes: when the array either appears outside a function or
4876 // has a const-qualified type. If foo and its initializer had elements
4877 // of type char *const rather than char *, or if foo were a global
4878 // variable, the array would have static storage duration. But it is
4879 // probably safest just to avoid the use of array compound literals in
4880 // C++ code.
4881 //
4882 // Obey that rule by checking constness for converted array types.
4883 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4884 !LValType->isArrayType() &&
4885 !CLETy.isConstant(Info.Ctx)) {
4886 Info.FFDiag(E);
4887 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4888 return CompleteObject();
4889 }
4890
4891 BaseVal = &CLE->getStaticValue();
4892 } else {
4893 if (!IsAccess)
4894 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4895 APValue Val;
4896 LVal.moveInto(Val);
4897 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4898 << AK
4899 << Val.getAsString(Info.Ctx,
4900 Info.Ctx.getLValueReferenceType(LValType));
4901 NoteLValueLocation(Info, LVal.Base);
4902 return CompleteObject();
4903 }
4904 } else if (AK != clang::AK_Dereference) {
4905 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4906 assert(BaseVal && "missing value for temporary");
4907 }
4908 }
4909
4910 // In C++14, we can't safely access any mutable state when we might be
4911 // evaluating after an unmodeled side effect. Parameters are modeled as state
4912 // in the caller, but aren't visible once the call returns, so they can be
4913 // modified in a speculatively-evaluated call.
4914 //
4915 // FIXME: Not all local state is mutable. Allow local constant subobjects
4916 // to be read here (but take care with 'mutable' fields).
4917 unsigned VisibleDepth = Depth;
4918 if (llvm::isa_and_nonnull<ParmVarDecl>(
4919 LVal.Base.dyn_cast<const ValueDecl *>()))
4920 ++VisibleDepth;
4921 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4922 Info.EvalStatus.HasSideEffects) ||
4923 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4924 return CompleteObject();
4925
4926 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4927}
4928
4929/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4930/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4931/// glvalue referred to by an entity of reference type.
4932///
4933/// \param Info - Information about the ongoing evaluation.
4934/// \param Conv - The expression for which we are performing the conversion.
4935/// Used for diagnostics.
4936/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4937/// case of a non-class type).
4938/// \param LVal - The glvalue on which we are attempting to perform this action.
4939/// \param RVal - The produced value will be placed here.
4940/// \param WantObjectRepresentation - If true, we're looking for the object
4941/// representation rather than the value, and in particular,
4942/// there is no requirement that the result be fully initialized.
4943static bool
4945 const LValue &LVal, APValue &RVal,
4946 bool WantObjectRepresentation = false) {
4947 if (LVal.Designator.Invalid)
4948 return false;
4949
4950 // Check for special cases where there is no existing APValue to look at.
4951 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4952
4953 AccessKinds AK =
4954 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4955
4956 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4958 // Special-case character extraction so we don't have to construct an
4959 // APValue for the whole string.
4960 assert(LVal.Designator.Entries.size() <= 1 &&
4961 "Can only read characters from string literals");
4962 if (LVal.Designator.Entries.empty()) {
4963 // Fail for now for LValue to RValue conversion of an array.
4964 // (This shouldn't show up in C/C++, but it could be triggered by a
4965 // weird EvaluateAsRValue call from a tool.)
4966 Info.FFDiag(Conv);
4967 return false;
4968 }
4969 if (LVal.Designator.isOnePastTheEnd()) {
4970 if (Info.getLangOpts().CPlusPlus11)
4971 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4972 else
4973 Info.FFDiag(Conv);
4974 return false;
4975 }
4976 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4977 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4978 return true;
4979 }
4980 }
4981
4982 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4983 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4984}
4985
4986static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4987 QualType DestTy,
4988 SmallVectorImpl<APValue> &SrcVals,
4989 SmallVectorImpl<QualType> &SrcTypes) {
4990 APValue Val;
4991 if (!Evaluate(Val, Info, E))
4992 return false;
4993
4994 // must be dealing with a record
4995 if (Val.isLValue()) {
4996 LValue LVal;
4997 LVal.setFrom(Info.Ctx, Val);
4998 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4999 return false;
5000 }
5001
5002 unsigned NEls = elementwiseSize(Info, DestTy);
5003 // flatten the source
5004 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5005 return false;
5006
5007 return true;
5008}
5009
5010/// Perform an assignment of Val to LVal. Takes ownership of Val.
5011static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5012 QualType LValType, APValue &Val) {
5013 if (LVal.Designator.Invalid)
5014 return false;
5015
5016 if (!Info.getLangOpts().CPlusPlus14) {
5017 Info.FFDiag(E);
5018 return false;
5019 }
5020
5021 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5022 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5023}
5024
5025namespace {
5026struct CompoundAssignSubobjectHandler {
5027 EvalInfo &Info;
5028 const CompoundAssignOperator *E;
5029 QualType PromotedLHSType;
5031 const APValue &RHS;
5032
5033 static const AccessKinds AccessKind = AK_Assign;
5034
5035 typedef bool result_type;
5036
5037 bool checkConst(QualType QT) {
5038 // Assigning to a const object has undefined behavior.
5039 if (QT.isConstQualified()) {
5040 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5041 return false;
5042 }
5043 return true;
5044 }
5045
5046 bool failed() { return false; }
5047 bool found(APValue &Subobj, QualType SubobjType) {
5048 switch (Subobj.getKind()) {
5049 case APValue::Int:
5050 return found(Subobj.getInt(), SubobjType);
5051 case APValue::Float:
5052 return found(Subobj.getFloat(), SubobjType);
5055 // FIXME: Implement complex compound assignment.
5056 Info.FFDiag(E);
5057 return false;
5058 case APValue::LValue:
5059 return foundPointer(Subobj, SubobjType);
5060 case APValue::Vector:
5061 return foundVector(Subobj, SubobjType);
5063 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5064 << /*read of=*/0 << /*uninitialized object=*/1
5065 << E->getLHS()->getSourceRange();
5066 return false;
5067 default:
5068 // FIXME: can this happen?
5069 Info.FFDiag(E);
5070 return false;
5071 }
5072 }
5073
5074 bool foundVector(APValue &Value, QualType SubobjType) {
5075 if (!checkConst(SubobjType))
5076 return false;
5077
5078 if (!SubobjType->isVectorType()) {
5079 Info.FFDiag(E);
5080 return false;
5081 }
5082 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5083 }
5084
5085 bool found(APSInt &Value, QualType SubobjType) {
5086 if (!checkConst(SubobjType))
5087 return false;
5088
5089 if (!SubobjType->isIntegerType()) {
5090 // We don't support compound assignment on integer-cast-to-pointer
5091 // values.
5092 Info.FFDiag(E);
5093 return false;
5094 }
5095
5096 if (RHS.isInt()) {
5097 APSInt LHS =
5098 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5099 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5100 return false;
5101 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5102 return true;
5103 } else if (RHS.isFloat()) {
5104 const FPOptions FPO = E->getFPFeaturesInEffect(
5105 Info.Ctx.getLangOpts());
5106 APFloat FValue(0.0);
5107 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5108 PromotedLHSType, FValue) &&
5109 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5110 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5111 Value);
5112 }
5113
5114 Info.FFDiag(E);
5115 return false;
5116 }
5117 bool found(APFloat &Value, QualType SubobjType) {
5118 return checkConst(SubobjType) &&
5119 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5120 Value) &&
5121 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5122 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5123 }
5124 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5125 if (!checkConst(SubobjType))
5126 return false;
5127
5128 QualType PointeeType;
5129 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5130 PointeeType = PT->getPointeeType();
5131
5132 if (PointeeType.isNull() || !RHS.isInt() ||
5133 (Opcode != BO_Add && Opcode != BO_Sub)) {
5134 Info.FFDiag(E);
5135 return false;
5136 }
5137
5138 APSInt Offset = RHS.getInt();
5139 if (Opcode == BO_Sub)
5140 negateAsSigned(Offset);
5141
5142 LValue LVal;
5143 LVal.setFrom(Info.Ctx, Subobj);
5144 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5145 return false;
5146 LVal.moveInto(Subobj);
5147 return true;
5148 }
5149};
5150} // end anonymous namespace
5151
5152const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5153
5154/// Perform a compound assignment of LVal <op>= RVal.
5155static bool handleCompoundAssignment(EvalInfo &Info,
5156 const CompoundAssignOperator *E,
5157 const LValue &LVal, QualType LValType,
5158 QualType PromotedLValType,
5159 BinaryOperatorKind Opcode,
5160 const APValue &RVal) {
5161 if (LVal.Designator.Invalid)
5162 return false;
5163
5164 if (!Info.getLangOpts().CPlusPlus14) {
5165 Info.FFDiag(E);
5166 return false;
5167 }
5168
5169 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5170 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5171 RVal };
5172 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5173}
5174
5175namespace {
5176struct IncDecSubobjectHandler {
5177 EvalInfo &Info;
5178 const UnaryOperator *E;
5180 APValue *Old;
5181
5182 typedef bool result_type;
5183
5184 bool checkConst(QualType QT) {
5185 // Assigning to a const object has undefined behavior.
5186 if (QT.isConstQualified()) {
5187 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5188 return false;
5189 }
5190 return true;
5191 }
5192
5193 bool failed() { return false; }
5194 bool found(APValue &Subobj, QualType SubobjType) {
5195 // Stash the old value. Also clear Old, so we don't clobber it later
5196 // if we're post-incrementing a complex.
5197 if (Old) {
5198 *Old = Subobj;
5199 Old = nullptr;
5200 }
5201
5202 switch (Subobj.getKind()) {
5203 case APValue::Int:
5204 return found(Subobj.getInt(), SubobjType);
5205 case APValue::Float:
5206 return found(Subobj.getFloat(), SubobjType);
5208 return found(Subobj.getComplexIntReal(),
5209 SubobjType->castAs<ComplexType>()->getElementType()
5210 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5212 return found(Subobj.getComplexFloatReal(),
5213 SubobjType->castAs<ComplexType>()->getElementType()
5214 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5215 case APValue::LValue:
5216 return foundPointer(Subobj, SubobjType);
5217 default:
5218 // FIXME: can this happen?
5219 Info.FFDiag(E);
5220 return false;
5221 }
5222 }
5223 bool found(APSInt &Value, QualType SubobjType) {
5224 if (!checkConst(SubobjType))
5225 return false;
5226
5227 if (!SubobjType->isIntegerType()) {
5228 // We don't support increment / decrement on integer-cast-to-pointer
5229 // values.
5230 Info.FFDiag(E);
5231 return false;
5232 }
5233
5234 if (Old) *Old = APValue(Value);
5235
5236 // bool arithmetic promotes to int, and the conversion back to bool
5237 // doesn't reduce mod 2^n, so special-case it.
5238 if (SubobjType->isBooleanType()) {
5239 if (AccessKind == AK_Increment)
5240 Value = 1;
5241 else
5242 Value = !Value;
5243 return true;
5244 }
5245
5246 bool WasNegative = Value.isNegative();
5247 if (AccessKind == AK_Increment) {
5248 ++Value;
5249
5250 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
5251 APSInt ActualValue(Value, /*IsUnsigned*/true);
5252 return HandleOverflow(Info, E, ActualValue, SubobjType);
5253 }
5254 } else {
5255 --Value;
5256
5257 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
5258 unsigned BitWidth = Value.getBitWidth();
5259 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5260 ActualValue.setBit(BitWidth);
5261 return HandleOverflow(Info, E, ActualValue, SubobjType);
5262 }
5263 }
5264 return true;
5265 }
5266 bool found(APFloat &Value, QualType SubobjType) {
5267 if (!checkConst(SubobjType))
5268 return false;
5269
5270 if (Old) *Old = APValue(Value);
5271
5272 APFloat One(Value.getSemantics(), 1);
5273 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5274 APFloat::opStatus St;
5275 if (AccessKind == AK_Increment)
5276 St = Value.add(One, RM);
5277 else
5278 St = Value.subtract(One, RM);
5279 return checkFloatingPointResult(Info, E, St);
5280 }
5281 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5282 if (!checkConst(SubobjType))
5283 return false;
5284
5285 QualType PointeeType;
5286 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5287 PointeeType = PT->getPointeeType();
5288 else {
5289 Info.FFDiag(E);
5290 return false;
5291 }
5292
5293 LValue LVal;
5294 LVal.setFrom(Info.Ctx, Subobj);
5295 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5296 AccessKind == AK_Increment ? 1 : -1))
5297 return false;
5298 LVal.moveInto(Subobj);
5299 return true;
5300 }
5301};
5302} // end anonymous namespace
5303
5304/// Perform an increment or decrement on LVal.
5305static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5306 QualType LValType, bool IsIncrement, APValue *Old) {
5307 if (LVal.Designator.Invalid)
5308 return false;
5309
5310 if (!Info.getLangOpts().CPlusPlus14) {
5311 Info.FFDiag(E);
5312 return false;
5313 }
5314
5315 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5316 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5317 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5318 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5319}
5320
5321/// Build an lvalue for the object argument of a member function call.
5322static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5323 LValue &This) {
5324 if (Object->getType()->isPointerType() && Object->isPRValue())
5325 return EvaluatePointer(Object, This, Info);
5326
5327 if (Object->isGLValue())
5328 return EvaluateLValue(Object, This, Info);
5329
5330 if (Object->getType()->isLiteralType(Info.Ctx))
5331 return EvaluateTemporary(Object, This, Info);
5332
5333 if (Object->getType()->isRecordType() && Object->isPRValue())
5334 return EvaluateTemporary(Object, This, Info);
5335
5336 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5337 return false;
5338}
5339
5340/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5341/// lvalue referring to the result.
5342///
5343/// \param Info - Information about the ongoing evaluation.
5344/// \param LV - An lvalue referring to the base of the member pointer.
5345/// \param RHS - The member pointer expression.
5346/// \param IncludeMember - Specifies whether the member itself is included in
5347/// the resulting LValue subobject designator. This is not possible when
5348/// creating a bound member function.
5349/// \return The field or method declaration to which the member pointer refers,
5350/// or 0 if evaluation fails.
5351static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5352 QualType LVType,
5353 LValue &LV,
5354 const Expr *RHS,
5355 bool IncludeMember = true) {
5356 MemberPtr MemPtr;
5357 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5358 return nullptr;
5359
5360 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5361 // member value, the behavior is undefined.
5362 if (!MemPtr.getDecl()) {
5363 // FIXME: Specific diagnostic.
5364 Info.FFDiag(RHS);
5365 return nullptr;
5366 }
5367
5368 if (MemPtr.isDerivedMember()) {
5369 // This is a member of some derived class. Truncate LV appropriately.
5370 // The end of the derived-to-base path for the base object must match the
5371 // derived-to-base path for the member pointer.
5372 // C++23 [expr.mptr.oper]p4:
5373 // If the result of E1 is an object [...] whose most derived object does
5374 // not contain the member to which E2 refers, the behavior is undefined.
5375 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5376 LV.Designator.Entries.size()) {
5377 Info.FFDiag(RHS);
5378 return nullptr;
5379 }
5380 unsigned PathLengthToMember =
5381 LV.Designator.Entries.size() - MemPtr.Path.size();
5382 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5383 const CXXRecordDecl *LVDecl = getAsBaseClass(
5384 LV.Designator.Entries[PathLengthToMember + I]);
5385 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5386 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5387 Info.FFDiag(RHS);
5388 return nullptr;
5389 }
5390 }
5391 // MemPtr.Path only contains the base classes of the class directly
5392 // containing the member E2. It is still necessary to check that the class
5393 // directly containing the member E2 lies on the derived-to-base path of E1
5394 // to avoid incorrectly permitting member pointer access into a sibling
5395 // class of the class containing the member E2. If this class would
5396 // correspond to the most-derived class of E1, it either isn't contained in
5397 // LV.Designator.Entries or the corresponding entry refers to an array
5398 // element instead. Therefore get the most derived class directly in this
5399 // case. Otherwise the previous entry should correpond to this class.
5400 const CXXRecordDecl *LastLVDecl =
5401 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5402 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5403 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5404 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5405 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5406 Info.FFDiag(RHS);
5407 return nullptr;
5408 }
5409
5410 // Truncate the lvalue to the appropriate derived class.
5411 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5412 PathLengthToMember))
5413 return nullptr;
5414 } else if (!MemPtr.Path.empty()) {
5415 // Extend the LValue path with the member pointer's path.
5416 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5417 MemPtr.Path.size() + IncludeMember);
5418
5419 // Walk down to the appropriate base class.
5420 if (const PointerType *PT = LVType->getAs<PointerType>())
5421 LVType = PT->getPointeeType();
5422 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5423 assert(RD && "member pointer access on non-class-type expression");
5424 // The first class in the path is that of the lvalue.
5425 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5426 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5427 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5428 return nullptr;
5429 RD = Base;
5430 }
5431 // Finally cast to the class containing the member.
5432 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5433 MemPtr.getContainingRecord()))
5434 return nullptr;
5435 }
5436
5437 // Add the member. Note that we cannot build bound member functions here.
5438 if (IncludeMember) {
5439 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5440 if (!HandleLValueMember(Info, RHS, LV, FD))
5441 return nullptr;
5442 } else if (const IndirectFieldDecl *IFD =
5443 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5444 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5445 return nullptr;
5446 } else {
5447 llvm_unreachable("can't construct reference to bound member function");
5448 }
5449 }
5450
5451 return MemPtr.getDecl();
5452}
5453
5454static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5455 const BinaryOperator *BO,
5456 LValue &LV,
5457 bool IncludeMember = true) {
5458 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5459
5460 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5461 if (Info.noteFailure()) {
5462 MemberPtr MemPtr;
5463 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5464 }
5465 return nullptr;
5466 }
5467
5468 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5469 BO->getRHS(), IncludeMember);
5470}
5471
5472/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5473/// the provided lvalue, which currently refers to the base object.
5474static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5475 LValue &Result) {
5476 SubobjectDesignator &D = Result.Designator;
5477 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5478 return false;
5479
5480 QualType TargetQT = E->getType();
5481 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5482 TargetQT = PT->getPointeeType();
5483
5484 auto InvalidCast = [&]() {
5485 if (!Info.checkingPotentialConstantExpression() ||
5486 !Result.AllowConstexprUnknown) {
5487 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5488 << D.MostDerivedType << TargetQT;
5489 }
5490 return false;
5491 };
5492
5493 // Check this cast lands within the final derived-to-base subobject path.
5494 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5495 return InvalidCast();
5496
5497 // Check the type of the final cast. We don't need to check the path,
5498 // since a cast can only be formed if the path is unique.
5499 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5500 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5501 const CXXRecordDecl *FinalType;
5502 if (NewEntriesSize == D.MostDerivedPathLength)
5503 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5504 else
5505 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5506 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5507 return InvalidCast();
5508
5509 // Truncate the lvalue to the appropriate derived class.
5510 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5511}
5512
5513/// Get the value to use for a default-initialized object of type T.
5514/// Return false if it encounters something invalid.
5516 bool Success = true;
5517
5518 // If there is already a value present don't overwrite it.
5519 if (!Result.isAbsent())
5520 return true;
5521
5522 if (auto *RD = T->getAsCXXRecordDecl()) {
5523 if (RD->isInvalidDecl()) {
5524 Result = APValue();
5525 return false;
5526 }
5527 if (RD->isUnion()) {
5528 Result = APValue((const FieldDecl *)nullptr);
5529 return true;
5530 }
5531 Result =
5532 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5533
5534 unsigned Index = 0;
5535 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5536 End = RD->bases_end();
5537 I != End; ++I, ++Index)
5538 Success &=
5539 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5540
5541 for (const auto *I : RD->fields()) {
5542 if (I->isUnnamedBitField())
5543 continue;
5545 I->getType(), Result.getStructField(I->getFieldIndex()));
5546 }
5547 return Success;
5548 }
5549
5550 if (auto *AT =
5551 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5552 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5553 if (Result.hasArrayFiller())
5554 Success &=
5555 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5556
5557 return Success;
5558 }
5559
5560 Result = APValue::IndeterminateValue();
5561 return true;
5562}
5563
5564namespace {
5565enum EvalStmtResult {
5566 /// Evaluation failed.
5567 ESR_Failed,
5568 /// Hit a 'return' statement.
5569 ESR_Returned,
5570 /// Evaluation succeeded.
5571 ESR_Succeeded,
5572 /// Hit a 'continue' statement.
5573 ESR_Continue,
5574 /// Hit a 'break' statement.
5575 ESR_Break,
5576 /// Still scanning for 'case' or 'default' statement.
5577 ESR_CaseNotFound
5578};
5579}
5580/// Evaluates the initializer of a reference.
5581static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5582 const ValueDecl *D,
5583 const Expr *Init, LValue &Result,
5584 APValue &Val) {
5585 assert(Init->isGLValue() && D->getType()->isReferenceType());
5586 // A reference is an lvalue.
5587 if (!EvaluateLValue(Init, Result, Info))
5588 return false;
5589 // [C++26][decl.ref]
5590 // The object designated by such a glvalue can be outside its lifetime
5591 // Because a null pointer value or a pointer past the end of an object
5592 // does not point to an object, a reference in a well-defined program cannot
5593 // refer to such things;
5594 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5595 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5596 return false;
5597 }
5598
5599 // Save the result.
5600 Result.moveInto(Val);
5601 return true;
5602}
5603
5604static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5605 if (VD->isInvalidDecl())
5606 return false;
5607 // We don't need to evaluate the initializer for a static local.
5608 if (!VD->hasLocalStorage())
5609 return true;
5610
5611 LValue Result;
5612 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5613 ScopeKind::Block, Result);
5614
5615 const Expr *InitE = VD->getInit();
5616 if (!InitE) {
5617 if (VD->getType()->isDependentType())
5618 return Info.noteSideEffect();
5619 return handleDefaultInitValue(VD->getType(), Val);
5620 }
5621 if (InitE->isValueDependent())
5622 return false;
5623
5624 // For references to objects, check they do not designate a one-past-the-end
5625 // object.
5626 if (VD->getType()->isReferenceType()) {
5627 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5628 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5629 // Wipe out any partially-computed value, to allow tracking that this
5630 // evaluation failed.
5631 Val = APValue();
5632 return false;
5633 }
5634
5635 return true;
5636}
5637
5638static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5639 const DecompositionDecl *DD);
5640
5641static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5642 bool EvaluateConditionDecl = false) {
5643 bool OK = true;
5644 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5645 OK &= EvaluateVarDecl(Info, VD);
5646
5647 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5648 EvaluateConditionDecl && DD)
5649 OK &= EvaluateDecompositionDeclInit(Info, DD);
5650
5651 return OK;
5652}
5653
5654static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5655 const DecompositionDecl *DD) {
5656 bool OK = true;
5657 for (auto *BD : DD->flat_bindings())
5658 if (auto *VD = BD->getHoldingVar())
5659 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5660
5661 return OK;
5662}
5663
5664static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5665 const VarDecl *VD) {
5666 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5667 if (!EvaluateDecompositionDeclInit(Info, DD))
5668 return false;
5669 }
5670 return true;
5671}
5672
5673static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5674 assert(E->isValueDependent());
5675 if (Info.noteSideEffect())
5676 return true;
5677 assert(E->containsErrors() && "valid value-dependent expression should never "
5678 "reach invalid code path.");
5679 return false;
5680}
5681
5682/// Evaluate a condition (either a variable declaration or an expression).
5683static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5684 const Expr *Cond, bool &Result) {
5685 if (Cond->isValueDependent())
5686 return false;
5687 FullExpressionRAII Scope(Info);
5688 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5689 return false;
5690 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5691 return false;
5692 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5693 return false;
5694 return Scope.destroy();
5695}
5696
5697namespace {
5698/// A location where the result (returned value) of evaluating a
5699/// statement should be stored.
5700struct StmtResult {
5701 /// The APValue that should be filled in with the returned value.
5702 APValue &Value;
5703 /// The location containing the result, if any (used to support RVO).
5704 const LValue *Slot;
5705};
5706
5707struct TempVersionRAII {
5708 CallStackFrame &Frame;
5709
5710 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5711 Frame.pushTempVersion();
5712 }
5713
5714 ~TempVersionRAII() {
5715 Frame.popTempVersion();
5716 }
5717};
5718
5719}
5720
5721static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5722 const Stmt *S,
5723 const SwitchCase *SC = nullptr);
5724
5725/// Helper to implement named break/continue. Returns 'true' if the evaluation
5726/// result should be propagated up. Otherwise, it sets the evaluation result
5727/// to either Continue to continue the current loop, or Succeeded to break it.
5728static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5729 const Stmt *LoopOrSwitch,
5731 EvalStmtResult &ESR) {
5732 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5733
5734 // For loops, map Succeeded to Continue so we don't have to check for both.
5735 if (!IsSwitch && ESR == ESR_Succeeded) {
5736 ESR = ESR_Continue;
5737 return false;
5738 }
5739
5740 if (ESR != ESR_Break && ESR != ESR_Continue)
5741 return false;
5742
5743 // Are we breaking out of or continuing this statement?
5744 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5745 const Stmt *StackTop = Info.BreakContinueStack.back();
5746 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5747 Info.BreakContinueStack.pop_back();
5748 if (ESR == ESR_Break)
5749 ESR = ESR_Succeeded;
5750 return false;
5751 }
5752
5753 // We're not. Propagate the result up.
5754 for (BlockScopeRAII *S : Scopes) {
5755 if (!S->destroy()) {
5756 ESR = ESR_Failed;
5757 break;
5758 }
5759 }
5760 return true;
5761}
5762
5763/// Evaluate the body of a loop, and translate the result as appropriate.
5764static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5765 const Stmt *Body,
5766 const SwitchCase *Case = nullptr) {
5767 BlockScopeRAII Scope(Info);
5768
5769 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5770 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5771 ESR = ESR_Failed;
5772
5773 return ESR;
5774}
5775
5776/// Evaluate a switch statement.
5777static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5778 const SwitchStmt *SS) {
5779 BlockScopeRAII Scope(Info);
5780
5781 // Evaluate the switch condition.
5782 APSInt Value;
5783 {
5784 if (const Stmt *Init = SS->getInit()) {
5785 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5786 if (ESR != ESR_Succeeded) {
5787 if (ESR != ESR_Failed && !Scope.destroy())
5788 ESR = ESR_Failed;
5789 return ESR;
5790 }
5791 }
5792
5793 FullExpressionRAII CondScope(Info);
5794 if (SS->getConditionVariable() &&
5795 !EvaluateDecl(Info, SS->getConditionVariable()))
5796 return ESR_Failed;
5797 if (SS->getCond()->isValueDependent()) {
5798 // We don't know what the value is, and which branch should jump to.
5799 EvaluateDependentExpr(SS->getCond(), Info);
5800 return ESR_Failed;
5801 }
5802 if (!EvaluateInteger(SS->getCond(), Value, Info))
5803 return ESR_Failed;
5804
5806 return ESR_Failed;
5807
5808 if (!CondScope.destroy())
5809 return ESR_Failed;
5810 }
5811
5812 // Find the switch case corresponding to the value of the condition.
5813 // FIXME: Cache this lookup.
5814 const SwitchCase *Found = nullptr;
5815 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5816 SC = SC->getNextSwitchCase()) {
5817 if (isa<DefaultStmt>(SC)) {
5818 Found = SC;
5819 continue;
5820 }
5821
5822 const CaseStmt *CS = cast<CaseStmt>(SC);
5823 const Expr *LHS = CS->getLHS();
5824 const Expr *RHS = CS->getRHS();
5825 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5826 return ESR_Failed;
5827 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5828 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5829 if (LHSValue <= Value && Value <= RHSValue) {
5830 Found = SC;
5831 break;
5832 }
5833 }
5834
5835 if (!Found)
5836 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5837
5838 // Search the switch body for the switch case and evaluate it from there.
5839 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5840 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5841 return ESR_Failed;
5842 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5843 return ESR;
5844
5845 switch (ESR) {
5846 case ESR_Break:
5847 llvm_unreachable("Should have been converted to Succeeded");
5848 case ESR_Succeeded:
5849 case ESR_Continue:
5850 case ESR_Failed:
5851 case ESR_Returned:
5852 return ESR;
5853 case ESR_CaseNotFound:
5854 // This can only happen if the switch case is nested within a statement
5855 // expression. We have no intention of supporting that.
5856 Info.FFDiag(Found->getBeginLoc(),
5857 diag::note_constexpr_stmt_expr_unsupported);
5858 return ESR_Failed;
5859 }
5860 llvm_unreachable("Invalid EvalStmtResult!");
5861}
5862
5863static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5864 // An expression E is a core constant expression unless the evaluation of E
5865 // would evaluate one of the following: [C++23] - a control flow that passes
5866 // through a declaration of a variable with static or thread storage duration
5867 // unless that variable is usable in constant expressions.
5868 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5869 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5870 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5871 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5872 return false;
5873 }
5874 return true;
5875}
5876
5877// Evaluate a statement.
5878static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5879 const Stmt *S, const SwitchCase *Case) {
5880 if (!Info.nextStep(S))
5881 return ESR_Failed;
5882
5883 // If we're hunting down a 'case' or 'default' label, recurse through
5884 // substatements until we hit the label.
5885 if (Case) {
5886 switch (S->getStmtClass()) {
5887 case Stmt::CompoundStmtClass:
5888 // FIXME: Precompute which substatement of a compound statement we
5889 // would jump to, and go straight there rather than performing a
5890 // linear scan each time.
5891 case Stmt::LabelStmtClass:
5892 case Stmt::AttributedStmtClass:
5893 case Stmt::DoStmtClass:
5894 break;
5895
5896 case Stmt::CaseStmtClass:
5897 case Stmt::DefaultStmtClass:
5898 if (Case == S)
5899 Case = nullptr;
5900 break;
5901
5902 case Stmt::IfStmtClass: {
5903 // FIXME: Precompute which side of an 'if' we would jump to, and go
5904 // straight there rather than scanning both sides.
5905 const IfStmt *IS = cast<IfStmt>(S);
5906
5907 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5908 // preceded by our switch label.
5909 BlockScopeRAII Scope(Info);
5910
5911 // Step into the init statement in case it brings an (uninitialized)
5912 // variable into scope.
5913 if (const Stmt *Init = IS->getInit()) {
5914 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5915 if (ESR != ESR_CaseNotFound) {
5916 assert(ESR != ESR_Succeeded);
5917 return ESR;
5918 }
5919 }
5920
5921 // Condition variable must be initialized if it exists.
5922 // FIXME: We can skip evaluating the body if there's a condition
5923 // variable, as there can't be any case labels within it.
5924 // (The same is true for 'for' statements.)
5925
5926 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5927 if (ESR == ESR_Failed)
5928 return ESR;
5929 if (ESR != ESR_CaseNotFound)
5930 return Scope.destroy() ? ESR : ESR_Failed;
5931 if (!IS->getElse())
5932 return ESR_CaseNotFound;
5933
5934 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5935 if (ESR == ESR_Failed)
5936 return ESR;
5937 if (ESR != ESR_CaseNotFound)
5938 return Scope.destroy() ? ESR : ESR_Failed;
5939 return ESR_CaseNotFound;
5940 }
5941
5942 case Stmt::WhileStmtClass: {
5943 EvalStmtResult ESR =
5944 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5945 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5946 return ESR;
5947 if (ESR != ESR_Continue)
5948 return ESR;
5949 break;
5950 }
5951
5952 case Stmt::ForStmtClass: {
5953 const ForStmt *FS = cast<ForStmt>(S);
5954 BlockScopeRAII Scope(Info);
5955
5956 // Step into the init statement in case it brings an (uninitialized)
5957 // variable into scope.
5958 if (const Stmt *Init = FS->getInit()) {
5959 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5960 if (ESR != ESR_CaseNotFound) {
5961 assert(ESR != ESR_Succeeded);
5962 return ESR;
5963 }
5964 }
5965
5966 EvalStmtResult ESR =
5967 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5968 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5969 return ESR;
5970 if (ESR != ESR_Continue)
5971 return ESR;
5972 if (const auto *Inc = FS->getInc()) {
5973 if (Inc->isValueDependent()) {
5974 if (!EvaluateDependentExpr(Inc, Info))
5975 return ESR_Failed;
5976 } else {
5977 FullExpressionRAII IncScope(Info);
5978 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5979 return ESR_Failed;
5980 }
5981 }
5982 break;
5983 }
5984
5985 case Stmt::DeclStmtClass: {
5986 // Start the lifetime of any uninitialized variables we encounter. They
5987 // might be used by the selected branch of the switch.
5988 const DeclStmt *DS = cast<DeclStmt>(S);
5989 for (const auto *D : DS->decls()) {
5990 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5991 if (!CheckLocalVariableDeclaration(Info, VD))
5992 return ESR_Failed;
5993 if (VD->hasLocalStorage() && !VD->getInit())
5994 if (!EvaluateVarDecl(Info, VD))
5995 return ESR_Failed;
5996 // FIXME: If the variable has initialization that can't be jumped
5997 // over, bail out of any immediately-surrounding compound-statement
5998 // too. There can't be any case labels here.
5999 }
6000 }
6001 return ESR_CaseNotFound;
6002 }
6003
6004 default:
6005 return ESR_CaseNotFound;
6006 }
6007 }
6008
6009 switch (S->getStmtClass()) {
6010 default:
6011 if (const Expr *E = dyn_cast<Expr>(S)) {
6012 if (E->isValueDependent()) {
6013 if (!EvaluateDependentExpr(E, Info))
6014 return ESR_Failed;
6015 } else {
6016 // Don't bother evaluating beyond an expression-statement which couldn't
6017 // be evaluated.
6018 // FIXME: Do we need the FullExpressionRAII object here?
6019 // VisitExprWithCleanups should create one when necessary.
6020 FullExpressionRAII Scope(Info);
6021 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6022 return ESR_Failed;
6023 }
6024 return ESR_Succeeded;
6025 }
6026
6027 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6028 return ESR_Failed;
6029
6030 case Stmt::NullStmtClass:
6031 return ESR_Succeeded;
6032
6033 case Stmt::DeclStmtClass: {
6034 const DeclStmt *DS = cast<DeclStmt>(S);
6035 for (const auto *D : DS->decls()) {
6036 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6037 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6038 return ESR_Failed;
6039 // Each declaration initialization is its own full-expression.
6040 FullExpressionRAII Scope(Info);
6041 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6042 !Info.noteFailure())
6043 return ESR_Failed;
6044 if (!Scope.destroy())
6045 return ESR_Failed;
6046 }
6047 return ESR_Succeeded;
6048 }
6049
6050 case Stmt::ReturnStmtClass: {
6051 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6052 FullExpressionRAII Scope(Info);
6053 if (RetExpr && RetExpr->isValueDependent()) {
6054 EvaluateDependentExpr(RetExpr, Info);
6055 // We know we returned, but we don't know what the value is.
6056 return ESR_Failed;
6057 }
6058 if (RetExpr &&
6059 !(Result.Slot
6060 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6061 : Evaluate(Result.Value, Info, RetExpr)))
6062 return ESR_Failed;
6063 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6064 }
6065
6066 case Stmt::CompoundStmtClass: {
6067 BlockScopeRAII Scope(Info);
6068
6069 const CompoundStmt *CS = cast<CompoundStmt>(S);
6070 for (const auto *BI : CS->body()) {
6071 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6072 if (ESR == ESR_Succeeded)
6073 Case = nullptr;
6074 else if (ESR != ESR_CaseNotFound) {
6075 if (ESR != ESR_Failed && !Scope.destroy())
6076 return ESR_Failed;
6077 return ESR;
6078 }
6079 }
6080 if (Case)
6081 return ESR_CaseNotFound;
6082 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6083 }
6084
6085 case Stmt::IfStmtClass: {
6086 const IfStmt *IS = cast<IfStmt>(S);
6087
6088 // Evaluate the condition, as either a var decl or as an expression.
6089 BlockScopeRAII Scope(Info);
6090 if (const Stmt *Init = IS->getInit()) {
6091 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6092 if (ESR != ESR_Succeeded) {
6093 if (ESR != ESR_Failed && !Scope.destroy())
6094 return ESR_Failed;
6095 return ESR;
6096 }
6097 }
6098 bool Cond;
6099 if (IS->isConsteval()) {
6101 // If we are not in a constant context, if consteval should not evaluate
6102 // to true.
6103 if (!Info.InConstantContext)
6104 Cond = !Cond;
6105 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6106 Cond))
6107 return ESR_Failed;
6108
6109 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6110 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6111 if (ESR != ESR_Succeeded) {
6112 if (ESR != ESR_Failed && !Scope.destroy())
6113 return ESR_Failed;
6114 return ESR;
6115 }
6116 }
6117 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6118 }
6119
6120 case Stmt::WhileStmtClass: {
6121 const WhileStmt *WS = cast<WhileStmt>(S);
6122 while (true) {
6123 BlockScopeRAII Scope(Info);
6124 bool Continue;
6125 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6126 Continue))
6127 return ESR_Failed;
6128 if (!Continue)
6129 break;
6130
6131 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6132 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6133 return ESR;
6134
6135 if (ESR != ESR_Continue) {
6136 if (ESR != ESR_Failed && !Scope.destroy())
6137 return ESR_Failed;
6138 return ESR;
6139 }
6140 if (!Scope.destroy())
6141 return ESR_Failed;
6142 }
6143 return ESR_Succeeded;
6144 }
6145
6146 case Stmt::DoStmtClass: {
6147 const DoStmt *DS = cast<DoStmt>(S);
6148 bool Continue;
6149 do {
6150 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6151 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6152 return ESR;
6153 if (ESR != ESR_Continue)
6154 return ESR;
6155 Case = nullptr;
6156
6157 if (DS->getCond()->isValueDependent()) {
6158 EvaluateDependentExpr(DS->getCond(), Info);
6159 // Bailout as we don't know whether to keep going or terminate the loop.
6160 return ESR_Failed;
6161 }
6162 FullExpressionRAII CondScope(Info);
6163 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6164 !CondScope.destroy())
6165 return ESR_Failed;
6166 } while (Continue);
6167 return ESR_Succeeded;
6168 }
6169
6170 case Stmt::ForStmtClass: {
6171 const ForStmt *FS = cast<ForStmt>(S);
6172 BlockScopeRAII ForScope(Info);
6173 if (FS->getInit()) {
6174 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6175 if (ESR != ESR_Succeeded) {
6176 if (ESR != ESR_Failed && !ForScope.destroy())
6177 return ESR_Failed;
6178 return ESR;
6179 }
6180 }
6181 while (true) {
6182 BlockScopeRAII IterScope(Info);
6183 bool Continue = true;
6184 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6185 FS->getCond(), Continue))
6186 return ESR_Failed;
6187
6188 if (!Continue) {
6189 if (!IterScope.destroy())
6190 return ESR_Failed;
6191 break;
6192 }
6193
6194 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6195 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6196 return ESR;
6197 if (ESR != ESR_Continue) {
6198 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6199 return ESR_Failed;
6200 return ESR;
6201 }
6202
6203 if (const auto *Inc = FS->getInc()) {
6204 if (Inc->isValueDependent()) {
6205 if (!EvaluateDependentExpr(Inc, Info))
6206 return ESR_Failed;
6207 } else {
6208 FullExpressionRAII IncScope(Info);
6209 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6210 return ESR_Failed;
6211 }
6212 }
6213
6214 if (!IterScope.destroy())
6215 return ESR_Failed;
6216 }
6217 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6218 }
6219
6220 case Stmt::CXXForRangeStmtClass: {
6222 BlockScopeRAII Scope(Info);
6223
6224 // Evaluate the init-statement if present.
6225 if (FS->getInit()) {
6226 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6227 if (ESR != ESR_Succeeded) {
6228 if (ESR != ESR_Failed && !Scope.destroy())
6229 return ESR_Failed;
6230 return ESR;
6231 }
6232 }
6233
6234 // Initialize the __range variable.
6235 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6236 if (ESR != ESR_Succeeded) {
6237 if (ESR != ESR_Failed && !Scope.destroy())
6238 return ESR_Failed;
6239 return ESR;
6240 }
6241
6242 // In error-recovery cases it's possible to get here even if we failed to
6243 // synthesize the __begin and __end variables.
6244 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6245 return ESR_Failed;
6246
6247 // Create the __begin and __end iterators.
6248 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6249 if (ESR != ESR_Succeeded) {
6250 if (ESR != ESR_Failed && !Scope.destroy())
6251 return ESR_Failed;
6252 return ESR;
6253 }
6254 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6255 if (ESR != ESR_Succeeded) {
6256 if (ESR != ESR_Failed && !Scope.destroy())
6257 return ESR_Failed;
6258 return ESR;
6259 }
6260
6261 while (true) {
6262 // Condition: __begin != __end.
6263 {
6264 if (FS->getCond()->isValueDependent()) {
6265 EvaluateDependentExpr(FS->getCond(), Info);
6266 // We don't know whether to keep going or terminate the loop.
6267 return ESR_Failed;
6268 }
6269 bool Continue = true;
6270 FullExpressionRAII CondExpr(Info);
6271 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6272 return ESR_Failed;
6273 if (!Continue)
6274 break;
6275 }
6276
6277 // User's variable declaration, initialized by *__begin.
6278 BlockScopeRAII InnerScope(Info);
6279 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6280 if (ESR != ESR_Succeeded) {
6281 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6282 return ESR_Failed;
6283 return ESR;
6284 }
6285
6286 // Loop body.
6287 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6288 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6289 return ESR;
6290 if (ESR != ESR_Continue) {
6291 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6292 return ESR_Failed;
6293 return ESR;
6294 }
6295 if (FS->getInc()->isValueDependent()) {
6296 if (!EvaluateDependentExpr(FS->getInc(), Info))
6297 return ESR_Failed;
6298 } else {
6299 // Increment: ++__begin
6300 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6301 return ESR_Failed;
6302 }
6303
6304 if (!InnerScope.destroy())
6305 return ESR_Failed;
6306 }
6307
6308 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6309 }
6310
6311 case Stmt::SwitchStmtClass:
6312 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6313
6314 case Stmt::ContinueStmtClass:
6315 case Stmt::BreakStmtClass: {
6316 auto *B = cast<LoopControlStmt>(S);
6317 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6318 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6319 }
6320
6321 case Stmt::LabelStmtClass:
6322 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6323
6324 case Stmt::AttributedStmtClass: {
6325 const auto *AS = cast<AttributedStmt>(S);
6326 const auto *SS = AS->getSubStmt();
6327 MSConstexprContextRAII ConstexprContext(
6328 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6329 isa<ReturnStmt>(SS));
6330
6331 auto LO = Info.getASTContext().getLangOpts();
6332 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6333 for (auto *Attr : AS->getAttrs()) {
6334 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6335 if (!AA)
6336 continue;
6337
6338 auto *Assumption = AA->getAssumption();
6339 if (Assumption->isValueDependent())
6340 return ESR_Failed;
6341
6342 if (Assumption->HasSideEffects(Info.getASTContext()))
6343 continue;
6344
6345 bool Value;
6346 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6347 return ESR_Failed;
6348 if (!Value) {
6349 Info.CCEDiag(Assumption->getExprLoc(),
6350 diag::note_constexpr_assumption_failed);
6351 return ESR_Failed;
6352 }
6353 }
6354 }
6355
6356 return EvaluateStmt(Result, Info, SS, Case);
6357 }
6358
6359 case Stmt::CaseStmtClass:
6360 case Stmt::DefaultStmtClass:
6361 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6362 case Stmt::CXXTryStmtClass:
6363 // Evaluate try blocks by evaluating all sub statements.
6364 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6365 }
6366}
6367
6368/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6369/// default constructor. If so, we'll fold it whether or not it's marked as
6370/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6371/// so we need special handling.
6372static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6373 const CXXConstructorDecl *CD,
6374 bool IsValueInitialization) {
6375 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6376 return false;
6377
6378 // Value-initialization does not call a trivial default constructor, so such a
6379 // call is a core constant expression whether or not the constructor is
6380 // constexpr.
6381 if (!CD->isConstexpr() && !IsValueInitialization) {
6382 if (Info.getLangOpts().CPlusPlus11) {
6383 // FIXME: If DiagDecl is an implicitly-declared special member function,
6384 // we should be much more explicit about why it's not constexpr.
6385 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6386 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6387 Info.Note(CD->getLocation(), diag::note_declared_at);
6388 } else {
6389 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6390 }
6391 }
6392 return true;
6393}
6394
6395/// CheckConstexprFunction - Check that a function can be called in a constant
6396/// expression.
6397static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6399 const FunctionDecl *Definition,
6400 const Stmt *Body) {
6401 // Potential constant expressions can contain calls to declared, but not yet
6402 // defined, constexpr functions.
6403 if (Info.checkingPotentialConstantExpression() && !Definition &&
6404 Declaration->isConstexpr())
6405 return false;
6406
6407 // Bail out if the function declaration itself is invalid. We will
6408 // have produced a relevant diagnostic while parsing it, so just
6409 // note the problematic sub-expression.
6410 if (Declaration->isInvalidDecl()) {
6411 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6412 return false;
6413 }
6414
6415 // DR1872: An instantiated virtual constexpr function can't be called in a
6416 // constant expression (prior to C++20). We can still constant-fold such a
6417 // call.
6418 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6419 cast<CXXMethodDecl>(Declaration)->isVirtual())
6420 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6421
6422 if (Definition && Definition->isInvalidDecl()) {
6423 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6424 return false;
6425 }
6426
6427 // Can we evaluate this function call?
6428 if (Definition && Body &&
6429 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6430 Definition->hasAttr<MSConstexprAttr>())))
6431 return true;
6432
6433 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6434 // Special note for the assert() macro, as the normal error message falsely
6435 // implies we cannot use an assertion during constant evaluation.
6436 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6437 // FIXME: Instead of checking for an implementation-defined function,
6438 // check and evaluate the assert() macro.
6439 StringRef Name = DiagDecl->getName();
6440 bool AssertFailed =
6441 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6442 if (AssertFailed) {
6443 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6444 return false;
6445 }
6446 }
6447
6448 if (Info.getLangOpts().CPlusPlus11) {
6449 // If this function is not constexpr because it is an inherited
6450 // non-constexpr constructor, diagnose that directly.
6451 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6452 if (CD && CD->isInheritingConstructor()) {
6453 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6454 if (!Inherited->isConstexpr())
6455 DiagDecl = CD = Inherited;
6456 }
6457
6458 // FIXME: If DiagDecl is an implicitly-declared special member function
6459 // or an inheriting constructor, we should be much more explicit about why
6460 // it's not constexpr.
6461 if (CD && CD->isInheritingConstructor())
6462 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6463 << CD->getInheritedConstructor().getConstructor()->getParent();
6464 else
6465 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6466 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6467 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6468 } else {
6469 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6470 }
6471 return false;
6472}
6473
6474namespace {
6475struct CheckDynamicTypeHandler {
6477 typedef bool result_type;
6478 bool failed() { return false; }
6479 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6480 bool found(APSInt &Value, QualType SubobjType) { return true; }
6481 bool found(APFloat &Value, QualType SubobjType) { return true; }
6482};
6483} // end anonymous namespace
6484
6485/// Check that we can access the notional vptr of an object / determine its
6486/// dynamic type.
6487static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6488 AccessKinds AK, bool Polymorphic) {
6489 if (This.Designator.Invalid)
6490 return false;
6491
6492 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6493
6494 if (!Obj)
6495 return false;
6496
6497 if (!Obj.Value) {
6498 // The object is not usable in constant expressions, so we can't inspect
6499 // its value to see if it's in-lifetime or what the active union members
6500 // are. We can still check for a one-past-the-end lvalue.
6501 if (This.Designator.isOnePastTheEnd() ||
6502 This.Designator.isMostDerivedAnUnsizedArray()) {
6503 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6504 ? diag::note_constexpr_access_past_end
6505 : diag::note_constexpr_access_unsized_array)
6506 << AK;
6507 return false;
6508 } else if (Polymorphic) {
6509 // Conservatively refuse to perform a polymorphic operation if we would
6510 // not be able to read a notional 'vptr' value.
6511 if (!Info.checkingPotentialConstantExpression() ||
6512 !This.AllowConstexprUnknown) {
6513 APValue Val;
6514 This.moveInto(Val);
6515 QualType StarThisType =
6516 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6517 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6518 << AK << Val.getAsString(Info.Ctx, StarThisType);
6519 }
6520 return false;
6521 }
6522 return true;
6523 }
6524
6525 CheckDynamicTypeHandler Handler{AK};
6526 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6527}
6528
6529/// Check that the pointee of the 'this' pointer in a member function call is
6530/// either within its lifetime or in its period of construction or destruction.
6531static bool
6533 const LValue &This,
6534 const CXXMethodDecl *NamedMember) {
6535 return checkDynamicType(
6536 Info, E, This,
6537 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6538}
6539
6541 /// The dynamic class type of the object.
6543 /// The corresponding path length in the lvalue.
6544 unsigned PathLength;
6545};
6546
6547static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6548 unsigned PathLength) {
6549 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6550 Designator.Entries.size() && "invalid path length");
6551 return (PathLength == Designator.MostDerivedPathLength)
6552 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6553 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6554}
6555
6556/// Determine the dynamic type of an object.
6557static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6558 const Expr *E,
6559 LValue &This,
6560 AccessKinds AK) {
6561 // If we don't have an lvalue denoting an object of class type, there is no
6562 // meaningful dynamic type. (We consider objects of non-class type to have no
6563 // dynamic type.)
6564 if (!checkDynamicType(Info, E, This, AK,
6565 AK != AK_TypeId || This.AllowConstexprUnknown))
6566 return std::nullopt;
6567
6568 if (This.Designator.Invalid)
6569 return std::nullopt;
6570
6571 // Refuse to compute a dynamic type in the presence of virtual bases. This
6572 // shouldn't happen other than in constant-folding situations, since literal
6573 // types can't have virtual bases.
6574 //
6575 // Note that consumers of DynamicType assume that the type has no virtual
6576 // bases, and will need modifications if this restriction is relaxed.
6577 const CXXRecordDecl *Class =
6578 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6579 if (!Class || Class->getNumVBases()) {
6580 Info.FFDiag(E);
6581 return std::nullopt;
6582 }
6583
6584 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6585 // binary search here instead. But the overwhelmingly common case is that
6586 // we're not in the middle of a constructor, so it probably doesn't matter
6587 // in practice.
6588 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6589 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6590 PathLength <= Path.size(); ++PathLength) {
6591 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6592 Path.slice(0, PathLength))) {
6593 case ConstructionPhase::Bases:
6594 case ConstructionPhase::DestroyingBases:
6595 // We're constructing or destroying a base class. This is not the dynamic
6596 // type.
6597 break;
6598
6599 case ConstructionPhase::None:
6600 case ConstructionPhase::AfterBases:
6601 case ConstructionPhase::AfterFields:
6602 case ConstructionPhase::Destroying:
6603 // We've finished constructing the base classes and not yet started
6604 // destroying them again, so this is the dynamic type.
6605 return DynamicType{getBaseClassType(This.Designator, PathLength),
6606 PathLength};
6607 }
6608 }
6609
6610 // CWG issue 1517: we're constructing a base class of the object described by
6611 // 'This', so that object has not yet begun its period of construction and
6612 // any polymorphic operation on it results in undefined behavior.
6613 Info.FFDiag(E);
6614 return std::nullopt;
6615}
6616
6617/// Perform virtual dispatch.
6619 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6620 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6621 std::optional<DynamicType> DynType = ComputeDynamicType(
6622 Info, E, This,
6624 if (!DynType)
6625 return nullptr;
6626
6627 // Find the final overrider. It must be declared in one of the classes on the
6628 // path from the dynamic type to the static type.
6629 // FIXME: If we ever allow literal types to have virtual base classes, that
6630 // won't be true.
6631 const CXXMethodDecl *Callee = Found;
6632 unsigned PathLength = DynType->PathLength;
6633 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6634 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6635 const CXXMethodDecl *Overrider =
6636 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6637 if (Overrider) {
6638 Callee = Overrider;
6639 break;
6640 }
6641 }
6642
6643 // C++2a [class.abstract]p6:
6644 // the effect of making a virtual call to a pure virtual function [...] is
6645 // undefined
6646 if (Callee->isPureVirtual()) {
6647 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6648 Info.Note(Callee->getLocation(), diag::note_declared_at);
6649 return nullptr;
6650 }
6651
6652 // If necessary, walk the rest of the path to determine the sequence of
6653 // covariant adjustment steps to apply.
6654 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6655 Found->getReturnType())) {
6656 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6657 for (unsigned CovariantPathLength = PathLength + 1;
6658 CovariantPathLength != This.Designator.Entries.size();
6659 ++CovariantPathLength) {
6660 const CXXRecordDecl *NextClass =
6661 getBaseClassType(This.Designator, CovariantPathLength);
6662 const CXXMethodDecl *Next =
6663 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6664 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6665 Next->getReturnType(), CovariantAdjustmentPath.back()))
6666 CovariantAdjustmentPath.push_back(Next->getReturnType());
6667 }
6668 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6669 CovariantAdjustmentPath.back()))
6670 CovariantAdjustmentPath.push_back(Found->getReturnType());
6671 }
6672
6673 // Perform 'this' adjustment.
6674 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6675 return nullptr;
6676
6677 return Callee;
6678}
6679
6680/// Perform the adjustment from a value returned by a virtual function to
6681/// a value of the statically expected type, which may be a pointer or
6682/// reference to a base class of the returned type.
6683static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6684 APValue &Result,
6685 ArrayRef<QualType> Path) {
6686 assert(Result.isLValue() &&
6687 "unexpected kind of APValue for covariant return");
6688 if (Result.isNullPointer())
6689 return true;
6690
6691 LValue LVal;
6692 LVal.setFrom(Info.Ctx, Result);
6693
6694 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6695 for (unsigned I = 1; I != Path.size(); ++I) {
6696 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6697 assert(OldClass && NewClass && "unexpected kind of covariant return");
6698 if (OldClass != NewClass &&
6699 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6700 return false;
6701 OldClass = NewClass;
6702 }
6703
6704 LVal.moveInto(Result);
6705 return true;
6706}
6707
6708/// Determine whether \p Base, which is known to be a direct base class of
6709/// \p Derived, is a public base class.
6710static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6711 const CXXRecordDecl *Base) {
6712 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6713 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6714 if (BaseClass && declaresSameEntity(BaseClass, Base))
6715 return BaseSpec.getAccessSpecifier() == AS_public;
6716 }
6717 llvm_unreachable("Base is not a direct base of Derived");
6718}
6719
6720/// Apply the given dynamic cast operation on the provided lvalue.
6721///
6722/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6723/// to find a suitable target subobject.
6724static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6725 LValue &Ptr) {
6726 // We can't do anything with a non-symbolic pointer value.
6727 SubobjectDesignator &D = Ptr.Designator;
6728 if (D.Invalid)
6729 return false;
6730
6731 // C++ [expr.dynamic.cast]p6:
6732 // If v is a null pointer value, the result is a null pointer value.
6733 if (Ptr.isNullPointer() && !E->isGLValue())
6734 return true;
6735
6736 // For all the other cases, we need the pointer to point to an object within
6737 // its lifetime / period of construction / destruction, and we need to know
6738 // its dynamic type.
6739 std::optional<DynamicType> DynType =
6740 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6741 if (!DynType)
6742 return false;
6743
6744 // C++ [expr.dynamic.cast]p7:
6745 // If T is "pointer to cv void", then the result is a pointer to the most
6746 // derived object
6747 if (E->getType()->isVoidPointerType())
6748 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6749
6751 assert(C && "dynamic_cast target is not void pointer nor class");
6752 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6753
6754 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6755 // C++ [expr.dynamic.cast]p9:
6756 if (!E->isGLValue()) {
6757 // The value of a failed cast to pointer type is the null pointer value
6758 // of the required result type.
6759 Ptr.setNull(Info.Ctx, E->getType());
6760 return true;
6761 }
6762
6763 // A failed cast to reference type throws [...] std::bad_cast.
6764 unsigned DiagKind;
6765 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6766 DynType->Type->isDerivedFrom(C)))
6767 DiagKind = 0;
6768 else if (!Paths || Paths->begin() == Paths->end())
6769 DiagKind = 1;
6770 else if (Paths->isAmbiguous(CQT))
6771 DiagKind = 2;
6772 else {
6773 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6774 DiagKind = 3;
6775 }
6776 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6777 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6778 << Info.Ctx.getCanonicalTagType(DynType->Type)
6779 << E->getType().getUnqualifiedType();
6780 return false;
6781 };
6782
6783 // Runtime check, phase 1:
6784 // Walk from the base subobject towards the derived object looking for the
6785 // target type.
6786 for (int PathLength = Ptr.Designator.Entries.size();
6787 PathLength >= (int)DynType->PathLength; --PathLength) {
6788 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6789 if (declaresSameEntity(Class, C))
6790 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6791 // We can only walk across public inheritance edges.
6792 if (PathLength > (int)DynType->PathLength &&
6793 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6794 Class))
6795 return RuntimeCheckFailed(nullptr);
6796 }
6797
6798 // Runtime check, phase 2:
6799 // Search the dynamic type for an unambiguous public base of type C.
6800 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6801 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6802 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6803 Paths.front().Access == AS_public) {
6804 // Downcast to the dynamic type...
6805 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6806 return false;
6807 // ... then upcast to the chosen base class subobject.
6808 for (CXXBasePathElement &Elem : Paths.front())
6809 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6810 return false;
6811 return true;
6812 }
6813
6814 // Otherwise, the runtime check fails.
6815 return RuntimeCheckFailed(&Paths);
6816}
6817
6818namespace {
6819struct StartLifetimeOfUnionMemberHandler {
6820 EvalInfo &Info;
6821 const Expr *LHSExpr;
6822 const FieldDecl *Field;
6823 bool DuringInit;
6824 bool Failed = false;
6825 static const AccessKinds AccessKind = AK_Assign;
6826
6827 typedef bool result_type;
6828 bool failed() { return Failed; }
6829 bool found(APValue &Subobj, QualType SubobjType) {
6830 // We are supposed to perform no initialization but begin the lifetime of
6831 // the object. We interpret that as meaning to do what default
6832 // initialization of the object would do if all constructors involved were
6833 // trivial:
6834 // * All base, non-variant member, and array element subobjects' lifetimes
6835 // begin
6836 // * No variant members' lifetimes begin
6837 // * All scalar subobjects whose lifetimes begin have indeterminate values
6838 assert(SubobjType->isUnionType());
6839 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6840 // This union member is already active. If it's also in-lifetime, there's
6841 // nothing to do.
6842 if (Subobj.getUnionValue().hasValue())
6843 return true;
6844 } else if (DuringInit) {
6845 // We're currently in the process of initializing a different union
6846 // member. If we carried on, that initialization would attempt to
6847 // store to an inactive union member, resulting in undefined behavior.
6848 Info.FFDiag(LHSExpr,
6849 diag::note_constexpr_union_member_change_during_init);
6850 return false;
6851 }
6853 Failed = !handleDefaultInitValue(Field->getType(), Result);
6854 Subobj.setUnion(Field, Result);
6855 return true;
6856 }
6857 bool found(APSInt &Value, QualType SubobjType) {
6858 llvm_unreachable("wrong value kind for union object");
6859 }
6860 bool found(APFloat &Value, QualType SubobjType) {
6861 llvm_unreachable("wrong value kind for union object");
6862 }
6863};
6864} // end anonymous namespace
6865
6866const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6867
6868/// Handle a builtin simple-assignment or a call to a trivial assignment
6869/// operator whose left-hand side might involve a union member access. If it
6870/// does, implicitly start the lifetime of any accessed union elements per
6871/// C++20 [class.union]5.
6872static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6873 const Expr *LHSExpr,
6874 const LValue &LHS) {
6875 if (LHS.InvalidBase || LHS.Designator.Invalid)
6876 return false;
6877
6879 // C++ [class.union]p5:
6880 // define the set S(E) of subexpressions of E as follows:
6881 unsigned PathLength = LHS.Designator.Entries.size();
6882 for (const Expr *E = LHSExpr; E != nullptr;) {
6883 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6884 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6885 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6886 // Note that we can't implicitly start the lifetime of a reference,
6887 // so we don't need to proceed any further if we reach one.
6888 if (!FD || FD->getType()->isReferenceType())
6889 break;
6890
6891 // ... and also contains A.B if B names a union member ...
6892 if (FD->getParent()->isUnion()) {
6893 // ... of a non-class, non-array type, or of a class type with a
6894 // trivial default constructor that is not deleted, or an array of
6895 // such types.
6896 auto *RD =
6897 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6898 if (!RD || RD->hasTrivialDefaultConstructor())
6899 UnionPathLengths.push_back({PathLength - 1, FD});
6900 }
6901
6902 E = ME->getBase();
6903 --PathLength;
6904 assert(declaresSameEntity(FD,
6905 LHS.Designator.Entries[PathLength]
6906 .getAsBaseOrMember().getPointer()));
6907
6908 // -- If E is of the form A[B] and is interpreted as a built-in array
6909 // subscripting operator, S(E) is [S(the array operand, if any)].
6910 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6911 // Step over an ArrayToPointerDecay implicit cast.
6912 auto *Base = ASE->getBase()->IgnoreImplicit();
6913 if (!Base->getType()->isArrayType())
6914 break;
6915
6916 E = Base;
6917 --PathLength;
6918
6919 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6920 // Step over a derived-to-base conversion.
6921 E = ICE->getSubExpr();
6922 if (ICE->getCastKind() == CK_NoOp)
6923 continue;
6924 if (ICE->getCastKind() != CK_DerivedToBase &&
6925 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6926 break;
6927 // Walk path backwards as we walk up from the base to the derived class.
6928 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6929 if (Elt->isVirtual()) {
6930 // A class with virtual base classes never has a trivial default
6931 // constructor, so S(E) is empty in this case.
6932 E = nullptr;
6933 break;
6934 }
6935
6936 --PathLength;
6937 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6938 LHS.Designator.Entries[PathLength]
6939 .getAsBaseOrMember().getPointer()));
6940 }
6941
6942 // -- Otherwise, S(E) is empty.
6943 } else {
6944 break;
6945 }
6946 }
6947
6948 // Common case: no unions' lifetimes are started.
6949 if (UnionPathLengths.empty())
6950 return true;
6951
6952 // if modification of X [would access an inactive union member], an object
6953 // of the type of X is implicitly created
6954 CompleteObject Obj =
6955 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6956 if (!Obj)
6957 return false;
6958 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6959 llvm::reverse(UnionPathLengths)) {
6960 // Form a designator for the union object.
6961 SubobjectDesignator D = LHS.Designator;
6962 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6963
6964 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6965 ConstructionPhase::AfterBases;
6966 StartLifetimeOfUnionMemberHandler StartLifetime{
6967 Info, LHSExpr, LengthAndField.second, DuringInit};
6968 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6969 return false;
6970 }
6971
6972 return true;
6973}
6974
6975static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6976 CallRef Call, EvalInfo &Info, bool NonNull = false,
6977 APValue **EvaluatedArg = nullptr) {
6978 LValue LV;
6979 // Create the parameter slot and register its destruction. For a vararg
6980 // argument, create a temporary.
6981 // FIXME: For calling conventions that destroy parameters in the callee,
6982 // should we consider performing destruction when the function returns
6983 // instead?
6984 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6985 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6986 ScopeKind::Call, LV);
6987 if (!EvaluateInPlace(V, Info, LV, Arg))
6988 return false;
6989
6990 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6991 // undefined behavior, so is non-constant.
6992 if (NonNull && V.isLValue() && V.isNullPointer()) {
6993 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6994 return false;
6995 }
6996
6997 if (EvaluatedArg)
6998 *EvaluatedArg = &V;
6999
7000 return true;
7001}
7002
7003/// Evaluate the arguments to a function call.
7004static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7005 EvalInfo &Info, const FunctionDecl *Callee,
7006 bool RightToLeft = false,
7007 LValue *ObjectArg = nullptr) {
7008 bool Success = true;
7009 llvm::SmallBitVector ForbiddenNullArgs;
7010 if (Callee->hasAttr<NonNullAttr>()) {
7011 ForbiddenNullArgs.resize(Args.size());
7012 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7013 if (!Attr->args_size()) {
7014 ForbiddenNullArgs.set();
7015 break;
7016 } else
7017 for (auto Idx : Attr->args()) {
7018 unsigned ASTIdx = Idx.getASTIndex();
7019 if (ASTIdx >= Args.size())
7020 continue;
7021 ForbiddenNullArgs[ASTIdx] = true;
7022 }
7023 }
7024 }
7025 for (unsigned I = 0; I < Args.size(); I++) {
7026 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7027 const ParmVarDecl *PVD =
7028 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7029 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7030 APValue *That = nullptr;
7031 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7032 // If we're checking for a potential constant expression, evaluate all
7033 // initializers even if some of them fail.
7034 if (!Info.noteFailure())
7035 return false;
7036 Success = false;
7037 }
7038 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7039 ObjectArg->setFrom(Info.Ctx, *That);
7040 }
7041 return Success;
7042}
7043
7044/// Perform a trivial copy from Param, which is the parameter of a copy or move
7045/// constructor or assignment operator.
7046static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7047 const Expr *E, APValue &Result,
7048 bool CopyObjectRepresentation) {
7049 // Find the reference argument.
7050 CallStackFrame *Frame = Info.CurrentCall;
7051 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7052 if (!RefValue) {
7053 Info.FFDiag(E);
7054 return false;
7055 }
7056
7057 // Copy out the contents of the RHS object.
7058 LValue RefLValue;
7059 RefLValue.setFrom(Info.Ctx, *RefValue);
7061 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7062 CopyObjectRepresentation);
7063}
7064
7065/// Evaluate a function call.
7067 const FunctionDecl *Callee,
7068 const LValue *ObjectArg, const Expr *E,
7069 ArrayRef<const Expr *> Args, CallRef Call,
7070 const Stmt *Body, EvalInfo &Info,
7071 APValue &Result, const LValue *ResultSlot) {
7072 if (!Info.CheckCallLimit(CallLoc))
7073 return false;
7074
7075 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7076
7077 // For a trivial copy or move assignment, perform an APValue copy. This is
7078 // essential for unions, where the operations performed by the assignment
7079 // operator cannot be represented as statements.
7080 //
7081 // Skip this for non-union classes with no fields; in that case, the defaulted
7082 // copy/move does not actually read the object.
7083 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7084 if (MD && MD->isDefaulted() &&
7085 (MD->getParent()->isUnion() ||
7086 (MD->isTrivial() &&
7088 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7089 assert(ObjectArg &&
7091 APValue RHSValue;
7092 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7093 MD->getParent()->isUnion()))
7094 return false;
7095
7096 LValue Obj;
7097 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7099 RHSValue))
7100 return false;
7101 ObjectArg->moveInto(Result);
7102 return true;
7103 } else if (MD && isLambdaCallOperator(MD)) {
7104 // We're in a lambda; determine the lambda capture field maps unless we're
7105 // just constexpr checking a lambda's call operator. constexpr checking is
7106 // done before the captures have been added to the closure object (unless
7107 // we're inferring constexpr-ness), so we don't have access to them in this
7108 // case. But since we don't need the captures to constexpr check, we can
7109 // just ignore them.
7110 if (!Info.checkingPotentialConstantExpression())
7111 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7112 Frame.LambdaThisCaptureField);
7113 }
7114
7115 StmtResult Ret = {Result, ResultSlot};
7116 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7117 if (ESR == ESR_Succeeded) {
7118 if (Callee->getReturnType()->isVoidType())
7119 return true;
7120 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7121 }
7122 return ESR == ESR_Returned;
7123}
7124
7125/// Evaluate a constructor call.
7126static bool HandleConstructorCall(const Expr *E, const LValue &This,
7127 CallRef Call,
7129 EvalInfo &Info, APValue &Result) {
7130 SourceLocation CallLoc = E->getExprLoc();
7131 if (!Info.CheckCallLimit(CallLoc))
7132 return false;
7133
7134 const CXXRecordDecl *RD = Definition->getParent();
7135 if (RD->getNumVBases()) {
7136 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7137 return false;
7138 }
7139
7140 EvalInfo::EvaluatingConstructorRAII EvalObj(
7141 Info,
7142 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7143 RD->getNumBases());
7144 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7145
7146 // FIXME: Creating an APValue just to hold a nonexistent return value is
7147 // wasteful.
7148 APValue RetVal;
7149 StmtResult Ret = {RetVal, nullptr};
7150
7151 // If it's a delegating constructor, delegate.
7152 if (Definition->isDelegatingConstructor()) {
7154 if ((*I)->getInit()->isValueDependent()) {
7155 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7156 return false;
7157 } else {
7158 FullExpressionRAII InitScope(Info);
7159 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7160 !InitScope.destroy())
7161 return false;
7162 }
7163 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7164 }
7165
7166 // For a trivial copy or move constructor, perform an APValue copy. This is
7167 // essential for unions (or classes with anonymous union members), where the
7168 // operations performed by the constructor cannot be represented by
7169 // ctor-initializers.
7170 //
7171 // Skip this for empty non-union classes; we should not perform an
7172 // lvalue-to-rvalue conversion on them because their copy constructor does not
7173 // actually read them.
7174 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7175 (Definition->getParent()->isUnion() ||
7176 (Definition->isTrivial() &&
7178 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7179 Definition->getParent()->isUnion());
7180 }
7181
7182 // Reserve space for the struct members.
7183 if (!Result.hasValue()) {
7184 if (!RD->isUnion())
7185 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7186 RD->getNumFields());
7187 else
7188 // A union starts with no active member.
7189 Result = APValue((const FieldDecl*)nullptr);
7190 }
7191
7192 if (RD->isInvalidDecl()) return false;
7193 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7194
7195 // A scope for temporaries lifetime-extended by reference members.
7196 BlockScopeRAII LifetimeExtendedScope(Info);
7197
7198 bool Success = true;
7199 unsigned BasesSeen = 0;
7200#ifndef NDEBUG
7202#endif
7204 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7205 // We might be initializing the same field again if this is an indirect
7206 // field initialization.
7207 if (FieldIt == RD->field_end() ||
7208 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7209 assert(Indirect && "fields out of order?");
7210 return;
7211 }
7212
7213 // Default-initialize any fields with no explicit initializer.
7214 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7215 assert(FieldIt != RD->field_end() && "missing field?");
7216 if (!FieldIt->isUnnamedBitField())
7218 FieldIt->getType(),
7219 Result.getStructField(FieldIt->getFieldIndex()));
7220 }
7221 ++FieldIt;
7222 };
7223 for (const auto *I : Definition->inits()) {
7224 LValue Subobject = This;
7225 LValue SubobjectParent = This;
7226 APValue *Value = &Result;
7227
7228 // Determine the subobject to initialize.
7229 FieldDecl *FD = nullptr;
7230 if (I->isBaseInitializer()) {
7231 QualType BaseType(I->getBaseClass(), 0);
7232#ifndef NDEBUG
7233 // Non-virtual base classes are initialized in the order in the class
7234 // definition. We have already checked for virtual base classes.
7235 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7236 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7237 "base class initializers not in expected order");
7238 ++BaseIt;
7239#endif
7240 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7241 BaseType->getAsCXXRecordDecl(), &Layout))
7242 return false;
7243 Value = &Result.getStructBase(BasesSeen++);
7244 } else if ((FD = I->getMember())) {
7245 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7246 return false;
7247 if (RD->isUnion()) {
7248 Result = APValue(FD);
7249 Value = &Result.getUnionValue();
7250 } else {
7251 SkipToField(FD, false);
7252 Value = &Result.getStructField(FD->getFieldIndex());
7253 }
7254 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7255 // Walk the indirect field decl's chain to find the object to initialize,
7256 // and make sure we've initialized every step along it.
7257 auto IndirectFieldChain = IFD->chain();
7258 for (auto *C : IndirectFieldChain) {
7259 FD = cast<FieldDecl>(C);
7261 // Switch the union field if it differs. This happens if we had
7262 // preceding zero-initialization, and we're now initializing a union
7263 // subobject other than the first.
7264 // FIXME: In this case, the values of the other subobjects are
7265 // specified, since zero-initialization sets all padding bits to zero.
7266 if (!Value->hasValue() ||
7267 (Value->isUnion() &&
7268 !declaresSameEntity(Value->getUnionField(), FD))) {
7269 if (CD->isUnion())
7270 *Value = APValue(FD);
7271 else
7272 // FIXME: This immediately starts the lifetime of all members of
7273 // an anonymous struct. It would be preferable to strictly start
7274 // member lifetime in initialization order.
7276 *Value);
7277 }
7278 // Store Subobject as its parent before updating it for the last element
7279 // in the chain.
7280 if (C == IndirectFieldChain.back())
7281 SubobjectParent = Subobject;
7282 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7283 return false;
7284 if (CD->isUnion())
7285 Value = &Value->getUnionValue();
7286 else {
7287 if (C == IndirectFieldChain.front() && !RD->isUnion())
7288 SkipToField(FD, true);
7289 Value = &Value->getStructField(FD->getFieldIndex());
7290 }
7291 }
7292 } else {
7293 llvm_unreachable("unknown base initializer kind");
7294 }
7295
7296 // Need to override This for implicit field initializers as in this case
7297 // This refers to innermost anonymous struct/union containing initializer,
7298 // not to currently constructed class.
7299 const Expr *Init = I->getInit();
7300 if (Init->isValueDependent()) {
7301 if (!EvaluateDependentExpr(Init, Info))
7302 return false;
7303 } else {
7304 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7306 FullExpressionRAII InitScope(Info);
7307 if (FD && FD->getType()->isReferenceType() &&
7308 !FD->getType()->isFunctionReferenceType()) {
7309 LValue Result;
7310 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7311 *Value)) {
7312 if (!Info.noteFailure())
7313 return false;
7314 Success = false;
7315 }
7316 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7317 (FD && FD->isBitField() &&
7318 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7319 // If we're checking for a potential constant expression, evaluate all
7320 // initializers even if some of them fail.
7321 if (!Info.noteFailure())
7322 return false;
7323 Success = false;
7324 }
7325 }
7326
7327 // This is the point at which the dynamic type of the object becomes this
7328 // class type.
7329 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7330 EvalObj.finishedConstructingBases();
7331 }
7332
7333 // Default-initialize any remaining fields.
7334 if (!RD->isUnion()) {
7335 for (; FieldIt != RD->field_end(); ++FieldIt) {
7336 if (!FieldIt->isUnnamedBitField())
7338 FieldIt->getType(),
7339 Result.getStructField(FieldIt->getFieldIndex()));
7340 }
7341 }
7342
7343 EvalObj.finishedConstructingFields();
7344
7345 return Success &&
7346 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7347 LifetimeExtendedScope.destroy();
7348}
7349
7350static bool HandleConstructorCall(const Expr *E, const LValue &This,
7353 EvalInfo &Info, APValue &Result) {
7354 CallScopeRAII CallScope(Info);
7355 CallRef Call = Info.CurrentCall->createCall(Definition);
7356 if (!EvaluateArgs(Args, Call, Info, Definition))
7357 return false;
7358
7359 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7360 CallScope.destroy();
7361}
7362
7363static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7364 const LValue &This, APValue &Value,
7365 QualType T) {
7366 // Objects can only be destroyed while they're within their lifetimes.
7367 // FIXME: We have no representation for whether an object of type nullptr_t
7368 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7369 // as indeterminate instead?
7370 if (Value.isAbsent() && !T->isNullPtrType()) {
7371 APValue Printable;
7372 This.moveInto(Printable);
7373 Info.FFDiag(CallRange.getBegin(),
7374 diag::note_constexpr_destroy_out_of_lifetime)
7375 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7376 return false;
7377 }
7378
7379 // Invent an expression for location purposes.
7380 // FIXME: We shouldn't need to do this.
7381 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7382
7383 // For arrays, destroy elements right-to-left.
7384 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7385 uint64_t Size = CAT->getZExtSize();
7386 QualType ElemT = CAT->getElementType();
7387
7388 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7389 return false;
7390
7391 LValue ElemLV = This;
7392 ElemLV.addArray(Info, &LocE, CAT);
7393 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7394 return false;
7395
7396 // Ensure that we have actual array elements available to destroy; the
7397 // destructors might mutate the value, so we can't run them on the array
7398 // filler.
7399 if (Size && Size > Value.getArrayInitializedElts())
7400 expandArray(Value, Value.getArraySize() - 1);
7401
7402 // The size of the array might have been reduced by
7403 // a placement new.
7404 for (Size = Value.getArraySize(); Size != 0; --Size) {
7405 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7406 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7407 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7408 return false;
7409 }
7410
7411 // End the lifetime of this array now.
7412 Value = APValue();
7413 return true;
7414 }
7415
7416 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7417 if (!RD) {
7418 if (T.isDestructedType()) {
7419 Info.FFDiag(CallRange.getBegin(),
7420 diag::note_constexpr_unsupported_destruction)
7421 << T;
7422 return false;
7423 }
7424
7425 Value = APValue();
7426 return true;
7427 }
7428
7429 if (RD->getNumVBases()) {
7430 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7431 return false;
7432 }
7433
7434 const CXXDestructorDecl *DD = RD->getDestructor();
7435 if (!DD && !RD->hasTrivialDestructor()) {
7436 Info.FFDiag(CallRange.getBegin());
7437 return false;
7438 }
7439
7440 if (!DD || DD->isTrivial() ||
7441 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7442 // A trivial destructor just ends the lifetime of the object. Check for
7443 // this case before checking for a body, because we might not bother
7444 // building a body for a trivial destructor. Note that it doesn't matter
7445 // whether the destructor is constexpr in this case; all trivial
7446 // destructors are constexpr.
7447 //
7448 // If an anonymous union would be destroyed, some enclosing destructor must
7449 // have been explicitly defined, and the anonymous union destruction should
7450 // have no effect.
7451 Value = APValue();
7452 return true;
7453 }
7454
7455 if (!Info.CheckCallLimit(CallRange.getBegin()))
7456 return false;
7457
7458 const FunctionDecl *Definition = nullptr;
7459 const Stmt *Body = DD->getBody(Definition);
7460
7461 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7462 return false;
7463
7464 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7465 CallRef());
7466
7467 // We're now in the period of destruction of this object.
7468 unsigned BasesLeft = RD->getNumBases();
7469 EvalInfo::EvaluatingDestructorRAII EvalObj(
7470 Info,
7471 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7472 if (!EvalObj.DidInsert) {
7473 // C++2a [class.dtor]p19:
7474 // the behavior is undefined if the destructor is invoked for an object
7475 // whose lifetime has ended
7476 // (Note that formally the lifetime ends when the period of destruction
7477 // begins, even though certain uses of the object remain valid until the
7478 // period of destruction ends.)
7479 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7480 return false;
7481 }
7482
7483 // FIXME: Creating an APValue just to hold a nonexistent return value is
7484 // wasteful.
7485 APValue RetVal;
7486 StmtResult Ret = {RetVal, nullptr};
7487 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7488 return false;
7489
7490 // A union destructor does not implicitly destroy its members.
7491 if (RD->isUnion())
7492 return true;
7493
7494 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7495
7496 // We don't have a good way to iterate fields in reverse, so collect all the
7497 // fields first and then walk them backwards.
7498 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7499 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7500 if (FD->isUnnamedBitField())
7501 continue;
7502
7503 LValue Subobject = This;
7504 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7505 return false;
7506
7507 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7508 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7509 FD->getType()))
7510 return false;
7511 }
7512
7513 if (BasesLeft != 0)
7514 EvalObj.startedDestroyingBases();
7515
7516 // Destroy base classes in reverse order.
7517 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7518 --BasesLeft;
7519
7520 QualType BaseType = Base.getType();
7521 LValue Subobject = This;
7522 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7523 BaseType->getAsCXXRecordDecl(), &Layout))
7524 return false;
7525
7526 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7527 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7528 BaseType))
7529 return false;
7530 }
7531 assert(BasesLeft == 0 && "NumBases was wrong?");
7532
7533 // The period of destruction ends now. The object is gone.
7534 Value = APValue();
7535 return true;
7536}
7537
7538namespace {
7539struct DestroyObjectHandler {
7540 EvalInfo &Info;
7541 const Expr *E;
7542 const LValue &This;
7543 const AccessKinds AccessKind;
7544
7545 typedef bool result_type;
7546 bool failed() { return false; }
7547 bool found(APValue &Subobj, QualType SubobjType) {
7548 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7549 SubobjType);
7550 }
7551 bool found(APSInt &Value, QualType SubobjType) {
7552 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7553 return false;
7554 }
7555 bool found(APFloat &Value, QualType SubobjType) {
7556 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7557 return false;
7558 }
7559};
7560}
7561
7562/// Perform a destructor or pseudo-destructor call on the given object, which
7563/// might in general not be a complete object.
7564static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7565 const LValue &This, QualType ThisType) {
7566 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7567 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7568 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7569}
7570
7571/// Destroy and end the lifetime of the given complete object.
7572static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7574 QualType T) {
7575 // If we've had an unmodeled side-effect, we can't rely on mutable state
7576 // (such as the object we're about to destroy) being correct.
7577 if (Info.EvalStatus.HasSideEffects)
7578 return false;
7579
7580 LValue LV;
7581 LV.set({LVBase});
7582 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7583}
7584
7585/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7586static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7587 LValue &Result) {
7588 if (Info.checkingPotentialConstantExpression() ||
7589 Info.SpeculativeEvaluationDepth)
7590 return false;
7591
7592 // This is permitted only within a call to std::allocator<T>::allocate.
7593 auto Caller = Info.getStdAllocatorCaller("allocate");
7594 if (!Caller) {
7595 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7596 ? diag::note_constexpr_new_untyped
7597 : diag::note_constexpr_new);
7598 return false;
7599 }
7600
7601 QualType ElemType = Caller.ElemType;
7602 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7603 Info.FFDiag(E->getExprLoc(),
7604 diag::note_constexpr_new_not_complete_object_type)
7605 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7606 return false;
7607 }
7608
7609 APSInt ByteSize;
7610 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7611 return false;
7612 bool IsNothrow = false;
7613 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7614 EvaluateIgnoredValue(Info, E->getArg(I));
7615 IsNothrow |= E->getType()->isNothrowT();
7616 }
7617
7618 CharUnits ElemSize;
7619 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7620 return false;
7621 APInt Size, Remainder;
7622 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7623 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7624 if (Remainder != 0) {
7625 // This likely indicates a bug in the implementation of 'std::allocator'.
7626 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7627 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7628 return false;
7629 }
7630
7631 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7632 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7633 if (IsNothrow) {
7634 Result.setNull(Info.Ctx, E->getType());
7635 return true;
7636 }
7637 return false;
7638 }
7639
7640 QualType AllocType = Info.Ctx.getConstantArrayType(
7641 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7642 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7643 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7644 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7645 return true;
7646}
7647
7649 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7650 if (CXXDestructorDecl *DD = RD->getDestructor())
7651 return DD->isVirtual();
7652 return false;
7653}
7654
7656 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7657 if (CXXDestructorDecl *DD = RD->getDestructor())
7658 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7659 return nullptr;
7660}
7661
7662/// Check that the given object is a suitable pointer to a heap allocation that
7663/// still exists and is of the right kind for the purpose of a deletion.
7664///
7665/// On success, returns the heap allocation to deallocate. On failure, produces
7666/// a diagnostic and returns std::nullopt.
7667static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7668 const LValue &Pointer,
7669 DynAlloc::Kind DeallocKind) {
7670 auto PointerAsString = [&] {
7671 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7672 };
7673
7674 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7675 if (!DA) {
7676 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7677 << PointerAsString();
7678 if (Pointer.Base)
7679 NoteLValueLocation(Info, Pointer.Base);
7680 return std::nullopt;
7681 }
7682
7683 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7684 if (!Alloc) {
7685 Info.FFDiag(E, diag::note_constexpr_double_delete);
7686 return std::nullopt;
7687 }
7688
7689 if (DeallocKind != (*Alloc)->getKind()) {
7690 QualType AllocType = Pointer.Base.getDynamicAllocType();
7691 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7692 << DeallocKind << (*Alloc)->getKind() << AllocType;
7693 NoteLValueLocation(Info, Pointer.Base);
7694 return std::nullopt;
7695 }
7696
7697 bool Subobject = false;
7698 if (DeallocKind == DynAlloc::New) {
7699 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7700 Pointer.Designator.isOnePastTheEnd();
7701 } else {
7702 Subobject = Pointer.Designator.Entries.size() != 1 ||
7703 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7704 }
7705 if (Subobject) {
7706 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7707 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7708 return std::nullopt;
7709 }
7710
7711 return Alloc;
7712}
7713
7714// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7715static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7716 if (Info.checkingPotentialConstantExpression() ||
7717 Info.SpeculativeEvaluationDepth)
7718 return false;
7719
7720 // This is permitted only within a call to std::allocator<T>::deallocate.
7721 if (!Info.getStdAllocatorCaller("deallocate")) {
7722 Info.FFDiag(E->getExprLoc());
7723 return true;
7724 }
7725
7726 LValue Pointer;
7727 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7728 return false;
7729 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7730 EvaluateIgnoredValue(Info, E->getArg(I));
7731
7732 if (Pointer.Designator.Invalid)
7733 return false;
7734
7735 // Deleting a null pointer would have no effect, but it's not permitted by
7736 // std::allocator<T>::deallocate's contract.
7737 if (Pointer.isNullPointer()) {
7738 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7739 return true;
7740 }
7741
7742 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7743 return false;
7744
7745 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7746 return true;
7747}
7748
7749//===----------------------------------------------------------------------===//
7750// Generic Evaluation
7751//===----------------------------------------------------------------------===//
7752namespace {
7753
7754class BitCastBuffer {
7755 // FIXME: We're going to need bit-level granularity when we support
7756 // bit-fields.
7757 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7758 // we don't support a host or target where that is the case. Still, we should
7759 // use a more generic type in case we ever do.
7760 SmallVector<std::optional<unsigned char>, 32> Bytes;
7761
7762 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7763 "Need at least 8 bit unsigned char");
7764
7765 bool TargetIsLittleEndian;
7766
7767public:
7768 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7769 : Bytes(Width.getQuantity()),
7770 TargetIsLittleEndian(TargetIsLittleEndian) {}
7771
7772 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7773 SmallVectorImpl<unsigned char> &Output) const {
7774 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7775 // If a byte of an integer is uninitialized, then the whole integer is
7776 // uninitialized.
7777 if (!Bytes[I.getQuantity()])
7778 return false;
7779 Output.push_back(*Bytes[I.getQuantity()]);
7780 }
7781 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7782 std::reverse(Output.begin(), Output.end());
7783 return true;
7784 }
7785
7786 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7787 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7788 std::reverse(Input.begin(), Input.end());
7789
7790 size_t Index = 0;
7791 for (unsigned char Byte : Input) {
7792 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7793 Bytes[Offset.getQuantity() + Index] = Byte;
7794 ++Index;
7795 }
7796 }
7797
7798 size_t size() { return Bytes.size(); }
7799};
7800
7801/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7802/// target would represent the value at runtime.
7803class APValueToBufferConverter {
7804 EvalInfo &Info;
7805 BitCastBuffer Buffer;
7806 const CastExpr *BCE;
7807
7808 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7809 const CastExpr *BCE)
7810 : Info(Info),
7811 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7812 BCE(BCE) {}
7813
7814 bool visit(const APValue &Val, QualType Ty) {
7815 return visit(Val, Ty, CharUnits::fromQuantity(0));
7816 }
7817
7818 // Write out Val with type Ty into Buffer starting at Offset.
7819 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7820 assert((size_t)Offset.getQuantity() <= Buffer.size());
7821
7822 // As a special case, nullptr_t has an indeterminate value.
7823 if (Ty->isNullPtrType())
7824 return true;
7825
7826 // Dig through Src to find the byte at SrcOffset.
7827 switch (Val.getKind()) {
7829 case APValue::None:
7830 return true;
7831
7832 case APValue::Int:
7833 return visitInt(Val.getInt(), Ty, Offset);
7834 case APValue::Float:
7835 return visitFloat(Val.getFloat(), Ty, Offset);
7836 case APValue::Array:
7837 return visitArray(Val, Ty, Offset);
7838 case APValue::Struct:
7839 return visitRecord(Val, Ty, Offset);
7840 case APValue::Vector:
7841 return visitVector(Val, Ty, Offset);
7842
7845 return visitComplex(Val, Ty, Offset);
7847 // FIXME: We should support these.
7848
7849 case APValue::Union:
7852 Info.FFDiag(BCE->getBeginLoc(),
7853 diag::note_constexpr_bit_cast_unsupported_type)
7854 << Ty;
7855 return false;
7856 }
7857
7858 case APValue::LValue:
7859 llvm_unreachable("LValue subobject in bit_cast?");
7860 }
7861 llvm_unreachable("Unhandled APValue::ValueKind");
7862 }
7863
7864 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7865 const RecordDecl *RD = Ty->getAsRecordDecl();
7866 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7867
7868 // Visit the base classes.
7869 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7870 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7871 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7872 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7873 const APValue &Base = Val.getStructBase(I);
7874
7875 // Can happen in error cases.
7876 if (!Base.isStruct())
7877 return false;
7878
7879 if (!visitRecord(Base, BS.getType(),
7880 Layout.getBaseClassOffset(BaseDecl) + Offset))
7881 return false;
7882 }
7883 }
7884
7885 // Visit the fields.
7886 unsigned FieldIdx = 0;
7887 for (FieldDecl *FD : RD->fields()) {
7888 if (FD->isBitField()) {
7889 Info.FFDiag(BCE->getBeginLoc(),
7890 diag::note_constexpr_bit_cast_unsupported_bitfield);
7891 return false;
7892 }
7893
7894 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7895
7896 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7897 "only bit-fields can have sub-char alignment");
7898 CharUnits FieldOffset =
7899 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7900 QualType FieldTy = FD->getType();
7901 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7902 return false;
7903 ++FieldIdx;
7904 }
7905
7906 return true;
7907 }
7908
7909 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7910 const auto *CAT =
7911 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7912 if (!CAT)
7913 return false;
7914
7915 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7916 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7917 unsigned ArraySize = Val.getArraySize();
7918 // First, initialize the initialized elements.
7919 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7920 const APValue &SubObj = Val.getArrayInitializedElt(I);
7921 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7922 return false;
7923 }
7924
7925 // Next, initialize the rest of the array using the filler.
7926 if (Val.hasArrayFiller()) {
7927 const APValue &Filler = Val.getArrayFiller();
7928 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7929 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7930 return false;
7931 }
7932 }
7933
7934 return true;
7935 }
7936
7937 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7938 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7939 QualType EltTy = ComplexTy->getElementType();
7940 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7941 bool IsInt = Val.isComplexInt();
7942
7943 if (IsInt) {
7944 if (!visitInt(Val.getComplexIntReal(), EltTy,
7945 Offset + (0 * EltSizeChars)))
7946 return false;
7947 if (!visitInt(Val.getComplexIntImag(), EltTy,
7948 Offset + (1 * EltSizeChars)))
7949 return false;
7950 } else {
7951 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7952 Offset + (0 * EltSizeChars)))
7953 return false;
7954 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7955 Offset + (1 * EltSizeChars)))
7956 return false;
7957 }
7958
7959 return true;
7960 }
7961
7962 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7963 const VectorType *VTy = Ty->castAs<VectorType>();
7964 QualType EltTy = VTy->getElementType();
7965 unsigned NElts = VTy->getNumElements();
7966
7967 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7968 // Special handling for OpenCL bool vectors:
7969 // Since these vectors are stored as packed bits, but we can't write
7970 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7971 // together into an appropriately sized APInt and write them all out at
7972 // once. Because we don't accept vectors where NElts * EltSize isn't a
7973 // multiple of the char size, there will be no padding space, so we don't
7974 // have to worry about writing data which should have been left
7975 // uninitialized.
7976 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7977
7978 llvm::APInt Res = llvm::APInt::getZero(NElts);
7979 for (unsigned I = 0; I < NElts; ++I) {
7980 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7981 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7982 "bool vector element must be 1-bit unsigned integer!");
7983
7984 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7985 }
7986
7987 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7988 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7989 Buffer.writeObject(Offset, Bytes);
7990 } else {
7991 // Iterate over each of the elements and write them out to the buffer at
7992 // the appropriate offset.
7993 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7994 for (unsigned I = 0; I < NElts; ++I) {
7995 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7996 return false;
7997 }
7998 }
7999
8000 return true;
8001 }
8002
8003 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8004 APSInt AdjustedVal = Val;
8005 unsigned Width = AdjustedVal.getBitWidth();
8006 if (Ty->isBooleanType()) {
8007 Width = Info.Ctx.getTypeSize(Ty);
8008 AdjustedVal = AdjustedVal.extend(Width);
8009 }
8010
8011 SmallVector<uint8_t, 8> Bytes(Width / 8);
8012 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8013 Buffer.writeObject(Offset, Bytes);
8014 return true;
8015 }
8016
8017 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8018 APSInt AsInt(Val.bitcastToAPInt());
8019 return visitInt(AsInt, Ty, Offset);
8020 }
8021
8022public:
8023 static std::optional<BitCastBuffer>
8024 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8025 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8026 APValueToBufferConverter Converter(Info, DstSize, BCE);
8027 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8028 return std::nullopt;
8029 return Converter.Buffer;
8030 }
8031};
8032
8033/// Write an BitCastBuffer into an APValue.
8034class BufferToAPValueConverter {
8035 EvalInfo &Info;
8036 const BitCastBuffer &Buffer;
8037 const CastExpr *BCE;
8038
8039 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8040 const CastExpr *BCE)
8041 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8042
8043 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8044 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8045 // Ideally this will be unreachable.
8046 std::nullopt_t unsupportedType(QualType Ty) {
8047 Info.FFDiag(BCE->getBeginLoc(),
8048 diag::note_constexpr_bit_cast_unsupported_type)
8049 << Ty;
8050 return std::nullopt;
8051 }
8052
8053 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8054 Info.FFDiag(BCE->getBeginLoc(),
8055 diag::note_constexpr_bit_cast_unrepresentable_value)
8056 << Ty << toString(Val, /*Radix=*/10);
8057 return std::nullopt;
8058 }
8059
8060 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8061 const EnumType *EnumSugar = nullptr) {
8062 if (T->isNullPtrType()) {
8063 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8064 return APValue((Expr *)nullptr,
8065 /*Offset=*/CharUnits::fromQuantity(NullValue),
8066 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8067 }
8068
8069 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8070
8071 // Work around floating point types that contain unused padding bytes. This
8072 // is really just `long double` on x86, which is the only fundamental type
8073 // with padding bytes.
8074 if (T->isRealFloatingType()) {
8075 const llvm::fltSemantics &Semantics =
8076 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8077 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8078 assert(NumBits % 8 == 0);
8079 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8080 if (NumBytes != SizeOf)
8081 SizeOf = NumBytes;
8082 }
8083
8084 SmallVector<uint8_t, 8> Bytes;
8085 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8086 // If this is std::byte or unsigned char, then its okay to store an
8087 // indeterminate value.
8088 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8089 bool IsUChar =
8090 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8091 T->isSpecificBuiltinType(BuiltinType::Char_U));
8092 if (!IsStdByte && !IsUChar) {
8093 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8094 Info.FFDiag(BCE->getExprLoc(),
8095 diag::note_constexpr_bit_cast_indet_dest)
8096 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8097 return std::nullopt;
8098 }
8099
8101 }
8102
8103 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8104 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8105
8107 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8108
8109 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8110 if (IntWidth != Val.getBitWidth()) {
8111 APSInt Truncated = Val.trunc(IntWidth);
8112 if (Truncated.extend(Val.getBitWidth()) != Val)
8113 return unrepresentableValue(QualType(T, 0), Val);
8114 Val = Truncated;
8115 }
8116
8117 return APValue(Val);
8118 }
8119
8120 if (T->isRealFloatingType()) {
8121 const llvm::fltSemantics &Semantics =
8122 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8123 return APValue(APFloat(Semantics, Val));
8124 }
8125
8126 return unsupportedType(QualType(T, 0));
8127 }
8128
8129 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8130 const RecordDecl *RD = RTy->getAsRecordDecl();
8131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8132
8133 unsigned NumBases = 0;
8134 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8135 NumBases = CXXRD->getNumBases();
8136
8137 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8138
8139 // Visit the base classes.
8140 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8141 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8142 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8143 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8144
8145 std::optional<APValue> SubObj = visitType(
8146 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8147 if (!SubObj)
8148 return std::nullopt;
8149 ResultVal.getStructBase(I) = *SubObj;
8150 }
8151 }
8152
8153 // Visit the fields.
8154 unsigned FieldIdx = 0;
8155 for (FieldDecl *FD : RD->fields()) {
8156 // FIXME: We don't currently support bit-fields. A lot of the logic for
8157 // this is in CodeGen, so we need to factor it around.
8158 if (FD->isBitField()) {
8159 Info.FFDiag(BCE->getBeginLoc(),
8160 diag::note_constexpr_bit_cast_unsupported_bitfield);
8161 return std::nullopt;
8162 }
8163
8164 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8165 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8166
8167 CharUnits FieldOffset =
8168 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8169 Offset;
8170 QualType FieldTy = FD->getType();
8171 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8172 if (!SubObj)
8173 return std::nullopt;
8174 ResultVal.getStructField(FieldIdx) = *SubObj;
8175 ++FieldIdx;
8176 }
8177
8178 return ResultVal;
8179 }
8180
8181 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8182 QualType RepresentationType =
8183 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8184 assert(!RepresentationType.isNull() &&
8185 "enum forward decl should be caught by Sema");
8186 const auto *AsBuiltin =
8187 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8188 // Recurse into the underlying type. Treat std::byte transparently as
8189 // unsigned char.
8190 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8191 }
8192
8193 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8194 size_t Size = Ty->getLimitedSize();
8195 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8196
8197 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8198 for (size_t I = 0; I != Size; ++I) {
8199 std::optional<APValue> ElementValue =
8200 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8201 if (!ElementValue)
8202 return std::nullopt;
8203 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8204 }
8205
8206 return ArrayValue;
8207 }
8208
8209 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8210 QualType ElementType = Ty->getElementType();
8211 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8212 bool IsInt = ElementType->isIntegerType();
8213
8214 std::optional<APValue> Values[2];
8215 for (unsigned I = 0; I != 2; ++I) {
8216 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8217 if (!Values[I])
8218 return std::nullopt;
8219 }
8220
8221 if (IsInt)
8222 return APValue(Values[0]->getInt(), Values[1]->getInt());
8223 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8224 }
8225
8226 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8227 QualType EltTy = VTy->getElementType();
8228 unsigned NElts = VTy->getNumElements();
8229 unsigned EltSize =
8230 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8231
8232 SmallVector<APValue, 4> Elts;
8233 Elts.reserve(NElts);
8234 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8235 // Special handling for OpenCL bool vectors:
8236 // Since these vectors are stored as packed bits, but we can't read
8237 // individual bits from the BitCastBuffer, we'll buffer all of the
8238 // elements together into an appropriately sized APInt and write them all
8239 // out at once. Because we don't accept vectors where NElts * EltSize
8240 // isn't a multiple of the char size, there will be no padding space, so
8241 // we don't have to worry about reading any padding data which didn't
8242 // actually need to be accessed.
8243 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8244
8245 SmallVector<uint8_t, 8> Bytes;
8246 Bytes.reserve(NElts / 8);
8247 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8248 return std::nullopt;
8249
8250 APSInt SValInt(NElts, true);
8251 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8252
8253 for (unsigned I = 0; I < NElts; ++I) {
8254 llvm::APInt Elt =
8255 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8256 Elts.emplace_back(
8257 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8258 }
8259 } else {
8260 // Iterate over each of the elements and read them from the buffer at
8261 // the appropriate offset.
8262 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8263 for (unsigned I = 0; I < NElts; ++I) {
8264 std::optional<APValue> EltValue =
8265 visitType(EltTy, Offset + I * EltSizeChars);
8266 if (!EltValue)
8267 return std::nullopt;
8268 Elts.push_back(std::move(*EltValue));
8269 }
8270 }
8271
8272 return APValue(Elts.data(), Elts.size());
8273 }
8274
8275 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8276 return unsupportedType(QualType(Ty, 0));
8277 }
8278
8279 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8280 QualType Can = Ty.getCanonicalType();
8281
8282 switch (Can->getTypeClass()) {
8283#define TYPE(Class, Base) \
8284 case Type::Class: \
8285 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8286#define ABSTRACT_TYPE(Class, Base)
8287#define NON_CANONICAL_TYPE(Class, Base) \
8288 case Type::Class: \
8289 llvm_unreachable("non-canonical type should be impossible!");
8290#define DEPENDENT_TYPE(Class, Base) \
8291 case Type::Class: \
8292 llvm_unreachable( \
8293 "dependent types aren't supported in the constant evaluator!");
8294#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8295 case Type::Class: \
8296 llvm_unreachable("either dependent or not canonical!");
8297#include "clang/AST/TypeNodes.inc"
8298 }
8299 llvm_unreachable("Unhandled Type::TypeClass");
8300 }
8301
8302public:
8303 // Pull out a full value of type DstType.
8304 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8305 const CastExpr *BCE) {
8306 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8307 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8308 }
8309};
8310
8311static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8312 QualType Ty, EvalInfo *Info,
8313 const ASTContext &Ctx,
8314 bool CheckingDest) {
8315 Ty = Ty.getCanonicalType();
8316
8317 auto diag = [&](int Reason) {
8318 if (Info)
8319 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8320 << CheckingDest << (Reason == 4) << Reason;
8321 return false;
8322 };
8323 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8324 if (Info)
8325 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8326 << NoteTy << Construct << Ty;
8327 return false;
8328 };
8329
8330 if (Ty->isUnionType())
8331 return diag(0);
8332 if (Ty->isPointerType())
8333 return diag(1);
8334 if (Ty->isMemberPointerType())
8335 return diag(2);
8336 if (Ty.isVolatileQualified())
8337 return diag(3);
8338
8339 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8340 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8341 for (CXXBaseSpecifier &BS : CXXRD->bases())
8342 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8343 CheckingDest))
8344 return note(1, BS.getType(), BS.getBeginLoc());
8345 }
8346 for (FieldDecl *FD : Record->fields()) {
8347 if (FD->getType()->isReferenceType())
8348 return diag(4);
8349 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8350 CheckingDest))
8351 return note(0, FD->getType(), FD->getBeginLoc());
8352 }
8353 }
8354
8355 if (Ty->isArrayType() &&
8356 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8357 Info, Ctx, CheckingDest))
8358 return false;
8359
8360 if (const auto *VTy = Ty->getAs<VectorType>()) {
8361 QualType EltTy = VTy->getElementType();
8362 unsigned NElts = VTy->getNumElements();
8363 unsigned EltSize =
8364 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8365
8366 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8367 // The vector's size in bits is not a multiple of the target's byte size,
8368 // so its layout is unspecified. For now, we'll simply treat these cases
8369 // as unsupported (this should only be possible with OpenCL bool vectors
8370 // whose element count isn't a multiple of the byte size).
8371 if (Info)
8372 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8373 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8374 return false;
8375 }
8376
8377 if (EltTy->isRealFloatingType() &&
8378 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8379 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8380 // by both clang and LLVM, so for now we won't allow bit_casts involving
8381 // it in a constexpr context.
8382 if (Info)
8383 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8384 << EltTy;
8385 return false;
8386 }
8387 }
8388
8389 return true;
8390}
8391
8392static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8393 const ASTContext &Ctx,
8394 const CastExpr *BCE) {
8395 bool DestOK = checkBitCastConstexprEligibilityType(
8396 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8397 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8398 BCE->getBeginLoc(),
8399 BCE->getSubExpr()->getType(), Info, Ctx, false);
8400 return SourceOK;
8401}
8402
8403static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8404 const APValue &SourceRValue,
8405 const CastExpr *BCE) {
8406 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8407 "no host or target supports non 8-bit chars");
8408
8409 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8410 return false;
8411
8412 // Read out SourceValue into a char buffer.
8413 std::optional<BitCastBuffer> Buffer =
8414 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8415 if (!Buffer)
8416 return false;
8417
8418 // Write out the buffer into a new APValue.
8419 std::optional<APValue> MaybeDestValue =
8420 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8421 if (!MaybeDestValue)
8422 return false;
8423
8424 DestValue = std::move(*MaybeDestValue);
8425 return true;
8426}
8427
8428static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8429 APValue &SourceValue,
8430 const CastExpr *BCE) {
8431 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8432 "no host or target supports non 8-bit chars");
8433 assert(SourceValue.isLValue() &&
8434 "LValueToRValueBitcast requires an lvalue operand!");
8435
8436 LValue SourceLValue;
8437 APValue SourceRValue;
8438 SourceLValue.setFrom(Info.Ctx, SourceValue);
8440 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8441 SourceRValue, /*WantObjectRepresentation=*/true))
8442 return false;
8443
8444 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8445}
8446
8447template <class Derived>
8448class ExprEvaluatorBase
8449 : public ConstStmtVisitor<Derived, bool> {
8450private:
8451 Derived &getDerived() { return static_cast<Derived&>(*this); }
8452 bool DerivedSuccess(const APValue &V, const Expr *E) {
8453 return getDerived().Success(V, E);
8454 }
8455 bool DerivedZeroInitialization(const Expr *E) {
8456 return getDerived().ZeroInitialization(E);
8457 }
8458
8459 // Check whether a conditional operator with a non-constant condition is a
8460 // potential constant expression. If neither arm is a potential constant
8461 // expression, then the conditional operator is not either.
8462 template<typename ConditionalOperator>
8463 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8464 assert(Info.checkingPotentialConstantExpression());
8465
8466 // Speculatively evaluate both arms.
8467 SmallVector<PartialDiagnosticAt, 8> Diag;
8468 {
8469 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8470 StmtVisitorTy::Visit(E->getFalseExpr());
8471 if (Diag.empty())
8472 return;
8473 }
8474
8475 {
8476 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8477 Diag.clear();
8478 StmtVisitorTy::Visit(E->getTrueExpr());
8479 if (Diag.empty())
8480 return;
8481 }
8482
8483 Error(E, diag::note_constexpr_conditional_never_const);
8484 }
8485
8486
8487 template<typename ConditionalOperator>
8488 bool HandleConditionalOperator(const ConditionalOperator *E) {
8489 bool BoolResult;
8490 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8491 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8492 CheckPotentialConstantConditional(E);
8493 return false;
8494 }
8495 if (Info.noteFailure()) {
8496 StmtVisitorTy::Visit(E->getTrueExpr());
8497 StmtVisitorTy::Visit(E->getFalseExpr());
8498 }
8499 return false;
8500 }
8501
8502 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8503 return StmtVisitorTy::Visit(EvalExpr);
8504 }
8505
8506protected:
8507 EvalInfo &Info;
8508 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8509 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8510
8511 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8512 return Info.CCEDiag(E, D);
8513 }
8514
8515 bool ZeroInitialization(const Expr *E) { return Error(E); }
8516
8517 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8518 unsigned BuiltinOp = E->getBuiltinCallee();
8519 return BuiltinOp != 0 &&
8520 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8521 }
8522
8523public:
8524 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8525
8526 EvalInfo &getEvalInfo() { return Info; }
8527
8528 /// Report an evaluation error. This should only be called when an error is
8529 /// first discovered. When propagating an error, just return false.
8530 bool Error(const Expr *E, diag::kind D) {
8531 Info.FFDiag(E, D) << E->getSourceRange();
8532 return false;
8533 }
8534 bool Error(const Expr *E) {
8535 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8536 }
8537
8538 bool VisitStmt(const Stmt *) {
8539 llvm_unreachable("Expression evaluator should not be called on stmts");
8540 }
8541 bool VisitExpr(const Expr *E) {
8542 return Error(E);
8543 }
8544
8545 bool VisitEmbedExpr(const EmbedExpr *E) {
8546 const auto It = E->begin();
8547 return StmtVisitorTy::Visit(*It);
8548 }
8549
8550 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8551 return StmtVisitorTy::Visit(E->getFunctionName());
8552 }
8553 bool VisitConstantExpr(const ConstantExpr *E) {
8554 if (E->hasAPValueResult())
8555 return DerivedSuccess(E->getAPValueResult(), E);
8556
8557 return StmtVisitorTy::Visit(E->getSubExpr());
8558 }
8559
8560 bool VisitParenExpr(const ParenExpr *E)
8561 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8562 bool VisitUnaryExtension(const UnaryOperator *E)
8563 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8564 bool VisitUnaryPlus(const UnaryOperator *E)
8565 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8566 bool VisitChooseExpr(const ChooseExpr *E)
8567 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8568 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8569 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8570 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8571 { return StmtVisitorTy::Visit(E->getReplacement()); }
8572 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8573 TempVersionRAII RAII(*Info.CurrentCall);
8574 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8575 return StmtVisitorTy::Visit(E->getExpr());
8576 }
8577 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8578 TempVersionRAII RAII(*Info.CurrentCall);
8579 // The initializer may not have been parsed yet, or might be erroneous.
8580 if (!E->getExpr())
8581 return Error(E);
8582 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8583 return StmtVisitorTy::Visit(E->getExpr());
8584 }
8585
8586 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8587 FullExpressionRAII Scope(Info);
8588 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8589 }
8590
8591 // Temporaries are registered when created, so we don't care about
8592 // CXXBindTemporaryExpr.
8593 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8594 return StmtVisitorTy::Visit(E->getSubExpr());
8595 }
8596
8597 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8598 CCEDiag(E, diag::note_constexpr_invalid_cast)
8599 << diag::ConstexprInvalidCastKind::Reinterpret;
8600 return static_cast<Derived*>(this)->VisitCastExpr(E);
8601 }
8602 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8603 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8604 CCEDiag(E, diag::note_constexpr_invalid_cast)
8605 << diag::ConstexprInvalidCastKind::Dynamic;
8606 return static_cast<Derived*>(this)->VisitCastExpr(E);
8607 }
8608 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8609 return static_cast<Derived*>(this)->VisitCastExpr(E);
8610 }
8611
8612 bool VisitBinaryOperator(const BinaryOperator *E) {
8613 switch (E->getOpcode()) {
8614 default:
8615 return Error(E);
8616
8617 case BO_Comma:
8618 VisitIgnoredValue(E->getLHS());
8619 return StmtVisitorTy::Visit(E->getRHS());
8620
8621 case BO_PtrMemD:
8622 case BO_PtrMemI: {
8623 LValue Obj;
8624 if (!HandleMemberPointerAccess(Info, E, Obj))
8625 return false;
8627 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8628 return false;
8629 return DerivedSuccess(Result, E);
8630 }
8631 }
8632 }
8633
8634 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8635 return StmtVisitorTy::Visit(E->getSemanticForm());
8636 }
8637
8638 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8639 // Evaluate and cache the common expression. We treat it as a temporary,
8640 // even though it's not quite the same thing.
8641 LValue CommonLV;
8642 if (!Evaluate(Info.CurrentCall->createTemporary(
8643 E->getOpaqueValue(),
8644 getStorageType(Info.Ctx, E->getOpaqueValue()),
8645 ScopeKind::FullExpression, CommonLV),
8646 Info, E->getCommon()))
8647 return false;
8648
8649 return HandleConditionalOperator(E);
8650 }
8651
8652 bool VisitConditionalOperator(const ConditionalOperator *E) {
8653 bool IsBcpCall = false;
8654 // If the condition (ignoring parens) is a __builtin_constant_p call,
8655 // the result is a constant expression if it can be folded without
8656 // side-effects. This is an important GNU extension. See GCC PR38377
8657 // for discussion.
8658 if (const CallExpr *CallCE =
8659 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8660 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8661 IsBcpCall = true;
8662
8663 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8664 // constant expression; we can't check whether it's potentially foldable.
8665 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8666 // it would return 'false' in this mode.
8667 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8668 return false;
8669
8670 FoldConstant Fold(Info, IsBcpCall);
8671 if (!HandleConditionalOperator(E)) {
8672 Fold.keepDiagnostics();
8673 return false;
8674 }
8675
8676 return true;
8677 }
8678
8679 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8680 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8681 Value && !Value->isAbsent())
8682 return DerivedSuccess(*Value, E);
8683
8684 const Expr *Source = E->getSourceExpr();
8685 if (!Source)
8686 return Error(E);
8687 if (Source == E) {
8688 assert(0 && "OpaqueValueExpr recursively refers to itself");
8689 return Error(E);
8690 }
8691 return StmtVisitorTy::Visit(Source);
8692 }
8693
8694 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8695 for (const Expr *SemE : E->semantics()) {
8696 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8697 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8698 // result expression: there could be two different LValues that would
8699 // refer to the same object in that case, and we can't model that.
8700 if (SemE == E->getResultExpr())
8701 return Error(E);
8702
8703 // Unique OVEs get evaluated if and when we encounter them when
8704 // emitting the rest of the semantic form, rather than eagerly.
8705 if (OVE->isUnique())
8706 continue;
8707
8708 LValue LV;
8709 if (!Evaluate(Info.CurrentCall->createTemporary(
8710 OVE, getStorageType(Info.Ctx, OVE),
8711 ScopeKind::FullExpression, LV),
8712 Info, OVE->getSourceExpr()))
8713 return false;
8714 } else if (SemE == E->getResultExpr()) {
8715 if (!StmtVisitorTy::Visit(SemE))
8716 return false;
8717 } else {
8718 if (!EvaluateIgnoredValue(Info, SemE))
8719 return false;
8720 }
8721 }
8722 return true;
8723 }
8724
8725 bool VisitCallExpr(const CallExpr *E) {
8727 if (!handleCallExpr(E, Result, nullptr))
8728 return false;
8729 return DerivedSuccess(Result, E);
8730 }
8731
8732 bool handleCallExpr(const CallExpr *E, APValue &Result,
8733 const LValue *ResultSlot) {
8734 CallScopeRAII CallScope(Info);
8735
8736 const Expr *Callee = E->getCallee()->IgnoreParens();
8737 QualType CalleeType = Callee->getType();
8738
8739 const FunctionDecl *FD = nullptr;
8740 LValue *This = nullptr, ObjectArg;
8741 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8742 bool HasQualifier = false;
8743
8744 CallRef Call;
8745
8746 // Extract function decl and 'this' pointer from the callee.
8747 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8748 const CXXMethodDecl *Member = nullptr;
8749 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8750 // Explicit bound member calls, such as x.f() or p->g();
8751 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8752 return false;
8753 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8754 if (!Member)
8755 return Error(Callee);
8756 This = &ObjectArg;
8757 HasQualifier = ME->hasQualifier();
8758 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8759 // Indirect bound member calls ('.*' or '->*').
8760 const ValueDecl *D =
8761 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8762 if (!D)
8763 return false;
8764 Member = dyn_cast<CXXMethodDecl>(D);
8765 if (!Member)
8766 return Error(Callee);
8767 This = &ObjectArg;
8768 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8769 if (!Info.getLangOpts().CPlusPlus20)
8770 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8771 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8772 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8773 } else
8774 return Error(Callee);
8775 FD = Member;
8776 } else if (CalleeType->isFunctionPointerType()) {
8777 LValue CalleeLV;
8778 if (!EvaluatePointer(Callee, CalleeLV, Info))
8779 return false;
8780
8781 if (!CalleeLV.getLValueOffset().isZero())
8782 return Error(Callee);
8783 if (CalleeLV.isNullPointer()) {
8784 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8785 << const_cast<Expr *>(Callee);
8786 return false;
8787 }
8788 FD = dyn_cast_or_null<FunctionDecl>(
8789 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8790 if (!FD)
8791 return Error(Callee);
8792 // Don't call function pointers which have been cast to some other type.
8793 // Per DR (no number yet), the caller and callee can differ in noexcept.
8795 CalleeType->getPointeeType(), FD->getType())) {
8796 return Error(E);
8797 }
8798
8799 // For an (overloaded) assignment expression, evaluate the RHS before the
8800 // LHS.
8801 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8802 if (OCE && OCE->isAssignmentOp()) {
8803 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8804 Call = Info.CurrentCall->createCall(FD);
8805 bool HasThis = false;
8806 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8807 HasThis = MD->isImplicitObjectMemberFunction();
8808 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8809 /*RightToLeft=*/true, &ObjectArg))
8810 return false;
8811 }
8812
8813 // Overloaded operator calls to member functions are represented as normal
8814 // calls with '*this' as the first argument.
8815 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8816 if (MD &&
8817 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8818 // FIXME: When selecting an implicit conversion for an overloaded
8819 // operator delete, we sometimes try to evaluate calls to conversion
8820 // operators without a 'this' parameter!
8821 if (Args.empty())
8822 return Error(E);
8823
8824 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8825 return false;
8826
8827 // If we are calling a static operator, the 'this' argument needs to be
8828 // ignored after being evaluated.
8829 if (MD->isInstance())
8830 This = &ObjectArg;
8831
8832 // If this is syntactically a simple assignment using a trivial
8833 // assignment operator, start the lifetimes of union members as needed,
8834 // per C++20 [class.union]5.
8835 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8836 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8837 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8838 return false;
8839
8840 Args = Args.slice(1);
8841 } else if (MD && MD->isLambdaStaticInvoker()) {
8842 // Map the static invoker for the lambda back to the call operator.
8843 // Conveniently, we don't have to slice out the 'this' argument (as is
8844 // being done for the non-static case), since a static member function
8845 // doesn't have an implicit argument passed in.
8846 const CXXRecordDecl *ClosureClass = MD->getParent();
8847 assert(
8848 ClosureClass->captures().empty() &&
8849 "Number of captures must be zero for conversion to function-ptr");
8850
8851 const CXXMethodDecl *LambdaCallOp =
8852 ClosureClass->getLambdaCallOperator();
8853
8854 // Set 'FD', the function that will be called below, to the call
8855 // operator. If the closure object represents a generic lambda, find
8856 // the corresponding specialization of the call operator.
8857
8858 if (ClosureClass->isGenericLambda()) {
8859 assert(MD->isFunctionTemplateSpecialization() &&
8860 "A generic lambda's static-invoker function must be a "
8861 "template specialization");
8862 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8863 FunctionTemplateDecl *CallOpTemplate =
8864 LambdaCallOp->getDescribedFunctionTemplate();
8865 void *InsertPos = nullptr;
8866 FunctionDecl *CorrespondingCallOpSpecialization =
8867 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8868 assert(CorrespondingCallOpSpecialization &&
8869 "We must always have a function call operator specialization "
8870 "that corresponds to our static invoker specialization");
8871 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8872 FD = CorrespondingCallOpSpecialization;
8873 } else
8874 FD = LambdaCallOp;
8876 if (FD->getDeclName().isAnyOperatorNew()) {
8877 LValue Ptr;
8878 if (!HandleOperatorNewCall(Info, E, Ptr))
8879 return false;
8880 Ptr.moveInto(Result);
8881 return CallScope.destroy();
8882 } else {
8883 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8884 }
8885 }
8886 } else
8887 return Error(E);
8888
8889 // Evaluate the arguments now if we've not already done so.
8890 if (!Call) {
8891 Call = Info.CurrentCall->createCall(FD);
8892 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8893 &ObjectArg))
8894 return false;
8895 }
8896
8897 SmallVector<QualType, 4> CovariantAdjustmentPath;
8898 if (This) {
8899 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8900 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8901 // Perform virtual dispatch, if necessary.
8902 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8903 CovariantAdjustmentPath);
8904 if (!FD)
8905 return false;
8906 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8907 // Check that the 'this' pointer points to an object of the right type.
8908 // FIXME: If this is an assignment operator call, we may need to change
8909 // the active union member before we check this.
8910 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8911 return false;
8912 }
8913 }
8914
8915 // Destructor calls are different enough that they have their own codepath.
8916 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8917 assert(This && "no 'this' pointer for destructor call");
8918 return HandleDestruction(Info, E, *This,
8919 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8920 CallScope.destroy();
8921 }
8922
8923 const FunctionDecl *Definition = nullptr;
8924 Stmt *Body = FD->getBody(Definition);
8925 SourceLocation Loc = E->getExprLoc();
8926
8927 // Treat the object argument as `this` when evaluating defaulted
8928 // special menmber functions
8930 This = &ObjectArg;
8931
8932 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8933 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8934 Result, ResultSlot))
8935 return false;
8936
8937 if (!CovariantAdjustmentPath.empty() &&
8939 CovariantAdjustmentPath))
8940 return false;
8941
8942 return CallScope.destroy();
8943 }
8944
8945 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8946 return StmtVisitorTy::Visit(E->getInitializer());
8947 }
8948 bool VisitInitListExpr(const InitListExpr *E) {
8949 if (E->getNumInits() == 0)
8950 return DerivedZeroInitialization(E);
8951 if (E->getNumInits() == 1)
8952 return StmtVisitorTy::Visit(E->getInit(0));
8953 return Error(E);
8954 }
8955 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8956 return DerivedZeroInitialization(E);
8957 }
8958 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8959 return DerivedZeroInitialization(E);
8960 }
8961 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8962 return DerivedZeroInitialization(E);
8963 }
8964
8965 /// A member expression where the object is a prvalue is itself a prvalue.
8966 bool VisitMemberExpr(const MemberExpr *E) {
8967 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8968 "missing temporary materialization conversion");
8969 assert(!E->isArrow() && "missing call to bound member function?");
8970
8971 APValue Val;
8972 if (!Evaluate(Val, Info, E->getBase()))
8973 return false;
8974
8975 QualType BaseTy = E->getBase()->getType();
8976
8977 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8978 if (!FD) return Error(E);
8979 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8980 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8981 FD->getParent()->getCanonicalDecl() &&
8982 "record / field mismatch");
8983
8984 // Note: there is no lvalue base here. But this case should only ever
8985 // happen in C or in C++98, where we cannot be evaluating a constexpr
8986 // constructor, which is the only case the base matters.
8987 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8988 SubobjectDesignator Designator(BaseTy);
8989 Designator.addDeclUnchecked(FD);
8990
8992 return extractSubobject(Info, E, Obj, Designator, Result) &&
8993 DerivedSuccess(Result, E);
8994 }
8995
8996 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8997 APValue Val;
8998 if (!Evaluate(Val, Info, E->getBase()))
8999 return false;
9000
9001 if (Val.isVector()) {
9002 SmallVector<uint32_t, 4> Indices;
9003 E->getEncodedElementAccess(Indices);
9004 if (Indices.size() == 1) {
9005 // Return scalar.
9006 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9007 } else {
9008 // Construct new APValue vector.
9009 SmallVector<APValue, 4> Elts;
9010 for (unsigned I = 0; I < Indices.size(); ++I) {
9011 Elts.push_back(Val.getVectorElt(Indices[I]));
9012 }
9013 APValue VecResult(Elts.data(), Indices.size());
9014 return DerivedSuccess(VecResult, E);
9015 }
9016 }
9017
9018 return false;
9019 }
9020
9021 bool VisitCastExpr(const CastExpr *E) {
9022 switch (E->getCastKind()) {
9023 default:
9024 break;
9025
9026 case CK_AtomicToNonAtomic: {
9027 APValue AtomicVal;
9028 // This does not need to be done in place even for class/array types:
9029 // atomic-to-non-atomic conversion implies copying the object
9030 // representation.
9031 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9032 return false;
9033 return DerivedSuccess(AtomicVal, E);
9034 }
9035
9036 case CK_NoOp:
9037 case CK_UserDefinedConversion:
9038 return StmtVisitorTy::Visit(E->getSubExpr());
9039
9040 case CK_HLSLArrayRValue: {
9041 const Expr *SubExpr = E->getSubExpr();
9042 if (!SubExpr->isGLValue()) {
9043 APValue Val;
9044 if (!Evaluate(Val, Info, SubExpr))
9045 return false;
9046 return DerivedSuccess(Val, E);
9047 }
9048
9049 LValue LVal;
9050 if (!EvaluateLValue(SubExpr, LVal, Info))
9051 return false;
9052 APValue RVal;
9053 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9054 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9055 RVal))
9056 return false;
9057 return DerivedSuccess(RVal, E);
9058 }
9059 case CK_LValueToRValue: {
9060 LValue LVal;
9061 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9062 return false;
9063 APValue RVal;
9064 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9066 LVal, RVal))
9067 return false;
9068 return DerivedSuccess(RVal, E);
9069 }
9070 case CK_LValueToRValueBitCast: {
9071 APValue DestValue, SourceValue;
9072 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9073 return false;
9074 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9075 return false;
9076 return DerivedSuccess(DestValue, E);
9077 }
9078
9079 case CK_AddressSpaceConversion: {
9080 APValue Value;
9081 if (!Evaluate(Value, Info, E->getSubExpr()))
9082 return false;
9083 return DerivedSuccess(Value, E);
9084 }
9085 }
9086
9087 return Error(E);
9088 }
9089
9090 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9091 return VisitUnaryPostIncDec(UO);
9092 }
9093 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9094 return VisitUnaryPostIncDec(UO);
9095 }
9096 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9097 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9098 return Error(UO);
9099
9100 LValue LVal;
9101 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9102 return false;
9103 APValue RVal;
9104 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9105 UO->isIncrementOp(), &RVal))
9106 return false;
9107 return DerivedSuccess(RVal, UO);
9108 }
9109
9110 bool VisitStmtExpr(const StmtExpr *E) {
9111 // We will have checked the full-expressions inside the statement expression
9112 // when they were completed, and don't need to check them again now.
9113 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9114 false);
9115
9116 const CompoundStmt *CS = E->getSubStmt();
9117 if (CS->body_empty())
9118 return true;
9119
9120 BlockScopeRAII Scope(Info);
9122 BE = CS->body_end();
9123 /**/; ++BI) {
9124 if (BI + 1 == BE) {
9125 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9126 if (!FinalExpr) {
9127 Info.FFDiag((*BI)->getBeginLoc(),
9128 diag::note_constexpr_stmt_expr_unsupported);
9129 return false;
9130 }
9131 return this->Visit(FinalExpr) && Scope.destroy();
9132 }
9133
9135 StmtResult Result = { ReturnValue, nullptr };
9136 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9137 if (ESR != ESR_Succeeded) {
9138 // FIXME: If the statement-expression terminated due to 'return',
9139 // 'break', or 'continue', it would be nice to propagate that to
9140 // the outer statement evaluation rather than bailing out.
9141 if (ESR != ESR_Failed)
9142 Info.FFDiag((*BI)->getBeginLoc(),
9143 diag::note_constexpr_stmt_expr_unsupported);
9144 return false;
9145 }
9146 }
9147
9148 llvm_unreachable("Return from function from the loop above.");
9149 }
9150
9151 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9152 return StmtVisitorTy::Visit(E->getSelectedExpr());
9153 }
9154
9155 /// Visit a value which is evaluated, but whose value is ignored.
9156 void VisitIgnoredValue(const Expr *E) {
9157 EvaluateIgnoredValue(Info, E);
9158 }
9159
9160 /// Potentially visit a MemberExpr's base expression.
9161 void VisitIgnoredBaseExpression(const Expr *E) {
9162 // While MSVC doesn't evaluate the base expression, it does diagnose the
9163 // presence of side-effecting behavior.
9164 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9165 return;
9166 VisitIgnoredValue(E);
9167 }
9168};
9169
9170} // namespace
9171
9172//===----------------------------------------------------------------------===//
9173// Common base class for lvalue and temporary evaluation.
9174//===----------------------------------------------------------------------===//
9175namespace {
9176template<class Derived>
9177class LValueExprEvaluatorBase
9178 : public ExprEvaluatorBase<Derived> {
9179protected:
9180 LValue &Result;
9181 bool InvalidBaseOK;
9182 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9183 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9184
9185 bool Success(APValue::LValueBase B) {
9186 Result.set(B);
9187 return true;
9188 }
9189
9190 bool evaluatePointer(const Expr *E, LValue &Result) {
9191 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9192 }
9193
9194public:
9195 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9196 : ExprEvaluatorBaseTy(Info), Result(Result),
9197 InvalidBaseOK(InvalidBaseOK) {}
9198
9199 bool Success(const APValue &V, const Expr *E) {
9200 Result.setFrom(this->Info.Ctx, V);
9201 return true;
9202 }
9203
9204 bool VisitMemberExpr(const MemberExpr *E) {
9205 // Handle non-static data members.
9206 QualType BaseTy;
9207 bool EvalOK;
9208 if (E->isArrow()) {
9209 EvalOK = evaluatePointer(E->getBase(), Result);
9210 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9211 } else if (E->getBase()->isPRValue()) {
9212 assert(E->getBase()->getType()->isRecordType());
9213 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9214 BaseTy = E->getBase()->getType();
9215 } else {
9216 EvalOK = this->Visit(E->getBase());
9217 BaseTy = E->getBase()->getType();
9218 }
9219 if (!EvalOK) {
9220 if (!InvalidBaseOK)
9221 return false;
9222 Result.setInvalid(E);
9223 return true;
9224 }
9225
9226 const ValueDecl *MD = E->getMemberDecl();
9227 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9228 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9229 FD->getParent()->getCanonicalDecl() &&
9230 "record / field mismatch");
9231 (void)BaseTy;
9232 if (!HandleLValueMember(this->Info, E, Result, FD))
9233 return false;
9234 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9235 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9236 return false;
9237 } else
9238 return this->Error(E);
9239
9240 if (MD->getType()->isReferenceType()) {
9241 APValue RefValue;
9242 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9243 RefValue))
9244 return false;
9245 return Success(RefValue, E);
9246 }
9247 return true;
9248 }
9249
9250 bool VisitBinaryOperator(const BinaryOperator *E) {
9251 switch (E->getOpcode()) {
9252 default:
9253 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9254
9255 case BO_PtrMemD:
9256 case BO_PtrMemI:
9257 return HandleMemberPointerAccess(this->Info, E, Result);
9258 }
9259 }
9260
9261 bool VisitCastExpr(const CastExpr *E) {
9262 switch (E->getCastKind()) {
9263 default:
9264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9265
9266 case CK_DerivedToBase:
9267 case CK_UncheckedDerivedToBase:
9268 if (!this->Visit(E->getSubExpr()))
9269 return false;
9270
9271 // Now figure out the necessary offset to add to the base LV to get from
9272 // the derived class to the base class.
9273 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9274 Result);
9275 }
9276 }
9277};
9278}
9279
9280//===----------------------------------------------------------------------===//
9281// LValue Evaluation
9282//
9283// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9284// function designators (in C), decl references to void objects (in C), and
9285// temporaries (if building with -Wno-address-of-temporary).
9286//
9287// LValue evaluation produces values comprising a base expression of one of the
9288// following types:
9289// - Declarations
9290// * VarDecl
9291// * FunctionDecl
9292// - Literals
9293// * CompoundLiteralExpr in C (and in global scope in C++)
9294// * StringLiteral
9295// * PredefinedExpr
9296// * ObjCStringLiteralExpr
9297// * ObjCEncodeExpr
9298// * AddrLabelExpr
9299// * BlockExpr
9300// * CallExpr for a MakeStringConstant builtin
9301// - typeid(T) expressions, as TypeInfoLValues
9302// - Locals and temporaries
9303// * MaterializeTemporaryExpr
9304// * Any Expr, with a CallIndex indicating the function in which the temporary
9305// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9306// from the AST (FIXME).
9307// * A MaterializeTemporaryExpr that has static storage duration, with no
9308// CallIndex, for a lifetime-extended temporary.
9309// * The ConstantExpr that is currently being evaluated during evaluation of an
9310// immediate invocation.
9311// plus an offset in bytes.
9312//===----------------------------------------------------------------------===//
9313namespace {
9314class LValueExprEvaluator
9315 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9316public:
9317 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9318 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9319
9320 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9321 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9322
9323 bool VisitCallExpr(const CallExpr *E);
9324 bool VisitDeclRefExpr(const DeclRefExpr *E);
9325 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9326 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9327 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9328 bool VisitMemberExpr(const MemberExpr *E);
9329 bool VisitStringLiteral(const StringLiteral *E) {
9330 return Success(APValue::LValueBase(
9331 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
9332 }
9333 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9334 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9335 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9336 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9337 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9338 bool VisitUnaryDeref(const UnaryOperator *E);
9339 bool VisitUnaryReal(const UnaryOperator *E);
9340 bool VisitUnaryImag(const UnaryOperator *E);
9341 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9342 return VisitUnaryPreIncDec(UO);
9343 }
9344 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9345 return VisitUnaryPreIncDec(UO);
9346 }
9347 bool VisitBinAssign(const BinaryOperator *BO);
9348 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9349
9350 bool VisitCastExpr(const CastExpr *E) {
9351 switch (E->getCastKind()) {
9352 default:
9353 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9354
9355 case CK_LValueBitCast:
9356 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9357 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9358 << Info.Ctx.getLangOpts().CPlusPlus;
9359 if (!Visit(E->getSubExpr()))
9360 return false;
9361 Result.Designator.setInvalid();
9362 return true;
9363
9364 case CK_BaseToDerived:
9365 if (!Visit(E->getSubExpr()))
9366 return false;
9367 return HandleBaseToDerivedCast(Info, E, Result);
9368
9369 case CK_Dynamic:
9370 if (!Visit(E->getSubExpr()))
9371 return false;
9373 }
9374 }
9375};
9376} // end anonymous namespace
9377
9378/// Get an lvalue to a field of a lambda's closure type.
9379static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9380 const CXXMethodDecl *MD, const FieldDecl *FD,
9381 bool LValueToRValueConversion) {
9382 // Static lambda function call operators can't have captures. We already
9383 // diagnosed this, so bail out here.
9384 if (MD->isStatic()) {
9385 assert(Info.CurrentCall->This == nullptr &&
9386 "This should not be set for a static call operator");
9387 return false;
9388 }
9389
9390 // Start with 'Result' referring to the complete closure object...
9392 // Self may be passed by reference or by value.
9393 const ParmVarDecl *Self = MD->getParamDecl(0);
9394 if (Self->getType()->isReferenceType()) {
9395 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9396 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9397 Result.setFrom(Info.Ctx, *RefValue);
9398 } else {
9399 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9400 CallStackFrame *Frame =
9401 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9402 .first;
9403 unsigned Version = Info.CurrentCall->Arguments.Version;
9404 Result.set({VD, Frame->Index, Version});
9405 }
9406 } else
9407 Result = *Info.CurrentCall->This;
9408
9409 // ... then update it to refer to the field of the closure object
9410 // that represents the capture.
9411 if (!HandleLValueMember(Info, E, Result, FD))
9412 return false;
9413
9414 // And if the field is of reference type (or if we captured '*this' by
9415 // reference), update 'Result' to refer to what
9416 // the field refers to.
9417 if (LValueToRValueConversion) {
9418 APValue RVal;
9419 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9420 return false;
9421 Result.setFrom(Info.Ctx, RVal);
9422 }
9423 return true;
9424}
9425
9426/// Evaluate an expression as an lvalue. This can be legitimately called on
9427/// expressions which are not glvalues, in three cases:
9428/// * function designators in C, and
9429/// * "extern void" objects
9430/// * @selector() expressions in Objective-C
9431static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9432 bool InvalidBaseOK) {
9433 assert(!E->isValueDependent());
9434 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9436 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9437}
9438
9439bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9440 const ValueDecl *D = E->getDecl();
9441
9442 // If we are within a lambda's call operator, check whether the 'VD' referred
9443 // to within 'E' actually represents a lambda-capture that maps to a
9444 // data-member/field within the closure object, and if so, evaluate to the
9445 // field or what the field refers to.
9446 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9448 // We don't always have a complete capture-map when checking or inferring if
9449 // the function call operator meets the requirements of a constexpr function
9450 // - but we don't need to evaluate the captures to determine constexprness
9451 // (dcl.constexpr C++17).
9452 if (Info.checkingPotentialConstantExpression())
9453 return false;
9454
9455 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9456 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9457 return HandleLambdaCapture(Info, E, Result, MD, FD,
9458 FD->getType()->isReferenceType());
9459 }
9460 }
9461
9462 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9463 UnnamedGlobalConstantDecl>(D))
9464 return Success(cast<ValueDecl>(D));
9465 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9466 return VisitVarDecl(E, VD);
9467 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9468 return Visit(BD->getBinding());
9469 return Error(E);
9470}
9471
9472bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9473 CallStackFrame *Frame = nullptr;
9474 unsigned Version = 0;
9475 if (VD->hasLocalStorage()) {
9476 // Only if a local variable was declared in the function currently being
9477 // evaluated, do we expect to be able to find its value in the current
9478 // frame. (Otherwise it was likely declared in an enclosing context and
9479 // could either have a valid evaluatable value (for e.g. a constexpr
9480 // variable) or be ill-formed (and trigger an appropriate evaluation
9481 // diagnostic)).
9482 CallStackFrame *CurrFrame = Info.CurrentCall;
9483 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9484 // Function parameters are stored in some caller's frame. (Usually the
9485 // immediate caller, but for an inherited constructor they may be more
9486 // distant.)
9487 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9488 if (CurrFrame->Arguments) {
9489 VD = CurrFrame->Arguments.getOrigParam(PVD);
9490 Frame =
9491 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9492 Version = CurrFrame->Arguments.Version;
9493 }
9494 } else {
9495 Frame = CurrFrame;
9496 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9497 }
9498 }
9499 }
9500
9501 if (!VD->getType()->isReferenceType()) {
9502 if (Frame) {
9503 Result.set({VD, Frame->Index, Version});
9504 return true;
9505 }
9506 return Success(VD);
9507 }
9508
9509 if (!Info.getLangOpts().CPlusPlus11) {
9510 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9511 << VD << VD->getType();
9512 Info.Note(VD->getLocation(), diag::note_declared_at);
9513 }
9514
9515 APValue *V;
9516 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9517 return false;
9518
9519 if (!V) {
9520 Result.set(VD);
9521 Result.AllowConstexprUnknown = true;
9522 return true;
9523 }
9524
9525 return Success(*V, E);
9526}
9527
9528bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9529 if (!IsConstantEvaluatedBuiltinCall(E))
9530 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9531
9532 switch (E->getBuiltinCallee()) {
9533 default:
9534 return false;
9535 case Builtin::BIas_const:
9536 case Builtin::BIforward:
9537 case Builtin::BIforward_like:
9538 case Builtin::BImove:
9539 case Builtin::BImove_if_noexcept:
9540 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9541 return Visit(E->getArg(0));
9542 break;
9543 }
9544
9545 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9546}
9547
9548bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9549 const MaterializeTemporaryExpr *E) {
9550 // Walk through the expression to find the materialized temporary itself.
9553 const Expr *Inner =
9554 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9555
9556 // If we passed any comma operators, evaluate their LHSs.
9557 for (const Expr *E : CommaLHSs)
9558 if (!EvaluateIgnoredValue(Info, E))
9559 return false;
9560
9561 // A materialized temporary with static storage duration can appear within the
9562 // result of a constant expression evaluation, so we need to preserve its
9563 // value for use outside this evaluation.
9564 APValue *Value;
9565 if (E->getStorageDuration() == SD_Static) {
9566 if (Info.EvalMode == EvaluationMode::ConstantFold)
9567 return false;
9568 // FIXME: What about SD_Thread?
9569 Value = E->getOrCreateValue(true);
9570 *Value = APValue();
9571 Result.set(E);
9572 } else {
9573 Value = &Info.CurrentCall->createTemporary(
9574 E, Inner->getType(),
9575 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9576 : ScopeKind::Block,
9577 Result);
9578 }
9579
9580 QualType Type = Inner->getType();
9581
9582 // Materialize the temporary itself.
9583 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9584 *Value = APValue();
9585 return false;
9586 }
9587
9588 // Adjust our lvalue to refer to the desired subobject.
9589 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9590 --I;
9591 switch (Adjustments[I].Kind) {
9593 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9594 Type, Result))
9595 return false;
9596 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9597 break;
9598
9600 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9601 return false;
9602 Type = Adjustments[I].Field->getType();
9603 break;
9604
9606 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9607 Adjustments[I].Ptr.RHS))
9608 return false;
9609 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9610 break;
9611 }
9612 }
9613
9614 return true;
9615}
9616
9617bool
9618LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9619 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9620 "lvalue compound literal in c++?");
9621 APValue *Lit;
9622 // If CompountLiteral has static storage, its value can be used outside
9623 // this expression. So evaluate it once and store it in ASTContext.
9624 if (E->hasStaticStorage()) {
9625 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9626 Result.set(E);
9627 // Reset any previously evaluated state, otherwise evaluation below might
9628 // fail.
9629 // FIXME: Should we just re-use the previously evaluated value instead?
9630 *Lit = APValue();
9631 } else {
9632 assert(!Info.getLangOpts().CPlusPlus);
9633 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9634 ScopeKind::Block, Result);
9635 }
9636 // FIXME: Evaluating in place isn't always right. We should figure out how to
9637 // use appropriate evaluation context here, see
9638 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9639 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9640 *Lit = APValue();
9641 return false;
9642 }
9643 return true;
9644}
9645
9646bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9647 TypeInfoLValue TypeInfo;
9648
9649 if (!E->isPotentiallyEvaluated()) {
9650 if (E->isTypeOperand())
9651 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9652 else
9653 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9654 } else {
9655 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9656 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9657 << E->getExprOperand()->getType()
9658 << E->getExprOperand()->getSourceRange();
9659 }
9660
9661 if (!Visit(E->getExprOperand()))
9662 return false;
9663
9664 std::optional<DynamicType> DynType =
9666 if (!DynType)
9667 return false;
9668
9669 TypeInfo = TypeInfoLValue(
9670 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9671 }
9672
9673 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9674}
9675
9676bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9677 return Success(E->getGuidDecl());
9678}
9679
9680bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9681 // Handle static data members.
9682 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9683 VisitIgnoredBaseExpression(E->getBase());
9684 return VisitVarDecl(E, VD);
9685 }
9686
9687 // Handle static member functions.
9688 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9689 if (MD->isStatic()) {
9690 VisitIgnoredBaseExpression(E->getBase());
9691 return Success(MD);
9692 }
9693 }
9694
9695 // Handle non-static data members.
9696 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9697}
9698
9699bool LValueExprEvaluator::VisitExtVectorElementExpr(
9700 const ExtVectorElementExpr *E) {
9701 bool Success = true;
9702
9703 APValue Val;
9704 if (!Evaluate(Val, Info, E->getBase())) {
9705 if (!Info.noteFailure())
9706 return false;
9707 Success = false;
9708 }
9709
9711 E->getEncodedElementAccess(Indices);
9712 // FIXME: support accessing more than one element
9713 if (Indices.size() > 1)
9714 return false;
9715
9716 if (Success) {
9717 Result.setFrom(Info.Ctx, Val);
9718 QualType BaseType = E->getBase()->getType();
9719 if (E->isArrow())
9720 BaseType = BaseType->getPointeeType();
9721 const auto *VT = BaseType->castAs<VectorType>();
9722 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9723 VT->getNumElements(), Indices[0]);
9724 }
9725
9726 return Success;
9727}
9728
9729bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9730 if (E->getBase()->getType()->isSveVLSBuiltinType())
9731 return Error(E);
9732
9733 APSInt Index;
9734 bool Success = true;
9735
9736 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9737 APValue Val;
9738 if (!Evaluate(Val, Info, E->getBase())) {
9739 if (!Info.noteFailure())
9740 return false;
9741 Success = false;
9742 }
9743
9744 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9745 if (!Info.noteFailure())
9746 return false;
9747 Success = false;
9748 }
9749
9750 if (Success) {
9751 Result.setFrom(Info.Ctx, Val);
9752 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9753 VT->getNumElements(), Index.getExtValue());
9754 }
9755
9756 return Success;
9757 }
9758
9759 // C++17's rules require us to evaluate the LHS first, regardless of which
9760 // side is the base.
9761 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9762 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9763 : !EvaluateInteger(SubExpr, Index, Info)) {
9764 if (!Info.noteFailure())
9765 return false;
9766 Success = false;
9767 }
9768 }
9769
9770 return Success &&
9771 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9772}
9773
9774bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9775 bool Success = evaluatePointer(E->getSubExpr(), Result);
9776 // [C++26][expr.unary.op]
9777 // If the operand points to an object or function, the result
9778 // denotes that object or function; otherwise, the behavior is undefined.
9779 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9780 // immediately.
9782 return Success;
9784 E->getType())) ||
9785 Info.noteUndefinedBehavior();
9786}
9787
9788bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9789 if (!Visit(E->getSubExpr()))
9790 return false;
9791 // __real is a no-op on scalar lvalues.
9792 if (E->getSubExpr()->getType()->isAnyComplexType())
9793 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9794 return true;
9795}
9796
9797bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9798 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9799 "lvalue __imag__ on scalar?");
9800 if (!Visit(E->getSubExpr()))
9801 return false;
9802 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9803 return true;
9804}
9805
9806bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9807 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9808 return Error(UO);
9809
9810 if (!this->Visit(UO->getSubExpr()))
9811 return false;
9812
9813 return handleIncDec(
9814 this->Info, UO, Result, UO->getSubExpr()->getType(),
9815 UO->isIncrementOp(), nullptr);
9816}
9817
9818bool LValueExprEvaluator::VisitCompoundAssignOperator(
9819 const CompoundAssignOperator *CAO) {
9820 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9821 return Error(CAO);
9822
9823 bool Success = true;
9824
9825 // C++17 onwards require that we evaluate the RHS first.
9826 APValue RHS;
9827 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9828 if (!Info.noteFailure())
9829 return false;
9830 Success = false;
9831 }
9832
9833 // The overall lvalue result is the result of evaluating the LHS.
9834 if (!this->Visit(CAO->getLHS()) || !Success)
9835 return false;
9836
9838 this->Info, CAO,
9839 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9840 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9841}
9842
9843bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9844 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9845 return Error(E);
9846
9847 bool Success = true;
9848
9849 // C++17 onwards require that we evaluate the RHS first.
9850 APValue NewVal;
9851 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9852 if (!Info.noteFailure())
9853 return false;
9854 Success = false;
9855 }
9856
9857 if (!this->Visit(E->getLHS()) || !Success)
9858 return false;
9859
9860 if (Info.getLangOpts().CPlusPlus20 &&
9862 return false;
9863
9864 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9865 NewVal);
9866}
9867
9868//===----------------------------------------------------------------------===//
9869// Pointer Evaluation
9870//===----------------------------------------------------------------------===//
9871
9872/// Convenience function. LVal's base must be a call to an alloc_size
9873/// function.
9875 const LValue &LVal,
9876 llvm::APInt &Result) {
9877 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9878 "Can't get the size of a non alloc_size function");
9879 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9880 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9881 std::optional<llvm::APInt> Size =
9882 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9883 if (!Size)
9884 return false;
9885
9886 Result = std::move(*Size);
9887 return true;
9888}
9889
9890/// Attempts to evaluate the given LValueBase as the result of a call to
9891/// a function with the alloc_size attribute. If it was possible to do so, this
9892/// function will return true, make Result's Base point to said function call,
9893/// and mark Result's Base as invalid.
9895 LValue &Result) {
9896 if (Base.isNull())
9897 return false;
9898
9899 // Because we do no form of static analysis, we only support const variables.
9900 //
9901 // Additionally, we can't support parameters, nor can we support static
9902 // variables (in the latter case, use-before-assign isn't UB; in the former,
9903 // we have no clue what they'll be assigned to).
9904 const auto *VD =
9905 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9906 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9907 return false;
9908
9909 const Expr *Init = VD->getAnyInitializer();
9910 if (!Init || Init->getType().isNull())
9911 return false;
9912
9913 const Expr *E = Init->IgnoreParens();
9914 if (!tryUnwrapAllocSizeCall(E))
9915 return false;
9916
9917 // Store E instead of E unwrapped so that the type of the LValue's base is
9918 // what the user wanted.
9919 Result.setInvalid(E);
9920
9921 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9922 Result.addUnsizedArray(Info, E, Pointee);
9923 return true;
9924}
9925
9926namespace {
9927class PointerExprEvaluator
9928 : public ExprEvaluatorBase<PointerExprEvaluator> {
9929 LValue &Result;
9930 bool InvalidBaseOK;
9931
9932 bool Success(const Expr *E) {
9933 Result.set(E);
9934 return true;
9935 }
9936
9937 bool evaluateLValue(const Expr *E, LValue &Result) {
9938 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9939 }
9940
9941 bool evaluatePointer(const Expr *E, LValue &Result) {
9942 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9943 }
9944
9945 bool visitNonBuiltinCallExpr(const CallExpr *E);
9946public:
9947
9948 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9949 : ExprEvaluatorBaseTy(info), Result(Result),
9950 InvalidBaseOK(InvalidBaseOK) {}
9951
9952 bool Success(const APValue &V, const Expr *E) {
9953 Result.setFrom(Info.Ctx, V);
9954 return true;
9955 }
9956 bool ZeroInitialization(const Expr *E) {
9957 Result.setNull(Info.Ctx, E->getType());
9958 return true;
9959 }
9960
9961 bool VisitBinaryOperator(const BinaryOperator *E);
9962 bool VisitCastExpr(const CastExpr* E);
9963 bool VisitUnaryAddrOf(const UnaryOperator *E);
9964 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9965 { return Success(E); }
9966 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9968 return Success(E);
9969 if (Info.noteFailure())
9970 EvaluateIgnoredValue(Info, E->getSubExpr());
9971 return Error(E);
9972 }
9973 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9974 { return Success(E); }
9975 bool VisitCallExpr(const CallExpr *E);
9976 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9977 bool VisitBlockExpr(const BlockExpr *E) {
9978 if (!E->getBlockDecl()->hasCaptures())
9979 return Success(E);
9980 return Error(E);
9981 }
9982 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9983 auto DiagnoseInvalidUseOfThis = [&] {
9984 if (Info.getLangOpts().CPlusPlus11)
9985 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9986 else
9987 Info.FFDiag(E);
9988 };
9989
9990 // Can't look at 'this' when checking a potential constant expression.
9991 if (Info.checkingPotentialConstantExpression())
9992 return false;
9993
9994 bool IsExplicitLambda =
9995 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9996 if (!IsExplicitLambda) {
9997 if (!Info.CurrentCall->This) {
9998 DiagnoseInvalidUseOfThis();
9999 return false;
10000 }
10001
10002 Result = *Info.CurrentCall->This;
10003 }
10004
10005 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10006 // Ensure we actually have captured 'this'. If something was wrong with
10007 // 'this' capture, the error would have been previously reported.
10008 // Otherwise we can be inside of a default initialization of an object
10009 // declared by lambda's body, so no need to return false.
10010 if (!Info.CurrentCall->LambdaThisCaptureField) {
10011 if (IsExplicitLambda && !Info.CurrentCall->This) {
10012 DiagnoseInvalidUseOfThis();
10013 return false;
10014 }
10015
10016 return true;
10017 }
10018
10019 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10020 return HandleLambdaCapture(
10021 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10022 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10023 }
10024 return true;
10025 }
10026
10027 bool VisitCXXNewExpr(const CXXNewExpr *E);
10028
10029 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10030 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10031 APValue LValResult = E->EvaluateInContext(
10032 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10033 Result.setFrom(Info.Ctx, LValResult);
10034 return true;
10035 }
10036
10037 bool VisitEmbedExpr(const EmbedExpr *E) {
10038 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10039 return true;
10040 }
10041
10042 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10043 std::string ResultStr = E->ComputeName(Info.Ctx);
10044
10045 QualType CharTy = Info.Ctx.CharTy.withConst();
10046 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10047 ResultStr.size() + 1);
10048 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10049 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10050
10051 StringLiteral *SL =
10052 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10053 /*Pascal*/ false, ArrayTy, E->getLocation());
10054
10055 evaluateLValue(SL, Result);
10056 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10057 return true;
10058 }
10059
10060 // FIXME: Missing: @protocol, @selector
10061};
10062} // end anonymous namespace
10063
10064static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10065 bool InvalidBaseOK) {
10066 assert(!E->isValueDependent());
10067 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10068 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10069}
10070
10071bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10072 if (E->getOpcode() != BO_Add &&
10073 E->getOpcode() != BO_Sub)
10074 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10075
10076 const Expr *PExp = E->getLHS();
10077 const Expr *IExp = E->getRHS();
10078 if (IExp->getType()->isPointerType())
10079 std::swap(PExp, IExp);
10080
10081 bool EvalPtrOK = evaluatePointer(PExp, Result);
10082 if (!EvalPtrOK && !Info.noteFailure())
10083 return false;
10084
10085 llvm::APSInt Offset;
10086 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10087 return false;
10088
10089 if (E->getOpcode() == BO_Sub)
10090 negateAsSigned(Offset);
10091
10092 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10093 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10094}
10095
10096bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10097 return evaluateLValue(E->getSubExpr(), Result);
10098}
10099
10100// Is the provided decl 'std::source_location::current'?
10102 if (!FD)
10103 return false;
10104 const IdentifierInfo *FnII = FD->getIdentifier();
10105 if (!FnII || !FnII->isStr("current"))
10106 return false;
10107
10108 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10109 if (!RD)
10110 return false;
10111
10112 const IdentifierInfo *ClassII = RD->getIdentifier();
10113 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10114}
10115
10116bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10117 const Expr *SubExpr = E->getSubExpr();
10118
10119 switch (E->getCastKind()) {
10120 default:
10121 break;
10122 case CK_BitCast:
10123 case CK_CPointerToObjCPointerCast:
10124 case CK_BlockPointerToObjCPointerCast:
10125 case CK_AnyPointerToBlockPointerCast:
10126 case CK_AddressSpaceConversion:
10127 if (!Visit(SubExpr))
10128 return false;
10129 if (E->getType()->isFunctionPointerType() ||
10130 SubExpr->getType()->isFunctionPointerType()) {
10131 // Casting between two function pointer types, or between a function
10132 // pointer and an object pointer, is always a reinterpret_cast.
10133 CCEDiag(E, diag::note_constexpr_invalid_cast)
10134 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10135 << Info.Ctx.getLangOpts().CPlusPlus;
10136 Result.Designator.setInvalid();
10137 } else if (!E->getType()->isVoidPointerType()) {
10138 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10139 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10140 // also static_casts, but we disallow them as a resolution to DR1312.
10141 //
10142 // In some circumstances, we permit casting from void* to cv1 T*, when the
10143 // actual pointee object is actually a cv2 T.
10144 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10145 !Result.IsNullPtr;
10146 bool VoidPtrCastMaybeOK =
10147 Result.IsNullPtr ||
10148 (HasValidResult &&
10149 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10150 E->getType()->getPointeeType()));
10151 // 1. We'll allow it in std::allocator::allocate, and anything which that
10152 // calls.
10153 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10154 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10155 // We'll allow it in the body of std::source_location::current. GCC's
10156 // implementation had a parameter of type `void*`, and casts from
10157 // that back to `const __impl*` in its body.
10158 if (VoidPtrCastMaybeOK &&
10159 (Info.getStdAllocatorCaller("allocate") ||
10160 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10161 Info.getLangOpts().CPlusPlus26)) {
10162 // Permitted.
10163 } else {
10164 if (SubExpr->getType()->isVoidPointerType() &&
10165 Info.getLangOpts().CPlusPlus) {
10166 if (HasValidResult)
10167 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10168 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10169 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10170 << E->getType()->getPointeeType();
10171 else
10172 CCEDiag(E, diag::note_constexpr_invalid_cast)
10173 << diag::ConstexprInvalidCastKind::CastFrom
10174 << SubExpr->getType();
10175 } else
10176 CCEDiag(E, diag::note_constexpr_invalid_cast)
10177 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10178 << Info.Ctx.getLangOpts().CPlusPlus;
10179 Result.Designator.setInvalid();
10180 }
10181 }
10182 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10183 ZeroInitialization(E);
10184 return true;
10185
10186 case CK_DerivedToBase:
10187 case CK_UncheckedDerivedToBase:
10188 if (!evaluatePointer(E->getSubExpr(), Result))
10189 return false;
10190 if (!Result.Base && Result.Offset.isZero())
10191 return true;
10192
10193 // Now figure out the necessary offset to add to the base LV to get from
10194 // the derived class to the base class.
10195 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10196 castAs<PointerType>()->getPointeeType(),
10197 Result);
10198
10199 case CK_BaseToDerived:
10200 if (!Visit(E->getSubExpr()))
10201 return false;
10202 if (!Result.Base && Result.Offset.isZero())
10203 return true;
10204 return HandleBaseToDerivedCast(Info, E, Result);
10205
10206 case CK_Dynamic:
10207 if (!Visit(E->getSubExpr()))
10208 return false;
10210
10211 case CK_NullToPointer:
10212 VisitIgnoredValue(E->getSubExpr());
10213 return ZeroInitialization(E);
10214
10215 case CK_IntegralToPointer: {
10216 CCEDiag(E, diag::note_constexpr_invalid_cast)
10217 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10218 << Info.Ctx.getLangOpts().CPlusPlus;
10219
10220 APValue Value;
10221 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10222 break;
10223
10224 if (Value.isInt()) {
10225 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10226 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10227 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10228 Result.setNull(Info.Ctx, E->getType());
10229 } else {
10230 Result.Base = (Expr *)nullptr;
10231 Result.InvalidBase = false;
10232 Result.Offset = CharUnits::fromQuantity(N);
10233 Result.Designator.setInvalid();
10234 Result.IsNullPtr = false;
10235 }
10236 return true;
10237 } else {
10238 // In rare instances, the value isn't an lvalue.
10239 // For example, when the value is the difference between the addresses of
10240 // two labels. We reject that as a constant expression because we can't
10241 // compute a valid offset to convert into a pointer.
10242 if (!Value.isLValue())
10243 return false;
10244
10245 // Cast is of an lvalue, no need to change value.
10246 Result.setFrom(Info.Ctx, Value);
10247 return true;
10248 }
10249 }
10250
10251 case CK_ArrayToPointerDecay: {
10252 if (SubExpr->isGLValue()) {
10253 if (!evaluateLValue(SubExpr, Result))
10254 return false;
10255 } else {
10256 APValue &Value = Info.CurrentCall->createTemporary(
10257 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10258 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10259 return false;
10260 }
10261 // The result is a pointer to the first element of the array.
10262 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10263 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10264 Result.addArray(Info, E, CAT);
10265 else
10266 Result.addUnsizedArray(Info, E, AT->getElementType());
10267 return true;
10268 }
10269
10270 case CK_FunctionToPointerDecay:
10271 return evaluateLValue(SubExpr, Result);
10272
10273 case CK_LValueToRValue: {
10274 LValue LVal;
10275 if (!evaluateLValue(E->getSubExpr(), LVal))
10276 return false;
10277
10278 APValue RVal;
10279 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10281 LVal, RVal))
10282 return InvalidBaseOK &&
10283 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10284 return Success(RVal, E);
10285 }
10286 }
10287
10288 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10289}
10290
10292 UnaryExprOrTypeTrait ExprKind) {
10293 // C++ [expr.alignof]p3:
10294 // When alignof is applied to a reference type, the result is the
10295 // alignment of the referenced type.
10296 T = T.getNonReferenceType();
10297
10298 if (T.getQualifiers().hasUnaligned())
10299 return CharUnits::One();
10300
10301 const bool AlignOfReturnsPreferred =
10302 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10303
10304 // __alignof is defined to return the preferred alignment.
10305 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10306 // as well.
10307 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10308 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10309 // alignof and _Alignof are defined to return the ABI alignment.
10310 else if (ExprKind == UETT_AlignOf)
10311 return Ctx.getTypeAlignInChars(T.getTypePtr());
10312 else
10313 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10314}
10315
10317 UnaryExprOrTypeTrait ExprKind) {
10318 E = E->IgnoreParens();
10319
10320 // The kinds of expressions that we have special-case logic here for
10321 // should be kept up to date with the special checks for those
10322 // expressions in Sema.
10323
10324 // alignof decl is always accepted, even if it doesn't make sense: we default
10325 // to 1 in those cases.
10326 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10327 return Ctx.getDeclAlign(DRE->getDecl(),
10328 /*RefAsPointee*/ true);
10329
10330 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10331 return Ctx.getDeclAlign(ME->getMemberDecl(),
10332 /*RefAsPointee*/ true);
10333
10334 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10335}
10336
10337static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10338 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10339 return Info.Ctx.getDeclAlign(VD);
10340 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10341 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10342 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10343}
10344
10345/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10346/// __builtin_is_aligned and __builtin_assume_aligned.
10347static bool getAlignmentArgument(const Expr *E, QualType ForType,
10348 EvalInfo &Info, APSInt &Alignment) {
10349 if (!EvaluateInteger(E, Alignment, Info))
10350 return false;
10351 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10352 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10353 return false;
10354 }
10355 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10356 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10357 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10358 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10359 << MaxValue << ForType << Alignment;
10360 return false;
10361 }
10362 // Ensure both alignment and source value have the same bit width so that we
10363 // don't assert when computing the resulting value.
10364 APSInt ExtAlignment =
10365 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10366 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10367 "Alignment should not be changed by ext/trunc");
10368 Alignment = ExtAlignment;
10369 assert(Alignment.getBitWidth() == SrcWidth);
10370 return true;
10371}
10372
10373// To be clear: this happily visits unsupported builtins. Better name welcomed.
10374bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10375 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10376 return true;
10377
10378 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10379 return false;
10380
10381 Result.setInvalid(E);
10382 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10383 Result.addUnsizedArray(Info, E, PointeeTy);
10384 return true;
10385}
10386
10387bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10388 if (!IsConstantEvaluatedBuiltinCall(E))
10389 return visitNonBuiltinCallExpr(E);
10390 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10391}
10392
10393// Determine if T is a character type for which we guarantee that
10394// sizeof(T) == 1.
10396 return T->isCharType() || T->isChar8Type();
10397}
10398
10399bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10400 unsigned BuiltinOp) {
10401 if (IsOpaqueConstantCall(E))
10402 return Success(E);
10403
10404 switch (BuiltinOp) {
10405 case Builtin::BIaddressof:
10406 case Builtin::BI__addressof:
10407 case Builtin::BI__builtin_addressof:
10408 return evaluateLValue(E->getArg(0), Result);
10409 case Builtin::BI__builtin_assume_aligned: {
10410 // We need to be very careful here because: if the pointer does not have the
10411 // asserted alignment, then the behavior is undefined, and undefined
10412 // behavior is non-constant.
10413 if (!evaluatePointer(E->getArg(0), Result))
10414 return false;
10415
10416 LValue OffsetResult(Result);
10417 APSInt Alignment;
10418 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10419 Alignment))
10420 return false;
10421 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10422
10423 if (E->getNumArgs() > 2) {
10424 APSInt Offset;
10425 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10426 return false;
10427
10428 int64_t AdditionalOffset = -Offset.getZExtValue();
10429 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10430 }
10431
10432 // If there is a base object, then it must have the correct alignment.
10433 if (OffsetResult.Base) {
10434 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10435
10436 if (BaseAlignment < Align) {
10437 Result.Designator.setInvalid();
10438 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10439 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10440 return false;
10441 }
10442 }
10443
10444 // The offset must also have the correct alignment.
10445 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10446 Result.Designator.setInvalid();
10447
10448 (OffsetResult.Base
10449 ? CCEDiag(E->getArg(0),
10450 diag::note_constexpr_baa_insufficient_alignment)
10451 << 1
10452 : CCEDiag(E->getArg(0),
10453 diag::note_constexpr_baa_value_insufficient_alignment))
10454 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10455 return false;
10456 }
10457
10458 return true;
10459 }
10460 case Builtin::BI__builtin_align_up:
10461 case Builtin::BI__builtin_align_down: {
10462 if (!evaluatePointer(E->getArg(0), Result))
10463 return false;
10464 APSInt Alignment;
10465 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10466 Alignment))
10467 return false;
10468 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10469 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10470 // For align_up/align_down, we can return the same value if the alignment
10471 // is known to be greater or equal to the requested value.
10472 if (PtrAlign.getQuantity() >= Alignment)
10473 return true;
10474
10475 // The alignment could be greater than the minimum at run-time, so we cannot
10476 // infer much about the resulting pointer value. One case is possible:
10477 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10478 // can infer the correct index if the requested alignment is smaller than
10479 // the base alignment so we can perform the computation on the offset.
10480 if (BaseAlignment.getQuantity() >= Alignment) {
10481 assert(Alignment.getBitWidth() <= 64 &&
10482 "Cannot handle > 64-bit address-space");
10483 uint64_t Alignment64 = Alignment.getZExtValue();
10484 CharUnits NewOffset = CharUnits::fromQuantity(
10485 BuiltinOp == Builtin::BI__builtin_align_down
10486 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10487 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10488 Result.adjustOffset(NewOffset - Result.Offset);
10489 // TODO: diagnose out-of-bounds values/only allow for arrays?
10490 return true;
10491 }
10492 // Otherwise, we cannot constant-evaluate the result.
10493 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10494 << Alignment;
10495 return false;
10496 }
10497 case Builtin::BI__builtin_operator_new:
10498 return HandleOperatorNewCall(Info, E, Result);
10499 case Builtin::BI__builtin_launder:
10500 return evaluatePointer(E->getArg(0), Result);
10501 case Builtin::BIstrchr:
10502 case Builtin::BIwcschr:
10503 case Builtin::BImemchr:
10504 case Builtin::BIwmemchr:
10505 if (Info.getLangOpts().CPlusPlus11)
10506 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10507 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10508 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10509 else
10510 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10511 [[fallthrough]];
10512 case Builtin::BI__builtin_strchr:
10513 case Builtin::BI__builtin_wcschr:
10514 case Builtin::BI__builtin_memchr:
10515 case Builtin::BI__builtin_char_memchr:
10516 case Builtin::BI__builtin_wmemchr: {
10517 if (!Visit(E->getArg(0)))
10518 return false;
10519 APSInt Desired;
10520 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10521 return false;
10522 uint64_t MaxLength = uint64_t(-1);
10523 if (BuiltinOp != Builtin::BIstrchr &&
10524 BuiltinOp != Builtin::BIwcschr &&
10525 BuiltinOp != Builtin::BI__builtin_strchr &&
10526 BuiltinOp != Builtin::BI__builtin_wcschr) {
10527 APSInt N;
10528 if (!EvaluateInteger(E->getArg(2), N, Info))
10529 return false;
10530 MaxLength = N.getZExtValue();
10531 }
10532 // We cannot find the value if there are no candidates to match against.
10533 if (MaxLength == 0u)
10534 return ZeroInitialization(E);
10535 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10536 Result.Designator.Invalid)
10537 return false;
10538 QualType CharTy = Result.Designator.getType(Info.Ctx);
10539 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10540 BuiltinOp == Builtin::BI__builtin_memchr;
10541 assert(IsRawByte ||
10542 Info.Ctx.hasSameUnqualifiedType(
10543 CharTy, E->getArg(0)->getType()->getPointeeType()));
10544 // Pointers to const void may point to objects of incomplete type.
10545 if (IsRawByte && CharTy->isIncompleteType()) {
10546 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10547 return false;
10548 }
10549 // Give up on byte-oriented matching against multibyte elements.
10550 // FIXME: We can compare the bytes in the correct order.
10551 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10552 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10553 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10554 return false;
10555 }
10556 // Figure out what value we're actually looking for (after converting to
10557 // the corresponding unsigned type if necessary).
10558 uint64_t DesiredVal;
10559 bool StopAtNull = false;
10560 switch (BuiltinOp) {
10561 case Builtin::BIstrchr:
10562 case Builtin::BI__builtin_strchr:
10563 // strchr compares directly to the passed integer, and therefore
10564 // always fails if given an int that is not a char.
10565 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10566 E->getArg(1)->getType(),
10567 Desired),
10568 Desired))
10569 return ZeroInitialization(E);
10570 StopAtNull = true;
10571 [[fallthrough]];
10572 case Builtin::BImemchr:
10573 case Builtin::BI__builtin_memchr:
10574 case Builtin::BI__builtin_char_memchr:
10575 // memchr compares by converting both sides to unsigned char. That's also
10576 // correct for strchr if we get this far (to cope with plain char being
10577 // unsigned in the strchr case).
10578 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10579 break;
10580
10581 case Builtin::BIwcschr:
10582 case Builtin::BI__builtin_wcschr:
10583 StopAtNull = true;
10584 [[fallthrough]];
10585 case Builtin::BIwmemchr:
10586 case Builtin::BI__builtin_wmemchr:
10587 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10588 DesiredVal = Desired.getZExtValue();
10589 break;
10590 }
10591
10592 for (; MaxLength; --MaxLength) {
10593 APValue Char;
10594 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10595 !Char.isInt())
10596 return false;
10597 if (Char.getInt().getZExtValue() == DesiredVal)
10598 return true;
10599 if (StopAtNull && !Char.getInt())
10600 break;
10601 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10602 return false;
10603 }
10604 // Not found: return nullptr.
10605 return ZeroInitialization(E);
10606 }
10607
10608 case Builtin::BImemcpy:
10609 case Builtin::BImemmove:
10610 case Builtin::BIwmemcpy:
10611 case Builtin::BIwmemmove:
10612 if (Info.getLangOpts().CPlusPlus11)
10613 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10614 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10615 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10616 else
10617 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10618 [[fallthrough]];
10619 case Builtin::BI__builtin_memcpy:
10620 case Builtin::BI__builtin_memmove:
10621 case Builtin::BI__builtin_wmemcpy:
10622 case Builtin::BI__builtin_wmemmove: {
10623 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10624 BuiltinOp == Builtin::BIwmemmove ||
10625 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10626 BuiltinOp == Builtin::BI__builtin_wmemmove;
10627 bool Move = BuiltinOp == Builtin::BImemmove ||
10628 BuiltinOp == Builtin::BIwmemmove ||
10629 BuiltinOp == Builtin::BI__builtin_memmove ||
10630 BuiltinOp == Builtin::BI__builtin_wmemmove;
10631
10632 // The result of mem* is the first argument.
10633 if (!Visit(E->getArg(0)))
10634 return false;
10635 LValue Dest = Result;
10636
10637 LValue Src;
10638 if (!EvaluatePointer(E->getArg(1), Src, Info))
10639 return false;
10640
10641 APSInt N;
10642 if (!EvaluateInteger(E->getArg(2), N, Info))
10643 return false;
10644 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10645
10646 // If the size is zero, we treat this as always being a valid no-op.
10647 // (Even if one of the src and dest pointers is null.)
10648 if (!N)
10649 return true;
10650
10651 // Otherwise, if either of the operands is null, we can't proceed. Don't
10652 // try to determine the type of the copied objects, because there aren't
10653 // any.
10654 if (!Src.Base || !Dest.Base) {
10655 APValue Val;
10656 (!Src.Base ? Src : Dest).moveInto(Val);
10657 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10658 << Move << WChar << !!Src.Base
10659 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10660 return false;
10661 }
10662 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10663 return false;
10664
10665 // We require that Src and Dest are both pointers to arrays of
10666 // trivially-copyable type. (For the wide version, the designator will be
10667 // invalid if the designated object is not a wchar_t.)
10668 QualType T = Dest.Designator.getType(Info.Ctx);
10669 QualType SrcT = Src.Designator.getType(Info.Ctx);
10670 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10671 // FIXME: Consider using our bit_cast implementation to support this.
10672 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10673 return false;
10674 }
10675 if (T->isIncompleteType()) {
10676 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10677 return false;
10678 }
10679 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10680 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10681 return false;
10682 }
10683
10684 // Figure out how many T's we're copying.
10685 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10686 if (TSize == 0)
10687 return false;
10688 if (!WChar) {
10689 uint64_t Remainder;
10690 llvm::APInt OrigN = N;
10691 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10692 if (Remainder) {
10693 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10694 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10695 << (unsigned)TSize;
10696 return false;
10697 }
10698 }
10699
10700 // Check that the copying will remain within the arrays, just so that we
10701 // can give a more meaningful diagnostic. This implicitly also checks that
10702 // N fits into 64 bits.
10703 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10704 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10705 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10706 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10707 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10708 << toString(N, 10, /*Signed*/false);
10709 return false;
10710 }
10711 uint64_t NElems = N.getZExtValue();
10712 uint64_t NBytes = NElems * TSize;
10713
10714 // Check for overlap.
10715 int Direction = 1;
10716 if (HasSameBase(Src, Dest)) {
10717 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10718 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10719 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10720 // Dest is inside the source region.
10721 if (!Move) {
10722 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10723 return false;
10724 }
10725 // For memmove and friends, copy backwards.
10726 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10727 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10728 return false;
10729 Direction = -1;
10730 } else if (!Move && SrcOffset >= DestOffset &&
10731 SrcOffset - DestOffset < NBytes) {
10732 // Src is inside the destination region for memcpy: invalid.
10733 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10734 return false;
10735 }
10736 }
10737
10738 while (true) {
10739 APValue Val;
10740 // FIXME: Set WantObjectRepresentation to true if we're copying a
10741 // char-like type?
10742 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10743 !handleAssignment(Info, E, Dest, T, Val))
10744 return false;
10745 // Do not iterate past the last element; if we're copying backwards, that
10746 // might take us off the start of the array.
10747 if (--NElems == 0)
10748 return true;
10749 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10750 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10751 return false;
10752 }
10753 }
10754
10755 default:
10756 return false;
10757 }
10758}
10759
10760static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10761 APValue &Result, const InitListExpr *ILE,
10762 QualType AllocType);
10763static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10764 APValue &Result,
10765 const CXXConstructExpr *CCE,
10766 QualType AllocType);
10767
10768bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10769 if (!Info.getLangOpts().CPlusPlus20)
10770 Info.CCEDiag(E, diag::note_constexpr_new);
10771
10772 // We cannot speculatively evaluate a delete expression.
10773 if (Info.SpeculativeEvaluationDepth)
10774 return false;
10775
10776 FunctionDecl *OperatorNew = E->getOperatorNew();
10777 QualType AllocType = E->getAllocatedType();
10778 QualType TargetType = AllocType;
10779
10780 bool IsNothrow = false;
10781 bool IsPlacement = false;
10782
10783 if (E->getNumPlacementArgs() == 1 &&
10784 E->getPlacementArg(0)->getType()->isNothrowT()) {
10785 // The only new-placement list we support is of the form (std::nothrow).
10786 //
10787 // FIXME: There is no restriction on this, but it's not clear that any
10788 // other form makes any sense. We get here for cases such as:
10789 //
10790 // new (std::align_val_t{N}) X(int)
10791 //
10792 // (which should presumably be valid only if N is a multiple of
10793 // alignof(int), and in any case can't be deallocated unless N is
10794 // alignof(X) and X has new-extended alignment).
10795 LValue Nothrow;
10796 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10797 return false;
10798 IsNothrow = true;
10799 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10800 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10801 (Info.CurrentCall->CanEvalMSConstexpr &&
10802 OperatorNew->hasAttr<MSConstexprAttr>())) {
10803 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10804 return false;
10805 if (Result.Designator.Invalid)
10806 return false;
10807 TargetType = E->getPlacementArg(0)->getType();
10808 IsPlacement = true;
10809 } else {
10810 Info.FFDiag(E, diag::note_constexpr_new_placement)
10811 << /*C++26 feature*/ 1 << E->getSourceRange();
10812 return false;
10813 }
10814 } else if (E->getNumPlacementArgs()) {
10815 Info.FFDiag(E, diag::note_constexpr_new_placement)
10816 << /*Unsupported*/ 0 << E->getSourceRange();
10817 return false;
10818 } else if (!OperatorNew
10819 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10820 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10821 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10822 return false;
10823 }
10824
10825 const Expr *Init = E->getInitializer();
10826 const InitListExpr *ResizedArrayILE = nullptr;
10827 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10828 bool ValueInit = false;
10829
10830 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10831 const Expr *Stripped = *ArraySize;
10832 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10833 Stripped = ICE->getSubExpr())
10834 if (ICE->getCastKind() != CK_NoOp &&
10835 ICE->getCastKind() != CK_IntegralCast)
10836 break;
10837
10838 llvm::APSInt ArrayBound;
10839 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10840 return false;
10841
10842 // C++ [expr.new]p9:
10843 // The expression is erroneous if:
10844 // -- [...] its value before converting to size_t [or] applying the
10845 // second standard conversion sequence is less than zero
10846 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10847 if (IsNothrow)
10848 return ZeroInitialization(E);
10849
10850 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10851 << ArrayBound << (*ArraySize)->getSourceRange();
10852 return false;
10853 }
10854
10855 // -- its value is such that the size of the allocated object would
10856 // exceed the implementation-defined limit
10857 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10859 Info.Ctx, AllocType, ArrayBound),
10860 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10861 if (IsNothrow)
10862 return ZeroInitialization(E);
10863 return false;
10864 }
10865
10866 // -- the new-initializer is a braced-init-list and the number of
10867 // array elements for which initializers are provided [...]
10868 // exceeds the number of elements to initialize
10869 if (!Init) {
10870 // No initialization is performed.
10871 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10873 ValueInit = true;
10874 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10875 ResizedArrayCCE = CCE;
10876 } else {
10877 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10878 assert(CAT && "unexpected type for array initializer");
10879
10880 unsigned Bits =
10881 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10882 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10883 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10884 if (InitBound.ugt(AllocBound)) {
10885 if (IsNothrow)
10886 return ZeroInitialization(E);
10887
10888 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10889 << toString(AllocBound, 10, /*Signed=*/false)
10890 << toString(InitBound, 10, /*Signed=*/false)
10891 << (*ArraySize)->getSourceRange();
10892 return false;
10893 }
10894
10895 // If the sizes differ, we must have an initializer list, and we need
10896 // special handling for this case when we initialize.
10897 if (InitBound != AllocBound)
10898 ResizedArrayILE = cast<InitListExpr>(Init);
10899 }
10900
10901 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10902 ArraySizeModifier::Normal, 0);
10903 } else {
10904 assert(!AllocType->isArrayType() &&
10905 "array allocation with non-array new");
10906 }
10907
10908 APValue *Val;
10909 if (IsPlacement) {
10911 struct FindObjectHandler {
10912 EvalInfo &Info;
10913 const Expr *E;
10914 QualType AllocType;
10915 const AccessKinds AccessKind;
10916 APValue *Value;
10917
10918 typedef bool result_type;
10919 bool failed() { return false; }
10920 bool checkConst(QualType QT) {
10921 if (QT.isConstQualified()) {
10922 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10923 return false;
10924 }
10925 return true;
10926 }
10927 bool found(APValue &Subobj, QualType SubobjType) {
10928 if (!checkConst(SubobjType))
10929 return false;
10930 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10931 // old name of the object to be used to name the new object.
10932 unsigned SubobjectSize = 1;
10933 unsigned AllocSize = 1;
10934 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10935 AllocSize = CAT->getZExtSize();
10936 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10937 SubobjectSize = CAT->getZExtSize();
10938 if (SubobjectSize < AllocSize ||
10939 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10940 Info.Ctx.getBaseElementType(AllocType))) {
10941 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10942 << SubobjType << AllocType;
10943 return false;
10944 }
10945 Value = &Subobj;
10946 return true;
10947 }
10948 bool found(APSInt &Value, QualType SubobjType) {
10949 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10950 return false;
10951 }
10952 bool found(APFloat &Value, QualType SubobjType) {
10953 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10954 return false;
10955 }
10956 } Handler = {Info, E, AllocType, AK, nullptr};
10957
10958 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10959 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10960 return false;
10961
10962 Val = Handler.Value;
10963
10964 // [basic.life]p1:
10965 // The lifetime of an object o of type T ends when [...] the storage
10966 // which the object occupies is [...] reused by an object that is not
10967 // nested within o (6.6.2).
10968 *Val = APValue();
10969 } else {
10970 // Perform the allocation and obtain a pointer to the resulting object.
10971 Val = Info.createHeapAlloc(E, AllocType, Result);
10972 if (!Val)
10973 return false;
10974 }
10975
10976 if (ValueInit) {
10977 ImplicitValueInitExpr VIE(AllocType);
10978 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10979 return false;
10980 } else if (ResizedArrayILE) {
10981 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10982 AllocType))
10983 return false;
10984 } else if (ResizedArrayCCE) {
10985 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10986 AllocType))
10987 return false;
10988 } else if (Init) {
10989 if (!EvaluateInPlace(*Val, Info, Result, Init))
10990 return false;
10991 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10992 return false;
10993 }
10994
10995 // Array new returns a pointer to the first element, not a pointer to the
10996 // array.
10997 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10998 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10999
11000 return true;
11001}
11002//===----------------------------------------------------------------------===//
11003// Member Pointer Evaluation
11004//===----------------------------------------------------------------------===//
11005
11006namespace {
11007class MemberPointerExprEvaluator
11008 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11009 MemberPtr &Result;
11010
11011 bool Success(const ValueDecl *D) {
11012 Result = MemberPtr(D);
11013 return true;
11014 }
11015public:
11016
11017 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11018 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11019
11020 bool Success(const APValue &V, const Expr *E) {
11021 Result.setFrom(V);
11022 return true;
11023 }
11024 bool ZeroInitialization(const Expr *E) {
11025 return Success((const ValueDecl*)nullptr);
11026 }
11027
11028 bool VisitCastExpr(const CastExpr *E);
11029 bool VisitUnaryAddrOf(const UnaryOperator *E);
11030};
11031} // end anonymous namespace
11032
11033static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11034 EvalInfo &Info) {
11035 assert(!E->isValueDependent());
11036 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11037 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11038}
11039
11040bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11041 switch (E->getCastKind()) {
11042 default:
11043 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11044
11045 case CK_NullToMemberPointer:
11046 VisitIgnoredValue(E->getSubExpr());
11047 return ZeroInitialization(E);
11048
11049 case CK_BaseToDerivedMemberPointer: {
11050 if (!Visit(E->getSubExpr()))
11051 return false;
11052 if (E->path_empty())
11053 return true;
11054 // Base-to-derived member pointer casts store the path in derived-to-base
11055 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11056 // the wrong end of the derived->base arc, so stagger the path by one class.
11057 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11058 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11059 PathI != PathE; ++PathI) {
11060 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11061 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11062 if (!Result.castToDerived(Derived))
11063 return Error(E);
11064 }
11065 if (!Result.castToDerived(E->getType()
11066 ->castAs<MemberPointerType>()
11067 ->getMostRecentCXXRecordDecl()))
11068 return Error(E);
11069 return true;
11070 }
11071
11072 case CK_DerivedToBaseMemberPointer:
11073 if (!Visit(E->getSubExpr()))
11074 return false;
11075 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11076 PathE = E->path_end(); PathI != PathE; ++PathI) {
11077 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11078 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11079 if (!Result.castToBase(Base))
11080 return Error(E);
11081 }
11082 return true;
11083 }
11084}
11085
11086bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11087 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11088 // member can be formed.
11089 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11090}
11091
11092//===----------------------------------------------------------------------===//
11093// Record Evaluation
11094//===----------------------------------------------------------------------===//
11095
11096namespace {
11097 class RecordExprEvaluator
11098 : public ExprEvaluatorBase<RecordExprEvaluator> {
11099 const LValue &This;
11100 APValue &Result;
11101 public:
11102
11103 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11104 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11105
11106 bool Success(const APValue &V, const Expr *E) {
11107 Result = V;
11108 return true;
11109 }
11110 bool ZeroInitialization(const Expr *E) {
11111 return ZeroInitialization(E, E->getType());
11112 }
11113 bool ZeroInitialization(const Expr *E, QualType T);
11114
11115 bool VisitCallExpr(const CallExpr *E) {
11116 return handleCallExpr(E, Result, &This);
11117 }
11118 bool VisitCastExpr(const CastExpr *E);
11119 bool VisitInitListExpr(const InitListExpr *E);
11120 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11121 return VisitCXXConstructExpr(E, E->getType());
11122 }
11123 bool VisitLambdaExpr(const LambdaExpr *E);
11124 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11125 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11126 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11127 bool VisitBinCmp(const BinaryOperator *E);
11128 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11129 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11130 ArrayRef<Expr *> Args);
11131 };
11132}
11133
11134/// Perform zero-initialization on an object of non-union class type.
11135/// C++11 [dcl.init]p5:
11136/// To zero-initialize an object or reference of type T means:
11137/// [...]
11138/// -- if T is a (possibly cv-qualified) non-union class type,
11139/// each non-static data member and each base-class subobject is
11140/// zero-initialized
11141static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11142 const RecordDecl *RD,
11143 const LValue &This, APValue &Result) {
11144 assert(!RD->isUnion() && "Expected non-union class type");
11145 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11146 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11147 RD->getNumFields());
11148
11149 if (RD->isInvalidDecl()) return false;
11150 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11151
11152 if (CD) {
11153 unsigned Index = 0;
11155 End = CD->bases_end(); I != End; ++I, ++Index) {
11156 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11157 LValue Subobject = This;
11158 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11159 return false;
11160 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11161 Result.getStructBase(Index)))
11162 return false;
11163 }
11164 }
11165
11166 for (const auto *I : RD->fields()) {
11167 // -- if T is a reference type, no initialization is performed.
11168 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11169 continue;
11170
11171 LValue Subobject = This;
11172 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11173 return false;
11174
11175 ImplicitValueInitExpr VIE(I->getType());
11176 if (!EvaluateInPlace(
11177 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11178 return false;
11179 }
11180
11181 return true;
11182}
11183
11184bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11185 const auto *RD = T->castAsRecordDecl();
11186 if (RD->isInvalidDecl()) return false;
11187 if (RD->isUnion()) {
11188 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11189 // object's first non-static named data member is zero-initialized
11191 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11192 ++I;
11193 if (I == RD->field_end()) {
11194 Result = APValue((const FieldDecl*)nullptr);
11195 return true;
11196 }
11197
11198 LValue Subobject = This;
11199 if (!HandleLValueMember(Info, E, Subobject, *I))
11200 return false;
11201 Result = APValue(*I);
11202 ImplicitValueInitExpr VIE(I->getType());
11203 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11204 }
11205
11206 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11207 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11208 return false;
11209 }
11210
11211 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11212}
11213
11214bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11215 switch (E->getCastKind()) {
11216 default:
11217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11218
11219 case CK_ConstructorConversion:
11220 return Visit(E->getSubExpr());
11221
11222 case CK_DerivedToBase:
11223 case CK_UncheckedDerivedToBase: {
11224 APValue DerivedObject;
11225 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11226 return false;
11227 if (!DerivedObject.isStruct())
11228 return Error(E->getSubExpr());
11229
11230 // Derived-to-base rvalue conversion: just slice off the derived part.
11231 APValue *Value = &DerivedObject;
11232 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11233 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11234 PathE = E->path_end(); PathI != PathE; ++PathI) {
11235 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11236 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11237 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11238 RD = Base;
11239 }
11240 Result = *Value;
11241 return true;
11242 }
11243 case CK_HLSLAggregateSplatCast: {
11244 APValue Val;
11245 QualType ValTy;
11246
11247 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11248 return false;
11249
11250 unsigned NEls = elementwiseSize(Info, E->getType());
11251 // splat our Val
11252 SmallVector<APValue> SplatEls(NEls, Val);
11253 SmallVector<QualType> SplatType(NEls, ValTy);
11254
11255 // cast the elements and construct our struct result
11256 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11257 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11258 SplatType))
11259 return false;
11260
11261 return true;
11262 }
11263 case CK_HLSLElementwiseCast: {
11264 SmallVector<APValue> SrcEls;
11265 SmallVector<QualType> SrcTypes;
11266
11267 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11268 SrcTypes))
11269 return false;
11270
11271 // cast the elements and construct our struct result
11272 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11273 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11274 SrcTypes))
11275 return false;
11276
11277 return true;
11278 }
11279 }
11280}
11281
11282bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11283 if (E->isTransparent())
11284 return Visit(E->getInit(0));
11285 return VisitCXXParenListOrInitListExpr(E, E->inits());
11286}
11287
11288bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11289 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11290 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11291 if (RD->isInvalidDecl()) return false;
11292 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11293 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11294
11295 EvalInfo::EvaluatingConstructorRAII EvalObj(
11296 Info,
11297 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11298 CXXRD && CXXRD->getNumBases());
11299
11300 if (RD->isUnion()) {
11301 const FieldDecl *Field;
11302 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11303 Field = ILE->getInitializedFieldInUnion();
11304 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11305 Field = PLIE->getInitializedFieldInUnion();
11306 } else {
11307 llvm_unreachable(
11308 "Expression is neither an init list nor a C++ paren list");
11309 }
11310
11311 Result = APValue(Field);
11312 if (!Field)
11313 return true;
11314
11315 // If the initializer list for a union does not contain any elements, the
11316 // first element of the union is value-initialized.
11317 // FIXME: The element should be initialized from an initializer list.
11318 // Is this difference ever observable for initializer lists which
11319 // we don't build?
11320 ImplicitValueInitExpr VIE(Field->getType());
11321 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11322
11323 LValue Subobject = This;
11324 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11325 return false;
11326
11327 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11328 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11329 isa<CXXDefaultInitExpr>(InitExpr));
11330
11331 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11332 if (Field->isBitField())
11333 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11334 Field);
11335 return true;
11336 }
11337
11338 return false;
11339 }
11340
11341 if (!Result.hasValue())
11342 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11343 RD->getNumFields());
11344 unsigned ElementNo = 0;
11345 bool Success = true;
11346
11347 // Initialize base classes.
11348 if (CXXRD && CXXRD->getNumBases()) {
11349 for (const auto &Base : CXXRD->bases()) {
11350 assert(ElementNo < Args.size() && "missing init for base class");
11351 const Expr *Init = Args[ElementNo];
11352
11353 LValue Subobject = This;
11354 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11355 return false;
11356
11357 APValue &FieldVal = Result.getStructBase(ElementNo);
11358 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11359 if (!Info.noteFailure())
11360 return false;
11361 Success = false;
11362 }
11363 ++ElementNo;
11364 }
11365
11366 EvalObj.finishedConstructingBases();
11367 }
11368
11369 // Initialize members.
11370 for (const auto *Field : RD->fields()) {
11371 // Anonymous bit-fields are not considered members of the class for
11372 // purposes of aggregate initialization.
11373 if (Field->isUnnamedBitField())
11374 continue;
11375
11376 LValue Subobject = This;
11377
11378 bool HaveInit = ElementNo < Args.size();
11379
11380 // FIXME: Diagnostics here should point to the end of the initializer
11381 // list, not the start.
11382 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11383 Subobject, Field, &Layout))
11384 return false;
11385
11386 // Perform an implicit value-initialization for members beyond the end of
11387 // the initializer list.
11388 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11389 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11390
11391 if (Field->getType()->isIncompleteArrayType()) {
11392 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11393 if (!CAT->isZeroSize()) {
11394 // Bail out for now. This might sort of "work", but the rest of the
11395 // code isn't really prepared to handle it.
11396 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11397 return false;
11398 }
11399 }
11400 }
11401
11402 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11403 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11405
11406 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11407 if (Field->getType()->isReferenceType()) {
11408 LValue Result;
11410 FieldVal)) {
11411 if (!Info.noteFailure())
11412 return false;
11413 Success = false;
11414 }
11415 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11416 (Field->isBitField() &&
11417 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11418 if (!Info.noteFailure())
11419 return false;
11420 Success = false;
11421 }
11422 }
11423
11424 EvalObj.finishedConstructingFields();
11425
11426 return Success;
11427}
11428
11429bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11430 QualType T) {
11431 // Note that E's type is not necessarily the type of our class here; we might
11432 // be initializing an array element instead.
11433 const CXXConstructorDecl *FD = E->getConstructor();
11434 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11435
11436 bool ZeroInit = E->requiresZeroInitialization();
11437 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11438 if (ZeroInit)
11439 return ZeroInitialization(E, T);
11440
11442 }
11443
11444 const FunctionDecl *Definition = nullptr;
11445 auto Body = FD->getBody(Definition);
11446
11447 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11448 return false;
11449
11450 // Avoid materializing a temporary for an elidable copy/move constructor.
11451 if (E->isElidable() && !ZeroInit) {
11452 // FIXME: This only handles the simplest case, where the source object
11453 // is passed directly as the first argument to the constructor.
11454 // This should also handle stepping though implicit casts and
11455 // and conversion sequences which involve two steps, with a
11456 // conversion operator followed by a converting constructor.
11457 const Expr *SrcObj = E->getArg(0);
11458 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11459 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11460 if (const MaterializeTemporaryExpr *ME =
11461 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11462 return Visit(ME->getSubExpr());
11463 }
11464
11465 if (ZeroInit && !ZeroInitialization(E, T))
11466 return false;
11467
11468 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11469 return HandleConstructorCall(E, This, Args,
11471 Result);
11472}
11473
11474bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11475 const CXXInheritedCtorInitExpr *E) {
11476 if (!Info.CurrentCall) {
11477 assert(Info.checkingPotentialConstantExpression());
11478 return false;
11479 }
11480
11481 const CXXConstructorDecl *FD = E->getConstructor();
11482 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11483 return false;
11484
11485 const FunctionDecl *Definition = nullptr;
11486 auto Body = FD->getBody(Definition);
11487
11488 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11489 return false;
11490
11491 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11493 Result);
11494}
11495
11496bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11497 const CXXStdInitializerListExpr *E) {
11498 const ConstantArrayType *ArrayType =
11499 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11500
11501 LValue Array;
11502 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11503 return false;
11504
11505 assert(ArrayType && "unexpected type for array initializer");
11506
11507 // Get a pointer to the first element of the array.
11508 Array.addArray(Info, E, ArrayType);
11509
11510 // FIXME: What if the initializer_list type has base classes, etc?
11511 Result = APValue(APValue::UninitStruct(), 0, 2);
11512 Array.moveInto(Result.getStructField(0));
11513
11514 auto *Record = E->getType()->castAsRecordDecl();
11515 RecordDecl::field_iterator Field = Record->field_begin();
11516 assert(Field != Record->field_end() &&
11517 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11518 ArrayType->getElementType()) &&
11519 "Expected std::initializer_list first field to be const E *");
11520 ++Field;
11521 assert(Field != Record->field_end() &&
11522 "Expected std::initializer_list to have two fields");
11523
11524 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11525 // Length.
11526 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11527 } else {
11528 // End pointer.
11529 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11530 ArrayType->getElementType()) &&
11531 "Expected std::initializer_list second field to be const E *");
11532 if (!HandleLValueArrayAdjustment(Info, E, Array,
11533 ArrayType->getElementType(),
11534 ArrayType->getZExtSize()))
11535 return false;
11536 Array.moveInto(Result.getStructField(1));
11537 }
11538
11539 assert(++Field == Record->field_end() &&
11540 "Expected std::initializer_list to only have two fields");
11541
11542 return true;
11543}
11544
11545bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11546 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11547 if (ClosureClass->isInvalidDecl())
11548 return false;
11549
11550 const size_t NumFields = ClosureClass->getNumFields();
11551
11552 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11553 E->capture_init_end()) &&
11554 "The number of lambda capture initializers should equal the number of "
11555 "fields within the closure type");
11556
11557 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11558 // Iterate through all the lambda's closure object's fields and initialize
11559 // them.
11560 auto *CaptureInitIt = E->capture_init_begin();
11561 bool Success = true;
11562 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11563 for (const auto *Field : ClosureClass->fields()) {
11564 assert(CaptureInitIt != E->capture_init_end());
11565 // Get the initializer for this field
11566 Expr *const CurFieldInit = *CaptureInitIt++;
11567
11568 // If there is no initializer, either this is a VLA or an error has
11569 // occurred.
11570 if (!CurFieldInit || CurFieldInit->containsErrors())
11571 return Error(E);
11572
11573 LValue Subobject = This;
11574
11575 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11576 return false;
11577
11578 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11579 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11580 if (!Info.keepEvaluatingAfterFailure())
11581 return false;
11582 Success = false;
11583 }
11584 }
11585 return Success;
11586}
11587
11588static bool EvaluateRecord(const Expr *E, const LValue &This,
11589 APValue &Result, EvalInfo &Info) {
11590 assert(!E->isValueDependent());
11591 assert(E->isPRValue() && E->getType()->isRecordType() &&
11592 "can't evaluate expression as a record rvalue");
11593 return RecordExprEvaluator(Info, This, Result).Visit(E);
11594}
11595
11596//===----------------------------------------------------------------------===//
11597// Temporary Evaluation
11598//
11599// Temporaries are represented in the AST as rvalues, but generally behave like
11600// lvalues. The full-object of which the temporary is a subobject is implicitly
11601// materialized so that a reference can bind to it.
11602//===----------------------------------------------------------------------===//
11603namespace {
11604class TemporaryExprEvaluator
11605 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11606public:
11607 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11608 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11609
11610 /// Visit an expression which constructs the value of this temporary.
11611 bool VisitConstructExpr(const Expr *E) {
11612 APValue &Value = Info.CurrentCall->createTemporary(
11613 E, E->getType(), ScopeKind::FullExpression, Result);
11614 return EvaluateInPlace(Value, Info, Result, E);
11615 }
11616
11617 bool VisitCastExpr(const CastExpr *E) {
11618 switch (E->getCastKind()) {
11619 default:
11620 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11621
11622 case CK_ConstructorConversion:
11623 return VisitConstructExpr(E->getSubExpr());
11624 }
11625 }
11626 bool VisitInitListExpr(const InitListExpr *E) {
11627 return VisitConstructExpr(E);
11628 }
11629 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11630 return VisitConstructExpr(E);
11631 }
11632 bool VisitCallExpr(const CallExpr *E) {
11633 return VisitConstructExpr(E);
11634 }
11635 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11636 return VisitConstructExpr(E);
11637 }
11638 bool VisitLambdaExpr(const LambdaExpr *E) {
11639 return VisitConstructExpr(E);
11640 }
11641};
11642} // end anonymous namespace
11643
11644/// Evaluate an expression of record type as a temporary.
11645static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11646 assert(!E->isValueDependent());
11647 assert(E->isPRValue() && E->getType()->isRecordType());
11648 return TemporaryExprEvaluator(Info, Result).Visit(E);
11649}
11650
11651//===----------------------------------------------------------------------===//
11652// Vector Evaluation
11653//===----------------------------------------------------------------------===//
11654
11655namespace {
11656 class VectorExprEvaluator
11657 : public ExprEvaluatorBase<VectorExprEvaluator> {
11658 APValue &Result;
11659 public:
11660
11661 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11662 : ExprEvaluatorBaseTy(info), Result(Result) {}
11663
11664 bool Success(ArrayRef<APValue> V, const Expr *E) {
11665 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11666 // FIXME: remove this APValue copy.
11667 Result = APValue(V.data(), V.size());
11668 return true;
11669 }
11670 bool Success(const APValue &V, const Expr *E) {
11671 assert(V.isVector());
11672 Result = V;
11673 return true;
11674 }
11675 bool ZeroInitialization(const Expr *E);
11676
11677 bool VisitUnaryReal(const UnaryOperator *E)
11678 { return Visit(E->getSubExpr()); }
11679 bool VisitCastExpr(const CastExpr* E);
11680 bool VisitInitListExpr(const InitListExpr *E);
11681 bool VisitUnaryImag(const UnaryOperator *E);
11682 bool VisitBinaryOperator(const BinaryOperator *E);
11683 bool VisitUnaryOperator(const UnaryOperator *E);
11684 bool VisitCallExpr(const CallExpr *E);
11685 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11686 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11687
11688 // FIXME: Missing: conditional operator (for GNU
11689 // conditional select), ExtVectorElementExpr
11690 };
11691} // end anonymous namespace
11692
11693static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11694 assert(E->isPRValue() && E->getType()->isVectorType() &&
11695 "not a vector prvalue");
11696 return VectorExprEvaluator(Info, Result).Visit(E);
11697}
11698
11699static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11700 assert(Val.isVector() && "expected vector APValue");
11701 unsigned NumElts = Val.getVectorLength();
11702
11703 // Each element is one bit, so create an integer with NumElts bits.
11704 llvm::APInt Result(NumElts, 0);
11705
11706 for (unsigned I = 0; I < NumElts; ++I) {
11707 const APValue &Elt = Val.getVectorElt(I);
11708 assert(Elt.isInt() && "expected integer element in bool vector");
11709
11710 if (Elt.getInt().getBoolValue())
11711 Result.setBit(I);
11712 }
11713
11714 return Result;
11715}
11716
11717bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11718 const VectorType *VTy = E->getType()->castAs<VectorType>();
11719 unsigned NElts = VTy->getNumElements();
11720
11721 const Expr *SE = E->getSubExpr();
11722 QualType SETy = SE->getType();
11723
11724 switch (E->getCastKind()) {
11725 case CK_VectorSplat: {
11726 APValue Val = APValue();
11727 if (SETy->isIntegerType()) {
11728 APSInt IntResult;
11729 if (!EvaluateInteger(SE, IntResult, Info))
11730 return false;
11731 Val = APValue(std::move(IntResult));
11732 } else if (SETy->isRealFloatingType()) {
11733 APFloat FloatResult(0.0);
11734 if (!EvaluateFloat(SE, FloatResult, Info))
11735 return false;
11736 Val = APValue(std::move(FloatResult));
11737 } else {
11738 return Error(E);
11739 }
11740
11741 // Splat and create vector APValue.
11742 SmallVector<APValue, 4> Elts(NElts, Val);
11743 return Success(Elts, E);
11744 }
11745 case CK_BitCast: {
11746 APValue SVal;
11747 if (!Evaluate(SVal, Info, SE))
11748 return false;
11749
11750 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11751 // Give up if the input isn't an int, float, or vector. For example, we
11752 // reject "(v4i16)(intptr_t)&a".
11753 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11754 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11755 << Info.Ctx.getLangOpts().CPlusPlus;
11756 return false;
11757 }
11758
11759 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11760 return false;
11761
11762 return true;
11763 }
11764 case CK_HLSLVectorTruncation: {
11765 APValue Val;
11766 SmallVector<APValue, 4> Elements;
11767 if (!EvaluateVector(SE, Val, Info))
11768 return Error(E);
11769 for (unsigned I = 0; I < NElts; I++)
11770 Elements.push_back(Val.getVectorElt(I));
11771 return Success(Elements, E);
11772 }
11773 case CK_HLSLMatrixTruncation: {
11774 // TODO: See #168935. Add matrix truncation support to expr constant.
11775 return Error(E);
11776 }
11777 case CK_HLSLAggregateSplatCast: {
11778 APValue Val;
11779 QualType ValTy;
11780
11781 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11782 return false;
11783
11784 // cast our Val once.
11786 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11787 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11788 Result))
11789 return false;
11790
11791 SmallVector<APValue, 4> SplatEls(NElts, Result);
11792 return Success(SplatEls, E);
11793 }
11794 case CK_HLSLElementwiseCast: {
11795 SmallVector<APValue> SrcVals;
11796 SmallVector<QualType> SrcTypes;
11797
11798 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11799 return false;
11800
11801 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11802 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11803 SmallVector<APValue, 4> ResultEls(NElts);
11804 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11805 ResultEls))
11806 return false;
11807 return Success(ResultEls, E);
11808 }
11809 default:
11810 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11811 }
11812}
11813
11814bool
11815VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11816 const VectorType *VT = E->getType()->castAs<VectorType>();
11817 unsigned NumInits = E->getNumInits();
11818 unsigned NumElements = VT->getNumElements();
11819
11820 QualType EltTy = VT->getElementType();
11821 SmallVector<APValue, 4> Elements;
11822
11823 // MFloat8 type doesn't have constants and thus constant folding
11824 // is impossible.
11825 if (EltTy->isMFloat8Type())
11826 return false;
11827
11828 // The number of initializers can be less than the number of
11829 // vector elements. For OpenCL, this can be due to nested vector
11830 // initialization. For GCC compatibility, missing trailing elements
11831 // should be initialized with zeroes.
11832 unsigned CountInits = 0, CountElts = 0;
11833 while (CountElts < NumElements) {
11834 // Handle nested vector initialization.
11835 if (CountInits < NumInits
11836 && E->getInit(CountInits)->getType()->isVectorType()) {
11837 APValue v;
11838 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11839 return Error(E);
11840 unsigned vlen = v.getVectorLength();
11841 for (unsigned j = 0; j < vlen; j++)
11842 Elements.push_back(v.getVectorElt(j));
11843 CountElts += vlen;
11844 } else if (EltTy->isIntegerType()) {
11845 llvm::APSInt sInt(32);
11846 if (CountInits < NumInits) {
11847 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11848 return false;
11849 } else // trailing integer zero.
11850 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11851 Elements.push_back(APValue(sInt));
11852 CountElts++;
11853 } else {
11854 llvm::APFloat f(0.0);
11855 if (CountInits < NumInits) {
11856 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11857 return false;
11858 } else // trailing float zero.
11859 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11860 Elements.push_back(APValue(f));
11861 CountElts++;
11862 }
11863 CountInits++;
11864 }
11865 return Success(Elements, E);
11866}
11867
11868bool
11869VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11870 const auto *VT = E->getType()->castAs<VectorType>();
11871 QualType EltTy = VT->getElementType();
11872 APValue ZeroElement;
11873 if (EltTy->isIntegerType())
11874 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11875 else
11876 ZeroElement =
11877 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11878
11879 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11880 return Success(Elements, E);
11881}
11882
11883bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11884 VisitIgnoredValue(E->getSubExpr());
11885 return ZeroInitialization(E);
11886}
11887
11888bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11889 BinaryOperatorKind Op = E->getOpcode();
11890 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11891 "Operation not supported on vector types");
11892
11893 if (Op == BO_Comma)
11894 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11895
11896 Expr *LHS = E->getLHS();
11897 Expr *RHS = E->getRHS();
11898
11899 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11900 "Must both be vector types");
11901 // Checking JUST the types are the same would be fine, except shifts don't
11902 // need to have their types be the same (since you always shift by an int).
11903 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11904 E->getType()->castAs<VectorType>()->getNumElements() &&
11905 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11906 E->getType()->castAs<VectorType>()->getNumElements() &&
11907 "All operands must be the same size.");
11908
11909 APValue LHSValue;
11910 APValue RHSValue;
11911 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11912 if (!LHSOK && !Info.noteFailure())
11913 return false;
11914 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11915 return false;
11916
11917 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11918 return false;
11919
11920 return Success(LHSValue, E);
11921}
11922
11923static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11924 QualType ResultTy,
11926 APValue Elt) {
11927 switch (Op) {
11928 case UO_Plus:
11929 // Nothing to do here.
11930 return Elt;
11931 case UO_Minus:
11932 if (Elt.getKind() == APValue::Int) {
11933 Elt.getInt().negate();
11934 } else {
11935 assert(Elt.getKind() == APValue::Float &&
11936 "Vector can only be int or float type");
11937 Elt.getFloat().changeSign();
11938 }
11939 return Elt;
11940 case UO_Not:
11941 // This is only valid for integral types anyway, so we don't have to handle
11942 // float here.
11943 assert(Elt.getKind() == APValue::Int &&
11944 "Vector operator ~ can only be int");
11945 Elt.getInt().flipAllBits();
11946 return Elt;
11947 case UO_LNot: {
11948 if (Elt.getKind() == APValue::Int) {
11949 Elt.getInt() = !Elt.getInt();
11950 // operator ! on vectors returns -1 for 'truth', so negate it.
11951 Elt.getInt().negate();
11952 return Elt;
11953 }
11954 assert(Elt.getKind() == APValue::Float &&
11955 "Vector can only be int or float type");
11956 // Float types result in an int of the same size, but -1 for true, or 0 for
11957 // false.
11958 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11959 ResultTy->isUnsignedIntegerType()};
11960 if (Elt.getFloat().isZero())
11961 EltResult.setAllBits();
11962 else
11963 EltResult.clearAllBits();
11964
11965 return APValue{EltResult};
11966 }
11967 default:
11968 // FIXME: Implement the rest of the unary operators.
11969 return std::nullopt;
11970 }
11971}
11972
11973bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11974 Expr *SubExpr = E->getSubExpr();
11975 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11976 // This result element type differs in the case of negating a floating point
11977 // vector, since the result type is the a vector of the equivilant sized
11978 // integer.
11979 const QualType ResultEltTy = VD->getElementType();
11980 UnaryOperatorKind Op = E->getOpcode();
11981
11982 APValue SubExprValue;
11983 if (!Evaluate(SubExprValue, Info, SubExpr))
11984 return false;
11985
11986 // FIXME: This vector evaluator someday needs to be changed to be LValue
11987 // aware/keep LValue information around, rather than dealing with just vector
11988 // types directly. Until then, we cannot handle cases where the operand to
11989 // these unary operators is an LValue. The only case I've been able to see
11990 // cause this is operator++ assigning to a member expression (only valid in
11991 // altivec compilations) in C mode, so this shouldn't limit us too much.
11992 if (SubExprValue.isLValue())
11993 return false;
11994
11995 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11996 "Vector length doesn't match type?");
11997
11998 SmallVector<APValue, 4> ResultElements;
11999 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12000 std::optional<APValue> Elt = handleVectorUnaryOperator(
12001 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12002 if (!Elt)
12003 return false;
12004 ResultElements.push_back(*Elt);
12005 }
12006 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12007}
12008
12009static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12010 const Expr *E, QualType SourceTy,
12011 QualType DestTy, APValue const &Original,
12012 APValue &Result) {
12013 if (SourceTy->isIntegerType()) {
12014 if (DestTy->isRealFloatingType()) {
12015 Result = APValue(APFloat(0.0));
12016 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12017 DestTy, Result.getFloat());
12018 }
12019 if (DestTy->isIntegerType()) {
12020 Result = APValue(
12021 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12022 return true;
12023 }
12024 } else if (SourceTy->isRealFloatingType()) {
12025 if (DestTy->isRealFloatingType()) {
12026 Result = Original;
12027 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12028 Result.getFloat());
12029 }
12030 if (DestTy->isIntegerType()) {
12031 Result = APValue(APSInt());
12032 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12033 DestTy, Result.getInt());
12034 }
12035 }
12036
12037 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12038 << SourceTy << DestTy;
12039 return false;
12040}
12041
12042static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12043 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12044 APValue LHS, RHS;
12045 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12046 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12047 return false;
12048
12049 unsigned LHSVecLen = LHS.getVectorLength();
12050 unsigned RHSVecLen = RHS.getVectorLength();
12051
12052 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12053 "pack builtin LHSVecLen must equal to RHSVecLen");
12054
12055 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12056 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12057
12058 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12059 QualType DstElemTy = DstVT->getElementType();
12060 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12061
12062 const unsigned SrcPerLane = 128 / SrcBits;
12063 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12064
12066 Out.reserve(LHSVecLen + RHSVecLen);
12067
12068 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12069 unsigned base = Lane * SrcPerLane;
12070 for (unsigned I = 0; I != SrcPerLane; ++I)
12071 Out.emplace_back(APValue(
12072 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12073 for (unsigned I = 0; I != SrcPerLane; ++I)
12074 Out.emplace_back(APValue(
12075 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12076 }
12077
12078 Result = APValue(Out.data(), Out.size());
12079 return true;
12080}
12081
12083 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12084 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12085 GetSourceIndex) {
12086
12087 const auto *VT = Call->getType()->getAs<VectorType>();
12088 if (!VT)
12089 return false;
12090
12091 unsigned ShuffleMask = 0;
12092 APValue A, MaskVector, B;
12093 bool IsVectorMask = false;
12094 bool IsSingleOperand = (Call->getNumArgs() == 2);
12095
12096 if (IsSingleOperand) {
12097 QualType MaskType = Call->getArg(1)->getType();
12098 if (MaskType->isVectorType()) {
12099 IsVectorMask = true;
12100 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12101 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12102 return false;
12103 B = A;
12104 } else if (MaskType->isIntegerType()) {
12105 APSInt MaskImm;
12106 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12107 return false;
12108 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12109 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12110 return false;
12111 B = A;
12112 } else {
12113 return false;
12114 }
12115 } else {
12116 QualType Arg2Type = Call->getArg(2)->getType();
12117 if (Arg2Type->isVectorType()) {
12118 IsVectorMask = true;
12119 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12120 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12121 !EvaluateAsRValue(Info, Call->getArg(2), B))
12122 return false;
12123 } else if (Arg2Type->isIntegerType()) {
12124 APSInt MaskImm;
12125 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12126 return false;
12127 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12128 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12129 !EvaluateAsRValue(Info, Call->getArg(1), B))
12130 return false;
12131 } else {
12132 return false;
12133 }
12134 }
12135
12136 unsigned NumElts = VT->getNumElements();
12137 SmallVector<APValue, 64> ResultElements;
12138 ResultElements.reserve(NumElts);
12139
12140 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12141 if (IsVectorMask) {
12142 ShuffleMask = static_cast<unsigned>(
12143 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12144 }
12145 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12146
12147 if (SrcIdx < 0) {
12148 // Zero out this element
12149 QualType ElemTy = VT->getElementType();
12150 if (ElemTy->isRealFloatingType()) {
12151 ResultElements.push_back(
12152 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12153 } else if (ElemTy->isIntegerType()) {
12154 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12155 ResultElements.push_back(APValue(Zero));
12156 } else {
12157 // Other types of fallback logic
12158 ResultElements.push_back(APValue());
12159 }
12160 } else {
12161 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12162 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12163 }
12164 }
12165
12166 Out = APValue(ResultElements.data(), ResultElements.size());
12167 return true;
12168}
12169static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12170 APFloat OrigVal, APValue &Result) {
12171
12172 if (OrigVal.isInfinity()) {
12173 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12174 return false;
12175 }
12176 if (OrigVal.isNaN()) {
12177 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12178 return false;
12179 }
12180
12181 APFloat Val = OrigVal;
12182 bool LosesInfo = false;
12183 APFloat::opStatus Status = Val.convert(
12184 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12185
12186 if (LosesInfo || Val.isDenormal()) {
12187 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12188 return false;
12189 }
12190
12191 if (Status != APFloat::opOK) {
12192 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12193 return false;
12194 }
12195
12196 Result = APValue(Val);
12197 return true;
12198}
12200 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12201 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12202 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12203
12204 APValue Source, Count;
12205 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12206 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12207 return false;
12208
12209 assert(Call->getNumArgs() == 2);
12210
12211 QualType SourceTy = Call->getArg(0)->getType();
12212 assert(SourceTy->isVectorType() &&
12213 Call->getArg(1)->getType()->isVectorType());
12214
12215 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12216 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12217 unsigned DestLen = Source.getVectorLength();
12218 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12219 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12220 unsigned NumBitsInQWord = 64;
12221 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12223 Result.reserve(DestLen);
12224
12225 uint64_t CountLQWord = 0;
12226 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12227 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12228 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12229 }
12230
12231 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12232 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12233 if (CountLQWord < DestEltWidth) {
12234 Result.push_back(
12235 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12236 } else {
12237 Result.push_back(
12238 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12239 }
12240 }
12241 Out = APValue(Result.data(), Result.size());
12242 return true;
12243}
12244
12245bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12246 if (!IsConstantEvaluatedBuiltinCall(E))
12247 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12248
12249 auto EvaluateBinOpExpr =
12250 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12251 APValue SourceLHS, SourceRHS;
12252 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12253 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12254 return false;
12255
12256 auto *DestTy = E->getType()->castAs<VectorType>();
12257 QualType DestEltTy = DestTy->getElementType();
12258 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12259 unsigned SourceLen = SourceLHS.getVectorLength();
12260 SmallVector<APValue, 4> ResultElements;
12261 ResultElements.reserve(SourceLen);
12262
12263 if (SourceRHS.isInt()) {
12264 const APSInt &RHS = SourceRHS.getInt();
12265 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12266 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12267 ResultElements.push_back(
12268 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12269 }
12270 } else {
12271 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12272 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12273 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12274 ResultElements.push_back(
12275 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12276 }
12277 }
12278 return Success(APValue(ResultElements.data(), SourceLen), E);
12279 };
12280
12281 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12282 APSInt Mask;
12283 APValue AVal, WVal;
12284 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12285 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12286 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12287 return false;
12288
12289 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12291 Res.reserve(Len);
12292 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12293 for (unsigned I = 1; I < Len; ++I)
12294 Res.push_back(WVal.getVectorElt(I));
12295 APValue V(Res.data(), Res.size());
12296 return Success(V, E);
12297 };
12298
12299 switch (E->getBuiltinCallee()) {
12300 default:
12301 return false;
12302 case Builtin::BI__builtin_elementwise_popcount:
12303 case Builtin::BI__builtin_elementwise_bitreverse: {
12304 APValue Source;
12305 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12306 return false;
12307
12308 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12309 unsigned SourceLen = Source.getVectorLength();
12310 SmallVector<APValue, 4> ResultElements;
12311 ResultElements.reserve(SourceLen);
12312
12313 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12314 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12315 switch (E->getBuiltinCallee()) {
12316 case Builtin::BI__builtin_elementwise_popcount:
12317 ResultElements.push_back(APValue(
12318 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12319 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12320 break;
12321 case Builtin::BI__builtin_elementwise_bitreverse:
12322 ResultElements.push_back(
12323 APValue(APSInt(Elt.reverseBits(),
12324 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12325 break;
12326 }
12327 }
12328
12329 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12330 }
12331 case Builtin::BI__builtin_elementwise_abs: {
12332 APValue Source;
12333 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12334 return false;
12335
12336 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12337 unsigned SourceLen = Source.getVectorLength();
12338 SmallVector<APValue, 4> ResultElements;
12339 ResultElements.reserve(SourceLen);
12340
12341 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12342 APValue CurrentEle = Source.getVectorElt(EltNum);
12343 APValue Val = DestEltTy->isFloatingType()
12344 ? APValue(llvm::abs(CurrentEle.getFloat()))
12345 : APValue(APSInt(
12346 CurrentEle.getInt().abs(),
12347 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12348 ResultElements.push_back(Val);
12349 }
12350
12351 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12352 }
12353
12354 case Builtin::BI__builtin_elementwise_add_sat:
12355 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12356 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12357 });
12358
12359 case Builtin::BI__builtin_elementwise_sub_sat:
12360 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12361 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12362 });
12363
12364 case X86::BI__builtin_ia32_extract128i256:
12365 case X86::BI__builtin_ia32_vextractf128_pd256:
12366 case X86::BI__builtin_ia32_vextractf128_ps256:
12367 case X86::BI__builtin_ia32_vextractf128_si256: {
12368 APValue SourceVec, SourceImm;
12369 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12370 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12371 return false;
12372
12373 if (!SourceVec.isVector())
12374 return false;
12375
12376 const auto *RetVT = E->getType()->castAs<VectorType>();
12377 unsigned RetLen = RetVT->getNumElements();
12378 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12379
12380 SmallVector<APValue, 32> ResultElements;
12381 ResultElements.reserve(RetLen);
12382
12383 for (unsigned I = 0; I < RetLen; I++)
12384 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12385
12386 return Success(APValue(ResultElements.data(), RetLen), E);
12387 }
12388
12389 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12390 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12391 case X86::BI__builtin_ia32_extracti32x4_mask:
12392 case X86::BI__builtin_ia32_extractf32x4_mask:
12393 case X86::BI__builtin_ia32_extracti32x8_mask:
12394 case X86::BI__builtin_ia32_extractf32x8_mask:
12395 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12396 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12397 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12398 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12399 case X86::BI__builtin_ia32_extracti64x4_mask:
12400 case X86::BI__builtin_ia32_extractf64x4_mask: {
12401 APValue SourceVec, MergeVec;
12402 APSInt Imm, MaskImm;
12403
12404 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12405 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12406 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12407 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12408 return false;
12409
12410 const auto *RetVT = E->getType()->castAs<VectorType>();
12411 unsigned RetLen = RetVT->getNumElements();
12412
12413 if (!SourceVec.isVector() || !MergeVec.isVector())
12414 return false;
12415 unsigned SrcLen = SourceVec.getVectorLength();
12416 unsigned Lanes = SrcLen / RetLen;
12417 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12418 unsigned Base = Lane * RetLen;
12419
12420 SmallVector<APValue, 32> ResultElements;
12421 ResultElements.reserve(RetLen);
12422 for (unsigned I = 0; I < RetLen; ++I) {
12423 if (MaskImm[I])
12424 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12425 else
12426 ResultElements.push_back(MergeVec.getVectorElt(I));
12427 }
12428 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12429 }
12430
12431 case clang::X86::BI__builtin_ia32_pavgb128:
12432 case clang::X86::BI__builtin_ia32_pavgw128:
12433 case clang::X86::BI__builtin_ia32_pavgb256:
12434 case clang::X86::BI__builtin_ia32_pavgw256:
12435 case clang::X86::BI__builtin_ia32_pavgb512:
12436 case clang::X86::BI__builtin_ia32_pavgw512:
12437 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12438
12439 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12440 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12441 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12442 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12443 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12444 .extractBits(16, 1);
12445 });
12446
12447 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12448 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12449 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12450 case clang::X86::BI__builtin_ia32_pmaddwd128:
12451 case clang::X86::BI__builtin_ia32_pmaddwd256:
12452 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12453 APValue SourceLHS, SourceRHS;
12454 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12455 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12456 return false;
12457
12458 auto *DestTy = E->getType()->castAs<VectorType>();
12459 QualType DestEltTy = DestTy->getElementType();
12460 unsigned SourceLen = SourceLHS.getVectorLength();
12461 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12462 SmallVector<APValue, 4> ResultElements;
12463 ResultElements.reserve(SourceLen / 2);
12464
12465 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12466 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12467 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12468 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12469 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12470 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12471
12472 switch (E->getBuiltinCallee()) {
12473 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12474 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12475 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12476 ResultElements.push_back(APValue(
12477 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12478 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12479 DestUnsigned)));
12480 break;
12481 case clang::X86::BI__builtin_ia32_pmaddwd128:
12482 case clang::X86::BI__builtin_ia32_pmaddwd256:
12483 case clang::X86::BI__builtin_ia32_pmaddwd512:
12484 ResultElements.push_back(
12485 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12486 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12487 DestUnsigned)));
12488 break;
12489 }
12490 }
12491
12492 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12493 }
12494
12495 case clang::X86::BI__builtin_ia32_pmulhuw128:
12496 case clang::X86::BI__builtin_ia32_pmulhuw256:
12497 case clang::X86::BI__builtin_ia32_pmulhuw512:
12498 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12499
12500 case clang::X86::BI__builtin_ia32_pmulhw128:
12501 case clang::X86::BI__builtin_ia32_pmulhw256:
12502 case clang::X86::BI__builtin_ia32_pmulhw512:
12503 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12504
12505 case clang::X86::BI__builtin_ia32_psllv2di:
12506 case clang::X86::BI__builtin_ia32_psllv4di:
12507 case clang::X86::BI__builtin_ia32_psllv4si:
12508 case clang::X86::BI__builtin_ia32_psllv8di:
12509 case clang::X86::BI__builtin_ia32_psllv8hi:
12510 case clang::X86::BI__builtin_ia32_psllv8si:
12511 case clang::X86::BI__builtin_ia32_psllv16hi:
12512 case clang::X86::BI__builtin_ia32_psllv16si:
12513 case clang::X86::BI__builtin_ia32_psllv32hi:
12514 case clang::X86::BI__builtin_ia32_psllwi128:
12515 case clang::X86::BI__builtin_ia32_pslldi128:
12516 case clang::X86::BI__builtin_ia32_psllqi128:
12517 case clang::X86::BI__builtin_ia32_psllwi256:
12518 case clang::X86::BI__builtin_ia32_pslldi256:
12519 case clang::X86::BI__builtin_ia32_psllqi256:
12520 case clang::X86::BI__builtin_ia32_psllwi512:
12521 case clang::X86::BI__builtin_ia32_pslldi512:
12522 case clang::X86::BI__builtin_ia32_psllqi512:
12523 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12524 if (RHS.uge(LHS.getBitWidth())) {
12525 return APInt::getZero(LHS.getBitWidth());
12526 }
12527 return LHS.shl(RHS.getZExtValue());
12528 });
12529
12530 case clang::X86::BI__builtin_ia32_psrav4si:
12531 case clang::X86::BI__builtin_ia32_psrav8di:
12532 case clang::X86::BI__builtin_ia32_psrav8hi:
12533 case clang::X86::BI__builtin_ia32_psrav8si:
12534 case clang::X86::BI__builtin_ia32_psrav16hi:
12535 case clang::X86::BI__builtin_ia32_psrav16si:
12536 case clang::X86::BI__builtin_ia32_psrav32hi:
12537 case clang::X86::BI__builtin_ia32_psravq128:
12538 case clang::X86::BI__builtin_ia32_psravq256:
12539 case clang::X86::BI__builtin_ia32_psrawi128:
12540 case clang::X86::BI__builtin_ia32_psradi128:
12541 case clang::X86::BI__builtin_ia32_psraqi128:
12542 case clang::X86::BI__builtin_ia32_psrawi256:
12543 case clang::X86::BI__builtin_ia32_psradi256:
12544 case clang::X86::BI__builtin_ia32_psraqi256:
12545 case clang::X86::BI__builtin_ia32_psrawi512:
12546 case clang::X86::BI__builtin_ia32_psradi512:
12547 case clang::X86::BI__builtin_ia32_psraqi512:
12548 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12549 if (RHS.uge(LHS.getBitWidth())) {
12550 return LHS.ashr(LHS.getBitWidth() - 1);
12551 }
12552 return LHS.ashr(RHS.getZExtValue());
12553 });
12554
12555 case clang::X86::BI__builtin_ia32_psrlv2di:
12556 case clang::X86::BI__builtin_ia32_psrlv4di:
12557 case clang::X86::BI__builtin_ia32_psrlv4si:
12558 case clang::X86::BI__builtin_ia32_psrlv8di:
12559 case clang::X86::BI__builtin_ia32_psrlv8hi:
12560 case clang::X86::BI__builtin_ia32_psrlv8si:
12561 case clang::X86::BI__builtin_ia32_psrlv16hi:
12562 case clang::X86::BI__builtin_ia32_psrlv16si:
12563 case clang::X86::BI__builtin_ia32_psrlv32hi:
12564 case clang::X86::BI__builtin_ia32_psrlwi128:
12565 case clang::X86::BI__builtin_ia32_psrldi128:
12566 case clang::X86::BI__builtin_ia32_psrlqi128:
12567 case clang::X86::BI__builtin_ia32_psrlwi256:
12568 case clang::X86::BI__builtin_ia32_psrldi256:
12569 case clang::X86::BI__builtin_ia32_psrlqi256:
12570 case clang::X86::BI__builtin_ia32_psrlwi512:
12571 case clang::X86::BI__builtin_ia32_psrldi512:
12572 case clang::X86::BI__builtin_ia32_psrlqi512:
12573 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12574 if (RHS.uge(LHS.getBitWidth())) {
12575 return APInt::getZero(LHS.getBitWidth());
12576 }
12577 return LHS.lshr(RHS.getZExtValue());
12578 });
12579 case X86::BI__builtin_ia32_packsswb128:
12580 case X86::BI__builtin_ia32_packsswb256:
12581 case X86::BI__builtin_ia32_packsswb512:
12582 case X86::BI__builtin_ia32_packssdw128:
12583 case X86::BI__builtin_ia32_packssdw256:
12584 case X86::BI__builtin_ia32_packssdw512:
12585 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12586 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12587 });
12588 case X86::BI__builtin_ia32_packusdw128:
12589 case X86::BI__builtin_ia32_packusdw256:
12590 case X86::BI__builtin_ia32_packusdw512:
12591 case X86::BI__builtin_ia32_packuswb128:
12592 case X86::BI__builtin_ia32_packuswb256:
12593 case X86::BI__builtin_ia32_packuswb512:
12594 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12595 unsigned DstBits = Src.getBitWidth() / 2;
12596 if (Src.isNegative())
12597 return APInt::getZero(DstBits);
12598 if (Src.isIntN(DstBits))
12599 return APInt((Src).trunc(DstBits));
12600 return APInt::getAllOnes(DstBits);
12601 });
12602 case clang::X86::BI__builtin_ia32_selectss_128:
12603 return EvalSelectScalar(4);
12604 case clang::X86::BI__builtin_ia32_selectsd_128:
12605 return EvalSelectScalar(2);
12606 case clang::X86::BI__builtin_ia32_selectsh_128:
12607 case clang::X86::BI__builtin_ia32_selectsbf_128:
12608 return EvalSelectScalar(8);
12609 case clang::X86::BI__builtin_ia32_pmuldq128:
12610 case clang::X86::BI__builtin_ia32_pmuldq256:
12611 case clang::X86::BI__builtin_ia32_pmuldq512:
12612 case clang::X86::BI__builtin_ia32_pmuludq128:
12613 case clang::X86::BI__builtin_ia32_pmuludq256:
12614 case clang::X86::BI__builtin_ia32_pmuludq512: {
12615 APValue SourceLHS, SourceRHS;
12616 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12617 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12618 return false;
12619
12620 unsigned SourceLen = SourceLHS.getVectorLength();
12621 SmallVector<APValue, 4> ResultElements;
12622 ResultElements.reserve(SourceLen / 2);
12623
12624 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12625 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12626 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12627
12628 switch (E->getBuiltinCallee()) {
12629 case clang::X86::BI__builtin_ia32_pmuludq128:
12630 case clang::X86::BI__builtin_ia32_pmuludq256:
12631 case clang::X86::BI__builtin_ia32_pmuludq512:
12632 ResultElements.push_back(
12633 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12634 break;
12635 case clang::X86::BI__builtin_ia32_pmuldq128:
12636 case clang::X86::BI__builtin_ia32_pmuldq256:
12637 case clang::X86::BI__builtin_ia32_pmuldq512:
12638 ResultElements.push_back(
12639 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12640 break;
12641 }
12642 }
12643
12644 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12645 }
12646
12647 case X86::BI__builtin_ia32_vpmadd52luq128:
12648 case X86::BI__builtin_ia32_vpmadd52luq256:
12649 case X86::BI__builtin_ia32_vpmadd52luq512: {
12650 APValue A, B, C;
12651 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12652 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12653 !EvaluateAsRValue(Info, E->getArg(2), C))
12654 return false;
12655
12656 unsigned ALen = A.getVectorLength();
12657 SmallVector<APValue, 4> ResultElements;
12658 ResultElements.reserve(ALen);
12659
12660 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12661 APInt AElt = A.getVectorElt(EltNum).getInt();
12662 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12663 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12664 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12665 ResultElements.push_back(APValue(ResElt));
12666 }
12667
12668 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12669 }
12670 case X86::BI__builtin_ia32_vpmadd52huq128:
12671 case X86::BI__builtin_ia32_vpmadd52huq256:
12672 case X86::BI__builtin_ia32_vpmadd52huq512: {
12673 APValue A, B, C;
12674 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12675 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12676 !EvaluateAsRValue(Info, E->getArg(2), C))
12677 return false;
12678
12679 unsigned ALen = A.getVectorLength();
12680 SmallVector<APValue, 4> ResultElements;
12681 ResultElements.reserve(ALen);
12682
12683 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12684 APInt AElt = A.getVectorElt(EltNum).getInt();
12685 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12686 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12687 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12688 ResultElements.push_back(APValue(ResElt));
12689 }
12690
12691 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12692 }
12693
12694 case clang::X86::BI__builtin_ia32_vprotbi:
12695 case clang::X86::BI__builtin_ia32_vprotdi:
12696 case clang::X86::BI__builtin_ia32_vprotqi:
12697 case clang::X86::BI__builtin_ia32_vprotwi:
12698 case clang::X86::BI__builtin_ia32_prold128:
12699 case clang::X86::BI__builtin_ia32_prold256:
12700 case clang::X86::BI__builtin_ia32_prold512:
12701 case clang::X86::BI__builtin_ia32_prolq128:
12702 case clang::X86::BI__builtin_ia32_prolq256:
12703 case clang::X86::BI__builtin_ia32_prolq512:
12704 return EvaluateBinOpExpr(
12705 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12706
12707 case clang::X86::BI__builtin_ia32_prord128:
12708 case clang::X86::BI__builtin_ia32_prord256:
12709 case clang::X86::BI__builtin_ia32_prord512:
12710 case clang::X86::BI__builtin_ia32_prorq128:
12711 case clang::X86::BI__builtin_ia32_prorq256:
12712 case clang::X86::BI__builtin_ia32_prorq512:
12713 return EvaluateBinOpExpr(
12714 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12715
12716 case Builtin::BI__builtin_elementwise_max:
12717 case Builtin::BI__builtin_elementwise_min: {
12718 APValue SourceLHS, SourceRHS;
12719 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12720 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12721 return false;
12722
12723 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12724
12725 if (!DestEltTy->isIntegerType())
12726 return false;
12727
12728 unsigned SourceLen = SourceLHS.getVectorLength();
12729 SmallVector<APValue, 4> ResultElements;
12730 ResultElements.reserve(SourceLen);
12731
12732 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12733 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12734 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12735 switch (E->getBuiltinCallee()) {
12736 case Builtin::BI__builtin_elementwise_max:
12737 ResultElements.push_back(
12738 APValue(APSInt(std::max(LHS, RHS),
12739 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12740 break;
12741 case Builtin::BI__builtin_elementwise_min:
12742 ResultElements.push_back(
12743 APValue(APSInt(std::min(LHS, RHS),
12744 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12745 break;
12746 }
12747 }
12748
12749 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12750 }
12751 case X86::BI__builtin_ia32_vpshldd128:
12752 case X86::BI__builtin_ia32_vpshldd256:
12753 case X86::BI__builtin_ia32_vpshldd512:
12754 case X86::BI__builtin_ia32_vpshldq128:
12755 case X86::BI__builtin_ia32_vpshldq256:
12756 case X86::BI__builtin_ia32_vpshldq512:
12757 case X86::BI__builtin_ia32_vpshldw128:
12758 case X86::BI__builtin_ia32_vpshldw256:
12759 case X86::BI__builtin_ia32_vpshldw512: {
12760 APValue SourceHi, SourceLo, SourceAmt;
12761 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12762 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12763 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12764 return false;
12765
12766 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12767 unsigned SourceLen = SourceHi.getVectorLength();
12768 SmallVector<APValue, 32> ResultElements;
12769 ResultElements.reserve(SourceLen);
12770
12771 APInt Amt = SourceAmt.getInt();
12772 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12773 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12774 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12775 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12776 ResultElements.push_back(
12778 }
12779
12780 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12781 }
12782 case X86::BI__builtin_ia32_vpshrdd128:
12783 case X86::BI__builtin_ia32_vpshrdd256:
12784 case X86::BI__builtin_ia32_vpshrdd512:
12785 case X86::BI__builtin_ia32_vpshrdq128:
12786 case X86::BI__builtin_ia32_vpshrdq256:
12787 case X86::BI__builtin_ia32_vpshrdq512:
12788 case X86::BI__builtin_ia32_vpshrdw128:
12789 case X86::BI__builtin_ia32_vpshrdw256:
12790 case X86::BI__builtin_ia32_vpshrdw512: {
12791 // NOTE: Reversed Hi/Lo operands.
12792 APValue SourceHi, SourceLo, SourceAmt;
12793 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12794 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12795 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12796 return false;
12797
12798 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12799 unsigned SourceLen = SourceHi.getVectorLength();
12800 SmallVector<APValue, 32> ResultElements;
12801 ResultElements.reserve(SourceLen);
12802
12803 APInt Amt = SourceAmt.getInt();
12804 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12805 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12806 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12807 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12808 ResultElements.push_back(
12810 }
12811
12812 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12813 }
12814 case X86::BI__builtin_ia32_vpconflictsi_128:
12815 case X86::BI__builtin_ia32_vpconflictsi_256:
12816 case X86::BI__builtin_ia32_vpconflictsi_512:
12817 case X86::BI__builtin_ia32_vpconflictdi_128:
12818 case X86::BI__builtin_ia32_vpconflictdi_256:
12819 case X86::BI__builtin_ia32_vpconflictdi_512: {
12820 APValue Source;
12821
12822 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12823 return false;
12824
12825 unsigned SourceLen = Source.getVectorLength();
12826 SmallVector<APValue, 32> ResultElements;
12827 ResultElements.reserve(SourceLen);
12828
12829 const auto *VecT = E->getType()->castAs<VectorType>();
12830 bool DestUnsigned =
12831 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12832
12833 for (unsigned I = 0; I != SourceLen; ++I) {
12834 const APValue &EltI = Source.getVectorElt(I);
12835
12836 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12837 for (unsigned J = 0; J != I; ++J) {
12838 const APValue &EltJ = Source.getVectorElt(J);
12839 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12840 }
12841 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12842 }
12843 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12844 }
12845 case X86::BI__builtin_ia32_blendpd:
12846 case X86::BI__builtin_ia32_blendpd256:
12847 case X86::BI__builtin_ia32_blendps:
12848 case X86::BI__builtin_ia32_blendps256:
12849 case X86::BI__builtin_ia32_pblendw128:
12850 case X86::BI__builtin_ia32_pblendw256:
12851 case X86::BI__builtin_ia32_pblendd128:
12852 case X86::BI__builtin_ia32_pblendd256: {
12853 APValue SourceF, SourceT, SourceC;
12854 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12855 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12856 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12857 return false;
12858
12859 const APInt &C = SourceC.getInt();
12860 unsigned SourceLen = SourceF.getVectorLength();
12861 SmallVector<APValue, 32> ResultElements;
12862 ResultElements.reserve(SourceLen);
12863 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
12864 const APValue &F = SourceF.getVectorElt(EltNum);
12865 const APValue &T = SourceT.getVectorElt(EltNum);
12866 ResultElements.push_back(C[EltNum % 8] ? T : F);
12867 }
12868
12869 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12870 }
12871
12872 case X86::BI__builtin_ia32_psignb128:
12873 case X86::BI__builtin_ia32_psignb256:
12874 case X86::BI__builtin_ia32_psignw128:
12875 case X86::BI__builtin_ia32_psignw256:
12876 case X86::BI__builtin_ia32_psignd128:
12877 case X86::BI__builtin_ia32_psignd256:
12878 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
12879 if (BElem.isZero())
12880 return APInt::getZero(AElem.getBitWidth());
12881 if (BElem.isNegative())
12882 return -AElem;
12883 return AElem;
12884 });
12885
12886 case X86::BI__builtin_ia32_blendvpd:
12887 case X86::BI__builtin_ia32_blendvpd256:
12888 case X86::BI__builtin_ia32_blendvps:
12889 case X86::BI__builtin_ia32_blendvps256:
12890 case X86::BI__builtin_ia32_pblendvb128:
12891 case X86::BI__builtin_ia32_pblendvb256: {
12892 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
12893 APValue SourceF, SourceT, SourceC;
12894 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
12895 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
12896 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12897 return false;
12898
12899 unsigned SourceLen = SourceF.getVectorLength();
12900 SmallVector<APValue, 32> ResultElements;
12901 ResultElements.reserve(SourceLen);
12902
12903 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12904 const APValue &F = SourceF.getVectorElt(EltNum);
12905 const APValue &T = SourceT.getVectorElt(EltNum);
12906 const APValue &C = SourceC.getVectorElt(EltNum);
12907 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
12908 ResultElements.push_back(M.isNegative() ? T : F);
12909 }
12910
12911 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12912 }
12913 case X86::BI__builtin_ia32_selectb_128:
12914 case X86::BI__builtin_ia32_selectb_256:
12915 case X86::BI__builtin_ia32_selectb_512:
12916 case X86::BI__builtin_ia32_selectw_128:
12917 case X86::BI__builtin_ia32_selectw_256:
12918 case X86::BI__builtin_ia32_selectw_512:
12919 case X86::BI__builtin_ia32_selectd_128:
12920 case X86::BI__builtin_ia32_selectd_256:
12921 case X86::BI__builtin_ia32_selectd_512:
12922 case X86::BI__builtin_ia32_selectq_128:
12923 case X86::BI__builtin_ia32_selectq_256:
12924 case X86::BI__builtin_ia32_selectq_512:
12925 case X86::BI__builtin_ia32_selectph_128:
12926 case X86::BI__builtin_ia32_selectph_256:
12927 case X86::BI__builtin_ia32_selectph_512:
12928 case X86::BI__builtin_ia32_selectpbf_128:
12929 case X86::BI__builtin_ia32_selectpbf_256:
12930 case X86::BI__builtin_ia32_selectpbf_512:
12931 case X86::BI__builtin_ia32_selectps_128:
12932 case X86::BI__builtin_ia32_selectps_256:
12933 case X86::BI__builtin_ia32_selectps_512:
12934 case X86::BI__builtin_ia32_selectpd_128:
12935 case X86::BI__builtin_ia32_selectpd_256:
12936 case X86::BI__builtin_ia32_selectpd_512: {
12937 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
12938 APValue SourceMask, SourceLHS, SourceRHS;
12939 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
12940 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
12941 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
12942 return false;
12943
12944 APSInt Mask = SourceMask.getInt();
12945 unsigned SourceLen = SourceLHS.getVectorLength();
12946 SmallVector<APValue, 4> ResultElements;
12947 ResultElements.reserve(SourceLen);
12948
12949 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12950 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
12951 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
12952 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
12953 }
12954
12955 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12956 }
12957
12958 case X86::BI__builtin_ia32_cvtsd2ss: {
12959 APValue VecA, VecB;
12960 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12961 !EvaluateAsRValue(Info, E->getArg(1), VecB))
12962 return false;
12963
12964 SmallVector<APValue, 4> Elements;
12965
12966 APValue ResultVal;
12967 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
12968 ResultVal))
12969 return false;
12970
12971 Elements.push_back(ResultVal);
12972
12973 unsigned NumEltsA = VecA.getVectorLength();
12974 for (unsigned I = 1; I < NumEltsA; ++I) {
12975 Elements.push_back(VecA.getVectorElt(I));
12976 }
12977
12978 return Success(Elements, E);
12979 }
12980 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
12981 APValue VecA, VecB, VecSrc, MaskValue;
12982
12983 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12984 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12985 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12986 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
12987 return false;
12988
12989 unsigned Mask = MaskValue.getInt().getZExtValue();
12990 SmallVector<APValue, 4> Elements;
12991
12992 if (Mask & 1) {
12993 APValue ResultVal;
12994 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
12995 ResultVal))
12996 return false;
12997 Elements.push_back(ResultVal);
12998 } else {
12999 Elements.push_back(VecSrc.getVectorElt(0));
13000 }
13001
13002 unsigned NumEltsA = VecA.getVectorLength();
13003 for (unsigned I = 1; I < NumEltsA; ++I) {
13004 Elements.push_back(VecA.getVectorElt(I));
13005 }
13006
13007 return Success(Elements, E);
13008 }
13009 case X86::BI__builtin_ia32_cvtpd2ps:
13010 case X86::BI__builtin_ia32_cvtpd2ps256:
13011 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13012 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13013
13014 const auto BuiltinID = E->getBuiltinCallee();
13015 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13016 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13017
13018 APValue InputValue;
13019 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13020 return false;
13021
13022 APValue MergeValue;
13023 unsigned Mask = 0xFFFFFFFF;
13024 bool NeedsMerge = false;
13025 if (IsMasked) {
13026 APValue MaskValue;
13027 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13028 return false;
13029 Mask = MaskValue.getInt().getZExtValue();
13030 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13031 for (unsigned I = 0; I < NumEltsResult; ++I) {
13032 if (!((Mask >> I) & 1)) {
13033 NeedsMerge = true;
13034 break;
13035 }
13036 }
13037 if (NeedsMerge) {
13038 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13039 return false;
13040 }
13041 }
13042
13043 unsigned NumEltsResult =
13044 E->getType()->getAs<VectorType>()->getNumElements();
13045 unsigned NumEltsInput = InputValue.getVectorLength();
13046 SmallVector<APValue, 8> Elements;
13047 for (unsigned I = 0; I < NumEltsResult; ++I) {
13048 if (IsMasked && !((Mask >> I) & 1)) {
13049 if (!NeedsMerge) {
13050 return false;
13051 }
13052 Elements.push_back(MergeValue.getVectorElt(I));
13053 continue;
13054 }
13055
13056 if (I >= NumEltsInput) {
13057 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13058 continue;
13059 }
13060
13061 APValue ResultVal;
13063 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13064 return false;
13065
13066 Elements.push_back(ResultVal);
13067 }
13068 return Success(Elements, E);
13069 }
13070
13071 case X86::BI__builtin_ia32_shufps:
13072 case X86::BI__builtin_ia32_shufps256:
13073 case X86::BI__builtin_ia32_shufps512: {
13074 APValue R;
13075 if (!evalShuffleGeneric(
13076 Info, E, R,
13077 [](unsigned DstIdx,
13078 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13079 constexpr unsigned LaneBits = 128u;
13080 unsigned NumElemPerLane = LaneBits / 32;
13081 unsigned NumSelectableElems = NumElemPerLane / 2;
13082 unsigned BitsPerElem = 2;
13083 unsigned IndexMask = (1u << BitsPerElem) - 1;
13084 unsigned MaskBits = 8;
13085 unsigned Lane = DstIdx / NumElemPerLane;
13086 unsigned ElemInLane = DstIdx % NumElemPerLane;
13087 unsigned LaneOffset = Lane * NumElemPerLane;
13088 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13089 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13090 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13091 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13092 }))
13093 return false;
13094 return Success(R, E);
13095 }
13096 case X86::BI__builtin_ia32_shufpd:
13097 case X86::BI__builtin_ia32_shufpd256:
13098 case X86::BI__builtin_ia32_shufpd512: {
13099 APValue R;
13100 if (!evalShuffleGeneric(
13101 Info, E, R,
13102 [](unsigned DstIdx,
13103 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13104 constexpr unsigned LaneBits = 128u;
13105 unsigned NumElemPerLane = LaneBits / 64;
13106 unsigned NumSelectableElems = NumElemPerLane / 2;
13107 unsigned BitsPerElem = 1;
13108 unsigned IndexMask = (1u << BitsPerElem) - 1;
13109 unsigned MaskBits = 8;
13110 unsigned Lane = DstIdx / NumElemPerLane;
13111 unsigned ElemInLane = DstIdx % NumElemPerLane;
13112 unsigned LaneOffset = Lane * NumElemPerLane;
13113 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13114 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13115 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13116 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13117 }))
13118 return false;
13119 return Success(R, E);
13120 }
13121 case X86::BI__builtin_ia32_insertps128: {
13122 APValue R;
13123 if (!evalShuffleGeneric(
13124 Info, E, R,
13125 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13126 // Bits [3:0]: zero mask - if bit is set, zero this element
13127 if ((Mask & (1 << DstIdx)) != 0) {
13128 return {0, -1};
13129 }
13130 // Bits [7:6]: select element from source vector Y (0-3)
13131 // Bits [5:4]: select destination position (0-3)
13132 unsigned SrcElem = (Mask >> 6) & 0x3;
13133 unsigned DstElem = (Mask >> 4) & 0x3;
13134 if (DstIdx == DstElem) {
13135 // Insert element from source vector (B) at this position
13136 return {1, static_cast<int>(SrcElem)};
13137 } else {
13138 // Copy from destination vector (A)
13139 return {0, static_cast<int>(DstIdx)};
13140 }
13141 }))
13142 return false;
13143 return Success(R, E);
13144 }
13145 case X86::BI__builtin_ia32_pshufb128:
13146 case X86::BI__builtin_ia32_pshufb256:
13147 case X86::BI__builtin_ia32_pshufb512: {
13148 APValue R;
13149 if (!evalShuffleGeneric(
13150 Info, E, R,
13151 [](unsigned DstIdx,
13152 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13153 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13154 if (Ctlb & 0x80)
13155 return std::make_pair(0, -1);
13156
13157 unsigned LaneBase = (DstIdx / 16) * 16;
13158 unsigned SrcOffset = Ctlb & 0x0F;
13159 unsigned SrcIdx = LaneBase + SrcOffset;
13160 return std::make_pair(0, static_cast<int>(SrcIdx));
13161 }))
13162 return false;
13163 return Success(R, E);
13164 }
13165
13166 case X86::BI__builtin_ia32_pshuflw:
13167 case X86::BI__builtin_ia32_pshuflw256:
13168 case X86::BI__builtin_ia32_pshuflw512: {
13169 APValue R;
13170 if (!evalShuffleGeneric(
13171 Info, E, R,
13172 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13173 constexpr unsigned LaneBits = 128u;
13174 constexpr unsigned ElemBits = 16u;
13175 constexpr unsigned LaneElts = LaneBits / ElemBits;
13176 constexpr unsigned HalfSize = 4;
13177 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13178 unsigned LaneIdx = DstIdx % LaneElts;
13179 if (LaneIdx < HalfSize) {
13180 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13181 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13182 }
13183 return std::make_pair(0, static_cast<int>(DstIdx));
13184 }))
13185 return false;
13186 return Success(R, E);
13187 }
13188
13189 case X86::BI__builtin_ia32_pshufhw:
13190 case X86::BI__builtin_ia32_pshufhw256:
13191 case X86::BI__builtin_ia32_pshufhw512: {
13192 APValue R;
13193 if (!evalShuffleGeneric(
13194 Info, E, R,
13195 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13196 constexpr unsigned LaneBits = 128u;
13197 constexpr unsigned ElemBits = 16u;
13198 constexpr unsigned LaneElts = LaneBits / ElemBits;
13199 constexpr unsigned HalfSize = 4;
13200 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13201 unsigned LaneIdx = DstIdx % LaneElts;
13202 if (LaneIdx >= HalfSize) {
13203 unsigned Rel = LaneIdx - HalfSize;
13204 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13205 return std::make_pair(
13206 0, static_cast<int>(LaneBase + HalfSize + Sel));
13207 }
13208 return std::make_pair(0, static_cast<int>(DstIdx));
13209 }))
13210 return false;
13211 return Success(R, E);
13212 }
13213
13214 case X86::BI__builtin_ia32_pshufd:
13215 case X86::BI__builtin_ia32_pshufd256:
13216 case X86::BI__builtin_ia32_pshufd512:
13217 case X86::BI__builtin_ia32_vpermilps:
13218 case X86::BI__builtin_ia32_vpermilps256:
13219 case X86::BI__builtin_ia32_vpermilps512: {
13220 APValue R;
13221 if (!evalShuffleGeneric(
13222 Info, E, R,
13223 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13224 constexpr unsigned LaneBits = 128u;
13225 constexpr unsigned ElemBits = 32u;
13226 constexpr unsigned LaneElts = LaneBits / ElemBits;
13227 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13228 unsigned LaneIdx = DstIdx % LaneElts;
13229 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13230 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13231 }))
13232 return false;
13233 return Success(R, E);
13234 }
13235
13236 case X86::BI__builtin_ia32_vpermilvarpd:
13237 case X86::BI__builtin_ia32_vpermilvarpd256:
13238 case X86::BI__builtin_ia32_vpermilvarpd512: {
13239 APValue R;
13240 if (!evalShuffleGeneric(
13241 Info, E, R,
13242 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13243 unsigned NumElemPerLane = 2;
13244 unsigned Lane = DstIdx / NumElemPerLane;
13245 unsigned Offset = Mask & 0b10 ? 1 : 0;
13246 return std::make_pair(
13247 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13248 }))
13249 return false;
13250 return Success(R, E);
13251 }
13252
13253 case X86::BI__builtin_ia32_vpermilpd:
13254 case X86::BI__builtin_ia32_vpermilpd256:
13255 case X86::BI__builtin_ia32_vpermilpd512: {
13256 APValue R;
13257 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13258 unsigned NumElemPerLane = 2;
13259 unsigned BitsPerElem = 1;
13260 unsigned MaskBits = 8;
13261 unsigned IndexMask = 0x1;
13262 unsigned Lane = DstIdx / NumElemPerLane;
13263 unsigned LaneOffset = Lane * NumElemPerLane;
13264 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13265 unsigned Index = (Control >> BitIndex) & IndexMask;
13266 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13267 }))
13268 return false;
13269 return Success(R, E);
13270 }
13271
13272 case X86::BI__builtin_ia32_permdf256:
13273 case X86::BI__builtin_ia32_permdi256: {
13274 APValue R;
13275 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13276 // permute4x64 operates on 4 64-bit elements
13277 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13278 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13279 return std::make_pair(0, static_cast<int>(Index));
13280 }))
13281 return false;
13282 return Success(R, E);
13283 }
13284
13285 case X86::BI__builtin_ia32_vpermilvarps:
13286 case X86::BI__builtin_ia32_vpermilvarps256:
13287 case X86::BI__builtin_ia32_vpermilvarps512: {
13288 APValue R;
13289 if (!evalShuffleGeneric(
13290 Info, E, R,
13291 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13292 unsigned NumElemPerLane = 4;
13293 unsigned Lane = DstIdx / NumElemPerLane;
13294 unsigned Offset = Mask & 0b11;
13295 return std::make_pair(
13296 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13297 }))
13298 return false;
13299 return Success(R, E);
13300 }
13301
13302 case X86::BI__builtin_ia32_vpmultishiftqb128:
13303 case X86::BI__builtin_ia32_vpmultishiftqb256:
13304 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13305 assert(E->getNumArgs() == 2);
13306
13307 APValue A, B;
13308 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13309 return false;
13310
13311 assert(A.getVectorLength() == B.getVectorLength());
13312 unsigned NumBytesInQWord = 8;
13313 unsigned NumBitsInByte = 8;
13314 unsigned NumBytes = A.getVectorLength();
13315 unsigned NumQWords = NumBytes / NumBytesInQWord;
13317 Result.reserve(NumBytes);
13318
13319 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13320 APInt BQWord(64, 0);
13321 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13322 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13323 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13324 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13325 }
13326
13327 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13328 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13329 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13330
13331 APInt Byte(8, 0);
13332 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13333 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13334 }
13335 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13336 }
13337 }
13338 return Success(APValue(Result.data(), Result.size()), E);
13339 }
13340
13341 case X86::BI__builtin_ia32_phminposuw128: {
13342 APValue Source;
13343 if (!Evaluate(Source, Info, E->getArg(0)))
13344 return false;
13345 unsigned SourceLen = Source.getVectorLength();
13346 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13347 QualType ElemQT = VT->getElementType();
13348 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13349
13350 APInt MinIndex(ElemBitWidth, 0);
13351 APInt MinVal = Source.getVectorElt(0).getInt();
13352 for (unsigned I = 1; I != SourceLen; ++I) {
13353 APInt Val = Source.getVectorElt(I).getInt();
13354 if (MinVal.ugt(Val)) {
13355 MinVal = Val;
13356 MinIndex = I;
13357 }
13358 }
13359
13360 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13361 ->castAs<VectorType>()
13362 ->getElementType()
13363 ->isUnsignedIntegerOrEnumerationType();
13364
13366 Result.reserve(SourceLen);
13367 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13368 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13369 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13370 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13371 }
13372 return Success(APValue(Result.data(), Result.size()), E);
13373 }
13374
13375 case X86::BI__builtin_ia32_psraq128:
13376 case X86::BI__builtin_ia32_psraq256:
13377 case X86::BI__builtin_ia32_psraq512:
13378 case X86::BI__builtin_ia32_psrad128:
13379 case X86::BI__builtin_ia32_psrad256:
13380 case X86::BI__builtin_ia32_psrad512:
13381 case X86::BI__builtin_ia32_psraw128:
13382 case X86::BI__builtin_ia32_psraw256:
13383 case X86::BI__builtin_ia32_psraw512: {
13384 APValue R;
13385 if (!evalShiftWithCount(
13386 Info, E, R,
13387 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13388 [](const APInt &Elt, unsigned Width) {
13389 return Elt.ashr(Width - 1);
13390 }))
13391 return false;
13392 return Success(R, E);
13393 }
13394
13395 case X86::BI__builtin_ia32_psllq128:
13396 case X86::BI__builtin_ia32_psllq256:
13397 case X86::BI__builtin_ia32_psllq512:
13398 case X86::BI__builtin_ia32_pslld128:
13399 case X86::BI__builtin_ia32_pslld256:
13400 case X86::BI__builtin_ia32_pslld512:
13401 case X86::BI__builtin_ia32_psllw128:
13402 case X86::BI__builtin_ia32_psllw256:
13403 case X86::BI__builtin_ia32_psllw512: {
13404 APValue R;
13405 if (!evalShiftWithCount(
13406 Info, E, R,
13407 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13408 [](const APInt &Elt, unsigned Width) {
13409 return APInt::getZero(Width);
13410 }))
13411 return false;
13412 return Success(R, E);
13413 }
13414
13415 case X86::BI__builtin_ia32_psrlq128:
13416 case X86::BI__builtin_ia32_psrlq256:
13417 case X86::BI__builtin_ia32_psrlq512:
13418 case X86::BI__builtin_ia32_psrld128:
13419 case X86::BI__builtin_ia32_psrld256:
13420 case X86::BI__builtin_ia32_psrld512:
13421 case X86::BI__builtin_ia32_psrlw128:
13422 case X86::BI__builtin_ia32_psrlw256:
13423 case X86::BI__builtin_ia32_psrlw512: {
13424 APValue R;
13425 if (!evalShiftWithCount(
13426 Info, E, R,
13427 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13428 [](const APInt &Elt, unsigned Width) {
13429 return APInt::getZero(Width);
13430 }))
13431 return false;
13432 return Success(R, E);
13433 }
13434
13435 case X86::BI__builtin_ia32_pternlogd128_mask:
13436 case X86::BI__builtin_ia32_pternlogd256_mask:
13437 case X86::BI__builtin_ia32_pternlogd512_mask:
13438 case X86::BI__builtin_ia32_pternlogq128_mask:
13439 case X86::BI__builtin_ia32_pternlogq256_mask:
13440 case X86::BI__builtin_ia32_pternlogq512_mask: {
13441 APValue AValue, BValue, CValue, ImmValue, UValue;
13442 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13443 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13444 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13445 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13446 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13447 return false;
13448
13449 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13450 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13451 APInt Imm = ImmValue.getInt();
13452 APInt U = UValue.getInt();
13453 unsigned ResultLen = AValue.getVectorLength();
13454 SmallVector<APValue, 16> ResultElements;
13455 ResultElements.reserve(ResultLen);
13456
13457 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13458 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13459 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13460 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13461
13462 if (U[EltNum]) {
13463 unsigned BitWidth = ALane.getBitWidth();
13464 APInt ResLane(BitWidth, 0);
13465
13466 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13467 unsigned ABit = ALane[Bit];
13468 unsigned BBit = BLane[Bit];
13469 unsigned CBit = CLane[Bit];
13470
13471 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13472 ResLane.setBitVal(Bit, Imm[Idx]);
13473 }
13474 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13475 } else {
13476 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13477 }
13478 }
13479 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13480 }
13481 case X86::BI__builtin_ia32_pternlogd128_maskz:
13482 case X86::BI__builtin_ia32_pternlogd256_maskz:
13483 case X86::BI__builtin_ia32_pternlogd512_maskz:
13484 case X86::BI__builtin_ia32_pternlogq128_maskz:
13485 case X86::BI__builtin_ia32_pternlogq256_maskz:
13486 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13487 APValue AValue, BValue, CValue, ImmValue, UValue;
13488 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13489 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13490 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13491 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13492 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13493 return false;
13494
13495 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13496 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13497 APInt Imm = ImmValue.getInt();
13498 APInt U = UValue.getInt();
13499 unsigned ResultLen = AValue.getVectorLength();
13500 SmallVector<APValue, 16> ResultElements;
13501 ResultElements.reserve(ResultLen);
13502
13503 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13504 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13505 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13506 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13507
13508 unsigned BitWidth = ALane.getBitWidth();
13509 APInt ResLane(BitWidth, 0);
13510
13511 if (U[EltNum]) {
13512 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13513 unsigned ABit = ALane[Bit];
13514 unsigned BBit = BLane[Bit];
13515 unsigned CBit = CLane[Bit];
13516
13517 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13518 ResLane.setBitVal(Bit, Imm[Idx]);
13519 }
13520 }
13521 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13522 }
13523 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13524 }
13525
13526 case Builtin::BI__builtin_elementwise_clzg:
13527 case Builtin::BI__builtin_elementwise_ctzg: {
13528 APValue SourceLHS;
13529 std::optional<APValue> Fallback;
13530 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13531 return false;
13532 if (E->getNumArgs() > 1) {
13533 APValue FallbackTmp;
13534 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13535 return false;
13536 Fallback = FallbackTmp;
13537 }
13538
13539 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13540 unsigned SourceLen = SourceLHS.getVectorLength();
13541 SmallVector<APValue, 4> ResultElements;
13542 ResultElements.reserve(SourceLen);
13543
13544 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13545 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13546 if (!LHS) {
13547 // Without a fallback, a zero element is undefined
13548 if (!Fallback) {
13549 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13550 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13551 Builtin::BI__builtin_elementwise_ctzg);
13552 return false;
13553 }
13554 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13555 continue;
13556 }
13557 switch (E->getBuiltinCallee()) {
13558 case Builtin::BI__builtin_elementwise_clzg:
13559 ResultElements.push_back(APValue(
13560 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13561 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13562 break;
13563 case Builtin::BI__builtin_elementwise_ctzg:
13564 ResultElements.push_back(APValue(
13565 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13566 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13567 break;
13568 }
13569 }
13570
13571 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13572 }
13573
13574 case Builtin::BI__builtin_elementwise_fma: {
13575 APValue SourceX, SourceY, SourceZ;
13576 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13577 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13578 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13579 return false;
13580
13581 unsigned SourceLen = SourceX.getVectorLength();
13582 SmallVector<APValue> ResultElements;
13583 ResultElements.reserve(SourceLen);
13584 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13585 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13586 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13587 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13588 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13589 APFloat Result(X);
13590 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13591 ResultElements.push_back(APValue(Result));
13592 }
13593 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13594 }
13595
13596 case clang::X86::BI__builtin_ia32_phaddw128:
13597 case clang::X86::BI__builtin_ia32_phaddw256:
13598 case clang::X86::BI__builtin_ia32_phaddd128:
13599 case clang::X86::BI__builtin_ia32_phaddd256:
13600 case clang::X86::BI__builtin_ia32_phaddsw128:
13601 case clang::X86::BI__builtin_ia32_phaddsw256:
13602
13603 case clang::X86::BI__builtin_ia32_phsubw128:
13604 case clang::X86::BI__builtin_ia32_phsubw256:
13605 case clang::X86::BI__builtin_ia32_phsubd128:
13606 case clang::X86::BI__builtin_ia32_phsubd256:
13607 case clang::X86::BI__builtin_ia32_phsubsw128:
13608 case clang::X86::BI__builtin_ia32_phsubsw256: {
13609 APValue SourceLHS, SourceRHS;
13610 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13611 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13612 return false;
13613 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13614 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13615
13616 unsigned NumElts = SourceLHS.getVectorLength();
13617 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13618 unsigned EltsPerLane = 128 / EltBits;
13619 SmallVector<APValue, 4> ResultElements;
13620 ResultElements.reserve(NumElts);
13621
13622 for (unsigned LaneStart = 0; LaneStart != NumElts;
13623 LaneStart += EltsPerLane) {
13624 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13625 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13626 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13627 switch (E->getBuiltinCallee()) {
13628 case clang::X86::BI__builtin_ia32_phaddw128:
13629 case clang::X86::BI__builtin_ia32_phaddw256:
13630 case clang::X86::BI__builtin_ia32_phaddd128:
13631 case clang::X86::BI__builtin_ia32_phaddd256: {
13632 APSInt Res(LHSA + LHSB, DestUnsigned);
13633 ResultElements.push_back(APValue(Res));
13634 break;
13635 }
13636 case clang::X86::BI__builtin_ia32_phaddsw128:
13637 case clang::X86::BI__builtin_ia32_phaddsw256: {
13638 APSInt Res(LHSA.sadd_sat(LHSB));
13639 ResultElements.push_back(APValue(Res));
13640 break;
13641 }
13642 case clang::X86::BI__builtin_ia32_phsubw128:
13643 case clang::X86::BI__builtin_ia32_phsubw256:
13644 case clang::X86::BI__builtin_ia32_phsubd128:
13645 case clang::X86::BI__builtin_ia32_phsubd256: {
13646 APSInt Res(LHSA - LHSB, DestUnsigned);
13647 ResultElements.push_back(APValue(Res));
13648 break;
13649 }
13650 case clang::X86::BI__builtin_ia32_phsubsw128:
13651 case clang::X86::BI__builtin_ia32_phsubsw256: {
13652 APSInt Res(LHSA.ssub_sat(LHSB));
13653 ResultElements.push_back(APValue(Res));
13654 break;
13655 }
13656 }
13657 }
13658 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13659 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13660 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13661 switch (E->getBuiltinCallee()) {
13662 case clang::X86::BI__builtin_ia32_phaddw128:
13663 case clang::X86::BI__builtin_ia32_phaddw256:
13664 case clang::X86::BI__builtin_ia32_phaddd128:
13665 case clang::X86::BI__builtin_ia32_phaddd256: {
13666 APSInt Res(RHSA + RHSB, DestUnsigned);
13667 ResultElements.push_back(APValue(Res));
13668 break;
13669 }
13670 case clang::X86::BI__builtin_ia32_phaddsw128:
13671 case clang::X86::BI__builtin_ia32_phaddsw256: {
13672 APSInt Res(RHSA.sadd_sat(RHSB));
13673 ResultElements.push_back(APValue(Res));
13674 break;
13675 }
13676 case clang::X86::BI__builtin_ia32_phsubw128:
13677 case clang::X86::BI__builtin_ia32_phsubw256:
13678 case clang::X86::BI__builtin_ia32_phsubd128:
13679 case clang::X86::BI__builtin_ia32_phsubd256: {
13680 APSInt Res(RHSA - RHSB, DestUnsigned);
13681 ResultElements.push_back(APValue(Res));
13682 break;
13683 }
13684 case clang::X86::BI__builtin_ia32_phsubsw128:
13685 case clang::X86::BI__builtin_ia32_phsubsw256: {
13686 APSInt Res(RHSA.ssub_sat(RHSB));
13687 ResultElements.push_back(APValue(Res));
13688 break;
13689 }
13690 }
13691 }
13692 }
13693 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13694 }
13695 case clang::X86::BI__builtin_ia32_haddpd:
13696 case clang::X86::BI__builtin_ia32_haddps:
13697 case clang::X86::BI__builtin_ia32_haddps256:
13698 case clang::X86::BI__builtin_ia32_haddpd256:
13699 case clang::X86::BI__builtin_ia32_hsubpd:
13700 case clang::X86::BI__builtin_ia32_hsubps:
13701 case clang::X86::BI__builtin_ia32_hsubps256:
13702 case clang::X86::BI__builtin_ia32_hsubpd256: {
13703 APValue SourceLHS, SourceRHS;
13704 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13705 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13706 return false;
13707 unsigned NumElts = SourceLHS.getVectorLength();
13708 SmallVector<APValue, 4> ResultElements;
13709 ResultElements.reserve(NumElts);
13710 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13711 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13712 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13713 unsigned NumLanes = NumElts * EltBits / 128;
13714 unsigned NumElemsPerLane = NumElts / NumLanes;
13715 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13716
13717 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13718 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13719 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13720 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13721 switch (E->getBuiltinCallee()) {
13722 case clang::X86::BI__builtin_ia32_haddpd:
13723 case clang::X86::BI__builtin_ia32_haddps:
13724 case clang::X86::BI__builtin_ia32_haddps256:
13725 case clang::X86::BI__builtin_ia32_haddpd256:
13726 LHSA.add(LHSB, RM);
13727 break;
13728 case clang::X86::BI__builtin_ia32_hsubpd:
13729 case clang::X86::BI__builtin_ia32_hsubps:
13730 case clang::X86::BI__builtin_ia32_hsubps256:
13731 case clang::X86::BI__builtin_ia32_hsubpd256:
13732 LHSA.subtract(LHSB, RM);
13733 break;
13734 }
13735 ResultElements.push_back(APValue(LHSA));
13736 }
13737 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13738 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13739 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13740 switch (E->getBuiltinCallee()) {
13741 case clang::X86::BI__builtin_ia32_haddpd:
13742 case clang::X86::BI__builtin_ia32_haddps:
13743 case clang::X86::BI__builtin_ia32_haddps256:
13744 case clang::X86::BI__builtin_ia32_haddpd256:
13745 RHSA.add(RHSB, RM);
13746 break;
13747 case clang::X86::BI__builtin_ia32_hsubpd:
13748 case clang::X86::BI__builtin_ia32_hsubps:
13749 case clang::X86::BI__builtin_ia32_hsubps256:
13750 case clang::X86::BI__builtin_ia32_hsubpd256:
13751 RHSA.subtract(RHSB, RM);
13752 break;
13753 }
13754 ResultElements.push_back(APValue(RHSA));
13755 }
13756 }
13757 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13758 }
13759 case clang::X86::BI__builtin_ia32_addsubpd:
13760 case clang::X86::BI__builtin_ia32_addsubps:
13761 case clang::X86::BI__builtin_ia32_addsubpd256:
13762 case clang::X86::BI__builtin_ia32_addsubps256: {
13763 // Addsub: alternates between subtraction and addition
13764 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13765 APValue SourceLHS, SourceRHS;
13766 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13767 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13768 return false;
13769 unsigned NumElems = SourceLHS.getVectorLength();
13770 SmallVector<APValue, 8> ResultElements;
13771 ResultElements.reserve(NumElems);
13772 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13773
13774 for (unsigned I = 0; I != NumElems; ++I) {
13775 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13776 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13777 if (I % 2 == 0) {
13778 // Even indices: subtract
13779 LHS.subtract(RHS, RM);
13780 } else {
13781 // Odd indices: add
13782 LHS.add(RHS, RM);
13783 }
13784 ResultElements.push_back(APValue(LHS));
13785 }
13786 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13787 }
13788 case clang::X86::BI__builtin_ia32_pclmulqdq128:
13789 case clang::X86::BI__builtin_ia32_pclmulqdq256:
13790 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
13791 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
13792 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
13793 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
13794 APValue SourceLHS, SourceRHS;
13795 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13796 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13797 return false;
13798
13799 APSInt Imm8;
13800 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
13801 return false;
13802
13803 // Extract bits 0 and 4 from imm8
13804 bool SelectUpperA = (Imm8 & 0x01) != 0;
13805 bool SelectUpperB = (Imm8 & 0x10) != 0;
13806
13807 unsigned NumElems = SourceLHS.getVectorLength();
13808 SmallVector<APValue, 8> ResultElements;
13809 ResultElements.reserve(NumElems);
13810 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13811 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13812
13813 // Process each 128-bit lane
13814 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
13815 // Get the two 64-bit halves of the first operand
13816 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
13817 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
13818 // Get the two 64-bit halves of the second operand
13819 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
13820 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
13821
13822 // Select the appropriate 64-bit values based on imm8
13823 APInt A = SelectUpperA ? A1 : A0;
13824 APInt B = SelectUpperB ? B1 : B0;
13825
13826 // Extend both operands to 128 bits for carry-less multiplication
13827 APInt A128 = A.zext(128);
13828 APInt B128 = B.zext(128);
13829
13830 // Use APIntOps::clmul for carry-less multiplication
13831 APInt Result = llvm::APIntOps::clmul(A128, B128);
13832
13833 // Split the 128-bit result into two 64-bit halves
13834 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
13835 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
13836
13837 ResultElements.push_back(APValue(ResultLow));
13838 ResultElements.push_back(APValue(ResultHigh));
13839 }
13840
13841 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13842 }
13843 case Builtin::BI__builtin_elementwise_fshl:
13844 case Builtin::BI__builtin_elementwise_fshr: {
13845 APValue SourceHi, SourceLo, SourceShift;
13846 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13847 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13848 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13849 return false;
13850
13851 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13852 if (!DestEltTy->isIntegerType())
13853 return false;
13854
13855 unsigned SourceLen = SourceHi.getVectorLength();
13856 SmallVector<APValue> ResultElements;
13857 ResultElements.reserve(SourceLen);
13858 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13859 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
13860 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
13861 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
13862 switch (E->getBuiltinCallee()) {
13863 case Builtin::BI__builtin_elementwise_fshl:
13864 ResultElements.push_back(APValue(
13865 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
13866 break;
13867 case Builtin::BI__builtin_elementwise_fshr:
13868 ResultElements.push_back(APValue(
13869 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
13870 break;
13871 }
13872 }
13873
13874 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13875 }
13876
13877 case X86::BI__builtin_ia32_shuf_f32x4_256:
13878 case X86::BI__builtin_ia32_shuf_i32x4_256:
13879 case X86::BI__builtin_ia32_shuf_f64x2_256:
13880 case X86::BI__builtin_ia32_shuf_i64x2_256:
13881 case X86::BI__builtin_ia32_shuf_f32x4:
13882 case X86::BI__builtin_ia32_shuf_i32x4:
13883 case X86::BI__builtin_ia32_shuf_f64x2:
13884 case X86::BI__builtin_ia32_shuf_i64x2: {
13885 APValue SourceA, SourceB;
13886 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13887 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
13888 return false;
13889
13890 APSInt Imm;
13891 if (!EvaluateInteger(E->getArg(2), Imm, Info))
13892 return false;
13893
13894 // Destination and sources A, B all have the same type.
13895 unsigned NumElems = SourceA.getVectorLength();
13896 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13897 QualType ElemQT = VT->getElementType();
13898 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
13899 unsigned LaneBits = 128u;
13900 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
13901 unsigned NumElemsPerLane = LaneBits / ElemBits;
13902
13903 unsigned DstLen = SourceA.getVectorLength();
13904 SmallVector<APValue, 16> ResultElements;
13905 ResultElements.reserve(DstLen);
13906
13907 APValue R;
13908 if (!evalShuffleGeneric(
13909 Info, E, R,
13910 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
13911 -> std::pair<unsigned, int> {
13912 // DstIdx determines source. ShuffleMask selects lane in source.
13913 unsigned BitsPerElem = NumLanes / 2;
13914 unsigned IndexMask = (1u << BitsPerElem) - 1;
13915 unsigned Lane = DstIdx / NumElemsPerLane;
13916 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
13917 unsigned BitIdx = BitsPerElem * Lane;
13918 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
13919 unsigned ElemInLane = DstIdx % NumElemsPerLane;
13920 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
13921 return {SrcIdx, IdxToPick};
13922 }))
13923 return false;
13924 return Success(R, E);
13925 }
13926
13927 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
13928 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
13929 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
13930 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
13931 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
13932 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
13933
13934 APValue X, A;
13935 APSInt Imm;
13936 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
13937 !EvaluateAsRValue(Info, E->getArg(1), A) ||
13938 !EvaluateInteger(E->getArg(2), Imm, Info))
13939 return false;
13940
13941 assert(X.isVector() && A.isVector());
13942 assert(X.getVectorLength() == A.getVectorLength());
13943
13944 bool IsInverse = false;
13945 switch (E->getBuiltinCallee()) {
13946 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
13947 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
13948 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
13949 IsInverse = true;
13950 }
13951 }
13952
13953 unsigned NumBitsInByte = 8;
13954 unsigned NumBytesInQWord = 8;
13955 unsigned NumBitsInQWord = 64;
13956 unsigned NumBytes = A.getVectorLength();
13957 unsigned NumQWords = NumBytes / NumBytesInQWord;
13959 Result.reserve(NumBytes);
13960
13961 // computing A*X + Imm
13962 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
13963 // Extract the QWords from X, A
13964 APInt XQWord(NumBitsInQWord, 0);
13965 APInt AQWord(NumBitsInQWord, 0);
13966 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13967 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
13968 APInt XByte = X.getVectorElt(Idx).getInt();
13969 APInt AByte = A.getVectorElt(Idx).getInt();
13970 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
13971 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
13972 }
13973
13974 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13975 uint8_t XByte =
13976 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
13977 Result.push_back(APValue(APSInt(
13978 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
13979 }
13980 }
13981
13982 return Success(APValue(Result.data(), Result.size()), E);
13983 }
13984
13985 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
13986 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
13987 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
13988 APValue A, B;
13989 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13990 !EvaluateAsRValue(Info, E->getArg(1), B))
13991 return false;
13992
13993 assert(A.isVector() && B.isVector());
13994 assert(A.getVectorLength() == B.getVectorLength());
13995
13996 unsigned NumBytes = A.getVectorLength();
13998 Result.reserve(NumBytes);
13999
14000 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14001 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14002 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14003 Result.push_back(APValue(
14004 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14005 }
14006
14007 return Success(APValue(Result.data(), Result.size()), E);
14008 }
14009
14010 case X86::BI__builtin_ia32_insertf32x4_256:
14011 case X86::BI__builtin_ia32_inserti32x4_256:
14012 case X86::BI__builtin_ia32_insertf64x2_256:
14013 case X86::BI__builtin_ia32_inserti64x2_256:
14014 case X86::BI__builtin_ia32_insertf32x4:
14015 case X86::BI__builtin_ia32_inserti32x4:
14016 case X86::BI__builtin_ia32_insertf64x2_512:
14017 case X86::BI__builtin_ia32_inserti64x2_512:
14018 case X86::BI__builtin_ia32_insertf32x8:
14019 case X86::BI__builtin_ia32_inserti32x8:
14020 case X86::BI__builtin_ia32_insertf64x4:
14021 case X86::BI__builtin_ia32_inserti64x4:
14022 case X86::BI__builtin_ia32_vinsertf128_ps256:
14023 case X86::BI__builtin_ia32_vinsertf128_pd256:
14024 case X86::BI__builtin_ia32_vinsertf128_si256:
14025 case X86::BI__builtin_ia32_insert128i256: {
14026 APValue SourceDst, SourceSub;
14027 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14028 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14029 return false;
14030
14031 APSInt Imm;
14032 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14033 return false;
14034
14035 assert(SourceDst.isVector() && SourceSub.isVector());
14036 unsigned DstLen = SourceDst.getVectorLength();
14037 unsigned SubLen = SourceSub.getVectorLength();
14038 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14039 unsigned NumLanes = DstLen / SubLen;
14040 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14041
14042 SmallVector<APValue, 16> ResultElements;
14043 ResultElements.reserve(DstLen);
14044
14045 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14046 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14047 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14048 else
14049 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14050 }
14051
14052 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14053 }
14054
14055 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14056 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14057 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14058 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14059 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14060 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14061 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14062 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14063 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14064 APValue VecVal;
14065 APSInt Scalar, IndexAPS;
14066 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14067 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14068 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14069 return false;
14070
14071 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14072 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14073 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14074 Scalar.setIsUnsigned(ElemUnsigned);
14075 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14076 APValue ElemAV(ElemAPS);
14077
14078 unsigned NumElems = VecVal.getVectorLength();
14079 unsigned Index =
14080 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14081
14083 Elems.reserve(NumElems);
14084 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14085 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14086
14087 return Success(APValue(Elems.data(), NumElems), E);
14088 }
14089
14090 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14091 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14092 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14093 APValue R;
14094 if (!evalShuffleGeneric(
14095 Info, E, R,
14096 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14097 unsigned LaneBase = (DstIdx / 16) * 16;
14098 unsigned LaneIdx = DstIdx % 16;
14099 if (LaneIdx < Shift)
14100 return std::make_pair(0, -1);
14101
14102 return std::make_pair(
14103 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14104 }))
14105 return false;
14106 return Success(R, E);
14107 }
14108
14109 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14110 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14111 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14112 APValue R;
14113 if (!evalShuffleGeneric(
14114 Info, E, R,
14115 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14116 unsigned LaneBase = (DstIdx / 16) * 16;
14117 unsigned LaneIdx = DstIdx % 16;
14118 if (LaneIdx + Shift < 16)
14119 return std::make_pair(
14120 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14121
14122 return std::make_pair(0, -1);
14123 }))
14124 return false;
14125 return Success(R, E);
14126 }
14127
14128 case X86::BI__builtin_ia32_palignr128:
14129 case X86::BI__builtin_ia32_palignr256:
14130 case X86::BI__builtin_ia32_palignr512: {
14131 APValue R;
14132 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14133 // Default to -1 → zero-fill this destination element
14134 unsigned VecIdx = 1;
14135 int ElemIdx = -1;
14136
14137 int Lane = DstIdx / 16;
14138 int Offset = DstIdx % 16;
14139
14140 // Elements come from VecB first, then VecA after the shift boundary
14141 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14142 if (ShiftedIdx < 16) { // from VecB
14143 ElemIdx = ShiftedIdx + (Lane * 16);
14144 } else if (ShiftedIdx < 32) { // from VecA
14145 VecIdx = 0;
14146 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14147 }
14148
14149 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14150 }))
14151 return false;
14152 return Success(R, E);
14153 }
14154 case X86::BI__builtin_ia32_alignd128:
14155 case X86::BI__builtin_ia32_alignd256:
14156 case X86::BI__builtin_ia32_alignd512:
14157 case X86::BI__builtin_ia32_alignq128:
14158 case X86::BI__builtin_ia32_alignq256:
14159 case X86::BI__builtin_ia32_alignq512: {
14160 APValue R;
14161 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14162 if (!evalShuffleGeneric(Info, E, R,
14163 [NumElems](unsigned DstIdx, unsigned Shift) {
14164 unsigned Imm = Shift & 0xFF;
14165 unsigned EffectiveShift = Imm & (NumElems - 1);
14166 unsigned SourcePos = DstIdx + EffectiveShift;
14167 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14168 unsigned ElemIdx = SourcePos & (NumElems - 1);
14169
14170 return std::pair<unsigned, int>{
14171 VecIdx, static_cast<int>(ElemIdx)};
14172 }))
14173 return false;
14174 return Success(R, E);
14175 }
14176 case X86::BI__builtin_ia32_permvarsi256:
14177 case X86::BI__builtin_ia32_permvarsf256:
14178 case X86::BI__builtin_ia32_permvardf512:
14179 case X86::BI__builtin_ia32_permvardi512:
14180 case X86::BI__builtin_ia32_permvarhi128: {
14181 APValue R;
14182 if (!evalShuffleGeneric(Info, E, R,
14183 [](unsigned DstIdx, unsigned ShuffleMask) {
14184 int Offset = ShuffleMask & 0x7;
14185 return std::pair<unsigned, int>{0, Offset};
14186 }))
14187 return false;
14188 return Success(R, E);
14189 }
14190 case X86::BI__builtin_ia32_permvarqi128:
14191 case X86::BI__builtin_ia32_permvarhi256:
14192 case X86::BI__builtin_ia32_permvarsi512:
14193 case X86::BI__builtin_ia32_permvarsf512: {
14194 APValue R;
14195 if (!evalShuffleGeneric(Info, E, R,
14196 [](unsigned DstIdx, unsigned ShuffleMask) {
14197 int Offset = ShuffleMask & 0xF;
14198 return std::pair<unsigned, int>{0, Offset};
14199 }))
14200 return false;
14201 return Success(R, E);
14202 }
14203 case X86::BI__builtin_ia32_permvardi256:
14204 case X86::BI__builtin_ia32_permvardf256: {
14205 APValue R;
14206 if (!evalShuffleGeneric(Info, E, R,
14207 [](unsigned DstIdx, unsigned ShuffleMask) {
14208 int Offset = ShuffleMask & 0x3;
14209 return std::pair<unsigned, int>{0, Offset};
14210 }))
14211 return false;
14212 return Success(R, E);
14213 }
14214 case X86::BI__builtin_ia32_permvarqi256:
14215 case X86::BI__builtin_ia32_permvarhi512: {
14216 APValue R;
14217 if (!evalShuffleGeneric(Info, E, R,
14218 [](unsigned DstIdx, unsigned ShuffleMask) {
14219 int Offset = ShuffleMask & 0x1F;
14220 return std::pair<unsigned, int>{0, Offset};
14221 }))
14222 return false;
14223 return Success(R, E);
14224 }
14225 case X86::BI__builtin_ia32_permvarqi512: {
14226 APValue R;
14227 if (!evalShuffleGeneric(Info, E, R,
14228 [](unsigned DstIdx, unsigned ShuffleMask) {
14229 int Offset = ShuffleMask & 0x3F;
14230 return std::pair<unsigned, int>{0, Offset};
14231 }))
14232 return false;
14233 return Success(R, E);
14234 }
14235 case X86::BI__builtin_ia32_vpermi2varq128:
14236 case X86::BI__builtin_ia32_vpermi2varpd128: {
14237 APValue R;
14238 if (!evalShuffleGeneric(Info, E, R,
14239 [](unsigned DstIdx, unsigned ShuffleMask) {
14240 int Offset = ShuffleMask & 0x1;
14241 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14242 return std::pair<unsigned, int>{SrcIdx, Offset};
14243 }))
14244 return false;
14245 return Success(R, E);
14246 }
14247 case X86::BI__builtin_ia32_vpermi2vard128:
14248 case X86::BI__builtin_ia32_vpermi2varps128:
14249 case X86::BI__builtin_ia32_vpermi2varq256:
14250 case X86::BI__builtin_ia32_vpermi2varpd256: {
14251 APValue R;
14252 if (!evalShuffleGeneric(Info, E, R,
14253 [](unsigned DstIdx, unsigned ShuffleMask) {
14254 int Offset = ShuffleMask & 0x3;
14255 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14256 return std::pair<unsigned, int>{SrcIdx, Offset};
14257 }))
14258 return false;
14259 return Success(R, E);
14260 }
14261 case X86::BI__builtin_ia32_vpermi2varhi128:
14262 case X86::BI__builtin_ia32_vpermi2vard256:
14263 case X86::BI__builtin_ia32_vpermi2varps256:
14264 case X86::BI__builtin_ia32_vpermi2varq512:
14265 case X86::BI__builtin_ia32_vpermi2varpd512: {
14266 APValue R;
14267 if (!evalShuffleGeneric(Info, E, R,
14268 [](unsigned DstIdx, unsigned ShuffleMask) {
14269 int Offset = ShuffleMask & 0x7;
14270 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14271 return std::pair<unsigned, int>{SrcIdx, Offset};
14272 }))
14273 return false;
14274 return Success(R, E);
14275 }
14276 case X86::BI__builtin_ia32_vpermi2varqi128:
14277 case X86::BI__builtin_ia32_vpermi2varhi256:
14278 case X86::BI__builtin_ia32_vpermi2vard512:
14279 case X86::BI__builtin_ia32_vpermi2varps512: {
14280 APValue R;
14281 if (!evalShuffleGeneric(Info, E, R,
14282 [](unsigned DstIdx, unsigned ShuffleMask) {
14283 int Offset = ShuffleMask & 0xF;
14284 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14285 return std::pair<unsigned, int>{SrcIdx, Offset};
14286 }))
14287 return false;
14288 return Success(R, E);
14289 }
14290 case X86::BI__builtin_ia32_vpermi2varqi256:
14291 case X86::BI__builtin_ia32_vpermi2varhi512: {
14292 APValue R;
14293 if (!evalShuffleGeneric(Info, E, R,
14294 [](unsigned DstIdx, unsigned ShuffleMask) {
14295 int Offset = ShuffleMask & 0x1F;
14296 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14297 return std::pair<unsigned, int>{SrcIdx, Offset};
14298 }))
14299 return false;
14300 return Success(R, E);
14301 }
14302 case X86::BI__builtin_ia32_vpermi2varqi512: {
14303 APValue R;
14304 if (!evalShuffleGeneric(Info, E, R,
14305 [](unsigned DstIdx, unsigned ShuffleMask) {
14306 int Offset = ShuffleMask & 0x3F;
14307 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14308 return std::pair<unsigned, int>{SrcIdx, Offset};
14309 }))
14310 return false;
14311 return Success(R, E);
14312 }
14313
14314 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14315 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14316 APValue SrcVec;
14317 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14318 return false;
14319
14320 APSInt Imm;
14321 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14322 return false;
14323
14324 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14325 unsigned SrcNumElems = SrcVTy->getNumElements();
14326 const auto *DstVTy = E->getType()->castAs<VectorType>();
14327 unsigned DstNumElems = DstVTy->getNumElements();
14328 QualType DstElemTy = DstVTy->getElementType();
14329
14330 const llvm::fltSemantics &HalfSem =
14331 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14332
14333 int ImmVal = Imm.getZExtValue();
14334 bool UseMXCSR = (ImmVal & 4) != 0;
14335 bool IsFPConstrained =
14337
14338 llvm::RoundingMode RM;
14339 if (!UseMXCSR) {
14340 switch (ImmVal & 3) {
14341 case 0:
14342 RM = llvm::RoundingMode::NearestTiesToEven;
14343 break;
14344 case 1:
14345 RM = llvm::RoundingMode::TowardNegative;
14346 break;
14347 case 2:
14348 RM = llvm::RoundingMode::TowardPositive;
14349 break;
14350 case 3:
14351 RM = llvm::RoundingMode::TowardZero;
14352 break;
14353 default:
14354 llvm_unreachable("Invalid immediate rounding mode");
14355 }
14356 } else {
14357 RM = llvm::RoundingMode::NearestTiesToEven;
14358 }
14359
14360 SmallVector<APValue, 8> ResultElements;
14361 ResultElements.reserve(DstNumElems);
14362
14363 for (unsigned I = 0; I < SrcNumElems; ++I) {
14364 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14365
14366 bool LostInfo;
14367 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14368
14369 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14370 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14371 return false;
14372 }
14373
14374 APSInt DstInt(SrcVal.bitcastToAPInt(),
14376 ResultElements.push_back(APValue(DstInt));
14377 }
14378
14379 if (DstNumElems > SrcNumElems) {
14380 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14381 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14382 ResultElements.push_back(APValue(Zero));
14383 }
14384 }
14385
14386 return Success(ResultElements, E);
14387 }
14388 }
14389}
14390
14391bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14392 APValue Source;
14393 QualType SourceVecType = E->getSrcExpr()->getType();
14394 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14395 return false;
14396
14397 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14398 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14399
14400 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14401
14402 auto SourceLen = Source.getVectorLength();
14403 SmallVector<APValue, 4> ResultElements;
14404 ResultElements.reserve(SourceLen);
14405 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14406 APValue Elt;
14407 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14408 Source.getVectorElt(EltNum), Elt))
14409 return false;
14410 ResultElements.push_back(std::move(Elt));
14411 }
14412
14413 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14414}
14415
14416static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14417 QualType ElemType, APValue const &VecVal1,
14418 APValue const &VecVal2, unsigned EltNum,
14419 APValue &Result) {
14420 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14421 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14422
14423 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14424 int64_t index = IndexVal.getExtValue();
14425 // The spec says that -1 should be treated as undef for optimizations,
14426 // but in constexpr we'd have to produce an APValue::Indeterminate,
14427 // which is prohibited from being a top-level constant value. Emit a
14428 // diagnostic instead.
14429 if (index == -1) {
14430 Info.FFDiag(
14431 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14432 << EltNum;
14433 return false;
14434 }
14435
14436 if (index < 0 ||
14437 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14438 llvm_unreachable("Out of bounds shuffle index");
14439
14440 if (index >= TotalElementsInInputVector1)
14441 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14442 else
14443 Result = VecVal1.getVectorElt(index);
14444 return true;
14445}
14446
14447bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14448 // FIXME: Unary shuffle with mask not currently supported.
14449 if (E->getNumSubExprs() == 2)
14450 return Error(E);
14451 APValue VecVal1;
14452 const Expr *Vec1 = E->getExpr(0);
14453 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14454 return false;
14455 APValue VecVal2;
14456 const Expr *Vec2 = E->getExpr(1);
14457 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14458 return false;
14459
14460 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14461 QualType DestElTy = DestVecTy->getElementType();
14462
14463 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14464
14465 SmallVector<APValue, 4> ResultElements;
14466 ResultElements.reserve(TotalElementsInOutputVector);
14467 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14468 APValue Elt;
14469 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14470 return false;
14471 ResultElements.push_back(std::move(Elt));
14472 }
14473
14474 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14475}
14476
14477//===----------------------------------------------------------------------===//
14478// Array Evaluation
14479//===----------------------------------------------------------------------===//
14480
14481namespace {
14482 class ArrayExprEvaluator
14483 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14484 const LValue &This;
14485 APValue &Result;
14486 public:
14487
14488 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14489 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14490
14491 bool Success(const APValue &V, const Expr *E) {
14492 assert(V.isArray() && "expected array");
14493 Result = V;
14494 return true;
14495 }
14496
14497 bool ZeroInitialization(const Expr *E) {
14498 const ConstantArrayType *CAT =
14499 Info.Ctx.getAsConstantArrayType(E->getType());
14500 if (!CAT) {
14501 if (E->getType()->isIncompleteArrayType()) {
14502 // We can be asked to zero-initialize a flexible array member; this
14503 // is represented as an ImplicitValueInitExpr of incomplete array
14504 // type. In this case, the array has zero elements.
14505 Result = APValue(APValue::UninitArray(), 0, 0);
14506 return true;
14507 }
14508 // FIXME: We could handle VLAs here.
14509 return Error(E);
14510 }
14511
14512 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14513 if (!Result.hasArrayFiller())
14514 return true;
14515
14516 // Zero-initialize all elements.
14517 LValue Subobject = This;
14518 Subobject.addArray(Info, E, CAT);
14519 ImplicitValueInitExpr VIE(CAT->getElementType());
14520 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14521 }
14522
14523 bool VisitCallExpr(const CallExpr *E) {
14524 return handleCallExpr(E, Result, &This);
14525 }
14526 bool VisitCastExpr(const CastExpr *E);
14527 bool VisitInitListExpr(const InitListExpr *E,
14528 QualType AllocType = QualType());
14529 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14530 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14531 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14532 const LValue &Subobject,
14533 APValue *Value, QualType Type);
14534 bool VisitStringLiteral(const StringLiteral *E,
14535 QualType AllocType = QualType()) {
14536 expandStringLiteral(Info, E, Result, AllocType);
14537 return true;
14538 }
14539 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14540 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14541 ArrayRef<Expr *> Args,
14542 const Expr *ArrayFiller,
14543 QualType AllocType = QualType());
14544 };
14545} // end anonymous namespace
14546
14547static bool EvaluateArray(const Expr *E, const LValue &This,
14548 APValue &Result, EvalInfo &Info) {
14549 assert(!E->isValueDependent());
14550 assert(E->isPRValue() && E->getType()->isArrayType() &&
14551 "not an array prvalue");
14552 return ArrayExprEvaluator(Info, This, Result).Visit(E);
14553}
14554
14555static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
14556 APValue &Result, const InitListExpr *ILE,
14557 QualType AllocType) {
14558 assert(!ILE->isValueDependent());
14559 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
14560 "not an array prvalue");
14561 return ArrayExprEvaluator(Info, This, Result)
14562 .VisitInitListExpr(ILE, AllocType);
14563}
14564
14565static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
14566 APValue &Result,
14567 const CXXConstructExpr *CCE,
14568 QualType AllocType) {
14569 assert(!CCE->isValueDependent());
14570 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
14571 "not an array prvalue");
14572 return ArrayExprEvaluator(Info, This, Result)
14573 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
14574}
14575
14576// Return true iff the given array filler may depend on the element index.
14577static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
14578 // For now, just allow non-class value-initialization and initialization
14579 // lists comprised of them.
14580 if (isa<ImplicitValueInitExpr>(FillerExpr))
14581 return false;
14582 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
14583 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
14584 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
14585 return true;
14586 }
14587
14588 if (ILE->hasArrayFiller() &&
14589 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
14590 return true;
14591
14592 return false;
14593 }
14594 return true;
14595}
14596
14597bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
14598 const Expr *SE = E->getSubExpr();
14599
14600 switch (E->getCastKind()) {
14601 default:
14602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14603 case CK_HLSLAggregateSplatCast: {
14604 APValue Val;
14605 QualType ValTy;
14606
14607 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14608 return false;
14609
14610 unsigned NEls = elementwiseSize(Info, E->getType());
14611
14612 SmallVector<APValue> SplatEls(NEls, Val);
14613 SmallVector<QualType> SplatType(NEls, ValTy);
14614
14615 // cast the elements
14616 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14617 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
14618 SplatType))
14619 return false;
14620
14621 return true;
14622 }
14623 case CK_HLSLElementwiseCast: {
14624 SmallVector<APValue> SrcEls;
14625 SmallVector<QualType> SrcTypes;
14626
14627 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
14628 return false;
14629
14630 // cast the elements
14631 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14632 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
14633 SrcTypes))
14634 return false;
14635 return true;
14636 }
14637 }
14638}
14639
14640bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
14641 QualType AllocType) {
14642 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14643 AllocType.isNull() ? E->getType() : AllocType);
14644 if (!CAT)
14645 return Error(E);
14646
14647 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
14648 // an appropriately-typed string literal enclosed in braces.
14649 if (E->isStringLiteralInit()) {
14650 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
14651 // FIXME: Support ObjCEncodeExpr here once we support it in
14652 // ArrayExprEvaluator generally.
14653 if (!SL)
14654 return Error(E);
14655 return VisitStringLiteral(SL, AllocType);
14656 }
14657 // Any other transparent list init will need proper handling of the
14658 // AllocType; we can't just recurse to the inner initializer.
14659 assert(!E->isTransparent() &&
14660 "transparent array list initialization is not string literal init?");
14661
14662 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
14663 AllocType);
14664}
14665
14666bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
14667 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
14668 QualType AllocType) {
14669 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
14670 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
14671
14672 bool Success = true;
14673
14674 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
14675 "zero-initialized array shouldn't have any initialized elts");
14676 APValue Filler;
14677 if (Result.isArray() && Result.hasArrayFiller())
14678 Filler = Result.getArrayFiller();
14679
14680 unsigned NumEltsToInit = Args.size();
14681 unsigned NumElts = CAT->getZExtSize();
14682
14683 // If the initializer might depend on the array index, run it for each
14684 // array element.
14685 if (NumEltsToInit != NumElts &&
14686 MaybeElementDependentArrayFiller(ArrayFiller)) {
14687 NumEltsToInit = NumElts;
14688 } else {
14689 for (auto *Init : Args) {
14690 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
14691 NumEltsToInit += EmbedS->getDataElementCount() - 1;
14692 }
14693 if (NumEltsToInit > NumElts)
14694 NumEltsToInit = NumElts;
14695 }
14696
14697 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
14698 << NumEltsToInit << ".\n");
14699
14700 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
14701
14702 // If the array was previously zero-initialized, preserve the
14703 // zero-initialized values.
14704 if (Filler.hasValue()) {
14705 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
14706 Result.getArrayInitializedElt(I) = Filler;
14707 if (Result.hasArrayFiller())
14708 Result.getArrayFiller() = Filler;
14709 }
14710
14711 LValue Subobject = This;
14712 Subobject.addArray(Info, ExprToVisit, CAT);
14713 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
14714 if (Init->isValueDependent())
14715 return EvaluateDependentExpr(Init, Info);
14716
14717 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
14718 Subobject, Init) ||
14719 !HandleLValueArrayAdjustment(Info, Init, Subobject,
14720 CAT->getElementType(), 1)) {
14721 if (!Info.noteFailure())
14722 return false;
14723 Success = false;
14724 }
14725 return true;
14726 };
14727 unsigned ArrayIndex = 0;
14728 QualType DestTy = CAT->getElementType();
14729 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
14730 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
14731 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
14732 if (ArrayIndex >= NumEltsToInit)
14733 break;
14734 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
14735 StringLiteral *SL = EmbedS->getDataStringLiteral();
14736 for (unsigned I = EmbedS->getStartingElementPos(),
14737 N = EmbedS->getDataElementCount();
14738 I != EmbedS->getStartingElementPos() + N; ++I) {
14739 Value = SL->getCodeUnit(I);
14740 if (DestTy->isIntegerType()) {
14741 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
14742 } else {
14743 assert(DestTy->isFloatingType() && "unexpected type");
14744 const FPOptions FPO =
14745 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14746 APFloat FValue(0.0);
14747 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
14748 DestTy, FValue))
14749 return false;
14750 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
14751 }
14752 ArrayIndex++;
14753 }
14754 } else {
14755 if (!Eval(Init, ArrayIndex))
14756 return false;
14757 ++ArrayIndex;
14758 }
14759 }
14760
14761 if (!Result.hasArrayFiller())
14762 return Success;
14763
14764 // If we get here, we have a trivial filler, which we can just evaluate
14765 // once and splat over the rest of the array elements.
14766 assert(ArrayFiller && "no array filler for incomplete init list");
14767 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
14768 ArrayFiller) &&
14769 Success;
14770}
14771
14772bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
14773 LValue CommonLV;
14774 if (E->getCommonExpr() &&
14775 !Evaluate(Info.CurrentCall->createTemporary(
14776 E->getCommonExpr(),
14777 getStorageType(Info.Ctx, E->getCommonExpr()),
14778 ScopeKind::FullExpression, CommonLV),
14779 Info, E->getCommonExpr()->getSourceExpr()))
14780 return false;
14781
14783
14784 uint64_t Elements = CAT->getZExtSize();
14785 Result = APValue(APValue::UninitArray(), Elements, Elements);
14786
14787 LValue Subobject = This;
14788 Subobject.addArray(Info, E, CAT);
14789
14790 bool Success = true;
14791 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
14792 // C++ [class.temporary]/5
14793 // There are four contexts in which temporaries are destroyed at a different
14794 // point than the end of the full-expression. [...] The second context is
14795 // when a copy constructor is called to copy an element of an array while
14796 // the entire array is copied [...]. In either case, if the constructor has
14797 // one or more default arguments, the destruction of every temporary created
14798 // in a default argument is sequenced before the construction of the next
14799 // array element, if any.
14800 FullExpressionRAII Scope(Info);
14801
14802 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
14803 Info, Subobject, E->getSubExpr()) ||
14804 !HandleLValueArrayAdjustment(Info, E, Subobject,
14805 CAT->getElementType(), 1)) {
14806 if (!Info.noteFailure())
14807 return false;
14808 Success = false;
14809 }
14810
14811 // Make sure we run the destructors too.
14812 Scope.destroy();
14813 }
14814
14815 return Success;
14816}
14817
14818bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
14819 return VisitCXXConstructExpr(E, This, &Result, E->getType());
14820}
14821
14822bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
14823 const LValue &Subobject,
14824 APValue *Value,
14825 QualType Type) {
14826 bool HadZeroInit = Value->hasValue();
14827
14828 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
14829 unsigned FinalSize = CAT->getZExtSize();
14830
14831 // Preserve the array filler if we had prior zero-initialization.
14832 APValue Filler =
14833 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
14834 : APValue();
14835
14836 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
14837 if (FinalSize == 0)
14838 return true;
14839
14840 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
14841 Info, E->getExprLoc(), E->getConstructor(),
14843 LValue ArrayElt = Subobject;
14844 ArrayElt.addArray(Info, E, CAT);
14845 // We do the whole initialization in two passes, first for just one element,
14846 // then for the whole array. It's possible we may find out we can't do const
14847 // init in the first pass, in which case we avoid allocating a potentially
14848 // large array. We don't do more passes because expanding array requires
14849 // copying the data, which is wasteful.
14850 for (const unsigned N : {1u, FinalSize}) {
14851 unsigned OldElts = Value->getArrayInitializedElts();
14852 if (OldElts == N)
14853 break;
14854
14855 // Expand the array to appropriate size.
14856 APValue NewValue(APValue::UninitArray(), N, FinalSize);
14857 for (unsigned I = 0; I < OldElts; ++I)
14858 NewValue.getArrayInitializedElt(I).swap(
14859 Value->getArrayInitializedElt(I));
14860 Value->swap(NewValue);
14861
14862 if (HadZeroInit)
14863 for (unsigned I = OldElts; I < N; ++I)
14864 Value->getArrayInitializedElt(I) = Filler;
14865
14866 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
14867 // If we have a trivial constructor, only evaluate it once and copy
14868 // the result into all the array elements.
14869 APValue &FirstResult = Value->getArrayInitializedElt(0);
14870 for (unsigned I = OldElts; I < FinalSize; ++I)
14871 Value->getArrayInitializedElt(I) = FirstResult;
14872 } else {
14873 for (unsigned I = OldElts; I < N; ++I) {
14874 if (!VisitCXXConstructExpr(E, ArrayElt,
14875 &Value->getArrayInitializedElt(I),
14876 CAT->getElementType()) ||
14877 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
14878 CAT->getElementType(), 1))
14879 return false;
14880 // When checking for const initilization any diagnostic is considered
14881 // an error.
14882 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
14883 !Info.keepEvaluatingAfterFailure())
14884 return false;
14885 }
14886 }
14887 }
14888
14889 return true;
14890 }
14891
14892 if (!Type->isRecordType())
14893 return Error(E);
14894
14895 return RecordExprEvaluator(Info, Subobject, *Value)
14896 .VisitCXXConstructExpr(E, Type);
14897}
14898
14899bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
14900 const CXXParenListInitExpr *E) {
14901 assert(E->getType()->isConstantArrayType() &&
14902 "Expression result is not a constant array type");
14903
14904 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
14905 E->getArrayFiller());
14906}
14907
14908//===----------------------------------------------------------------------===//
14909// Integer Evaluation
14910//
14911// As a GNU extension, we support casting pointers to sufficiently-wide integer
14912// types and back in constant folding. Integer values are thus represented
14913// either as an integer-valued APValue, or as an lvalue-valued APValue.
14914//===----------------------------------------------------------------------===//
14915
14916namespace {
14917class IntExprEvaluator
14918 : public ExprEvaluatorBase<IntExprEvaluator> {
14919 APValue &Result;
14920public:
14921 IntExprEvaluator(EvalInfo &info, APValue &result)
14922 : ExprEvaluatorBaseTy(info), Result(result) {}
14923
14924 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
14925 assert(E->getType()->isIntegralOrEnumerationType() &&
14926 "Invalid evaluation result.");
14927 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
14928 "Invalid evaluation result.");
14929 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14930 "Invalid evaluation result.");
14931 Result = APValue(SI);
14932 return true;
14933 }
14934 bool Success(const llvm::APSInt &SI, const Expr *E) {
14935 return Success(SI, E, Result);
14936 }
14937
14938 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
14939 assert(E->getType()->isIntegralOrEnumerationType() &&
14940 "Invalid evaluation result.");
14941 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
14942 "Invalid evaluation result.");
14943 Result = APValue(APSInt(I));
14944 Result.getInt().setIsUnsigned(
14946 return true;
14947 }
14948 bool Success(const llvm::APInt &I, const Expr *E) {
14949 return Success(I, E, Result);
14950 }
14951
14952 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
14953 assert(E->getType()->isIntegralOrEnumerationType() &&
14954 "Invalid evaluation result.");
14955 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
14956 return true;
14957 }
14958 bool Success(uint64_t Value, const Expr *E) {
14959 return Success(Value, E, Result);
14960 }
14961
14962 bool Success(CharUnits Size, const Expr *E) {
14963 return Success(Size.getQuantity(), E);
14964 }
14965
14966 bool Success(const APValue &V, const Expr *E) {
14967 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
14968 // pointer allow further evaluation of the value.
14969 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
14970 V.allowConstexprUnknown()) {
14971 Result = V;
14972 return true;
14973 }
14974 return Success(V.getInt(), E);
14975 }
14976
14977 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
14978
14979 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
14980 const CallExpr *);
14981
14982 //===--------------------------------------------------------------------===//
14983 // Visitor Methods
14984 //===--------------------------------------------------------------------===//
14985
14986 bool VisitIntegerLiteral(const IntegerLiteral *E) {
14987 return Success(E->getValue(), E);
14988 }
14989 bool VisitCharacterLiteral(const CharacterLiteral *E) {
14990 return Success(E->getValue(), E);
14991 }
14992
14993 bool CheckReferencedDecl(const Expr *E, const Decl *D);
14994 bool VisitDeclRefExpr(const DeclRefExpr *E) {
14995 if (CheckReferencedDecl(E, E->getDecl()))
14996 return true;
14997
14998 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
14999 }
15000 bool VisitMemberExpr(const MemberExpr *E) {
15001 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15002 VisitIgnoredBaseExpression(E->getBase());
15003 return true;
15004 }
15005
15006 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15007 }
15008
15009 bool VisitCallExpr(const CallExpr *E);
15010 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15011 bool VisitBinaryOperator(const BinaryOperator *E);
15012 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15013 bool VisitUnaryOperator(const UnaryOperator *E);
15014
15015 bool VisitCastExpr(const CastExpr* E);
15016 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15017
15018 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15019 return Success(E->getValue(), E);
15020 }
15021
15022 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15023 return Success(E->getValue(), E);
15024 }
15025
15026 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15027 if (Info.ArrayInitIndex == uint64_t(-1)) {
15028 // We were asked to evaluate this subexpression independent of the
15029 // enclosing ArrayInitLoopExpr. We can't do that.
15030 Info.FFDiag(E);
15031 return false;
15032 }
15033 return Success(Info.ArrayInitIndex, E);
15034 }
15035
15036 // Note, GNU defines __null as an integer, not a pointer.
15037 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15038 return ZeroInitialization(E);
15039 }
15040
15041 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15042 if (E->isStoredAsBoolean())
15043 return Success(E->getBoolValue(), E);
15044 if (E->getAPValue().isAbsent())
15045 return false;
15046 assert(E->getAPValue().isInt() && "APValue type not supported");
15047 return Success(E->getAPValue().getInt(), E);
15048 }
15049
15050 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15051 return Success(E->getValue(), E);
15052 }
15053
15054 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15055 return Success(E->getValue(), E);
15056 }
15057
15058 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15059 // This should not be evaluated during constant expr evaluation, as it
15060 // should always be in an unevaluated context (the args list of a 'gang' or
15061 // 'tile' clause).
15062 return Error(E);
15063 }
15064
15065 bool VisitUnaryReal(const UnaryOperator *E);
15066 bool VisitUnaryImag(const UnaryOperator *E);
15067
15068 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15069 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15070 bool VisitSourceLocExpr(const SourceLocExpr *E);
15071 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15072 bool VisitRequiresExpr(const RequiresExpr *E);
15073 // FIXME: Missing: array subscript of vector, member of vector
15074};
15075
15076class FixedPointExprEvaluator
15077 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15078 APValue &Result;
15079
15080 public:
15081 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15082 : ExprEvaluatorBaseTy(info), Result(result) {}
15083
15084 bool Success(const llvm::APInt &I, const Expr *E) {
15085 return Success(
15086 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15087 }
15088
15089 bool Success(uint64_t Value, const Expr *E) {
15090 return Success(
15091 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15092 }
15093
15094 bool Success(const APValue &V, const Expr *E) {
15095 return Success(V.getFixedPoint(), E);
15096 }
15097
15098 bool Success(const APFixedPoint &V, const Expr *E) {
15099 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15100 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15101 "Invalid evaluation result.");
15102 Result = APValue(V);
15103 return true;
15104 }
15105
15106 bool ZeroInitialization(const Expr *E) {
15107 return Success(0, E);
15108 }
15109
15110 //===--------------------------------------------------------------------===//
15111 // Visitor Methods
15112 //===--------------------------------------------------------------------===//
15113
15114 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15115 return Success(E->getValue(), E);
15116 }
15117
15118 bool VisitCastExpr(const CastExpr *E);
15119 bool VisitUnaryOperator(const UnaryOperator *E);
15120 bool VisitBinaryOperator(const BinaryOperator *E);
15121};
15122} // end anonymous namespace
15123
15124/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15125/// produce either the integer value or a pointer.
15126///
15127/// GCC has a heinous extension which folds casts between pointer types and
15128/// pointer-sized integral types. We support this by allowing the evaluation of
15129/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15130/// Some simple arithmetic on such values is supported (they are treated much
15131/// like char*).
15132static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
15133 EvalInfo &Info) {
15134 assert(!E->isValueDependent());
15135 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15136 return IntExprEvaluator(Info, Result).Visit(E);
15137}
15138
15139static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15140 assert(!E->isValueDependent());
15141 APValue Val;
15142 if (!EvaluateIntegerOrLValue(E, Val, Info))
15143 return false;
15144 if (!Val.isInt()) {
15145 // FIXME: It would be better to produce the diagnostic for casting
15146 // a pointer to an integer.
15147 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15148 return false;
15149 }
15150 Result = Val.getInt();
15151 return true;
15152}
15153
15154bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15156 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15157 return Success(Evaluated, E);
15158}
15159
15160static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15161 EvalInfo &Info) {
15162 assert(!E->isValueDependent());
15163 if (E->getType()->isFixedPointType()) {
15164 APValue Val;
15165 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15166 return false;
15167 if (!Val.isFixedPoint())
15168 return false;
15169
15170 Result = Val.getFixedPoint();
15171 return true;
15172 }
15173 return false;
15174}
15175
15176static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15177 EvalInfo &Info) {
15178 assert(!E->isValueDependent());
15179 if (E->getType()->isIntegerType()) {
15180 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15181 APSInt Val;
15182 if (!EvaluateInteger(E, Val, Info))
15183 return false;
15184 Result = APFixedPoint(Val, FXSema);
15185 return true;
15186 } else if (E->getType()->isFixedPointType()) {
15187 return EvaluateFixedPoint(E, Result, Info);
15188 }
15189 return false;
15190}
15191
15192/// Check whether the given declaration can be directly converted to an integral
15193/// rvalue. If not, no diagnostic is produced; there are other things we can
15194/// try.
15195bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15196 // Enums are integer constant exprs.
15197 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15198 // Check for signedness/width mismatches between E type and ECD value.
15199 bool SameSign = (ECD->getInitVal().isSigned()
15201 bool SameWidth = (ECD->getInitVal().getBitWidth()
15202 == Info.Ctx.getIntWidth(E->getType()));
15203 if (SameSign && SameWidth)
15204 return Success(ECD->getInitVal(), E);
15205 else {
15206 // Get rid of mismatch (otherwise Success assertions will fail)
15207 // by computing a new value matching the type of E.
15208 llvm::APSInt Val = ECD->getInitVal();
15209 if (!SameSign)
15210 Val.setIsSigned(!ECD->getInitVal().isSigned());
15211 if (!SameWidth)
15212 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15213 return Success(Val, E);
15214 }
15215 }
15216 return false;
15217}
15218
15219/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15220/// as GCC.
15222 const LangOptions &LangOpts) {
15223 assert(!T->isDependentType() && "unexpected dependent type");
15224
15225 QualType CanTy = T.getCanonicalType();
15226
15227 switch (CanTy->getTypeClass()) {
15228#define TYPE(ID, BASE)
15229#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15230#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15231#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15232#include "clang/AST/TypeNodes.inc"
15233 case Type::Auto:
15234 case Type::DeducedTemplateSpecialization:
15235 llvm_unreachable("unexpected non-canonical or dependent type");
15236
15237 case Type::Builtin:
15238 switch (cast<BuiltinType>(CanTy)->getKind()) {
15239#define BUILTIN_TYPE(ID, SINGLETON_ID)
15240#define SIGNED_TYPE(ID, SINGLETON_ID) \
15241 case BuiltinType::ID: return GCCTypeClass::Integer;
15242#define FLOATING_TYPE(ID, SINGLETON_ID) \
15243 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15244#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15245 case BuiltinType::ID: break;
15246#include "clang/AST/BuiltinTypes.def"
15247 case BuiltinType::Void:
15248 return GCCTypeClass::Void;
15249
15250 case BuiltinType::Bool:
15251 return GCCTypeClass::Bool;
15252
15253 case BuiltinType::Char_U:
15254 case BuiltinType::UChar:
15255 case BuiltinType::WChar_U:
15256 case BuiltinType::Char8:
15257 case BuiltinType::Char16:
15258 case BuiltinType::Char32:
15259 case BuiltinType::UShort:
15260 case BuiltinType::UInt:
15261 case BuiltinType::ULong:
15262 case BuiltinType::ULongLong:
15263 case BuiltinType::UInt128:
15264 return GCCTypeClass::Integer;
15265
15266 case BuiltinType::UShortAccum:
15267 case BuiltinType::UAccum:
15268 case BuiltinType::ULongAccum:
15269 case BuiltinType::UShortFract:
15270 case BuiltinType::UFract:
15271 case BuiltinType::ULongFract:
15272 case BuiltinType::SatUShortAccum:
15273 case BuiltinType::SatUAccum:
15274 case BuiltinType::SatULongAccum:
15275 case BuiltinType::SatUShortFract:
15276 case BuiltinType::SatUFract:
15277 case BuiltinType::SatULongFract:
15278 return GCCTypeClass::None;
15279
15280 case BuiltinType::NullPtr:
15281
15282 case BuiltinType::ObjCId:
15283 case BuiltinType::ObjCClass:
15284 case BuiltinType::ObjCSel:
15285#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15286 case BuiltinType::Id:
15287#include "clang/Basic/OpenCLImageTypes.def"
15288#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15289 case BuiltinType::Id:
15290#include "clang/Basic/OpenCLExtensionTypes.def"
15291 case BuiltinType::OCLSampler:
15292 case BuiltinType::OCLEvent:
15293 case BuiltinType::OCLClkEvent:
15294 case BuiltinType::OCLQueue:
15295 case BuiltinType::OCLReserveID:
15296#define SVE_TYPE(Name, Id, SingletonId) \
15297 case BuiltinType::Id:
15298#include "clang/Basic/AArch64ACLETypes.def"
15299#define PPC_VECTOR_TYPE(Name, Id, Size) \
15300 case BuiltinType::Id:
15301#include "clang/Basic/PPCTypes.def"
15302#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15303#include "clang/Basic/RISCVVTypes.def"
15304#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15305#include "clang/Basic/WebAssemblyReferenceTypes.def"
15306#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15307#include "clang/Basic/AMDGPUTypes.def"
15308#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15309#include "clang/Basic/HLSLIntangibleTypes.def"
15310 return GCCTypeClass::None;
15311
15312 case BuiltinType::Dependent:
15313 llvm_unreachable("unexpected dependent type");
15314 };
15315 llvm_unreachable("unexpected placeholder type");
15316
15317 case Type::Enum:
15318 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15319
15320 case Type::Pointer:
15321 case Type::ConstantArray:
15322 case Type::VariableArray:
15323 case Type::IncompleteArray:
15324 case Type::FunctionNoProto:
15325 case Type::FunctionProto:
15326 case Type::ArrayParameter:
15327 return GCCTypeClass::Pointer;
15328
15329 case Type::MemberPointer:
15330 return CanTy->isMemberDataPointerType()
15333
15334 case Type::Complex:
15335 return GCCTypeClass::Complex;
15336
15337 case Type::Record:
15338 return CanTy->isUnionType() ? GCCTypeClass::Union
15340
15341 case Type::Atomic:
15342 // GCC classifies _Atomic T the same as T.
15344 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15345
15346 case Type::Vector:
15347 case Type::ExtVector:
15348 return GCCTypeClass::Vector;
15349
15350 case Type::BlockPointer:
15351 case Type::ConstantMatrix:
15352 case Type::ObjCObject:
15353 case Type::ObjCInterface:
15354 case Type::ObjCObjectPointer:
15355 case Type::Pipe:
15356 case Type::HLSLAttributedResource:
15357 case Type::HLSLInlineSpirv:
15358 // Classify all other types that don't fit into the regular
15359 // classification the same way.
15360 return GCCTypeClass::None;
15361
15362 case Type::BitInt:
15363 return GCCTypeClass::BitInt;
15364
15365 case Type::LValueReference:
15366 case Type::RValueReference:
15367 llvm_unreachable("invalid type for expression");
15368 }
15369
15370 llvm_unreachable("unexpected type class");
15371}
15372
15373/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15374/// as GCC.
15375static GCCTypeClass
15377 // If no argument was supplied, default to None. This isn't
15378 // ideal, however it is what gcc does.
15379 if (E->getNumArgs() == 0)
15380 return GCCTypeClass::None;
15381
15382 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15383 // being an ICE, but still folds it to a constant using the type of the first
15384 // argument.
15385 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15386}
15387
15388/// EvaluateBuiltinConstantPForLValue - Determine the result of
15389/// __builtin_constant_p when applied to the given pointer.
15390///
15391/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15392/// or it points to the first character of a string literal.
15395 if (Base.isNull()) {
15396 // A null base is acceptable.
15397 return true;
15398 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15399 if (!isa<StringLiteral>(E))
15400 return false;
15401 return LV.getLValueOffset().isZero();
15402 } else if (Base.is<TypeInfoLValue>()) {
15403 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15404 // evaluate to true.
15405 return true;
15406 } else {
15407 // Any other base is not constant enough for GCC.
15408 return false;
15409 }
15410}
15411
15412/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15413/// GCC as we can manage.
15414static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15415 // This evaluation is not permitted to have side-effects, so evaluate it in
15416 // a speculative evaluation context.
15417 SpeculativeEvaluationRAII SpeculativeEval(Info);
15418
15419 // Constant-folding is always enabled for the operand of __builtin_constant_p
15420 // (even when the enclosing evaluation context otherwise requires a strict
15421 // language-specific constant expression).
15422 FoldConstant Fold(Info, true);
15423
15424 QualType ArgType = Arg->getType();
15425
15426 // __builtin_constant_p always has one operand. The rules which gcc follows
15427 // are not precisely documented, but are as follows:
15428 //
15429 // - If the operand is of integral, floating, complex or enumeration type,
15430 // and can be folded to a known value of that type, it returns 1.
15431 // - If the operand can be folded to a pointer to the first character
15432 // of a string literal (or such a pointer cast to an integral type)
15433 // or to a null pointer or an integer cast to a pointer, it returns 1.
15434 //
15435 // Otherwise, it returns 0.
15436 //
15437 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15438 // its support for this did not work prior to GCC 9 and is not yet well
15439 // understood.
15440 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15441 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15442 ArgType->isNullPtrType()) {
15443 APValue V;
15444 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15445 Fold.keepDiagnostics();
15446 return false;
15447 }
15448
15449 // For a pointer (possibly cast to integer), there are special rules.
15450 if (V.getKind() == APValue::LValue)
15452
15453 // Otherwise, any constant value is good enough.
15454 return V.hasValue();
15455 }
15456
15457 // Anything else isn't considered to be sufficiently constant.
15458 return false;
15459}
15460
15461/// Retrieves the "underlying object type" of the given expression,
15462/// as used by __builtin_object_size.
15464 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15465 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15466 return VD->getType();
15467 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15469 return E->getType();
15470 } else if (B.is<TypeInfoLValue>()) {
15471 return B.getTypeInfoType();
15472 } else if (B.is<DynamicAllocLValue>()) {
15473 return B.getDynamicAllocType();
15474 }
15475
15476 return QualType();
15477}
15478
15479/// A more selective version of E->IgnoreParenCasts for
15480/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15481/// to change the type of E.
15482/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15483///
15484/// Always returns an RValue with a pointer representation.
15485static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15486 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15487
15488 const Expr *NoParens = E->IgnoreParens();
15489 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15490 if (Cast == nullptr)
15491 return NoParens;
15492
15493 // We only conservatively allow a few kinds of casts, because this code is
15494 // inherently a simple solution that seeks to support the common case.
15495 auto CastKind = Cast->getCastKind();
15496 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15497 CastKind != CK_AddressSpaceConversion)
15498 return NoParens;
15499
15500 const auto *SubExpr = Cast->getSubExpr();
15501 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15502 return NoParens;
15503 return ignorePointerCastsAndParens(SubExpr);
15504}
15505
15506/// Checks to see if the given LValue's Designator is at the end of the LValue's
15507/// record layout. e.g.
15508/// struct { struct { int a, b; } fst, snd; } obj;
15509/// obj.fst // no
15510/// obj.snd // yes
15511/// obj.fst.a // no
15512/// obj.fst.b // no
15513/// obj.snd.a // no
15514/// obj.snd.b // yes
15515///
15516/// Please note: this function is specialized for how __builtin_object_size
15517/// views "objects".
15518///
15519/// If this encounters an invalid RecordDecl or otherwise cannot determine the
15520/// correct result, it will always return true.
15521static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
15522 assert(!LVal.Designator.Invalid);
15523
15524 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
15525 const RecordDecl *Parent = FD->getParent();
15526 if (Parent->isInvalidDecl() || Parent->isUnion())
15527 return true;
15528 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
15529 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
15530 };
15531
15532 auto &Base = LVal.getLValueBase();
15533 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
15534 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
15535 if (!IsLastOrInvalidFieldDecl(FD))
15536 return false;
15537 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
15538 for (auto *FD : IFD->chain()) {
15539 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
15540 return false;
15541 }
15542 }
15543 }
15544
15545 unsigned I = 0;
15546 QualType BaseType = getType(Base);
15547 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
15548 // If we don't know the array bound, conservatively assume we're looking at
15549 // the final array element.
15550 ++I;
15551 if (BaseType->isIncompleteArrayType())
15552 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
15553 else
15554 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
15555 }
15556
15557 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
15558 const auto &Entry = LVal.Designator.Entries[I];
15559 if (BaseType->isArrayType()) {
15560 // Because __builtin_object_size treats arrays as objects, we can ignore
15561 // the index iff this is the last array in the Designator.
15562 if (I + 1 == E)
15563 return true;
15564 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
15565 uint64_t Index = Entry.getAsArrayIndex();
15566 if (Index + 1 != CAT->getZExtSize())
15567 return false;
15568 BaseType = CAT->getElementType();
15569 } else if (BaseType->isAnyComplexType()) {
15570 const auto *CT = BaseType->castAs<ComplexType>();
15571 uint64_t Index = Entry.getAsArrayIndex();
15572 if (Index != 1)
15573 return false;
15574 BaseType = CT->getElementType();
15575 } else if (auto *FD = getAsField(Entry)) {
15576 if (!IsLastOrInvalidFieldDecl(FD))
15577 return false;
15578 BaseType = FD->getType();
15579 } else {
15580 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
15581 return false;
15582 }
15583 }
15584 return true;
15585}
15586
15587/// Tests to see if the LValue has a user-specified designator (that isn't
15588/// necessarily valid). Note that this always returns 'true' if the LValue has
15589/// an unsized array as its first designator entry, because there's currently no
15590/// way to tell if the user typed *foo or foo[0].
15591static bool refersToCompleteObject(const LValue &LVal) {
15592 if (LVal.Designator.Invalid)
15593 return false;
15594
15595 if (!LVal.Designator.Entries.empty())
15596 return LVal.Designator.isMostDerivedAnUnsizedArray();
15597
15598 if (!LVal.InvalidBase)
15599 return true;
15600
15601 // If `E` is a MemberExpr, then the first part of the designator is hiding in
15602 // the LValueBase.
15603 const auto *E = LVal.Base.dyn_cast<const Expr *>();
15604 return !E || !isa<MemberExpr>(E);
15605}
15606
15607/// Attempts to detect a user writing into a piece of memory that's impossible
15608/// to figure out the size of by just using types.
15609static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
15610 const SubobjectDesignator &Designator = LVal.Designator;
15611 // Notes:
15612 // - Users can only write off of the end when we have an invalid base. Invalid
15613 // bases imply we don't know where the memory came from.
15614 // - We used to be a bit more aggressive here; we'd only be conservative if
15615 // the array at the end was flexible, or if it had 0 or 1 elements. This
15616 // broke some common standard library extensions (PR30346), but was
15617 // otherwise seemingly fine. It may be useful to reintroduce this behavior
15618 // with some sort of list. OTOH, it seems that GCC is always
15619 // conservative with the last element in structs (if it's an array), so our
15620 // current behavior is more compatible than an explicit list approach would
15621 // be.
15622 auto isFlexibleArrayMember = [&] {
15624 FAMKind StrictFlexArraysLevel =
15625 Ctx.getLangOpts().getStrictFlexArraysLevel();
15626
15627 if (Designator.isMostDerivedAnUnsizedArray())
15628 return true;
15629
15630 if (StrictFlexArraysLevel == FAMKind::Default)
15631 return true;
15632
15633 if (Designator.getMostDerivedArraySize() == 0 &&
15634 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
15635 return true;
15636
15637 if (Designator.getMostDerivedArraySize() == 1 &&
15638 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
15639 return true;
15640
15641 return false;
15642 };
15643
15644 return LVal.InvalidBase &&
15645 Designator.Entries.size() == Designator.MostDerivedPathLength &&
15646 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
15647 isDesignatorAtObjectEnd(Ctx, LVal);
15648}
15649
15650/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
15651/// Fails if the conversion would cause loss of precision.
15652static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
15653 CharUnits &Result) {
15654 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
15655 if (Int.ugt(CharUnitsMax))
15656 return false;
15657 Result = CharUnits::fromQuantity(Int.getZExtValue());
15658 return true;
15659}
15660
15661/// If we're evaluating the object size of an instance of a struct that
15662/// contains a flexible array member, add the size of the initializer.
15663static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
15664 const LValue &LV, CharUnits &Size) {
15665 if (!T.isNull() && T->isStructureType() &&
15666 T->castAsRecordDecl()->hasFlexibleArrayMember())
15667 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
15668 if (const auto *VD = dyn_cast<VarDecl>(V))
15669 if (VD->hasInit())
15670 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
15671}
15672
15673/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
15674/// determine how many bytes exist from the beginning of the object to either
15675/// the end of the current subobject, or the end of the object itself, depending
15676/// on what the LValue looks like + the value of Type.
15677///
15678/// If this returns false, the value of Result is undefined.
15679static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
15680 unsigned Type, const LValue &LVal,
15681 CharUnits &EndOffset) {
15682 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
15683
15684 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
15685 if (Ty.isNull())
15686 return false;
15687
15688 Ty = Ty.getNonReferenceType();
15689
15690 if (Ty->isIncompleteType() || Ty->isFunctionType())
15691 return false;
15692
15693 return HandleSizeof(Info, ExprLoc, Ty, Result);
15694 };
15695
15696 // We want to evaluate the size of the entire object. This is a valid fallback
15697 // for when Type=1 and the designator is invalid, because we're asked for an
15698 // upper-bound.
15699 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
15700 // Type=3 wants a lower bound, so we can't fall back to this.
15701 if (Type == 3 && !DetermineForCompleteObject)
15702 return false;
15703
15704 llvm::APInt APEndOffset;
15705 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15706 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15707 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15708
15709 if (LVal.InvalidBase)
15710 return false;
15711
15712 QualType BaseTy = getObjectType(LVal.getLValueBase());
15713 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
15714 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
15715 return Ret;
15716 }
15717
15718 // We want to evaluate the size of a subobject.
15719 const SubobjectDesignator &Designator = LVal.Designator;
15720
15721 // The following is a moderately common idiom in C:
15722 //
15723 // struct Foo { int a; char c[1]; };
15724 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
15725 // strcpy(&F->c[0], Bar);
15726 //
15727 // In order to not break too much legacy code, we need to support it.
15728 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
15729 // If we can resolve this to an alloc_size call, we can hand that back,
15730 // because we know for certain how many bytes there are to write to.
15731 llvm::APInt APEndOffset;
15732 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
15733 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
15734 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
15735
15736 // If we cannot determine the size of the initial allocation, then we can't
15737 // given an accurate upper-bound. However, we are still able to give
15738 // conservative lower-bounds for Type=3.
15739 if (Type == 1)
15740 return false;
15741 }
15742
15743 CharUnits BytesPerElem;
15744 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
15745 return false;
15746
15747 // According to the GCC documentation, we want the size of the subobject
15748 // denoted by the pointer. But that's not quite right -- what we actually
15749 // want is the size of the immediately-enclosing array, if there is one.
15750 int64_t ElemsRemaining;
15751 if (Designator.MostDerivedIsArrayElement &&
15752 Designator.Entries.size() == Designator.MostDerivedPathLength) {
15753 uint64_t ArraySize = Designator.getMostDerivedArraySize();
15754 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
15755 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
15756 } else {
15757 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
15758 }
15759
15760 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
15761 return true;
15762}
15763
15764/// Tries to evaluate the __builtin_object_size for @p E. If successful,
15765/// returns true and stores the result in @p Size.
15766///
15767/// If @p WasError is non-null, this will report whether the failure to evaluate
15768/// is to be treated as an Error in IntExprEvaluator.
15769static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
15770 EvalInfo &Info, uint64_t &Size) {
15771 // Determine the denoted object.
15772 LValue LVal;
15773 {
15774 // The operand of __builtin_object_size is never evaluated for side-effects.
15775 // If there are any, but we can determine the pointed-to object anyway, then
15776 // ignore the side-effects.
15777 SpeculativeEvaluationRAII SpeculativeEval(Info);
15778 IgnoreSideEffectsRAII Fold(Info);
15779
15780 if (E->isGLValue()) {
15781 // It's possible for us to be given GLValues if we're called via
15782 // Expr::tryEvaluateObjectSize.
15783 APValue RVal;
15784 if (!EvaluateAsRValue(Info, E, RVal))
15785 return false;
15786 LVal.setFrom(Info.Ctx, RVal);
15787 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
15788 /*InvalidBaseOK=*/true))
15789 return false;
15790 }
15791
15792 // If we point to before the start of the object, there are no accessible
15793 // bytes.
15794 if (LVal.getLValueOffset().isNegative()) {
15795 Size = 0;
15796 return true;
15797 }
15798
15799 CharUnits EndOffset;
15800 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
15801 return false;
15802
15803 // If we've fallen outside of the end offset, just pretend there's nothing to
15804 // write to/read from.
15805 if (EndOffset <= LVal.getLValueOffset())
15806 Size = 0;
15807 else
15808 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
15809 return true;
15810}
15811
15812bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
15813 if (!IsConstantEvaluatedBuiltinCall(E))
15814 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15815 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
15816}
15817
15818static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
15819 APValue &Val, APSInt &Alignment) {
15820 QualType SrcTy = E->getArg(0)->getType();
15821 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
15822 return false;
15823 // Even though we are evaluating integer expressions we could get a pointer
15824 // argument for the __builtin_is_aligned() case.
15825 if (SrcTy->isPointerType()) {
15826 LValue Ptr;
15827 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
15828 return false;
15829 Ptr.moveInto(Val);
15830 } else if (!SrcTy->isIntegralOrEnumerationType()) {
15831 Info.FFDiag(E->getArg(0));
15832 return false;
15833 } else {
15834 APSInt SrcInt;
15835 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
15836 return false;
15837 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
15838 "Bit widths must be the same");
15839 Val = APValue(SrcInt);
15840 }
15841 assert(Val.hasValue());
15842 return true;
15843}
15844
15845bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
15846 unsigned BuiltinOp) {
15847 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
15848 Fn) {
15849 APValue SourceLHS, SourceRHS;
15850 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
15851 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
15852 return false;
15853
15854 unsigned SourceLen = SourceLHS.getVectorLength();
15855 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
15856 QualType ElemQT = VT->getElementType();
15857 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
15858
15859 APInt AWide(LaneWidth * SourceLen, 0);
15860 APInt BWide(LaneWidth * SourceLen, 0);
15861
15862 for (unsigned I = 0; I != SourceLen; ++I) {
15863 APInt ALane;
15864 APInt BLane;
15865 if (ElemQT->isIntegerType()) { // Get value.
15866 ALane = SourceLHS.getVectorElt(I).getInt();
15867 BLane = SourceRHS.getVectorElt(I).getInt();
15868 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
15869 ALane =
15870 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15871 BLane =
15872 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
15873 } else { // Must be integer or floating type.
15874 return false;
15875 }
15876 AWide.insertBits(ALane, I * LaneWidth);
15877 BWide.insertBits(BLane, I * LaneWidth);
15878 }
15879 return Success(Fn(AWide, BWide), E);
15880 };
15881
15882 auto HandleMaskBinOp =
15883 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
15884 -> bool {
15885 APValue LHS, RHS;
15886 if (!Evaluate(LHS, Info, E->getArg(0)) ||
15887 !Evaluate(RHS, Info, E->getArg(1)))
15888 return false;
15889
15890 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
15891
15892 return Success(APValue(ResultInt), E);
15893 };
15894
15895 switch (BuiltinOp) {
15896 default:
15897 return false;
15898
15899 case Builtin::BI__builtin_dynamic_object_size:
15900 case Builtin::BI__builtin_object_size: {
15901 // The type was checked when we built the expression.
15902 unsigned Type =
15903 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
15904 assert(Type <= 3 && "unexpected type");
15905
15906 uint64_t Size;
15907 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
15908 return Success(Size, E);
15909
15910 if (E->getArg(0)->HasSideEffects(Info.Ctx))
15911 return Success((Type & 2) ? 0 : -1, E);
15912
15913 // Expression had no side effects, but we couldn't statically determine the
15914 // size of the referenced object.
15915 switch (Info.EvalMode) {
15916 case EvaluationMode::ConstantExpression:
15917 case EvaluationMode::ConstantFold:
15918 case EvaluationMode::IgnoreSideEffects:
15919 // Leave it to IR generation.
15920 return Error(E);
15921 case EvaluationMode::ConstantExpressionUnevaluated:
15922 // Reduce it to a constant now.
15923 return Success((Type & 2) ? 0 : -1, E);
15924 }
15925
15926 llvm_unreachable("unexpected EvalMode");
15927 }
15928
15929 case Builtin::BI__builtin_os_log_format_buffer_size: {
15930 analyze_os_log::OSLogBufferLayout Layout;
15931 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
15932 return Success(Layout.size().getQuantity(), E);
15933 }
15934
15935 case Builtin::BI__builtin_is_aligned: {
15936 APValue Src;
15937 APSInt Alignment;
15938 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15939 return false;
15940 if (Src.isLValue()) {
15941 // If we evaluated a pointer, check the minimum known alignment.
15942 LValue Ptr;
15943 Ptr.setFrom(Info.Ctx, Src);
15944 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
15945 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
15946 // We can return true if the known alignment at the computed offset is
15947 // greater than the requested alignment.
15948 assert(PtrAlign.isPowerOfTwo());
15949 assert(Alignment.isPowerOf2());
15950 if (PtrAlign.getQuantity() >= Alignment)
15951 return Success(1, E);
15952 // If the alignment is not known to be sufficient, some cases could still
15953 // be aligned at run time. However, if the requested alignment is less or
15954 // equal to the base alignment and the offset is not aligned, we know that
15955 // the run-time value can never be aligned.
15956 if (BaseAlignment.getQuantity() >= Alignment &&
15957 PtrAlign.getQuantity() < Alignment)
15958 return Success(0, E);
15959 // Otherwise we can't infer whether the value is sufficiently aligned.
15960 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
15961 // in cases where we can't fully evaluate the pointer.
15962 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
15963 << Alignment;
15964 return false;
15965 }
15966 assert(Src.isInt());
15967 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
15968 }
15969 case Builtin::BI__builtin_align_up: {
15970 APValue Src;
15971 APSInt Alignment;
15972 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15973 return false;
15974 if (!Src.isInt())
15975 return Error(E);
15976 APSInt AlignedVal =
15977 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
15978 Src.getInt().isUnsigned());
15979 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15980 return Success(AlignedVal, E);
15981 }
15982 case Builtin::BI__builtin_align_down: {
15983 APValue Src;
15984 APSInt Alignment;
15985 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
15986 return false;
15987 if (!Src.isInt())
15988 return Error(E);
15989 APSInt AlignedVal =
15990 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
15991 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
15992 return Success(AlignedVal, E);
15993 }
15994
15995 case Builtin::BI__builtin_bitreverse8:
15996 case Builtin::BI__builtin_bitreverse16:
15997 case Builtin::BI__builtin_bitreverse32:
15998 case Builtin::BI__builtin_bitreverse64:
15999 case Builtin::BI__builtin_elementwise_bitreverse: {
16000 APSInt Val;
16001 if (!EvaluateInteger(E->getArg(0), Val, Info))
16002 return false;
16003
16004 return Success(Val.reverseBits(), E);
16005 }
16006 case Builtin::BI__builtin_bswapg:
16007 case Builtin::BI__builtin_bswap16:
16008 case Builtin::BI__builtin_bswap32:
16009 case Builtin::BI__builtin_bswap64: {
16010 APSInt Val;
16011 if (!EvaluateInteger(E->getArg(0), Val, Info))
16012 return false;
16013 if (Val.getBitWidth() == 8)
16014 return Success(Val, E);
16015
16016 return Success(Val.byteSwap(), E);
16017 }
16018
16019 case Builtin::BI__builtin_classify_type:
16020 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16021
16022 case Builtin::BI__builtin_clrsb:
16023 case Builtin::BI__builtin_clrsbl:
16024 case Builtin::BI__builtin_clrsbll: {
16025 APSInt Val;
16026 if (!EvaluateInteger(E->getArg(0), Val, Info))
16027 return false;
16028
16029 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16030 }
16031
16032 case Builtin::BI__builtin_clz:
16033 case Builtin::BI__builtin_clzl:
16034 case Builtin::BI__builtin_clzll:
16035 case Builtin::BI__builtin_clzs:
16036 case Builtin::BI__builtin_clzg:
16037 case Builtin::BI__builtin_elementwise_clzg:
16038 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16039 case Builtin::BI__lzcnt:
16040 case Builtin::BI__lzcnt64: {
16041 APSInt Val;
16042 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16043 APValue Vec;
16044 if (!EvaluateVector(E->getArg(0), Vec, Info))
16045 return false;
16046 Val = ConvertBoolVectorToInt(Vec);
16047 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16048 return false;
16049 }
16050
16051 std::optional<APSInt> Fallback;
16052 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16053 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16054 E->getNumArgs() > 1) {
16055 APSInt FallbackTemp;
16056 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16057 return false;
16058 Fallback = FallbackTemp;
16059 }
16060
16061 if (!Val) {
16062 if (Fallback)
16063 return Success(*Fallback, E);
16064
16065 // When the argument is 0, the result of GCC builtins is undefined,
16066 // whereas for Microsoft intrinsics, the result is the bit-width of the
16067 // argument.
16068 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16069 BuiltinOp != Builtin::BI__lzcnt &&
16070 BuiltinOp != Builtin::BI__lzcnt64;
16071
16072 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16073 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16074 << /*IsTrailing=*/false;
16075 }
16076
16077 if (ZeroIsUndefined)
16078 return Error(E);
16079 }
16080
16081 return Success(Val.countl_zero(), E);
16082 }
16083
16084 case Builtin::BI__builtin_constant_p: {
16085 const Expr *Arg = E->getArg(0);
16086 if (EvaluateBuiltinConstantP(Info, Arg))
16087 return Success(true, E);
16088 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16089 // Outside a constant context, eagerly evaluate to false in the presence
16090 // of side-effects in order to avoid -Wunsequenced false-positives in
16091 // a branch on __builtin_constant_p(expr).
16092 return Success(false, E);
16093 }
16094 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16095 return false;
16096 }
16097
16098 case Builtin::BI__noop:
16099 // __noop always evaluates successfully and returns 0.
16100 return Success(0, E);
16101
16102 case Builtin::BI__builtin_is_constant_evaluated: {
16103 const auto *Callee = Info.CurrentCall->getCallee();
16104 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16105 (Info.CallStackDepth == 1 ||
16106 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16107 Callee->getIdentifier() &&
16108 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16109 // FIXME: Find a better way to avoid duplicated diagnostics.
16110 if (Info.EvalStatus.Diag)
16111 Info.report((Info.CallStackDepth == 1)
16112 ? E->getExprLoc()
16113 : Info.CurrentCall->getCallRange().getBegin(),
16114 diag::warn_is_constant_evaluated_always_true_constexpr)
16115 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16116 : "std::is_constant_evaluated");
16117 }
16118
16119 return Success(Info.InConstantContext, E);
16120 }
16121
16122 case Builtin::BI__builtin_is_within_lifetime:
16123 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16124 return Success(*result, E);
16125 return false;
16126
16127 case Builtin::BI__builtin_ctz:
16128 case Builtin::BI__builtin_ctzl:
16129 case Builtin::BI__builtin_ctzll:
16130 case Builtin::BI__builtin_ctzs:
16131 case Builtin::BI__builtin_ctzg:
16132 case Builtin::BI__builtin_elementwise_ctzg: {
16133 APSInt Val;
16134 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16135 APValue Vec;
16136 if (!EvaluateVector(E->getArg(0), Vec, Info))
16137 return false;
16138 Val = ConvertBoolVectorToInt(Vec);
16139 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16140 return false;
16141 }
16142
16143 std::optional<APSInt> Fallback;
16144 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16145 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16146 E->getNumArgs() > 1) {
16147 APSInt FallbackTemp;
16148 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16149 return false;
16150 Fallback = FallbackTemp;
16151 }
16152
16153 if (!Val) {
16154 if (Fallback)
16155 return Success(*Fallback, E);
16156
16157 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16158 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16159 << /*IsTrailing=*/true;
16160 }
16161 return Error(E);
16162 }
16163
16164 return Success(Val.countr_zero(), E);
16165 }
16166
16167 case Builtin::BI__builtin_eh_return_data_regno: {
16168 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16169 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16170 return Success(Operand, E);
16171 }
16172
16173 case Builtin::BI__builtin_elementwise_abs: {
16174 APSInt Val;
16175 if (!EvaluateInteger(E->getArg(0), Val, Info))
16176 return false;
16177
16178 return Success(Val.abs(), E);
16179 }
16180
16181 case Builtin::BI__builtin_expect:
16182 case Builtin::BI__builtin_expect_with_probability:
16183 return Visit(E->getArg(0));
16184
16185 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16186 const auto *Literal =
16188 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16189 return Success(Result, E);
16190 }
16191
16192 case Builtin::BI__builtin_infer_alloc_token: {
16193 // If we fail to infer a type, this fails to be a constant expression; this
16194 // can be checked with __builtin_constant_p(...).
16195 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16196 if (AllocType.isNull())
16197 return Error(
16198 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16199 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16200 if (!ATMD)
16201 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16202 auto Mode =
16203 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16204 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16205 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16206 uint64_t MaxTokens =
16207 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16208 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16209 if (!MaybeToken)
16210 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16211 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16212 }
16213
16214 case Builtin::BI__builtin_ffs:
16215 case Builtin::BI__builtin_ffsl:
16216 case Builtin::BI__builtin_ffsll: {
16217 APSInt Val;
16218 if (!EvaluateInteger(E->getArg(0), Val, Info))
16219 return false;
16220
16221 unsigned N = Val.countr_zero();
16222 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16223 }
16224
16225 case Builtin::BI__builtin_fpclassify: {
16226 APFloat Val(0.0);
16227 if (!EvaluateFloat(E->getArg(5), Val, Info))
16228 return false;
16229 unsigned Arg;
16230 switch (Val.getCategory()) {
16231 case APFloat::fcNaN: Arg = 0; break;
16232 case APFloat::fcInfinity: Arg = 1; break;
16233 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16234 case APFloat::fcZero: Arg = 4; break;
16235 }
16236 return Visit(E->getArg(Arg));
16237 }
16238
16239 case Builtin::BI__builtin_isinf_sign: {
16240 APFloat Val(0.0);
16241 return EvaluateFloat(E->getArg(0), Val, Info) &&
16242 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16243 }
16244
16245 case Builtin::BI__builtin_isinf: {
16246 APFloat Val(0.0);
16247 return EvaluateFloat(E->getArg(0), Val, Info) &&
16248 Success(Val.isInfinity() ? 1 : 0, E);
16249 }
16250
16251 case Builtin::BI__builtin_isfinite: {
16252 APFloat Val(0.0);
16253 return EvaluateFloat(E->getArg(0), Val, Info) &&
16254 Success(Val.isFinite() ? 1 : 0, E);
16255 }
16256
16257 case Builtin::BI__builtin_isnan: {
16258 APFloat Val(0.0);
16259 return EvaluateFloat(E->getArg(0), Val, Info) &&
16260 Success(Val.isNaN() ? 1 : 0, E);
16261 }
16262
16263 case Builtin::BI__builtin_isnormal: {
16264 APFloat Val(0.0);
16265 return EvaluateFloat(E->getArg(0), Val, Info) &&
16266 Success(Val.isNormal() ? 1 : 0, E);
16267 }
16268
16269 case Builtin::BI__builtin_issubnormal: {
16270 APFloat Val(0.0);
16271 return EvaluateFloat(E->getArg(0), Val, Info) &&
16272 Success(Val.isDenormal() ? 1 : 0, E);
16273 }
16274
16275 case Builtin::BI__builtin_iszero: {
16276 APFloat Val(0.0);
16277 return EvaluateFloat(E->getArg(0), Val, Info) &&
16278 Success(Val.isZero() ? 1 : 0, E);
16279 }
16280
16281 case Builtin::BI__builtin_signbit:
16282 case Builtin::BI__builtin_signbitf:
16283 case Builtin::BI__builtin_signbitl: {
16284 APFloat Val(0.0);
16285 return EvaluateFloat(E->getArg(0), Val, Info) &&
16286 Success(Val.isNegative() ? 1 : 0, E);
16287 }
16288
16289 case Builtin::BI__builtin_isgreater:
16290 case Builtin::BI__builtin_isgreaterequal:
16291 case Builtin::BI__builtin_isless:
16292 case Builtin::BI__builtin_islessequal:
16293 case Builtin::BI__builtin_islessgreater:
16294 case Builtin::BI__builtin_isunordered: {
16295 APFloat LHS(0.0);
16296 APFloat RHS(0.0);
16297 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16298 !EvaluateFloat(E->getArg(1), RHS, Info))
16299 return false;
16300
16301 return Success(
16302 [&] {
16303 switch (BuiltinOp) {
16304 case Builtin::BI__builtin_isgreater:
16305 return LHS > RHS;
16306 case Builtin::BI__builtin_isgreaterequal:
16307 return LHS >= RHS;
16308 case Builtin::BI__builtin_isless:
16309 return LHS < RHS;
16310 case Builtin::BI__builtin_islessequal:
16311 return LHS <= RHS;
16312 case Builtin::BI__builtin_islessgreater: {
16313 APFloat::cmpResult cmp = LHS.compare(RHS);
16314 return cmp == APFloat::cmpResult::cmpLessThan ||
16315 cmp == APFloat::cmpResult::cmpGreaterThan;
16316 }
16317 case Builtin::BI__builtin_isunordered:
16318 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16319 default:
16320 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16321 "point comparison function");
16322 }
16323 }()
16324 ? 1
16325 : 0,
16326 E);
16327 }
16328
16329 case Builtin::BI__builtin_issignaling: {
16330 APFloat Val(0.0);
16331 return EvaluateFloat(E->getArg(0), Val, Info) &&
16332 Success(Val.isSignaling() ? 1 : 0, E);
16333 }
16334
16335 case Builtin::BI__builtin_isfpclass: {
16336 APSInt MaskVal;
16337 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16338 return false;
16339 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16340 APFloat Val(0.0);
16341 return EvaluateFloat(E->getArg(0), Val, Info) &&
16342 Success((Val.classify() & Test) ? 1 : 0, E);
16343 }
16344
16345 case Builtin::BI__builtin_parity:
16346 case Builtin::BI__builtin_parityl:
16347 case Builtin::BI__builtin_parityll: {
16348 APSInt Val;
16349 if (!EvaluateInteger(E->getArg(0), Val, Info))
16350 return false;
16351
16352 return Success(Val.popcount() % 2, E);
16353 }
16354
16355 case Builtin::BI__builtin_abs:
16356 case Builtin::BI__builtin_labs:
16357 case Builtin::BI__builtin_llabs: {
16358 APSInt Val;
16359 if (!EvaluateInteger(E->getArg(0), Val, Info))
16360 return false;
16361 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16362 /*IsUnsigned=*/false))
16363 return false;
16364 if (Val.isNegative())
16365 Val.negate();
16366 return Success(Val, E);
16367 }
16368
16369 case Builtin::BI__builtin_popcount:
16370 case Builtin::BI__builtin_popcountl:
16371 case Builtin::BI__builtin_popcountll:
16372 case Builtin::BI__builtin_popcountg:
16373 case Builtin::BI__builtin_elementwise_popcount:
16374 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16375 case Builtin::BI__popcnt:
16376 case Builtin::BI__popcnt64: {
16377 APSInt Val;
16378 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16379 APValue Vec;
16380 if (!EvaluateVector(E->getArg(0), Vec, Info))
16381 return false;
16382 Val = ConvertBoolVectorToInt(Vec);
16383 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16384 return false;
16385 }
16386
16387 return Success(Val.popcount(), E);
16388 }
16389
16390 case Builtin::BI__builtin_rotateleft8:
16391 case Builtin::BI__builtin_rotateleft16:
16392 case Builtin::BI__builtin_rotateleft32:
16393 case Builtin::BI__builtin_rotateleft64:
16394 case Builtin::BI_rotl8: // Microsoft variants of rotate right
16395 case Builtin::BI_rotl16:
16396 case Builtin::BI_rotl:
16397 case Builtin::BI_lrotl:
16398 case Builtin::BI_rotl64: {
16399 APSInt Val, Amt;
16400 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16401 !EvaluateInteger(E->getArg(1), Amt, Info))
16402 return false;
16403
16404 return Success(Val.rotl(Amt), E);
16405 }
16406
16407 case Builtin::BI__builtin_rotateright8:
16408 case Builtin::BI__builtin_rotateright16:
16409 case Builtin::BI__builtin_rotateright32:
16410 case Builtin::BI__builtin_rotateright64:
16411 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16412 case Builtin::BI_rotr16:
16413 case Builtin::BI_rotr:
16414 case Builtin::BI_lrotr:
16415 case Builtin::BI_rotr64: {
16416 APSInt Val, Amt;
16417 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16418 !EvaluateInteger(E->getArg(1), Amt, Info))
16419 return false;
16420
16421 return Success(Val.rotr(Amt), E);
16422 }
16423
16424 case Builtin::BI__builtin_elementwise_add_sat: {
16425 APSInt LHS, RHS;
16426 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16427 !EvaluateInteger(E->getArg(1), RHS, Info))
16428 return false;
16429
16430 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
16431 return Success(APSInt(Result, !LHS.isSigned()), E);
16432 }
16433 case Builtin::BI__builtin_elementwise_sub_sat: {
16434 APSInt LHS, RHS;
16435 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16436 !EvaluateInteger(E->getArg(1), RHS, Info))
16437 return false;
16438
16439 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
16440 return Success(APSInt(Result, !LHS.isSigned()), E);
16441 }
16442 case Builtin::BI__builtin_elementwise_max: {
16443 APSInt LHS, RHS;
16444 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16445 !EvaluateInteger(E->getArg(1), RHS, Info))
16446 return false;
16447
16448 APInt Result = std::max(LHS, RHS);
16449 return Success(APSInt(Result, !LHS.isSigned()), E);
16450 }
16451 case Builtin::BI__builtin_elementwise_min: {
16452 APSInt LHS, RHS;
16453 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16454 !EvaluateInteger(E->getArg(1), RHS, Info))
16455 return false;
16456
16457 APInt Result = std::min(LHS, RHS);
16458 return Success(APSInt(Result, !LHS.isSigned()), E);
16459 }
16460 case Builtin::BI__builtin_elementwise_fshl:
16461 case Builtin::BI__builtin_elementwise_fshr: {
16462 APSInt Hi, Lo, Shift;
16463 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
16464 !EvaluateInteger(E->getArg(1), Lo, Info) ||
16465 !EvaluateInteger(E->getArg(2), Shift, Info))
16466 return false;
16467
16468 switch (BuiltinOp) {
16469 case Builtin::BI__builtin_elementwise_fshl: {
16470 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
16471 return Success(Result, E);
16472 }
16473 case Builtin::BI__builtin_elementwise_fshr: {
16474 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
16475 return Success(Result, E);
16476 }
16477 }
16478 llvm_unreachable("Fully covered switch above");
16479 }
16480 case Builtin::BIstrlen:
16481 case Builtin::BIwcslen:
16482 // A call to strlen is not a constant expression.
16483 if (Info.getLangOpts().CPlusPlus11)
16484 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16485 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16486 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16487 else
16488 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16489 [[fallthrough]];
16490 case Builtin::BI__builtin_strlen:
16491 case Builtin::BI__builtin_wcslen: {
16492 // As an extension, we support __builtin_strlen() as a constant expression,
16493 // and support folding strlen() to a constant.
16494 uint64_t StrLen;
16495 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
16496 return Success(StrLen, E);
16497 return false;
16498 }
16499
16500 case Builtin::BIstrcmp:
16501 case Builtin::BIwcscmp:
16502 case Builtin::BIstrncmp:
16503 case Builtin::BIwcsncmp:
16504 case Builtin::BImemcmp:
16505 case Builtin::BIbcmp:
16506 case Builtin::BIwmemcmp:
16507 // A call to strlen is not a constant expression.
16508 if (Info.getLangOpts().CPlusPlus11)
16509 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16510 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16511 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16512 else
16513 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16514 [[fallthrough]];
16515 case Builtin::BI__builtin_strcmp:
16516 case Builtin::BI__builtin_wcscmp:
16517 case Builtin::BI__builtin_strncmp:
16518 case Builtin::BI__builtin_wcsncmp:
16519 case Builtin::BI__builtin_memcmp:
16520 case Builtin::BI__builtin_bcmp:
16521 case Builtin::BI__builtin_wmemcmp: {
16522 LValue String1, String2;
16523 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
16524 !EvaluatePointer(E->getArg(1), String2, Info))
16525 return false;
16526
16527 uint64_t MaxLength = uint64_t(-1);
16528 if (BuiltinOp != Builtin::BIstrcmp &&
16529 BuiltinOp != Builtin::BIwcscmp &&
16530 BuiltinOp != Builtin::BI__builtin_strcmp &&
16531 BuiltinOp != Builtin::BI__builtin_wcscmp) {
16532 APSInt N;
16533 if (!EvaluateInteger(E->getArg(2), N, Info))
16534 return false;
16535 MaxLength = N.getZExtValue();
16536 }
16537
16538 // Empty substrings compare equal by definition.
16539 if (MaxLength == 0u)
16540 return Success(0, E);
16541
16542 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16543 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16544 String1.Designator.Invalid || String2.Designator.Invalid)
16545 return false;
16546
16547 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
16548 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
16549
16550 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
16551 BuiltinOp == Builtin::BIbcmp ||
16552 BuiltinOp == Builtin::BI__builtin_memcmp ||
16553 BuiltinOp == Builtin::BI__builtin_bcmp;
16554
16555 assert(IsRawByte ||
16556 (Info.Ctx.hasSameUnqualifiedType(
16557 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
16558 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
16559
16560 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
16561 // 'char8_t', but no other types.
16562 if (IsRawByte &&
16563 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
16564 // FIXME: Consider using our bit_cast implementation to support this.
16565 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
16566 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
16567 << CharTy2;
16568 return false;
16569 }
16570
16571 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
16572 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
16573 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
16574 Char1.isInt() && Char2.isInt();
16575 };
16576 const auto &AdvanceElems = [&] {
16577 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
16578 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
16579 };
16580
16581 bool StopAtNull =
16582 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
16583 BuiltinOp != Builtin::BIwmemcmp &&
16584 BuiltinOp != Builtin::BI__builtin_memcmp &&
16585 BuiltinOp != Builtin::BI__builtin_bcmp &&
16586 BuiltinOp != Builtin::BI__builtin_wmemcmp);
16587 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
16588 BuiltinOp == Builtin::BIwcsncmp ||
16589 BuiltinOp == Builtin::BIwmemcmp ||
16590 BuiltinOp == Builtin::BI__builtin_wcscmp ||
16591 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
16592 BuiltinOp == Builtin::BI__builtin_wmemcmp;
16593
16594 for (; MaxLength; --MaxLength) {
16595 APValue Char1, Char2;
16596 if (!ReadCurElems(Char1, Char2))
16597 return false;
16598 if (Char1.getInt().ne(Char2.getInt())) {
16599 if (IsWide) // wmemcmp compares with wchar_t signedness.
16600 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
16601 // memcmp always compares unsigned chars.
16602 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
16603 }
16604 if (StopAtNull && !Char1.getInt())
16605 return Success(0, E);
16606 assert(!(StopAtNull && !Char2.getInt()));
16607 if (!AdvanceElems())
16608 return false;
16609 }
16610 // We hit the strncmp / memcmp limit.
16611 return Success(0, E);
16612 }
16613
16614 case Builtin::BI__atomic_always_lock_free:
16615 case Builtin::BI__atomic_is_lock_free:
16616 case Builtin::BI__c11_atomic_is_lock_free: {
16617 APSInt SizeVal;
16618 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
16619 return false;
16620
16621 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
16622 // of two less than or equal to the maximum inline atomic width, we know it
16623 // is lock-free. If the size isn't a power of two, or greater than the
16624 // maximum alignment where we promote atomics, we know it is not lock-free
16625 // (at least not in the sense of atomic_is_lock_free). Otherwise,
16626 // the answer can only be determined at runtime; for example, 16-byte
16627 // atomics have lock-free implementations on some, but not all,
16628 // x86-64 processors.
16629
16630 // Check power-of-two.
16631 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
16632 if (Size.isPowerOfTwo()) {
16633 // Check against inlining width.
16634 unsigned InlineWidthBits =
16636 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
16637 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
16638 Size == CharUnits::One())
16639 return Success(1, E);
16640
16641 // If the pointer argument can be evaluated to a compile-time constant
16642 // integer (or nullptr), check if that value is appropriately aligned.
16643 const Expr *PtrArg = E->getArg(1);
16644 Expr::EvalResult ExprResult;
16645 APSInt IntResult;
16646 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
16647 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
16648 Info.Ctx) &&
16649 IntResult.isAligned(Size.getAsAlign()))
16650 return Success(1, E);
16651
16652 // Otherwise, check if the type's alignment against Size.
16653 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
16654 // Drop the potential implicit-cast to 'const volatile void*', getting
16655 // the underlying type.
16656 if (ICE->getCastKind() == CK_BitCast)
16657 PtrArg = ICE->getSubExpr();
16658 }
16659
16660 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
16661 QualType PointeeType = PtrTy->getPointeeType();
16662 if (!PointeeType->isIncompleteType() &&
16663 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
16664 // OK, we will inline operations on this object.
16665 return Success(1, E);
16666 }
16667 }
16668 }
16669 }
16670
16671 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
16672 Success(0, E) : Error(E);
16673 }
16674 case Builtin::BI__builtin_addcb:
16675 case Builtin::BI__builtin_addcs:
16676 case Builtin::BI__builtin_addc:
16677 case Builtin::BI__builtin_addcl:
16678 case Builtin::BI__builtin_addcll:
16679 case Builtin::BI__builtin_subcb:
16680 case Builtin::BI__builtin_subcs:
16681 case Builtin::BI__builtin_subc:
16682 case Builtin::BI__builtin_subcl:
16683 case Builtin::BI__builtin_subcll: {
16684 LValue CarryOutLValue;
16685 APSInt LHS, RHS, CarryIn, CarryOut, Result;
16686 QualType ResultType = E->getArg(0)->getType();
16687 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16688 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16689 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
16690 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
16691 return false;
16692 // Copy the number of bits and sign.
16693 Result = LHS;
16694 CarryOut = LHS;
16695
16696 bool FirstOverflowed = false;
16697 bool SecondOverflowed = false;
16698 switch (BuiltinOp) {
16699 default:
16700 llvm_unreachable("Invalid value for BuiltinOp");
16701 case Builtin::BI__builtin_addcb:
16702 case Builtin::BI__builtin_addcs:
16703 case Builtin::BI__builtin_addc:
16704 case Builtin::BI__builtin_addcl:
16705 case Builtin::BI__builtin_addcll:
16706 Result =
16707 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
16708 break;
16709 case Builtin::BI__builtin_subcb:
16710 case Builtin::BI__builtin_subcs:
16711 case Builtin::BI__builtin_subc:
16712 case Builtin::BI__builtin_subcl:
16713 case Builtin::BI__builtin_subcll:
16714 Result =
16715 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
16716 break;
16717 }
16718
16719 // It is possible for both overflows to happen but CGBuiltin uses an OR so
16720 // this is consistent.
16721 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
16722 APValue APV{CarryOut};
16723 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
16724 return false;
16725 return Success(Result, E);
16726 }
16727 case Builtin::BI__builtin_add_overflow:
16728 case Builtin::BI__builtin_sub_overflow:
16729 case Builtin::BI__builtin_mul_overflow:
16730 case Builtin::BI__builtin_sadd_overflow:
16731 case Builtin::BI__builtin_uadd_overflow:
16732 case Builtin::BI__builtin_uaddl_overflow:
16733 case Builtin::BI__builtin_uaddll_overflow:
16734 case Builtin::BI__builtin_usub_overflow:
16735 case Builtin::BI__builtin_usubl_overflow:
16736 case Builtin::BI__builtin_usubll_overflow:
16737 case Builtin::BI__builtin_umul_overflow:
16738 case Builtin::BI__builtin_umull_overflow:
16739 case Builtin::BI__builtin_umulll_overflow:
16740 case Builtin::BI__builtin_saddl_overflow:
16741 case Builtin::BI__builtin_saddll_overflow:
16742 case Builtin::BI__builtin_ssub_overflow:
16743 case Builtin::BI__builtin_ssubl_overflow:
16744 case Builtin::BI__builtin_ssubll_overflow:
16745 case Builtin::BI__builtin_smul_overflow:
16746 case Builtin::BI__builtin_smull_overflow:
16747 case Builtin::BI__builtin_smulll_overflow: {
16748 LValue ResultLValue;
16749 APSInt LHS, RHS;
16750
16751 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
16752 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16753 !EvaluateInteger(E->getArg(1), RHS, Info) ||
16754 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
16755 return false;
16756
16757 APSInt Result;
16758 bool DidOverflow = false;
16759
16760 // If the types don't have to match, enlarge all 3 to the largest of them.
16761 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16762 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16763 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16764 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
16766 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
16768 uint64_t LHSSize = LHS.getBitWidth();
16769 uint64_t RHSSize = RHS.getBitWidth();
16770 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
16771 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
16772
16773 // Add an additional bit if the signedness isn't uniformly agreed to. We
16774 // could do this ONLY if there is a signed and an unsigned that both have
16775 // MaxBits, but the code to check that is pretty nasty. The issue will be
16776 // caught in the shrink-to-result later anyway.
16777 if (IsSigned && !AllSigned)
16778 ++MaxBits;
16779
16780 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
16781 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
16782 Result = APSInt(MaxBits, !IsSigned);
16783 }
16784
16785 // Find largest int.
16786 switch (BuiltinOp) {
16787 default:
16788 llvm_unreachable("Invalid value for BuiltinOp");
16789 case Builtin::BI__builtin_add_overflow:
16790 case Builtin::BI__builtin_sadd_overflow:
16791 case Builtin::BI__builtin_saddl_overflow:
16792 case Builtin::BI__builtin_saddll_overflow:
16793 case Builtin::BI__builtin_uadd_overflow:
16794 case Builtin::BI__builtin_uaddl_overflow:
16795 case Builtin::BI__builtin_uaddll_overflow:
16796 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
16797 : LHS.uadd_ov(RHS, DidOverflow);
16798 break;
16799 case Builtin::BI__builtin_sub_overflow:
16800 case Builtin::BI__builtin_ssub_overflow:
16801 case Builtin::BI__builtin_ssubl_overflow:
16802 case Builtin::BI__builtin_ssubll_overflow:
16803 case Builtin::BI__builtin_usub_overflow:
16804 case Builtin::BI__builtin_usubl_overflow:
16805 case Builtin::BI__builtin_usubll_overflow:
16806 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
16807 : LHS.usub_ov(RHS, DidOverflow);
16808 break;
16809 case Builtin::BI__builtin_mul_overflow:
16810 case Builtin::BI__builtin_smul_overflow:
16811 case Builtin::BI__builtin_smull_overflow:
16812 case Builtin::BI__builtin_smulll_overflow:
16813 case Builtin::BI__builtin_umul_overflow:
16814 case Builtin::BI__builtin_umull_overflow:
16815 case Builtin::BI__builtin_umulll_overflow:
16816 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
16817 : LHS.umul_ov(RHS, DidOverflow);
16818 break;
16819 }
16820
16821 // In the case where multiple sizes are allowed, truncate and see if
16822 // the values are the same.
16823 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
16824 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
16825 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
16826 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
16827 // since it will give us the behavior of a TruncOrSelf in the case where
16828 // its parameter <= its size. We previously set Result to be at least the
16829 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
16830 // will work exactly like TruncOrSelf.
16831 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
16832 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
16833
16834 if (!APSInt::isSameValue(Temp, Result))
16835 DidOverflow = true;
16836 Result = Temp;
16837 }
16838
16839 APValue APV{Result};
16840 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16841 return false;
16842 return Success(DidOverflow, E);
16843 }
16844
16845 case Builtin::BI__builtin_reduce_add:
16846 case Builtin::BI__builtin_reduce_mul:
16847 case Builtin::BI__builtin_reduce_and:
16848 case Builtin::BI__builtin_reduce_or:
16849 case Builtin::BI__builtin_reduce_xor:
16850 case Builtin::BI__builtin_reduce_min:
16851 case Builtin::BI__builtin_reduce_max: {
16852 APValue Source;
16853 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
16854 return false;
16855
16856 unsigned SourceLen = Source.getVectorLength();
16857 APSInt Reduced = Source.getVectorElt(0).getInt();
16858 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
16859 switch (BuiltinOp) {
16860 default:
16861 return false;
16862 case Builtin::BI__builtin_reduce_add: {
16864 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16865 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
16866 return false;
16867 break;
16868 }
16869 case Builtin::BI__builtin_reduce_mul: {
16871 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
16872 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
16873 return false;
16874 break;
16875 }
16876 case Builtin::BI__builtin_reduce_and: {
16877 Reduced &= Source.getVectorElt(EltNum).getInt();
16878 break;
16879 }
16880 case Builtin::BI__builtin_reduce_or: {
16881 Reduced |= Source.getVectorElt(EltNum).getInt();
16882 break;
16883 }
16884 case Builtin::BI__builtin_reduce_xor: {
16885 Reduced ^= Source.getVectorElt(EltNum).getInt();
16886 break;
16887 }
16888 case Builtin::BI__builtin_reduce_min: {
16889 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
16890 break;
16891 }
16892 case Builtin::BI__builtin_reduce_max: {
16893 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
16894 break;
16895 }
16896 }
16897 }
16898
16899 return Success(Reduced, E);
16900 }
16901
16902 case clang::X86::BI__builtin_ia32_addcarryx_u32:
16903 case clang::X86::BI__builtin_ia32_addcarryx_u64:
16904 case clang::X86::BI__builtin_ia32_subborrow_u32:
16905 case clang::X86::BI__builtin_ia32_subborrow_u64: {
16906 LValue ResultLValue;
16907 APSInt CarryIn, LHS, RHS;
16908 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
16909 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
16910 !EvaluateInteger(E->getArg(1), LHS, Info) ||
16911 !EvaluateInteger(E->getArg(2), RHS, Info) ||
16912 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
16913 return false;
16914
16915 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
16916 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
16917
16918 unsigned BitWidth = LHS.getBitWidth();
16919 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
16920 APInt ExResult =
16921 IsAdd
16922 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
16923 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
16924
16925 APInt Result = ExResult.extractBits(BitWidth, 0);
16926 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
16927
16928 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
16929 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
16930 return false;
16931 return Success(CarryOut, E);
16932 }
16933
16934 case clang::X86::BI__builtin_ia32_movmskps:
16935 case clang::X86::BI__builtin_ia32_movmskpd:
16936 case clang::X86::BI__builtin_ia32_pmovmskb128:
16937 case clang::X86::BI__builtin_ia32_pmovmskb256:
16938 case clang::X86::BI__builtin_ia32_movmskps256:
16939 case clang::X86::BI__builtin_ia32_movmskpd256: {
16940 APValue Source;
16941 if (!Evaluate(Source, Info, E->getArg(0)))
16942 return false;
16943 unsigned SourceLen = Source.getVectorLength();
16944 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16945 QualType ElemQT = VT->getElementType();
16946 unsigned ResultLen = Info.Ctx.getTypeSize(
16947 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
16948 APInt Result(ResultLen, 0);
16949
16950 for (unsigned I = 0; I != SourceLen; ++I) {
16951 APInt Elem;
16952 if (ElemQT->isIntegerType()) {
16953 Elem = Source.getVectorElt(I).getInt();
16954 } else if (ElemQT->isRealFloatingType()) {
16955 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
16956 } else {
16957 return false;
16958 }
16959 Result.setBitVal(I, Elem.isNegative());
16960 }
16961 return Success(Result, E);
16962 }
16963
16964 case clang::X86::BI__builtin_ia32_bextr_u32:
16965 case clang::X86::BI__builtin_ia32_bextr_u64:
16966 case clang::X86::BI__builtin_ia32_bextri_u32:
16967 case clang::X86::BI__builtin_ia32_bextri_u64: {
16968 APSInt Val, Idx;
16969 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16970 !EvaluateInteger(E->getArg(1), Idx, Info))
16971 return false;
16972
16973 unsigned BitWidth = Val.getBitWidth();
16974 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
16975 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
16976 Length = Length > BitWidth ? BitWidth : Length;
16977
16978 // Handle out of bounds cases.
16979 if (Length == 0 || Shift >= BitWidth)
16980 return Success(0, E);
16981
16982 uint64_t Result = Val.getZExtValue() >> Shift;
16983 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
16984 return Success(Result, E);
16985 }
16986
16987 case clang::X86::BI__builtin_ia32_bzhi_si:
16988 case clang::X86::BI__builtin_ia32_bzhi_di: {
16989 APSInt Val, Idx;
16990 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
16991 !EvaluateInteger(E->getArg(1), Idx, Info))
16992 return false;
16993
16994 unsigned BitWidth = Val.getBitWidth();
16995 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
16996 if (Index < BitWidth)
16997 Val.clearHighBits(BitWidth - Index);
16998 return Success(Val, E);
16999 }
17000
17001 case clang::X86::BI__builtin_ia32_ktestcqi:
17002 case clang::X86::BI__builtin_ia32_ktestchi:
17003 case clang::X86::BI__builtin_ia32_ktestcsi:
17004 case clang::X86::BI__builtin_ia32_ktestcdi: {
17005 APSInt A, B;
17006 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17007 !EvaluateInteger(E->getArg(1), B, Info))
17008 return false;
17009
17010 return Success((~A & B) == 0, E);
17011 }
17012
17013 case clang::X86::BI__builtin_ia32_ktestzqi:
17014 case clang::X86::BI__builtin_ia32_ktestzhi:
17015 case clang::X86::BI__builtin_ia32_ktestzsi:
17016 case clang::X86::BI__builtin_ia32_ktestzdi: {
17017 APSInt A, B;
17018 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17019 !EvaluateInteger(E->getArg(1), B, Info))
17020 return false;
17021
17022 return Success((A & B) == 0, E);
17023 }
17024
17025 case clang::X86::BI__builtin_ia32_kortestcqi:
17026 case clang::X86::BI__builtin_ia32_kortestchi:
17027 case clang::X86::BI__builtin_ia32_kortestcsi:
17028 case clang::X86::BI__builtin_ia32_kortestcdi: {
17029 APSInt A, B;
17030 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17031 !EvaluateInteger(E->getArg(1), B, Info))
17032 return false;
17033
17034 return Success(~(A | B) == 0, E);
17035 }
17036
17037 case clang::X86::BI__builtin_ia32_kortestzqi:
17038 case clang::X86::BI__builtin_ia32_kortestzhi:
17039 case clang::X86::BI__builtin_ia32_kortestzsi:
17040 case clang::X86::BI__builtin_ia32_kortestzdi: {
17041 APSInt A, B;
17042 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17043 !EvaluateInteger(E->getArg(1), B, Info))
17044 return false;
17045
17046 return Success((A | B) == 0, E);
17047 }
17048
17049 case clang::X86::BI__builtin_ia32_kunpckhi:
17050 case clang::X86::BI__builtin_ia32_kunpckdi:
17051 case clang::X86::BI__builtin_ia32_kunpcksi: {
17052 APSInt A, B;
17053 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17054 !EvaluateInteger(E->getArg(1), B, Info))
17055 return false;
17056
17057 // Generic kunpack: extract lower half of each operand and concatenate
17058 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17059 unsigned BW = A.getBitWidth();
17060 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17061 return Success(Result, E);
17062 }
17063
17064 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17065 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17066 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17067 APSInt Val;
17068 if (!EvaluateInteger(E->getArg(0), Val, Info))
17069 return false;
17070 return Success(Val.countLeadingZeros(), E);
17071 }
17072
17073 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17074 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17075 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17076 APSInt Val;
17077 if (!EvaluateInteger(E->getArg(0), Val, Info))
17078 return false;
17079 return Success(Val.countTrailingZeros(), E);
17080 }
17081
17082 case clang::X86::BI__builtin_ia32_pdep_si:
17083 case clang::X86::BI__builtin_ia32_pdep_di: {
17084 APSInt Val, Msk;
17085 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17086 !EvaluateInteger(E->getArg(1), Msk, Info))
17087 return false;
17088
17089 unsigned BitWidth = Val.getBitWidth();
17090 APInt Result = APInt::getZero(BitWidth);
17091 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17092 if (Msk[I])
17093 Result.setBitVal(I, Val[P++]);
17094 return Success(Result, E);
17095 }
17096
17097 case clang::X86::BI__builtin_ia32_pext_si:
17098 case clang::X86::BI__builtin_ia32_pext_di: {
17099 APSInt Val, Msk;
17100 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17101 !EvaluateInteger(E->getArg(1), Msk, Info))
17102 return false;
17103
17104 unsigned BitWidth = Val.getBitWidth();
17105 APInt Result = APInt::getZero(BitWidth);
17106 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17107 if (Msk[I])
17108 Result.setBitVal(P++, Val[I]);
17109 return Success(Result, E);
17110 }
17111 case X86::BI__builtin_ia32_ptestz128:
17112 case X86::BI__builtin_ia32_ptestz256:
17113 case X86::BI__builtin_ia32_vtestzps:
17114 case X86::BI__builtin_ia32_vtestzps256:
17115 case X86::BI__builtin_ia32_vtestzpd:
17116 case X86::BI__builtin_ia32_vtestzpd256: {
17117 return EvalTestOp(
17118 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17119 }
17120 case X86::BI__builtin_ia32_ptestc128:
17121 case X86::BI__builtin_ia32_ptestc256:
17122 case X86::BI__builtin_ia32_vtestcps:
17123 case X86::BI__builtin_ia32_vtestcps256:
17124 case X86::BI__builtin_ia32_vtestcpd:
17125 case X86::BI__builtin_ia32_vtestcpd256: {
17126 return EvalTestOp(
17127 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17128 }
17129 case X86::BI__builtin_ia32_ptestnzc128:
17130 case X86::BI__builtin_ia32_ptestnzc256:
17131 case X86::BI__builtin_ia32_vtestnzcps:
17132 case X86::BI__builtin_ia32_vtestnzcps256:
17133 case X86::BI__builtin_ia32_vtestnzcpd:
17134 case X86::BI__builtin_ia32_vtestnzcpd256: {
17135 return EvalTestOp([](const APInt &A, const APInt &B) {
17136 return ((A & B) != 0) && ((~A & B) != 0);
17137 });
17138 }
17139 case X86::BI__builtin_ia32_kandqi:
17140 case X86::BI__builtin_ia32_kandhi:
17141 case X86::BI__builtin_ia32_kandsi:
17142 case X86::BI__builtin_ia32_kanddi: {
17143 return HandleMaskBinOp(
17144 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17145 }
17146
17147 case X86::BI__builtin_ia32_kandnqi:
17148 case X86::BI__builtin_ia32_kandnhi:
17149 case X86::BI__builtin_ia32_kandnsi:
17150 case X86::BI__builtin_ia32_kandndi: {
17151 return HandleMaskBinOp(
17152 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17153 }
17154
17155 case X86::BI__builtin_ia32_korqi:
17156 case X86::BI__builtin_ia32_korhi:
17157 case X86::BI__builtin_ia32_korsi:
17158 case X86::BI__builtin_ia32_kordi: {
17159 return HandleMaskBinOp(
17160 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17161 }
17162
17163 case X86::BI__builtin_ia32_kxnorqi:
17164 case X86::BI__builtin_ia32_kxnorhi:
17165 case X86::BI__builtin_ia32_kxnorsi:
17166 case X86::BI__builtin_ia32_kxnordi: {
17167 return HandleMaskBinOp(
17168 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17169 }
17170
17171 case X86::BI__builtin_ia32_kxorqi:
17172 case X86::BI__builtin_ia32_kxorhi:
17173 case X86::BI__builtin_ia32_kxorsi:
17174 case X86::BI__builtin_ia32_kxordi: {
17175 return HandleMaskBinOp(
17176 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17177 }
17178
17179 case X86::BI__builtin_ia32_knotqi:
17180 case X86::BI__builtin_ia32_knothi:
17181 case X86::BI__builtin_ia32_knotsi:
17182 case X86::BI__builtin_ia32_knotdi: {
17183 APSInt Val;
17184 if (!EvaluateInteger(E->getArg(0), Val, Info))
17185 return false;
17186 APSInt Result = ~Val;
17187 return Success(APValue(Result), E);
17188 }
17189
17190 case X86::BI__builtin_ia32_kaddqi:
17191 case X86::BI__builtin_ia32_kaddhi:
17192 case X86::BI__builtin_ia32_kaddsi:
17193 case X86::BI__builtin_ia32_kadddi: {
17194 return HandleMaskBinOp(
17195 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17196 }
17197
17198 case X86::BI__builtin_ia32_kmovb:
17199 case X86::BI__builtin_ia32_kmovw:
17200 case X86::BI__builtin_ia32_kmovd:
17201 case X86::BI__builtin_ia32_kmovq: {
17202 APSInt Val;
17203 if (!EvaluateInteger(E->getArg(0), Val, Info))
17204 return false;
17205 return Success(Val, E);
17206 }
17207
17208 case X86::BI__builtin_ia32_kshiftliqi:
17209 case X86::BI__builtin_ia32_kshiftlihi:
17210 case X86::BI__builtin_ia32_kshiftlisi:
17211 case X86::BI__builtin_ia32_kshiftlidi: {
17212 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17213 unsigned Amt = RHS.getZExtValue() & 0xFF;
17214 if (Amt >= LHS.getBitWidth())
17215 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17216 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17217 });
17218 }
17219
17220 case X86::BI__builtin_ia32_kshiftriqi:
17221 case X86::BI__builtin_ia32_kshiftrihi:
17222 case X86::BI__builtin_ia32_kshiftrisi:
17223 case X86::BI__builtin_ia32_kshiftridi: {
17224 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17225 unsigned Amt = RHS.getZExtValue() & 0xFF;
17226 if (Amt >= LHS.getBitWidth())
17227 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17228 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17229 });
17230 }
17231
17232 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17233 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17234 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17235 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17236 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17237 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17238 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17239 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17240 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
17241 APValue Vec;
17242 APSInt IdxAPS;
17243 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17244 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17245 return false;
17246 unsigned N = Vec.getVectorLength();
17247 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17248 return Success(Vec.getVectorElt(Idx).getInt(), E);
17249 }
17250
17251 case clang::X86::BI__builtin_ia32_cvtb2mask128:
17252 case clang::X86::BI__builtin_ia32_cvtb2mask256:
17253 case clang::X86::BI__builtin_ia32_cvtb2mask512:
17254 case clang::X86::BI__builtin_ia32_cvtw2mask128:
17255 case clang::X86::BI__builtin_ia32_cvtw2mask256:
17256 case clang::X86::BI__builtin_ia32_cvtw2mask512:
17257 case clang::X86::BI__builtin_ia32_cvtd2mask128:
17258 case clang::X86::BI__builtin_ia32_cvtd2mask256:
17259 case clang::X86::BI__builtin_ia32_cvtd2mask512:
17260 case clang::X86::BI__builtin_ia32_cvtq2mask128:
17261 case clang::X86::BI__builtin_ia32_cvtq2mask256:
17262 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
17263 assert(E->getNumArgs() == 1);
17264 APValue Vec;
17265 if (!EvaluateVector(E->getArg(0), Vec, Info))
17266 return false;
17267
17268 unsigned VectorLen = Vec.getVectorLength();
17269 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
17270 llvm::APInt Bits(RetWidth, 0);
17271
17272 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
17273 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
17274 unsigned MSB = A[A.getBitWidth() - 1];
17275 Bits.setBitVal(ElemNum, MSB);
17276 }
17277
17278 APSInt RetMask(Bits, /*isUnsigned=*/true);
17279 return Success(APValue(RetMask), E);
17280 }
17281
17282 case clang::X86::BI__builtin_ia32_cmpb128_mask:
17283 case clang::X86::BI__builtin_ia32_cmpw128_mask:
17284 case clang::X86::BI__builtin_ia32_cmpd128_mask:
17285 case clang::X86::BI__builtin_ia32_cmpq128_mask:
17286 case clang::X86::BI__builtin_ia32_cmpb256_mask:
17287 case clang::X86::BI__builtin_ia32_cmpw256_mask:
17288 case clang::X86::BI__builtin_ia32_cmpd256_mask:
17289 case clang::X86::BI__builtin_ia32_cmpq256_mask:
17290 case clang::X86::BI__builtin_ia32_cmpb512_mask:
17291 case clang::X86::BI__builtin_ia32_cmpw512_mask:
17292 case clang::X86::BI__builtin_ia32_cmpd512_mask:
17293 case clang::X86::BI__builtin_ia32_cmpq512_mask:
17294 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
17295 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
17296 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
17297 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
17298 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
17299 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
17300 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
17301 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
17302 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
17303 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
17304 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
17305 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
17306 assert(E->getNumArgs() == 4);
17307
17308 bool IsUnsigned =
17309 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
17310 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
17311
17312 APValue LHS, RHS;
17313 APSInt Mask, Opcode;
17314 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
17315 !EvaluateVector(E->getArg(1), RHS, Info) ||
17316 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
17317 !EvaluateInteger(E->getArg(3), Mask, Info))
17318 return false;
17319
17320 assert(LHS.getVectorLength() == RHS.getVectorLength());
17321
17322 unsigned VectorLen = LHS.getVectorLength();
17323 unsigned RetWidth = Mask.getBitWidth();
17324
17325 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17326
17327 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
17328 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
17329 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
17330 bool Result = false;
17331
17332 switch (Opcode.getExtValue() & 0x7) {
17333 case 0: // _MM_CMPINT_EQ
17334 Result = (A == B);
17335 break;
17336 case 1: // _MM_CMPINT_LT
17337 Result = IsUnsigned ? A.ult(B) : A.slt(B);
17338 break;
17339 case 2: // _MM_CMPINT_LE
17340 Result = IsUnsigned ? A.ule(B) : A.sle(B);
17341 break;
17342 case 3: // _MM_CMPINT_FALSE
17343 Result = false;
17344 break;
17345 case 4: // _MM_CMPINT_NE
17346 Result = (A != B);
17347 break;
17348 case 5: // _MM_CMPINT_NLT (>=)
17349 Result = IsUnsigned ? A.uge(B) : A.sge(B);
17350 break;
17351 case 6: // _MM_CMPINT_NLE (>)
17352 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
17353 break;
17354 case 7: // _MM_CMPINT_TRUE
17355 Result = true;
17356 break;
17357 }
17358
17359 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
17360 }
17361
17362 return Success(APValue(RetMask), E);
17363 }
17364 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
17365 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
17366 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
17367 assert(E->getNumArgs() == 3);
17368
17369 APValue Source, ShuffleMask;
17370 APSInt ZeroMask;
17371 if (!EvaluateVector(E->getArg(0), Source, Info) ||
17372 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
17373 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
17374 return false;
17375
17376 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
17377 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
17378
17379 unsigned NumBytesInQWord = 8;
17380 unsigned NumBitsInByte = 8;
17381 unsigned NumBytes = Source.getVectorLength();
17382 unsigned NumQWords = NumBytes / NumBytesInQWord;
17383 unsigned RetWidth = ZeroMask.getBitWidth();
17384 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17385
17386 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
17387 APInt SourceQWord(64, 0);
17388 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17389 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
17390 .getInt()
17391 .getZExtValue();
17392 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
17393 }
17394
17395 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17396 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
17397 unsigned M =
17398 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
17399 if (ZeroMask[SelIdx]) {
17400 RetMask.setBitVal(SelIdx, SourceQWord[M]);
17401 }
17402 }
17403 }
17404 return Success(APValue(RetMask), E);
17405 }
17406 }
17407}
17408
17409/// Determine whether this is a pointer past the end of the complete
17410/// object referred to by the lvalue.
17412 const LValue &LV) {
17413 // A null pointer can be viewed as being "past the end" but we don't
17414 // choose to look at it that way here.
17415 if (!LV.getLValueBase())
17416 return false;
17417
17418 // If the designator is valid and refers to a subobject, we're not pointing
17419 // past the end.
17420 if (!LV.getLValueDesignator().Invalid &&
17421 !LV.getLValueDesignator().isOnePastTheEnd())
17422 return false;
17423
17424 // A pointer to an incomplete type might be past-the-end if the type's size is
17425 // zero. We cannot tell because the type is incomplete.
17426 QualType Ty = getType(LV.getLValueBase());
17427 if (Ty->isIncompleteType())
17428 return true;
17429
17430 // Can't be past the end of an invalid object.
17431 if (LV.getLValueDesignator().Invalid)
17432 return false;
17433
17434 // We're a past-the-end pointer if we point to the byte after the object,
17435 // no matter what our type or path is.
17436 auto Size = Ctx.getTypeSizeInChars(Ty);
17437 return LV.getLValueOffset() == Size;
17438}
17439
17440namespace {
17441
17442/// Data recursive integer evaluator of certain binary operators.
17443///
17444/// We use a data recursive algorithm for binary operators so that we are able
17445/// to handle extreme cases of chained binary operators without causing stack
17446/// overflow.
17447class DataRecursiveIntBinOpEvaluator {
17448 struct EvalResult {
17449 APValue Val;
17450 bool Failed = false;
17451
17452 EvalResult() = default;
17453
17454 void swap(EvalResult &RHS) {
17455 Val.swap(RHS.Val);
17456 Failed = RHS.Failed;
17457 RHS.Failed = false;
17458 }
17459 };
17460
17461 struct Job {
17462 const Expr *E;
17463 EvalResult LHSResult; // meaningful only for binary operator expression.
17464 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
17465
17466 Job() = default;
17467 Job(Job &&) = default;
17468
17469 void startSpeculativeEval(EvalInfo &Info) {
17470 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
17471 }
17472
17473 private:
17474 SpeculativeEvaluationRAII SpecEvalRAII;
17475 };
17476
17477 SmallVector<Job, 16> Queue;
17478
17479 IntExprEvaluator &IntEval;
17480 EvalInfo &Info;
17481 APValue &FinalResult;
17482
17483public:
17484 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
17485 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
17486
17487 /// True if \param E is a binary operator that we are going to handle
17488 /// data recursively.
17489 /// We handle binary operators that are comma, logical, or that have operands
17490 /// with integral or enumeration type.
17491 static bool shouldEnqueue(const BinaryOperator *E) {
17492 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
17496 }
17497
17498 bool Traverse(const BinaryOperator *E) {
17499 enqueue(E);
17500 EvalResult PrevResult;
17501 while (!Queue.empty())
17502 process(PrevResult);
17503
17504 if (PrevResult.Failed) return false;
17505
17506 FinalResult.swap(PrevResult.Val);
17507 return true;
17508 }
17509
17510private:
17511 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
17512 return IntEval.Success(Value, E, Result);
17513 }
17514 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
17515 return IntEval.Success(Value, E, Result);
17516 }
17517 bool Error(const Expr *E) {
17518 return IntEval.Error(E);
17519 }
17520 bool Error(const Expr *E, diag::kind D) {
17521 return IntEval.Error(E, D);
17522 }
17523
17524 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
17525 return Info.CCEDiag(E, D);
17526 }
17527
17528 // Returns true if visiting the RHS is necessary, false otherwise.
17529 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17530 bool &SuppressRHSDiags);
17531
17532 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17533 const BinaryOperator *E, APValue &Result);
17534
17535 void EvaluateExpr(const Expr *E, EvalResult &Result) {
17536 Result.Failed = !Evaluate(Result.Val, Info, E);
17537 if (Result.Failed)
17538 Result.Val = APValue();
17539 }
17540
17541 void process(EvalResult &Result);
17542
17543 void enqueue(const Expr *E) {
17544 E = E->IgnoreParens();
17545 Queue.resize(Queue.size()+1);
17546 Queue.back().E = E;
17547 Queue.back().Kind = Job::AnyExprKind;
17548 }
17549};
17550
17551}
17552
17553bool DataRecursiveIntBinOpEvaluator::
17554 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17555 bool &SuppressRHSDiags) {
17556 if (E->getOpcode() == BO_Comma) {
17557 // Ignore LHS but note if we could not evaluate it.
17558 if (LHSResult.Failed)
17559 return Info.noteSideEffect();
17560 return true;
17561 }
17562
17563 if (E->isLogicalOp()) {
17564 bool LHSAsBool;
17565 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
17566 // We were able to evaluate the LHS, see if we can get away with not
17567 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
17568 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
17569 Success(LHSAsBool, E, LHSResult.Val);
17570 return false; // Ignore RHS
17571 }
17572 } else {
17573 LHSResult.Failed = true;
17574
17575 // Since we weren't able to evaluate the left hand side, it
17576 // might have had side effects.
17577 if (!Info.noteSideEffect())
17578 return false;
17579
17580 // We can't evaluate the LHS; however, sometimes the result
17581 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17582 // Don't ignore RHS and suppress diagnostics from this arm.
17583 SuppressRHSDiags = true;
17584 }
17585
17586 return true;
17587 }
17588
17589 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17591
17592 if (LHSResult.Failed && !Info.noteFailure())
17593 return false; // Ignore RHS;
17594
17595 return true;
17596}
17597
17598static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
17599 bool IsSub) {
17600 // Compute the new offset in the appropriate width, wrapping at 64 bits.
17601 // FIXME: When compiling for a 32-bit target, we should use 32-bit
17602 // offsets.
17603 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
17604 CharUnits &Offset = LVal.getLValueOffset();
17605 uint64_t Offset64 = Offset.getQuantity();
17606 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
17607 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
17608 : Offset64 + Index64);
17609}
17610
17611bool DataRecursiveIntBinOpEvaluator::
17612 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17613 const BinaryOperator *E, APValue &Result) {
17614 if (E->getOpcode() == BO_Comma) {
17615 if (RHSResult.Failed)
17616 return false;
17617 Result = RHSResult.Val;
17618 return true;
17619 }
17620
17621 if (E->isLogicalOp()) {
17622 bool lhsResult, rhsResult;
17623 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
17624 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
17625
17626 if (LHSIsOK) {
17627 if (RHSIsOK) {
17628 if (E->getOpcode() == BO_LOr)
17629 return Success(lhsResult || rhsResult, E, Result);
17630 else
17631 return Success(lhsResult && rhsResult, E, Result);
17632 }
17633 } else {
17634 if (RHSIsOK) {
17635 // We can't evaluate the LHS; however, sometimes the result
17636 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17637 if (rhsResult == (E->getOpcode() == BO_LOr))
17638 return Success(rhsResult, E, Result);
17639 }
17640 }
17641
17642 return false;
17643 }
17644
17645 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17647
17648 if (LHSResult.Failed || RHSResult.Failed)
17649 return false;
17650
17651 const APValue &LHSVal = LHSResult.Val;
17652 const APValue &RHSVal = RHSResult.Val;
17653
17654 // Handle cases like (unsigned long)&a + 4.
17655 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
17656 Result = LHSVal;
17657 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
17658 return true;
17659 }
17660
17661 // Handle cases like 4 + (unsigned long)&a
17662 if (E->getOpcode() == BO_Add &&
17663 RHSVal.isLValue() && LHSVal.isInt()) {
17664 Result = RHSVal;
17665 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
17666 return true;
17667 }
17668
17669 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
17670 // Handle (intptr_t)&&A - (intptr_t)&&B.
17671 if (!LHSVal.getLValueOffset().isZero() ||
17672 !RHSVal.getLValueOffset().isZero())
17673 return false;
17674 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
17675 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
17676 if (!LHSExpr || !RHSExpr)
17677 return false;
17678 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
17679 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
17680 if (!LHSAddrExpr || !RHSAddrExpr)
17681 return false;
17682 // Make sure both labels come from the same function.
17683 if (LHSAddrExpr->getLabel()->getDeclContext() !=
17684 RHSAddrExpr->getLabel()->getDeclContext())
17685 return false;
17686 Result = APValue(LHSAddrExpr, RHSAddrExpr);
17687 return true;
17688 }
17689
17690 // All the remaining cases expect both operands to be an integer
17691 if (!LHSVal.isInt() || !RHSVal.isInt())
17692 return Error(E);
17693
17694 // Set up the width and signedness manually, in case it can't be deduced
17695 // from the operation we're performing.
17696 // FIXME: Don't do this in the cases where we can deduce it.
17697 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
17699 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
17700 RHSVal.getInt(), Value))
17701 return false;
17702 return Success(Value, E, Result);
17703}
17704
17705void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
17706 Job &job = Queue.back();
17707
17708 switch (job.Kind) {
17709 case Job::AnyExprKind: {
17710 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
17711 if (shouldEnqueue(Bop)) {
17712 job.Kind = Job::BinOpKind;
17713 enqueue(Bop->getLHS());
17714 return;
17715 }
17716 }
17717
17718 EvaluateExpr(job.E, Result);
17719 Queue.pop_back();
17720 return;
17721 }
17722
17723 case Job::BinOpKind: {
17724 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17725 bool SuppressRHSDiags = false;
17726 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
17727 Queue.pop_back();
17728 return;
17729 }
17730 if (SuppressRHSDiags)
17731 job.startSpeculativeEval(Info);
17732 job.LHSResult.swap(Result);
17733 job.Kind = Job::BinOpVisitedLHSKind;
17734 enqueue(Bop->getRHS());
17735 return;
17736 }
17737
17738 case Job::BinOpVisitedLHSKind: {
17739 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
17740 EvalResult RHS;
17741 RHS.swap(Result);
17742 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
17743 Queue.pop_back();
17744 return;
17745 }
17746 }
17747
17748 llvm_unreachable("Invalid Job::Kind!");
17749}
17750
17751namespace {
17752enum class CmpResult {
17753 Unequal,
17754 Less,
17755 Equal,
17756 Greater,
17757 Unordered,
17758};
17759}
17760
17761template <class SuccessCB, class AfterCB>
17762static bool
17764 SuccessCB &&Success, AfterCB &&DoAfter) {
17765 assert(!E->isValueDependent());
17766 assert(E->isComparisonOp() && "expected comparison operator");
17767 assert((E->getOpcode() == BO_Cmp ||
17769 "unsupported binary expression evaluation");
17770 auto Error = [&](const Expr *E) {
17771 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17772 return false;
17773 };
17774
17775 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
17776 bool IsEquality = E->isEqualityOp();
17777
17778 QualType LHSTy = E->getLHS()->getType();
17779 QualType RHSTy = E->getRHS()->getType();
17780
17781 if (LHSTy->isIntegralOrEnumerationType() &&
17782 RHSTy->isIntegralOrEnumerationType()) {
17783 APSInt LHS, RHS;
17784 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
17785 if (!LHSOK && !Info.noteFailure())
17786 return false;
17787 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
17788 return false;
17789 if (LHS < RHS)
17790 return Success(CmpResult::Less, E);
17791 if (LHS > RHS)
17792 return Success(CmpResult::Greater, E);
17793 return Success(CmpResult::Equal, E);
17794 }
17795
17796 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
17797 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
17798 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
17799
17800 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
17801 if (!LHSOK && !Info.noteFailure())
17802 return false;
17803 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
17804 return false;
17805 if (LHSFX < RHSFX)
17806 return Success(CmpResult::Less, E);
17807 if (LHSFX > RHSFX)
17808 return Success(CmpResult::Greater, E);
17809 return Success(CmpResult::Equal, E);
17810 }
17811
17812 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
17813 ComplexValue LHS, RHS;
17814 bool LHSOK;
17815 if (E->isAssignmentOp()) {
17816 LValue LV;
17817 EvaluateLValue(E->getLHS(), LV, Info);
17818 LHSOK = false;
17819 } else if (LHSTy->isRealFloatingType()) {
17820 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
17821 if (LHSOK) {
17822 LHS.makeComplexFloat();
17823 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
17824 }
17825 } else {
17826 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
17827 }
17828 if (!LHSOK && !Info.noteFailure())
17829 return false;
17830
17831 if (E->getRHS()->getType()->isRealFloatingType()) {
17832 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
17833 return false;
17834 RHS.makeComplexFloat();
17835 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
17836 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
17837 return false;
17838
17839 if (LHS.isComplexFloat()) {
17840 APFloat::cmpResult CR_r =
17841 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
17842 APFloat::cmpResult CR_i =
17843 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
17844 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
17845 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17846 } else {
17847 assert(IsEquality && "invalid complex comparison");
17848 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
17849 LHS.getComplexIntImag() == RHS.getComplexIntImag();
17850 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
17851 }
17852 }
17853
17854 if (LHSTy->isRealFloatingType() &&
17855 RHSTy->isRealFloatingType()) {
17856 APFloat RHS(0.0), LHS(0.0);
17857
17858 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
17859 if (!LHSOK && !Info.noteFailure())
17860 return false;
17861
17862 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
17863 return false;
17864
17865 assert(E->isComparisonOp() && "Invalid binary operator!");
17866 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
17867 if (!Info.InConstantContext &&
17868 APFloatCmpResult == APFloat::cmpUnordered &&
17870 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
17871 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
17872 return false;
17873 }
17874 auto GetCmpRes = [&]() {
17875 switch (APFloatCmpResult) {
17876 case APFloat::cmpEqual:
17877 return CmpResult::Equal;
17878 case APFloat::cmpLessThan:
17879 return CmpResult::Less;
17880 case APFloat::cmpGreaterThan:
17881 return CmpResult::Greater;
17882 case APFloat::cmpUnordered:
17883 return CmpResult::Unordered;
17884 }
17885 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
17886 };
17887 return Success(GetCmpRes(), E);
17888 }
17889
17890 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
17891 LValue LHSValue, RHSValue;
17892
17893 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
17894 if (!LHSOK && !Info.noteFailure())
17895 return false;
17896
17897 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
17898 return false;
17899
17900 // Reject differing bases from the normal codepath; we special-case
17901 // comparisons to null.
17902 if (!HasSameBase(LHSValue, RHSValue)) {
17903 // Bail out early if we're checking potential constant expression.
17904 // Otherwise, prefer to diagnose other issues.
17905 if (Info.checkingPotentialConstantExpression() &&
17906 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
17907 return false;
17908 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
17909 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
17910 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
17911 Info.FFDiag(E, DiagID)
17912 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
17913 return false;
17914 };
17915 // Inequalities and subtractions between unrelated pointers have
17916 // unspecified or undefined behavior.
17917 if (!IsEquality)
17918 return DiagComparison(
17919 diag::note_constexpr_pointer_comparison_unspecified);
17920 // A constant address may compare equal to the address of a symbol.
17921 // The one exception is that address of an object cannot compare equal
17922 // to a null pointer constant.
17923 // TODO: Should we restrict this to actual null pointers, and exclude the
17924 // case of zero cast to pointer type?
17925 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
17926 (!RHSValue.Base && !RHSValue.Offset.isZero()))
17927 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
17928 !RHSValue.Base);
17929 // C++2c [intro.object]/10:
17930 // Two objects [...] may have the same address if [...] they are both
17931 // potentially non-unique objects.
17932 // C++2c [intro.object]/9:
17933 // An object is potentially non-unique if it is a string literal object,
17934 // the backing array of an initializer list, or a subobject thereof.
17935 //
17936 // This makes the comparison result unspecified, so it's not a constant
17937 // expression.
17938 //
17939 // TODO: Do we need to handle the initializer list case here?
17940 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
17941 return DiagComparison(diag::note_constexpr_literal_comparison);
17942 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
17943 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
17944 !IsOpaqueConstantCall(LHSValue));
17945 // We can't tell whether weak symbols will end up pointing to the same
17946 // object.
17947 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
17948 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
17949 !IsWeakLValue(LHSValue));
17950 // We can't compare the address of the start of one object with the
17951 // past-the-end address of another object, per C++ DR1652.
17952 if (LHSValue.Base && LHSValue.Offset.isZero() &&
17953 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
17954 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17955 true);
17956 if (RHSValue.Base && RHSValue.Offset.isZero() &&
17957 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
17958 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
17959 false);
17960 // We can't tell whether an object is at the same address as another
17961 // zero sized object.
17962 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
17963 (LHSValue.Base && isZeroSized(RHSValue)))
17964 return DiagComparison(
17965 diag::note_constexpr_pointer_comparison_zero_sized);
17966 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
17967 return DiagComparison(
17968 diag::note_constexpr_pointer_comparison_unspecified);
17969 // FIXME: Verify both variables are live.
17970 return Success(CmpResult::Unequal, E);
17971 }
17972
17973 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
17974 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
17975
17976 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
17977 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
17978
17979 // C++11 [expr.rel]p2:
17980 // - If two pointers point to non-static data members of the same object,
17981 // or to subobjects or array elements fo such members, recursively, the
17982 // pointer to the later declared member compares greater provided the
17983 // two members have the same access control and provided their class is
17984 // not a union.
17985 // [...]
17986 // - Otherwise pointer comparisons are unspecified.
17987 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
17988 bool WasArrayIndex;
17989 unsigned Mismatch = FindDesignatorMismatch(
17990 LHSValue.Base.isNull() ? QualType()
17991 : getType(LHSValue.Base).getNonReferenceType(),
17992 LHSDesignator, RHSDesignator, WasArrayIndex);
17993 // At the point where the designators diverge, the comparison has a
17994 // specified value if:
17995 // - we are comparing array indices
17996 // - we are comparing fields of a union, or fields with the same access
17997 // Otherwise, the result is unspecified and thus the comparison is not a
17998 // constant expression.
17999 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18000 Mismatch < RHSDesignator.Entries.size()) {
18001 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18002 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18003 if (!LF && !RF)
18004 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18005 else if (!LF)
18006 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18007 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18008 << RF->getParent() << RF;
18009 else if (!RF)
18010 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18011 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18012 << LF->getParent() << LF;
18013 else if (!LF->getParent()->isUnion() &&
18014 LF->getAccess() != RF->getAccess())
18015 Info.CCEDiag(E,
18016 diag::note_constexpr_pointer_comparison_differing_access)
18017 << LF << LF->getAccess() << RF << RF->getAccess()
18018 << LF->getParent();
18019 }
18020 }
18021
18022 // The comparison here must be unsigned, and performed with the same
18023 // width as the pointer.
18024 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18025 uint64_t CompareLHS = LHSOffset.getQuantity();
18026 uint64_t CompareRHS = RHSOffset.getQuantity();
18027 assert(PtrSize <= 64 && "Unexpected pointer width");
18028 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18029 CompareLHS &= Mask;
18030 CompareRHS &= Mask;
18031
18032 // If there is a base and this is a relational operator, we can only
18033 // compare pointers within the object in question; otherwise, the result
18034 // depends on where the object is located in memory.
18035 if (!LHSValue.Base.isNull() && IsRelational) {
18036 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18037 if (BaseTy->isIncompleteType())
18038 return Error(E);
18039 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18040 uint64_t OffsetLimit = Size.getQuantity();
18041 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18042 return Error(E);
18043 }
18044
18045 if (CompareLHS < CompareRHS)
18046 return Success(CmpResult::Less, E);
18047 if (CompareLHS > CompareRHS)
18048 return Success(CmpResult::Greater, E);
18049 return Success(CmpResult::Equal, E);
18050 }
18051
18052 if (LHSTy->isMemberPointerType()) {
18053 assert(IsEquality && "unexpected member pointer operation");
18054 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18055
18056 MemberPtr LHSValue, RHSValue;
18057
18058 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18059 if (!LHSOK && !Info.noteFailure())
18060 return false;
18061
18062 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18063 return false;
18064
18065 // If either operand is a pointer to a weak function, the comparison is not
18066 // constant.
18067 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18068 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18069 << LHSValue.getDecl();
18070 return false;
18071 }
18072 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18073 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18074 << RHSValue.getDecl();
18075 return false;
18076 }
18077
18078 // C++11 [expr.eq]p2:
18079 // If both operands are null, they compare equal. Otherwise if only one is
18080 // null, they compare unequal.
18081 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18082 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18083 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18084 }
18085
18086 // Otherwise if either is a pointer to a virtual member function, the
18087 // result is unspecified.
18088 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18089 if (MD->isVirtual())
18090 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18091 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18092 if (MD->isVirtual())
18093 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18094
18095 // Otherwise they compare equal if and only if they would refer to the
18096 // same member of the same most derived object or the same subobject if
18097 // they were dereferenced with a hypothetical object of the associated
18098 // class type.
18099 bool Equal = LHSValue == RHSValue;
18100 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18101 }
18102
18103 if (LHSTy->isNullPtrType()) {
18104 assert(E->isComparisonOp() && "unexpected nullptr operation");
18105 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18106 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18107 // are compared, the result is true of the operator is <=, >= or ==, and
18108 // false otherwise.
18109 LValue Res;
18110 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18111 !EvaluatePointer(E->getRHS(), Res, Info))
18112 return false;
18113 return Success(CmpResult::Equal, E);
18114 }
18115
18116 return DoAfter();
18117}
18118
18119bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18120 if (!CheckLiteralType(Info, E))
18121 return false;
18122
18123 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18125 switch (CR) {
18126 case CmpResult::Unequal:
18127 llvm_unreachable("should never produce Unequal for three-way comparison");
18128 case CmpResult::Less:
18129 CCR = ComparisonCategoryResult::Less;
18130 break;
18131 case CmpResult::Equal:
18132 CCR = ComparisonCategoryResult::Equal;
18133 break;
18134 case CmpResult::Greater:
18135 CCR = ComparisonCategoryResult::Greater;
18136 break;
18137 case CmpResult::Unordered:
18138 CCR = ComparisonCategoryResult::Unordered;
18139 break;
18140 }
18141 // Evaluation succeeded. Lookup the information for the comparison category
18142 // type and fetch the VarDecl for the result.
18143 const ComparisonCategoryInfo &CmpInfo =
18144 Info.Ctx.CompCategories.getInfoForType(E->getType());
18145 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18146 // Check and evaluate the result as a constant expression.
18147 LValue LV;
18148 LV.set(VD);
18149 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18150 return false;
18151 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18152 ConstantExprKind::Normal);
18153 };
18154 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18155 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18156 });
18157}
18158
18159bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18160 const CXXParenListInitExpr *E) {
18161 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18162}
18163
18164bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18165 // We don't support assignment in C. C++ assignments don't get here because
18166 // assignment is an lvalue in C++.
18167 if (E->isAssignmentOp()) {
18168 Error(E);
18169 if (!Info.noteFailure())
18170 return false;
18171 }
18172
18173 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18174 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18175
18176 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18178 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18179
18180 if (E->isComparisonOp()) {
18181 // Evaluate builtin binary comparisons by evaluating them as three-way
18182 // comparisons and then translating the result.
18183 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18184 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18185 "should only produce Unequal for equality comparisons");
18186 bool IsEqual = CR == CmpResult::Equal,
18187 IsLess = CR == CmpResult::Less,
18188 IsGreater = CR == CmpResult::Greater;
18189 auto Op = E->getOpcode();
18190 switch (Op) {
18191 default:
18192 llvm_unreachable("unsupported binary operator");
18193 case BO_EQ:
18194 case BO_NE:
18195 return Success(IsEqual == (Op == BO_EQ), E);
18196 case BO_LT:
18197 return Success(IsLess, E);
18198 case BO_GT:
18199 return Success(IsGreater, E);
18200 case BO_LE:
18201 return Success(IsEqual || IsLess, E);
18202 case BO_GE:
18203 return Success(IsEqual || IsGreater, E);
18204 }
18205 };
18206 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18207 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18208 });
18209 }
18210
18211 QualType LHSTy = E->getLHS()->getType();
18212 QualType RHSTy = E->getRHS()->getType();
18213
18214 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18215 E->getOpcode() == BO_Sub) {
18216 LValue LHSValue, RHSValue;
18217
18218 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18219 if (!LHSOK && !Info.noteFailure())
18220 return false;
18221
18222 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18223 return false;
18224
18225 // Reject differing bases from the normal codepath; we special-case
18226 // comparisons to null.
18227 if (!HasSameBase(LHSValue, RHSValue)) {
18228 if (Info.checkingPotentialConstantExpression() &&
18229 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18230 return false;
18231
18232 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18233 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18234
18235 auto DiagArith = [&](unsigned DiagID) {
18236 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18237 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18238 Info.FFDiag(E, DiagID) << LHS << RHS;
18239 if (LHSExpr && LHSExpr == RHSExpr)
18240 Info.Note(LHSExpr->getExprLoc(),
18241 diag::note_constexpr_repeated_literal_eval)
18242 << LHSExpr->getSourceRange();
18243 return false;
18244 };
18245
18246 if (!LHSExpr || !RHSExpr)
18247 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
18248
18249 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18250 return DiagArith(diag::note_constexpr_literal_arith);
18251
18252 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18253 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18254 if (!LHSAddrExpr || !RHSAddrExpr)
18255 return Error(E);
18256 // Make sure both labels come from the same function.
18257 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18258 RHSAddrExpr->getLabel()->getDeclContext())
18259 return Error(E);
18260 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
18261 }
18262 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18263 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18264
18265 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18266 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18267
18268 // C++11 [expr.add]p6:
18269 // Unless both pointers point to elements of the same array object, or
18270 // one past the last element of the array object, the behavior is
18271 // undefined.
18272 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
18273 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
18274 RHSDesignator))
18275 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
18276
18277 QualType Type = E->getLHS()->getType();
18278 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
18279
18280 CharUnits ElementSize;
18281 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
18282 return false;
18283
18284 // As an extension, a type may have zero size (empty struct or union in
18285 // C, array of zero length). Pointer subtraction in such cases has
18286 // undefined behavior, so is not constant.
18287 if (ElementSize.isZero()) {
18288 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
18289 << ElementType;
18290 return false;
18291 }
18292
18293 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
18294 // and produce incorrect results when it overflows. Such behavior
18295 // appears to be non-conforming, but is common, so perhaps we should
18296 // assume the standard intended for such cases to be undefined behavior
18297 // and check for them.
18298
18299 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
18300 // overflow in the final conversion to ptrdiff_t.
18301 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
18302 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
18303 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
18304 false);
18305 APSInt TrueResult = (LHS - RHS) / ElemSize;
18306 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
18307
18308 if (Result.extend(65) != TrueResult &&
18309 !HandleOverflow(Info, E, TrueResult, E->getType()))
18310 return false;
18311 return Success(Result, E);
18312 }
18313
18314 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18315}
18316
18317/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
18318/// a result as the expression's type.
18319bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
18320 const UnaryExprOrTypeTraitExpr *E) {
18321 switch(E->getKind()) {
18322 case UETT_PreferredAlignOf:
18323 case UETT_AlignOf: {
18324 if (E->isArgumentType())
18325 return Success(
18326 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
18327 else
18328 return Success(
18329 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
18330 }
18331
18332 case UETT_PtrAuthTypeDiscriminator: {
18333 if (E->getArgumentType()->isDependentType())
18334 return false;
18335 return Success(
18337 }
18338 case UETT_VecStep: {
18339 QualType Ty = E->getTypeOfArgument();
18340
18341 if (Ty->isVectorType()) {
18342 unsigned n = Ty->castAs<VectorType>()->getNumElements();
18343
18344 // The vec_step built-in functions that take a 3-component
18345 // vector return 4. (OpenCL 1.1 spec 6.11.12)
18346 if (n == 3)
18347 n = 4;
18348
18349 return Success(n, E);
18350 } else
18351 return Success(1, E);
18352 }
18353
18354 case UETT_DataSizeOf:
18355 case UETT_SizeOf: {
18356 QualType SrcTy = E->getTypeOfArgument();
18357 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
18358 // the result is the size of the referenced type."
18359 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
18360 SrcTy = Ref->getPointeeType();
18361
18362 CharUnits Sizeof;
18363 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
18364 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
18365 : SizeOfType::SizeOf)) {
18366 return false;
18367 }
18368 return Success(Sizeof, E);
18369 }
18370 case UETT_OpenMPRequiredSimdAlign:
18371 assert(E->isArgumentType());
18372 return Success(
18373 Info.Ctx.toCharUnitsFromBits(
18375 .getQuantity(),
18376 E);
18377 case UETT_VectorElements: {
18378 QualType Ty = E->getTypeOfArgument();
18379 // If the vector has a fixed size, we can determine the number of elements
18380 // at compile time.
18381 if (const auto *VT = Ty->getAs<VectorType>())
18382 return Success(VT->getNumElements(), E);
18383
18384 assert(Ty->isSizelessVectorType());
18385 if (Info.InConstantContext)
18386 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
18387 << E->getSourceRange();
18388
18389 return false;
18390 }
18391 case UETT_CountOf: {
18392 QualType Ty = E->getTypeOfArgument();
18393 assert(Ty->isArrayType());
18394
18395 // We don't need to worry about array element qualifiers, so getting the
18396 // unsafe array type is fine.
18397 if (const auto *CAT =
18398 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
18399 return Success(CAT->getSize(), E);
18400 }
18401
18402 assert(!Ty->isConstantSizeType());
18403
18404 // If it's a variable-length array type, we need to check whether it is a
18405 // multidimensional array. If so, we need to check the size expression of
18406 // the VLA to see if it's a constant size. If so, we can return that value.
18407 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
18408 assert(VAT);
18409 if (VAT->getElementType()->isArrayType()) {
18410 // Variable array size expression could be missing (e.g. int a[*][10]) In
18411 // that case, it can't be a constant expression.
18412 if (!VAT->getSizeExpr()) {
18413 Info.FFDiag(E->getBeginLoc());
18414 return false;
18415 }
18416
18417 std::optional<APSInt> Res =
18418 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
18419 if (Res) {
18420 // The resulting value always has type size_t, so we need to make the
18421 // returned APInt have the correct sign and bit-width.
18422 APInt Val{
18423 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
18424 Res->getZExtValue()};
18425 return Success(Val, E);
18426 }
18427 }
18428
18429 // Definitely a variable-length type, which is not an ICE.
18430 // FIXME: Better diagnostic.
18431 Info.FFDiag(E->getBeginLoc());
18432 return false;
18433 }
18434 }
18435
18436 llvm_unreachable("unknown expr/type trait");
18437}
18438
18439bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
18440 CharUnits Result;
18441 unsigned n = OOE->getNumComponents();
18442 if (n == 0)
18443 return Error(OOE);
18444 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
18445 for (unsigned i = 0; i != n; ++i) {
18446 OffsetOfNode ON = OOE->getComponent(i);
18447 switch (ON.getKind()) {
18448 case OffsetOfNode::Array: {
18449 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
18450 APSInt IdxResult;
18451 if (!EvaluateInteger(Idx, IdxResult, Info))
18452 return false;
18453 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
18454 if (!AT)
18455 return Error(OOE);
18456 CurrentType = AT->getElementType();
18457 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
18458 Result += IdxResult.getSExtValue() * ElementSize;
18459 break;
18460 }
18461
18462 case OffsetOfNode::Field: {
18463 FieldDecl *MemberDecl = ON.getField();
18464 const auto *RD = CurrentType->getAsRecordDecl();
18465 if (!RD)
18466 return Error(OOE);
18467 if (RD->isInvalidDecl()) return false;
18468 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18469 unsigned i = MemberDecl->getFieldIndex();
18470 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
18471 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
18472 CurrentType = MemberDecl->getType().getNonReferenceType();
18473 break;
18474 }
18475
18477 llvm_unreachable("dependent __builtin_offsetof");
18478
18479 case OffsetOfNode::Base: {
18480 CXXBaseSpecifier *BaseSpec = ON.getBase();
18481 if (BaseSpec->isVirtual())
18482 return Error(OOE);
18483
18484 // Find the layout of the class whose base we are looking into.
18485 const auto *RD = CurrentType->getAsCXXRecordDecl();
18486 if (!RD)
18487 return Error(OOE);
18488 if (RD->isInvalidDecl()) return false;
18489 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18490
18491 // Find the base class itself.
18492 CurrentType = BaseSpec->getType();
18493 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
18494 if (!BaseRD)
18495 return Error(OOE);
18496
18497 // Add the offset to the base.
18498 Result += RL.getBaseClassOffset(BaseRD);
18499 break;
18500 }
18501 }
18502 }
18503 return Success(Result, OOE);
18504}
18505
18506bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18507 switch (E->getOpcode()) {
18508 default:
18509 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
18510 // See C99 6.6p3.
18511 return Error(E);
18512 case UO_Extension:
18513 // FIXME: Should extension allow i-c-e extension expressions in its scope?
18514 // If so, we could clear the diagnostic ID.
18515 return Visit(E->getSubExpr());
18516 case UO_Plus:
18517 // The result is just the value.
18518 return Visit(E->getSubExpr());
18519 case UO_Minus: {
18520 if (!Visit(E->getSubExpr()))
18521 return false;
18522 if (!Result.isInt()) return Error(E);
18523 const APSInt &Value = Result.getInt();
18524 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
18525 if (Info.checkingForUndefinedBehavior())
18526 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18527 diag::warn_integer_constant_overflow)
18528 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
18529 /*UpperCase=*/true, /*InsertSeparators=*/true)
18530 << E->getType() << E->getSourceRange();
18531
18532 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
18533 E->getType()))
18534 return false;
18535 }
18536 return Success(-Value, E);
18537 }
18538 case UO_Not: {
18539 if (!Visit(E->getSubExpr()))
18540 return false;
18541 if (!Result.isInt()) return Error(E);
18542 return Success(~Result.getInt(), E);
18543 }
18544 case UO_LNot: {
18545 bool bres;
18546 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18547 return false;
18548 return Success(!bres, E);
18549 }
18550 }
18551}
18552
18553/// HandleCast - This is used to evaluate implicit or explicit casts where the
18554/// result type is integer.
18555bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
18556 const Expr *SubExpr = E->getSubExpr();
18557 QualType DestType = E->getType();
18558 QualType SrcType = SubExpr->getType();
18559
18560 switch (E->getCastKind()) {
18561 case CK_BaseToDerived:
18562 case CK_DerivedToBase:
18563 case CK_UncheckedDerivedToBase:
18564 case CK_Dynamic:
18565 case CK_ToUnion:
18566 case CK_ArrayToPointerDecay:
18567 case CK_FunctionToPointerDecay:
18568 case CK_NullToPointer:
18569 case CK_NullToMemberPointer:
18570 case CK_BaseToDerivedMemberPointer:
18571 case CK_DerivedToBaseMemberPointer:
18572 case CK_ReinterpretMemberPointer:
18573 case CK_ConstructorConversion:
18574 case CK_IntegralToPointer:
18575 case CK_ToVoid:
18576 case CK_VectorSplat:
18577 case CK_IntegralToFloating:
18578 case CK_FloatingCast:
18579 case CK_CPointerToObjCPointerCast:
18580 case CK_BlockPointerToObjCPointerCast:
18581 case CK_AnyPointerToBlockPointerCast:
18582 case CK_ObjCObjectLValueCast:
18583 case CK_FloatingRealToComplex:
18584 case CK_FloatingComplexToReal:
18585 case CK_FloatingComplexCast:
18586 case CK_FloatingComplexToIntegralComplex:
18587 case CK_IntegralRealToComplex:
18588 case CK_IntegralComplexCast:
18589 case CK_IntegralComplexToFloatingComplex:
18590 case CK_BuiltinFnToFnPtr:
18591 case CK_ZeroToOCLOpaqueType:
18592 case CK_NonAtomicToAtomic:
18593 case CK_AddressSpaceConversion:
18594 case CK_IntToOCLSampler:
18595 case CK_FloatingToFixedPoint:
18596 case CK_FixedPointToFloating:
18597 case CK_FixedPointCast:
18598 case CK_IntegralToFixedPoint:
18599 case CK_MatrixCast:
18600 case CK_HLSLAggregateSplatCast:
18601 llvm_unreachable("invalid cast kind for integral value");
18602
18603 case CK_BitCast:
18604 case CK_Dependent:
18605 case CK_LValueBitCast:
18606 case CK_ARCProduceObject:
18607 case CK_ARCConsumeObject:
18608 case CK_ARCReclaimReturnedObject:
18609 case CK_ARCExtendBlockObject:
18610 case CK_CopyAndAutoreleaseBlockObject:
18611 return Error(E);
18612
18613 case CK_UserDefinedConversion:
18614 case CK_LValueToRValue:
18615 case CK_AtomicToNonAtomic:
18616 case CK_NoOp:
18617 case CK_LValueToRValueBitCast:
18618 case CK_HLSLArrayRValue:
18619 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18620
18621 case CK_MemberPointerToBoolean:
18622 case CK_PointerToBoolean:
18623 case CK_IntegralToBoolean:
18624 case CK_FloatingToBoolean:
18625 case CK_BooleanToSignedIntegral:
18626 case CK_FloatingComplexToBoolean:
18627 case CK_IntegralComplexToBoolean: {
18628 bool BoolResult;
18629 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
18630 return false;
18631 uint64_t IntResult = BoolResult;
18632 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
18633 IntResult = (uint64_t)-1;
18634 return Success(IntResult, E);
18635 }
18636
18637 case CK_FixedPointToIntegral: {
18638 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
18639 if (!EvaluateFixedPoint(SubExpr, Src, Info))
18640 return false;
18641 bool Overflowed;
18642 llvm::APSInt Result = Src.convertToInt(
18643 Info.Ctx.getIntWidth(DestType),
18644 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
18645 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
18646 return false;
18647 return Success(Result, E);
18648 }
18649
18650 case CK_FixedPointToBoolean: {
18651 // Unsigned padding does not affect this.
18652 APValue Val;
18653 if (!Evaluate(Val, Info, SubExpr))
18654 return false;
18655 return Success(Val.getFixedPoint().getBoolValue(), E);
18656 }
18657
18658 case CK_IntegralCast: {
18659 if (!Visit(SubExpr))
18660 return false;
18661
18662 if (!Result.isInt()) {
18663 // Allow casts of address-of-label differences if they are no-ops
18664 // or narrowing. (The narrowing case isn't actually guaranteed to
18665 // be constant-evaluatable except in some narrow cases which are hard
18666 // to detect here. We let it through on the assumption the user knows
18667 // what they are doing.)
18668 if (Result.isAddrLabelDiff())
18669 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
18670 // Only allow casts of lvalues if they are lossless.
18671 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
18672 }
18673
18674 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
18675 const auto *ED = DestType->getAsEnumDecl();
18676 // Check that the value is within the range of the enumeration values.
18677 //
18678 // This corressponds to [expr.static.cast]p10 which says:
18679 // A value of integral or enumeration type can be explicitly converted
18680 // to a complete enumeration type ... If the enumeration type does not
18681 // have a fixed underlying type, the value is unchanged if the original
18682 // value is within the range of the enumeration values ([dcl.enum]), and
18683 // otherwise, the behavior is undefined.
18684 //
18685 // This was resolved as part of DR2338 which has CD5 status.
18686 if (!ED->isFixed()) {
18687 llvm::APInt Min;
18688 llvm::APInt Max;
18689
18690 ED->getValueRange(Max, Min);
18691 --Max;
18692
18693 if (ED->getNumNegativeBits() &&
18694 (Max.slt(Result.getInt().getSExtValue()) ||
18695 Min.sgt(Result.getInt().getSExtValue())))
18696 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18697 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
18698 << Max.getSExtValue() << ED;
18699 else if (!ED->getNumNegativeBits() &&
18700 Max.ult(Result.getInt().getZExtValue()))
18701 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
18702 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
18703 << Max.getZExtValue() << ED;
18704 }
18705 }
18706
18707 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
18708 Result.getInt()), E);
18709 }
18710
18711 case CK_PointerToIntegral: {
18712 CCEDiag(E, diag::note_constexpr_invalid_cast)
18713 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
18714 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
18715
18716 LValue LV;
18717 if (!EvaluatePointer(SubExpr, LV, Info))
18718 return false;
18719
18720 if (LV.getLValueBase()) {
18721 // Only allow based lvalue casts if they are lossless.
18722 // FIXME: Allow a larger integer size than the pointer size, and allow
18723 // narrowing back down to pointer width in subsequent integral casts.
18724 // FIXME: Check integer type's active bits, not its type size.
18725 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
18726 return Error(E);
18727
18728 LV.Designator.setInvalid();
18729 LV.moveInto(Result);
18730 return true;
18731 }
18732
18733 APSInt AsInt;
18734 APValue V;
18735 LV.moveInto(V);
18736 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
18737 llvm_unreachable("Can't cast this!");
18738
18739 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
18740 }
18741
18742 case CK_IntegralComplexToReal: {
18743 ComplexValue C;
18744 if (!EvaluateComplex(SubExpr, C, Info))
18745 return false;
18746 return Success(C.getComplexIntReal(), E);
18747 }
18748
18749 case CK_FloatingToIntegral: {
18750 APFloat F(0.0);
18751 if (!EvaluateFloat(SubExpr, F, Info))
18752 return false;
18753
18754 APSInt Value;
18755 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
18756 return false;
18757 return Success(Value, E);
18758 }
18759 case CK_HLSLVectorTruncation: {
18760 APValue Val;
18761 if (!EvaluateVector(SubExpr, Val, Info))
18762 return Error(E);
18763 return Success(Val.getVectorElt(0), E);
18764 }
18765 case CK_HLSLMatrixTruncation: {
18766 // TODO: See #168935. Add matrix truncation support to expr constant.
18767 return Error(E);
18768 }
18769 case CK_HLSLElementwiseCast: {
18770 SmallVector<APValue> SrcVals;
18771 SmallVector<QualType> SrcTypes;
18772
18773 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
18774 return false;
18775
18776 // cast our single element
18777 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
18778 APValue ResultVal;
18779 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
18780 ResultVal))
18781 return false;
18782 return Success(ResultVal, E);
18783 }
18784 }
18785
18786 llvm_unreachable("unknown cast resulting in integral value");
18787}
18788
18789bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
18790 if (E->getSubExpr()->getType()->isAnyComplexType()) {
18791 ComplexValue LV;
18792 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18793 return false;
18794 if (!LV.isComplexInt())
18795 return Error(E);
18796 return Success(LV.getComplexIntReal(), E);
18797 }
18798
18799 return Visit(E->getSubExpr());
18800}
18801
18802bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
18803 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
18804 ComplexValue LV;
18805 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
18806 return false;
18807 if (!LV.isComplexInt())
18808 return Error(E);
18809 return Success(LV.getComplexIntImag(), E);
18810 }
18811
18812 VisitIgnoredValue(E->getSubExpr());
18813 return Success(0, E);
18814}
18815
18816bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
18817 return Success(E->getPackLength(), E);
18818}
18819
18820bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
18821 return Success(E->getValue(), E);
18822}
18823
18824bool IntExprEvaluator::VisitConceptSpecializationExpr(
18825 const ConceptSpecializationExpr *E) {
18826 return Success(E->isSatisfied(), E);
18827}
18828
18829bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
18830 return Success(E->isSatisfied(), E);
18831}
18832
18833bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18834 switch (E->getOpcode()) {
18835 default:
18836 // Invalid unary operators
18837 return Error(E);
18838 case UO_Plus:
18839 // The result is just the value.
18840 return Visit(E->getSubExpr());
18841 case UO_Minus: {
18842 if (!Visit(E->getSubExpr())) return false;
18843 if (!Result.isFixedPoint())
18844 return Error(E);
18845 bool Overflowed;
18846 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
18847 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
18848 return false;
18849 return Success(Negated, E);
18850 }
18851 case UO_LNot: {
18852 bool bres;
18853 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18854 return false;
18855 return Success(!bres, E);
18856 }
18857 }
18858}
18859
18860bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
18861 const Expr *SubExpr = E->getSubExpr();
18862 QualType DestType = E->getType();
18863 assert(DestType->isFixedPointType() &&
18864 "Expected destination type to be a fixed point type");
18865 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
18866
18867 switch (E->getCastKind()) {
18868 case CK_FixedPointCast: {
18869 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
18870 if (!EvaluateFixedPoint(SubExpr, Src, Info))
18871 return false;
18872 bool Overflowed;
18873 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
18874 if (Overflowed) {
18875 if (Info.checkingForUndefinedBehavior())
18876 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18877 diag::warn_fixedpoint_constant_overflow)
18878 << Result.toString() << E->getType();
18879 if (!HandleOverflow(Info, E, Result, E->getType()))
18880 return false;
18881 }
18882 return Success(Result, E);
18883 }
18884 case CK_IntegralToFixedPoint: {
18885 APSInt Src;
18886 if (!EvaluateInteger(SubExpr, Src, Info))
18887 return false;
18888
18889 bool Overflowed;
18890 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
18891 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18892
18893 if (Overflowed) {
18894 if (Info.checkingForUndefinedBehavior())
18895 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18896 diag::warn_fixedpoint_constant_overflow)
18897 << IntResult.toString() << E->getType();
18898 if (!HandleOverflow(Info, E, IntResult, E->getType()))
18899 return false;
18900 }
18901
18902 return Success(IntResult, E);
18903 }
18904 case CK_FloatingToFixedPoint: {
18905 APFloat Src(0.0);
18906 if (!EvaluateFloat(SubExpr, Src, Info))
18907 return false;
18908
18909 bool Overflowed;
18910 APFixedPoint Result = APFixedPoint::getFromFloatValue(
18911 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
18912
18913 if (Overflowed) {
18914 if (Info.checkingForUndefinedBehavior())
18915 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18916 diag::warn_fixedpoint_constant_overflow)
18917 << Result.toString() << E->getType();
18918 if (!HandleOverflow(Info, E, Result, E->getType()))
18919 return false;
18920 }
18921
18922 return Success(Result, E);
18923 }
18924 case CK_NoOp:
18925 case CK_LValueToRValue:
18926 return ExprEvaluatorBaseTy::VisitCastExpr(E);
18927 default:
18928 return Error(E);
18929 }
18930}
18931
18932bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18933 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
18934 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18935
18936 const Expr *LHS = E->getLHS();
18937 const Expr *RHS = E->getRHS();
18938 FixedPointSemantics ResultFXSema =
18939 Info.Ctx.getFixedPointSemantics(E->getType());
18940
18941 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
18942 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
18943 return false;
18944 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
18945 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
18946 return false;
18947
18948 bool OpOverflow = false, ConversionOverflow = false;
18949 APFixedPoint Result(LHSFX.getSemantics());
18950 switch (E->getOpcode()) {
18951 case BO_Add: {
18952 Result = LHSFX.add(RHSFX, &OpOverflow)
18953 .convert(ResultFXSema, &ConversionOverflow);
18954 break;
18955 }
18956 case BO_Sub: {
18957 Result = LHSFX.sub(RHSFX, &OpOverflow)
18958 .convert(ResultFXSema, &ConversionOverflow);
18959 break;
18960 }
18961 case BO_Mul: {
18962 Result = LHSFX.mul(RHSFX, &OpOverflow)
18963 .convert(ResultFXSema, &ConversionOverflow);
18964 break;
18965 }
18966 case BO_Div: {
18967 if (RHSFX.getValue() == 0) {
18968 Info.FFDiag(E, diag::note_expr_divide_by_zero);
18969 return false;
18970 }
18971 Result = LHSFX.div(RHSFX, &OpOverflow)
18972 .convert(ResultFXSema, &ConversionOverflow);
18973 break;
18974 }
18975 case BO_Shl:
18976 case BO_Shr: {
18977 FixedPointSemantics LHSSema = LHSFX.getSemantics();
18978 llvm::APSInt RHSVal = RHSFX.getValue();
18979
18980 unsigned ShiftBW =
18981 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
18982 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
18983 // Embedded-C 4.1.6.2.2:
18984 // The right operand must be nonnegative and less than the total number
18985 // of (nonpadding) bits of the fixed-point operand ...
18986 if (RHSVal.isNegative())
18987 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
18988 else if (Amt != RHSVal)
18989 Info.CCEDiag(E, diag::note_constexpr_large_shift)
18990 << RHSVal << E->getType() << ShiftBW;
18991
18992 if (E->getOpcode() == BO_Shl)
18993 Result = LHSFX.shl(Amt, &OpOverflow);
18994 else
18995 Result = LHSFX.shr(Amt, &OpOverflow);
18996 break;
18997 }
18998 default:
18999 return false;
19000 }
19001 if (OpOverflow || ConversionOverflow) {
19002 if (Info.checkingForUndefinedBehavior())
19003 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19004 diag::warn_fixedpoint_constant_overflow)
19005 << Result.toString() << E->getType();
19006 if (!HandleOverflow(Info, E, Result, E->getType()))
19007 return false;
19008 }
19009 return Success(Result, E);
19010}
19011
19012//===----------------------------------------------------------------------===//
19013// Float Evaluation
19014//===----------------------------------------------------------------------===//
19015
19016namespace {
19017class FloatExprEvaluator
19018 : public ExprEvaluatorBase<FloatExprEvaluator> {
19019 APFloat &Result;
19020public:
19021 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19022 : ExprEvaluatorBaseTy(info), Result(result) {}
19023
19024 bool Success(const APValue &V, const Expr *e) {
19025 Result = V.getFloat();
19026 return true;
19027 }
19028
19029 bool ZeroInitialization(const Expr *E) {
19030 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19031 return true;
19032 }
19033
19034 bool VisitCallExpr(const CallExpr *E);
19035
19036 bool VisitUnaryOperator(const UnaryOperator *E);
19037 bool VisitBinaryOperator(const BinaryOperator *E);
19038 bool VisitFloatingLiteral(const FloatingLiteral *E);
19039 bool VisitCastExpr(const CastExpr *E);
19040
19041 bool VisitUnaryReal(const UnaryOperator *E);
19042 bool VisitUnaryImag(const UnaryOperator *E);
19043
19044 // FIXME: Missing: array subscript of vector, member of vector
19045};
19046} // end anonymous namespace
19047
19048static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19049 assert(!E->isValueDependent());
19050 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19051 return FloatExprEvaluator(Info, Result).Visit(E);
19052}
19053
19054static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19055 QualType ResultTy,
19056 const Expr *Arg,
19057 bool SNaN,
19058 llvm::APFloat &Result) {
19059 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19060 if (!S) return false;
19061
19062 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19063
19064 llvm::APInt fill;
19065
19066 // Treat empty strings as if they were zero.
19067 if (S->getString().empty())
19068 fill = llvm::APInt(32, 0);
19069 else if (S->getString().getAsInteger(0, fill))
19070 return false;
19071
19072 if (Context.getTargetInfo().isNan2008()) {
19073 if (SNaN)
19074 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19075 else
19076 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19077 } else {
19078 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19079 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19080 // a different encoding to what became a standard in 2008, and for pre-
19081 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19082 // sNaN. This is now known as "legacy NaN" encoding.
19083 if (SNaN)
19084 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19085 else
19086 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19087 }
19088
19089 return true;
19090}
19091
19092bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19093 if (!IsConstantEvaluatedBuiltinCall(E))
19094 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19095
19096 switch (E->getBuiltinCallee()) {
19097 default:
19098 return false;
19099
19100 case Builtin::BI__builtin_huge_val:
19101 case Builtin::BI__builtin_huge_valf:
19102 case Builtin::BI__builtin_huge_vall:
19103 case Builtin::BI__builtin_huge_valf16:
19104 case Builtin::BI__builtin_huge_valf128:
19105 case Builtin::BI__builtin_inf:
19106 case Builtin::BI__builtin_inff:
19107 case Builtin::BI__builtin_infl:
19108 case Builtin::BI__builtin_inff16:
19109 case Builtin::BI__builtin_inff128: {
19110 const llvm::fltSemantics &Sem =
19111 Info.Ctx.getFloatTypeSemantics(E->getType());
19112 Result = llvm::APFloat::getInf(Sem);
19113 return true;
19114 }
19115
19116 case Builtin::BI__builtin_nans:
19117 case Builtin::BI__builtin_nansf:
19118 case Builtin::BI__builtin_nansl:
19119 case Builtin::BI__builtin_nansf16:
19120 case Builtin::BI__builtin_nansf128:
19121 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19122 true, Result))
19123 return Error(E);
19124 return true;
19125
19126 case Builtin::BI__builtin_nan:
19127 case Builtin::BI__builtin_nanf:
19128 case Builtin::BI__builtin_nanl:
19129 case Builtin::BI__builtin_nanf16:
19130 case Builtin::BI__builtin_nanf128:
19131 // If this is __builtin_nan() turn this into a nan, otherwise we
19132 // can't constant fold it.
19133 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19134 false, Result))
19135 return Error(E);
19136 return true;
19137
19138 case Builtin::BI__builtin_elementwise_abs:
19139 case Builtin::BI__builtin_fabs:
19140 case Builtin::BI__builtin_fabsf:
19141 case Builtin::BI__builtin_fabsl:
19142 case Builtin::BI__builtin_fabsf128:
19143 // The C standard says "fabs raises no floating-point exceptions,
19144 // even if x is a signaling NaN. The returned value is independent of
19145 // the current rounding direction mode." Therefore constant folding can
19146 // proceed without regard to the floating point settings.
19147 // Reference, WG14 N2478 F.10.4.3
19148 if (!EvaluateFloat(E->getArg(0), Result, Info))
19149 return false;
19150
19151 if (Result.isNegative())
19152 Result.changeSign();
19153 return true;
19154
19155 case Builtin::BI__arithmetic_fence:
19156 return EvaluateFloat(E->getArg(0), Result, Info);
19157
19158 // FIXME: Builtin::BI__builtin_powi
19159 // FIXME: Builtin::BI__builtin_powif
19160 // FIXME: Builtin::BI__builtin_powil
19161
19162 case Builtin::BI__builtin_copysign:
19163 case Builtin::BI__builtin_copysignf:
19164 case Builtin::BI__builtin_copysignl:
19165 case Builtin::BI__builtin_copysignf128: {
19166 APFloat RHS(0.);
19167 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19168 !EvaluateFloat(E->getArg(1), RHS, Info))
19169 return false;
19170 Result.copySign(RHS);
19171 return true;
19172 }
19173
19174 case Builtin::BI__builtin_fmax:
19175 case Builtin::BI__builtin_fmaxf:
19176 case Builtin::BI__builtin_fmaxl:
19177 case Builtin::BI__builtin_fmaxf16:
19178 case Builtin::BI__builtin_fmaxf128: {
19179 APFloat RHS(0.);
19180 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19181 !EvaluateFloat(E->getArg(1), RHS, Info))
19182 return false;
19183 Result = maxnum(Result, RHS);
19184 return true;
19185 }
19186
19187 case Builtin::BI__builtin_fmin:
19188 case Builtin::BI__builtin_fminf:
19189 case Builtin::BI__builtin_fminl:
19190 case Builtin::BI__builtin_fminf16:
19191 case Builtin::BI__builtin_fminf128: {
19192 APFloat RHS(0.);
19193 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19194 !EvaluateFloat(E->getArg(1), RHS, Info))
19195 return false;
19196 Result = minnum(Result, RHS);
19197 return true;
19198 }
19199
19200 case Builtin::BI__builtin_fmaximum_num:
19201 case Builtin::BI__builtin_fmaximum_numf:
19202 case Builtin::BI__builtin_fmaximum_numl:
19203 case Builtin::BI__builtin_fmaximum_numf16:
19204 case Builtin::BI__builtin_fmaximum_numf128: {
19205 APFloat RHS(0.);
19206 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19207 !EvaluateFloat(E->getArg(1), RHS, Info))
19208 return false;
19209 Result = maximumnum(Result, RHS);
19210 return true;
19211 }
19212
19213 case Builtin::BI__builtin_fminimum_num:
19214 case Builtin::BI__builtin_fminimum_numf:
19215 case Builtin::BI__builtin_fminimum_numl:
19216 case Builtin::BI__builtin_fminimum_numf16:
19217 case Builtin::BI__builtin_fminimum_numf128: {
19218 APFloat RHS(0.);
19219 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19220 !EvaluateFloat(E->getArg(1), RHS, Info))
19221 return false;
19222 Result = minimumnum(Result, RHS);
19223 return true;
19224 }
19225
19226 case Builtin::BI__builtin_elementwise_fma: {
19227 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19228 !E->getArg(2)->isPRValue()) {
19229 return false;
19230 }
19231 APFloat SourceY(0.), SourceZ(0.);
19232 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19233 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
19234 !EvaluateFloat(E->getArg(2), SourceZ, Info))
19235 return false;
19236 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
19237 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
19238 return true;
19239 }
19240
19241 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
19242 APValue Vec;
19243 APSInt IdxAPS;
19244 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
19245 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
19246 return false;
19247 unsigned N = Vec.getVectorLength();
19248 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19249 return Success(Vec.getVectorElt(Idx), E);
19250 }
19251 }
19252}
19253
19254bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19255 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19256 ComplexValue CV;
19257 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19258 return false;
19259 Result = CV.FloatReal;
19260 return true;
19261 }
19262
19263 return Visit(E->getSubExpr());
19264}
19265
19266bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19267 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19268 ComplexValue CV;
19269 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19270 return false;
19271 Result = CV.FloatImag;
19272 return true;
19273 }
19274
19275 VisitIgnoredValue(E->getSubExpr());
19276 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
19277 Result = llvm::APFloat::getZero(Sem);
19278 return true;
19279}
19280
19281bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19282 switch (E->getOpcode()) {
19283 default: return Error(E);
19284 case UO_Plus:
19285 return EvaluateFloat(E->getSubExpr(), Result, Info);
19286 case UO_Minus:
19287 // In C standard, WG14 N2478 F.3 p4
19288 // "the unary - raises no floating point exceptions,
19289 // even if the operand is signalling."
19290 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
19291 return false;
19292 Result.changeSign();
19293 return true;
19294 }
19295}
19296
19297bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19298 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19299 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19300
19301 APFloat RHS(0.0);
19302 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
19303 if (!LHSOK && !Info.noteFailure())
19304 return false;
19305 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
19306 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
19307}
19308
19309bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
19310 Result = E->getValue();
19311 return true;
19312}
19313
19314bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
19315 const Expr* SubExpr = E->getSubExpr();
19316
19317 switch (E->getCastKind()) {
19318 default:
19319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19320
19321 case CK_HLSLAggregateSplatCast:
19322 llvm_unreachable("invalid cast kind for floating value");
19323
19324 case CK_IntegralToFloating: {
19325 APSInt IntResult;
19326 const FPOptions FPO = E->getFPFeaturesInEffect(
19327 Info.Ctx.getLangOpts());
19328 return EvaluateInteger(SubExpr, IntResult, Info) &&
19329 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
19330 IntResult, E->getType(), Result);
19331 }
19332
19333 case CK_FixedPointToFloating: {
19334 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19335 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
19336 return false;
19337 Result =
19338 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
19339 return true;
19340 }
19341
19342 case CK_FloatingCast: {
19343 if (!Visit(SubExpr))
19344 return false;
19345 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
19346 Result);
19347 }
19348
19349 case CK_FloatingComplexToReal: {
19350 ComplexValue V;
19351 if (!EvaluateComplex(SubExpr, V, Info))
19352 return false;
19353 Result = V.getComplexFloatReal();
19354 return true;
19355 }
19356 case CK_HLSLVectorTruncation: {
19357 APValue Val;
19358 if (!EvaluateVector(SubExpr, Val, Info))
19359 return Error(E);
19360 return Success(Val.getVectorElt(0), E);
19361 }
19362 case CK_HLSLMatrixTruncation: {
19363 // TODO: See #168935. Add matrix truncation support to expr constant.
19364 return Error(E);
19365 }
19366 case CK_HLSLElementwiseCast: {
19367 SmallVector<APValue> SrcVals;
19368 SmallVector<QualType> SrcTypes;
19369
19370 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
19371 SrcTypes))
19372 return false;
19373 APValue Val;
19374
19375 // cast our single element
19376 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19377 APValue ResultVal;
19378 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
19379 ResultVal))
19380 return false;
19381 return Success(ResultVal, E);
19382 }
19383 }
19384}
19385
19386//===----------------------------------------------------------------------===//
19387// Complex Evaluation (for float and integer)
19388//===----------------------------------------------------------------------===//
19389
19390namespace {
19391class ComplexExprEvaluator
19392 : public ExprEvaluatorBase<ComplexExprEvaluator> {
19393 ComplexValue &Result;
19394
19395public:
19396 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
19397 : ExprEvaluatorBaseTy(info), Result(Result) {}
19398
19399 bool Success(const APValue &V, const Expr *e) {
19400 Result.setFrom(V);
19401 return true;
19402 }
19403
19404 bool ZeroInitialization(const Expr *E);
19405
19406 //===--------------------------------------------------------------------===//
19407 // Visitor Methods
19408 //===--------------------------------------------------------------------===//
19409
19410 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
19411 bool VisitCastExpr(const CastExpr *E);
19412 bool VisitBinaryOperator(const BinaryOperator *E);
19413 bool VisitUnaryOperator(const UnaryOperator *E);
19414 bool VisitInitListExpr(const InitListExpr *E);
19415 bool VisitCallExpr(const CallExpr *E);
19416};
19417} // end anonymous namespace
19418
19419static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
19420 EvalInfo &Info) {
19421 assert(!E->isValueDependent());
19422 assert(E->isPRValue() && E->getType()->isAnyComplexType());
19423 return ComplexExprEvaluator(Info, Result).Visit(E);
19424}
19425
19426bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
19427 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
19428 if (ElemTy->isRealFloatingType()) {
19429 Result.makeComplexFloat();
19430 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
19431 Result.FloatReal = Zero;
19432 Result.FloatImag = Zero;
19433 } else {
19434 Result.makeComplexInt();
19435 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
19436 Result.IntReal = Zero;
19437 Result.IntImag = Zero;
19438 }
19439 return true;
19440}
19441
19442bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
19443 const Expr* SubExpr = E->getSubExpr();
19444
19445 if (SubExpr->getType()->isRealFloatingType()) {
19446 Result.makeComplexFloat();
19447 APFloat &Imag = Result.FloatImag;
19448 if (!EvaluateFloat(SubExpr, Imag, Info))
19449 return false;
19450
19451 Result.FloatReal = APFloat(Imag.getSemantics());
19452 return true;
19453 } else {
19454 assert(SubExpr->getType()->isIntegerType() &&
19455 "Unexpected imaginary literal.");
19456
19457 Result.makeComplexInt();
19458 APSInt &Imag = Result.IntImag;
19459 if (!EvaluateInteger(SubExpr, Imag, Info))
19460 return false;
19461
19462 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
19463 return true;
19464 }
19465}
19466
19467bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
19468
19469 switch (E->getCastKind()) {
19470 case CK_BitCast:
19471 case CK_BaseToDerived:
19472 case CK_DerivedToBase:
19473 case CK_UncheckedDerivedToBase:
19474 case CK_Dynamic:
19475 case CK_ToUnion:
19476 case CK_ArrayToPointerDecay:
19477 case CK_FunctionToPointerDecay:
19478 case CK_NullToPointer:
19479 case CK_NullToMemberPointer:
19480 case CK_BaseToDerivedMemberPointer:
19481 case CK_DerivedToBaseMemberPointer:
19482 case CK_MemberPointerToBoolean:
19483 case CK_ReinterpretMemberPointer:
19484 case CK_ConstructorConversion:
19485 case CK_IntegralToPointer:
19486 case CK_PointerToIntegral:
19487 case CK_PointerToBoolean:
19488 case CK_ToVoid:
19489 case CK_VectorSplat:
19490 case CK_IntegralCast:
19491 case CK_BooleanToSignedIntegral:
19492 case CK_IntegralToBoolean:
19493 case CK_IntegralToFloating:
19494 case CK_FloatingToIntegral:
19495 case CK_FloatingToBoolean:
19496 case CK_FloatingCast:
19497 case CK_CPointerToObjCPointerCast:
19498 case CK_BlockPointerToObjCPointerCast:
19499 case CK_AnyPointerToBlockPointerCast:
19500 case CK_ObjCObjectLValueCast:
19501 case CK_FloatingComplexToReal:
19502 case CK_FloatingComplexToBoolean:
19503 case CK_IntegralComplexToReal:
19504 case CK_IntegralComplexToBoolean:
19505 case CK_ARCProduceObject:
19506 case CK_ARCConsumeObject:
19507 case CK_ARCReclaimReturnedObject:
19508 case CK_ARCExtendBlockObject:
19509 case CK_CopyAndAutoreleaseBlockObject:
19510 case CK_BuiltinFnToFnPtr:
19511 case CK_ZeroToOCLOpaqueType:
19512 case CK_NonAtomicToAtomic:
19513 case CK_AddressSpaceConversion:
19514 case CK_IntToOCLSampler:
19515 case CK_FloatingToFixedPoint:
19516 case CK_FixedPointToFloating:
19517 case CK_FixedPointCast:
19518 case CK_FixedPointToBoolean:
19519 case CK_FixedPointToIntegral:
19520 case CK_IntegralToFixedPoint:
19521 case CK_MatrixCast:
19522 case CK_HLSLVectorTruncation:
19523 case CK_HLSLMatrixTruncation:
19524 case CK_HLSLElementwiseCast:
19525 case CK_HLSLAggregateSplatCast:
19526 llvm_unreachable("invalid cast kind for complex value");
19527
19528 case CK_LValueToRValue:
19529 case CK_AtomicToNonAtomic:
19530 case CK_NoOp:
19531 case CK_LValueToRValueBitCast:
19532 case CK_HLSLArrayRValue:
19533 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19534
19535 case CK_Dependent:
19536 case CK_LValueBitCast:
19537 case CK_UserDefinedConversion:
19538 return Error(E);
19539
19540 case CK_FloatingRealToComplex: {
19541 APFloat &Real = Result.FloatReal;
19542 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
19543 return false;
19544
19545 Result.makeComplexFloat();
19546 Result.FloatImag = APFloat(Real.getSemantics());
19547 return true;
19548 }
19549
19550 case CK_FloatingComplexCast: {
19551 if (!Visit(E->getSubExpr()))
19552 return false;
19553
19554 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19555 QualType From
19556 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19557
19558 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
19559 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
19560 }
19561
19562 case CK_FloatingComplexToIntegralComplex: {
19563 if (!Visit(E->getSubExpr()))
19564 return false;
19565
19566 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19567 QualType From
19568 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19569 Result.makeComplexInt();
19570 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
19571 To, Result.IntReal) &&
19572 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
19573 To, Result.IntImag);
19574 }
19575
19576 case CK_IntegralRealToComplex: {
19577 APSInt &Real = Result.IntReal;
19578 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
19579 return false;
19580
19581 Result.makeComplexInt();
19582 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
19583 return true;
19584 }
19585
19586 case CK_IntegralComplexCast: {
19587 if (!Visit(E->getSubExpr()))
19588 return false;
19589
19590 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19591 QualType From
19592 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19593
19594 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
19595 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
19596 return true;
19597 }
19598
19599 case CK_IntegralComplexToFloatingComplex: {
19600 if (!Visit(E->getSubExpr()))
19601 return false;
19602
19603 const FPOptions FPO = E->getFPFeaturesInEffect(
19604 Info.Ctx.getLangOpts());
19605 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19606 QualType From
19607 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19608 Result.makeComplexFloat();
19609 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
19610 To, Result.FloatReal) &&
19611 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
19612 To, Result.FloatImag);
19613 }
19614 }
19615
19616 llvm_unreachable("unknown cast resulting in complex value");
19617}
19618
19619uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
19620 // Lookup Table for Multiplicative Inverse in GF(2^8)
19621 const uint8_t GFInv[256] = {
19622 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
19623 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
19624 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
19625 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
19626 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
19627 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
19628 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
19629 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
19630 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
19631 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
19632 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
19633 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
19634 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
19635 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
19636 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
19637 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
19638 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
19639 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
19640 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
19641 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
19642 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
19643 0xcd, 0x1a, 0x41, 0x1c};
19644
19645 return GFInv[Byte];
19646}
19647
19648uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
19649 bool Inverse) {
19650 unsigned NumBitsInByte = 8;
19651 // Computing the affine transformation
19652 uint8_t RetByte = 0;
19653 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19654 uint8_t AByte =
19655 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
19656 .getLoBits(8)
19657 .getZExtValue();
19658 uint8_t Product;
19659 if (Inverse) {
19660 Product = AByte & GFNIMultiplicativeInverse(XByte);
19661 } else {
19662 Product = AByte & XByte;
19663 }
19664 uint8_t Parity = 0;
19665
19666 // Dot product in GF(2) uses XOR instead of addition
19667 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
19668 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
19669 }
19670
19671 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
19672 RetByte |= (Temp ^ Parity) << BitIdx;
19673 }
19674 return RetByte;
19675}
19676
19677uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
19678 // Multiplying two polynomials of degree 7
19679 // Polynomial of degree 7
19680 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
19681 uint16_t TWord = 0;
19682 unsigned NumBitsInByte = 8;
19683 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
19684 if ((BByte >> BitIdx) & 0x1) {
19685 TWord = TWord ^ (AByte << BitIdx);
19686 }
19687 }
19688
19689 // When multiplying two polynomials of degree 7
19690 // results in a polynomial of degree 14
19691 // so the result has to be reduced to 7
19692 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
19693 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
19694 if ((TWord >> BitIdx) & 0x1) {
19695 TWord = TWord ^ (0x11B << (BitIdx - 8));
19696 }
19697 }
19698 return (TWord & 0xFF);
19699}
19700
19701void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
19702 APFloat &ResR, APFloat &ResI) {
19703 // This is an implementation of complex multiplication according to the
19704 // constraints laid out in C11 Annex G. The implementation uses the
19705 // following naming scheme:
19706 // (a + ib) * (c + id)
19707
19708 APFloat AC = A * C;
19709 APFloat BD = B * D;
19710 APFloat AD = A * D;
19711 APFloat BC = B * C;
19712 ResR = AC - BD;
19713 ResI = AD + BC;
19714 if (ResR.isNaN() && ResI.isNaN()) {
19715 bool Recalc = false;
19716 if (A.isInfinity() || B.isInfinity()) {
19717 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19718 A);
19719 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19720 B);
19721 if (C.isNaN())
19722 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19723 if (D.isNaN())
19724 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19725 Recalc = true;
19726 }
19727 if (C.isInfinity() || D.isInfinity()) {
19728 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19729 C);
19730 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19731 D);
19732 if (A.isNaN())
19733 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19734 if (B.isNaN())
19735 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19736 Recalc = true;
19737 }
19738 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
19739 BC.isInfinity())) {
19740 if (A.isNaN())
19741 A = APFloat::copySign(APFloat(A.getSemantics()), A);
19742 if (B.isNaN())
19743 B = APFloat::copySign(APFloat(B.getSemantics()), B);
19744 if (C.isNaN())
19745 C = APFloat::copySign(APFloat(C.getSemantics()), C);
19746 if (D.isNaN())
19747 D = APFloat::copySign(APFloat(D.getSemantics()), D);
19748 Recalc = true;
19749 }
19750 if (Recalc) {
19751 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
19752 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
19753 }
19754 }
19755}
19756
19757void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
19758 APFloat &ResR, APFloat &ResI) {
19759 // This is an implementation of complex division according to the
19760 // constraints laid out in C11 Annex G. The implementation uses the
19761 // following naming scheme:
19762 // (a + ib) / (c + id)
19763
19764 int DenomLogB = 0;
19765 APFloat MaxCD = maxnum(abs(C), abs(D));
19766 if (MaxCD.isFinite()) {
19767 DenomLogB = ilogb(MaxCD);
19768 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
19769 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
19770 }
19771 APFloat Denom = C * C + D * D;
19772 ResR =
19773 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19774 ResI =
19775 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
19776 if (ResR.isNaN() && ResI.isNaN()) {
19777 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
19778 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
19779 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
19780 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
19781 D.isFinite()) {
19782 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
19783 A);
19784 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
19785 B);
19786 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
19787 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
19788 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
19789 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
19790 C);
19791 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
19792 D);
19793 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
19794 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
19795 }
19796 }
19797}
19798
19799bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19800 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19801 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19802
19803 // Track whether the LHS or RHS is real at the type system level. When this is
19804 // the case we can simplify our evaluation strategy.
19805 bool LHSReal = false, RHSReal = false;
19806
19807 bool LHSOK;
19808 if (E->getLHS()->getType()->isRealFloatingType()) {
19809 LHSReal = true;
19810 APFloat &Real = Result.FloatReal;
19811 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
19812 if (LHSOK) {
19813 Result.makeComplexFloat();
19814 Result.FloatImag = APFloat(Real.getSemantics());
19815 }
19816 } else {
19817 LHSOK = Visit(E->getLHS());
19818 }
19819 if (!LHSOK && !Info.noteFailure())
19820 return false;
19821
19822 ComplexValue RHS;
19823 if (E->getRHS()->getType()->isRealFloatingType()) {
19824 RHSReal = true;
19825 APFloat &Real = RHS.FloatReal;
19826 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
19827 return false;
19828 RHS.makeComplexFloat();
19829 RHS.FloatImag = APFloat(Real.getSemantics());
19830 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19831 return false;
19832
19833 assert(!(LHSReal && RHSReal) &&
19834 "Cannot have both operands of a complex operation be real.");
19835 switch (E->getOpcode()) {
19836 default: return Error(E);
19837 case BO_Add:
19838 if (Result.isComplexFloat()) {
19839 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
19840 APFloat::rmNearestTiesToEven);
19841 if (LHSReal)
19842 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
19843 else if (!RHSReal)
19844 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
19845 APFloat::rmNearestTiesToEven);
19846 } else {
19847 Result.getComplexIntReal() += RHS.getComplexIntReal();
19848 Result.getComplexIntImag() += RHS.getComplexIntImag();
19849 }
19850 break;
19851 case BO_Sub:
19852 if (Result.isComplexFloat()) {
19853 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
19854 APFloat::rmNearestTiesToEven);
19855 if (LHSReal) {
19856 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
19857 Result.getComplexFloatImag().changeSign();
19858 } else if (!RHSReal) {
19859 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
19860 APFloat::rmNearestTiesToEven);
19861 }
19862 } else {
19863 Result.getComplexIntReal() -= RHS.getComplexIntReal();
19864 Result.getComplexIntImag() -= RHS.getComplexIntImag();
19865 }
19866 break;
19867 case BO_Mul:
19868 if (Result.isComplexFloat()) {
19869 // This is an implementation of complex multiplication according to the
19870 // constraints laid out in C11 Annex G. The implementation uses the
19871 // following naming scheme:
19872 // (a + ib) * (c + id)
19873 ComplexValue LHS = Result;
19874 APFloat &A = LHS.getComplexFloatReal();
19875 APFloat &B = LHS.getComplexFloatImag();
19876 APFloat &C = RHS.getComplexFloatReal();
19877 APFloat &D = RHS.getComplexFloatImag();
19878 APFloat &ResR = Result.getComplexFloatReal();
19879 APFloat &ResI = Result.getComplexFloatImag();
19880 if (LHSReal) {
19881 assert(!RHSReal && "Cannot have two real operands for a complex op!");
19882 ResR = A;
19883 ResI = A;
19884 // ResR = A * C;
19885 // ResI = A * D;
19886 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
19887 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
19888 return false;
19889 } else if (RHSReal) {
19890 // ResR = C * A;
19891 // ResI = C * B;
19892 ResR = C;
19893 ResI = C;
19894 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
19895 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
19896 return false;
19897 } else {
19898 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
19899 }
19900 } else {
19901 ComplexValue LHS = Result;
19902 Result.getComplexIntReal() =
19903 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
19904 LHS.getComplexIntImag() * RHS.getComplexIntImag());
19905 Result.getComplexIntImag() =
19906 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
19907 LHS.getComplexIntImag() * RHS.getComplexIntReal());
19908 }
19909 break;
19910 case BO_Div:
19911 if (Result.isComplexFloat()) {
19912 // This is an implementation of complex division according to the
19913 // constraints laid out in C11 Annex G. The implementation uses the
19914 // following naming scheme:
19915 // (a + ib) / (c + id)
19916 ComplexValue LHS = Result;
19917 APFloat &A = LHS.getComplexFloatReal();
19918 APFloat &B = LHS.getComplexFloatImag();
19919 APFloat &C = RHS.getComplexFloatReal();
19920 APFloat &D = RHS.getComplexFloatImag();
19921 APFloat &ResR = Result.getComplexFloatReal();
19922 APFloat &ResI = Result.getComplexFloatImag();
19923 if (RHSReal) {
19924 ResR = A;
19925 ResI = B;
19926 // ResR = A / C;
19927 // ResI = B / C;
19928 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
19929 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
19930 return false;
19931 } else {
19932 if (LHSReal) {
19933 // No real optimizations we can do here, stub out with zero.
19934 B = APFloat::getZero(A.getSemantics());
19935 }
19936 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
19937 }
19938 } else {
19939 ComplexValue LHS = Result;
19940 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
19941 RHS.getComplexIntImag() * RHS.getComplexIntImag();
19942 if (Den.isZero())
19943 return Error(E, diag::note_expr_divide_by_zero);
19944
19945 Result.getComplexIntReal() =
19946 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
19947 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
19948 Result.getComplexIntImag() =
19949 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
19950 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
19951 }
19952 break;
19953 }
19954
19955 return true;
19956}
19957
19958bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19959 // Get the operand value into 'Result'.
19960 if (!Visit(E->getSubExpr()))
19961 return false;
19962
19963 switch (E->getOpcode()) {
19964 default:
19965 return Error(E);
19966 case UO_Extension:
19967 return true;
19968 case UO_Plus:
19969 // The result is always just the subexpr.
19970 return true;
19971 case UO_Minus:
19972 if (Result.isComplexFloat()) {
19973 Result.getComplexFloatReal().changeSign();
19974 Result.getComplexFloatImag().changeSign();
19975 }
19976 else {
19977 Result.getComplexIntReal() = -Result.getComplexIntReal();
19978 Result.getComplexIntImag() = -Result.getComplexIntImag();
19979 }
19980 return true;
19981 case UO_Not:
19982 if (Result.isComplexFloat())
19983 Result.getComplexFloatImag().changeSign();
19984 else
19985 Result.getComplexIntImag() = -Result.getComplexIntImag();
19986 return true;
19987 }
19988}
19989
19990bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
19991 if (E->getNumInits() == 2) {
19992 if (E->getType()->isComplexType()) {
19993 Result.makeComplexFloat();
19994 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
19995 return false;
19996 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
19997 return false;
19998 } else {
19999 Result.makeComplexInt();
20000 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20001 return false;
20002 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20003 return false;
20004 }
20005 return true;
20006 }
20007 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20008}
20009
20010bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20011 if (!IsConstantEvaluatedBuiltinCall(E))
20012 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20013
20014 switch (E->getBuiltinCallee()) {
20015 case Builtin::BI__builtin_complex:
20016 Result.makeComplexFloat();
20017 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20018 return false;
20019 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20020 return false;
20021 return true;
20022
20023 default:
20024 return false;
20025 }
20026}
20027
20028//===----------------------------------------------------------------------===//
20029// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20030// implicit conversion.
20031//===----------------------------------------------------------------------===//
20032
20033namespace {
20034class AtomicExprEvaluator :
20035 public ExprEvaluatorBase<AtomicExprEvaluator> {
20036 const LValue *This;
20037 APValue &Result;
20038public:
20039 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20040 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20041
20042 bool Success(const APValue &V, const Expr *E) {
20043 Result = V;
20044 return true;
20045 }
20046
20047 bool ZeroInitialization(const Expr *E) {
20048 ImplicitValueInitExpr VIE(
20049 E->getType()->castAs<AtomicType>()->getValueType());
20050 // For atomic-qualified class (and array) types in C++, initialize the
20051 // _Atomic-wrapped subobject directly, in-place.
20052 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20053 : Evaluate(Result, Info, &VIE);
20054 }
20055
20056 bool VisitCastExpr(const CastExpr *E) {
20057 switch (E->getCastKind()) {
20058 default:
20059 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20060 case CK_NullToPointer:
20061 VisitIgnoredValue(E->getSubExpr());
20062 return ZeroInitialization(E);
20063 case CK_NonAtomicToAtomic:
20064 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20065 : Evaluate(Result, Info, E->getSubExpr());
20066 }
20067 }
20068};
20069} // end anonymous namespace
20070
20071static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20072 EvalInfo &Info) {
20073 assert(!E->isValueDependent());
20074 assert(E->isPRValue() && E->getType()->isAtomicType());
20075 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20076}
20077
20078//===----------------------------------------------------------------------===//
20079// Void expression evaluation, primarily for a cast to void on the LHS of a
20080// comma operator
20081//===----------------------------------------------------------------------===//
20082
20083namespace {
20084class VoidExprEvaluator
20085 : public ExprEvaluatorBase<VoidExprEvaluator> {
20086public:
20087 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20088
20089 bool Success(const APValue &V, const Expr *e) { return true; }
20090
20091 bool ZeroInitialization(const Expr *E) { return true; }
20092
20093 bool VisitCastExpr(const CastExpr *E) {
20094 switch (E->getCastKind()) {
20095 default:
20096 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20097 case CK_ToVoid:
20098 VisitIgnoredValue(E->getSubExpr());
20099 return true;
20100 }
20101 }
20102
20103 bool VisitCallExpr(const CallExpr *E) {
20104 if (!IsConstantEvaluatedBuiltinCall(E))
20105 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20106
20107 switch (E->getBuiltinCallee()) {
20108 case Builtin::BI__assume:
20109 case Builtin::BI__builtin_assume:
20110 // The argument is not evaluated!
20111 return true;
20112
20113 case Builtin::BI__builtin_operator_delete:
20114 return HandleOperatorDeleteCall(Info, E);
20115
20116 default:
20117 return false;
20118 }
20119 }
20120
20121 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20122};
20123} // end anonymous namespace
20124
20125bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20126 // We cannot speculatively evaluate a delete expression.
20127 if (Info.SpeculativeEvaluationDepth)
20128 return false;
20129
20130 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20131 if (!OperatorDelete
20132 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20133 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20134 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20135 return false;
20136 }
20137
20138 const Expr *Arg = E->getArgument();
20139
20140 LValue Pointer;
20141 if (!EvaluatePointer(Arg, Pointer, Info))
20142 return false;
20143 if (Pointer.Designator.Invalid)
20144 return false;
20145
20146 // Deleting a null pointer has no effect.
20147 if (Pointer.isNullPointer()) {
20148 // This is the only case where we need to produce an extension warning:
20149 // the only other way we can succeed is if we find a dynamic allocation,
20150 // and we will have warned when we allocated it in that case.
20151 if (!Info.getLangOpts().CPlusPlus20)
20152 Info.CCEDiag(E, diag::note_constexpr_new);
20153 return true;
20154 }
20155
20156 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20157 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20158 if (!Alloc)
20159 return false;
20160 QualType AllocType = Pointer.Base.getDynamicAllocType();
20161
20162 // For the non-array case, the designator must be empty if the static type
20163 // does not have a virtual destructor.
20164 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20166 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20167 << Arg->getType()->getPointeeType() << AllocType;
20168 return false;
20169 }
20170
20171 // For a class type with a virtual destructor, the selected operator delete
20172 // is the one looked up when building the destructor.
20173 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20174 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20175 if (VirtualDelete &&
20176 !VirtualDelete
20177 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20178 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20179 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20180 return false;
20181 }
20182 }
20183
20184 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20185 (*Alloc)->Value, AllocType))
20186 return false;
20187
20188 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20189 // The element was already erased. This means the destructor call also
20190 // deleted the object.
20191 // FIXME: This probably results in undefined behavior before we get this
20192 // far, and should be diagnosed elsewhere first.
20193 Info.FFDiag(E, diag::note_constexpr_double_delete);
20194 return false;
20195 }
20196
20197 return true;
20198}
20199
20200static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
20201 assert(!E->isValueDependent());
20202 assert(E->isPRValue() && E->getType()->isVoidType());
20203 return VoidExprEvaluator(Info).Visit(E);
20204}
20205
20206//===----------------------------------------------------------------------===//
20207// Top level Expr::EvaluateAsRValue method.
20208//===----------------------------------------------------------------------===//
20209
20210static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
20211 assert(!E->isValueDependent());
20212 // In C, function designators are not lvalues, but we evaluate them as if they
20213 // are.
20214 QualType T = E->getType();
20215 if (E->isGLValue() || T->isFunctionType()) {
20216 LValue LV;
20217 if (!EvaluateLValue(E, LV, Info))
20218 return false;
20219 LV.moveInto(Result);
20220 } else if (T->isVectorType()) {
20221 if (!EvaluateVector(E, Result, Info))
20222 return false;
20223 } else if (T->isIntegralOrEnumerationType()) {
20224 if (!IntExprEvaluator(Info, Result).Visit(E))
20225 return false;
20226 } else if (T->hasPointerRepresentation()) {
20227 LValue LV;
20228 if (!EvaluatePointer(E, LV, Info))
20229 return false;
20230 LV.moveInto(Result);
20231 } else if (T->isRealFloatingType()) {
20232 llvm::APFloat F(0.0);
20233 if (!EvaluateFloat(E, F, Info))
20234 return false;
20235 Result = APValue(F);
20236 } else if (T->isAnyComplexType()) {
20237 ComplexValue C;
20238 if (!EvaluateComplex(E, C, Info))
20239 return false;
20240 C.moveInto(Result);
20241 } else if (T->isFixedPointType()) {
20242 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
20243 } else if (T->isMemberPointerType()) {
20244 MemberPtr P;
20245 if (!EvaluateMemberPointer(E, P, Info))
20246 return false;
20247 P.moveInto(Result);
20248 return true;
20249 } else if (T->isArrayType()) {
20250 LValue LV;
20251 APValue &Value =
20252 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20253 if (!EvaluateArray(E, LV, Value, Info))
20254 return false;
20255 Result = Value;
20256 } else if (T->isRecordType()) {
20257 LValue LV;
20258 APValue &Value =
20259 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20260 if (!EvaluateRecord(E, LV, Value, Info))
20261 return false;
20262 Result = Value;
20263 } else if (T->isVoidType()) {
20264 if (!Info.getLangOpts().CPlusPlus11)
20265 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
20266 << E->getType();
20267 if (!EvaluateVoid(E, Info))
20268 return false;
20269 } else if (T->isAtomicType()) {
20270 QualType Unqual = T.getAtomicUnqualifiedType();
20271 if (Unqual->isArrayType() || Unqual->isRecordType()) {
20272 LValue LV;
20273 APValue &Value = Info.CurrentCall->createTemporary(
20274 E, Unqual, ScopeKind::FullExpression, LV);
20275 if (!EvaluateAtomic(E, &LV, Value, Info))
20276 return false;
20277 Result = Value;
20278 } else {
20279 if (!EvaluateAtomic(E, nullptr, Result, Info))
20280 return false;
20281 }
20282 } else if (Info.getLangOpts().CPlusPlus11) {
20283 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
20284 return false;
20285 } else {
20286 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
20287 return false;
20288 }
20289
20290 return true;
20291}
20292
20293/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
20294/// cases, the in-place evaluation is essential, since later initializers for
20295/// an object can indirectly refer to subobjects which were initialized earlier.
20296static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
20297 const Expr *E, bool AllowNonLiteralTypes) {
20298 assert(!E->isValueDependent());
20299
20300 // Normally expressions passed to EvaluateInPlace have a type, but not when
20301 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
20302 // replaced with a CXXConstructExpr. This can happen in LLDB.
20303 if (E->getType().isNull())
20304 return false;
20305
20306 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
20307 return false;
20308
20309 if (E->isPRValue()) {
20310 // Evaluate arrays and record types in-place, so that later initializers can
20311 // refer to earlier-initialized members of the object.
20312 QualType T = E->getType();
20313 if (T->isArrayType())
20314 return EvaluateArray(E, This, Result, Info);
20315 else if (T->isRecordType())
20316 return EvaluateRecord(E, This, Result, Info);
20317 else if (T->isAtomicType()) {
20318 QualType Unqual = T.getAtomicUnqualifiedType();
20319 if (Unqual->isArrayType() || Unqual->isRecordType())
20320 return EvaluateAtomic(E, &This, Result, Info);
20321 }
20322 }
20323
20324 // For any other type, in-place evaluation is unimportant.
20325 return Evaluate(Result, Info, E);
20326}
20327
20328/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
20329/// lvalue-to-rvalue cast if it is an lvalue.
20330static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
20331 assert(!E->isValueDependent());
20332
20333 if (E->getType().isNull())
20334 return false;
20335
20336 if (!CheckLiteralType(Info, E))
20337 return false;
20338
20339 if (Info.EnableNewConstInterp) {
20340 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
20341 return false;
20342 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20343 ConstantExprKind::Normal);
20344 }
20345
20346 if (!::Evaluate(Result, Info, E))
20347 return false;
20348
20349 // Implicit lvalue-to-rvalue cast.
20350 if (E->isGLValue()) {
20351 LValue LV;
20352 LV.setFrom(Info.Ctx, Result);
20353 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
20354 return false;
20355 }
20356
20357 // Check this core constant expression is a constant expression.
20358 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20359 ConstantExprKind::Normal) &&
20360 CheckMemoryLeaks(Info);
20361}
20362
20363static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
20364 const ASTContext &Ctx, bool &IsConst) {
20365 // Fast-path evaluations of integer literals, since we sometimes see files
20366 // containing vast quantities of these.
20367 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
20368 Result =
20369 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
20370 IsConst = true;
20371 return true;
20372 }
20373
20374 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
20375 Result = APValue(APSInt(APInt(1, L->getValue())));
20376 IsConst = true;
20377 return true;
20378 }
20379
20380 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
20381 Result = APValue(FL->getValue());
20382 IsConst = true;
20383 return true;
20384 }
20385
20386 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
20387 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
20388 IsConst = true;
20389 return true;
20390 }
20391
20392 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
20393 if (CE->hasAPValueResult()) {
20394 APValue APV = CE->getAPValueResult();
20395 if (!APV.isLValue()) {
20396 Result = std::move(APV);
20397 IsConst = true;
20398 return true;
20399 }
20400 }
20401
20402 // The SubExpr is usually just an IntegerLiteral.
20403 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
20404 }
20405
20406 // This case should be rare, but we need to check it before we check on
20407 // the type below.
20408 if (Exp->getType().isNull()) {
20409 IsConst = false;
20410 return true;
20411 }
20412
20413 return false;
20414}
20415
20418 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
20419 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
20420}
20421
20422static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
20423 const ASTContext &Ctx, EvalInfo &Info) {
20424 assert(!E->isValueDependent());
20425 bool IsConst;
20426 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
20427 return IsConst;
20428
20429 return EvaluateAsRValue(Info, E, Result.Val);
20430}
20431
20433 const ASTContext &Ctx,
20434 Expr::SideEffectsKind AllowSideEffects,
20435 EvalInfo &Info) {
20436 assert(!E->isValueDependent());
20438 return false;
20439
20440 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
20441 !ExprResult.Val.isInt() ||
20442 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20443 return false;
20444
20445 return true;
20446}
20447
20449 const ASTContext &Ctx,
20450 Expr::SideEffectsKind AllowSideEffects,
20451 EvalInfo &Info) {
20452 assert(!E->isValueDependent());
20453 if (!E->getType()->isFixedPointType())
20454 return false;
20455
20456 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
20457 return false;
20458
20459 if (!ExprResult.Val.isFixedPoint() ||
20460 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20461 return false;
20462
20463 return true;
20464}
20465
20466/// EvaluateAsRValue - Return true if this is a constant which we can fold using
20467/// any crazy technique (that has nothing to do with language standards) that
20468/// we want to. If this function returns true, it returns the folded constant
20469/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
20470/// will be applied to the result.
20472 bool InConstantContext) const {
20473 assert(!isValueDependent() &&
20474 "Expression evaluator can't be called on a dependent expression.");
20475 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
20476 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20477 Info.InConstantContext = InConstantContext;
20478 return ::EvaluateAsRValue(this, Result, Ctx, Info);
20479}
20480
20482 bool InConstantContext) const {
20483 assert(!isValueDependent() &&
20484 "Expression evaluator can't be called on a dependent expression.");
20485 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
20486 EvalResult Scratch;
20487 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
20488 HandleConversionToBool(Scratch.Val, Result);
20489}
20490
20492 SideEffectsKind AllowSideEffects,
20493 bool InConstantContext) const {
20494 assert(!isValueDependent() &&
20495 "Expression evaluator can't be called on a dependent expression.");
20496 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
20497 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20498 Info.InConstantContext = InConstantContext;
20499 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
20500}
20501
20503 SideEffectsKind AllowSideEffects,
20504 bool InConstantContext) const {
20505 assert(!isValueDependent() &&
20506 "Expression evaluator can't be called on a dependent expression.");
20507 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
20508 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20509 Info.InConstantContext = InConstantContext;
20510 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
20511}
20512
20513bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
20514 SideEffectsKind AllowSideEffects,
20515 bool InConstantContext) const {
20516 assert(!isValueDependent() &&
20517 "Expression evaluator can't be called on a dependent expression.");
20518
20519 if (!getType()->isRealFloatingType())
20520 return false;
20521
20522 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
20524 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
20525 !ExprResult.Val.isFloat() ||
20526 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20527 return false;
20528
20529 Result = ExprResult.Val.getFloat();
20530 return true;
20531}
20532
20534 bool InConstantContext) const {
20535 assert(!isValueDependent() &&
20536 "Expression evaluator can't be called on a dependent expression.");
20537
20538 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
20539 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
20540 Info.InConstantContext = InConstantContext;
20541 LValue LV;
20542 CheckedTemporaries CheckedTemps;
20543
20544 if (Info.EnableNewConstInterp) {
20545 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
20546 ConstantExprKind::Normal))
20547 return false;
20548
20549 LV.setFrom(Ctx, Result.Val);
20551 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
20552 ConstantExprKind::Normal, CheckedTemps);
20553 }
20554
20555 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
20556 Result.HasSideEffects ||
20559 ConstantExprKind::Normal, CheckedTemps))
20560 return false;
20561
20562 LV.moveInto(Result.Val);
20563 return true;
20564}
20565
20567 APValue DestroyedValue, QualType Type,
20568 SourceLocation Loc, Expr::EvalStatus &EStatus,
20569 bool IsConstantDestruction) {
20570 EvalInfo Info(Ctx, EStatus,
20571 IsConstantDestruction ? EvaluationMode::ConstantExpression
20573 Info.setEvaluatingDecl(Base, DestroyedValue,
20574 EvalInfo::EvaluatingDeclKind::Dtor);
20575 Info.InConstantContext = IsConstantDestruction;
20576
20577 LValue LVal;
20578 LVal.set(Base);
20579
20580 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
20581 EStatus.HasSideEffects)
20582 return false;
20583
20584 if (!Info.discardCleanups())
20585 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20586
20587 return true;
20588}
20589
20591 ConstantExprKind Kind) const {
20592 assert(!isValueDependent() &&
20593 "Expression evaluator can't be called on a dependent expression.");
20594 bool IsConst;
20595 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
20596 Result.Val.hasValue())
20597 return true;
20598
20599 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
20601 EvalInfo Info(Ctx, Result, EM);
20602 Info.InConstantContext = true;
20603
20604 if (Info.EnableNewConstInterp) {
20605 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
20606 return false;
20607 return CheckConstantExpression(Info, getExprLoc(),
20608 getStorageType(Ctx, this), Result.Val, Kind);
20609 }
20610
20611 // The type of the object we're initializing is 'const T' for a class NTTP.
20612 QualType T = getType();
20613 if (Kind == ConstantExprKind::ClassTemplateArgument)
20614 T.addConst();
20615
20616 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
20617 // represent the result of the evaluation. CheckConstantExpression ensures
20618 // this doesn't escape.
20619 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
20620 APValue::LValueBase Base(&BaseMTE);
20621 Info.setEvaluatingDecl(Base, Result.Val);
20622
20623 LValue LVal;
20624 LVal.set(Base);
20625 // C++23 [intro.execution]/p5
20626 // A full-expression is [...] a constant-expression
20627 // So we need to make sure temporary objects are destroyed after having
20628 // evaluating the expression (per C++23 [class.temporary]/p4).
20629 FullExpressionRAII Scope(Info);
20630 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
20631 Result.HasSideEffects || !Scope.destroy())
20632 return false;
20633
20634 if (!Info.discardCleanups())
20635 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20636
20637 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
20638 Result.Val, Kind))
20639 return false;
20640 if (!CheckMemoryLeaks(Info))
20641 return false;
20642
20643 // If this is a class template argument, it's required to have constant
20644 // destruction too.
20645 if (Kind == ConstantExprKind::ClassTemplateArgument &&
20647 true) ||
20648 Result.HasSideEffects)) {
20649 // FIXME: Prefix a note to indicate that the problem is lack of constant
20650 // destruction.
20651 return false;
20652 }
20653
20654 return true;
20655}
20656
20658 const VarDecl *VD,
20660 bool IsConstantInitialization) const {
20661 assert(!isValueDependent() &&
20662 "Expression evaluator can't be called on a dependent expression.");
20663 assert(VD && "Need a valid VarDecl");
20664
20665 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
20666 std::string Name;
20667 llvm::raw_string_ostream OS(Name);
20668 VD->printQualifiedName(OS);
20669 return Name;
20670 });
20671
20672 Expr::EvalStatus EStatus;
20673 EStatus.Diag = &Notes;
20674
20675 EvalInfo Info(Ctx, EStatus,
20676 (IsConstantInitialization &&
20677 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
20680 Info.setEvaluatingDecl(VD, Value);
20681 Info.InConstantContext = IsConstantInitialization;
20682
20683 SourceLocation DeclLoc = VD->getLocation();
20684 QualType DeclTy = VD->getType();
20685
20686 if (Info.EnableNewConstInterp) {
20687 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
20688 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
20689 return false;
20690
20691 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20692 ConstantExprKind::Normal);
20693 } else {
20694 LValue LVal;
20695 LVal.set(VD);
20696
20697 {
20698 // C++23 [intro.execution]/p5
20699 // A full-expression is ... an init-declarator ([dcl.decl]) or a
20700 // mem-initializer.
20701 // So we need to make sure temporary objects are destroyed after having
20702 // evaluated the expression (per C++23 [class.temporary]/p4).
20703 //
20704 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
20705 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
20706 // outermost FullExpr, such as ExprWithCleanups.
20707 FullExpressionRAII Scope(Info);
20708 if (!EvaluateInPlace(Value, Info, LVal, this,
20709 /*AllowNonLiteralTypes=*/true) ||
20710 EStatus.HasSideEffects)
20711 return false;
20712 }
20713
20714 // At this point, any lifetime-extended temporaries are completely
20715 // initialized.
20716 Info.performLifetimeExtension();
20717
20718 if (!Info.discardCleanups())
20719 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
20720 }
20721
20722 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
20723 ConstantExprKind::Normal) &&
20724 CheckMemoryLeaks(Info);
20725}
20726
20729 Expr::EvalStatus EStatus;
20730 EStatus.Diag = &Notes;
20731
20732 // Only treat the destruction as constant destruction if we formally have
20733 // constant initialization (or are usable in a constant expression).
20734 bool IsConstantDestruction = hasConstantInitialization();
20735
20736 // Make a copy of the value for the destructor to mutate, if we know it.
20737 // Otherwise, treat the value as default-initialized; if the destructor works
20738 // anyway, then the destruction is constant (and must be essentially empty).
20739 APValue DestroyedValue;
20740 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
20741 DestroyedValue = *getEvaluatedValue();
20742 else if (!handleDefaultInitValue(getType(), DestroyedValue))
20743 return false;
20744
20745 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
20746 getType(), getLocation(), EStatus,
20747 IsConstantDestruction) ||
20748 EStatus.HasSideEffects)
20749 return false;
20750
20751 ensureEvaluatedStmt()->HasConstantDestruction = true;
20752 return true;
20753}
20754
20755/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
20756/// constant folded, but discard the result.
20758 assert(!isValueDependent() &&
20759 "Expression evaluator can't be called on a dependent expression.");
20760
20762 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
20764}
20765
20766APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
20767 assert(!isValueDependent() &&
20768 "Expression evaluator can't be called on a dependent expression.");
20769
20770 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
20771 EvalResult EVResult;
20772 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20773 Info.InConstantContext = true;
20774
20775 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
20776 (void)Result;
20777 assert(Result && "Could not evaluate expression");
20778 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
20779
20780 return EVResult.Val.getInt();
20781}
20782
20785 assert(!isValueDependent() &&
20786 "Expression evaluator can't be called on a dependent expression.");
20787
20788 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
20789 EvalResult EVResult;
20790 EVResult.Diag = Diag;
20791 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20792 Info.InConstantContext = true;
20793 Info.CheckingForUndefinedBehavior = true;
20794
20795 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
20796 (void)Result;
20797 assert(Result && "Could not evaluate expression");
20798 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
20799
20800 return EVResult.Val.getInt();
20801}
20802
20804 assert(!isValueDependent() &&
20805 "Expression evaluator can't be called on a dependent expression.");
20806
20807 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
20808 bool IsConst;
20809 EvalResult EVResult;
20810 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
20811 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
20812 Info.CheckingForUndefinedBehavior = true;
20813 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
20814 }
20815}
20816
20818 assert(Val.isLValue());
20819 return IsGlobalLValue(Val.getLValueBase());
20820}
20821
20822/// isIntegerConstantExpr - this recursive routine will test if an expression is
20823/// an integer constant expression.
20824
20825/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
20826/// comma, etc
20827
20828// CheckICE - This function does the fundamental ICE checking: the returned
20829// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
20830//
20831// Note that to reduce code duplication, this helper does no evaluation
20832// itself; the caller checks whether the expression is evaluatable, and
20833// in the rare cases where CheckICE actually cares about the evaluated
20834// value, it calls into Evaluate.
20835
20836namespace {
20837
20838enum ICEKind {
20839 /// This expression is an ICE.
20840 IK_ICE,
20841 /// This expression is not an ICE, but if it isn't evaluated, it's
20842 /// a legal subexpression for an ICE. This return value is used to handle
20843 /// the comma operator in C99 mode, and non-constant subexpressions.
20844 IK_ICEIfUnevaluated,
20845 /// This expression is not an ICE, and is not a legal subexpression for one.
20846 IK_NotICE
20847};
20848
20849struct ICEDiag {
20850 ICEKind Kind;
20851 SourceLocation Loc;
20852
20853 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
20854};
20855
20856}
20857
20858static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
20859
20860static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
20861
20862static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
20863 Expr::EvalResult EVResult;
20864 Expr::EvalStatus Status;
20865 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
20866
20867 Info.InConstantContext = true;
20868 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
20869 !EVResult.Val.isInt())
20870 return ICEDiag(IK_NotICE, E->getBeginLoc());
20871
20872 return NoDiag();
20873}
20874
20875static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
20876 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
20878 return ICEDiag(IK_NotICE, E->getBeginLoc());
20879
20880 switch (E->getStmtClass()) {
20881#define ABSTRACT_STMT(Node)
20882#define STMT(Node, Base) case Expr::Node##Class:
20883#define EXPR(Node, Base)
20884#include "clang/AST/StmtNodes.inc"
20885 case Expr::PredefinedExprClass:
20886 case Expr::FloatingLiteralClass:
20887 case Expr::ImaginaryLiteralClass:
20888 case Expr::StringLiteralClass:
20889 case Expr::ArraySubscriptExprClass:
20890 case Expr::MatrixSingleSubscriptExprClass:
20891 case Expr::MatrixSubscriptExprClass:
20892 case Expr::ArraySectionExprClass:
20893 case Expr::OMPArrayShapingExprClass:
20894 case Expr::OMPIteratorExprClass:
20895 case Expr::MemberExprClass:
20896 case Expr::CompoundAssignOperatorClass:
20897 case Expr::CompoundLiteralExprClass:
20898 case Expr::ExtVectorElementExprClass:
20899 case Expr::DesignatedInitExprClass:
20900 case Expr::ArrayInitLoopExprClass:
20901 case Expr::ArrayInitIndexExprClass:
20902 case Expr::NoInitExprClass:
20903 case Expr::DesignatedInitUpdateExprClass:
20904 case Expr::ImplicitValueInitExprClass:
20905 case Expr::ParenListExprClass:
20906 case Expr::VAArgExprClass:
20907 case Expr::AddrLabelExprClass:
20908 case Expr::StmtExprClass:
20909 case Expr::CXXMemberCallExprClass:
20910 case Expr::CUDAKernelCallExprClass:
20911 case Expr::CXXAddrspaceCastExprClass:
20912 case Expr::CXXDynamicCastExprClass:
20913 case Expr::CXXTypeidExprClass:
20914 case Expr::CXXUuidofExprClass:
20915 case Expr::MSPropertyRefExprClass:
20916 case Expr::MSPropertySubscriptExprClass:
20917 case Expr::CXXNullPtrLiteralExprClass:
20918 case Expr::UserDefinedLiteralClass:
20919 case Expr::CXXThisExprClass:
20920 case Expr::CXXThrowExprClass:
20921 case Expr::CXXNewExprClass:
20922 case Expr::CXXDeleteExprClass:
20923 case Expr::CXXPseudoDestructorExprClass:
20924 case Expr::UnresolvedLookupExprClass:
20925 case Expr::RecoveryExprClass:
20926 case Expr::DependentScopeDeclRefExprClass:
20927 case Expr::CXXConstructExprClass:
20928 case Expr::CXXInheritedCtorInitExprClass:
20929 case Expr::CXXStdInitializerListExprClass:
20930 case Expr::CXXBindTemporaryExprClass:
20931 case Expr::ExprWithCleanupsClass:
20932 case Expr::CXXTemporaryObjectExprClass:
20933 case Expr::CXXUnresolvedConstructExprClass:
20934 case Expr::CXXDependentScopeMemberExprClass:
20935 case Expr::UnresolvedMemberExprClass:
20936 case Expr::ObjCStringLiteralClass:
20937 case Expr::ObjCBoxedExprClass:
20938 case Expr::ObjCArrayLiteralClass:
20939 case Expr::ObjCDictionaryLiteralClass:
20940 case Expr::ObjCEncodeExprClass:
20941 case Expr::ObjCMessageExprClass:
20942 case Expr::ObjCSelectorExprClass:
20943 case Expr::ObjCProtocolExprClass:
20944 case Expr::ObjCIvarRefExprClass:
20945 case Expr::ObjCPropertyRefExprClass:
20946 case Expr::ObjCSubscriptRefExprClass:
20947 case Expr::ObjCIsaExprClass:
20948 case Expr::ObjCAvailabilityCheckExprClass:
20949 case Expr::ShuffleVectorExprClass:
20950 case Expr::ConvertVectorExprClass:
20951 case Expr::BlockExprClass:
20952 case Expr::NoStmtClass:
20953 case Expr::OpaqueValueExprClass:
20954 case Expr::PackExpansionExprClass:
20955 case Expr::SubstNonTypeTemplateParmPackExprClass:
20956 case Expr::FunctionParmPackExprClass:
20957 case Expr::AsTypeExprClass:
20958 case Expr::ObjCIndirectCopyRestoreExprClass:
20959 case Expr::MaterializeTemporaryExprClass:
20960 case Expr::PseudoObjectExprClass:
20961 case Expr::AtomicExprClass:
20962 case Expr::LambdaExprClass:
20963 case Expr::CXXFoldExprClass:
20964 case Expr::CoawaitExprClass:
20965 case Expr::DependentCoawaitExprClass:
20966 case Expr::CoyieldExprClass:
20967 case Expr::SYCLUniqueStableNameExprClass:
20968 case Expr::CXXParenListInitExprClass:
20969 case Expr::HLSLOutArgExprClass:
20970 return ICEDiag(IK_NotICE, E->getBeginLoc());
20971
20972 case Expr::InitListExprClass: {
20973 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
20974 // form "T x = { a };" is equivalent to "T x = a;".
20975 // Unless we're initializing a reference, T is a scalar as it is known to be
20976 // of integral or enumeration type.
20977 if (E->isPRValue())
20978 if (cast<InitListExpr>(E)->getNumInits() == 1)
20979 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
20980 return ICEDiag(IK_NotICE, E->getBeginLoc());
20981 }
20982
20983 case Expr::SizeOfPackExprClass:
20984 case Expr::GNUNullExprClass:
20985 case Expr::SourceLocExprClass:
20986 case Expr::EmbedExprClass:
20987 case Expr::OpenACCAsteriskSizeExprClass:
20988 return NoDiag();
20989
20990 case Expr::PackIndexingExprClass:
20991 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
20992
20993 case Expr::SubstNonTypeTemplateParmExprClass:
20994 return
20995 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
20996
20997 case Expr::ConstantExprClass:
20998 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
20999
21000 case Expr::ParenExprClass:
21001 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21002 case Expr::GenericSelectionExprClass:
21003 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21004 case Expr::IntegerLiteralClass:
21005 case Expr::FixedPointLiteralClass:
21006 case Expr::CharacterLiteralClass:
21007 case Expr::ObjCBoolLiteralExprClass:
21008 case Expr::CXXBoolLiteralExprClass:
21009 case Expr::CXXScalarValueInitExprClass:
21010 case Expr::TypeTraitExprClass:
21011 case Expr::ConceptSpecializationExprClass:
21012 case Expr::RequiresExprClass:
21013 case Expr::ArrayTypeTraitExprClass:
21014 case Expr::ExpressionTraitExprClass:
21015 case Expr::CXXNoexceptExprClass:
21016 return NoDiag();
21017 case Expr::CallExprClass:
21018 case Expr::CXXOperatorCallExprClass: {
21019 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21020 // constant expressions, but they can never be ICEs because an ICE cannot
21021 // contain an operand of (pointer to) function type.
21022 const CallExpr *CE = cast<CallExpr>(E);
21023 if (CE->getBuiltinCallee())
21024 return CheckEvalInICE(E, Ctx);
21025 return ICEDiag(IK_NotICE, E->getBeginLoc());
21026 }
21027 case Expr::CXXRewrittenBinaryOperatorClass:
21028 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21029 Ctx);
21030 case Expr::DeclRefExprClass: {
21031 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21032 if (isa<EnumConstantDecl>(D))
21033 return NoDiag();
21034
21035 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21036 // integer variables in constant expressions:
21037 //
21038 // C++ 7.1.5.1p2
21039 // A variable of non-volatile const-qualified integral or enumeration
21040 // type initialized by an ICE can be used in ICEs.
21041 //
21042 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21043 // that mode, use of reference variables should not be allowed.
21044 const VarDecl *VD = dyn_cast<VarDecl>(D);
21045 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21046 !VD->getType()->isReferenceType())
21047 return NoDiag();
21048
21049 return ICEDiag(IK_NotICE, E->getBeginLoc());
21050 }
21051 case Expr::UnaryOperatorClass: {
21052 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21053 switch (Exp->getOpcode()) {
21054 case UO_PostInc:
21055 case UO_PostDec:
21056 case UO_PreInc:
21057 case UO_PreDec:
21058 case UO_AddrOf:
21059 case UO_Deref:
21060 case UO_Coawait:
21061 // C99 6.6/3 allows increment and decrement within unevaluated
21062 // subexpressions of constant expressions, but they can never be ICEs
21063 // because an ICE cannot contain an lvalue operand.
21064 return ICEDiag(IK_NotICE, E->getBeginLoc());
21065 case UO_Extension:
21066 case UO_LNot:
21067 case UO_Plus:
21068 case UO_Minus:
21069 case UO_Not:
21070 case UO_Real:
21071 case UO_Imag:
21072 return CheckICE(Exp->getSubExpr(), Ctx);
21073 }
21074 llvm_unreachable("invalid unary operator class");
21075 }
21076 case Expr::OffsetOfExprClass: {
21077 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21078 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21079 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21080 // compliance: we should warn earlier for offsetof expressions with
21081 // array subscripts that aren't ICEs, and if the array subscripts
21082 // are ICEs, the value of the offsetof must be an integer constant.
21083 return CheckEvalInICE(E, Ctx);
21084 }
21085 case Expr::UnaryExprOrTypeTraitExprClass: {
21087 if ((Exp->getKind() == UETT_SizeOf) &&
21089 return ICEDiag(IK_NotICE, E->getBeginLoc());
21090 if (Exp->getKind() == UETT_CountOf) {
21091 QualType ArgTy = Exp->getTypeOfArgument();
21092 if (ArgTy->isVariableArrayType()) {
21093 // We need to look whether the array is multidimensional. If it is,
21094 // then we want to check the size expression manually to see whether
21095 // it is an ICE or not.
21096 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21097 if (VAT->getElementType()->isArrayType())
21098 // Variable array size expression could be missing (e.g. int a[*][10])
21099 // In that case, it can't be a constant expression.
21100 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21101 : ICEDiag(IK_NotICE, E->getBeginLoc());
21102
21103 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21104 return ICEDiag(IK_NotICE, E->getBeginLoc());
21105 }
21106 }
21107 return NoDiag();
21108 }
21109 case Expr::BinaryOperatorClass: {
21110 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21111 switch (Exp->getOpcode()) {
21112 case BO_PtrMemD:
21113 case BO_PtrMemI:
21114 case BO_Assign:
21115 case BO_MulAssign:
21116 case BO_DivAssign:
21117 case BO_RemAssign:
21118 case BO_AddAssign:
21119 case BO_SubAssign:
21120 case BO_ShlAssign:
21121 case BO_ShrAssign:
21122 case BO_AndAssign:
21123 case BO_XorAssign:
21124 case BO_OrAssign:
21125 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21126 // constant expressions, but they can never be ICEs because an ICE cannot
21127 // contain an lvalue operand.
21128 return ICEDiag(IK_NotICE, E->getBeginLoc());
21129
21130 case BO_Mul:
21131 case BO_Div:
21132 case BO_Rem:
21133 case BO_Add:
21134 case BO_Sub:
21135 case BO_Shl:
21136 case BO_Shr:
21137 case BO_LT:
21138 case BO_GT:
21139 case BO_LE:
21140 case BO_GE:
21141 case BO_EQ:
21142 case BO_NE:
21143 case BO_And:
21144 case BO_Xor:
21145 case BO_Or:
21146 case BO_Comma:
21147 case BO_Cmp: {
21148 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21149 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21150 if (Exp->getOpcode() == BO_Div ||
21151 Exp->getOpcode() == BO_Rem) {
21152 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21153 // we don't evaluate one.
21154 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21155 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21156 if (REval == 0)
21157 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21158 if (REval.isSigned() && REval.isAllOnes()) {
21159 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21160 if (LEval.isMinSignedValue())
21161 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21162 }
21163 }
21164 }
21165 if (Exp->getOpcode() == BO_Comma) {
21166 if (Ctx.getLangOpts().C99) {
21167 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21168 // if it isn't evaluated.
21169 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
21170 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21171 } else {
21172 // In both C89 and C++, commas in ICEs are illegal.
21173 return ICEDiag(IK_NotICE, E->getBeginLoc());
21174 }
21175 }
21176 return Worst(LHSResult, RHSResult);
21177 }
21178 case BO_LAnd:
21179 case BO_LOr: {
21180 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21181 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21182 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
21183 // Rare case where the RHS has a comma "side-effect"; we need
21184 // to actually check the condition to see whether the side
21185 // with the comma is evaluated.
21186 if ((Exp->getOpcode() == BO_LAnd) !=
21187 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
21188 return RHSResult;
21189 return NoDiag();
21190 }
21191
21192 return Worst(LHSResult, RHSResult);
21193 }
21194 }
21195 llvm_unreachable("invalid binary operator kind");
21196 }
21197 case Expr::ImplicitCastExprClass:
21198 case Expr::CStyleCastExprClass:
21199 case Expr::CXXFunctionalCastExprClass:
21200 case Expr::CXXStaticCastExprClass:
21201 case Expr::CXXReinterpretCastExprClass:
21202 case Expr::CXXConstCastExprClass:
21203 case Expr::ObjCBridgedCastExprClass: {
21204 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
21205 if (isa<ExplicitCastExpr>(E)) {
21206 if (const FloatingLiteral *FL
21207 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
21208 unsigned DestWidth = Ctx.getIntWidth(E->getType());
21209 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
21210 APSInt IgnoredVal(DestWidth, !DestSigned);
21211 bool Ignored;
21212 // If the value does not fit in the destination type, the behavior is
21213 // undefined, so we are not required to treat it as a constant
21214 // expression.
21215 if (FL->getValue().convertToInteger(IgnoredVal,
21216 llvm::APFloat::rmTowardZero,
21217 &Ignored) & APFloat::opInvalidOp)
21218 return ICEDiag(IK_NotICE, E->getBeginLoc());
21219 return NoDiag();
21220 }
21221 }
21222 switch (cast<CastExpr>(E)->getCastKind()) {
21223 case CK_LValueToRValue:
21224 case CK_AtomicToNonAtomic:
21225 case CK_NonAtomicToAtomic:
21226 case CK_NoOp:
21227 case CK_IntegralToBoolean:
21228 case CK_IntegralCast:
21229 return CheckICE(SubExpr, Ctx);
21230 default:
21231 return ICEDiag(IK_NotICE, E->getBeginLoc());
21232 }
21233 }
21234 case Expr::BinaryConditionalOperatorClass: {
21236 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
21237 if (CommonResult.Kind == IK_NotICE) return CommonResult;
21238 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21239 if (FalseResult.Kind == IK_NotICE) return FalseResult;
21240 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
21241 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
21242 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
21243 return FalseResult;
21244 }
21245 case Expr::ConditionalOperatorClass: {
21247 // If the condition (ignoring parens) is a __builtin_constant_p call,
21248 // then only the true side is actually considered in an integer constant
21249 // expression, and it is fully evaluated. This is an important GNU
21250 // extension. See GCC PR38377 for discussion.
21251 if (const CallExpr *CallCE
21252 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
21253 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
21254 return CheckEvalInICE(E, Ctx);
21255 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
21256 if (CondResult.Kind == IK_NotICE)
21257 return CondResult;
21258
21259 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
21260 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21261
21262 if (TrueResult.Kind == IK_NotICE)
21263 return TrueResult;
21264 if (FalseResult.Kind == IK_NotICE)
21265 return FalseResult;
21266 if (CondResult.Kind == IK_ICEIfUnevaluated)
21267 return CondResult;
21268 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
21269 return NoDiag();
21270 // Rare case where the diagnostics depend on which side is evaluated
21271 // Note that if we get here, CondResult is 0, and at least one of
21272 // TrueResult and FalseResult is non-zero.
21273 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
21274 return FalseResult;
21275 return TrueResult;
21276 }
21277 case Expr::CXXDefaultArgExprClass:
21278 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
21279 case Expr::CXXDefaultInitExprClass:
21280 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
21281 case Expr::ChooseExprClass: {
21282 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
21283 }
21284 case Expr::BuiltinBitCastExprClass: {
21285 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
21286 return ICEDiag(IK_NotICE, E->getBeginLoc());
21287 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
21288 }
21289 }
21290
21291 llvm_unreachable("Invalid StmtClass!");
21292}
21293
21294/// Evaluate an expression as a C++11 integral constant expression.
21296 const Expr *E,
21297 llvm::APSInt *Value) {
21299 return false;
21300
21301 APValue Result;
21302 if (!E->isCXX11ConstantExpr(Ctx, &Result))
21303 return false;
21304
21305 if (!Result.isInt())
21306 return false;
21307
21308 if (Value) *Value = Result.getInt();
21309 return true;
21310}
21311
21313 assert(!isValueDependent() &&
21314 "Expression evaluator can't be called on a dependent expression.");
21315
21316 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
21317
21318 if (Ctx.getLangOpts().CPlusPlus11)
21319 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
21320
21321 ICEDiag D = CheckICE(this, Ctx);
21322 if (D.Kind != IK_ICE)
21323 return false;
21324 return true;
21325}
21326
21327std::optional<llvm::APSInt>
21329 if (isValueDependent()) {
21330 // Expression evaluator can't succeed on a dependent expression.
21331 return std::nullopt;
21332 }
21333
21334 if (Ctx.getLangOpts().CPlusPlus11) {
21335 APSInt Value;
21337 return Value;
21338 return std::nullopt;
21339 }
21340
21341 if (!isIntegerConstantExpr(Ctx))
21342 return std::nullopt;
21343
21344 // The only possible side-effects here are due to UB discovered in the
21345 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
21346 // required to treat the expression as an ICE, so we produce the folded
21347 // value.
21349 Expr::EvalStatus Status;
21350 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
21351 Info.InConstantContext = true;
21352
21353 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
21354 llvm_unreachable("ICE cannot be evaluated!");
21355
21356 return ExprResult.Val.getInt();
21357}
21358
21360 assert(!isValueDependent() &&
21361 "Expression evaluator can't be called on a dependent expression.");
21362
21363 return CheckICE(this, Ctx).Kind == IK_ICE;
21364}
21365
21367 assert(!isValueDependent() &&
21368 "Expression evaluator can't be called on a dependent expression.");
21369
21370 // We support this checking in C++98 mode in order to diagnose compatibility
21371 // issues.
21372 assert(Ctx.getLangOpts().CPlusPlus);
21373
21374 bool IsConst;
21375 APValue Scratch;
21376 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
21377 if (Result)
21378 *Result = Scratch;
21379 return true;
21380 }
21381
21382 // Build evaluation settings.
21383 Expr::EvalStatus Status;
21385 Status.Diag = &Diags;
21386 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21387
21388 bool IsConstExpr =
21389 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
21390 // FIXME: We don't produce a diagnostic for this, but the callers that
21391 // call us on arbitrary full-expressions should generally not care.
21392 Info.discardCleanups() && !Status.HasSideEffects;
21393
21394 return IsConstExpr && Diags.empty();
21395}
21396
21398 const FunctionDecl *Callee,
21400 const Expr *This) const {
21401 assert(!isValueDependent() &&
21402 "Expression evaluator can't be called on a dependent expression.");
21403
21404 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
21405 std::string Name;
21406 llvm::raw_string_ostream OS(Name);
21407 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
21408 /*Qualified=*/true);
21409 return Name;
21410 });
21411
21412 Expr::EvalStatus Status;
21413 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
21414 Info.InConstantContext = true;
21415
21416 LValue ThisVal;
21417 const LValue *ThisPtr = nullptr;
21418 if (This) {
21419#ifndef NDEBUG
21420 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
21421 assert(MD && "Don't provide `this` for non-methods.");
21422 assert(MD->isImplicitObjectMemberFunction() &&
21423 "Don't provide `this` for methods without an implicit object.");
21424#endif
21425 if (!This->isValueDependent() &&
21426 EvaluateObjectArgument(Info, This, ThisVal) &&
21427 !Info.EvalStatus.HasSideEffects)
21428 ThisPtr = &ThisVal;
21429
21430 // Ignore any side-effects from a failed evaluation. This is safe because
21431 // they can't interfere with any other argument evaluation.
21432 Info.EvalStatus.HasSideEffects = false;
21433 }
21434
21435 CallRef Call = Info.CurrentCall->createCall(Callee);
21436 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
21437 I != E; ++I) {
21438 unsigned Idx = I - Args.begin();
21439 if (Idx >= Callee->getNumParams())
21440 break;
21441 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
21442 if ((*I)->isValueDependent() ||
21443 !EvaluateCallArg(PVD, *I, Call, Info) ||
21444 Info.EvalStatus.HasSideEffects) {
21445 // If evaluation fails, throw away the argument entirely.
21446 if (APValue *Slot = Info.getParamSlot(Call, PVD))
21447 *Slot = APValue();
21448 }
21449
21450 // Ignore any side-effects from a failed evaluation. This is safe because
21451 // they can't interfere with any other argument evaluation.
21452 Info.EvalStatus.HasSideEffects = false;
21453 }
21454
21455 // Parameter cleanups happen in the caller and are not part of this
21456 // evaluation.
21457 Info.discardCleanups();
21458 Info.EvalStatus.HasSideEffects = false;
21459
21460 // Build fake call to Callee.
21461 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
21462 Call);
21463 // FIXME: Missing ExprWithCleanups in enable_if conditions?
21464 FullExpressionRAII Scope(Info);
21465 return Evaluate(Value, Info, this) && Scope.destroy() &&
21466 !Info.EvalStatus.HasSideEffects;
21467}
21468
21471 PartialDiagnosticAt> &Diags) {
21472 // FIXME: It would be useful to check constexpr function templates, but at the
21473 // moment the constant expression evaluator cannot cope with the non-rigorous
21474 // ASTs which we build for dependent expressions.
21475 if (FD->isDependentContext())
21476 return true;
21477
21478 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
21479 std::string Name;
21480 llvm::raw_string_ostream OS(Name);
21482 /*Qualified=*/true);
21483 return Name;
21484 });
21485
21486 Expr::EvalStatus Status;
21487 Status.Diag = &Diags;
21488
21489 EvalInfo Info(FD->getASTContext(), Status,
21491 Info.InConstantContext = true;
21492 Info.CheckingPotentialConstantExpression = true;
21493
21494 // The constexpr VM attempts to compile all methods to bytecode here.
21495 if (Info.EnableNewConstInterp) {
21496 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
21497 return Diags.empty();
21498 }
21499
21500 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
21501 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
21502
21503 // Fabricate an arbitrary expression on the stack and pretend that it
21504 // is a temporary being used as the 'this' pointer.
21505 LValue This;
21506 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
21507 : Info.Ctx.IntTy);
21508 This.set({&VIE, Info.CurrentCall->Index});
21509
21511
21512 APValue Scratch;
21513 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
21514 // Evaluate the call as a constant initializer, to allow the construction
21515 // of objects of non-literal types.
21516 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
21517 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
21518 } else {
21519 SourceLocation Loc = FD->getLocation();
21521 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
21522 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
21523 /*ResultSlot=*/nullptr);
21524 }
21525
21526 return Diags.empty();
21527}
21528
21530 const FunctionDecl *FD,
21532 PartialDiagnosticAt> &Diags) {
21533 assert(!E->isValueDependent() &&
21534 "Expression evaluator can't be called on a dependent expression.");
21535
21536 Expr::EvalStatus Status;
21537 Status.Diag = &Diags;
21538
21539 EvalInfo Info(FD->getASTContext(), Status,
21541 Info.InConstantContext = true;
21542 Info.CheckingPotentialConstantExpression = true;
21543
21544 if (Info.EnableNewConstInterp) {
21546 return Diags.empty();
21547 }
21548
21549 // Fabricate a call stack frame to give the arguments a plausible cover story.
21550 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
21551 /*CallExpr=*/nullptr, CallRef());
21552
21553 APValue ResultScratch;
21554 Evaluate(ResultScratch, Info, E);
21555 return Diags.empty();
21556}
21557
21559 unsigned Type) const {
21560 if (!getType()->isPointerType())
21561 return false;
21562
21563 Expr::EvalStatus Status;
21564 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21565 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
21566}
21567
21568static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
21569 EvalInfo &Info, std::string *StringResult) {
21570 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
21571 return false;
21572
21573 LValue String;
21574
21575 if (!EvaluatePointer(E, String, Info))
21576 return false;
21577
21578 QualType CharTy = E->getType()->getPointeeType();
21579
21580 // Fast path: if it's a string literal, search the string value.
21581 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
21582 String.getLValueBase().dyn_cast<const Expr *>())) {
21583 StringRef Str = S->getBytes();
21584 int64_t Off = String.Offset.getQuantity();
21585 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
21586 S->getCharByteWidth() == 1 &&
21587 // FIXME: Add fast-path for wchar_t too.
21588 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
21589 Str = Str.substr(Off);
21590
21591 StringRef::size_type Pos = Str.find(0);
21592 if (Pos != StringRef::npos)
21593 Str = Str.substr(0, Pos);
21594
21595 Result = Str.size();
21596 if (StringResult)
21597 *StringResult = Str;
21598 return true;
21599 }
21600
21601 // Fall through to slow path.
21602 }
21603
21604 // Slow path: scan the bytes of the string looking for the terminating 0.
21605 for (uint64_t Strlen = 0; /**/; ++Strlen) {
21606 APValue Char;
21607 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
21608 !Char.isInt())
21609 return false;
21610 if (!Char.getInt()) {
21611 Result = Strlen;
21612 return true;
21613 } else if (StringResult)
21614 StringResult->push_back(Char.getInt().getExtValue());
21615 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
21616 return false;
21617 }
21618}
21619
21620std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
21621 Expr::EvalStatus Status;
21622 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21623 uint64_t Result;
21624 std::string StringResult;
21625
21626 if (Info.EnableNewConstInterp) {
21627 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
21628 return std::nullopt;
21629 return StringResult;
21630 }
21631
21632 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
21633 return StringResult;
21634 return std::nullopt;
21635}
21636
21637template <typename T>
21638static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
21639 const Expr *SizeExpression,
21640 const Expr *PtrExpression,
21641 ASTContext &Ctx,
21642 Expr::EvalResult &Status) {
21643 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21644 Info.InConstantContext = true;
21645
21646 if (Info.EnableNewConstInterp)
21647 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
21648 PtrExpression, Result);
21649
21650 LValue String;
21651 FullExpressionRAII Scope(Info);
21652 APSInt SizeValue;
21653 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
21654 return false;
21655
21656 uint64_t Size = SizeValue.getZExtValue();
21657
21658 // FIXME: better protect against invalid or excessive sizes
21659 if constexpr (std::is_same_v<APValue, T>)
21660 Result = APValue(APValue::UninitArray{}, Size, Size);
21661 else {
21662 if (Size < Result.max_size())
21663 Result.reserve(Size);
21664 }
21665 if (!::EvaluatePointer(PtrExpression, String, Info))
21666 return false;
21667
21668 QualType CharTy = PtrExpression->getType()->getPointeeType();
21669 for (uint64_t I = 0; I < Size; ++I) {
21670 APValue Char;
21671 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
21672 Char))
21673 return false;
21674
21675 if constexpr (std::is_same_v<APValue, T>) {
21676 Result.getArrayInitializedElt(I) = std::move(Char);
21677 } else {
21678 APSInt C = Char.getInt();
21679
21680 assert(C.getBitWidth() <= 8 &&
21681 "string element not representable in char");
21682
21683 Result.push_back(static_cast<char>(C.getExtValue()));
21684 }
21685
21686 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
21687 return false;
21688 }
21689
21690 return Scope.destroy() && CheckMemoryLeaks(Info);
21691}
21692
21694 const Expr *SizeExpression,
21695 const Expr *PtrExpression, ASTContext &Ctx,
21696 EvalResult &Status) const {
21697 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21698 PtrExpression, Ctx, Status);
21699}
21700
21702 const Expr *SizeExpression,
21703 const Expr *PtrExpression, ASTContext &Ctx,
21704 EvalResult &Status) const {
21705 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
21706 PtrExpression, Ctx, Status);
21707}
21708
21709bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
21710 Expr::EvalStatus Status;
21711 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
21712
21713 if (Info.EnableNewConstInterp)
21714 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this, Result);
21715
21716 return EvaluateBuiltinStrLen(this, Result, Info);
21717}
21718
21719namespace {
21720struct IsWithinLifetimeHandler {
21721 EvalInfo &Info;
21722 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
21723 using result_type = std::optional<bool>;
21724 std::optional<bool> failed() { return std::nullopt; }
21725 template <typename T>
21726 std::optional<bool> found(T &Subobj, QualType SubobjType) {
21727 return true;
21728 }
21729};
21730
21731std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
21732 const CallExpr *E) {
21733 EvalInfo &Info = IEE.Info;
21734 // Sometimes this is called during some sorts of constant folding / early
21735 // evaluation. These are meant for non-constant expressions and are not
21736 // necessary since this consteval builtin will never be evaluated at runtime.
21737 // Just fail to evaluate when not in a constant context.
21738 if (!Info.InConstantContext)
21739 return std::nullopt;
21740 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
21741 const Expr *Arg = E->getArg(0);
21742 if (Arg->isValueDependent())
21743 return std::nullopt;
21744 LValue Val;
21745 if (!EvaluatePointer(Arg, Val, Info))
21746 return std::nullopt;
21747
21748 if (Val.allowConstexprUnknown())
21749 return true;
21750
21751 auto Error = [&](int Diag) {
21752 bool CalledFromStd = false;
21753 const auto *Callee = Info.CurrentCall->getCallee();
21754 if (Callee && Callee->isInStdNamespace()) {
21755 const IdentifierInfo *Identifier = Callee->getIdentifier();
21756 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
21757 }
21758 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
21759 : E->getExprLoc(),
21760 diag::err_invalid_is_within_lifetime)
21761 << (CalledFromStd ? "std::is_within_lifetime"
21762 : "__builtin_is_within_lifetime")
21763 << Diag;
21764 return std::nullopt;
21765 };
21766 // C++2c [meta.const.eval]p4:
21767 // During the evaluation of an expression E as a core constant expression, a
21768 // call to this function is ill-formed unless p points to an object that is
21769 // usable in constant expressions or whose complete object's lifetime began
21770 // within E.
21771
21772 // Make sure it points to an object
21773 // nullptr does not point to an object
21774 if (Val.isNullPointer() || Val.getLValueBase().isNull())
21775 return Error(0);
21776 QualType T = Val.getLValueBase().getType();
21777 assert(!T->isFunctionType() &&
21778 "Pointers to functions should have been typed as function pointers "
21779 "which would have been rejected earlier");
21780 assert(T->isObjectType());
21781 // Hypothetical array element is not an object
21782 if (Val.getLValueDesignator().isOnePastTheEnd())
21783 return Error(1);
21784 assert(Val.getLValueDesignator().isValidSubobject() &&
21785 "Unchecked case for valid subobject");
21786 // All other ill-formed values should have failed EvaluatePointer, so the
21787 // object should be a pointer to an object that is usable in a constant
21788 // expression or whose complete lifetime began within the expression
21789 CompleteObject CO =
21790 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
21791 // The lifetime hasn't begun yet if we are still evaluating the
21792 // initializer ([basic.life]p(1.2))
21793 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
21794 return Error(2);
21795
21796 if (!CO)
21797 return false;
21798 IsWithinLifetimeHandler handler{Info};
21799 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
21800}
21801} // 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 EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static 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 bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static 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)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:207
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:221
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:215
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:584
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:576
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:489
APValue & getStructField(unsigned i)
Definition APValue.h:617
const FieldDecl * getUnionField() const
Definition APValue.h:629
bool isVector() const
Definition APValue.h:473
APSInt & getComplexIntImag()
Definition APValue.h:527
bool isAbsent() const
Definition APValue.h:463
bool isComplexInt() const
Definition APValue.h:470
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:204
ValueKind getKind() const
Definition APValue.h:461
unsigned getArrayInitializedElts() const
Definition APValue.h:595
static APValue IndeterminateValue()
Definition APValue.h:432
bool isFloat() const
Definition APValue.h:468
APFixedPoint & getFixedPoint()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:465
bool hasLValuePath() const
Definition APValue.cpp:998
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getUnionValue()
Definition APValue.h:633
CharUnits & getLValueOffset()
Definition APValue.cpp:993
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
bool isComplexFloat() const
Definition APValue.h:471
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
APValue & getArrayFiller()
Definition APValue.h:587
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1059
bool isIndeterminate() const
Definition APValue.h:464
bool isInt() const
Definition APValue.h:467
unsigned getArraySize() const
Definition APValue.h:599
bool allowConstexprUnknown() const
Definition APValue.h:318
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
bool isFixedPoint() const
Definition APValue.h:469
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:475
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
APValue & getStructBase(unsigned i)
Definition APValue.h:612
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:851
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
CanQualType VoidPtrTy
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:792
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CanQualType CharTy
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType IntTy
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
CanQualType HalfTy
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:4573
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5983
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5988
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2750
uint64_t getValue() const
Definition ExprCXX.h:3044
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
QualType getElementType() const
Definition TypeBase.h:3735
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8092
Attr - This represents one attribute.
Definition Attr.h:45
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4453
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4507
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4491
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4488
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4132
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4138
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4185
SourceLocation getExprLoc() const
Definition Expr.h:4079
Expr * getRHS() const
Definition Expr.h:4090
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4124
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4115
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4174
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4251
Opcode getOpcode() const
Definition Expr.h:4083
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4135
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4787
const BlockDecl * getBlockDecl() const
Definition Expr.h:6636
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:85
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:459
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:1515
bool getValue() const
Definition ExprCXX.h:740
Represents a call to a C++ constructor.
Definition ExprCXX.h:1548
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1617
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1691
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1650
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1688
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:2999
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2690
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2665
bool isArrayForm() const
Definition ExprCXX.h:2652
bool isGlobalDelete() const
Definition ExprCXX.h:2651
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1788
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isInstance() const
Definition DeclCXX.h:2156
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2845
QualType getAllocatedType() const
Definition ExprCXX.h:2434
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:2469
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2503
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2494
SourceRange getSourceRange() const
Definition ExprCXX.h:2610
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2459
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2533
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:1673
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1784
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:304
bool isImplicit() const
Definition ExprCXX.h:1177
bool isTypeOperand() const
Definition ExprCXX.h:884
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:161
Expr * getExprOperand() const
Definition ExprCXX.h:895
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1114
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
SourceLocation getBeginLoc() const
Definition Expr.h:3277
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3573
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1591
Expr * getCallee()
Definition Expr.h:3090
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3236
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3137
Decl * getCalleeDecl()
Definition Expr.h:3120
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1602
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
Definition Stmt.h:1911
Expr * getLHS()
Definition Stmt.h:1994
Expr * getRHS()
Definition Stmt.h:2006
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3676
path_iterator path_begin()
Definition Expr.h:3746
unsigned path_size() const
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3720
path_iterator path_end()
Definition Expr.h:3747
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3743
bool path_empty() const
Definition Expr.h:3744
Expr * getSubExpr()
Definition Expr.h:3726
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3790
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1629
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4884
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3276
QualType getElementType() const
Definition TypeBase.h:3286
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4300
QualType getComputationLHSType() const
Definition Expr.h:4334
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3605
bool hasStaticStorage() const
Definition Expr.h:3650
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5570
bool isFileScope() const
Definition Expr.h:3637
const Expr * getInitializer() const
Definition Expr.h:3633
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1731
bool body_empty() const
Definition Stmt.h:1775
Stmt *const * const_body_iterator
Definition Stmt.h:1803
body_iterator body_end()
Definition Stmt.h:1796
body_range body()
Definition Stmt.h:1794
body_iterator body_begin()
Definition Stmt.h:1795
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4391
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4423
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4414
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4418
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3824
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:254
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3850
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3831
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3857
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3837
APValue getAPValueResult() const
Definition Expr.cpp:412
bool hasAPValueResult() const
Definition Expr.h:1157
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4796
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4809
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
ValueDecl * getDecl()
Definition Expr.h:1338
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1622
decl_range decls()
Definition Stmt.h:1670
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:449
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
A decomposition declaration.
Definition DeclCXX.h:4245
auto flat_bindings() const
Definition DeclCXX.h:4288
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2823
Stmt * getBody()
Definition Stmt.h:2848
Expr * getCond()
Definition Stmt.h:2841
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
ChildElementIter< false > begin()
Definition Expr.h:5232
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3928
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3955
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:83
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:670
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:674
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:672
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3968
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
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:3085
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3669
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:3252
Expr()=delete
ConstantExprKind
Definition Expr.h:749
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4415
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4447
const Expr * getBase() const
Definition Expr.h:6581
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4748
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3407
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1575
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2879
Stmt * getInit()
Definition Stmt.h:2894
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1082
Stmt * getBody()
Definition Stmt.h:2923
Expr * getInc()
Definition Stmt.h:2922
Expr * getCond()
Definition Stmt.h:2921
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3275
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4201
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4189
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3861
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4325
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition Decl.h:2783
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3422
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:3121
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:6462
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:2250
Stmt * getThen()
Definition Stmt.h:2339
Stmt * getInit()
Definition Stmt.h:2400
bool isNonNegatedConsteval() const
Definition Stmt.h:2435
Expr * getCond()
Definition Stmt.h:2327
Stmt * getElse()
Definition Stmt.h:2348
bool isConsteval() const
Definition Stmt.h:2430
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1030
const Expr * getSubExpr() const
Definition Expr.h:1743
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6057
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
Describes an C or C++ initializer list.
Definition Expr.h:5299
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2461
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2447
unsigned getNumInits() const
Definition Expr.h:5329
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5401
const Expr * getInit(unsigned Init) const
Definition Expr.h:5353
ArrayRef< Expr * > inits()
Definition Expr.h:5349
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2106
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2094
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1400
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h: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:3364
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
Expr * getBase() const
Definition Expr.h:3441
bool isArrow() const
Definition Expr.h:3548
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:153
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2586
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2574
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2567
unsigned getNumComponents() const
Definition Expr.h:2582
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2479
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2426
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2430
@ Field
A field.
Definition Expr.h:2428
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2433
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2475
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2199
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
bool isExplicitObjectParameter() const
Definition Decl.h:1878
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
StringLiteral * getFunctionName()
Definition Expr.h:2049
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6804
ArrayRef< Expr * > semantics()
Definition Expr.h:6828
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8377
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8293
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:8478
QualType getCanonicalType() const
Definition TypeBase.h:8345
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8387
void removeLocalVolatile()
Definition TypeBase.h:8409
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1164
void removeLocalConst()
Definition TypeBase.h:8401
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8366
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8339
Represents a struct/union/class.
Definition Decl.h:4321
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4537
field_iterator field_end() const
Definition Decl.h:4527
field_range fields() const
Definition Decl.h:4524
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4521
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4373
bool field_empty() const
Definition Decl.h:4532
field_iterator field_begin() const
Definition Decl.cpp:5209
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2155
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:586
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4643
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4695
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4676
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4682
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:2281
bool isIntType() const
Definition Expr.h:5041
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:4612
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1484
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
unsigned getLength() const
Definition Expr.h:1909
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1875
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
unsigned getCharByteWidth() const
Definition Expr.h:1910
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1884
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2500
Expr * getCond()
Definition Stmt.h:2563
Stmt * getBody()
Definition Stmt.h:2575
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1148
Stmt * getInit()
Definition Stmt.h:2580
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2631
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4895
bool isUnion() const
Definition Decl.h:3922
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:858
bool isBigEndian() const
virtual int getEHDataRegisterNumber(unsigned RegNo) const
Return the register number that __builtin_eh_return_regno would return with the specified argument.
unsigned getCharWidth() const
Definition TargetInfo.h:520
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:8275
bool getBoolValue() const
Definition ExprCXX.h:2947
const APValue & getAPValue() const
Definition ExprCXX.h:2952
bool isStoredAsBoolean() const
Definition ExprCXX.h:2943
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8892
bool isBooleanType() const
Definition TypeBase.h:9022
bool isFunctionReferenceType() const
Definition TypeBase.h:8604
bool isMFloat8Type() const
Definition TypeBase.h:8917
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:418
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2993
bool isIncompleteArrayType() const
Definition TypeBase.h:8637
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9188
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8633
bool isNothrowT() const
Definition Type.cpp:3170
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:712
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2425
bool isArrayType() const
Definition TypeBase.h:8629
bool isFunctionPointerType() const
Definition TypeBase.h:8597
bool isPointerType() const
Definition TypeBase.h:8530
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8936
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9179
bool isReferenceType() const
Definition TypeBase.h:8554
bool isEnumeralType() const
Definition TypeBase.h:8661
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1909
bool isVariableArrayType() const
Definition TypeBase.h:8641
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9010
bool isExtVectorBoolType() const
Definition TypeBase.h:8677
bool isMemberDataPointerType() const
Definition TypeBase.h:8622
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8665
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8948
bool isMemberPointerType() const
Definition TypeBase.h:8611
bool isAtomicType() const
Definition TypeBase.h:8718
bool isComplexIntegerType() const
Definition Type.cpp:730
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9165
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8526
bool isVectorType() const
Definition TypeBase.h:8669
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isFloatingType() const
Definition Type.cpp:2304
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2929
bool isAnyPointerType() const
Definition TypeBase.h:8538
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9112
bool isNullPtrType() const
Definition TypeBase.h:8929
bool isRecordType() const
Definition TypeBase.h:8657
bool isUnionType() const
Definition Type.cpp:718
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2569
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9056
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2625
QualType getArgumentType() const
Definition Expr.h:2668
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2704
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2694
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
SourceLocation getExprLoc() const
Definition Expr.h:2368
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2326
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2298
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5515
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
bool hasInit() const
Definition Decl.cpp:2405
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2643
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2582
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2884
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2655
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2373
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:2493
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2564
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2635
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:2382
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2535
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Expr * getSizeExpr() const
Definition TypeBase.h:3981
Represents a GCC generic vector type.
Definition TypeBase.h:4176
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2688
Expr * getCond()
Definition Stmt.h:2740
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1209
Stmt * getBody()
Definition Stmt.h:2752
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:226
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:242
bool evaluateStrlen(State &Parent, const Expr *E, uint64_t &Result)
Evalute.
Definition Context.cpp:288
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:59
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:39
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:72
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:102
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1235
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:42
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2802
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:3521
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:42
@ CSK_ArrayToPointer
Definition State.h:46
@ CSK_Derived
Definition State.h:44
@ CSK_Base
Definition State.h:43
@ CSK_Real
Definition State.h:48
@ CSK_ArrayIndex
Definition State.h:47
@ CSK_Imag
Definition State.h:49
@ CSK_VectorElement
Definition State.h:50
@ CSK_Field
Definition State.h:45
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:26
@ AK_TypeId
Definition State.h:34
@ AK_Construct
Definition State.h:35
@ AK_Increment
Definition State.h:30
@ AK_DynamicCast
Definition State.h:33
@ AK_Read
Definition State.h:27
@ AK_Assign
Definition State.h:29
@ AK_IsWithinLifetime
Definition State.h:37
@ AK_MemberCall
Definition State.h:32
@ AK_ReadObjectRepresentation
Definition State.h:28
@ AK_Dereference
Definition State.h:38
@ AK_Destroy
Definition State.h:36
@ AK_Decrement
Definition State.h:31
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:563
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:53
@ ConstantFold
Fold the expression to a constant.
Definition State.h:67
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:63
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:71
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:831
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:609
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define trunc(__x)
Definition tgmath.h:1216
#define scalbn(__x, __y)
Definition tgmath.h:1165